Merge branch 'master' into jgrpp

# Conflicts:
#	src/genworld_gui.cpp
#	src/group_gui.cpp
#	src/saveload/saveload.cpp
#	src/settings_gui.cpp
#	src/toolbar_gui.cpp
#	src/vehicle_gui.cpp
#	src/vehicle_gui_base.h
#	src/widgets/dropdown.cpp
#	src/widgets/dropdown_type.h
This commit is contained in:
Jonathan G Rennison
2019-04-11 18:12:22 +01:00
53 changed files with 587 additions and 627 deletions

View File

@@ -479,12 +479,12 @@ struct AISettingsWindow : public Window {
this->clicked_dropdown = true; this->clicked_dropdown = true;
this->closing_dropdown = false; this->closing_dropdown = false;
DropDownList *list = new DropDownList(); DropDownList list;
for (int i = config_item.min_value; i <= config_item.max_value; i++) { for (int i = config_item.min_value; i <= config_item.max_value; i++) {
list->push_back(new DropDownListCharStringItem(config_item.labels->Find(i)->second, i, false)); list.emplace_back(new DropDownListCharStringItem(config_item.labels->Find(i)->second, i, false));
} }
ShowDropDownListAt(this, list, old_val, -1, wi_rect, COLOUR_ORANGE, true); ShowDropDownListAt(this, std::move(list), old_val, -1, wi_rect, COLOUR_ORANGE, true);
} }
} }
} else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) { } else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) {

View File

@@ -214,12 +214,12 @@ class BuildAirportWindow : public PickerWindowBase {
Scrollbar *vscroll; Scrollbar *vscroll;
/** Build a dropdown list of available airport classes */ /** Build a dropdown list of available airport classes */
static DropDownList *BuildAirportClassDropDown() static DropDownList BuildAirportClassDropDown()
{ {
DropDownList *list = new DropDownList(); DropDownList list;
for (uint i = 0; i < AirportClass::GetClassCount(); i++) { for (uint i = 0; i < AirportClass::GetClassCount(); i++) {
list->push_back(new DropDownListStringItem(AirportClass::Get((AirportClassID)i)->name, i, false)); list.emplace_back(new DropDownListStringItem(AirportClass::Get((AirportClassID)i)->name, i, false));
} }
return list; return list;

View File

@@ -467,10 +467,10 @@ public:
break; break;
case WID_RV_TRAIN_ENGINEWAGON_DROPDOWN: { case WID_RV_TRAIN_ENGINEWAGON_DROPDOWN: {
DropDownList *list = new DropDownList(); DropDownList list;
list->push_back(new DropDownListStringItem(STR_REPLACE_ENGINES, 1, false)); list.emplace_back(new DropDownListStringItem(STR_REPLACE_ENGINES, 1, false));
list->push_back(new DropDownListStringItem(STR_REPLACE_WAGONS, 0, false)); list.emplace_back(new DropDownListStringItem(STR_REPLACE_WAGONS, 0, false));
ShowDropDownList(this, list, this->replace_engines ? 1 : 0, WID_RV_TRAIN_ENGINEWAGON_DROPDOWN); ShowDropDownList(this, std::move(list), this->replace_engines ? 1 : 0, WID_RV_TRAIN_ENGINEWAGON_DROPDOWN);
break; break;
} }

View File

@@ -606,18 +606,18 @@ private:
} }
} }
DropDownList *list = new DropDownList(); DropDownList list;
if (default_livery != NULL) { if (default_livery != NULL) {
/* Add COLOUR_END to put the colour out of range, but also allow us to show what the default is */ /* Add COLOUR_END to put the colour out of range, but also allow us to show what the default is */
default_col = (primary ? default_livery->colour1 : default_livery->colour2) + COLOUR_END; default_col = (primary ? default_livery->colour1 : default_livery->colour2) + COLOUR_END;
list->push_back(new DropDownListColourItem(default_col, false)); list.emplace_back(new DropDownListColourItem(default_col, false));
} }
for (uint i = 0; i < lengthof(_colour_dropdown); i++) { for (uint i = 0; i < lengthof(_colour_dropdown); i++) {
list->push_back(new DropDownListColourItem(i, HasBit(used_colours, i))); list.emplace_back(new DropDownListColourItem(i, HasBit(used_colours, i)));
} }
byte sel = (default_livery == NULL || HasBit(livery->in_use, primary ? 0 : 1)) ? (primary ? livery->colour1 : livery->colour2) : default_col; byte sel = (default_livery == NULL || HasBit(livery->in_use, primary ? 0 : 1)) ? (primary ? livery->colour1 : livery->colour2) : default_col;
ShowDropDownList(this, list, sel, widget); ShowDropDownList(this, std::move(list), sel, widget);
} }
static int CDECL GroupNameSorter(const Group * const *a, const Group * const *b) static int CDECL GroupNameSorter(const Group * const *a, const Group * const *b)

View File

@@ -556,7 +556,7 @@ DEF_CONSOLE_CMD(ConUnBan)
/* Try by IP. */ /* Try by IP. */
uint index; uint index;
for (index = 0; index < _network_ban_list.size(); index++) { for (index = 0; index < _network_ban_list.size(); index++) {
if (strcmp(_network_ban_list[index], argv[1]) == 0) break; if (_network_ban_list[index] == argv[1]) break;
} }
/* Try by index. */ /* Try by index. */
@@ -566,9 +566,8 @@ DEF_CONSOLE_CMD(ConUnBan)
if (index < _network_ban_list.size()) { if (index < _network_ban_list.size()) {
char msg[64]; char msg[64];
seprintf(msg, lastof(msg), "Unbanned %s", _network_ban_list[index]); seprintf(msg, lastof(msg), "Unbanned %s", _network_ban_list[index].c_str());
IConsolePrint(CC_DEFAULT, msg); IConsolePrint(CC_DEFAULT, msg);
free(_network_ban_list[index]);
_network_ban_list.erase(_network_ban_list.begin() + index); _network_ban_list.erase(_network_ban_list.begin() + index);
} else { } else {
IConsolePrint(CC_DEFAULT, "Invalid list index or IP not in ban-list."); IConsolePrint(CC_DEFAULT, "Invalid list index or IP not in ban-list.");
@@ -588,8 +587,8 @@ DEF_CONSOLE_CMD(ConBanList)
IConsolePrint(CC_DEFAULT, "Banlist: "); IConsolePrint(CC_DEFAULT, "Banlist: ");
uint i = 1; uint i = 1;
for (char *entry : _network_ban_list) { for (const auto &entry : _network_ban_list) {
IConsolePrintF(CC_DEFAULT, " %d) %s", i, entry); IConsolePrintF(CC_DEFAULT, " %d) %s", i, entry.c_str());
} }
return true; return true;

View File

@@ -167,7 +167,7 @@ public:
template <typename T> template <typename T>
class AutoFreePtr class AutoFreePtr
{ {
T *ptr; ///< Stored pointer. T *ptr = nullptr; ///< Stored pointer.
public: public:
AutoFreePtr(T *ptr) : ptr(ptr) {} AutoFreePtr(T *ptr) : ptr(ptr) {}
@@ -192,6 +192,18 @@ public:
inline operator T *() { return this->ptr; } inline operator T *() { return this->ptr; }
/** Cast to underlaying regular pointer. */ /** Cast to underlaying regular pointer. */
inline operator const T *() const { return this->ptr; } inline operator const T *() const { return this->ptr; }
AutoFreePtr(AutoFreePtr<T> &&other) noexcept
{
*this = std::move(other);
}
AutoFreePtr& operator=(AutoFreePtr<T> &&other) noexcept
{
this->Assign(other.ptr);
other.ptr = nullptr;
return *this;
}
}; };
#endif /* ALLOC_TYPE_HPP */ #endif /* ALLOC_TYPE_HPP */

View File

@@ -69,66 +69,4 @@ T* grow(std::vector<T>& vec, std::size_t num)
return vec.data() + pos; return vec.data() + pos;
} }
/**
* Simple vector template class, with automatic free.
*
* @note There are no asserts in the class so you have
* to care about that you grab an item which is
* inside the list.
*
* @param T The type of the items stored, must be a pointer
*/
template <typename T>
class AutoFreeSmallVector : public std::vector<T> {
public:
~AutoFreeSmallVector()
{
this->Clear();
}
/**
* Remove all items from the list.
*/
inline void Clear()
{
for (T p : *this) {
free(p);
}
std::vector<T>::clear();
}
};
/**
* Simple vector template class, with automatic delete.
*
* @note There are no asserts in the class so you have
* to care about that you grab an item which is
* inside the list.
*
* @param T The type of the items stored, must be a pointer
*/
template <typename T>
class AutoDeleteSmallVector : public std::vector<T> {
public:
~AutoDeleteSmallVector()
{
this->Clear();
}
/**
* Remove all items from the list.
*/
inline void Clear()
{
for (T p : *this) {
delete p;
}
std::vector<T>::clear();
}
};
typedef AutoFreeSmallVector<char*> StringList; ///< Type for a list of strings.
#endif /* SMALLVEC_TYPE_HPP */ #endif /* SMALLVEC_TYPE_HPP */

View File

@@ -69,21 +69,21 @@ struct SetDateWindow : Window {
virtual void ShowDateDropDown(int widget) virtual void ShowDateDropDown(int widget)
{ {
int selected; int selected;
DropDownList *list = new DropDownList(); DropDownList list;
switch (widget) { switch (widget) {
default: NOT_REACHED(); default: NOT_REACHED();
case WID_SD_DAY: case WID_SD_DAY:
for (uint i = 0; i < 31; i++) { for (uint i = 0; i < 31; i++) {
list->push_back(new DropDownListStringItem(STR_DAY_NUMBER_1ST + i, i + 1, false)); list.emplace_back(new DropDownListStringItem(STR_DAY_NUMBER_1ST + i, i + 1, false));
} }
selected = this->date.day; selected = this->date.day;
break; break;
case WID_SD_MONTH: case WID_SD_MONTH:
for (uint i = 0; i < 12; i++) { for (uint i = 0; i < 12; i++) {
list->push_back(new DropDownListStringItem(STR_MONTH_JAN + i, i, false)); list.emplace_back(new DropDownListStringItem(STR_MONTH_JAN + i, i, false));
} }
selected = this->date.month; selected = this->date.month;
break; break;
@@ -92,13 +92,13 @@ struct SetDateWindow : Window {
for (Year i = this->min_year; i <= this->max_year; i++) { for (Year i = this->min_year; i <= this->max_year; i++) {
DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_JUST_INT, i, false); DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_JUST_INT, i, false);
item->SetParam(0, i); item->SetParam(0, i);
list->push_back(item); list.emplace_back(item);
} }
selected = this->date.year; selected = this->date.year;
break; break;
} }
ShowDropDownList(this, list, selected, widget); ShowDropDownList(this, std::move(list), selected, widget);
} }
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
@@ -194,7 +194,7 @@ struct SetMinutesWindow : SetDateWindow
virtual void ShowDateDropDown(int widget) virtual void ShowDateDropDown(int widget)
{ {
int selected; int selected;
DropDownList *list = new DropDownList(); DropDownList list;
switch (widget) { switch (widget) {
default: NOT_REACHED(); default: NOT_REACHED();
@@ -203,7 +203,7 @@ struct SetMinutesWindow : SetDateWindow
for (uint i = 0; i < 60; i++) { for (uint i = 0; i < 60; i++) {
DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_JUST_INT, i, false); DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_JUST_INT, i, false);
item->SetParam(0, i); item->SetParam(0, i);
list->push_back(item); list.emplace_back(item);
} }
selected = MINUTES_MINUTE(minutes); selected = MINUTES_MINUTE(minutes);
break; break;
@@ -212,14 +212,14 @@ struct SetMinutesWindow : SetDateWindow
for (uint i = 0; i < 24; i++) { for (uint i = 0; i < 24; i++) {
DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_JUST_INT, i, false); DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_JUST_INT, i, false);
item->SetParam(0, i); item->SetParam(0, i);
list->push_back(item); list.emplace_back(item);
} }
selected = MINUTES_HOUR(minutes); selected = MINUTES_HOUR(minutes);
break; break;
} }
ShowDropDownList(this, list, selected, widget); ShowDropDownList(this, std::move(list), selected, widget);
} }
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)

View File

@@ -23,6 +23,7 @@
#include "table/strings.h" #include "table/strings.h"
#include <stdarg.h> #include <stdarg.h>
#include <memory>
#include "../safeguards.h" #include "../safeguards.h"
@@ -80,16 +81,14 @@ LanguageStrings::~LanguageStrings()
* @param file The file to read from. * @param file The file to read from.
* @return The raw strings, or NULL upon error. * @return The raw strings, or NULL upon error.
*/ */
LanguageStrings *ReadRawLanguageStrings(const char *file) std::unique_ptr<LanguageStrings> ReadRawLanguageStrings(const char *file)
{ {
LanguageStrings *ret = NULL;
FILE *fh = NULL;
try { try {
size_t to_read; size_t to_read;
fh = FioFOpenFile(file, "rb", GAME_DIR, &to_read); FILE *fh = FioFOpenFile(file, "rb", GAME_DIR, &to_read);
if (fh == NULL) { if (fh == NULL) return NULL;
return NULL;
} FileCloser fhClose(fh);
const char *langname = strrchr(file, PATHSEPCHAR); const char *langname = strrchr(file, PATHSEPCHAR);
if (langname == NULL) { if (langname == NULL) {
@@ -99,12 +98,9 @@ LanguageStrings *ReadRawLanguageStrings(const char *file)
} }
/* Check for invalid empty filename */ /* Check for invalid empty filename */
if (*langname == '.' || *langname == 0) { if (*langname == '.' || *langname == 0) return NULL;
fclose(fh);
return NULL;
}
ret = new LanguageStrings(langname, strchr(langname, '.')); std::unique_ptr<LanguageStrings> ret(new LanguageStrings(langname, strchr(langname, '.')));
char buffer[2048]; char buffer[2048];
while (to_read != 0 && fgets(buffer, sizeof(buffer), fh) != NULL) { while (to_read != 0 && fgets(buffer, sizeof(buffer), fh) != NULL) {
@@ -115,7 +111,7 @@ LanguageStrings *ReadRawLanguageStrings(const char *file)
while (i > 0 && (buffer[i - 1] == '\r' || buffer[i - 1] == '\n' || buffer[i - 1] == ' ')) i--; while (i > 0 && (buffer[i - 1] == '\r' || buffer[i - 1] == '\n' || buffer[i - 1] == ' ')) i--;
buffer[i] = '\0'; buffer[i] = '\0';
ret->lines.push_back(stredup(buffer, buffer + to_read - 1)); ret->lines.emplace_back(buffer, buffer + to_read - 1);
if (len > to_read) { if (len > to_read) {
to_read = 0; to_read = 0;
@@ -124,11 +120,8 @@ LanguageStrings *ReadRawLanguageStrings(const char *file)
} }
} }
fclose(fh);
return ret; return ret;
} catch (...) { } catch (...) {
if (fh != NULL) fclose(fh);
delete ret;
return NULL; return NULL;
} }
} }
@@ -136,8 +129,8 @@ LanguageStrings *ReadRawLanguageStrings(const char *file)
/** A reader that simply reads using fopen. */ /** A reader that simply reads using fopen. */
struct StringListReader : StringReader { struct StringListReader : StringReader {
const char * const *p; ///< The current location of the iteration. StringList::const_iterator p; ///< The current location of the iteration.
const char * const *end; ///< The end of the iteration. StringList::const_iterator end; ///< The end of the iteration.
/** /**
* Create the reader. * Create the reader.
@@ -146,8 +139,8 @@ struct StringListReader : StringReader {
* @param master Are we reading the master file? * @param master Are we reading the master file?
* @param translation Are we reading a translation? * @param translation Are we reading a translation?
*/ */
StringListReader(StringData &data, const LanguageStrings *strings, bool master, bool translation) : StringListReader(StringData &data, const LanguageStrings &strings, bool master, bool translation) :
StringReader(data, strings->language, master, translation), p(strings->lines.data()), end(p + strings->lines.size()) StringReader(data, strings.language, master, translation), p(strings.lines.begin()), end(strings.lines.end())
{ {
} }
@@ -155,7 +148,7 @@ struct StringListReader : StringReader {
{ {
if (this->p == this->end) return NULL; if (this->p == this->end) return NULL;
strecpy(buffer, *this->p, last); strecpy(buffer, this->p->c_str(), last);
this->p++; this->p++;
return buffer; return buffer;
@@ -164,13 +157,13 @@ struct StringListReader : StringReader {
/** Class for writing an encoded language. */ /** Class for writing an encoded language. */
struct TranslationWriter : LanguageWriter { struct TranslationWriter : LanguageWriter {
StringList *strings; ///< The encoded strings. StringList &strings; ///< The encoded strings.
/** /**
* Writer for the encoded data. * Writer for the encoded data.
* @param strings The string table to add the strings to. * @param strings The string table to add the strings to.
*/ */
TranslationWriter(StringList *strings) : strings(strings) TranslationWriter(StringList &strings) : strings(strings)
{ {
} }
@@ -191,28 +184,25 @@ struct TranslationWriter : LanguageWriter {
void Write(const byte *buffer, size_t length) void Write(const byte *buffer, size_t length)
{ {
char *dest = MallocT<char>(length + 1); this->strings.emplace_back((const char *)buffer, length);
memcpy(dest, buffer, length);
dest[length] = '\0';
this->strings->push_back(dest);
} }
}; };
/** Class for writing the string IDs. */ /** Class for writing the string IDs. */
struct StringNameWriter : HeaderWriter { struct StringNameWriter : HeaderWriter {
StringList *strings; ///< The string names. StringList &strings; ///< The string names.
/** /**
* Writer for the string names. * Writer for the string names.
* @param strings The string table to add the strings to. * @param strings The string table to add the strings to.
*/ */
StringNameWriter(StringList *strings) : strings(strings) StringNameWriter(StringList &strings) : strings(strings)
{ {
} }
void WriteStringID(const char *name, int stringid) void WriteStringID(const char *name, int stringid)
{ {
if (stringid == (int)this->strings->size()) this->strings->push_back(stredup(name)); if (stringid == (int)this->strings.size()) this->strings.emplace_back(name);
} }
void Finalise(const StringData &data) void Finalise(const StringData &data)
@@ -246,7 +236,10 @@ public:
{ {
if (strcmp(filename, exclude) == 0) return true; if (strcmp(filename, exclude) == 0) return true;
gs->raw_strings.push_back(ReadRawLanguageStrings(filename)); auto ls = ReadRawLanguageStrings(filename);
if (ls == NULL) return false;
gs->raw_strings.push_back(std::move(ls));
return true; return true;
} }
}; };
@@ -267,9 +260,12 @@ GameStrings *LoadTranslations()
strecpy(e, "lang" PATHSEP "english.txt", lastof(filename)); strecpy(e, "lang" PATHSEP "english.txt", lastof(filename));
if (!FioCheckFileExists(filename, GAME_DIR)) return NULL; if (!FioCheckFileExists(filename, GAME_DIR)) return NULL;
auto ls = ReadRawLanguageStrings(filename);
if (ls == NULL) return NULL;
GameStrings *gs = new GameStrings(); GameStrings *gs = new GameStrings();
try { try {
gs->raw_strings.push_back(ReadRawLanguageStrings(filename)); gs->raw_strings.push_back(std::move(ls));
/* Scan for other language files */ /* Scan for other language files */
LanguageScanner scanner(gs, filename); LanguageScanner scanner(gs, filename);
@@ -309,23 +305,23 @@ GameStrings *LoadTranslations()
void GameStrings::Compile() void GameStrings::Compile()
{ {
StringData data(1); StringData data(1);
StringListReader master_reader(data, this->raw_strings[0], true, false); StringListReader master_reader(data, *this->raw_strings[0], true, false);
master_reader.ParseFile(); master_reader.ParseFile();
if (_errors != 0) throw std::exception(); if (_errors != 0) throw std::exception();
this->version = data.Version(); this->version = data.Version();
StringNameWriter id_writer(&this->string_names); StringNameWriter id_writer(this->string_names);
id_writer.WriteHeader(data); id_writer.WriteHeader(data);
for (LanguageStrings *p : this->raw_strings) { for (const auto &p : this->raw_strings) {
data.FreeTranslation(); data.FreeTranslation();
StringListReader translation_reader(data, p, false, strcmp(p->language, "english") != 0); StringListReader translation_reader(data, *p, false, strcmp(p->language, "english") != 0);
translation_reader.ParseFile(); translation_reader.ParseFile();
if (_errors != 0) throw std::exception(); if (_errors != 0) throw std::exception();
this->compiled_strings.push_back(new LanguageStrings(p->language)); this->compiled_strings.emplace_back(new LanguageStrings(p->language));
TranslationWriter writer(&this->compiled_strings.back()->lines); TranslationWriter writer(this->compiled_strings.back()->lines);
writer.WriteLang(data); writer.WriteLang(data);
} }
} }
@@ -341,7 +337,7 @@ GameStrings *_current_data = NULL;
const char *GetGameStringPtr(uint id) const char *GetGameStringPtr(uint id)
{ {
if (id >= _current_data->cur_language->lines.size()) return GetStringPtr(STR_UNDEFINED); if (id >= _current_data->cur_language->lines.size()) return GetStringPtr(STR_UNDEFINED);
return _current_data->cur_language->lines[id]; return _current_data->cur_language->lines[id].c_str();
} }
/** /**
@@ -360,8 +356,8 @@ void RegisterGameTranslation(Squirrel *engine)
if (SQ_FAILED(sq_get(vm, -2))) return; if (SQ_FAILED(sq_get(vm, -2))) return;
int idx = 0; int idx = 0;
for (const char * const p : _current_data->string_names) { for (const auto &p : _current_data->string_names) {
sq_pushstring(vm, p, -1); sq_pushstring(vm, p.c_str(), -1);
sq_pushinteger(vm, idx); sq_pushinteger(vm, idx);
sq_rawset(vm, -3); sq_rawset(vm, -3);
idx++; idx++;
@@ -392,7 +388,7 @@ void ReconsiderGameScriptLanguage()
assert(language != NULL); assert(language != NULL);
language++; language++;
for (LanguageStrings *p : _current_data->compiled_strings) { for (auto &p : _current_data->compiled_strings) {
if (strcmp(p->language, language) == 0) { if (strcmp(p->language, language) == 0) {
_current_data->cur_language = p; _current_data->cur_language = p;
return; return;

View File

@@ -30,10 +30,10 @@ struct LanguageStrings {
/** Container for all the game strings. */ /** Container for all the game strings. */
struct GameStrings { struct GameStrings {
uint version; ///< The version of the language strings. uint version; ///< The version of the language strings.
LanguageStrings *cur_language; ///< The current (compiled) language. std::shared_ptr<LanguageStrings> cur_language; ///< The current (compiled) language.
AutoDeleteSmallVector<LanguageStrings *> raw_strings; ///< The raw strings per language, first must be English/the master language!. std::vector<std::unique_ptr<LanguageStrings>> raw_strings; ///< The raw strings per language, first must be English/the master language!.
AutoDeleteSmallVector<LanguageStrings *> compiled_strings; ///< The compiled strings per language, first must be English/the master language!. std::vector<std::shared_ptr<LanguageStrings>> compiled_strings; ///< The compiled strings per language, first must be English/the master language!.
StringList string_names; ///< The names of the compiled strings. StringList string_names; ///< The names of the compiled strings.
void Compile(); void Compile();

View File

@@ -308,14 +308,14 @@ static bool CheckMapSize(bool print_warning = true)
* Dimension selected in the other dropdown is used to suggest which choices are 'valid' * Dimension selected in the other dropdown is used to suggest which choices are 'valid'
* @param other_dimension Dimension specified by the second dropdown. * @param other_dimension Dimension specified by the second dropdown.
*/ */
static DropDownList *BuildMapsizeDropDown(int other_dimension) static DropDownList BuildMapsizeDropDown(int other_dimension)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
for (uint i = MIN_MAP_SIZE_BITS; i <= MAX_MAP_SIZE_BITS; i++) { for (uint i = MIN_MAP_SIZE_BITS; i <= MAX_MAP_SIZE_BITS; i++) {
DropDownListParamStringItem *item = new DropDownListParamStringItem((i + other_dimension > MAX_MAP_TILES_BITS) ? STR_RED_INT : STR_JUST_INT, i, false); DropDownListParamStringItem *item = new DropDownListParamStringItem((i + other_dimension > MAX_MAP_TILES_BITS) ? STR_RED_INT : STR_JUST_INT, i, false);
item->SetParam(0, 1LL << i); item->SetParam(0, 1LL << i);
list->push_back(item); list.emplace_back(item);
} }
return list; return list;

View File

@@ -340,12 +340,12 @@ static void SetColourRemap(TextColour colour)
* @return In case of left or center alignment the right most pixel we have drawn to. * @return In case of left or center alignment the right most pixel we have drawn to.
* In case of right alignment the left most pixel we have drawn to. * In case of right alignment the left most pixel we have drawn to.
*/ */
static int DrawLayoutLine(const ParagraphLayouter::Line *line, int y, int left, int right, StringAlignment align, bool underline, bool truncation) static int DrawLayoutLine(const ParagraphLayouter::Line &line, int y, int left, int right, StringAlignment align, bool underline, bool truncation)
{ {
if (line->CountRuns() == 0) return 0; if (line.CountRuns() == 0) return 0;
int w = line->GetWidth(); int w = line.GetWidth();
int h = line->GetLeading(); int h = line.GetLeading();
/* /*
* The following is needed for truncation. * The following is needed for truncation.
@@ -376,7 +376,7 @@ static int DrawLayoutLine(const ParagraphLayouter::Line *line, int y, int left,
* another size would be chosen it won't have truncated too little for * another size would be chosen it won't have truncated too little for
* the truncation dots. * the truncation dots.
*/ */
FontCache *fc = ((const Font*)line->GetVisualRun(0)->GetFont())->fc; FontCache *fc = ((const Font*)line.GetVisualRun(0).GetFont())->fc;
GlyphID dot_glyph = fc->MapCharToGlyph('.'); GlyphID dot_glyph = fc->MapCharToGlyph('.');
dot_width = fc->GetGlyphWidth(dot_glyph); dot_width = fc->GetGlyphWidth(dot_glyph);
dot_sprite = fc->GetGlyph(dot_glyph); dot_sprite = fc->GetGlyph(dot_glyph);
@@ -421,9 +421,9 @@ static int DrawLayoutLine(const ParagraphLayouter::Line *line, int y, int left,
TextColour colour = TC_BLACK; TextColour colour = TC_BLACK;
bool draw_shadow = false; bool draw_shadow = false;
for (int run_index = 0; run_index < line->CountRuns(); run_index++) { for (int run_index = 0; run_index < line.CountRuns(); run_index++) {
const ParagraphLayouter::VisualRun *run = line->GetVisualRun(run_index); const ParagraphLayouter::VisualRun &run = line.GetVisualRun(run_index);
const Font *f = (const Font*)run->GetFont(); const Font *f = (const Font*)run.GetFont();
FontCache *fc = f->fc; FontCache *fc = f->fc;
colour = f->colour; colour = f->colour;
@@ -435,15 +435,15 @@ static int DrawLayoutLine(const ParagraphLayouter::Line *line, int y, int left,
draw_shadow = fc->GetDrawGlyphShadow() && (colour & TC_NO_SHADE) == 0 && colour != TC_BLACK; draw_shadow = fc->GetDrawGlyphShadow() && (colour & TC_NO_SHADE) == 0 && colour != TC_BLACK;
for (int i = 0; i < run->GetGlyphCount(); i++) { for (int i = 0; i < run.GetGlyphCount(); i++) {
GlyphID glyph = run->GetGlyphs()[i]; GlyphID glyph = run.GetGlyphs()[i];
/* Not a valid glyph (empty) */ /* Not a valid glyph (empty) */
if (glyph == 0xFFFF) continue; if (glyph == 0xFFFF) continue;
int begin_x = (int)run->GetPositions()[i * 2] + left - offset_x; int begin_x = (int)run.GetPositions()[i * 2] + left - offset_x;
int end_x = (int)run->GetPositions()[i * 2 + 2] + left - offset_x - 1; int end_x = (int)run.GetPositions()[i * 2 + 2] + left - offset_x - 1;
int top = (int)run->GetPositions()[i * 2 + 1] + y; int top = (int)run.GetPositions()[i * 2 + 1] + y;
/* Truncated away. */ /* Truncated away. */
if (truncation && (begin_x < min_x || end_x > max_x)) continue; if (truncation && (begin_x < min_x || end_x > max_x)) continue;
@@ -512,7 +512,7 @@ int DrawString(int left, int right, int top, const char *str, TextColour colour,
Layouter layout(str, INT32_MAX, colour, fontsize); Layouter layout(str, INT32_MAX, colour, fontsize);
if (layout.size() == 0) return 0; if (layout.size() == 0) return 0;
return DrawLayoutLine(layout.front(), top, left, right, align, underline, true); return DrawLayoutLine(*layout.front(), top, left, right, align, underline, true);
} }
/** /**
@@ -648,14 +648,14 @@ int DrawStringMultiLine(int left, int right, int top, int bottom, const char *st
int last_line = top; int last_line = top;
int first_line = bottom; int first_line = bottom;
for (const ParagraphLayouter::Line *line : layout) { for (const auto &line : layout) {
int line_height = line->GetLeading(); int line_height = line->GetLeading();
if (y >= top && y < bottom) { if (y >= top && y < bottom) {
last_line = y + line_height; last_line = y + line_height;
if (first_line > y) first_line = y; if (first_line > y) first_line = y;
DrawLayoutLine(line, y, left, right, align, underline, false); DrawLayoutLine(*line, y, left, right, align, underline, false);
} }
y += line_height; y += line_height;
} }

View File

@@ -124,7 +124,7 @@ le_bool Font::getGlyphPoint(LEGlyphID glyph, le_int32 pointNumber, LEPoint &poin
/** /**
* Wrapper for doing layouts with ICU. * Wrapper for doing layouts with ICU.
*/ */
class ICUParagraphLayout : public AutoDeleteSmallVector<ParagraphLayouter::Line *>, public ParagraphLayouter { class ICUParagraphLayout : public ParagraphLayouter {
icu::ParagraphLayout *p; ///< The actual ICU paragraph layout. icu::ParagraphLayout *p; ///< The actual ICU paragraph layout.
public: public:
/** Visual run contains data about the bit of text with the same font. */ /** Visual run contains data about the bit of text with the same font. */
@@ -134,33 +134,33 @@ public:
public: public:
ICUVisualRun(const icu::ParagraphLayout::VisualRun *vr) : vr(vr) { } ICUVisualRun(const icu::ParagraphLayout::VisualRun *vr) : vr(vr) { }
const Font *GetFont() const { return (const Font*)vr->getFont(); } const Font *GetFont() const override { return (const Font*)vr->getFont(); }
int GetGlyphCount() const { return vr->getGlyphCount(); } int GetGlyphCount() const override { return vr->getGlyphCount(); }
const GlyphID *GetGlyphs() const { return vr->getGlyphs(); } const GlyphID *GetGlyphs() const override { return vr->getGlyphs(); }
const float *GetPositions() const { return vr->getPositions(); } const float *GetPositions() const override { return vr->getPositions(); }
int GetLeading() const { return vr->getLeading(); } int GetLeading() const override { return vr->getLeading(); }
const int *GetGlyphToCharMap() const { return vr->getGlyphToCharMap(); } const int *GetGlyphToCharMap() const override { return vr->getGlyphToCharMap(); }
}; };
/** A single line worth of VisualRuns. */ /** A single line worth of VisualRuns. */
class ICULine : public AutoDeleteSmallVector<ICUVisualRun *>, public ParagraphLayouter::Line { class ICULine : public std::vector<ICUVisualRun>, public ParagraphLayouter::Line {
icu::ParagraphLayout::Line *l; ///< The actual ICU line. icu::ParagraphLayout::Line *l; ///< The actual ICU line.
public: public:
ICULine(icu::ParagraphLayout::Line *l) : l(l) ICULine(icu::ParagraphLayout::Line *l) : l(l)
{ {
for (int i = 0; i < l->countRuns(); i++) { for (int i = 0; i < l->countRuns(); i++) {
this->push_back(new ICUVisualRun(l->getVisualRun(i))); this->emplace_back(l->getVisualRun(i));
} }
} }
~ICULine() { delete l; } ~ICULine() override { delete l; }
int GetLeading() const { return l->getLeading(); } int GetLeading() const override { return l->getLeading(); }
int GetWidth() const { return l->getWidth(); } int GetWidth() const override { return l->getWidth(); }
int CountRuns() const { return l->countRuns(); } int CountRuns() const override { return l->countRuns(); }
const ParagraphLayouter::VisualRun *GetVisualRun(int run) const { return this->at(run); } const ParagraphLayouter::VisualRun &GetVisualRun(int run) const override { return this->at(run); }
int GetInternalCharLength(WChar c) const int GetInternalCharLength(WChar c) const override
{ {
/* ICU uses UTF-16 internally which means we need to account for surrogate pairs. */ /* ICU uses UTF-16 internally which means we need to account for surrogate pairs. */
return Utf8CharLen(c) < 4 ? 1 : 2; return Utf8CharLen(c) < 4 ? 1 : 2;
@@ -168,13 +168,13 @@ public:
}; };
ICUParagraphLayout(icu::ParagraphLayout *p) : p(p) { } ICUParagraphLayout(icu::ParagraphLayout *p) : p(p) { }
~ICUParagraphLayout() { delete p; } ~ICUParagraphLayout() override { delete p; }
void Reflow() { p->reflow(); } void Reflow() override { p->reflow(); }
ParagraphLayouter::Line *NextLine(int max_width) std::unique_ptr<const Line> NextLine(int max_width) override
{ {
icu::ParagraphLayout::Line *l = p->nextLine(max_width); icu::ParagraphLayout::Line *l = p->nextLine(max_width);
return l == NULL ? NULL : new ICULine(l); return std::unique_ptr<const Line>(l == NULL ? NULL : new ICULine(l));
} }
}; };
@@ -259,24 +259,25 @@ public:
public: public:
FallbackVisualRun(Font *font, const WChar *chars, int glyph_count, int x); FallbackVisualRun(Font *font, const WChar *chars, int glyph_count, int x);
~FallbackVisualRun(); FallbackVisualRun(FallbackVisualRun &&other) noexcept;
const Font *GetFont() const; ~FallbackVisualRun() override;
int GetGlyphCount() const; const Font *GetFont() const override;
const GlyphID *GetGlyphs() const; int GetGlyphCount() const override;
const float *GetPositions() const; const GlyphID *GetGlyphs() const override;
int GetLeading() const; const float *GetPositions() const override;
const int *GetGlyphToCharMap() const; int GetLeading() const override;
const int *GetGlyphToCharMap() const override;
}; };
/** A single line worth of VisualRuns. */ /** A single line worth of VisualRuns. */
class FallbackLine : public AutoDeleteSmallVector<FallbackVisualRun *>, public ParagraphLayouter::Line { class FallbackLine : public std::vector<FallbackVisualRun>, public ParagraphLayouter::Line {
public: public:
int GetLeading() const; int GetLeading() const override;
int GetWidth() const; int GetWidth() const override;
int CountRuns() const; int CountRuns() const override;
const ParagraphLayouter::VisualRun *GetVisualRun(int run) const; const ParagraphLayouter::VisualRun &GetVisualRun(int run) const override;
int GetInternalCharLength(WChar c) const { return 1; } int GetInternalCharLength(WChar c) const override { return 1; }
}; };
const WChar *buffer_begin; ///< Begin of the buffer. const WChar *buffer_begin; ///< Begin of the buffer.
@@ -284,8 +285,8 @@ public:
FontMap &runs; ///< The fonts we have to use for this paragraph. FontMap &runs; ///< The fonts we have to use for this paragraph.
FallbackParagraphLayout(WChar *buffer, int length, FontMap &runs); FallbackParagraphLayout(WChar *buffer, int length, FontMap &runs);
void Reflow(); void Reflow() override;
const ParagraphLayouter::Line *NextLine(int max_width); std::unique_ptr<const Line> NextLine(int max_width) override;
}; };
/** /**
@@ -350,6 +351,18 @@ FallbackParagraphLayout::FallbackVisualRun::FallbackVisualRun(Font *font, const
} }
} }
/** Move constructor for visual runs.*/
FallbackParagraphLayout::FallbackVisualRun::FallbackVisualRun(FallbackVisualRun &&other) noexcept : font(other.font), glyph_count(other.glyph_count)
{
this->positions = other.positions;
this->glyph_to_char = other.glyph_to_char;
this->glyphs = other.glyphs;
other.positions = NULL;
other.glyph_to_char = NULL;
other.glyphs = NULL;
}
/** Free all data. */ /** Free all data. */
FallbackParagraphLayout::FallbackVisualRun::~FallbackVisualRun() FallbackParagraphLayout::FallbackVisualRun::~FallbackVisualRun()
{ {
@@ -419,8 +432,8 @@ int FallbackParagraphLayout::FallbackVisualRun::GetLeading() const
int FallbackParagraphLayout::FallbackLine::GetLeading() const int FallbackParagraphLayout::FallbackLine::GetLeading() const
{ {
int leading = 0; int leading = 0;
for (const FallbackVisualRun * const &run : *this) { for (const auto &run : *this) {
leading = max(leading, run->GetLeading()); leading = max(leading, run.GetLeading());
} }
return leading; return leading;
@@ -439,8 +452,8 @@ int FallbackParagraphLayout::FallbackLine::GetWidth() const
* Since there is no left-to-right support, taking this value of * Since there is no left-to-right support, taking this value of
* the last run gives us the end of the line and thus the width. * the last run gives us the end of the line and thus the width.
*/ */
const ParagraphLayouter::VisualRun *run = this->GetVisualRun(this->CountRuns() - 1); const auto &run = this->GetVisualRun(this->CountRuns() - 1);
return (int)run->GetPositions()[run->GetGlyphCount() * 2]; return (int)run.GetPositions()[run.GetGlyphCount() * 2];
} }
/** /**
@@ -456,7 +469,7 @@ int FallbackParagraphLayout::FallbackLine::CountRuns() const
* Get a specific visual run. * Get a specific visual run.
* @return The visual run. * @return The visual run.
*/ */
const ParagraphLayouter::VisualRun *FallbackParagraphLayout::FallbackLine::GetVisualRun(int run) const const ParagraphLayouter::VisualRun &FallbackParagraphLayout::FallbackLine::GetVisualRun(int run) const
{ {
return this->at(run); return this->at(run);
} }
@@ -485,7 +498,7 @@ void FallbackParagraphLayout::Reflow()
* @param max_width The maximum width of the string. * @param max_width The maximum width of the string.
* @return A Line, or NULL when at the end of the paragraph. * @return A Line, or NULL when at the end of the paragraph.
*/ */
const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width) std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine(int max_width)
{ {
/* Simple idea: /* Simple idea:
* - split a line at a newline character, or at a space where we can break a line. * - split a line at a newline character, or at a space where we can break a line.
@@ -493,13 +506,13 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
*/ */
if (this->buffer == NULL) return NULL; if (this->buffer == NULL) return NULL;
FallbackLine *l = new FallbackLine(); std::unique_ptr<FallbackLine> l(new FallbackLine());
if (*this->buffer == '\0') { if (*this->buffer == '\0') {
/* Only a newline. */ /* Only a newline. */
this->buffer = NULL; this->buffer = NULL;
l->push_back(new FallbackVisualRun(this->runs.front().second, this->buffer, 0, 0)); l->emplace_back(this->runs.front().second, this->buffer, 0, 0);
return l; return std::move(l); // Not supposed to be needed, but clang-3.8 barfs otherwise.
} }
int offset = this->buffer - this->buffer_begin; int offset = this->buffer - this->buffer_begin;
@@ -527,7 +540,7 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
if (this->buffer == next_run) { if (this->buffer == next_run) {
int w = l->GetWidth(); int w = l->GetWidth();
l->push_back(new FallbackVisualRun(iter->second, begin, this->buffer - begin, w)); l->emplace_back(iter->second, begin, this->buffer - begin, w);
iter++; iter++;
assert(iter != this->runs.End()); assert(iter != this->runs.End());
@@ -549,7 +562,7 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
/* The character is wider than allowed width; don't know /* The character is wider than allowed width; don't know
* what to do with this case... bail out! */ * what to do with this case... bail out! */
this->buffer = NULL; this->buffer = NULL;
return l; return std::move(l); // Not supposed to be needed, but clang-3.8 barfs otherwise.
} }
if (last_space == NULL) { if (last_space == NULL) {
@@ -574,9 +587,9 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
if (l->size() == 0 || last_char - begin != 0) { if (l->size() == 0 || last_char - begin != 0) {
int w = l->GetWidth(); int w = l->GetWidth();
l->push_back(new FallbackVisualRun(iter->second, begin, last_char - begin, w)); l->emplace_back(iter->second, begin, last_char - begin, w);
} }
return l; return std::move(l); // Not supposed to be needed, but clang-3.8 barfs otherwise.
} }
/** /**
@@ -717,12 +730,12 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi
} }
} }
/* Copy all lines into a local cache so we can reuse them later on more easily. */ /* Move all lines into a local cache so we can reuse them later on more easily. */
const ParagraphLayouter::Line *l; for (;;) {
while ((l = line.layout->NextLine(maxw)) != NULL) { auto l = line.layout->NextLine(maxw);
this->push_back(l); if (l == NULL) break;
this->push_back(std::move(l));
} }
} while (c != '\0'); } while (c != '\0');
} }
@@ -733,7 +746,7 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi
Dimension Layouter::GetBounds() Dimension Layouter::GetBounds()
{ {
Dimension d = { 0, 0 }; Dimension d = { 0, 0 };
for (const ParagraphLayouter::Line *l : *this) { for (const auto &l : *this) {
d.width = max<uint>(d.width, l->GetWidth()); d.width = max<uint>(d.width, l->GetWidth());
d.height += l->GetLeading(); d.height += l->GetLeading();
} }
@@ -762,7 +775,7 @@ Point Layouter::GetCharPosition(const char *ch) const
if (str == ch) { if (str == ch) {
/* Valid character. */ /* Valid character. */
const ParagraphLayouter::Line *line = this->front(); const auto &line = this->front();
/* Pointer to the end-of-string/line marker? Return total line width. */ /* Pointer to the end-of-string/line marker? Return total line width. */
if (*ch == '\0' || *ch == '\n') { if (*ch == '\0' || *ch == '\n') {
@@ -772,12 +785,12 @@ Point Layouter::GetCharPosition(const char *ch) const
/* Scan all runs until we've found our code point index. */ /* Scan all runs until we've found our code point index. */
for (int run_index = 0; run_index < line->CountRuns(); run_index++) { for (int run_index = 0; run_index < line->CountRuns(); run_index++) {
const ParagraphLayouter::VisualRun *run = line->GetVisualRun(run_index); const ParagraphLayouter::VisualRun &run = line->GetVisualRun(run_index);
for (int i = 0; i < run->GetGlyphCount(); i++) { for (int i = 0; i < run.GetGlyphCount(); i++) {
/* Matching glyph? Return position. */ /* Matching glyph? Return position. */
if ((size_t)run->GetGlyphToCharMap()[i] == index) { if ((size_t)run.GetGlyphToCharMap()[i] == index) {
Point p = { (int)run->GetPositions()[i * 2], (int)run->GetPositions()[i * 2 + 1] }; Point p = { (int)run.GetPositions()[i * 2], (int)run.GetPositions()[i * 2 + 1] };
return p; return p;
} }
} }
@@ -795,21 +808,21 @@ Point Layouter::GetCharPosition(const char *ch) const
*/ */
const char *Layouter::GetCharAtPosition(int x) const const char *Layouter::GetCharAtPosition(int x) const
{ {
const ParagraphLayouter::Line *line = this->front(); const auto &line = this->front();
for (int run_index = 0; run_index < line->CountRuns(); run_index++) { for (int run_index = 0; run_index < line->CountRuns(); run_index++) {
const ParagraphLayouter::VisualRun *run = line->GetVisualRun(run_index); const ParagraphLayouter::VisualRun &run = line->GetVisualRun(run_index);
for (int i = 0; i < run->GetGlyphCount(); i++) { for (int i = 0; i < run.GetGlyphCount(); i++) {
/* Not a valid glyph (empty). */ /* Not a valid glyph (empty). */
if (run->GetGlyphs()[i] == 0xFFFF) continue; if (run.GetGlyphs()[i] == 0xFFFF) continue;
int begin_x = (int)run->GetPositions()[i * 2]; int begin_x = (int)run.GetPositions()[i * 2];
int end_x = (int)run->GetPositions()[i * 2 + 2]; int end_x = (int)run.GetPositions()[i * 2 + 2];
if (IsInsideMM(x, begin_x, end_x)) { if (IsInsideMM(x, begin_x, end_x)) {
/* Found our glyph, now convert to UTF-8 string index. */ /* Found our glyph, now convert to UTF-8 string index. */
size_t index = run->GetGlyphToCharMap()[i]; size_t index = run.GetGlyphToCharMap()[i];
size_t cur_idx = 0; size_t cur_idx = 0;
for (const char *str = this->string; *str != '\0'; ) { for (const char *str = this->string; *str != '\0'; ) {

View File

@@ -137,12 +137,12 @@ public:
virtual int GetLeading() const = 0; virtual int GetLeading() const = 0;
virtual int GetWidth() const = 0; virtual int GetWidth() const = 0;
virtual int CountRuns() const = 0; virtual int CountRuns() const = 0;
virtual const VisualRun *GetVisualRun(int run) const = 0; virtual const VisualRun &GetVisualRun(int run) const = 0;
virtual int GetInternalCharLength(WChar c) const = 0; virtual int GetInternalCharLength(WChar c) const = 0;
}; };
virtual void Reflow() = 0; virtual void Reflow() = 0;
virtual const Line *NextLine(int max_width) = 0; virtual std::unique_ptr<const Line> NextLine(int max_width) = 0;
}; };
/** /**
@@ -150,7 +150,7 @@ public:
* *
* It also accounts for the memory allocations and frees. * It also accounts for the memory allocations and frees.
*/ */
class Layouter : public AutoDeleteSmallVector<const ParagraphLayouter::Line *> { class Layouter : public std::vector<std::unique_ptr<const ParagraphLayouter::Line>> {
const char *string; ///< Pointer to the original string. const char *string; ///< Pointer to the original string.
/** Key into the linecache */ /** Key into the linecache */

View File

@@ -789,9 +789,9 @@ public:
break; break;
case WID_GL_MANAGE_VEHICLES_DROPDOWN: { case WID_GL_MANAGE_VEHICLES_DROPDOWN: {
DropDownList *list = this->BuildActionDropdownList(true, Group::IsValidID(this->vli.index), this->vli.vtype == VEH_TRAIN, DropDownList list = this->BuildActionDropdownList(true, Group::IsValidID(this->vli.index), this->vli.vtype == VEH_TRAIN,
0, false, IsTopLevelGroupID(this->vli.index)); 0, false, IsTopLevelGroupID(this->vli.index));
ShowDropDownList(this, list, -1, WID_GL_MANAGE_VEHICLES_DROPDOWN); ShowDropDownList(this, std::move(list), -1, WID_GL_MANAGE_VEHICLES_DROPDOWN);
break; break;
} }

View File

@@ -2717,34 +2717,30 @@ struct IndustryCargoesWindow : public Window {
break; break;
case WID_IC_CARGO_DROPDOWN: { case WID_IC_CARGO_DROPDOWN: {
DropDownList *lst = new DropDownList; DropDownList lst;
const CargoSpec *cs; const CargoSpec *cs;
FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) { FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
lst->push_back(new DropDownListStringItem(cs->name, cs->Index(), false)); lst.emplace_back(new DropDownListStringItem(cs->name, cs->Index(), false));
}
if (lst->size() == 0) {
delete lst;
break;
} }
if (!lst.empty()) {
int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1; int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1;
ShowDropDownList(this, lst, selected, WID_IC_CARGO_DROPDOWN, 0, true); ShowDropDownList(this, std::move(lst), selected, WID_IC_CARGO_DROPDOWN, 0, true);
}
break; break;
} }
case WID_IC_IND_DROPDOWN: { case WID_IC_IND_DROPDOWN: {
DropDownList *lst = new DropDownList; DropDownList lst;
for (uint i = 0; i < NUM_INDUSTRYTYPES; i++) { for (uint i = 0; i < NUM_INDUSTRYTYPES; i++) {
IndustryType ind = _sorted_industry_types[i]; IndustryType ind = _sorted_industry_types[i];
const IndustrySpec *indsp = GetIndustrySpec(ind); const IndustrySpec *indsp = GetIndustrySpec(ind);
if (!indsp->enabled) continue; if (!indsp->enabled) continue;
lst->push_back(new DropDownListStringItem(indsp->name, ind, false)); lst.emplace_back(new DropDownListStringItem(indsp->name, ind, false));
}
if (lst->size() == 0) {
delete lst;
break;
} }
if (!lst.empty()) {
int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1; int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1;
ShowDropDownList(this, lst, selected, WID_IC_IND_DROPDOWN, 0, true); ShowDropDownList(this, std::move(lst), selected, WID_IC_IND_DROPDOWN, 0, true);
}
break; break;
} }
} }

View File

@@ -226,8 +226,8 @@ STR_UNITS_HEIGHT_METRIC :{COMMA}{NBSP}m
STR_UNITS_HEIGHT_SI :{COMMA}{NBSP}m STR_UNITS_HEIGHT_SI :{COMMA}{NBSP}m
# Common window strings # Common window strings
STR_LIST_FILTER_TITLE :{BLACK}Filter String: STR_LIST_FILTER_TITLE :{BLACK}Filter-String:
STR_LIST_FILTER_OSKTITLE :{BLACK}Filter String STR_LIST_FILTER_OSKTITLE :{BLACK}Filter-String
STR_LIST_FILTER_TOOLTIP :{BLACK}Filter d'Lëscht op e Wuert STR_LIST_FILTER_TOOLTIP :{BLACK}Filter d'Lëscht op e Wuert
STR_TOOLTIP_GROUP_ORDER :{BLACK}Wiel Gruppéierreihefollëg STR_TOOLTIP_GROUP_ORDER :{BLACK}Wiel Gruppéierreihefollëg
@@ -675,6 +675,7 @@ STR_MUSIC_TOOLTIP_TOGGLE_PROGRAM_SHUFFLE :{BLACK}Schalt d
STR_MUSIC_TOOLTIP_SHOW_MUSIC_TRACK_SELECTION :{BLACK}Weis d'Fënster fir Musik ze wielen STR_MUSIC_TOOLTIP_SHOW_MUSIC_TRACK_SELECTION :{BLACK}Weis d'Fënster fir Musik ze wielen
# Playlist window # Playlist window
STR_PLAYLIST_MUSIC_SELECTION_SETNAME :{WHITE}Musik-Programm - '{STRING}'
STR_PLAYLIST_TRACK_NAME :{TINY_FONT}{LTBLUE}{ZEROFILL_NUM} "{STRING}" STR_PLAYLIST_TRACK_NAME :{TINY_FONT}{LTBLUE}{ZEROFILL_NUM} "{STRING}"
STR_PLAYLIST_TRACK_INDEX :{TINY_FONT}{BLACK}Lidder Index STR_PLAYLIST_TRACK_INDEX :{TINY_FONT}{BLACK}Lidder Index
STR_PLAYLIST_PROGRAM :{TINY_FONT}{BLACK}Programm - '{STRING}' STR_PLAYLIST_PROGRAM :{TINY_FONT}{BLACK}Programm - '{STRING}'
@@ -995,6 +996,7 @@ STR_GAME_OPTIONS_GUI_ZOOM_DROPDOWN_2X_ZOOM :Duebel
STR_GAME_OPTIONS_GUI_ZOOM_DROPDOWN_4X_ZOOM :Véierfach STR_GAME_OPTIONS_GUI_ZOOM_DROPDOWN_4X_ZOOM :Véierfach
STR_GAME_OPTIONS_FONT_ZOOM :{BLACK}Schrëftgréisst STR_GAME_OPTIONS_FONT_ZOOM :{BLACK}Schrëftgréisst
STR_GAME_OPTIONS_FONT_ZOOM_DROPDOWN_TOOLTIP :{BLACK}Wiel d'Interface-Schrëftgréisst aus
STR_GAME_OPTIONS_FONT_ZOOM_DROPDOWN_NORMAL :Normal STR_GAME_OPTIONS_FONT_ZOOM_DROPDOWN_NORMAL :Normal
STR_GAME_OPTIONS_FONT_ZOOM_DROPDOWN_2X_ZOOM :Duebel Gréisst STR_GAME_OPTIONS_FONT_ZOOM_DROPDOWN_2X_ZOOM :Duebel Gréisst
@@ -1356,6 +1358,7 @@ STR_CONFIG_SETTING_SMALLMAP_LAND_COLOUR_VIOLET :Mof
STR_CONFIG_SETTING_SCROLLMODE :Usiicht-Scrollverhalen: {STRING} STR_CONFIG_SETTING_SCROLLMODE :Usiicht-Scrollverhalen: {STRING}
STR_CONFIG_SETTING_SCROLLMODE_HELPTEXT :Verhalen beim Scrolle vun der Kaart STR_CONFIG_SETTING_SCROLLMODE_HELPTEXT :Verhalen beim Scrolle vun der Kaart
STR_CONFIG_SETTING_SCROLLMODE_DEFAULT :D'Usiicht mat der rietser Maustast bewegen, Maus-Positioun gespaart STR_CONFIG_SETTING_SCROLLMODE_DEFAULT :D'Usiicht mat der rietser Maustast bewegen, Maus-Positioun gespaart
STR_CONFIG_SETTING_SCROLLMODE_RMB :D'Kaart mat der rietser Maustast bewegen
STR_CONFIG_SETTING_SCROLLMODE_LMB :Kaart mat der lénker Maustast bewegen STR_CONFIG_SETTING_SCROLLMODE_LMB :Kaart mat der lénker Maustast bewegen
STR_CONFIG_SETTING_SMOOTH_SCROLLING :Feine Scrolling: {STRING} STR_CONFIG_SETTING_SMOOTH_SCROLLING :Feine Scrolling: {STRING}
STR_CONFIG_SETTING_SMOOTH_SCROLLING_HELPTEXT :Kontrolléiert wéi d'Haptusiicht op eng bestëmmten Positioun scrollt, wann een op déi kléng Kaart klickt oder en Befehl fir ob en spezifescht Objet ze scrollen gëtt. Wann ugeschalt, gëtt bis dohin gescrollt, wann ausgeschalt, spréngt d'Vue op den Zielobjet STR_CONFIG_SETTING_SMOOTH_SCROLLING_HELPTEXT :Kontrolléiert wéi d'Haptusiicht op eng bestëmmten Positioun scrollt, wann een op déi kléng Kaart klickt oder en Befehl fir ob en spezifescht Objet ze scrollen gëtt. Wann ugeschalt, gëtt bis dohin gescrollt, wann ausgeschalt, spréngt d'Vue op den Zielobjet
@@ -1580,6 +1583,7 @@ STR_CONFIG_SETTING_TOWN_FOUNDING_FORBIDDEN :Verbueden
STR_CONFIG_SETTING_TOWN_FOUNDING_ALLOWED :Erlaabt STR_CONFIG_SETTING_TOWN_FOUNDING_ALLOWED :Erlaabt
STR_CONFIG_SETTING_TOWN_FOUNDING_ALLOWED_CUSTOM_LAYOUT :Erlaabt, custom Stad-Layout STR_CONFIG_SETTING_TOWN_FOUNDING_ALLOWED_CUSTOM_LAYOUT :Erlaabt, custom Stad-Layout
STR_CONFIG_SETTING_TOWN_CARGOGENMODE :Duerfwuerengeneratioun: {STRING} STR_CONFIG_SETTING_TOWN_CARGOGENMODE :Duerfwuerengeneratioun: {STRING}
STR_CONFIG_SETTING_TOWN_CARGOGENMODE_HELPTEXT :Wéivill Wuere produzéiert ginn, relativ zur Bevölkerung vum Duerf.{}Quadratesche Wuesstum: En duebel sou grousst Duerf, generéiert véier mol souvill Passagéier.{}Lineare Wuesstum: En duebel sou grousst Duerf, generéiert duebel souvill Passagéier.
STR_CONFIG_SETTING_TOWN_CARGOGENMODE_BITCOUNT :Linear STR_CONFIG_SETTING_TOWN_CARGOGENMODE_BITCOUNT :Linear
STR_CONFIG_SETTING_EXTRA_TREE_PLACEMENT :Bamplazéirung: {STRING} STR_CONFIG_SETTING_EXTRA_TREE_PLACEMENT :Bamplazéirung: {STRING}
@@ -2704,13 +2708,19 @@ STR_ABOUT_COPYRIGHT_OPENTTD :{BLACK}OpenTTD
# Framerate display window # Framerate display window
STR_FRAMERATE_CAPTION :{WHITE}Biller pro Sekonn STR_FRAMERATE_CAPTION :{WHITE}Biller pro Sekonn
STR_FRAMERATE_CAPTION_SMALL :{STRING}{WHITE} ({DECIMAL}x)
STR_FRAMERATE_RATE_GAMELOOP_TOOLTIP :{BLACK}Unzuel Gameticks déi pro Sekonn simuléiert ginn. STR_FRAMERATE_RATE_GAMELOOP_TOOLTIP :{BLACK}Unzuel Gameticks déi pro Sekonn simuléiert ginn.
STR_FRAMERATE_RATE_BLITTER :{BLACK}Grafikframerate: {STRING}
STR_FRAMERATE_RATE_BLITTER_TOOLTIP :{BLACK}Unzuel u Videobiller déi pro Sekonn gerendert ginn.
STR_FRAMERATE_SPEED_FACTOR :{BLACK}Aktuelle Spillgeschw.-Faktor: {DECIMAL}x
STR_FRAMERATE_SPEED_FACTOR_TOOLTIP :{BLACK}Wéi séier d'Spill aktuell leeft, am Verglach mat der Geschw. vun der normaler Simulatioun.
STR_FRAMERATE_CURRENT :{WHITE}Aktuell STR_FRAMERATE_CURRENT :{WHITE}Aktuell
STR_FRAMERATE_AVERAGE :{WHITE}Mëttel STR_FRAMERATE_AVERAGE :{WHITE}Mëttel
STR_FRAMERATE_MS_GOOD :{LTBLUE}{DECIMAL} ms STR_FRAMERATE_MS_GOOD :{LTBLUE}{DECIMAL} ms
STR_FRAMERATE_MS_WARN :{YELLOW}{DECIMAL} ms STR_FRAMERATE_MS_WARN :{YELLOW}{DECIMAL} ms
STR_FRAMERATE_MS_BAD :{RED}{DECIMAL} ms STR_FRAMERATE_MS_BAD :{RED}{DECIMAL} ms
STR_FRAMERATE_FPS_GOOD :{LTBLUE}{DECIMAL} Biller/s STR_FRAMERATE_FPS_GOOD :{LTBLUE}{DECIMAL} Biller/s
STR_FRAMERATE_FPS_WARN :{YELLOW}{DECIMAL} Biller/s
STR_FRAMERATE_FPS_BAD :{RED}{DECIMAL} Biller/s STR_FRAMERATE_FPS_BAD :{RED}{DECIMAL} Biller/s
STR_FRAMERATE_GRAPH_SECONDS :{TINY_FONT}{COMMA} s STR_FRAMERATE_GRAPH_SECONDS :{TINY_FONT}{COMMA} s
############ Leave those lines in this order!! ############ Leave those lines in this order!!
@@ -2718,10 +2728,12 @@ STR_FRAMERATE_GAMELOOP :{BLACK}Spill to
STR_FRAMERATE_GL_TRAINS :{BLACK} Zuchticks: STR_FRAMERATE_GL_TRAINS :{BLACK} Zuchticks:
STR_FRAMERATE_GL_ROADVEHS :{BLACK} Stroossegefierer Ticken: STR_FRAMERATE_GL_ROADVEHS :{BLACK} Stroossegefierer Ticken:
STR_FRAMERATE_GL_LINKGRAPH :{BLACK} Linkgrafik-Verzögerung: STR_FRAMERATE_GL_LINKGRAPH :{BLACK} Linkgrafik-Verzögerung:
STR_FRAMERATE_DRAWING :{BLACK}Graphikrendering: STR_FRAMERATE_DRAWING :{BLACK}Grafikrendering:
STR_FRAMERATE_DRAWING_VIEWPORTS :{BLACK} Welt-Usiichten: STR_FRAMERATE_DRAWING_VIEWPORTS :{BLACK} Welt-Usiichten:
STR_FRAMERATE_VIDEO :{BLACK}Video-output: STR_FRAMERATE_VIDEO :{BLACK}Video-output:
STR_FRAMERATE_ALLSCRIPTS :{BLACK} GS/KI Total:
STR_FRAMERATE_GAMESCRIPT :{BLACK} Gamescript: STR_FRAMERATE_GAMESCRIPT :{BLACK} Gamescript:
STR_FRAMERATE_AI :{BLACK} KI {NUM} {STRING}
############ End of leave-in-this-order ############ End of leave-in-this-order
############ Leave those lines in this order!! ############ Leave those lines in this order!!
STR_FRAMETIME_CAPTION_GAMELOOP :Spill-Loop STR_FRAMETIME_CAPTION_GAMELOOP :Spill-Loop
@@ -2729,8 +2741,14 @@ STR_FRAMETIME_CAPTION_GL_ECONOMY :Wuerenhandling
STR_FRAMETIME_CAPTION_GL_TRAINS :Zuchticks STR_FRAMETIME_CAPTION_GL_TRAINS :Zuchticks
STR_FRAMETIME_CAPTION_GL_ROADVEHS :Stroossegefierer Ticken STR_FRAMETIME_CAPTION_GL_ROADVEHS :Stroossegefierer Ticken
STR_FRAMETIME_CAPTION_GL_SHIPS :Schëffticker STR_FRAMETIME_CAPTION_GL_SHIPS :Schëffticker
STR_FRAMETIME_CAPTION_GL_LANDSCAPE :Weltticks
STR_FRAMETIME_CAPTION_DRAWING :Grafikrendering
STR_FRAMETIME_CAPTION_DRAWING_VIEWPORTS :Weltusiicht-Rendering
STR_FRAMETIME_CAPTION_VIDEO :Video-output
STR_FRAMETIME_CAPTION_SOUND :Soundmixing STR_FRAMETIME_CAPTION_SOUND :Soundmixing
STR_FRAMETIME_CAPTION_ALLSCRIPTS :GS/KI Scripttotaler
STR_FRAMETIME_CAPTION_GAMESCRIPT :Spill-Script STR_FRAMETIME_CAPTION_GAMESCRIPT :Spill-Script
STR_FRAMETIME_CAPTION_AI :KI {NUM} {STRING}
############ End of leave-in-this-order ############ End of leave-in-this-order
@@ -2756,6 +2774,7 @@ STR_SAVELOAD_DETAIL_CAPTION :{BLACK}Detailer
STR_SAVELOAD_DETAIL_NOT_AVAILABLE :{BLACK}Keng Informatioun do STR_SAVELOAD_DETAIL_NOT_AVAILABLE :{BLACK}Keng Informatioun do
STR_SAVELOAD_DETAIL_COMPANY_INDEX :{SILVER}{COMMA}: {WHITE}{STRING} STR_SAVELOAD_DETAIL_COMPANY_INDEX :{SILVER}{COMMA}: {WHITE}{STRING}
STR_SAVELOAD_DETAIL_GRFSTATUS :{SILVER}NewGRF: {WHITE}{STRING} STR_SAVELOAD_DETAIL_GRFSTATUS :{SILVER}NewGRF: {WHITE}{STRING}
STR_SAVELOAD_FILTER_TITLE :{BLACK}Filter-String:
STR_SAVELOAD_OVERWRITE_TITLE :{WHITE}Datei iwwerschreiwen STR_SAVELOAD_OVERWRITE_TITLE :{WHITE}Datei iwwerschreiwen
STR_SAVELOAD_OSKTITLE :{BLACK}Gëff dem Spillstand en Numm STR_SAVELOAD_OSKTITLE :{BLACK}Gëff dem Spillstand en Numm
@@ -2874,6 +2893,7 @@ STR_NEWGRF_SETTINGS_VERSION :{BLACK}Versioun
STR_NEWGRF_SETTINGS_MIN_VERSION :{BLACK}Min. kompatibel Versioun: {SILVER}{NUM} STR_NEWGRF_SETTINGS_MIN_VERSION :{BLACK}Min. kompatibel Versioun: {SILVER}{NUM}
STR_NEWGRF_SETTINGS_MD5SUM :{BLACK}MD5sum: {SILVER}{STRING} STR_NEWGRF_SETTINGS_MD5SUM :{BLACK}MD5sum: {SILVER}{STRING}
STR_NEWGRF_SETTINGS_PALETTE :{BLACK}Palette: {SILVER}{STRING} STR_NEWGRF_SETTINGS_PALETTE :{BLACK}Palette: {SILVER}{STRING}
STR_NEWGRF_SETTINGS_PALETTE_DEFAULT :Standard (S)
STR_NEWGRF_SETTINGS_PALETTE_DEFAULT_32BPP :Standard (S) / 32 bpp STR_NEWGRF_SETTINGS_PALETTE_DEFAULT_32BPP :Standard (S) / 32 bpp
STR_NEWGRF_SETTINGS_PALETTE_LEGACY :Legacy (W) STR_NEWGRF_SETTINGS_PALETTE_LEGACY :Legacy (W)
STR_NEWGRF_SETTINGS_PARAMETER :{BLACK}Parameter: {SILVER}{STRING} STR_NEWGRF_SETTINGS_PARAMETER :{BLACK}Parameter: {SILVER}{STRING}
@@ -3032,7 +3052,7 @@ STR_TOWN_VIEW_TOWN_CAPTION :{WHITE}{TOWN}
STR_TOWN_VIEW_CITY_CAPTION :{WHITE}{TOWN} (Stad) STR_TOWN_VIEW_CITY_CAPTION :{WHITE}{TOWN} (Stad)
STR_TOWN_VIEW_POPULATION_HOUSES :{BLACK}Awunner: {ORANGE}{COMMA}{BLACK} Haiser: {ORANGE}{COMMA} STR_TOWN_VIEW_POPULATION_HOUSES :{BLACK}Awunner: {ORANGE}{COMMA}{BLACK} Haiser: {ORANGE}{COMMA}
STR_TOWN_VIEW_CARGO_LAST_MONTH_MAX :{BLACK}{CARGO_LIST} leschte Mount: {ORANGE}{COMMA}{BLACK} Max: {ORANGE}{COMMA} STR_TOWN_VIEW_CARGO_LAST_MONTH_MAX :{BLACK}{CARGO_LIST} leschte Mount: {ORANGE}{COMMA}{BLACK} Max: {ORANGE}{COMMA}
STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH :{BLACK}Gidder gebraucht fir Stadwuesstem: STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH :{BLACK}Gidder gebraucht fir Stadwuesstum:
STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_REQUIRED_GENERAL :{ORANGE}{STRING}{RED} gebraucht STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_REQUIRED_GENERAL :{ORANGE}{STRING}{RED} gebraucht
STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_REQUIRED_WINTER :{ORANGE}{STRING}{BLACK} gebraucht am Wanter STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_REQUIRED_WINTER :{ORANGE}{STRING}{BLACK} gebraucht am Wanter
STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_DELIVERED_GENERAL :{ORANGE}{STRING}{GREEN} geliwwert STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_DELIVERED_GENERAL :{ORANGE}{STRING}{GREEN} geliwwert
@@ -3339,6 +3359,7 @@ STR_INDUSTRY_VIEW_LOCATION_TOOLTIP :{BLACK}Zentréi
STR_INDUSTRY_VIEW_PRODUCTION_LEVEL :{BLACK}Produktiounslevel: {YELLOW}{COMMA}% STR_INDUSTRY_VIEW_PRODUCTION_LEVEL :{BLACK}Produktiounslevel: {YELLOW}{COMMA}%
STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE :{YELLOW}D'Industrie annoncéiert dass se zougemaach gëtt STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE :{YELLOW}D'Industrie annoncéiert dass se zougemaach gëtt
STR_INDUSTRY_VIEW_PRODUCES_N_CARGO :{BLACK}Produzéiert: {YELLOW}{STRING}{STRING}
STR_INDUSTRY_VIEW_CARGO_LIST_EXTENSION :, {STRING}{STRING} STR_INDUSTRY_VIEW_CARGO_LIST_EXTENSION :, {STRING}{STRING}
STR_INDUSTRY_VIEW_REQUIRES :{BLACK}Brauch: STR_INDUSTRY_VIEW_REQUIRES :{BLACK}Brauch:
@@ -3441,6 +3462,7 @@ STR_PURCHASE_INFO_COST :{BLACK}Käschte
STR_PURCHASE_INFO_COST_REFIT :{BLACK}Käschten: {GOLD}{CURRENCY_LONG}{BLACK} (Embaukäschten: {GOLD}{CURRENCY_LONG}{BLACK}) STR_PURCHASE_INFO_COST_REFIT :{BLACK}Käschten: {GOLD}{CURRENCY_LONG}{BLACK} (Embaukäschten: {GOLD}{CURRENCY_LONG}{BLACK})
STR_PURCHASE_INFO_WEIGHT_CWEIGHT :{BLACK}Gewiicht: {GOLD}{WEIGHT_SHORT} ({WEIGHT_SHORT}) STR_PURCHASE_INFO_WEIGHT_CWEIGHT :{BLACK}Gewiicht: {GOLD}{WEIGHT_SHORT} ({WEIGHT_SHORT})
STR_PURCHASE_INFO_COST_SPEED :{BLACK}Käschten: {GOLD}{CURRENCY_LONG}{BLACK} Geschw.: {GOLD}{VELOCITY} STR_PURCHASE_INFO_COST_SPEED :{BLACK}Käschten: {GOLD}{CURRENCY_LONG}{BLACK} Geschw.: {GOLD}{VELOCITY}
STR_PURCHASE_INFO_COST_REFIT_SPEED :{BLACK}Käschten: {GOLD}{CURRENCY_LONG}{BLACK} (Embaukäschten: {GOLD}{CURRENCY_LONG}{BLACK}) Geschw.: {GOLD}{VELOCITY}
STR_PURCHASE_INFO_AIRCRAFT_CAPACITY :{BLACK}Kapazitéit: {GOLD}{CARGO_LONG}, {CARGO_LONG} STR_PURCHASE_INFO_AIRCRAFT_CAPACITY :{BLACK}Kapazitéit: {GOLD}{CARGO_LONG}, {CARGO_LONG}
STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT :{BLACK}Ugedriwwen Waggonen: {GOLD}+{POWER}{BLACK} Gewiicht: {GOLD}+{WEIGHT_SHORT} STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT :{BLACK}Ugedriwwen Waggonen: {GOLD}+{POWER}{BLACK} Gewiicht: {GOLD}+{WEIGHT_SHORT}
STR_PURCHASE_INFO_REFITTABLE_TO :{BLACK}Embaubar zu: {GOLD}{STRING} STR_PURCHASE_INFO_REFITTABLE_TO :{BLACK}Embaubar zu: {GOLD}{STRING}
@@ -3460,13 +3482,17 @@ STR_BUY_VEHICLE_ROAD_VEHICLE_BUY_VEHICLE_BUTTON :{BLACK}Gefier k
STR_BUY_VEHICLE_SHIP_BUY_VEHICLE_BUTTON :{BLACK}Schëff kafen STR_BUY_VEHICLE_SHIP_BUY_VEHICLE_BUTTON :{BLACK}Schëff kafen
STR_BUY_VEHICLE_AIRCRAFT_BUY_VEHICLE_BUTTON :{BLACK}Fliger kafen STR_BUY_VEHICLE_AIRCRAFT_BUY_VEHICLE_BUTTON :{BLACK}Fliger kafen
STR_BUY_VEHICLE_TRAIN_BUY_REFIT_VEHICLE_BUTTON :{BLACK}Gefierer kafen an embauen STR_BUY_VEHICLE_TRAIN_BUY_REFIT_VEHICLE_BUTTON :{BLACK}Gefierer kafen an ëmbauen
STR_BUY_VEHICLE_ROAD_VEHICLE_BUY_REFIT_VEHICLE_BUTTON :{BLACK}Gefierer kafen an ëmbauen
STR_BUY_VEHICLE_SHIP_BUY_REFIT_VEHICLE_BUTTON :{BLACK}Schëff kafen an ëmbauen
STR_BUY_VEHICLE_AIRCRAFT_BUY_REFIT_VEHICLE_BUTTON :{BLACK}Fligeren kafen an ëmbauen
STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_TOOLTIP :{BLACK}Keeft den ungewielten Zuch. Shift+Klick weist ongeféier Käschten ouni Kaf STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_TOOLTIP :{BLACK}Keeft den ungewielten Zuch. Shift+Klick weist ongeféier Käschten ouni Kaf
STR_BUY_VEHICLE_ROAD_VEHICLE_BUY_VEHICLE_TOOLTIP :{BLACK}Keeft dat ugewielte Stroossegefier. Shift+Klick weist ongeféier Käschten ouni Kaf STR_BUY_VEHICLE_ROAD_VEHICLE_BUY_VEHICLE_TOOLTIP :{BLACK}Keeft dat ugewielte Stroossegefier. Shift+Klick weist ongeféier Käschten ouni Kaf
STR_BUY_VEHICLE_SHIP_BUY_VEHICLE_TOOLTIP :{BLACK}Keeft dat ugewielte Schëff. Shift+Klick weist ongeféier Käschten ouni Kaf STR_BUY_VEHICLE_SHIP_BUY_VEHICLE_TOOLTIP :{BLACK}Keeft dat ugewielte Schëff. Shift+Klick weist ongeféier Käschten ouni Kaf
STR_BUY_VEHICLE_AIRCRAFT_BUY_VEHICLE_TOOLTIP :{BLACK}Keeft den ungewielte Fliger. Shift+Klick weist ongeféier Käschten ouni Kaf STR_BUY_VEHICLE_AIRCRAFT_BUY_VEHICLE_TOOLTIP :{BLACK}Keeft den ungewielte Fliger. Shift+Klick weist ongeféier Käschten ouni Kaf
STR_BUY_VEHICLE_AIRCRAFT_BUY_REFIT_VEHICLE_TOOLTIP :{BLACK}Gewielte Fliger kafen an ëmbauen. Shift+Klick weist ongeféier Käschten ouni Kaf
STR_BUY_VEHICLE_TRAIN_RENAME_BUTTON :{BLACK}Ëmbenennen STR_BUY_VEHICLE_TRAIN_RENAME_BUTTON :{BLACK}Ëmbenennen
STR_BUY_VEHICLE_ROAD_VEHICLE_RENAME_BUTTON :{BLACK}Ëmbenennen STR_BUY_VEHICLE_ROAD_VEHICLE_RENAME_BUTTON :{BLACK}Ëmbenennen
@@ -3824,7 +3850,7 @@ STR_ORDER_DROP_TRANSFER :Transferéieren
STR_ORDER_DROP_NO_UNLOADING :Net entlueden STR_ORDER_DROP_NO_UNLOADING :Net entlueden
STR_ORDER_TOOLTIP_UNLOAD :{BLACK}Wiesselt d'Entluedverhale vun dem ungewielten Optrag STR_ORDER_TOOLTIP_UNLOAD :{BLACK}Wiesselt d'Entluedverhale vun dem ungewielten Optrag
STR_ORDER_REFIT :{BLACK}Ëmbauen STR_ORDER_REFIT :{BLACK}Embauen
STR_ORDER_REFIT_TOOLTIP :{BLACK}Wielt an wéi een Luedungstyp sollt emgebaut ginn. Ctrl+Klick fir den Ëmbau ze läschen STR_ORDER_REFIT_TOOLTIP :{BLACK}Wielt an wéi een Luedungstyp sollt emgebaut ginn. Ctrl+Klick fir den Ëmbau ze läschen
STR_ORDER_REFIT_AUTO :{BLACK}Embauen an der Statioun STR_ORDER_REFIT_AUTO :{BLACK}Embauen an der Statioun
STR_ORDER_REFIT_AUTO_TOOLTIP :{BLACK}Wiel wellëch Wuerentypen sollen auto-ersat ginn an dësem Optrag. Ctrl+Klick fir all Auto-Erneierungen wechzehuelen. Auto-Erneiern geht just wann d'Gefier ët erlaabt STR_ORDER_REFIT_AUTO_TOOLTIP :{BLACK}Wiel wellëch Wuerentypen sollen auto-ersat ginn an dësem Optrag. Ctrl+Klick fir all Auto-Erneierungen wechzehuelen. Auto-Erneiern geht just wann d'Gefier ët erlaabt
@@ -3920,8 +3946,8 @@ STR_ORDER_NO_UNLOAD_FULL_LOAD_ANY :(Net entlueden
STR_ORDER_NO_UNLOAD_NO_LOAD :(Keen Ent- an Belueden) STR_ORDER_NO_UNLOAD_NO_LOAD :(Keen Ent- an Belueden)
STR_ORDER_AUTO_REFIT :(Embauen op {STRING}) STR_ORDER_AUTO_REFIT :(Embauen op {STRING})
STR_ORDER_FULL_LOAD_REFIT :(Voll lueden mat Embauen op {STRING}) STR_ORDER_FULL_LOAD_REFIT :(Voll lueden mat ëmbauen op {STRING})
STR_ORDER_FULL_LOAD_ANY_REFIT :(Voll lueden mat all Wueren mat Embauen op {STRING}) STR_ORDER_FULL_LOAD_ANY_REFIT :(Voll lueden mat all Wueren mat ëmbauen op {STRING})
STR_ORDER_UNLOAD_REFIT :(Entlueden an Wueren lueden mat Embauen op {STRING}) STR_ORDER_UNLOAD_REFIT :(Entlueden an Wueren lueden mat Embauen op {STRING})
STR_ORDER_UNLOAD_FULL_LOAD_REFIT :(Entlueden an op voll Luedung waarden mat Embauen op {STRING}) STR_ORDER_UNLOAD_FULL_LOAD_REFIT :(Entlueden an op voll Luedung waarden mat Embauen op {STRING})
STR_ORDER_UNLOAD_FULL_LOAD_ANY_REFIT :(Entlueden an waard op iergendeng Volluedung mat Embauen op {STRING}) STR_ORDER_UNLOAD_FULL_LOAD_ANY_REFIT :(Entlueden an waard op iergendeng Volluedung mat Embauen op {STRING})
@@ -4422,6 +4448,7 @@ STR_ERROR_GROUP_CAN_T_CREATE :{WHITE}Kann d'G
STR_ERROR_GROUP_CAN_T_DELETE :{WHITE}Kann d'Grupp net läschen... STR_ERROR_GROUP_CAN_T_DELETE :{WHITE}Kann d'Grupp net läschen...
STR_ERROR_GROUP_CAN_T_RENAME :{WHITE}Kann d'Grupp net ëmbenennen... STR_ERROR_GROUP_CAN_T_RENAME :{WHITE}Kann d'Grupp net ëmbenennen...
STR_ERROR_GROUP_CAN_T_SET_PARENT :{WHITE}Kann iwwergeuerdent Grupp net setzen... STR_ERROR_GROUP_CAN_T_SET_PARENT :{WHITE}Kann iwwergeuerdent Grupp net setzen...
STR_ERROR_GROUP_CAN_T_SET_PARENT_RECURSION :{WHITE}... Schläifen an der Gruppenhierarchie si net erlabt
STR_ERROR_GROUP_CAN_T_REMOVE_ALL_VEHICLES :{WHITE}Kann net all d'Gefierer aus der Grupp läschen... STR_ERROR_GROUP_CAN_T_REMOVE_ALL_VEHICLES :{WHITE}Kann net all d'Gefierer aus der Grupp läschen...
STR_ERROR_GROUP_CAN_T_ADD_VEHICLE :{WHITE}Kann d'Gefier net bei d'Grupp bäisetzen... STR_ERROR_GROUP_CAN_T_ADD_VEHICLE :{WHITE}Kann d'Gefier net bei d'Grupp bäisetzen...
STR_ERROR_GROUP_CAN_T_ADD_SHARED_VEHICLE :{WHITE}Kann dei gedeelten Gefierer net bei d'Grupp bäisetzen... STR_ERROR_GROUP_CAN_T_ADD_SHARED_VEHICLE :{WHITE}Kann dei gedeelten Gefierer net bei d'Grupp bäisetzen...

View File

@@ -3435,6 +3435,7 @@ STR_GROUP_DEFAULT_ROAD_VEHICLES :Vehículos de c
STR_GROUP_DEFAULT_SHIPS :Barcos sin agrupar STR_GROUP_DEFAULT_SHIPS :Barcos sin agrupar
STR_GROUP_DEFAULT_AIRCRAFTS :Aeronaves sin agrupar STR_GROUP_DEFAULT_AIRCRAFTS :Aeronaves sin agrupar
STR_GROUP_COUNT_WITH_SUBGROUP :{TINY_FONT}{COMMA} (+{COMMA})
STR_GROUPS_CLICK_ON_GROUP_FOR_TOOLTIP :{BLACK}Grupos: Clic en un grupo para ver los vehículos incluidos. Arrastrar y soltar para reorganizar los grupos. STR_GROUPS_CLICK_ON_GROUP_FOR_TOOLTIP :{BLACK}Grupos: Clic en un grupo para ver los vehículos incluidos. Arrastrar y soltar para reorganizar los grupos.
STR_GROUP_CREATE_TOOLTIP :{BLACK}Clic para crear un grupo STR_GROUP_CREATE_TOOLTIP :{BLACK}Clic para crear un grupo
@@ -4472,6 +4473,7 @@ STR_ERROR_GROUP_CAN_T_CREATE :{WHITE}No se pu
STR_ERROR_GROUP_CAN_T_DELETE :{WHITE}No se puede eliminar grupo... STR_ERROR_GROUP_CAN_T_DELETE :{WHITE}No se puede eliminar grupo...
STR_ERROR_GROUP_CAN_T_RENAME :{WHITE}No se puede cambiar nombre del grupo... STR_ERROR_GROUP_CAN_T_RENAME :{WHITE}No se puede cambiar nombre del grupo...
STR_ERROR_GROUP_CAN_T_SET_PARENT :{WHITE}No se puede establecer la jerarquía de grupos... STR_ERROR_GROUP_CAN_T_SET_PARENT :{WHITE}No se puede establecer la jerarquía de grupos...
STR_ERROR_GROUP_CAN_T_SET_PARENT_RECURSION :{WHITE}... los bucles en la jerarquía de grupos no están permitidos
STR_ERROR_GROUP_CAN_T_REMOVE_ALL_VEHICLES :{WHITE}No se pueden quitar todos los vehículos de este grupo... STR_ERROR_GROUP_CAN_T_REMOVE_ALL_VEHICLES :{WHITE}No se pueden quitar todos los vehículos de este grupo...
STR_ERROR_GROUP_CAN_T_ADD_VEHICLE :{WHITE}No se puede añadir el vehículo a este grupo... STR_ERROR_GROUP_CAN_T_ADD_VEHICLE :{WHITE}No se puede añadir el vehículo a este grupo...
STR_ERROR_GROUP_CAN_T_ADD_SHARED_VEHICLE :{WHITE}No se pueden añadir vehículos compartidos al grupo... STR_ERROR_GROUP_CAN_T_ADD_SHARED_VEHICLE :{WHITE}No se pueden añadir vehículos compartidos al grupo...

View File

@@ -571,8 +571,7 @@ struct MusicTrackSelectionWindow : public Window {
case WID_MTS_MUSICSET: { case WID_MTS_MUSICSET: {
int selected = 0; int selected = 0;
DropDownList *dropdown = BuildMusicSetDropDownList(&selected); ShowDropDownList(this, BuildMusicSetDropDownList(&selected), selected, widget, 0, true, false);
ShowDropDownList(this, dropdown, selected, widget, 0, true, false);
break; break;
} }

View File

@@ -156,7 +156,7 @@ bool NetworkAddress::IsFamily(int family)
* @note netmask without /n assumes all bits need to match. * @note netmask without /n assumes all bits need to match.
* @return true if this IP is within the netmask. * @return true if this IP is within the netmask.
*/ */
bool NetworkAddress::IsInNetmask(char *netmask) bool NetworkAddress::IsInNetmask(const char *netmask)
{ {
/* Resolve it if we didn't do it already */ /* Resolve it if we didn't do it already */
if (!this->IsResolved()) this->GetAddress(); if (!this->IsResolved()) this->GetAddress();
@@ -166,17 +166,16 @@ bool NetworkAddress::IsInNetmask(char *netmask)
NetworkAddress mask_address; NetworkAddress mask_address;
/* Check for CIDR separator */ /* Check for CIDR separator */
char *chr_cidr = strchr(netmask, '/'); const char *chr_cidr = strchr(netmask, '/');
if (chr_cidr != NULL) { if (chr_cidr != NULL) {
int tmp_cidr = atoi(chr_cidr + 1); int tmp_cidr = atoi(chr_cidr + 1);
/* Invalid CIDR, treat as single host */ /* Invalid CIDR, treat as single host */
if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr; if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
/* Remove and then replace the / so that NetworkAddress works on the IP portion */ /* Remove the / so that NetworkAddress works on the IP portion */
*chr_cidr = '\0'; std::string ip_str(netmask, chr_cidr - netmask);
mask_address = NetworkAddress(netmask, 0, this->address.ss_family); mask_address = NetworkAddress(ip_str.c_str(), 0, this->address.ss_family);
*chr_cidr = '/';
} else { } else {
mask_address = NetworkAddress(netmask, 0, this->address.ss_family); mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
} }

View File

@@ -129,7 +129,7 @@ public:
} }
bool IsFamily(int family); bool IsFamily(int family);
bool IsInNetmask(char *netmask); bool IsInNetmask(const char *netmask);
/** /**
* Compare the address of this class with the address of another. * Compare the address of this class with the address of another.

View File

@@ -54,13 +54,13 @@ public:
/* Check if the client is banned */ /* Check if the client is banned */
bool banned = false; bool banned = false;
for (char *entry : _network_ban_list) { for (const auto &entry : _network_ban_list) {
banned = address.IsInNetmask(entry); banned = address.IsInNetmask(entry.c_str());
if (banned) { if (banned) {
Packet p(Tban_packet); Packet p(Tban_packet);
p.PrepareToSend(); p.PrepareToSend();
DEBUG(net, 1, "[%s] Banned ip tried to join (%s), refused", Tsocket::GetName(), entry); DEBUG(net, 1, "[%s] Banned ip tried to join (%s), refused", Tsocket::GetName(), entry.c_str());
if (send(s, (const char*)p.buffer, p.size, 0) < 0) { if (send(s, (const char*)p.buffer, p.size, 0) < 0) {
DEBUG(net, 0, "send failed with error %d", GET_LAST_ERROR()); DEBUG(net, 0, "send failed with error %d", GET_LAST_ERROR());

View File

@@ -651,8 +651,8 @@ void NetworkAddServer(const char *b)
*/ */
void GetBindAddresses(NetworkAddressList *addresses, uint16 port) void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
{ {
for (char *iter : _network_bind_list) { for (const auto &iter : _network_bind_list) {
addresses->emplace_back(iter, port); addresses->emplace_back(iter.c_str(), port);
} }
/* No address, so bind to everything. */ /* No address, so bind to everything. */
@@ -666,10 +666,10 @@ void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
* by the function that generates the config file. */ * by the function that generates the config file. */
void NetworkRebuildHostList() void NetworkRebuildHostList()
{ {
_network_host_list.Clear(); _network_host_list.clear();
for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) { for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
if (item->manually) _network_host_list.push_back(stredup(item->address.GetAddressAsString(false))); if (item->manually) _network_host_list.emplace_back(item->address.GetAddressAsString(false));
} }
} }

View File

@@ -43,7 +43,7 @@
struct PacketReader : LoadFilter { struct PacketReader : LoadFilter {
static const size_t CHUNK = 32 * 1024; ///< 32 KiB chunks of memory. static const size_t CHUNK = 32 * 1024; ///< 32 KiB chunks of memory.
AutoFreeSmallVector<byte *> blocks; ///< Buffer with blocks of allocated memory. std::vector<byte *> blocks; ///< Buffer with blocks of allocated memory.
byte *buf; ///< Buffer we're going to write to/read from. byte *buf; ///< Buffer we're going to write to/read from.
byte *bufe; ///< End of the buffer we write to/read from. byte *bufe; ///< End of the buffer we write to/read from.
byte **block; ///< The block we're reading from/writing to. byte **block; ///< The block we're reading from/writing to.
@@ -55,6 +55,13 @@ struct PacketReader : LoadFilter {
{ {
} }
~PacketReader() override
{
for (auto p : this->blocks) {
free(p);
}
}
/** /**
* Add a packet to this buffer. * Add a packet to this buffer.
* @param p The packet to add. * @param p The packet to add.

View File

@@ -1047,8 +1047,8 @@ void ShowNetworkGameWindow()
if (first) { if (first) {
first = false; first = false;
/* Add all servers from the config file to our list. */ /* Add all servers from the config file to our list. */
for (char *iter : _network_host_list) { for (const auto &iter : _network_host_list) {
NetworkAddServer(iter); NetworkAddServer(iter.c_str());
} }
} }

View File

@@ -2094,13 +2094,13 @@ uint NetworkServerKickOrBanIP(const char *ip, bool ban)
/* Add address to ban-list */ /* Add address to ban-list */
if (ban) { if (ban) {
bool contains = false; bool contains = false;
for (char *iter : _network_ban_list) { for (const auto &iter : _network_ban_list) {
if (strcmp(iter, ip) == 0) { if (iter == ip) {
contains = true; contains = true;
break; break;
} }
} }
if (!contains) _network_ban_list.push_back(stredup(ip)); if (!contains) _network_ban_list.emplace_back(ip);
} }
uint n = 0; uint n = 0;
@@ -2109,7 +2109,7 @@ uint NetworkServerKickOrBanIP(const char *ip, bool ban)
NetworkClientSocket *cs; NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) { FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->client_id == CLIENT_ID_SERVER) continue; if (cs->client_id == CLIENT_ID_SERVER) continue;
if (cs->client_address.IsInNetmask(const_cast<char *>(ip))) { if (cs->client_address.IsInNetmask(ip)) {
NetworkServerKickClient(cs->client_id); NetworkServerKickClient(cs->client_id);
n++; n++;
} }

View File

@@ -8229,7 +8229,7 @@ struct GRFPropertyMapAction {
const char *str_store = stredup(str); const char *str_store = stredup(str);
grfmsg(2, "Unimplemented mapped %s: %s, feature: %X, mapped to: %X, %s on use", grfmsg(2, "Unimplemented mapped %s: %s, feature: %X, mapped to: %X, %s on use",
this->descriptor, str, this->feature, this->prop_id, (this->fallback_mode == GPMFM_IGNORE) ? "ignoring" : "error"); this->descriptor, str, this->feature, this->prop_id, (this->fallback_mode == GPMFM_IGNORE) ? "ignoring" : "error");
_cur.grffile->remap_unknown_property_names.push_back(str_store); _cur.grffile->remap_unknown_property_names.emplace_back(str_store);
GRFFilePropertyRemapEntry &entry = _cur.grffile->action0_property_remaps[this->feature].Entry(this->prop_id); GRFFilePropertyRemapEntry &entry = _cur.grffile->action0_property_remaps[this->feature].Entry(this->prop_id);
entry.name = str_store; entry.name = str_store;
entry.id = (this->fallback_mode == GPMFM_IGNORE) ? A0RPI_UNKNOWN_IGNORE : A0RPI_UNKNOWN_ERROR; entry.id = (this->fallback_mode == GPMFM_IGNORE) ? A0RPI_UNKNOWN_IGNORE : A0RPI_UNKNOWN_ERROR;
@@ -8274,7 +8274,7 @@ struct GRFPropertyMapAction {
const char *str_store = stredup(str); const char *str_store = stredup(str);
grfmsg(2, "Unimplemented mapped %s: %s, mapped to: %X, %s on use", grfmsg(2, "Unimplemented mapped %s: %s, mapped to: %X, %s on use",
this->descriptor, str, this->prop_id, (this->fallback_mode == GPMFM_IGNORE) ? "ignoring" : "error"); this->descriptor, str, this->prop_id, (this->fallback_mode == GPMFM_IGNORE) ? "ignoring" : "error");
_cur.grffile->remap_unknown_property_names.push_back(str_store); _cur.grffile->remap_unknown_property_names.emplace_back(str_store);
Action5TypeRemapEntry &entry = _cur.grffile->action5_type_remaps.Entry(this->prop_id); Action5TypeRemapEntry &entry = _cur.grffile->action5_type_remaps.Entry(this->prop_id);
entry.name = str_store; entry.name = str_store;
entry.info = nullptr; entry.info = nullptr;

View File

@@ -226,7 +226,7 @@ struct GRFFile : ZeroedMemoryAllocator {
GRFFilePropertyRemapSet action0_property_remaps[GSF_END]; GRFFilePropertyRemapSet action0_property_remaps[GSF_END];
Action5TypeRemapSet action5_type_remaps; Action5TypeRemapSet action5_type_remaps;
AutoFreeSmallVector<const char *> remap_unknown_property_names; std::vector<AutoFreePtr<const char>> remap_unknown_property_names;
uint32 param[0x80]; uint32 param[0x80];
uint param_end; ///< one more than the highest set parameter uint param_end; ///< one more than the highest set parameter

View File

@@ -376,12 +376,12 @@ struct NewGRFParametersWindow : public Window {
this->clicked_dropdown = true; this->clicked_dropdown = true;
this->closing_dropdown = false; this->closing_dropdown = false;
DropDownList *list = new DropDownList(); DropDownList list;
for (uint32 i = par_info->min_value; i <= par_info->max_value; i++) { for (uint32 i = par_info->min_value; i <= par_info->max_value; i++) {
list->push_back(new DropDownListCharStringItem(GetGRFStringFromGRFText(par_info->value_names.Find(i)->second), i, false)); list.emplace_back(new DropDownListCharStringItem(GetGRFStringFromGRFText(par_info->value_names.Find(i)->second), i, false));
} }
ShowDropDownListAt(this, list, old_val, -1, wi_rect, COLOUR_ORANGE, true); ShowDropDownListAt(this, std::move(list), old_val, -1, wi_rect, COLOUR_ORANGE, true);
} }
} }
} else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) { } else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) {
@@ -565,8 +565,6 @@ void ShowNewGRFTextfileWindow(TextfileType file_type, const GRFConfig *c)
new NewGRFTextfileWindow(file_type, c); new NewGRFTextfileWindow(file_type, c);
} }
static GRFPresetList _grf_preset_list; ///< List of known NewGRF presets. @see GetGRFPresetList
typedef std::map<uint32, const GRFConfig *> GrfIdMap; ///< Map of grfid to the grf config. typedef std::map<uint32, const GRFConfig *> GrfIdMap; ///< Map of grfid to the grf config.
/** /**
@@ -606,6 +604,8 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
StringFilter string_filter; ///< Filter for available grf. StringFilter string_filter; ///< Filter for available grf.
QueryString filter_editbox; ///< Filter editbox; QueryString filter_editbox; ///< Filter editbox;
StringList grf_presets; ///< List of known NewGRF presets.
GRFConfig *actives; ///< Temporary active grf list to which changes are made. GRFConfig *actives; ///< Temporary active grf list to which changes are made.
GRFConfig *active_sel; ///< Selected active grf item. GRFConfig *active_sel; ///< Selected active grf item.
@@ -633,7 +633,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
this->active_over = -1; this->active_over = -1;
CopyGRFConfigList(&this->actives, *orig_list, false); CopyGRFConfigList(&this->actives, *orig_list, false);
GetGRFPresetList(&_grf_preset_list); this->grf_presets = GetGRFPresetList();
this->CreateNestedTree(); this->CreateNestedTree();
this->vscroll = this->GetScrollbar(WID_NS_SCROLLBAR); this->vscroll = this->GetScrollbar(WID_NS_SCROLLBAR);
@@ -675,7 +675,6 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
/* Remove the temporary copy of grf-list used in window */ /* Remove the temporary copy of grf-list used in window */
ClearGRFConfigList(&this->actives); ClearGRFConfigList(&this->actives);
_grf_preset_list.Clear();
} }
/** /**
@@ -749,12 +748,10 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
case WID_NS_PRESET_LIST: { case WID_NS_PRESET_LIST: {
Dimension d = GetStringBoundingBox(STR_NUM_CUSTOM); Dimension d = GetStringBoundingBox(STR_NUM_CUSTOM);
for (uint i = 0; i < _grf_preset_list.size(); i++) { for (const auto &i : this->grf_presets) {
if (_grf_preset_list[i] != NULL) { SetDParamStr(0, i.c_str());
SetDParamStr(0, _grf_preset_list[i]);
d = maxdim(d, GetStringBoundingBox(STR_JUST_RAW_STRING)); d = maxdim(d, GetStringBoundingBox(STR_JUST_RAW_STRING));
} }
}
d.width += padding.width; d.width += padding.width;
*size = maxdim(d, *size); *size = maxdim(d, *size);
break; break;
@@ -785,7 +782,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
SetDParam(0, STR_NUM_CUSTOM); SetDParam(0, STR_NUM_CUSTOM);
} else { } else {
SetDParam(0, STR_JUST_RAW_STRING); SetDParam(0, STR_JUST_RAW_STRING);
SetDParamStr(1, _grf_preset_list[this->preset]); SetDParamStr(1, this->grf_presets[this->preset].c_str());
} }
break; break;
} }
@@ -926,19 +923,17 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
switch (widget) { switch (widget) {
case WID_NS_PRESET_LIST: { case WID_NS_PRESET_LIST: {
DropDownList *list = new DropDownList(); DropDownList list;
/* Add 'None' option for clearing list */ /* Add 'None' option for clearing list */
list->push_back(new DropDownListStringItem(STR_NONE, -1, false)); list.emplace_back(new DropDownListStringItem(STR_NONE, -1, false));
for (uint i = 0; i < _grf_preset_list.size(); i++) { for (uint i = 0; i < this->grf_presets.size(); i++) {
if (_grf_preset_list[i] != NULL) { list.emplace_back(new DropDownListCharStringItem(this->grf_presets[i].c_str(), i, false));
list->push_back(new DropDownListCharStringItem(_grf_preset_list[i], i, false));
}
} }
this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window
ShowDropDownList(this, list, this->preset, WID_NS_PRESET_LIST); ShowDropDownList(this, std::move(list), this->preset, WID_NS_PRESET_LIST);
break; break;
} }
@@ -951,14 +946,14 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
} }
case WID_NS_PRESET_SAVE: case WID_NS_PRESET_SAVE:
ShowSavePresetWindow((this->preset == -1) ? NULL : _grf_preset_list[this->preset]); ShowSavePresetWindow((this->preset == -1) ? NULL : this->grf_presets[this->preset].c_str());
break; break;
case WID_NS_PRESET_DELETE: case WID_NS_PRESET_DELETE:
if (this->preset == -1) return; if (this->preset == -1) return;
DeleteGRFPresetFromConfig(_grf_preset_list[this->preset]); DeleteGRFPresetFromConfig(this->grf_presets[this->preset].c_str());
GetGRFPresetList(&_grf_preset_list); this->grf_presets = GetGRFPresetList();
this->preset = -1; this->preset = -1;
this->InvalidateData(); this->InvalidateData();
this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window
@@ -1159,7 +1154,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
this->preset = index; this->preset = index;
if (index != -1) { if (index != -1) {
this->actives = LoadGRFPresetFromConfig(_grf_preset_list[index]); this->actives = LoadGRFPresetFromConfig(this->grf_presets[index].c_str());
} }
this->avails.ForceRebuild(); this->avails.ForceRebuild();
@@ -1175,11 +1170,11 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
if (str == NULL) return; if (str == NULL) return;
SaveGRFPresetToConfig(str, this->actives); SaveGRFPresetToConfig(str, this->actives);
GetGRFPresetList(&_grf_preset_list); this->grf_presets = GetGRFPresetList();
/* Switch to this preset */ /* Switch to this preset */
for (uint i = 0; i < _grf_preset_list.size(); i++) { for (uint i = 0; i < this->grf_presets.size(); i++) {
if (_grf_preset_list[i] != NULL && strcmp(_grf_preset_list[i], str) == 0) { if (this->grf_presets[i] == str) {
this->preset = i; this->preset = i;
break; break;
} }
@@ -2048,7 +2043,7 @@ static WindowDesc _save_preset_desc(
/** Class for the save preset window. */ /** Class for the save preset window. */
struct SavePresetWindow : public Window { struct SavePresetWindow : public Window {
QueryString presetname_editbox; ///< Edit box of the save preset. QueryString presetname_editbox; ///< Edit box of the save preset.
GRFPresetList presets; ///< Available presets. StringList presets; ///< Available presets.
Scrollbar *vscroll; ///< Pointer to the scrollbar widget. Scrollbar *vscroll; ///< Pointer to the scrollbar widget.
int selected; ///< Selected entry in the preset list, or \c -1 if none selected. int selected; ///< Selected entry in the preset list, or \c -1 if none selected.
@@ -2058,11 +2053,11 @@ struct SavePresetWindow : public Window {
*/ */
SavePresetWindow(const char *initial_text) : Window(&_save_preset_desc), presetname_editbox(32) SavePresetWindow(const char *initial_text) : Window(&_save_preset_desc), presetname_editbox(32)
{ {
GetGRFPresetList(&this->presets); this->presets = GetGRFPresetList();
this->selected = -1; this->selected = -1;
if (initial_text != NULL) { if (initial_text != NULL) {
for (uint i = 0; i < this->presets.size(); i++) { for (uint i = 0; i < this->presets.size(); i++) {
if (!strcmp(initial_text, this->presets[i])) { if (this->presets[i] == initial_text) {
this->selected = i; this->selected = i;
break; break;
} }
@@ -2093,7 +2088,7 @@ struct SavePresetWindow : public Window {
resize->height = FONT_HEIGHT_NORMAL + 2U; resize->height = FONT_HEIGHT_NORMAL + 2U;
size->height = 0; size->height = 0;
for (uint i = 0; i < this->presets.size(); i++) { for (uint i = 0; i < this->presets.size(); i++) {
Dimension d = GetStringBoundingBox(this->presets[i]); Dimension d = GetStringBoundingBox(this->presets[i].c_str());
size->width = max(size->width, d.width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT); size->width = max(size->width, d.width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
resize->height = max(resize->height, d.height); resize->height = max(resize->height, d.height);
} }
@@ -2118,7 +2113,7 @@ struct SavePresetWindow : public Window {
for (uint i = min_index; i < max_index; i++) { for (uint i = min_index; i < max_index; i++) {
if ((int)i == this->selected) GfxFillRect(r.left + 1, y, r.right - 1, y + step_height - 2, PC_DARK_BLUE); if ((int)i == this->selected) GfxFillRect(r.left + 1, y, r.right - 1, y + step_height - 2, PC_DARK_BLUE);
const char *text = this->presets[i]; const char *text = this->presets[i].c_str();
DrawString(r.left + WD_FRAMERECT_LEFT, r.right, y + offset_y, text, ((int)i == this->selected) ? TC_WHITE : TC_SILVER); DrawString(r.left + WD_FRAMERECT_LEFT, r.right, y + offset_y, text, ((int)i == this->selected) ? TC_WHITE : TC_SILVER);
y += step_height; y += step_height;
} }
@@ -2134,7 +2129,7 @@ struct SavePresetWindow : public Window {
uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SVP_PRESET_LIST); uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SVP_PRESET_LIST);
if (row < this->presets.size()) { if (row < this->presets.size()) {
this->selected = row; this->selected = row;
this->presetname_editbox.text.Assign(this->presets[row]); this->presetname_editbox.text.Assign(this->presets[row].c_str());
this->SetWidgetDirty(WID_SVP_PRESET_LIST); this->SetWidgetDirty(WID_SVP_PRESET_LIST);
this->SetWidgetDirty(WID_SVP_EDITBOX); this->SetWidgetDirty(WID_SVP_EDITBOX);
} }

View File

@@ -509,8 +509,8 @@ struct AfterNewGRFScan : NewGRFScanCallback {
if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed; if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
if (dedicated_host != NULL) { if (dedicated_host != NULL) {
_network_bind_list.Clear(); _network_bind_list.clear();
_network_bind_list.push_back(stredup(dedicated_host)); _network_bind_list.emplace_back(dedicated_host);
} }
if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port; if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;

View File

@@ -64,7 +64,7 @@ static const StringID _cargo_type_unload_order_drowdown[] = {
}; };
static const uint32 _cargo_type_unload_order_drowdown_hidden_mask = 0x8; // 01000 static const uint32 _cargo_type_unload_order_drowdown_hidden_mask = 0x8; // 01000
DropDownList* GetSlotDropDownList(Owner owner, TraceRestrictSlotID slot_id, int &selected); DropDownList GetSlotDropDownList(Owner owner, TraceRestrictSlotID slot_id, int &selected);
struct CargoTypeOrdersWindow : public Window { struct CargoTypeOrdersWindow : public Window {
private: private:
@@ -2064,8 +2064,8 @@ public:
case WID_O_COND_SLOT: { case WID_O_COND_SLOT: {
int selected; int selected;
TraceRestrictSlotID value = this->vehicle->GetOrder(this->OrderGetSel())->GetXData(); TraceRestrictSlotID value = this->vehicle->GetOrder(this->OrderGetSel())->GetXData();
DropDownList *list = GetSlotDropDownList(this->vehicle->owner, value, selected); DropDownList list = GetSlotDropDownList(this->vehicle->owner, value, selected);
if (list != nullptr) ShowDropDownList(this, list, selected, WID_O_COND_SLOT, 0, true); if (!list.empty()) ShowDropDownList(this, std::move(list), selected, WID_O_COND_SLOT, 0, true);
break; break;
} }
@@ -2082,16 +2082,12 @@ public:
case WID_O_COND_CARGO: { case WID_O_COND_CARGO: {
uint value = this->vehicle->GetOrder(this->OrderGetSel())->GetConditionValue(); uint value = this->vehicle->GetOrder(this->OrderGetSel())->GetConditionValue();
DropDownList *list = new DropDownList(); DropDownList list;
for (size_t i = 0; i < _sorted_standard_cargo_specs_size; ++i) { for (size_t i = 0; i < _sorted_standard_cargo_specs_size; ++i) {
const CargoSpec *cs = _sorted_cargo_specs[i]; const CargoSpec *cs = _sorted_cargo_specs[i];
list->push_back(new DropDownListStringItem(cs->name, cs->Index(), false)); list.emplace_back(new DropDownListStringItem(cs->name, cs->Index(), false));
} }
if (list->size() == 0) { if (!list.empty()) ShowDropDownList(this, std::move(list), value, WID_O_COND_CARGO, 0);
delete list;
return;
}
ShowDropDownList(this, list, value, WID_O_COND_CARGO, 0);
break; break;
} }
@@ -2100,11 +2096,11 @@ public:
break; break;
case WID_O_COND_VARIABLE: { case WID_O_COND_VARIABLE: {
DropDownList *list = new DropDownList(); DropDownList list;
for (uint i = 0; i < lengthof(_order_conditional_variable); i++) { for (uint i = 0; i < lengthof(_order_conditional_variable); i++) {
list->push_back(new DropDownListStringItem(STR_ORDER_CONDITIONAL_LOAD_PERCENTAGE + _order_conditional_variable[i], _order_conditional_variable[i], false)); list.emplace_back(new DropDownListStringItem(STR_ORDER_CONDITIONAL_LOAD_PERCENTAGE + _order_conditional_variable[i], _order_conditional_variable[i], false));
} }
ShowDropDownList(this, list, this->vehicle->GetOrder(this->OrderGetSel())->GetConditionVariable(), WID_O_COND_VARIABLE); ShowDropDownList(this, std::move(list), this->vehicle->GetOrder(this->OrderGetSel())->GetConditionVariable(), WID_O_COND_VARIABLE);
break; break;
} }

View File

@@ -53,19 +53,20 @@ public:
public: public:
CoreTextVisualRun(CTRunRef run, Font *font, const CoreTextParagraphLayoutFactory::CharType *buff); CoreTextVisualRun(CTRunRef run, Font *font, const CoreTextParagraphLayoutFactory::CharType *buff);
CoreTextVisualRun(CoreTextVisualRun &&other) = default;
virtual const GlyphID *GetGlyphs() const { return &this->glyphs[0]; } const GlyphID *GetGlyphs() const override { return &this->glyphs[0]; }
virtual const float *GetPositions() const { return &this->positions[0]; } const float *GetPositions() const override { return &this->positions[0]; }
virtual const int *GetGlyphToCharMap() const { return &this->glyph_to_char[0]; } const int *GetGlyphToCharMap() const override { return &this->glyph_to_char[0]; }
virtual const Font *GetFont() const { return this->font; } const Font *GetFont() const override { return this->font; }
virtual int GetLeading() const { return this->font->fc->GetHeight(); } int GetLeading() const override { return this->font->fc->GetHeight(); }
virtual int GetGlyphCount() const { return (int)this->glyphs.size(); } int GetGlyphCount() const override { return (int)this->glyphs.size(); }
int GetAdvance() const { return this->total_advance; } int GetAdvance() const { return this->total_advance; }
}; };
/** A single line worth of VisualRuns. */ /** A single line worth of VisualRuns. */
class CoreTextLine : public AutoDeleteSmallVector<CoreTextVisualRun *>, public ParagraphLayouter::Line { class CoreTextLine : public std::vector<CoreTextVisualRun>, public ParagraphLayouter::Line {
public: public:
CoreTextLine(CTLineRef line, const FontMap &fontMapping, const CoreTextParagraphLayoutFactory::CharType *buff) CoreTextLine(CTLineRef line, const FontMap &fontMapping, const CoreTextParagraphLayoutFactory::CharType *buff)
{ {
@@ -78,17 +79,17 @@ public:
auto map = fontMapping.begin(); auto map = fontMapping.begin();
while (map < fontMapping.end() - 1 && map->first <= chars.location) map++; while (map < fontMapping.end() - 1 && map->first <= chars.location) map++;
this->push_back(new CoreTextVisualRun(run, map->second, buff)); this->emplace_back(run, map->second, buff);
} }
CFRelease(line); CFRelease(line);
} }
virtual int GetLeading() const; int GetLeading() const override;
virtual int GetWidth() const; int GetWidth() const override;
virtual int CountRuns() const { return this->size(); } int CountRuns() const override { return this->size(); }
virtual const VisualRun *GetVisualRun(int run) const { return this->at(run); } const VisualRun &GetVisualRun(int run) const override { return this->at(run); }
int GetInternalCharLength(WChar c) const int GetInternalCharLength(WChar c) const override
{ {
/* CoreText uses UTF-16 internally which means we need to account for surrogate pairs. */ /* CoreText uses UTF-16 internally which means we need to account for surrogate pairs. */
return c >= 0x010000U ? 2 : 1; return c >= 0x010000U ? 2 : 1;
@@ -100,17 +101,17 @@ public:
this->Reflow(); this->Reflow();
} }
virtual ~CoreTextParagraphLayout() ~CoreTextParagraphLayout() override
{ {
CFRelease(this->typesetter); CFRelease(this->typesetter);
} }
virtual void Reflow() void Reflow() override
{ {
this->cur_offset = 0; this->cur_offset = 0;
} }
virtual const Line *NextLine(int max_width); std::unique_ptr<const Line> NextLine(int max_width) override;
}; };
@@ -187,7 +188,7 @@ static CTRunDelegateCallbacks _sprite_font_callback = {
return typesetter != NULL ? new CoreTextParagraphLayout(typesetter, buff, length, fontMapping) : NULL; return typesetter != NULL ? new CoreTextParagraphLayout(typesetter, buff, length, fontMapping) : NULL;
} }
/* virtual */ const CoreTextParagraphLayout::Line *CoreTextParagraphLayout::NextLine(int max_width) /* virtual */ std::unique_ptr<const ParagraphLayouter::Line> CoreTextParagraphLayout::NextLine(int max_width)
{ {
if (this->cur_offset >= this->length) return NULL; if (this->cur_offset >= this->length) return NULL;
@@ -199,7 +200,7 @@ static CTRunDelegateCallbacks _sprite_font_callback = {
CTLineRef line = CTTypesetterCreateLine(this->typesetter, CFRangeMake(this->cur_offset, len)); CTLineRef line = CTTypesetterCreateLine(this->typesetter, CFRangeMake(this->cur_offset, len));
this->cur_offset += len; this->cur_offset += len;
return line != NULL ? new CoreTextLine(line, this->font_map, this->text_buffer) : NULL; return std::unique_ptr<const Line>(line != NULL ? new CoreTextLine(line, this->font_map, this->text_buffer) : NULL);
} }
CoreTextParagraphLayout::CoreTextVisualRun::CoreTextVisualRun(CTRunRef run, Font *font, const CoreTextParagraphLayoutFactory::CharType *buff) : font(font) CoreTextParagraphLayout::CoreTextVisualRun::CoreTextVisualRun(CTRunRef run, Font *font, const CoreTextParagraphLayoutFactory::CharType *buff) : font(font)
@@ -243,8 +244,8 @@ CoreTextParagraphLayout::CoreTextVisualRun::CoreTextVisualRun(CTRunRef run, Font
int CoreTextParagraphLayout::CoreTextLine::GetLeading() const int CoreTextParagraphLayout::CoreTextLine::GetLeading() const
{ {
int leading = 0; int leading = 0;
for (const CoreTextVisualRun * const &run : *this) { for (const auto &run : *this) {
leading = max(leading, run->GetLeading()); leading = max(leading, run.GetLeading());
} }
return leading; return leading;
@@ -259,8 +260,8 @@ int CoreTextParagraphLayout::CoreTextLine::GetWidth() const
if (this->size() == 0) return 0; if (this->size() == 0) return 0;
int total_width = 0; int total_width = 0;
for (const CoreTextVisualRun * const &run : *this) { for (const auto &run : *this) {
total_width += run->GetAdvance(); total_width += run.GetAdvance();
} }
return total_width; return total_width;

View File

@@ -30,10 +30,10 @@ class OSXStringIterator : public StringIterator {
size_t cur_pos; ///< Current iteration position. size_t cur_pos; ///< Current iteration position.
public: public:
virtual void SetString(const char *s); void SetString(const char *s) override;
virtual size_t SetCurPosition(size_t pos); size_t SetCurPosition(size_t pos) override;
virtual size_t Next(IterType what); size_t Next(IterType what) override;
virtual size_t Prev(IterType what); size_t Prev(IterType what) override;
static StringIterator *Create(); static StringIterator *Create();
}; };

View File

@@ -90,30 +90,31 @@ public:
public: public:
UniscribeVisualRun(const UniscribeRun &range, int x); UniscribeVisualRun(const UniscribeRun &range, int x);
virtual ~UniscribeVisualRun() UniscribeVisualRun(UniscribeVisualRun &&other) noexcept;
~UniscribeVisualRun() override
{ {
free(this->glyph_to_char); free(this->glyph_to_char);
} }
virtual const GlyphID *GetGlyphs() const { return &this->glyphs[0]; } const GlyphID *GetGlyphs() const override { return &this->glyphs[0]; }
virtual const float *GetPositions() const { return &this->positions[0]; } const float *GetPositions() const override { return &this->positions[0]; }
virtual const int *GetGlyphToCharMap() const; const int *GetGlyphToCharMap() const override;
virtual const Font *GetFont() const { return this->font; } const Font *GetFont() const override { return this->font; }
virtual int GetLeading() const { return this->font->fc->GetHeight(); } int GetLeading() const override { return this->font->fc->GetHeight(); }
virtual int GetGlyphCount() const { return this->num_glyphs; } int GetGlyphCount() const override { return this->num_glyphs; }
int GetAdvance() const { return this->total_advance; } int GetAdvance() const { return this->total_advance; }
}; };
/** A single line worth of VisualRuns. */ /** A single line worth of VisualRuns. */
class UniscribeLine : public AutoDeleteSmallVector<UniscribeVisualRun *>, public ParagraphLayouter::Line { class UniscribeLine : public std::vector<UniscribeVisualRun>, public ParagraphLayouter::Line {
public: public:
virtual int GetLeading() const; int GetLeading() const override;
virtual int GetWidth() const; int GetWidth() const override;
virtual int CountRuns() const { return (uint)this->size(); } int CountRuns() const override { return (uint)this->size(); }
virtual const VisualRun *GetVisualRun(int run) const { return this->at(run); } const VisualRun &GetVisualRun(int run) const override { return this->at(run); }
int GetInternalCharLength(WChar c) const int GetInternalCharLength(WChar c) const override
{ {
/* Uniscribe uses UTF-16 internally which means we need to account for surrogate pairs. */ /* Uniscribe uses UTF-16 internally which means we need to account for surrogate pairs. */
return c >= 0x010000U ? 2 : 1; return c >= 0x010000U ? 2 : 1;
@@ -125,15 +126,15 @@ public:
this->Reflow(); this->Reflow();
} }
virtual ~UniscribeParagraphLayout() {} ~UniscribeParagraphLayout() override {}
virtual void Reflow() void Reflow() override
{ {
this->cur_range = this->ranges.begin(); this->cur_range = this->ranges.begin();
this->cur_range_offset = 0; this->cur_range_offset = 0;
} }
virtual const Line *NextLine(int max_width); std::unique_ptr<const Line> NextLine(int max_width) override;
}; };
void UniscribeResetScriptCache(FontSize size) void UniscribeResetScriptCache(FontSize size)
@@ -317,7 +318,7 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
return new UniscribeParagraphLayout(ranges, buff); return new UniscribeParagraphLayout(ranges, buff);
} }
/* virtual */ const ParagraphLayouter::Line *UniscribeParagraphLayout::NextLine(int max_width) /* virtual */ std::unique_ptr<const ParagraphLayouter::Line> UniscribeParagraphLayout::NextLine(int max_width)
{ {
std::vector<UniscribeRun>::iterator start_run = this->cur_range; std::vector<UniscribeRun>::iterator start_run = this->cur_range;
std::vector<UniscribeRun>::iterator last_run = this->cur_range; std::vector<UniscribeRun>::iterator last_run = this->cur_range;
@@ -403,7 +404,7 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
if (FAILED(ScriptLayout((int)bidi_level.size(), &bidi_level[0], &vis_to_log[0], NULL))) return NULL; if (FAILED(ScriptLayout((int)bidi_level.size(), &bidi_level[0], &vis_to_log[0], NULL))) return NULL;
/* Create line. */ /* Create line. */
UniscribeLine *line = new UniscribeLine(); std::unique_ptr<UniscribeLine> line(new UniscribeLine());
int cur_pos = 0; int cur_pos = 0;
for (std::vector<INT>::iterator l = vis_to_log.begin(); l != vis_to_log.end(); l++) { for (std::vector<INT>::iterator l = vis_to_log.begin(); l != vis_to_log.end(); l++) {
@@ -424,7 +425,7 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
if (!UniscribeShapeRun(this->text_buffer, run)) return NULL; if (!UniscribeShapeRun(this->text_buffer, run)) return NULL;
} }
line->push_back(new UniscribeVisualRun(run, cur_pos)); line->emplace_back(run, cur_pos);
cur_pos += run.total_advance; cur_pos += run.total_advance;
} }
@@ -448,8 +449,8 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
int UniscribeParagraphLayout::UniscribeLine::GetLeading() const int UniscribeParagraphLayout::UniscribeLine::GetLeading() const
{ {
int leading = 0; int leading = 0;
for (const UniscribeVisualRun *run : *this) { for (const auto &run : *this) {
leading = max(leading, run->GetLeading()); leading = max(leading, run.GetLeading());
} }
return leading; return leading;
@@ -462,8 +463,8 @@ int UniscribeParagraphLayout::UniscribeLine::GetLeading() const
int UniscribeParagraphLayout::UniscribeLine::GetWidth() const int UniscribeParagraphLayout::UniscribeLine::GetWidth() const
{ {
int length = 0; int length = 0;
for (const UniscribeVisualRun *run : *this) { for (const auto &run : *this) {
length += run->GetAdvance(); length += run.GetAdvance();
} }
return length; return length;
@@ -484,6 +485,14 @@ UniscribeParagraphLayout::UniscribeVisualRun::UniscribeVisualRun(const Uniscribe
this->positions[this->num_glyphs * 2] = advance + x; this->positions[this->num_glyphs * 2] = advance + x;
} }
UniscribeParagraphLayout::UniscribeVisualRun::UniscribeVisualRun(UniscribeVisualRun&& other) noexcept
: glyphs(std::move(other.glyphs)), positions(std::move(other.positions)), char_to_glyph(std::move(other.char_to_glyph)),
start_pos(other.start_pos), total_advance(other.total_advance), num_glyphs(other.num_glyphs), font(other.font)
{
this->glyph_to_char = other.glyph_to_char;
other.glyph_to_char = NULL;
}
const int *UniscribeParagraphLayout::UniscribeVisualRun::GetGlyphToCharMap() const const int *UniscribeParagraphLayout::UniscribeVisualRun::GetGlyphToCharMap() const
{ {
if (this->glyph_to_char == NULL) { if (this->glyph_to_char == NULL) {

View File

@@ -81,10 +81,10 @@ class UniscribeStringIterator : public StringIterator {
size_t cur_pos; ///< Current iteration position. size_t cur_pos; ///< Current iteration position.
public: public:
virtual void SetString(const char *s); void SetString(const char *s) override;
virtual size_t SetCurPosition(size_t pos); size_t SetCurPosition(size_t pos) override;
virtual size_t Next(IterType what); size_t Next(IterType what) override;
virtual size_t Prev(IterType what); size_t Prev(IterType what) override;
}; };
#endif /* defined(WITH_UNISCRIBE) */ #endif /* defined(WITH_UNISCRIBE) */

View File

@@ -2180,7 +2180,7 @@ void InitializeRailGUI()
* @param all_option Whether to add an 'all types' item. * @param all_option Whether to add an 'all types' item.
* @return The populated and sorted #DropDownList. * @return The populated and sorted #DropDownList.
*/ */
DropDownList *GetRailTypeDropDownList(bool for_replacement, bool all_option) DropDownList GetRailTypeDropDownList(bool for_replacement, bool all_option)
{ {
RailTypes used_railtypes; RailTypes used_railtypes;
RailTypes avail_railtypes; RailTypes avail_railtypes;
@@ -2196,11 +2196,10 @@ DropDownList *GetRailTypeDropDownList(bool for_replacement, bool all_option)
used_railtypes = GetRailTypes(true); used_railtypes = GetRailTypes(true);
} }
DropDownList *list = new DropDownList(); DropDownList list;
if (all_option) { if (all_option) {
DropDownListStringItem *item = new DropDownListStringItem(STR_REPLACE_ALL_RAILTYPE, INVALID_RAILTYPE, false); list.emplace_back(new DropDownListStringItem(STR_REPLACE_ALL_RAILTYPE, INVALID_RAILTYPE, false));
list->push_back(item);
} }
Dimension d = { 0, 0 }; Dimension d = { 0, 0 };
@@ -2231,7 +2230,7 @@ DropDownList *GetRailTypeDropDownList(bool for_replacement, bool all_option)
} }
item->SetParam(0, rti->strings.menu_text); item->SetParam(0, rti->strings.menu_text);
item->SetParam(1, rti->max_speed); item->SetParam(1, rti->max_speed);
list->push_back(item); list.emplace_back(item);
} }
return list; return list;
} }

View File

@@ -19,6 +19,6 @@ struct Window *ShowBuildRailToolbar(RailType railtype);
void ReinitGuiAfterToggleElrail(bool disable); void ReinitGuiAfterToggleElrail(bool disable);
bool ResetSignalVariant(int32 = 0); bool ResetSignalVariant(int32 = 0);
void InitializeRailGUI(); void InitializeRailGUI();
DropDownList *GetRailTypeDropDownList(bool for_replacement = false, bool all_option = false); DropDownList GetRailTypeDropDownList(bool for_replacement = false, bool all_option = false);
#endif /* RAIL_GUI_H */ #endif /* RAIL_GUI_H */

View File

@@ -129,14 +129,14 @@ static const SaveLoad _game_language_string[] = {
SLE_END() SLE_END()
}; };
static void SaveReal_GSTR(LanguageStrings *ls) static void SaveReal_GSTR(const LanguageStrings *ls)
{ {
_game_saveload_string = ls->language; _game_saveload_string = ls->language;
_game_saveload_strings = (uint)ls->lines.size(); _game_saveload_strings = (uint)ls->lines.size();
SlObject(NULL, _game_language_header); SlObject(NULL, _game_language_header);
for (uint i = 0; i < _game_saveload_strings; i++) { for (const auto &i : ls->lines) {
_game_saveload_string = ls->lines[i]; _game_saveload_string = i.c_str();
SlObject(NULL, _game_language_string); SlObject(NULL, _game_language_string);
} }
} }
@@ -150,13 +150,13 @@ static void Load_GSTR()
_game_saveload_string = NULL; _game_saveload_string = NULL;
SlObject(NULL, _game_language_header); SlObject(NULL, _game_language_header);
LanguageStrings *ls = new LanguageStrings(_game_saveload_string != NULL ? _game_saveload_string : ""); std::unique_ptr<LanguageStrings> ls(new LanguageStrings(_game_saveload_string != NULL ? _game_saveload_string : ""));
for (uint i = 0; i < _game_saveload_strings; i++) { for (uint i = 0; i < _game_saveload_strings; i++) {
SlObject(NULL, _game_language_string); SlObject(NULL, _game_language_string);
ls->lines.push_back(stredup(_game_saveload_string != NULL ? _game_saveload_string : "")); ls->lines.emplace_back(_game_saveload_string != NULL ? _game_saveload_string : "");
} }
_current_data->raw_strings.push_back(ls); _current_data->raw_strings.push_back(std::move(ls));
} }
/* If there were no strings in the savegame, set GameStrings to NULL */ /* If there were no strings in the savegame, set GameStrings to NULL */
@@ -176,7 +176,7 @@ static void Save_GSTR()
for (uint i = 0; i < _current_data->raw_strings.size(); i++) { for (uint i = 0; i < _current_data->raw_strings.size(); i++) {
SlSetArrayIndex(i); SlSetArrayIndex(i);
SlAutolength((AutolengthProc *)SaveReal_GSTR, _current_data->raw_strings[i]); SlAutolength((AutolengthProc *)SaveReal_GSTR, _current_data->raw_strings[i].get());
} }
} }

View File

@@ -91,7 +91,7 @@ static ErrorList _settings_error_list; ///< Errors while loading minimal setting
typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object); typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList *list); typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList &list);
static bool IsSignedVarMemType(VarType vt); static bool IsSignedVarMemType(VarType vt);
@@ -725,16 +725,16 @@ static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grp
* @param grpname character string identifying the section-header of the ini file that will be parsed * @param grpname character string identifying the section-header of the ini file that will be parsed
* @param list new list with entries of the given section * @param list new list with entries of the given section
*/ */
static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *list) static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList &list)
{ {
IniGroup *group = ini->GetGroup(grpname); IniGroup *group = ini->GetGroup(grpname);
if (group == NULL || list == NULL) return; if (group == NULL) return;
list->Clear(); list.clear();
for (const IniItem *item = group->item; item != NULL; item = item->next) { for (const IniItem *item = group->item; item != NULL; item = item->next) {
if (item->name != NULL) list->push_back(stredup(item->name)); if (item->name != NULL) list.emplace_back(item->name);
} }
} }
@@ -747,15 +747,15 @@ static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *li
* @param list pointer to an string(pointer) array that will be used as the * @param list pointer to an string(pointer) array that will be used as the
* source to be saved into the relevant ini section * source to be saved into the relevant ini section
*/ */
static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *list) static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList &list)
{ {
IniGroup *group = ini->GetGroup(grpname); IniGroup *group = ini->GetGroup(grpname);
if (group == NULL || list == NULL) return; if (group == NULL) return;
group->Clear(); group->Clear();
for (char *iter : *list) { for (const auto &iter : list) {
group->GetItem(iter, true)->SetValue(""); group->GetItem(iter.c_str(), true)->SetValue("");
} }
} }
@@ -1828,9 +1828,9 @@ static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescP
proc(ini, _currency_settings,"currency", &_custom_currency); proc(ini, _currency_settings,"currency", &_custom_currency);
proc(ini, _company_settings, "company", &_settings_client.company); proc(ini, _company_settings, "company", &_settings_client.company);
proc_list(ini, "server_bind_addresses", &_network_bind_list); proc_list(ini, "server_bind_addresses", _network_bind_list);
proc_list(ini, "servers", &_network_host_list); proc_list(ini, "servers", _network_host_list);
proc_list(ini, "bans", &_network_ban_list); proc_list(ini, "bans", _network_ban_list);
} }
} }
@@ -1896,21 +1896,20 @@ void SaveToConfig()
/** /**
* Get the list of known NewGrf presets. * Get the list of known NewGrf presets.
* @param[in,out] list Pointer to list for storing the preset names. * @returns List of preset names.
*/ */
void GetGRFPresetList(GRFPresetList *list) StringList GetGRFPresetList()
{ {
list->Clear(); StringList list;
IniFile *ini = IniLoadConfig(); std::unique_ptr<IniFile> ini(IniLoadConfig());
IniGroup *group; for (IniGroup *group = ini->group; group != NULL; group = group->next) {
for (group = ini->group; group != NULL; group = group->next) {
if (strncmp(group->name, "preset-", 7) == 0) { if (strncmp(group->name, "preset-", 7) == 0) {
list->push_back(stredup(group->name + 7)); list.emplace_back(group->name + 7);
} }
} }
delete ini; return list;
} }
/** /**

View File

@@ -14,6 +14,7 @@
#include "core/smallvec_type.hpp" #include "core/smallvec_type.hpp"
#include "company_type.h" #include "company_type.h"
#include "string_type.h"
struct IniFile; struct IniFile;
@@ -28,11 +29,7 @@ void SaveToConfig();
void IniLoadWindowSettings(IniFile *ini, const char *grpname, void *desc); void IniLoadWindowSettings(IniFile *ini, const char *grpname, void *desc);
void IniSaveWindowSettings(IniFile *ini, const char *grpname, void *desc); void IniSaveWindowSettings(IniFile *ini, const char *grpname, void *desc);
/* Functions to load and save NewGRF settings to a separate StringList GetGRFPresetList();
* configuration file, used for presets. */
typedef AutoFreeSmallVector<char *> GRFPresetList;
void GetGRFPresetList(GRFPresetList *list);
struct GRFConfig *LoadGRFPresetFromConfig(const char *config_name); struct GRFConfig *LoadGRFPresetFromConfig(const char *config_name);
void SaveGRFPresetToConfig(const char *config_name, struct GRFConfig *config); void SaveGRFPresetToConfig(const char *config_name, struct GRFConfig *config);
void DeleteGRFPresetFromConfig(const char *config_name); void DeleteGRFPresetFromConfig(const char *config_name);

View File

@@ -122,20 +122,20 @@ static int GetCurRes()
static void ShowCustCurrency(); static void ShowCustCurrency();
template <class T> template <class T>
static DropDownList *BuildSetDropDownList(int *selected_index, bool allow_selection) static DropDownList BuildSetDropDownList(int *selected_index, bool allow_selection)
{ {
int n = T::GetNumSets(); int n = T::GetNumSets();
*selected_index = T::GetIndexOfUsedSet(); *selected_index = T::GetIndexOfUsedSet();
DropDownList *list = new DropDownList(); DropDownList list;
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
list->push_back(new DropDownListCharStringItem(T::GetSet(i)->name, i, !allow_selection && (*selected_index != i))); list.emplace_back(new DropDownListCharStringItem(T::GetSet(i)->name, i, !allow_selection && (*selected_index != i)));
} }
return list; return list;
} }
DropDownList *BuildMusicSetDropDownList(int *selected_index) DropDownList BuildMusicSetDropDownList(int *selected_index)
{ {
return BuildSetDropDownList<BaseMusic>(selected_index, true); return BuildSetDropDownList<BaseMusic>(selected_index, true);
} }
@@ -200,12 +200,11 @@ struct GameOptionsWindow : Window {
* @param selected_index Currently selected item * @param selected_index Currently selected item
* @return the built dropdown list, or NULL if the widget has no dropdown menu. * @return the built dropdown list, or NULL if the widget has no dropdown menu.
*/ */
DropDownList *BuildDropDownList(int widget, int *selected_index) const DropDownList BuildDropDownList(int widget, int *selected_index) const
{ {
DropDownList *list = NULL; DropDownList list;
switch (widget) { switch (widget) {
case WID_GO_CURRENCY_DROPDOWN: { // Setup currencies dropdown case WID_GO_CURRENCY_DROPDOWN: { // Setup currencies dropdown
list = new DropDownList();
*selected_index = this->opt->locale.currency; *selected_index = this->opt->locale.currency;
StringID *items = BuildCurrencyDropdown(); StringID *items = BuildCurrencyDropdown();
uint64 disabled = _game_mode == GM_MENU ? 0LL : ~GetMaskOfAllowedCurrencies(); uint64 disabled = _game_mode == GM_MENU ? 0LL : ~GetMaskOfAllowedCurrencies();
@@ -213,18 +212,17 @@ struct GameOptionsWindow : Window {
/* Add non-custom currencies; sorted naturally */ /* Add non-custom currencies; sorted naturally */
for (uint i = 0; i < CURRENCY_END; items++, i++) { for (uint i = 0; i < CURRENCY_END; items++, i++) {
if (i == CURRENCY_CUSTOM) continue; if (i == CURRENCY_CUSTOM) continue;
list->push_back(new DropDownListStringItem(*items, i, HasBit(disabled, i))); list.emplace_back(new DropDownListStringItem(*items, i, HasBit(disabled, i)));
} }
QSortT(list->data(), list->size(), DropDownListStringItem::NatSortFunc); std::sort(list.begin(), list.end(), DropDownListStringItem::NatSortFunc);
/* Append custom currency at the end */ /* Append custom currency at the end */
list->push_back(new DropDownListItem(-1, false)); // separator line list.emplace_back(new DropDownListItem(-1, false)); // separator line
list->push_back(new DropDownListStringItem(STR_GAME_OPTIONS_CURRENCY_CUSTOM, CURRENCY_CUSTOM, HasBit(disabled, CURRENCY_CUSTOM))); list.emplace_back(new DropDownListStringItem(STR_GAME_OPTIONS_CURRENCY_CUSTOM, CURRENCY_CUSTOM, HasBit(disabled, CURRENCY_CUSTOM)));
break; break;
} }
case WID_GO_ROADSIDE_DROPDOWN: { // Setup road-side dropdown case WID_GO_ROADSIDE_DROPDOWN: { // Setup road-side dropdown
list = new DropDownList();
*selected_index = this->opt->vehicle.road_side; *selected_index = this->opt->vehicle.road_side;
const StringID *items = _driveside_dropdown; const StringID *items = _driveside_dropdown;
uint disabled = 0; uint disabled = 0;
@@ -237,13 +235,12 @@ struct GameOptionsWindow : Window {
} }
for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) { for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
list->push_back(new DropDownListStringItem(*items, i, HasBit(disabled, i))); list.emplace_back(new DropDownListStringItem(*items, i, HasBit(disabled, i)));
} }
break; break;
} }
case WID_GO_TOWNNAME_DROPDOWN: { // Setup townname dropdown case WID_GO_TOWNNAME_DROPDOWN: { // Setup townname dropdown
list = new DropDownList();
*selected_index = this->opt->game_creation.town_name; *selected_index = this->opt->game_creation.town_name;
int enabled_item = (_game_mode == GM_MENU || Town::GetNumItems() == 0) ? -1 : *selected_index; int enabled_item = (_game_mode == GM_MENU || Town::GetNumItems() == 0) ? -1 : *selected_index;
@@ -251,71 +248,66 @@ struct GameOptionsWindow : Window {
/* Add and sort newgrf townnames generators */ /* Add and sort newgrf townnames generators */
for (int i = 0; i < _nb_grf_names; i++) { for (int i = 0; i < _nb_grf_names; i++) {
int result = _nb_orig_names + i; int result = _nb_orig_names + i;
list->push_back(new DropDownListStringItem(_grf_names[i], result, enabled_item != result && enabled_item >= 0)); list.emplace_back(new DropDownListStringItem(_grf_names[i], result, enabled_item != result && enabled_item >= 0));
} }
QSortT(list->data(), list->size(), DropDownListStringItem::NatSortFunc); std::sort(list.begin(), list.end(), DropDownListStringItem::NatSortFunc);
size_t newgrf_size = list->size(); size_t newgrf_size = list.size();
/* Insert newgrf_names at the top of the list */ /* Insert newgrf_names at the top of the list */
if (newgrf_size > 0) { if (newgrf_size > 0) {
list->push_back(new DropDownListItem(-1, false)); // separator line list.emplace_back(new DropDownListItem(-1, false)); // separator line
newgrf_size++; newgrf_size++;
} }
/* Add and sort original townnames generators */ /* Add and sort original townnames generators */
for (int i = 0; i < _nb_orig_names; i++) { for (int i = 0; i < _nb_orig_names; i++) {
list->push_back(new DropDownListStringItem(STR_GAME_OPTIONS_TOWN_NAME_ORIGINAL_ENGLISH + i, i, enabled_item != i && enabled_item >= 0)); list.emplace_back(new DropDownListStringItem(STR_GAME_OPTIONS_TOWN_NAME_ORIGINAL_ENGLISH + i, i, enabled_item != i && enabled_item >= 0));
} }
QSortT(list->data() + newgrf_size, list->size() - newgrf_size, DropDownListStringItem::NatSortFunc); std::sort(list.begin() + newgrf_size, list.end(), DropDownListStringItem::NatSortFunc);
break; break;
} }
case WID_GO_AUTOSAVE_DROPDOWN: { // Setup autosave dropdown case WID_GO_AUTOSAVE_DROPDOWN: { // Setup autosave dropdown
list = new DropDownList();
*selected_index = _settings_client.gui.autosave; *selected_index = _settings_client.gui.autosave;
const StringID *items = _autosave_dropdown; const StringID *items = _autosave_dropdown;
for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) { for (uint i = 0; *items != INVALID_STRING_ID; items++, i++) {
list->push_back(new DropDownListStringItem(*items, i, false)); list.emplace_back(new DropDownListStringItem(*items, i, false));
} }
break; break;
} }
case WID_GO_LANG_DROPDOWN: { // Setup interface language dropdown case WID_GO_LANG_DROPDOWN: { // Setup interface language dropdown
list = new DropDownList();
for (uint i = 0; i < _languages.size(); i++) { for (uint i = 0; i < _languages.size(); i++) {
if (&_languages[i] == _current_language) *selected_index = i; if (&_languages[i] == _current_language) *selected_index = i;
list->push_back(new DropDownListStringItem(SPECSTR_LANGUAGE_START + i, i, false)); list.emplace_back(new DropDownListStringItem(SPECSTR_LANGUAGE_START + i, i, false));
} }
QSortT(list->data(), list->size(), DropDownListStringItem::NatSortFunc); std::sort(list.begin(), list.end(), DropDownListStringItem::NatSortFunc);
break; break;
} }
case WID_GO_RESOLUTION_DROPDOWN: // Setup resolution dropdown case WID_GO_RESOLUTION_DROPDOWN: // Setup resolution dropdown
if (_num_resolutions == 0) break; if (_num_resolutions == 0) break;
list = new DropDownList();
*selected_index = GetCurRes(); *selected_index = GetCurRes();
for (int i = 0; i < _num_resolutions; i++) { for (int i = 0; i < _num_resolutions; i++) {
list->push_back(new DropDownListStringItem(SPECSTR_RESOLUTION_START + i, i, false)); list.emplace_back(new DropDownListStringItem(SPECSTR_RESOLUTION_START + i, i, false));
} }
break; break;
case WID_GO_GUI_ZOOM_DROPDOWN: { case WID_GO_GUI_ZOOM_DROPDOWN: {
list = new DropDownList();
*selected_index = ZOOM_LVL_OUT_4X - _gui_zoom; *selected_index = ZOOM_LVL_OUT_4X - _gui_zoom;
const StringID *items = _gui_zoom_dropdown; const StringID *items = _gui_zoom_dropdown;
for (int i = 0; *items != INVALID_STRING_ID; items++, i++) { for (int i = 0; *items != INVALID_STRING_ID; items++, i++) {
list->push_back(new DropDownListStringItem(*items, i, _settings_client.gui.zoom_min > ZOOM_LVL_OUT_4X - i)); list.emplace_back(new DropDownListStringItem(*items, i, _settings_client.gui.zoom_min > ZOOM_LVL_OUT_4X - i));
} }
break; break;
} }
case WID_GO_FONT_ZOOM_DROPDOWN: { case WID_GO_FONT_ZOOM_DROPDOWN: {
list = new DropDownList();
*selected_index = ZOOM_LVL_OUT_4X - _font_zoom; *selected_index = ZOOM_LVL_OUT_4X - _font_zoom;
const StringID *items = _font_zoom_dropdown; const StringID *items = _font_zoom_dropdown;
for (int i = 0; *items != INVALID_STRING_ID; items++, i++) { for (int i = 0; *items != INVALID_STRING_ID; items++, i++) {
list->push_back(new DropDownListStringItem(*items, i, false)); list.emplace_back(new DropDownListStringItem(*items, i, false));
} }
break; break;
} }
@@ -331,9 +323,6 @@ struct GameOptionsWindow : Window {
case WID_GO_BASE_MUSIC_DROPDOWN: case WID_GO_BASE_MUSIC_DROPDOWN:
list = BuildMusicSetDropDownList(selected_index); list = BuildMusicSetDropDownList(selected_index);
break; break;
default:
return NULL;
} }
return list; return list;
@@ -429,17 +418,16 @@ struct GameOptionsWindow : Window {
default: { default: {
int selected; int selected;
DropDownList *list = this->BuildDropDownList(widget, &selected); DropDownList list = this->BuildDropDownList(widget, &selected);
if (list != NULL) { if (!list.empty()) {
/* Find the biggest item for the default size. */ /* Find the biggest item for the default size. */
for (const DropDownListItem * const ddli : *list) { for (const auto &ddli : list) {
Dimension string_dim; Dimension string_dim;
int width = ddli->Width(); int width = ddli->Width();
string_dim.width = width + padding.width; string_dim.width = width + padding.width;
string_dim.height = ddli->Height(width) + padding.height; string_dim.height = ddli->Height(width) + padding.height;
*size = maxdim(*size, string_dim); *size = maxdim(*size, string_dim);
} }
delete list;
} }
} }
} }
@@ -477,9 +465,9 @@ struct GameOptionsWindow : Window {
default: { default: {
int selected; int selected;
DropDownList *list = this->BuildDropDownList(widget, &selected); DropDownList list = this->BuildDropDownList(widget, &selected);
if (list != NULL) { if (!list.empty()) {
ShowDropDownList(this, list, selected, widget); ShowDropDownList(this, std::move(list), selected, widget);
} else { } else {
if (widget == WID_GO_RESOLUTION_DROPDOWN) ShowErrorMessage(STR_ERROR_RESOLUTION_LIST_FAILED, INVALID_STRING_ID, WL_ERROR); if (widget == WID_GO_RESOLUTION_DROPDOWN) ShowErrorMessage(STR_ERROR_RESOLUTION_LIST_FAILED, INVALID_STRING_ID, WL_ERROR);
} }
@@ -2078,28 +2066,25 @@ struct GameSettingsWindow : Window {
} }
} }
DropDownList *BuildDropDownList(int widget) const DropDownList BuildDropDownList(int widget) const
{ {
DropDownList *list = NULL; DropDownList list;
switch (widget) { switch (widget) {
case WID_GS_RESTRICT_DROPDOWN: case WID_GS_RESTRICT_DROPDOWN:
list = new DropDownList();
for (int mode = 0; mode != RM_END; mode++) { for (int mode = 0; mode != RM_END; mode++) {
/* If we are in adv. settings screen for the new game's settings, /* If we are in adv. settings screen for the new game's settings,
* we don't want to allow comparing with new game's settings. */ * we don't want to allow comparing with new game's settings. */
bool disabled = mode == RM_CHANGED_AGAINST_NEW && settings_ptr == &_settings_newgame; bool disabled = mode == RM_CHANGED_AGAINST_NEW && settings_ptr == &_settings_newgame;
list->push_back(new DropDownListStringItem(_game_settings_restrict_dropdown[mode], mode, disabled)); list.emplace_back(new DropDownListStringItem(_game_settings_restrict_dropdown[mode], mode, disabled));
} }
break; break;
case WID_GS_TYPE_DROPDOWN: case WID_GS_TYPE_DROPDOWN:
list = new DropDownList(); list.emplace_back(new DropDownListStringItem(STR_CONFIG_SETTING_TYPE_DROPDOWN_ALL, ST_ALL, false));
list->push_back(new DropDownListStringItem(STR_CONFIG_SETTING_TYPE_DROPDOWN_ALL, ST_ALL, false)); list.emplace_back(new DropDownListStringItem(_game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_INGAME, ST_GAME, false));
list->push_back(new DropDownListStringItem(_game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_GAME_INGAME, ST_GAME, false)); list.emplace_back(new DropDownListStringItem(_game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_INGAME, ST_COMPANY, false));
list->push_back(new DropDownListStringItem(_game_mode == GM_MENU ? STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_MENU : STR_CONFIG_SETTING_TYPE_DROPDOWN_COMPANY_INGAME, ST_COMPANY, false)); list.emplace_back(new DropDownListStringItem(STR_CONFIG_SETTING_TYPE_DROPDOWN_CLIENT, ST_CLIENT, false));
list->push_back(new DropDownListStringItem(STR_CONFIG_SETTING_TYPE_DROPDOWN_CLIENT, ST_CLIENT, false));
break; break;
} }
return list; return list;
@@ -2171,17 +2156,17 @@ struct GameSettingsWindow : Window {
break; break;
case WID_GS_RESTRICT_DROPDOWN: { case WID_GS_RESTRICT_DROPDOWN: {
DropDownList *list = this->BuildDropDownList(widget); DropDownList list = this->BuildDropDownList(widget);
if (list != NULL) { if (!list.empty()) {
ShowDropDownList(this, list, this->filter.mode, widget); ShowDropDownList(this, std::move(list), this->filter.mode, widget);
} }
break; break;
} }
case WID_GS_TYPE_DROPDOWN: { case WID_GS_TYPE_DROPDOWN: {
DropDownList *list = this->BuildDropDownList(widget); DropDownList list = this->BuildDropDownList(widget);
if (list != NULL) { if (!list.empty()) {
ShowDropDownList(this, list, this->filter.type, widget); ShowDropDownList(this, std::move(list), this->filter.type, widget);
} }
break; break;
} }
@@ -2254,14 +2239,14 @@ struct GameSettingsWindow : Window {
this->valuedropdown_entry = pe; this->valuedropdown_entry = pe;
this->valuedropdown_entry->SetButtons(SEF_LEFT_DEPRESSED); this->valuedropdown_entry->SetButtons(SEF_LEFT_DEPRESSED);
DropDownList *list = new DropDownList(); DropDownList list;
for (int i = sdb->min; i <= (int)sdb->max; i++) { for (int i = sdb->min; i <= (int)sdb->max; i++) {
int val = sd->orderproc ? sd->orderproc(i - sdb->min) : i; int val = sd->orderproc ? sd->orderproc(i - sdb->min) : i;
assert_msg(val >= sdb->min && val <= (int)sdb->max, "min: %d, max: %d, val: %d", sdb->min, sdb->max, val); assert_msg(val >= sdb->min && val <= (int)sdb->max, "min: %d, max: %d, val: %d", sdb->min, sdb->max, val);
list->push_back(new DropDownListStringItem(sdb->str_val + val - sdb->min, val, false)); list.emplace_back(new DropDownListStringItem(sdb->str_val + val - sdb->min, val, false));
} }
ShowDropDownListAt(this, list, value, -1, wi_rect, COLOUR_ORANGE, true); ShowDropDownListAt(this, std::move(list), value, -1, wi_rect, COLOUR_ORANGE, true);
} }
} }
this->SetDirty(); this->SetDirty();

View File

@@ -24,7 +24,7 @@ void DrawArrowButtons(int x, int y, Colours button_colour, byte state, bool clic
void DrawDropDownButton(int x, int y, Colours button_colour, bool state, bool clickable); void DrawDropDownButton(int x, int y, Colours button_colour, bool state, bool clickable);
void DrawBoolButton(int x, int y, bool state, bool clickable); void DrawBoolButton(int x, int y, bool state, bool clickable);
DropDownList *BuildMusicSetDropDownList(int *selected_index); DropDownList BuildMusicSetDropDownList(int *selected_index);
/* Actually implemented in music_gui.cpp */ /* Actually implemented in music_gui.cpp */
void ChangeMusicSet(int index); void ChangeMusicSet(int index);

View File

@@ -83,6 +83,7 @@
#include <cstdlib> #include <cstdlib>
#include <climits> #include <climits>
#include <cassert> #include <cassert>
#include <memory>
#ifndef SIZE_MAX #ifndef SIZE_MAX
#define SIZE_MAX ((size_t)-1) #define SIZE_MAX ((size_t)-1)

View File

@@ -228,9 +228,9 @@ protected:
/** /**
* Builds the page selector drop down list. * Builds the page selector drop down list.
*/ */
DropDownList *BuildDropDownList() const DropDownList BuildDropDownList() const
{ {
DropDownList *list = new DropDownList(); DropDownList list;
uint16 page_num = 1; uint16 page_num = 1;
for (const StoryPage *p : this->story_pages) { for (const StoryPage *p : this->story_pages) {
bool current_page = p->index == this->selected_page_id; bool current_page = p->index == this->selected_page_id;
@@ -245,16 +245,10 @@ protected:
item = str_item; item = str_item;
} }
list->push_back(item); list.emplace_back(item);
page_num++; page_num++;
} }
/* Check if list is empty. */
if (list->size() == 0) {
delete list;
list = NULL;
}
return list; return list;
} }
@@ -611,8 +605,8 @@ public:
{ {
switch (widget) { switch (widget) {
case WID_SB_SEL_PAGE: { case WID_SB_SEL_PAGE: {
DropDownList *list = this->BuildDropDownList(); DropDownList list = this->BuildDropDownList();
if (list != NULL) { if (!list.empty()) {
/* Get the index of selected page. */ /* Get the index of selected page. */
int selected = 0; int selected = 0;
for (uint16 i = 0; i < this->story_pages.size(); i++) { for (uint16 i = 0; i < this->story_pages.size(); i++) {
@@ -621,7 +615,7 @@ public:
selected++; selected++;
} }
ShowDropDownList(this, list, selected, widget); ShowDropDownList(this, std::move(list), selected, widget);
} }
break; break;
} }

View File

@@ -724,13 +724,13 @@ public:
this->utf16_to_utf8.push_back(0); this->utf16_to_utf8.push_back(0);
} }
virtual ~IcuStringIterator() ~IcuStringIterator() override
{ {
delete this->char_itr; delete this->char_itr;
delete this->word_itr; delete this->word_itr;
} }
virtual void SetString(const char *s) void SetString(const char *s) override
{ {
const char *string_base = s; const char *string_base = s;
@@ -767,7 +767,7 @@ public:
this->word_itr->first(); this->word_itr->first();
} }
virtual size_t SetCurPosition(size_t pos) size_t SetCurPosition(size_t pos) override
{ {
/* Convert incoming position to an UTF-16 string index. */ /* Convert incoming position to an UTF-16 string index. */
uint utf16_pos = 0; uint utf16_pos = 0;
@@ -785,7 +785,7 @@ public:
return this->utf16_to_utf8[this->char_itr->current()]; return this->utf16_to_utf8[this->char_itr->current()];
} }
virtual size_t Next(IterType what) size_t Next(IterType what) override
{ {
int32_t pos; int32_t pos;
switch (what) { switch (what) {
@@ -817,7 +817,7 @@ public:
return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos]; return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
} }
virtual size_t Prev(IterType what) size_t Prev(IterType what) override
{ {
int32_t pos; int32_t pos;
switch (what) { switch (what) {

View File

@@ -13,6 +13,8 @@
#define STRING_TYPE_H #define STRING_TYPE_H
#include "core/enum_type.hpp" #include "core/enum_type.hpp"
#include <vector>
#include <string>
/** A non-breaking space. */ /** A non-breaking space. */
#define NBSP "\xC2\xA0" #define NBSP "\xC2\xA0"
@@ -54,4 +56,8 @@ enum StringValidationSettings {
}; };
DECLARE_ENUM_AS_BIT_SET(StringValidationSettings) DECLARE_ENUM_AS_BIT_SET(StringValidationSettings)
/** Type for a list of strings. */
typedef std::vector<std::string> StringList;
#endif /* STRING_TYPE_H */ #endif /* STRING_TYPE_H */

View File

@@ -876,10 +876,10 @@ struct TimetableWindow : Window {
bool leave_type_disabled = (order == NULL) || bool leave_type_disabled = (order == NULL) ||
((!(order->IsType(OT_GOTO_STATION) || (order->IsType(OT_GOTO_DEPOT) && !(order->GetDepotActionType() & ODATFB_HALT))) || ((!(order->IsType(OT_GOTO_STATION) || (order->IsType(OT_GOTO_DEPOT) && !(order->GetDepotActionType() & ODATFB_HALT))) ||
(order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION)) && !order->IsType(OT_CONDITIONAL)); (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION)) && !order->IsType(OT_CONDITIONAL));
DropDownList *list = new DropDownList(); DropDownList list;
list->push_back(new DropDownListStringItem(STR_TIMETABLE_LEAVE_NORMAL, OLT_NORMAL, leave_type_disabled)); list.emplace_back(new DropDownListStringItem(STR_TIMETABLE_LEAVE_NORMAL, OLT_NORMAL, leave_type_disabled));
list->push_back(new DropDownListStringItem(STR_TIMETABLE_LEAVE_EARLY, OLT_LEAVE_EARLY, leave_type_disabled)); list.emplace_back(new DropDownListStringItem(STR_TIMETABLE_LEAVE_EARLY, OLT_LEAVE_EARLY, leave_type_disabled));
ShowDropDownList(this, list, order != NULL ? order->GetLeaveType() : -1, WID_VT_EXTRA); ShowDropDownList(this, std::move(list), order != NULL ? order->GetLeaveType() : -1, WID_VT_EXTRA);
break; break;
} }
} }

View File

@@ -188,9 +188,9 @@ DropDownListItem *MakeCompanyDropDownListItem(CompanyID cid)
* @param list List of items * @param list List of items
* @param def Default item * @param def Default item
*/ */
static void PopupMainToolbMenu(Window *w, int widget, DropDownList *list, int def) static void PopupMainToolbMenu(Window *w, int widget, DropDownList &&list, int def)
{ {
ShowDropDownList(w, list, def, widget, 0, true, true); ShowDropDownList(w, std::move(list), def, widget, 0, true, true);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
} }
@@ -203,11 +203,11 @@ static void PopupMainToolbMenu(Window *w, int widget, DropDownList *list, int de
*/ */
static void PopupMainToolbMenu(Window *w, int widget, StringID string, int count) static void PopupMainToolbMenu(Window *w, int widget, StringID string, int count)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
list->push_back(new DropDownListStringItem(string + i, i, false)); list.emplace_back(new DropDownListStringItem(string + i, i, false));
} }
PopupMainToolbMenu(w, widget, list, 0); PopupMainToolbMenu(w, widget, std::move(list), 0);
} }
/** Enum for the Company Toolbar's network related buttons */ /** Enum for the Company Toolbar's network related buttons */
@@ -224,37 +224,37 @@ static const int CTMN_SPECTATOR = -4; ///< Show a company window as spectator
*/ */
static void PopupMainCompanyToolbMenu(Window *w, int widget, int grey = 0) static void PopupMainCompanyToolbMenu(Window *w, int widget, int grey = 0)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
switch (widget) { switch (widget) {
case WID_TN_COMPANIES: case WID_TN_COMPANIES:
if (!_networking) break; if (!_networking) break;
/* Add the client list button for the companies menu */ /* Add the client list button for the companies menu */
list->push_back(new DropDownListStringItem(STR_NETWORK_COMPANY_LIST_CLIENT_LIST, CTMN_CLIENT_LIST, false)); list.emplace_back(new DropDownListStringItem(STR_NETWORK_COMPANY_LIST_CLIENT_LIST, CTMN_CLIENT_LIST, false));
if (_local_company == COMPANY_SPECTATOR) { if (_local_company == COMPANY_SPECTATOR) {
list->push_back(new DropDownListStringItem(STR_NETWORK_COMPANY_LIST_NEW_COMPANY, CTMN_NEW_COMPANY, NetworkMaxCompaniesReached())); list.emplace_back(new DropDownListStringItem(STR_NETWORK_COMPANY_LIST_NEW_COMPANY, CTMN_NEW_COMPANY, NetworkMaxCompaniesReached()));
} else { } else {
list->push_back(new DropDownListStringItem(STR_NETWORK_COMPANY_LIST_SPECTATE, CTMN_SPECTATE, NetworkMaxSpectatorsReached())); list.emplace_back(new DropDownListStringItem(STR_NETWORK_COMPANY_LIST_SPECTATE, CTMN_SPECTATE, NetworkMaxSpectatorsReached()));
} }
break; break;
case WID_TN_STORY: case WID_TN_STORY:
list->push_back(new DropDownListStringItem(STR_STORY_BOOK_SPECTATOR, CTMN_SPECTATOR, false)); list.emplace_back(new DropDownListStringItem(STR_STORY_BOOK_SPECTATOR, CTMN_SPECTATOR, false));
break; break;
case WID_TN_GOAL: case WID_TN_GOAL:
list->push_back(new DropDownListStringItem(STR_GOALS_SPECTATOR, CTMN_SPECTATOR, false)); list.emplace_back(new DropDownListStringItem(STR_GOALS_SPECTATOR, CTMN_SPECTATOR, false));
break; break;
} }
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) { for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (!Company::IsValidID(c)) continue; if (!Company::IsValidID(c)) continue;
list->push_back(new DropDownListCompanyItem(c, false, HasBit(grey, c))); list.emplace_back(new DropDownListCompanyItem(c, false, HasBit(grey, c)));
} }
PopupMainToolbMenu(w, widget, list, _local_company == COMPANY_SPECTATOR ? (widget == WID_TN_COMPANIES ? CTMN_CLIENT_LIST : CTMN_SPECTATOR) : (int)_local_company); PopupMainToolbMenu(w, widget, std::move(list), _local_company == COMPANY_SPECTATOR ? (widget == WID_TN_COMPANIES ? CTMN_CLIENT_LIST : CTMN_SPECTATOR) : (int)_local_company);
} }
@@ -325,28 +325,28 @@ enum OptionMenuEntries {
*/ */
static CallBackFunction ToolbarOptionsClick(Window *w) static CallBackFunction ToolbarOptionsClick(Window *w)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
list->push_back(new DropDownListStringItem(STR_SETTINGS_MENU_GAME_OPTIONS, OME_GAMEOPTIONS, false)); list.emplace_back(new DropDownListStringItem(STR_SETTINGS_MENU_GAME_OPTIONS, OME_GAMEOPTIONS, false));
list->push_back(new DropDownListStringItem(STR_SETTINGS_MENU_CONFIG_SETTINGS_TREE, OME_SETTINGS, false)); list.emplace_back(new DropDownListStringItem(STR_SETTINGS_MENU_CONFIG_SETTINGS_TREE, OME_SETTINGS, false));
/* Changes to the per-AI settings don't get send from the server to the clients. Clients get /* Changes to the per-AI settings don't get send from the server to the clients. Clients get
* the settings once they join but never update it. As such don't show the window at all * the settings once they join but never update it. As such don't show the window at all
* to network clients. */ * to network clients. */
if (!_networking || _network_server) list->push_back(new DropDownListStringItem(STR_SETTINGS_MENU_SCRIPT_SETTINGS, OME_SCRIPT_SETTINGS, false)); if (!_networking || _network_server) list.emplace_back(new DropDownListStringItem(STR_SETTINGS_MENU_SCRIPT_SETTINGS, OME_SCRIPT_SETTINGS, false));
list->push_back(new DropDownListStringItem(STR_SETTINGS_MENU_NEWGRF_SETTINGS, OME_NEWGRFSETTINGS, false)); list.emplace_back(new DropDownListStringItem(STR_SETTINGS_MENU_NEWGRF_SETTINGS, OME_NEWGRFSETTINGS, false));
list->push_back(new DropDownListStringItem(STR_SETTINGS_MENU_ZONING, OME_ZONING, false)); list.emplace_back(new DropDownListStringItem(STR_SETTINGS_MENU_ZONING, OME_ZONING, false));
list->push_back(new DropDownListStringItem(STR_SETTINGS_MENU_TRANSPARENCY_OPTIONS, OME_TRANSPARENCIES, false)); list.emplace_back(new DropDownListStringItem(STR_SETTINGS_MENU_TRANSPARENCY_OPTIONS, OME_TRANSPARENCIES, false));
list->push_back(new DropDownListItem(-1, false)); list.emplace_back(new DropDownListItem(-1, false));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_TOWN_NAMES_DISPLAYED, OME_SHOW_TOWNNAMES, false, HasBit(_display_opt, DO_SHOW_TOWN_NAMES))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_TOWN_NAMES_DISPLAYED, OME_SHOW_TOWNNAMES, false, HasBit(_display_opt, DO_SHOW_TOWN_NAMES)));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_STATION_NAMES_DISPLAYED, OME_SHOW_STATIONNAMES, false, HasBit(_display_opt, DO_SHOW_STATION_NAMES))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_STATION_NAMES_DISPLAYED, OME_SHOW_STATIONNAMES, false, HasBit(_display_opt, DO_SHOW_STATION_NAMES)));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_WAYPOINTS_DISPLAYED, OME_SHOW_WAYPOINTNAMES, false, HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_WAYPOINTS_DISPLAYED, OME_SHOW_WAYPOINTNAMES, false, HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_SIGNS_DISPLAYED, OME_SHOW_SIGNS, false, HasBit(_display_opt, DO_SHOW_SIGNS))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_SIGNS_DISPLAYED, OME_SHOW_SIGNS, false, HasBit(_display_opt, DO_SHOW_SIGNS)));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_SHOW_COMPETITOR_SIGNS, OME_SHOW_COMPETITOR_SIGNS, false, HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_SHOW_COMPETITOR_SIGNS, OME_SHOW_COMPETITOR_SIGNS, false, HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS)));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_FULL_ANIMATION, OME_FULL_ANIMATION, false, HasBit(_display_opt, DO_FULL_ANIMATION))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_FULL_ANIMATION, OME_FULL_ANIMATION, false, HasBit(_display_opt, DO_FULL_ANIMATION)));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_FULL_DETAIL, OME_FULL_DETAILS, false, HasBit(_display_opt, DO_FULL_DETAIL))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_FULL_DETAIL, OME_FULL_DETAILS, false, HasBit(_display_opt, DO_FULL_DETAIL)));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_TRANSPARENT_BUILDINGS, OME_TRANSPARENTBUILDINGS, false, IsTransparencySet(TO_HOUSES))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_TRANSPARENT_BUILDINGS, OME_TRANSPARENTBUILDINGS, false, IsTransparencySet(TO_HOUSES)));
list->push_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_TRANSPARENT_SIGNS, OME_SHOW_STATIONSIGNS, false, IsTransparencySet(TO_SIGNS))); list.emplace_back(new DropDownListCheckedItem(STR_SETTINGS_MENU_TRANSPARENT_SIGNS, OME_SHOW_STATIONSIGNS, false, IsTransparencySet(TO_SIGNS)));
ShowDropDownList(w, list, 0, WID_TN_SETTINGS, 140, true, true); ShowDropDownList(w, std::move(list), 0, WID_TN_SETTINGS, 140, true, true);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
return CBF_NONE; return CBF_NONE;
} }
@@ -474,25 +474,25 @@ enum MapMenuEntries {
static CallBackFunction ToolbarMapClick(Window *w) static CallBackFunction ToolbarMapClick(Window *w)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
list->push_back(new DropDownListStringItem(STR_MAP_MENU_MAP_OF_WORLD, MME_SHOW_SMALLMAP, false)); list.emplace_back(new DropDownListStringItem(STR_MAP_MENU_MAP_OF_WORLD, MME_SHOW_SMALLMAP, false));
list->push_back(new DropDownListStringItem(STR_MAP_MENU_EXTRA_VIEW_PORT, MME_SHOW_EXTRAVIEWPORTS, false)); list.emplace_back(new DropDownListStringItem(STR_MAP_MENU_EXTRA_VIEW_PORT, MME_SHOW_EXTRAVIEWPORTS, false));
list->push_back(new DropDownListStringItem(STR_MAP_MENU_LINGRAPH_LEGEND, MME_SHOW_LINKGRAPH, false)); list.emplace_back(new DropDownListStringItem(STR_MAP_MENU_LINGRAPH_LEGEND, MME_SHOW_LINKGRAPH, false));
list->push_back(new DropDownListStringItem(STR_MAP_MENU_SIGN_LIST, MME_SHOW_SIGNLISTS, false)); list.emplace_back(new DropDownListStringItem(STR_MAP_MENU_SIGN_LIST, MME_SHOW_SIGNLISTS, false));
list->push_back(new DropDownListStringItem(STR_MAP_MENU_PLAN_LIST, MME_SHOW_PLANS, false)); list.emplace_back(new DropDownListStringItem(STR_MAP_MENU_PLAN_LIST, MME_SHOW_PLANS, false));
PopupMainToolbMenu(w, WID_TN_SMALL_MAP, list, 0); PopupMainToolbMenu(w, WID_TN_SMALL_MAP, std::move(list), 0);
return CBF_NONE; return CBF_NONE;
} }
static CallBackFunction ToolbarScenMapTownDir(Window *w) static CallBackFunction ToolbarScenMapTownDir(Window *w)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
list->push_back(new DropDownListStringItem(STR_MAP_MENU_MAP_OF_WORLD, MME_SHOW_SMALLMAP, false)); list.emplace_back(new DropDownListStringItem(STR_MAP_MENU_MAP_OF_WORLD, MME_SHOW_SMALLMAP, false));
list->push_back(new DropDownListStringItem(STR_MAP_MENU_EXTRA_VIEW_PORT, MME_SHOW_EXTRAVIEWPORTS, false)); list.emplace_back(new DropDownListStringItem(STR_MAP_MENU_EXTRA_VIEW_PORT, MME_SHOW_EXTRAVIEWPORTS, false));
list->push_back(new DropDownListStringItem(STR_MAP_MENU_SIGN_LIST, MME_SHOW_SIGNLISTS, false)); list.emplace_back(new DropDownListStringItem(STR_MAP_MENU_SIGN_LIST, MME_SHOW_SIGNLISTS, false));
list->push_back(new DropDownListStringItem(STR_TOWN_MENU_TOWN_DIRECTORY, MME_SHOW_TOWNDIRECTORY, false)); list.emplace_back(new DropDownListStringItem(STR_TOWN_MENU_TOWN_DIRECTORY, MME_SHOW_TOWNDIRECTORY, false));
list->push_back(new DropDownListStringItem(STR_INDUSTRY_MENU_INDUSTRY_DIRECTORY, MME_SHOW_INDUSTRYDIRECTORY, false)); list.emplace_back(new DropDownListStringItem(STR_INDUSTRY_MENU_INDUSTRY_DIRECTORY, MME_SHOW_INDUSTRYDIRECTORY, false));
PopupMainToolbMenu(w, WID_TE_SMALL_MAP, list, 0); PopupMainToolbMenu(w, WID_TE_SMALL_MAP, std::move(list), 0);
return CBF_NONE; return CBF_NONE;
} }
@@ -907,10 +907,10 @@ static CallBackFunction MenuClickBuildRail(int index)
static CallBackFunction ToolbarBuildRoadClick(Window *w) static CallBackFunction ToolbarBuildRoadClick(Window *w)
{ {
const Company *c = Company::Get(_local_company); const Company *c = Company::Get(_local_company);
DropDownList *list = new DropDownList(); DropDownList list;
/* Road is always visible and available. */ /* Road is always visible and available. */
list->push_back(new DropDownListIconItem(SPR_IMG_ROAD_X_DIR, PAL_NONE, STR_ROAD_MENU_ROAD_CONSTRUCTION, ROADTYPE_ROAD, false)); list.emplace_back(new DropDownListIconItem(SPR_IMG_ROAD_X_DIR, PAL_NONE, STR_ROAD_MENU_ROAD_CONSTRUCTION, ROADTYPE_ROAD, false));
/* Tram is only visible when there will be a tram, and available when that has been introduced. */ /* Tram is only visible when there will be a tram, and available when that has been introduced. */
Engine *e; Engine *e;
@@ -918,10 +918,10 @@ static CallBackFunction ToolbarBuildRoadClick(Window *w)
if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue; if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
if (!HasBit(e->info.misc_flags, EF_ROAD_TRAM)) continue; if (!HasBit(e->info.misc_flags, EF_ROAD_TRAM)) continue;
list->push_back(new DropDownListIconItem(SPR_IMG_TRAMWAY_X_DIR, PAL_NONE, STR_ROAD_MENU_TRAM_CONSTRUCTION, ROADTYPE_TRAM, !HasBit(c->avail_roadtypes, ROADTYPE_TRAM))); list.emplace_back(new DropDownListIconItem(SPR_IMG_TRAMWAY_X_DIR, PAL_NONE, STR_ROAD_MENU_TRAM_CONSTRUCTION, ROADTYPE_TRAM, !HasBit(c->avail_roadtypes, ROADTYPE_TRAM)));
break; break;
} }
ShowDropDownList(w, list, _last_built_roadtype, WID_TN_ROADS, 140, true, true); ShowDropDownList(w, std::move(list), _last_built_roadtype, WID_TN_ROADS, 140, true, true);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
return CBF_NONE; return CBF_NONE;
} }

View File

@@ -471,7 +471,7 @@ static const TraceRestrictDropDownListSet *GetSortedCargoTypeDropDownListSet()
/** /**
* Get a DropDownList of the group list * Get a DropDownList of the group list
*/ */
static DropDownList *GetGroupDropDownList(Owner owner, GroupID group_id, int &selected) static DropDownList GetGroupDropDownList(Owner owner, GroupID group_id, int &selected)
{ {
typedef GUIList<const Group*> GUIGroupList; typedef GUIList<const Group*> GUIGroupList;
extern int CDECL GroupNameSorter(const Group * const *a, const Group * const *b); extern int CDECL GroupNameSorter(const Group * const *a, const Group * const *b);
@@ -488,18 +488,18 @@ static DropDownList *GetGroupDropDownList(Owner owner, GroupID group_id, int &se
list.ForceResort(); list.ForceResort();
list.Sort(&GroupNameSorter); list.Sort(&GroupNameSorter);
DropDownList *dlist = new DropDownList(); DropDownList dlist;
selected = -1; selected = -1;
if (group_id == DEFAULT_GROUP) selected = DEFAULT_GROUP; if (group_id == DEFAULT_GROUP) selected = DEFAULT_GROUP;
dlist->push_back(new DropDownListStringItem(STR_GROUP_DEFAULT_TRAINS, DEFAULT_GROUP, false)); dlist.emplace_back(new DropDownListStringItem(STR_GROUP_DEFAULT_TRAINS, DEFAULT_GROUP, false));
for (size_t i = 0; i < list.size(); ++i) { for (size_t i = 0; i < list.size(); ++i) {
const Group *g = list[i]; const Group *g = list[i];
if (group_id == g->index) selected = group_id; if (group_id == g->index) selected = group_id;
DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_GROUP_NAME, g->index, false); DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_GROUP_NAME, g->index, false);
item->SetParam(0, g->index); item->SetParam(0, g->index);
dlist->push_back(item); dlist.emplace_back(item);
} }
return dlist; return dlist;
@@ -516,9 +516,10 @@ static int CDECL SlotNameSorter(const TraceRestrictSlot * const *a, const TraceR
/** /**
* Get a DropDownList of the group list * Get a DropDownList of the group list
*/ */
DropDownList *GetSlotDropDownList(Owner owner, TraceRestrictSlotID slot_id, int &selected) DropDownList GetSlotDropDownList(Owner owner, TraceRestrictSlotID slot_id, int &selected)
{ {
GUIList<const TraceRestrictSlot*> list; GUIList<const TraceRestrictSlot*> list;
DropDownList dlist;
const TraceRestrictSlot *slot; const TraceRestrictSlot *slot;
FOR_ALL_TRACE_RESTRICT_SLOTS(slot) { FOR_ALL_TRACE_RESTRICT_SLOTS(slot) {
@@ -527,12 +528,11 @@ DropDownList *GetSlotDropDownList(Owner owner, TraceRestrictSlotID slot_id, int
} }
} }
if (list.size() == 0) return NULL; if (list.size() == 0) return dlist;
list.ForceResort(); list.ForceResort();
list.Sort(&SlotNameSorter); list.Sort(&SlotNameSorter);
DropDownList *dlist = new DropDownList();
selected = -1; selected = -1;
for (size_t i = 0; i < list.size(); ++i) { for (size_t i = 0; i < list.size(); ++i) {
@@ -540,7 +540,7 @@ DropDownList *GetSlotDropDownList(Owner owner, TraceRestrictSlotID slot_id, int
if (slot_id == s->index) selected = slot_id; if (slot_id == s->index) selected = slot_id;
DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_TRACE_RESTRICT_SLOT_NAME, s->index, false); DropDownListParamStringItem *item = new DropDownListParamStringItem(STR_TRACE_RESTRICT_SLOT_NAME, s->index, false);
item->SetParam(0, s->index); item->SetParam(0, s->index);
dlist->push_back(item); dlist.emplace_back(item);
} }
return dlist; return dlist;
@@ -1498,8 +1498,8 @@ public:
case TRVT_GROUP_INDEX: { case TRVT_GROUP_INDEX: {
int selected; int selected;
DropDownList *dlist = GetGroupDropDownList(this->GetOwner(), GetTraceRestrictValue(item), selected); DropDownList dlist = GetGroupDropDownList(this->GetOwner(), GetTraceRestrictValue(item), selected);
ShowDropDownList(this, dlist, selected, TR_WIDGET_VALUE_DROPDOWN); ShowDropDownList(this, std::move(dlist), selected, TR_WIDGET_VALUE_DROPDOWN);
break; break;
} }
@@ -1509,8 +1509,8 @@ public:
case TRVT_SLOT_INDEX: { case TRVT_SLOT_INDEX: {
int selected; int selected;
DropDownList *dlist = GetSlotDropDownList(this->GetOwner(), GetTraceRestrictValue(item), selected); DropDownList dlist = GetSlotDropDownList(this->GetOwner(), GetTraceRestrictValue(item), selected);
if (dlist != NULL) ShowDropDownList(this, dlist, selected, TR_WIDGET_VALUE_DROPDOWN); if (!dlist.empty()) ShowDropDownList(this, std::move(dlist), selected, TR_WIDGET_VALUE_DROPDOWN);
break; break;
} }
@@ -1533,8 +1533,8 @@ public:
switch (GetTraceRestrictTypeProperties(item).value_type) { switch (GetTraceRestrictTypeProperties(item).value_type) {
case TRVT_SLOT_INDEX_INT: { case TRVT_SLOT_INDEX_INT: {
int selected; int selected;
DropDownList *dlist = GetSlotDropDownList(this->GetOwner(), GetTraceRestrictValue(item), selected); DropDownList dlist = GetSlotDropDownList(this->GetOwner(), GetTraceRestrictValue(item), selected);
if (dlist != NULL) ShowDropDownList(this, dlist, selected, TR_WIDGET_LEFT_AUX_DROPDOWN); if (!dlist.empty()) ShowDropDownList(this, std::move(dlist), selected, TR_WIDGET_LEFT_AUX_DROPDOWN);
break; break;
} }
@@ -2546,21 +2546,21 @@ private:
*/ */
void ShowCompanyDropDownListWithValue(CompanyID value, bool missing_ok, int button) void ShowCompanyDropDownListWithValue(CompanyID value, bool missing_ok, int button)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
Company *c; Company *c;
FOR_ALL_COMPANIES(c) { FOR_ALL_COMPANIES(c) {
list->push_back(MakeCompanyDropDownListItem(c->index)); list.emplace_back(MakeCompanyDropDownListItem(c->index));
if (c->index == value) missing_ok = true; if (c->index == value) missing_ok = true;
} }
list->push_back(new DropDownListStringItem(STR_TRACE_RESTRICT_UNDEFINED_COMPANY, INVALID_COMPANY, false)); list.emplace_back(new DropDownListStringItem(STR_TRACE_RESTRICT_UNDEFINED_COMPANY, INVALID_COMPANY, false));
if (INVALID_COMPANY == value) missing_ok = true; if (INVALID_COMPANY == value) missing_ok = true;
assert(missing_ok == true); assert(missing_ok == true);
assert(button == TR_WIDGET_VALUE_DROPDOWN); assert(button == TR_WIDGET_VALUE_DROPDOWN);
this->value_drop_down_is_company = true; this->value_drop_down_is_company = true;
ShowDropDownList(this, list, value, button, 0, true, false); ShowDropDownList(this, std::move(list), value, button, 0, true, false);
} }
/** /**

View File

@@ -337,34 +337,34 @@ bool BaseVehicleListWindow::ShouldShowActionDropdownList() const
* @param show_group If true include group-related stuff. * @param show_group If true include group-related stuff.
* @return Itemlist for dropdown * @return Itemlist for dropdown
*/ */
DropDownList *BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group, bool show_template_replace, DropDownList BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group, bool show_template_replace,
StringID change_order_str, bool show_create_group, bool consider_top_level) StringID change_order_str, bool show_create_group, bool consider_top_level)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
bool disable = this->vehicles.size() == 0; bool disable = this->vehicles.size() == 0;
bool mass_action_disable = disable || (_settings_client.gui.disable_top_veh_list_mass_actions && consider_top_level); bool mass_action_disable = disable || (_settings_client.gui.disable_top_veh_list_mass_actions && consider_top_level);
if (show_autoreplace) list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, disable)); if (show_autoreplace) list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, disable));
if (show_autoreplace && show_template_replace) { if (show_autoreplace && show_template_replace) {
list->push_back(new DropDownListStringItem(STR_TMPL_TEMPLATE_REPLACEMENT, ADI_TEMPLATE_REPLACE, disable)); list.emplace_back(new DropDownListStringItem(STR_TMPL_TEMPLATE_REPLACEMENT, ADI_TEMPLATE_REPLACE, disable));
} }
list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, mass_action_disable)); list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, mass_action_disable));
list->push_back(new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, mass_action_disable)); list.emplace_back(new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, mass_action_disable));
if (_settings_client.gui.show_depot_sell_gui) list->push_back(new DropDownListStringItem(this->vehicle_depot_sell_name[this->vli.vtype], ADI_DEPOT_SELL, mass_action_disable)); if (_settings_client.gui.show_depot_sell_gui) list.emplace_back(new DropDownListStringItem(this->vehicle_depot_sell_name[this->vli.vtype], ADI_DEPOT_SELL, mass_action_disable));
list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_CANCEL_DEPOT_SERVICE, ADI_CANCEL_DEPOT, mass_action_disable)); list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_CANCEL_DEPOT_SERVICE, ADI_CANCEL_DEPOT, mass_action_disable));
if (show_group) { if (show_group) {
list->push_back(new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, disable)); list.emplace_back(new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, disable));
list->push_back(new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, disable)); list.emplace_back(new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, disable));
} }
if (this->vli.vtype == VEH_TRAIN && _settings_client.gui.show_adv_tracerestrict_features) { if (this->vli.vtype == VEH_TRAIN && _settings_client.gui.show_adv_tracerestrict_features) {
list->push_back(new DropDownListStringItem(STR_TRACE_RESTRICT_SLOT_MANAGE, ADI_TRACERESTRICT_SLOT_MGMT, false)); list.emplace_back(new DropDownListStringItem(STR_TRACE_RESTRICT_SLOT_MANAGE, ADI_TRACERESTRICT_SLOT_MGMT, false));
} }
if (change_order_str != 0) { if (change_order_str != 0) {
list->push_back(new DropDownListStringItem(change_order_str, ADI_CHANGE_ORDER, false)); list.emplace_back(new DropDownListStringItem(change_order_str, ADI_CHANGE_ORDER, false));
} }
if (show_create_group) { if (show_create_group) {
list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_CREATE_GROUP, ADI_CREATE_GROUP, false)); list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_CREATE_GROUP, ADI_CREATE_GROUP, false));
} }
return list; return list;
@@ -2040,9 +2040,9 @@ public:
case WID_VL_MANAGE_VEHICLES_DROPDOWN: { case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
VehicleListIdentifier vli = VehicleListIdentifier::UnPack(this->window_number); VehicleListIdentifier vli = VehicleListIdentifier::UnPack(this->window_number);
DropDownList *list = this->BuildActionDropdownList(vli.type == VL_STANDARD, false, DropDownList list = this->BuildActionDropdownList(vli.type == VL_STANDARD, false,
this->vli.vtype == VEH_TRAIN, this->GetChangeOrderStringID(), true, vli.type == VL_STANDARD); this->vli.vtype == VEH_TRAIN, this->GetChangeOrderStringID(), true, vli.type == VL_STANDARD);
ShowDropDownList(this, list, -1, WID_VL_MANAGE_VEHICLES_DROPDOWN); ShowDropDownList(this, std::move(list), -1, WID_VL_MANAGE_VEHICLES_DROPDOWN);
break; break;
} }
@@ -3436,12 +3436,12 @@ public:
} else if (_settings_client.gui.show_depot_sell_gui && v->current_order.IsType(OT_GOTO_DEPOT)) { } else if (_settings_client.gui.show_depot_sell_gui && v->current_order.IsType(OT_GOTO_DEPOT)) {
if (_ctrl_pressed) { if (_ctrl_pressed) {
OrderDepotActionFlags flags = v->current_order.GetDepotActionType() & (ODATFB_HALT | ODATFB_SELL); OrderDepotActionFlags flags = v->current_order.GetDepotActionType() & (ODATFB_HALT | ODATFB_SELL);
DropDownList *list = new DropDownList(); DropDownList list;
list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, DEPOT_SERVICE | DEPOT_DONT_CANCEL, !flags)); list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, DEPOT_SERVICE | DEPOT_DONT_CANCEL, !flags));
list->push_back(new DropDownListStringItem(BaseVehicleListWindow::vehicle_depot_name[v->type], DEPOT_DONT_CANCEL, flags == ODATFB_HALT)); list.emplace_back(new DropDownListStringItem(BaseVehicleListWindow::vehicle_depot_name[v->type], DEPOT_DONT_CANCEL, flags == ODATFB_HALT));
list->push_back(new DropDownListStringItem(BaseVehicleListWindow::vehicle_depot_sell_name[v->type], DEPOT_SELL | DEPOT_DONT_CANCEL, flags == (ODATFB_HALT | ODATFB_SELL))); list.emplace_back(new DropDownListStringItem(BaseVehicleListWindow::vehicle_depot_sell_name[v->type], DEPOT_SELL | DEPOT_DONT_CANCEL, flags == (ODATFB_HALT | ODATFB_SELL)));
list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_CANCEL_DEPOT_SERVICE, DEPOT_CANCEL, false)); list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_CANCEL_DEPOT_SERVICE, DEPOT_CANCEL, false));
ShowDropDownList(this, list, -1, widget, 0, true); ShowDropDownList(this, std::move(list), -1, widget, 0, true);
} else { } else {
DoCommandP(v->tile, v->index | DEPOT_CANCEL, 0, GetCmdSendToDepot(v)); DoCommandP(v->tile, v->index | DEPOT_CANCEL, 0, GetCmdSendToDepot(v));
} }

View File

@@ -74,7 +74,7 @@ struct BaseVehicleListWindow : public Window {
void OnInit() override; void OnInit() override;
void CheckCargoFilterEnableState(int plane_widget, bool re_init, bool possible = true); void CheckCargoFilterEnableState(int plane_widget, bool re_init, bool possible = true);
Dimension GetActionDropdownSize(bool show_autoreplace, bool show_group, bool show_template_replace, StringID change_order_str = 0); Dimension GetActionDropdownSize(bool show_autoreplace, bool show_group, bool show_template_replace, StringID change_order_str = 0);
DropDownList *BuildActionDropdownList(bool show_autoreplace, bool show_group, bool show_template_replace, DropDownList BuildActionDropdownList(bool show_autoreplace, bool show_group, bool show_template_replace,
StringID change_order_str = 0, bool show_create_group = false, bool consider_top_level = false); StringID change_order_str = 0, bool show_create_group = false, bool consider_top_level = false);
bool ShouldShowActionDropdownList() const; bool ShouldShowActionDropdownList() const;
}; };

View File

@@ -51,12 +51,12 @@ void DropDownListStringItem::Draw(int left, int right, int top, int bottom, bool
* @return true if \a first precedes \a second. * @return true if \a first precedes \a second.
* @warning All items in the list need to be derivates of DropDownListStringItem. * @warning All items in the list need to be derivates of DropDownListStringItem.
*/ */
/* static */ int DropDownListStringItem::NatSortFunc(const DropDownListItem * const *first, const DropDownListItem * const * second) /* static */ bool DropDownListStringItem::NatSortFunc(std::unique_ptr<const DropDownListItem> const &first, std::unique_ptr<const DropDownListItem> const &second)
{ {
char buffer1[512], buffer2[512]; char buffer1[512], buffer2[512];
GetString(buffer1, static_cast<const DropDownListStringItem*>(*first)->String(), lastof(buffer1)); GetString(buffer1, static_cast<const DropDownListStringItem*>(first.get())->String(), lastof(buffer1));
GetString(buffer2, static_cast<const DropDownListStringItem*>(*second)->String(), lastof(buffer2)); GetString(buffer2, static_cast<const DropDownListStringItem*>(second.get())->String(), lastof(buffer2));
return strnatcmp(buffer1, buffer2); return strnatcmp(buffer1, buffer2) < 0;
} }
StringID DropDownListParamStringItem::String() const StringID DropDownListParamStringItem::String() const
@@ -126,7 +126,7 @@ struct DropdownWindow : Window {
WindowClass parent_wnd_class; ///< Parent window class. WindowClass parent_wnd_class; ///< Parent window class.
WindowNumber parent_wnd_num; ///< Parent window number. WindowNumber parent_wnd_num; ///< Parent window number.
int parent_button; ///< Parent widget number where the window is dropped from. int parent_button; ///< Parent widget number where the window is dropped from.
const DropDownList *list; ///< List with dropdown menu items. const DropDownList list; ///< List with dropdown menu items.
int selected_index; ///< Index of the selected item in the list. int selected_index; ///< Index of the selected item in the list.
byte click_delay; ///< Timer to delay selection. byte click_delay; ///< Timer to delay selection.
bool drag_mode; bool drag_mode;
@@ -149,10 +149,10 @@ struct DropdownWindow : Window {
* @param wi_colour Colour of the parent widget. * @param wi_colour Colour of the parent widget.
* @param scroll Dropdown menu has a scrollbar. * @param scroll Dropdown menu has a scrollbar.
*/ */
DropdownWindow(Window *parent, const DropDownList *list, int selected, int button, bool instant_close, const Point &position, const Dimension &size, Colours wi_colour, bool scroll, DropDownSyncFocus sync_parent_focus) DropdownWindow(Window *parent, DropDownList &&list, int selected, int button, bool instant_close, const Point &position, const Dimension &size, Colours wi_colour, bool scroll, DropDownSyncFocus sync_parent_focus)
: Window(&_dropdown_desc) : Window(&_dropdown_desc), list(std::move(list))
{ {
assert(list->size() > 0); assert(this->list.size() > 0);
this->position = position; this->position = position;
this->parent_wnd_class = parent->window_class; this->parent_wnd_class = parent->window_class;
@@ -178,16 +178,15 @@ struct DropdownWindow : Window {
/* Total length of list */ /* Total length of list */
int list_height = 0; int list_height = 0;
for (const DropDownListItem *item : *list) { for (const auto &item : this->list) {
list_height += item->Height(items_width); list_height += item->Height(items_width);
} }
/* Capacity is the average number of items visible */ /* Capacity is the average number of items visible */
this->vscroll->SetCapacity(size.height * (uint16)list->size() / list_height); this->vscroll->SetCapacity(size.height * (uint16)this->list.size() / list_height);
this->vscroll->SetCount((uint16)list->size()); this->vscroll->SetCount((uint16)this->list.size());
this->parent_button = button; this->parent_button = button;
this->list = list;
this->selected_index = selected; this->selected_index = selected;
this->click_delay = 0; this->click_delay = 0;
this->drag_mode = true; this->drag_mode = true;
@@ -212,7 +211,6 @@ struct DropdownWindow : Window {
SetFocusedWindow(w2); SetFocusedWindow(w2);
} }
} }
delete this->list;
} }
virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
@@ -234,7 +232,7 @@ struct DropdownWindow : Window {
int width = nwi->current_x - 4; int width = nwi->current_x - 4;
int pos = this->vscroll->GetPosition(); int pos = this->vscroll->GetPosition();
for (const DropDownListItem *item : *this->list) { for (const auto &item : this->list) {
/* Skip items that are scrolled up */ /* Skip items that are scrolled up */
if (--pos >= 0) continue; if (--pos >= 0) continue;
@@ -260,7 +258,7 @@ struct DropdownWindow : Window {
int y = r.top + 2; int y = r.top + 2;
int pos = this->vscroll->GetPosition(); int pos = this->vscroll->GetPosition();
for (const DropDownListItem *item : *this->list) { for (const auto &item : this->list) {
int item_height = item->Height(r.right - r.left + 1); int item_height = item->Height(r.right - r.left + 1);
/* Skip items that are scrolled up */ /* Skip items that are scrolled up */
@@ -378,8 +376,7 @@ struct DropdownWindow : Window {
/** /**
* Show a drop down list. * Show a drop down list.
* @param w Parent window for the list. * @param w Parent window for the list.
* @param list Prepopulated DropDownList. Will be deleted when the list is * @param list Prepopulated DropDownList.
* closed.
* @param selected The initially selected list item. * @param selected The initially selected list item.
* @param button The widget which is passed to Window::OnDropdownSelect and OnDropdownClose. * @param button The widget which is passed to Window::OnDropdownSelect and OnDropdownClose.
* Unless you override those functions, this should be then widget index of the dropdown button. * Unless you override those functions, this should be then widget index of the dropdown button.
@@ -389,7 +386,7 @@ struct DropdownWindow : Window {
* @param instant_close Set to true if releasing mouse button should close the * @param instant_close Set to true if releasing mouse button should close the
* list regardless of where the cursor is. * list regardless of where the cursor is.
*/ */
void ShowDropDownListAt(Window *w, const DropDownList *list, int selected, int button, Rect wi_rect, Colours wi_colour, bool auto_width, bool instant_close, DropDownSyncFocus sync_parent_focus) void ShowDropDownListAt(Window *w, DropDownList &&list, int selected, int button, Rect wi_rect, Colours wi_colour, bool auto_width, bool instant_close, DropDownSyncFocus sync_parent_focus)
{ {
DeleteWindowById(WC_DROPDOWN_MENU, 0); DeleteWindowById(WC_DROPDOWN_MENU, 0);
@@ -405,7 +402,7 @@ void ShowDropDownListAt(Window *w, const DropDownList *list, int selected, int b
/* Total height of list */ /* Total height of list */
uint height = 0; uint height = 0;
for (const DropDownListItem *item : *list) { for (const auto &item : list) {
height += item->Height(width); height += item->Height(width);
if (auto_width) max_item_width = max(max_item_width, item->Width() + 5); if (auto_width) max_item_width = max(max_item_width, item->Width() + 5);
} }
@@ -433,7 +430,7 @@ void ShowDropDownListAt(Window *w, const DropDownList *list, int selected, int b
/* If the dropdown doesn't fully fit, we need a dropdown. */ /* If the dropdown doesn't fully fit, we need a dropdown. */
if (height > available_height) { if (height > available_height) {
scroll = true; scroll = true;
uint avg_height = height / (uint)list->size(); uint avg_height = height / (uint)list.size();
/* Check at least there is space for one item. */ /* Check at least there is space for one item. */
assert(available_height >= avg_height); assert(available_height >= avg_height);
@@ -455,8 +452,8 @@ void ShowDropDownListAt(Window *w, const DropDownList *list, int selected, int b
if (auto_width) width = max(width, max_item_width); if (auto_width) width = max(width, max_item_width);
Point dw_pos = { w->left + (_current_text_dir == TD_RTL ? wi_rect.right + 1 - (int)width : wi_rect.left), top}; Point dw_pos = { w->left + (_current_text_dir == TD_RTL ? wi_rect.right + 1 - (int)width : wi_rect.left), top};
Dimension dw_size = {width, (uint)height}; Dimension dw_size = {width, height};
DropdownWindow *dropdown = new DropdownWindow(w, list, selected, button, instant_close, dw_pos, dw_size, wi_colour, scroll, sync_parent_focus); DropdownWindow *dropdown = new DropdownWindow(w, std::move(list), selected, button, instant_close, dw_pos, dw_size, wi_colour, scroll, sync_parent_focus);
/* The dropdown starts scrolling downwards when opening it towards /* The dropdown starts scrolling downwards when opening it towards
* the top and holding down the mouse button. It can be fooled by * the top and holding down the mouse button. It can be fooled by
@@ -467,8 +464,7 @@ void ShowDropDownListAt(Window *w, const DropDownList *list, int selected, int b
/** /**
* Show a drop down list. * Show a drop down list.
* @param w Parent window for the list. * @param w Parent window for the list.
* @param list Prepopulated DropDownList. Will be deleted when the list is * @param list Prepopulated DropDownList.
* closed.
* @param selected The initially selected list item. * @param selected The initially selected list item.
* @param button The widget within the parent window that is used to determine * @param button The widget within the parent window that is used to determine
* the list's location. * the list's location.
@@ -477,7 +473,7 @@ void ShowDropDownListAt(Window *w, const DropDownList *list, int selected, int b
* @param instant_close Set to true if releasing mouse button should close the * @param instant_close Set to true if releasing mouse button should close the
* list regardless of where the cursor is. * list regardless of where the cursor is.
*/ */
void ShowDropDownList(Window *w, const DropDownList *list, int selected, int button, uint width, bool auto_width, bool instant_close, DropDownSyncFocus sync_parent_focus) void ShowDropDownList(Window *w, DropDownList &&list, int selected, int button, uint width, bool auto_width, bool instant_close, DropDownSyncFocus sync_parent_focus)
{ {
/* Our parent's button widget is used to determine where to place the drop /* Our parent's button widget is used to determine where to place the drop
* down list window. */ * down list window. */
@@ -504,7 +500,7 @@ void ShowDropDownList(Window *w, const DropDownList *list, int selected, int but
} }
} }
ShowDropDownListAt(w, list, selected, button, wi_rect, wi_colour, auto_width, instant_close, sync_parent_focus); ShowDropDownListAt(w, std::move(list), selected, button, wi_rect, wi_colour, auto_width, instant_close, sync_parent_focus);
} }
/** /**
@@ -520,21 +516,15 @@ void ShowDropDownList(Window *w, const DropDownList *list, int selected, int but
*/ */
void ShowDropDownMenu(Window *w, const StringID *strings, int selected, int button, uint32 disabled_mask, uint32 hidden_mask, uint width, DropDownSyncFocus sync_parent_focus) void ShowDropDownMenu(Window *w, const StringID *strings, int selected, int button, uint32 disabled_mask, uint32 hidden_mask, uint width, DropDownSyncFocus sync_parent_focus)
{ {
DropDownList *list = new DropDownList(); DropDownList list;
for (uint i = 0; strings[i] != INVALID_STRING_ID; i++) { for (uint i = 0; strings[i] != INVALID_STRING_ID; i++) {
if (i >= 32 || !HasBit(hidden_mask, i)) { if (i >= 32 || !HasBit(hidden_mask, i)) {
list->push_back(new DropDownListStringItem(strings[i], i, i < 32 && HasBit(disabled_mask, i))); list.emplace_back(new DropDownListStringItem(strings[i], i, i < 32 && HasBit(disabled_mask, i)));
} }
} }
/* No entries in the list? */ if (!list.empty()) ShowDropDownList(w, std::move(list), selected, button, width, false, false, sync_parent_focus);
if (list->size() == 0) {
delete list;
return;
}
ShowDropDownList(w, list, selected, button, width, false, false, sync_parent_focus);
} }
/** /**

View File

@@ -56,7 +56,7 @@ public:
void Draw(int left, int right, int top, int bottom, bool sel, Colours bg_colour) const override; void Draw(int left, int right, int top, int bottom, bool sel, Colours bg_colour) const override;
virtual StringID String() const { return this->string; } virtual StringID String() const { return this->string; }
static int CDECL NatSortFunc(const DropDownListItem * const *first, const DropDownListItem * const *second); static bool NatSortFunc(std::unique_ptr<const DropDownListItem> const &first, std::unique_ptr<const DropDownListItem> const &second);
}; };
/** /**
@@ -96,19 +96,19 @@ class DropDownListIconItem : public DropDownListParamStringItem {
public: public:
DropDownListIconItem(SpriteID sprite, PaletteID pal, StringID string, int result, bool masked); DropDownListIconItem(SpriteID sprite, PaletteID pal, StringID string, int result, bool masked);
/* virtual */ uint Height(uint width) const; uint Height(uint width) const override;
/* virtual */ uint Width() const; uint Width() const override;
/* virtual */ void Draw(int left, int right, int top, int bottom, bool sel, Colours bg_colour) const; void Draw(int left, int right, int top, int bottom, bool sel, Colours bg_colour) const override;
void SetDimension(Dimension d); void SetDimension(Dimension d);
}; };
/** /**
* A drop down list is a collection of drop down list items. * A drop down list is a collection of drop down list items.
*/ */
typedef AutoDeleteSmallVector<const DropDownListItem *> DropDownList; typedef std::vector<std::unique_ptr<const DropDownListItem>> DropDownList;
void ShowDropDownListAt(Window *w, const DropDownList *list, int selected, int button, Rect wi_rect, Colours wi_colour, bool auto_width = false, bool instant_close = false, DropDownSyncFocus sync_parent_focus = DDSF_NONE); void ShowDropDownListAt(Window *w, DropDownList &&list, int selected, int button, Rect wi_rect, Colours wi_colour, bool auto_width = false, bool instant_close = false, DropDownSyncFocus sync_parent_focus = DDSF_NONE);
void ShowDropDownList(Window *w, const DropDownList *list, int selected, int button, uint width = 0, bool auto_width = false, bool instant_close = false, DropDownSyncFocus sync_parent_focus = DDSF_NONE); void ShowDropDownList(Window *w, DropDownList &&list, int selected, int button, uint width = 0, bool auto_width = false, bool instant_close = false, DropDownSyncFocus sync_parent_focus = DDSF_NONE);
#endif /* WIDGETS_DROPDOWN_TYPE_H */ #endif /* WIDGETS_DROPDOWN_TYPE_H */