From 332cbca36e3188f48b69955f3eff2db00cd435ff Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Tue, 9 Apr 2024 02:47:14 +0100 Subject: [PATCH 01/11] Codechange: Pass std::string_view from drivers instead of char *. --- src/driver.cpp | 12 ++++++------ src/driver.h | 16 ++++++++-------- src/music/allegro_m.cpp | 4 ++-- src/music/allegro_m.h | 4 ++-- src/music/bemidi.cpp | 4 ++-- src/music/bemidi.h | 4 ++-- src/music/cocoa_m.cpp | 4 ++-- src/music/cocoa_m.h | 4 ++-- src/music/dmusic.cpp | 4 ++-- src/music/dmusic.h | 4 ++-- src/music/extmidi.cpp | 8 ++++---- src/music/extmidi.h | 4 ++-- src/music/fluidsynth.cpp | 4 ++-- src/music/fluidsynth.h | 4 ++-- src/music/null_m.h | 4 ++-- src/music/win32_m.cpp | 4 ++-- src/music/win32_m.h | 4 ++-- src/settings_gui.cpp | 4 ++-- src/sound/allegro_s.cpp | 4 ++-- src/sound/allegro_s.h | 4 ++-- src/sound/cocoa_s.cpp | 4 ++-- src/sound/cocoa_s.h | 4 ++-- src/sound/null_s.h | 4 ++-- src/sound/sdl2_s.cpp | 4 ++-- src/sound/sdl_s.cpp | 4 ++-- src/sound/sdl_s.h | 4 ++-- src/sound/win32_s.cpp | 4 ++-- src/sound/win32_s.h | 4 ++-- src/sound/xaudio2_s.cpp | 6 +++--- src/sound/xaudio2_s.h | 4 ++-- src/video/allegro_v.cpp | 4 ++-- src/video/allegro_v.h | 4 ++-- src/video/cocoa/cocoa_ogl.h | 8 ++++---- src/video/cocoa/cocoa_ogl.mm | 12 ++++++------ src/video/cocoa/cocoa_v.h | 6 +++--- src/video/cocoa/cocoa_v.mm | 14 +++++++------- src/video/dedicated_v.cpp | 4 ++-- src/video/dedicated_v.h | 4 ++-- src/video/null_v.cpp | 4 ++-- src/video/null_v.h | 4 ++-- src/video/opengl.cpp | 10 +++++----- src/video/opengl.h | 4 ++-- src/video/sdl2_default_v.h | 2 +- src/video/sdl2_opengl_v.cpp | 12 ++++++------ src/video/sdl2_opengl_v.h | 6 +++--- src/video/sdl2_v.cpp | 22 +++++++++++----------- src/video/sdl2_v.h | 6 +++--- src/video/sdl_v.cpp | 4 ++-- src/video/sdl_v.h | 4 ++-- src/video/video_driver.hpp | 2 +- src/video/win32_v.cpp | 28 ++++++++++++++-------------- src/video/win32_v.h | 12 ++++++------ 52 files changed, 161 insertions(+), 161 deletions(-) diff --git a/src/driver.cpp b/src/driver.cpp index 5d3f2addd1..630a974fd4 100644 --- a/src/driver.cpp +++ b/src/driver.cpp @@ -148,15 +148,15 @@ bool DriverFactoryBase::SelectDriverImpl(const std::string &name, Driver::Type t Driver *newd = d->CreateInstance(); *GetActiveDriver(type) = newd; - const char *err = newd->Start({}); - if (err == nullptr) { + auto err = newd->Start({}); + if (!err) { Debug(driver, 1, "Successfully probed {} driver '{}'", GetDriverTypeName(type), d->name); delete oldd; return true; } *GetActiveDriver(type) = oldd; - Debug(driver, 1, "Probing {} driver '{}' failed with error: {}", GetDriverTypeName(type), d->name, err); + Debug(driver, 1, "Probing {} driver '{}' failed with error: {}", GetDriverTypeName(type), d->name, *err); delete newd; if (type == Driver::DT_VIDEO && _video_hw_accel && d->UsesHardwareAcceleration()) { @@ -192,10 +192,10 @@ bool DriverFactoryBase::SelectDriverImpl(const std::string &name, Driver::Type t /* Found our driver, let's try it */ Driver *newd = d->CreateInstance(); - const char *err = newd->Start(parms); - if (err != nullptr) { + auto err = newd->Start(parms); + if (err) { delete newd; - UserError("Unable to load driver '{}'. The error was: {}", d->name, err); + UserError("Unable to load driver '{}'. The error was: {}", d->name, *err); } Debug(driver, 1, "Successfully loaded {} driver '{}'", GetDriverTypeName(type), d->name); diff --git a/src/driver.h b/src/driver.h index 4683784266..ef39391890 100644 --- a/src/driver.h +++ b/src/driver.h @@ -23,9 +23,9 @@ public: /** * Start this driver. * @param parm Parameters passed to the driver. - * @return nullptr if everything went okay, otherwise an error message. + * @return std::nullopt if everything went okay, otherwise an error message. */ - virtual const char *Start(const StringList &parm) = 0; + virtual std::optional Start(const StringList &parm) = 0; /** * Stop this driver. @@ -47,7 +47,7 @@ public: * Get the name of this driver. * @return The name of the driver. */ - virtual const char *GetName() const = 0; + virtual std::string_view GetName() const = 0; }; DECLARE_POSTFIX_INCREMENT(Driver::Type) @@ -62,8 +62,8 @@ private: Driver::Type type; ///< The type of driver. int priority; ///< The priority of this factory. - const char *name; ///< The name of the drivers of this factory. - const char *description; ///< The description of this driver. + std::string_view name; ///< The name of the drivers of this factory. + std::string_view description; ///< The description of this driver. typedef std::map Drivers; ///< Type for a map of drivers. @@ -92,9 +92,9 @@ private: * @param type The type of driver to get the name of. * @return The name of the type. */ - static const char *GetDriverTypeName(Driver::Type type) + static std::string_view GetDriverTypeName(Driver::Type type) { - static const char * const driver_type_name[] = { "music", "sound", "video" }; + static const std::string_view driver_type_name[] = { "music", "sound", "video" }; return driver_type_name[type]; } @@ -135,7 +135,7 @@ public: * Get a nice description of the driver-class. * @return The description. */ - const char *GetDescription() const + std::string_view GetDescription() const { return this->description; } diff --git a/src/music/allegro_m.cpp b/src/music/allegro_m.cpp index 849be0f87c..ce9184f15f 100644 --- a/src/music/allegro_m.cpp +++ b/src/music/allegro_m.cpp @@ -26,7 +26,7 @@ static MIDI *_midi = nullptr; */ extern int _allegro_instance_count; -const char *MusicDriver_Allegro::Start(const StringList &) +std::optional MusicDriver_Allegro::Start(const StringList &) { if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, nullptr)) { Debug(driver, 0, "allegro: install_allegro failed '{}'", allegro_error); @@ -46,7 +46,7 @@ const char *MusicDriver_Allegro::Start(const StringList &) return "No sound card found"; } - return nullptr; + return std::nullopt; } void MusicDriver_Allegro::Stop() diff --git a/src/music/allegro_m.h b/src/music/allegro_m.h index 697fad4661..de59075f5e 100644 --- a/src/music/allegro_m.h +++ b/src/music/allegro_m.h @@ -15,7 +15,7 @@ /** Allegro's music player. */ class MusicDriver_Allegro : public MusicDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -26,7 +26,7 @@ public: bool IsSongPlaying() override; void SetVolume(uint8_t vol) override; - const char *GetName() const override { return "allegro"; } + std::string_view GetName() const override { return "allegro"; } }; /** Factory for allegro's music player. */ diff --git a/src/music/bemidi.cpp b/src/music/bemidi.cpp index 6fda4cfe06..44386cf6c8 100644 --- a/src/music/bemidi.cpp +++ b/src/music/bemidi.cpp @@ -18,9 +18,9 @@ /** Factory for BeOS' midi player. */ static FMusicDriver_BeMidi iFMusicDriver_BeMidi; -const char *MusicDriver_BeMidi::Start(const StringList &parm) +std::optional MusicDriver_BeMidi::Start(const StringList &parm) { - return nullptr; + return std::nullopt; } void MusicDriver_BeMidi::Stop() diff --git a/src/music/bemidi.h b/src/music/bemidi.h index 52e9d7bd68..47529aa51d 100644 --- a/src/music/bemidi.h +++ b/src/music/bemidi.h @@ -18,7 +18,7 @@ /** The midi player for BeOS. */ class MusicDriver_BeMidi : public MusicDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -29,7 +29,7 @@ public: bool IsSongPlaying() override; void SetVolume(uint8_t vol) override; - const char *GetName() const override { return "bemidi"; } + std::string_view GetName() const override { return "bemidi"; } private: BMidiSynthFile *midi_synth_file = nullptr; diff --git a/src/music/cocoa_m.cpp b/src/music/cocoa_m.cpp index 088f5bdf00..9aa847712f 100644 --- a/src/music/cocoa_m.cpp +++ b/src/music/cocoa_m.cpp @@ -79,11 +79,11 @@ static void DoSetVolume() /** * Initialized the MIDI player, including QuickTime initialization. */ -const char *MusicDriver_Cocoa::Start(const StringList &) +std::optional MusicDriver_Cocoa::Start(const StringList &) { if (NewMusicPlayer(&_player) != noErr) return "failed to create music player"; - return nullptr; + return std::nullopt; } diff --git a/src/music/cocoa_m.h b/src/music/cocoa_m.h index ffa87b00fc..dbf58e425e 100644 --- a/src/music/cocoa_m.h +++ b/src/music/cocoa_m.h @@ -14,7 +14,7 @@ class MusicDriver_Cocoa : public MusicDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -25,7 +25,7 @@ public: bool IsSongPlaying() override; void SetVolume(uint8_t vol) override; - const char *GetName() const override { return "cocoa"; } + std::string_view GetName() const override { return "cocoa"; } }; class FMusicDriver_Cocoa : public DriverFactoryBase { diff --git a/src/music/dmusic.cpp b/src/music/dmusic.cpp index 50be53accb..8d0919ceb3 100644 --- a/src/music/dmusic.cpp +++ b/src/music/dmusic.cpp @@ -1072,7 +1072,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls) } -const char *MusicDriver_DMusic::Start(const StringList &parm) +std::optional MusicDriver_DMusic::Start(const StringList &parm) { /* Initialize COM */ if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return "COM initialization failed"; @@ -1153,7 +1153,7 @@ const char *MusicDriver_DMusic::Start(const StringList &parm) if (!StartNewThread(&_dmusic_thread, "ottd:dmusic", &MidiThreadProc)) return "Can't create MIDI output thread"; - return nullptr; + return std::nullopt; } diff --git a/src/music/dmusic.h b/src/music/dmusic.h index 9c2e009dcd..32f0943d85 100644 --- a/src/music/dmusic.h +++ b/src/music/dmusic.h @@ -17,7 +17,7 @@ class MusicDriver_DMusic : public MusicDriver { public: virtual ~MusicDriver_DMusic(); - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -28,7 +28,7 @@ public: bool IsSongPlaying() override; void SetVolume(uint8_t vol) override; - const char *GetName() const override { return "dmusic"; } + std::string_view GetName() const override { return "dmusic"; } }; /** Factory for the DirectX music player. */ diff --git a/src/music/extmidi.cpp b/src/music/extmidi.cpp index 1538b1e7a6..22fd8fcfa0 100644 --- a/src/music/extmidi.cpp +++ b/src/music/extmidi.cpp @@ -35,10 +35,10 @@ /** Factory for the midi player that uses external players. */ static FMusicDriver_ExtMidi iFMusicDriver_ExtMidi; -const char *MusicDriver_ExtMidi::Start(const StringList &parm) +std::optional MusicDriver_ExtMidi::Start(const StringList &parm) { - if (strcmp(VideoDriver::GetInstance()->GetName(), "allegro") == 0 || - strcmp(SoundDriver::GetInstance()->GetName(), "allegro") == 0) { + if (VideoDriver::GetInstance()->GetName() == "allegro" || + SoundDriver::GetInstance()->GetName() == "allegro") { return "the extmidi driver does not work when Allegro is loaded."; } @@ -62,7 +62,7 @@ const char *MusicDriver_ExtMidi::Start(const StringList &parm) this->song.clear(); this->pid = -1; - return nullptr; + return std::nullopt; } void MusicDriver_ExtMidi::Stop() diff --git a/src/music/extmidi.h b/src/music/extmidi.h index ee4ebb8eff..f08c513008 100644 --- a/src/music/extmidi.h +++ b/src/music/extmidi.h @@ -22,7 +22,7 @@ private: void DoStop(); public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -33,7 +33,7 @@ public: bool IsSongPlaying() override; void SetVolume(uint8_t vol) override; - const char *GetName() const override { return "extmidi"; } + std::string_view GetName() const override { return "extmidi"; } }; class FMusicDriver_ExtMidi : public DriverFactoryBase { diff --git a/src/music/fluidsynth.cpp b/src/music/fluidsynth.cpp index 6cb92e6363..4ffd90e620 100644 --- a/src/music/fluidsynth.cpp +++ b/src/music/fluidsynth.cpp @@ -58,7 +58,7 @@ static void RenderMusicStream(int16_t *buffer, size_t samples) fluid_synth_write_s16(_midi.synth, samples, buffer, 0, 2, buffer, 1, 2); } -const char *MusicDriver_FluidSynth::Start(const StringList ¶m) +std::optional MusicDriver_FluidSynth::Start(const StringList ¶m) { std::lock_guard lock{ _midi.synth_mutex }; @@ -110,7 +110,7 @@ const char *MusicDriver_FluidSynth::Start(const StringList ¶m) _midi.player = nullptr; - return nullptr; + return std::nullopt; } void MusicDriver_FluidSynth::Stop() diff --git a/src/music/fluidsynth.h b/src/music/fluidsynth.h index 8eac4c000a..ae7a8385d8 100644 --- a/src/music/fluidsynth.h +++ b/src/music/fluidsynth.h @@ -15,7 +15,7 @@ /** Music driver making use of FluidSynth. */ class MusicDriver_FluidSynth : public MusicDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -26,7 +26,7 @@ public: bool IsSongPlaying() override; void SetVolume(uint8_t vol) override; - const char *GetName() const override { return "fluidsynth"; } + std::string_view GetName() const override { return "fluidsynth"; } }; /** Factory for the fluidsynth driver. */ diff --git a/src/music/null_m.h b/src/music/null_m.h index da6e5dd92c..9c2ca82855 100644 --- a/src/music/null_m.h +++ b/src/music/null_m.h @@ -15,7 +15,7 @@ /** The music player that does nothing. */ class MusicDriver_Null : public MusicDriver { public: - const char *Start(const StringList &) override { return nullptr; } + std::optional Start(const StringList &) override { return std::nullopt; } void Stop() override { } @@ -26,7 +26,7 @@ public: bool IsSongPlaying() override { return true; } void SetVolume(uint8_t) override { } - const char *GetName() const override { return "null"; } + std::string_view GetName() const override { return "null"; } }; /** Factory for the null music player. */ diff --git a/src/music/win32_m.cpp b/src/music/win32_m.cpp index de7ed630a2..886deab2c0 100644 --- a/src/music/win32_m.cpp +++ b/src/music/win32_m.cpp @@ -367,7 +367,7 @@ void MusicDriver_Win32::SetVolume(uint8_t vol) _midi.new_volume = vol; } -const char *MusicDriver_Win32::Start(const StringList &parm) +std::optional MusicDriver_Win32::Start(const StringList &parm) { Debug(driver, 2, "Win32-MIDI: Start: initializing"); @@ -416,7 +416,7 @@ const char *MusicDriver_Win32::Start(const StringList &parm) if (timeBeginPeriod(_midi.time_period) == MMSYSERR_NOERROR) { /* success */ Debug(driver, 2, "Win32-MIDI: Start: timer resolution is {}", _midi.time_period); - return nullptr; + return std::nullopt; } } midiOutClose(_midi.midi_out); diff --git a/src/music/win32_m.h b/src/music/win32_m.h index 74c0b938a6..bd6125420b 100644 --- a/src/music/win32_m.h +++ b/src/music/win32_m.h @@ -15,7 +15,7 @@ /** The Windows music player. */ class MusicDriver_Win32 : public MusicDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -26,7 +26,7 @@ public: bool IsSongPlaying() override; void SetVolume(uint8_t vol) override; - const char *GetName() const override { return "win32"; } + std::string_view GetName() const override { return "win32"; } }; /** Factory for Windows' music player. */ diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index b188d429e6..f1117563bc 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -579,7 +579,7 @@ struct GameOptionsWindow : Window { break; case WID_GO_VIDEO_DRIVER_INFO: - SetDParamStr(0, VideoDriver::GetInstance()->GetInfoString()); + SetDParamStr(0, std::string{VideoDriver::GetInstance()->GetInfoString()}); DrawStringMultiLine(r, STR_GAME_OPTIONS_VIDEO_DRIVER_INFO); break; @@ -641,7 +641,7 @@ struct GameOptionsWindow : Window { changed |= wid->UpdateVerticalSize(y); wid = this->GetWidget(WID_GO_VIDEO_DRIVER_INFO); - SetDParamStr(0, VideoDriver::GetInstance()->GetInfoString()); + SetDParamStr(0, std::string{VideoDriver::GetInstance()->GetInfoString()}); y = GetStringHeight(STR_GAME_OPTIONS_VIDEO_DRIVER_INFO, wid->current_x); changed |= wid->UpdateVerticalSize(y); diff --git a/src/sound/allegro_s.cpp b/src/sound/allegro_s.cpp index 1b695e8a43..a44578c160 100644 --- a/src/sound/allegro_s.cpp +++ b/src/sound/allegro_s.cpp @@ -50,7 +50,7 @@ void SoundDriver_Allegro::MainLoop() */ extern int _allegro_instance_count; -const char *SoundDriver_Allegro::Start(const StringList &parm) +std::optional SoundDriver_Allegro::Start(const StringList &parm) { if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, nullptr)) { Debug(driver, 0, "allegro: install_allegro failed '{}'", allegro_error); @@ -74,7 +74,7 @@ const char *SoundDriver_Allegro::Start(const StringList &parm) _buffer_size = GetDriverParamInt(parm, "samples", 1024) * hz / 11025; _stream = play_audio_stream(_buffer_size, 16, true, hz, 255, 128); MxInitialize(hz); - return nullptr; + return std::nullopt; } void SoundDriver_Allegro::Stop() diff --git a/src/sound/allegro_s.h b/src/sound/allegro_s.h index d2ef08366c..1026038355 100644 --- a/src/sound/allegro_s.h +++ b/src/sound/allegro_s.h @@ -15,12 +15,12 @@ /** Implementation of the allegro sound driver. */ class SoundDriver_Allegro : public SoundDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; void MainLoop() override; - const char *GetName() const override { return "allegro"; } + std::string_view GetName() const override { return "allegro"; } }; /** Factory for the allegro sound driver. */ diff --git a/src/sound/cocoa_s.cpp b/src/sound/cocoa_s.cpp index f059384181..6c4348acdb 100644 --- a/src/sound/cocoa_s.cpp +++ b/src/sound/cocoa_s.cpp @@ -44,7 +44,7 @@ static OSStatus audioCallback(void *, AudioUnitRenderActionFlags *, const AudioT } -const char *SoundDriver_Cocoa::Start(const StringList &parm) +std::optional SoundDriver_Cocoa::Start(const StringList &parm) { struct AURenderCallbackStruct callback; AudioStreamBasicDescription requestedDesc; @@ -108,7 +108,7 @@ const char *SoundDriver_Cocoa::Start(const StringList &parm) } /* We're running! */ - return nullptr; + return std::nullopt; } diff --git a/src/sound/cocoa_s.h b/src/sound/cocoa_s.h index f1e623ce5a..0f32e25b4d 100644 --- a/src/sound/cocoa_s.h +++ b/src/sound/cocoa_s.h @@ -14,10 +14,10 @@ class SoundDriver_Cocoa : public SoundDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; - const char *GetName() const override { return "cocoa"; } + std::string_view GetName() const override { return "cocoa"; } }; class FSoundDriver_Cocoa : public DriverFactoryBase { diff --git a/src/sound/null_s.h b/src/sound/null_s.h index ca699da236..fb931b84dd 100644 --- a/src/sound/null_s.h +++ b/src/sound/null_s.h @@ -15,10 +15,10 @@ /** Implementation of the null sound driver. */ class SoundDriver_Null : public SoundDriver { public: - const char *Start(const StringList &) override { return nullptr; } + std::optional Start(const StringList &) override { return std::nullopt; } void Stop() override { } - const char *GetName() const override { return "null"; } + std::string_view GetName() const override { return "null"; } bool HasOutput() const override { return false; } }; diff --git a/src/sound/sdl2_s.cpp b/src/sound/sdl2_s.cpp index 0a49ad0297..af12a00a31 100644 --- a/src/sound/sdl2_s.cpp +++ b/src/sound/sdl2_s.cpp @@ -30,7 +30,7 @@ static void CDECL fill_sound_buffer(void *, Uint8 *stream, int len) MxMixSamples(stream, len / 4); } -const char *SoundDriver_SDL::Start(const StringList &parm) +std::optional SoundDriver_SDL::Start(const StringList &parm) { SDL_AudioSpec spec; SDL_AudioSpec spec_actual; @@ -52,7 +52,7 @@ const char *SoundDriver_SDL::Start(const StringList &parm) SDL_AudioDeviceID dev = SDL_OpenAudioDevice(nullptr, 0, &spec, &spec_actual, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE); MxInitialize(spec_actual.freq); SDL_PauseAudioDevice(dev, 0); - return nullptr; + return std::nullopt; } void SoundDriver_SDL::Stop() diff --git a/src/sound/sdl_s.cpp b/src/sound/sdl_s.cpp index 4aeaa35b26..7b1f93e240 100644 --- a/src/sound/sdl_s.cpp +++ b/src/sound/sdl_s.cpp @@ -30,7 +30,7 @@ static void CDECL fill_sound_buffer(void *, Uint8 *stream, int len) MxMixSamples(stream, len / 4); } -const char *SoundDriver_SDL::Start(const StringList &parm) +std::optional SoundDriver_SDL::Start(const StringList &parm) { SDL_AudioSpec spec; @@ -51,7 +51,7 @@ const char *SoundDriver_SDL::Start(const StringList &parm) MxInitialize(spec.freq); SDL_OpenAudio(&spec, &spec); SDL_PauseAudio(0); - return nullptr; + return std::nullopt; } void SoundDriver_SDL::Stop() diff --git a/src/sound/sdl_s.h b/src/sound/sdl_s.h index fbe7d77d84..abf9ac6a20 100644 --- a/src/sound/sdl_s.h +++ b/src/sound/sdl_s.h @@ -15,10 +15,10 @@ /** Implementation of the SDL sound driver. */ class SoundDriver_SDL : public SoundDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; - const char *GetName() const override { return "sdl"; } + std::string_view GetName() const override { return "sdl"; } }; /** Factory for the SDL sound driver. */ diff --git a/src/sound/win32_s.cpp b/src/sound/win32_s.cpp index 73cc3c062d..e198fb806b 100644 --- a/src/sound/win32_s.cpp +++ b/src/sound/win32_s.cpp @@ -59,7 +59,7 @@ static DWORD WINAPI SoundThread(LPVOID) return 0; } -const char *SoundDriver_Win32::Start(const StringList &parm) +std::optional SoundDriver_Win32::Start(const StringList &parm) { WAVEFORMATEX wfex; wfex.wFormatTag = WAVE_FORMAT_PCM; @@ -89,7 +89,7 @@ const char *SoundDriver_Win32::Start(const StringList &parm) return error; } - return nullptr; + return std::nullopt; } void SoundDriver_Win32::Stop() diff --git a/src/sound/win32_s.h b/src/sound/win32_s.h index 5722b2089d..5801f8af41 100644 --- a/src/sound/win32_s.h +++ b/src/sound/win32_s.h @@ -15,10 +15,10 @@ /** Implementation of the sound driver for Windows. */ class SoundDriver_Win32 : public SoundDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; - const char *GetName() const override { return "win32"; } + std::string_view GetName() const override { return "win32"; } }; /** Factory for the sound driver for Windows. */ diff --git a/src/sound/xaudio2_s.cpp b/src/sound/xaudio2_s.cpp index 365cf46367..4b8d8236a6 100644 --- a/src/sound/xaudio2_s.cpp +++ b/src/sound/xaudio2_s.cpp @@ -135,10 +135,10 @@ static HRESULT CreateXAudio(API_XAudio2Create xAudio2Create) * Initialises the XAudio2 driver. * * @param parm Driver parameters. - * @return An error message if unsuccessful, or nullptr otherwise. + * @return An error message if unsuccessful, or std::nullopt otherwise. * */ -const char *SoundDriver_XAudio2::Start(const StringList &parm) +std::optional SoundDriver_XAudio2::Start(const StringList &parm) { HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); @@ -257,7 +257,7 @@ const char *SoundDriver_XAudio2::Start(const StringList &parm) return "Failed to submit the first audio buffer"; } - return nullptr; + return std::nullopt; } /** diff --git a/src/sound/xaudio2_s.h b/src/sound/xaudio2_s.h index 621655d8d5..17ec81f311 100644 --- a/src/sound/xaudio2_s.h +++ b/src/sound/xaudio2_s.h @@ -15,10 +15,10 @@ /** Implementation of the XAudio2 sound driver. */ class SoundDriver_XAudio2 : public SoundDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; - const char *GetName() const override { return "xaudio2"; } + std::string_view GetName() const override { return "xaudio2"; } }; /** Factory for the XAudio2 sound driver. */ diff --git a/src/video/allegro_v.cpp b/src/video/allegro_v.cpp index 77c90e1536..6cf585813d 100644 --- a/src/video/allegro_v.cpp +++ b/src/video/allegro_v.cpp @@ -420,7 +420,7 @@ bool VideoDriver_Allegro::PollEvent() */ int _allegro_instance_count = 0; -const char *VideoDriver_Allegro::Start(const StringList ¶m) +std::optional VideoDriver_Allegro::Start(const StringList ¶m) { if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, nullptr)) { Debug(driver, 0, "allegro: install_allegro failed '{}'", allegro_error); @@ -450,7 +450,7 @@ const char *VideoDriver_Allegro::Start(const StringList ¶m) this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread"); - return nullptr; + return std::nullopt; } void VideoDriver_Allegro::Stop() diff --git a/src/video/allegro_v.h b/src/video/allegro_v.h index d1576fea9e..8789b1158f 100644 --- a/src/video/allegro_v.h +++ b/src/video/allegro_v.h @@ -15,7 +15,7 @@ /** The allegro video driver. */ class VideoDriver_Allegro : public VideoDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -33,7 +33,7 @@ public: std::vector GetListOfMonitorRefreshRates() override; - const char *GetName() const override { return "allegro"; } + std::string_view GetName() const override { return "allegro"; } protected: void InputLoop() override; diff --git a/src/video/cocoa/cocoa_ogl.h b/src/video/cocoa/cocoa_ogl.h index 7c9534989c..a238fbce63 100644 --- a/src/video/cocoa/cocoa_ogl.h +++ b/src/video/cocoa/cocoa_ogl.h @@ -20,12 +20,12 @@ class VideoDriver_CocoaOpenGL : public VideoDriver_Cocoa { uint8_t *anim_buffer; ///< Animation buffer from OpenGL back-end. std::string driver_info; ///< Information string about selected driver. - const char *AllocateContext(bool allow_software); + std::optional AllocateContext(bool allow_software); public: VideoDriver_CocoaOpenGL() : VideoDriver_Cocoa(true), gl_context(nullptr), anim_buffer(nullptr), driver_info(this->GetName()) {} - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; bool HasEfficient8Bpp() const override { return true; } @@ -40,9 +40,9 @@ public: uint8_t *GetAnimBuffer() override { return this->anim_buffer; } /** Return driver name */ - const char *GetName() const override { return "cocoa-opengl"; } + std::string_view GetName() const override { return "cocoa-opengl"; } - const char *GetInfoString() const override { return this->driver_info.c_str(); } + std::string_view GetInfoString() const override { return this->driver_info; } void AllocateBackingStore(bool force = false) override; diff --git a/src/video/cocoa/cocoa_ogl.mm b/src/video/cocoa/cocoa_ogl.mm index a5fe9badeb..4b6cdc68c1 100644 --- a/src/video/cocoa/cocoa_ogl.mm +++ b/src/video/cocoa/cocoa_ogl.mm @@ -185,10 +185,10 @@ static bool _allowSoftware; static FVideoDriver_CocoaOpenGL iFVideoDriver_CocoaOpenGL; -const char *VideoDriver_CocoaOpenGL::Start(const StringList ¶m) +std::optional VideoDriver_CocoaOpenGL::Start(const StringList ¶m) { - const char *err = this->Initialize(); - if (err != nullptr) return err; + auto err = this->Initialize(); + if (err) return err; int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth(); if (bpp != 8 && bpp != 32) { @@ -198,7 +198,7 @@ const char *VideoDriver_CocoaOpenGL::Start(const StringList ¶m) /* Try to allocate GL context. */ err = this->AllocateContext(GetDriverParamBool(param, "software")); - if (err != nullptr) { + if (err) { this->Stop(); return err; } @@ -224,7 +224,7 @@ const char *VideoDriver_CocoaOpenGL::Start(const StringList ¶m) this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread"); - return nullptr; + return std::nullopt; } @@ -252,7 +252,7 @@ void VideoDriver_CocoaOpenGL::ClearSystemSprites() OpenGLBackend::Get()->ClearCursorCache(); } -const char *VideoDriver_CocoaOpenGL::AllocateContext(bool allow_software) +std::optional VideoDriver_CocoaOpenGL::AllocateContext(bool allow_software) { [ OTTD_CGLLayer setAllowSoftware:allow_software ]; diff --git a/src/video/cocoa/cocoa_v.h b/src/video/cocoa/cocoa_v.h index 06356018b0..edfa39646d 100644 --- a/src/video/cocoa/cocoa_v.h +++ b/src/video/cocoa/cocoa_v.h @@ -72,7 +72,7 @@ protected: void GameSizeChanged(); - const char *Initialize(); + std::optional Initialize(); void UpdateVideoModes(); @@ -109,11 +109,11 @@ public: VideoDriver_CocoaQuartz(); - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; /** Return driver name */ - const char *GetName() const override { return "cocoa"; } + std::string_view GetName() const override { return "cocoa"; } void AllocateBackingStore(bool force = false) override; diff --git a/src/video/cocoa/cocoa_v.mm b/src/video/cocoa/cocoa_v.mm index 7ba8314bab..7b08367cdc 100644 --- a/src/video/cocoa/cocoa_v.mm +++ b/src/video/cocoa/cocoa_v.mm @@ -122,7 +122,7 @@ void VideoDriver_Cocoa::Stop() } /** Common driver initialization. */ -const char *VideoDriver_Cocoa::Initialize() +std::optional VideoDriver_Cocoa::Initialize() { if (!MacOSVersionIsAtLeast(10, 7, 0)) return "The Cocoa video driver requires Mac OS X 10.7 or later."; @@ -130,12 +130,12 @@ const char *VideoDriver_Cocoa::Initialize() _cocoa_video_started = true; /* Don't create a window or enter fullscreen if we're just going to show a dialog. */ - if (!CocoaSetupApplication()) return nullptr; + if (!CocoaSetupApplication()) return std::nullopt; this->UpdateAutoResolution(); this->orig_res = _cur_resolution; - return nullptr; + return std::nullopt; } /** @@ -589,10 +589,10 @@ VideoDriver_CocoaQuartz::VideoDriver_CocoaQuartz() this->cgcontext = nullptr; } -const char *VideoDriver_CocoaQuartz::Start(const StringList ¶m) +std::optional VideoDriver_CocoaQuartz::Start(const StringList ¶m) { - const char *err = this->Initialize(); - if (err != nullptr) return err; + auto err = this->Initialize(); + if (err) return err; int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth(); if (bpp != 8 && bpp != 32) { @@ -615,7 +615,7 @@ const char *VideoDriver_CocoaQuartz::Start(const StringList ¶m) this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread"); - return nullptr; + return std::nullopt; } diff --git a/src/video/dedicated_v.cpp b/src/video/dedicated_v.cpp index 06998d1bf1..c0c0fa2278 100644 --- a/src/video/dedicated_v.cpp +++ b/src/video/dedicated_v.cpp @@ -103,7 +103,7 @@ extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, Detaile static FVideoDriver_Dedicated iFVideoDriver_Dedicated; -const char *VideoDriver_Dedicated::Start(const StringList &) +std::optional VideoDriver_Dedicated::Start(const StringList &) { this->UpdateAutoResolution(); @@ -131,7 +131,7 @@ const char *VideoDriver_Dedicated::Start(const StringList &) #endif Debug(driver, 1, "Loading dedicated server"); - return nullptr; + return std::nullopt; } void VideoDriver_Dedicated::Stop() diff --git a/src/video/dedicated_v.h b/src/video/dedicated_v.h index 54e2dd402b..f1271075d8 100644 --- a/src/video/dedicated_v.h +++ b/src/video/dedicated_v.h @@ -15,7 +15,7 @@ /** The dedicated server video driver. */ class VideoDriver_Dedicated : public VideoDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -26,7 +26,7 @@ public: bool ChangeResolution(int w, int h) override; bool ToggleFullscreen(bool fullscreen) override; - const char *GetName() const override { return "dedicated"; } + std::string_view GetName() const override { return "dedicated"; } bool HasGUI() const override { return false; } }; diff --git a/src/video/null_v.cpp b/src/video/null_v.cpp index c1e2c5396b..e3a032d71f 100644 --- a/src/video/null_v.cpp +++ b/src/video/null_v.cpp @@ -19,7 +19,7 @@ /** Factory for the null video driver. */ static FVideoDriver_Null iFVideoDriver_Null; -const char *VideoDriver_Null::Start(const StringList &parm) +std::optional VideoDriver_Null::Start(const StringList &parm) { #ifdef _MSC_VER /* Disable the MSVC assertion message box. */ @@ -39,7 +39,7 @@ const char *VideoDriver_Null::Start(const StringList &parm) /* Do not render, nor blit */ Debug(misc, 1, "Forcing blitter 'null'..."); BlitterFactory::SelectBlitter("null"); - return nullptr; + return std::nullopt; } void VideoDriver_Null::Stop() { } diff --git a/src/video/null_v.h b/src/video/null_v.h index ee83de7e65..4e0caffc57 100644 --- a/src/video/null_v.h +++ b/src/video/null_v.h @@ -18,7 +18,7 @@ private: uint ticks; ///< Amount of ticks to run. public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -29,7 +29,7 @@ public: bool ChangeResolution(int w, int h) override; bool ToggleFullscreen(bool fullscreen) override; - const char *GetName() const override { return "null"; } + std::string_view GetName() const override { return "null"; } bool HasGUI() const override { return false; } }; diff --git a/src/video/opengl.cpp b/src/video/opengl.cpp index ee9883c169..5b49f34126 100644 --- a/src/video/opengl.cpp +++ b/src/video/opengl.cpp @@ -462,9 +462,9 @@ void SetupDebugOutput() * Create and initialize the singleton back-end class. * @param get_proc Callback to get an OpenGL function from the OS driver. * @param screen_res Current display resolution. - * @return nullptr on success, error message otherwise. + * @return std::nullopt on success, error message otherwise. */ -/* static */ const char *OpenGLBackend::Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res) +/* static */ std::optional OpenGLBackend::Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res) { if (OpenGLBackend::instance != nullptr) OpenGLBackend::Destroy(); @@ -520,9 +520,9 @@ OpenGLBackend::~OpenGLBackend() /** * Check for the needed OpenGL functionality and allocate all resources. * @param screen_res Current display resolution. - * @return Error string or nullptr if successful. + * @return Error string or std::nullopt if successful. */ -const char *OpenGLBackend::Init(const Dimension &screen_res) +std::optional OpenGLBackend::Init(const Dimension &screen_res) { if (!BindBasicInfoProcs()) return "OpenGL not supported"; @@ -729,7 +729,7 @@ const char *OpenGLBackend::Init(const Dimension &screen_res) this->PrepareContext(); (void)_glGetError(); // Clear errors. - return nullptr; + return std::nullopt; } void OpenGLBackend::PrepareContext() diff --git a/src/video/opengl.h b/src/video/opengl.h index 9354afa1aa..b143039b40 100644 --- a/src/video/opengl.h +++ b/src/video/opengl.h @@ -72,7 +72,7 @@ private: OpenGLBackend(); ~OpenGLBackend(); - const char *Init(const Dimension &screen_res); + std::optional Init(const Dimension &screen_res); bool InitShaders(); void InternalClearCursorCache(); @@ -85,7 +85,7 @@ public: { return OpenGLBackend::instance; } - static const char *Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res); + static std::optional Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res); static void Destroy(); void PrepareContext(); diff --git a/src/video/sdl2_default_v.h b/src/video/sdl2_default_v.h index 3e1e3b894c..066aa5e056 100644 --- a/src/video/sdl2_default_v.h +++ b/src/video/sdl2_default_v.h @@ -15,7 +15,7 @@ /** The SDL video driver using default SDL backend. */ class VideoDriver_SDL_Default : public VideoDriver_SDL_Base { public: - const char *GetName() const override { return "sdl"; } + std::string_view GetName() const override { return "sdl"; } protected: bool AllocateBackingStore(int w, int h, bool force = false) override; diff --git a/src/video/sdl2_opengl_v.cpp b/src/video/sdl2_opengl_v.cpp index ac5ceb0361..eec52ef825 100644 --- a/src/video/sdl2_opengl_v.cpp +++ b/src/video/sdl2_opengl_v.cpp @@ -53,13 +53,13 @@ bool VideoDriver_SDL_OpenGL::CreateMainWindow(uint w, uint h, uint flags) return this->VideoDriver_SDL_Base::CreateMainWindow(w, h, flags | SDL_WINDOW_OPENGL); } -const char *VideoDriver_SDL_OpenGL::Start(const StringList ¶m) +std::optional VideoDriver_SDL_OpenGL::Start(const StringList ¶m) { - const char *error = VideoDriver_SDL_Base::Start(param); - if (error != nullptr) return error; + auto error = VideoDriver_SDL_Base::Start(param); + if (error) return error; error = this->AllocateContext(); - if (error != nullptr) { + if (error) { this->Stop(); return error; } @@ -81,7 +81,7 @@ const char *VideoDriver_SDL_OpenGL::Start(const StringList ¶m) /* Main loop expects to start with the buffer unmapped. */ this->ReleaseVideoPointer(); - return nullptr; + return std::nullopt; } void VideoDriver_SDL_OpenGL::Stop() @@ -105,7 +105,7 @@ void VideoDriver_SDL_OpenGL::ToggleVsync(bool vsync) SDL_GL_SetSwapInterval(vsync); } -const char *VideoDriver_SDL_OpenGL::AllocateContext() +std::optional VideoDriver_SDL_OpenGL::AllocateContext() { SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); diff --git a/src/video/sdl2_opengl_v.h b/src/video/sdl2_opengl_v.h index 23b204ed5d..b1e2f09f04 100644 --- a/src/video/sdl2_opengl_v.h +++ b/src/video/sdl2_opengl_v.h @@ -14,7 +14,7 @@ class VideoDriver_SDL_OpenGL : public VideoDriver_SDL_Base { public: VideoDriver_SDL_OpenGL() : VideoDriver_SDL_Base(true), gl_context(nullptr), anim_buffer(nullptr) {} - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -31,7 +31,7 @@ public: void ToggleVsync(bool vsync) override; - const char *GetName() const override { return "sdl-opengl"; } + std::string_view GetName() const override { return "sdl-opengl"; } protected: bool AllocateBackingStore(int w, int h, bool force = false) override; @@ -44,7 +44,7 @@ private: void *gl_context; ///< OpenGL context. uint8_t *anim_buffer; ///< Animation buffer from OpenGL back-end. - const char *AllocateContext(); + std::optional AllocateContext(); void DestroyContext(); }; diff --git a/src/video/sdl2_v.cpp b/src/video/sdl2_v.cpp index eb8791a02b..31d7411c44 100644 --- a/src/video/sdl2_v.cpp +++ b/src/video/sdl2_v.cpp @@ -503,34 +503,34 @@ bool VideoDriver_SDL_Base::PollEvent() return true; } -static const char *InitializeSDL() +static std::optional InitializeSDL() { /* Check if the video-driver is already initialized. */ - if (SDL_WasInit(SDL_INIT_VIDEO) != 0) return nullptr; + if (SDL_WasInit(SDL_INIT_VIDEO) != 0) return std::nullopt; if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) return SDL_GetError(); - return nullptr; + return std::nullopt; } -const char *VideoDriver_SDL_Base::Initialize() +std::optional VideoDriver_SDL_Base::Initialize() { this->UpdateAutoResolution(); - const char *error = InitializeSDL(); - if (error != nullptr) return error; + auto error = InitializeSDL(); + if (error) return error; FindResolutions(); Debug(driver, 2, "Resolution for display: {}x{}", _cur_resolution.width, _cur_resolution.height); - return nullptr; + return std::nullopt; } -const char *VideoDriver_SDL_Base::Start(const StringList ¶m) +std::optional VideoDriver_SDL_Base::Start(const StringList ¶m) { if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported"; - const char *error = this->Initialize(); - if (error != nullptr) return error; + auto error = this->Initialize(); + if (error) return error; #ifdef SDL_HINT_MOUSE_AUTO_CAPTURE if (GetDriverParamBool(param, "no_mouse_capture")) { @@ -566,7 +566,7 @@ const char *VideoDriver_SDL_Base::Start(const StringList ¶m) this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread"); #endif - return nullptr; + return std::nullopt; } void VideoDriver_SDL_Base::Stop() diff --git a/src/video/sdl2_v.h b/src/video/sdl2_v.h index dbc57c9e5b..45c064d0bc 100644 --- a/src/video/sdl2_v.h +++ b/src/video/sdl2_v.h @@ -19,7 +19,7 @@ class VideoDriver_SDL_Base : public VideoDriver { public: VideoDriver_SDL_Base(bool uses_hardware_acceleration = false) : VideoDriver(uses_hardware_acceleration), sdl_window(nullptr), buffer_locked(false) {} - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -41,7 +41,7 @@ public: std::vector GetListOfMonitorRefreshRates() override; - const char *GetInfoString() const override { return this->driver_info.c_str(); } + std::string_view GetInfoString() const override { return this->driver_info; } protected: struct SDL_Window *sdl_window; ///< Main SDL window. @@ -73,7 +73,7 @@ private: void LoopOnce(); void MainLoopCleanup(); bool CreateMainSurface(uint w, uint h, bool resize); - const char *Initialize(); + std::optional Initialize(); #ifdef __EMSCRIPTEN__ /* Convert a constant pointer back to a non-constant pointer to a member function. */ diff --git a/src/video/sdl_v.cpp b/src/video/sdl_v.cpp index 7928deedb2..c4f53ec9c8 100644 --- a/src/video/sdl_v.cpp +++ b/src/video/sdl_v.cpp @@ -576,7 +576,7 @@ bool VideoDriver_SDL::PollEvent() return true; } -const char *VideoDriver_SDL::Start(const StringList ¶m) +std::optional VideoDriver_SDL::Start(const StringList ¶m) { char buf[30]; _use_hwpalette = GetDriverParamInt(param, "hw_palette", 2); @@ -607,7 +607,7 @@ const char *VideoDriver_SDL::Start(const StringList ¶m) this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread"); - return nullptr; + return std::nullopt; } void VideoDriver_SDL::SetupKeyboard() diff --git a/src/video/sdl_v.h b/src/video/sdl_v.h index 2b37cbdb6a..ca7c37b94a 100644 --- a/src/video/sdl_v.h +++ b/src/video/sdl_v.h @@ -15,7 +15,7 @@ /** The SDL video driver. */ class VideoDriver_SDL : public VideoDriver { public: - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -31,7 +31,7 @@ public: bool ClaimMousePointer() override; - const char *GetName() const override { return "sdl"; } + std::string_view GetName() const override { return "sdl"; } protected: void InputLoop() override; diff --git a/src/video/video_driver.hpp b/src/video/video_driver.hpp index 87155d2b6a..874198d465 100644 --- a/src/video/video_driver.hpp +++ b/src/video/video_driver.hpp @@ -174,7 +174,7 @@ public: return Clamp(dpi_scale * 100, MIN_INTERFACE_SCALE, MAX_INTERFACE_SCALE); } - virtual const char *GetInfoString() const + virtual std::string_view GetInfoString() const { return this->GetName(); } diff --git a/src/video/win32_v.cpp b/src/video/win32_v.cpp index 7c055d253a..1e65ab6ac0 100644 --- a/src/video/win32_v.cpp +++ b/src/video/win32_v.cpp @@ -1030,7 +1030,7 @@ void VideoDriver_Win32Base::UnlockVideoBuffer() static FVideoDriver_Win32GDI iFVideoDriver_Win32GDI; -const char *VideoDriver_Win32GDI::Start(const StringList ¶m) +std::optional VideoDriver_Win32GDI::Start(const StringList ¶m) { if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported"; @@ -1044,7 +1044,7 @@ const char *VideoDriver_Win32GDI::Start(const StringList ¶m) this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread"); - return nullptr; + return std::nullopt; } void VideoDriver_Win32GDI::Stop() @@ -1237,9 +1237,9 @@ static OGLProc GetOGLProcAddressCallback(const char *proc) /** * Set the pixel format of a window- * @param dc Device context to set the pixel format of. - * @return nullptr on success, error message otherwise. + * @return std::nullopt on success, error message otherwise. */ -static const char *SelectPixelFormat(HDC dc) +static std::optional SelectPixelFormat(HDC dc) { PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // Size of this struct. @@ -1265,7 +1265,7 @@ static const char *SelectPixelFormat(HDC dc) if (format == 0) return "No suitable pixel format found"; if (!SetPixelFormat(dc, format, &pfd)) return "Can't set pixel format"; - return nullptr; + return std::nullopt; } /** Bind all WGL extension functions we need. */ @@ -1280,7 +1280,7 @@ static void LoadWGLExtensions() HDC dc = GetDC(wnd); /* Set pixel format of the window. */ - if (SelectPixelFormat(dc) == nullptr) { + if (SelectPixelFormat(dc) == std::nullopt) { /* Create rendering context. */ HGLRC rc = wglCreateContext(dc); if (rc != nullptr) { @@ -1320,7 +1320,7 @@ static void LoadWGLExtensions() static FVideoDriver_Win32OpenGL iFVideoDriver_Win32OpenGL; -const char *VideoDriver_Win32OpenGL::Start(const StringList ¶m) +std::optional VideoDriver_Win32OpenGL::Start(const StringList ¶m) { if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported"; @@ -1332,8 +1332,8 @@ const char *VideoDriver_Win32OpenGL::Start(const StringList ¶m) this->MakeWindow(_fullscreen); /* Create and initialize OpenGL context. */ - const char *err = this->AllocateContext(); - if (err != nullptr) { + auto err = this->AllocateContext(); + if (err) { this->Stop(); _cur_resolution = old_res; return err; @@ -1358,7 +1358,7 @@ const char *VideoDriver_Win32OpenGL::Start(const StringList ¶m) this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread"); - return nullptr; + return std::nullopt; } void VideoDriver_Win32OpenGL::Stop() @@ -1391,12 +1391,12 @@ void VideoDriver_Win32OpenGL::ToggleVsync(bool vsync) } } -const char *VideoDriver_Win32OpenGL::AllocateContext() +std::optional VideoDriver_Win32OpenGL::AllocateContext() { this->dc = GetDC(this->main_wnd); - const char *err = SelectPixelFormat(this->dc); - if (err != nullptr) return err; + auto err = SelectPixelFormat(this->dc); + if (err) return err; HGLRC rc = nullptr; @@ -1438,7 +1438,7 @@ bool VideoDriver_Win32OpenGL::ToggleFullscreen(bool full_screen) if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer(); this->DestroyContext(); bool res = this->VideoDriver_Win32Base::ToggleFullscreen(full_screen); - res &= this->AllocateContext() == nullptr; + res &= this->AllocateContext() == std::nullopt; this->ClientSizeChanged(this->width, this->height, true); return res; } diff --git a/src/video/win32_v.h b/src/video/win32_v.h index cb3bac49f8..4344910b01 100644 --- a/src/video/win32_v.h +++ b/src/video/win32_v.h @@ -79,13 +79,13 @@ class VideoDriver_Win32GDI : public VideoDriver_Win32Base { public: VideoDriver_Win32GDI() : dib_sect(nullptr), gdi_palette(nullptr), buffer_bits(nullptr) {} - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; bool AfterBlitterChange() override; - const char *GetName() const override { return "win32"; } + std::string_view GetName() const override { return "win32"; } protected: HBITMAP dib_sect; ///< System bitmap object referencing our rendering buffer. @@ -120,7 +120,7 @@ class VideoDriver_Win32OpenGL : public VideoDriver_Win32Base { public: VideoDriver_Win32OpenGL() : VideoDriver_Win32Base(true), dc(nullptr), gl_rc(nullptr), anim_buffer(nullptr), driver_info(this->GetName()) {} - const char *Start(const StringList ¶m) override; + std::optional Start(const StringList ¶m) override; void Stop() override; @@ -141,9 +141,9 @@ public: void ToggleVsync(bool vsync) override; - const char *GetName() const override { return "win32-opengl"; } + std::string_view GetName() const override { return "win32-opengl"; } - const char *GetInfoString() const override { return this->driver_info.c_str(); } + std::string_view GetInfoString() const override { return this->driver_info; } protected: HDC dc; ///< Window device context. @@ -160,7 +160,7 @@ protected: void ReleaseVideoPointer() override; void PaletteChanged(HWND) override {} - const char *AllocateContext(); + std::optional AllocateContext(); void DestroyContext(); }; From 6bc4a62c27128e248790c4e7fa57be3e4228bde9 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Tue, 9 Apr 2024 23:35:50 +0100 Subject: [PATCH 02/11] Codechange: Pass std::string_view from blitters instead of char *. --- src/blitter/32bpp_anim.hpp | 2 +- src/blitter/32bpp_anim_sse2.hpp | 2 +- src/blitter/32bpp_anim_sse4.hpp | 2 +- src/blitter/32bpp_optimized.hpp | 2 +- src/blitter/32bpp_simple.hpp | 2 +- src/blitter/32bpp_sse2.hpp | 2 +- src/blitter/32bpp_sse4.hpp | 2 +- src/blitter/32bpp_ssse3.hpp | 2 +- src/blitter/40bpp_anim.hpp | 2 +- src/blitter/8bpp_optimized.hpp | 2 +- src/blitter/8bpp_simple.hpp | 2 +- src/blitter/base.hpp | 2 +- src/blitter/factory.hpp | 4 ++-- src/blitter/null.hpp | 2 +- 14 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/blitter/32bpp_anim.hpp b/src/blitter/32bpp_anim.hpp index b5b19d784e..975a9bfd62 100644 --- a/src/blitter/32bpp_anim.hpp +++ b/src/blitter/32bpp_anim.hpp @@ -47,7 +47,7 @@ public: void PaletteAnimate(const Palette &palette) override; Blitter::PaletteAnimation UsePaletteAnimation() override; - const char *GetName() override { return "32bpp-anim"; } + std::string_view GetName() override { return "32bpp-anim"; } void PostResize() override; /** diff --git a/src/blitter/32bpp_anim_sse2.hpp b/src/blitter/32bpp_anim_sse2.hpp index 669cef80a7..56262e387f 100644 --- a/src/blitter/32bpp_anim_sse2.hpp +++ b/src/blitter/32bpp_anim_sse2.hpp @@ -31,7 +31,7 @@ class Blitter_32bppSSE2_Anim : public Blitter_32bppAnim { public: void PaletteAnimate(const Palette &palette) override; - const char *GetName() override { return "32bpp-sse2-anim"; } + std::string_view GetName() override { return "32bpp-sse2-anim"; } }; /** Factory for the partially 32bpp blitter with animation. */ diff --git a/src/blitter/32bpp_anim_sse4.hpp b/src/blitter/32bpp_anim_sse4.hpp index d11c90d341..b787c14e06 100644 --- a/src/blitter/32bpp_anim_sse4.hpp +++ b/src/blitter/32bpp_anim_sse4.hpp @@ -42,7 +42,7 @@ public: Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator) override { return Blitter_32bppSSE_Base::Encode(sprite, allocator); } - const char *GetName() override { return "32bpp-sse4-anim"; } + std::string_view GetName() override { return "32bpp-sse4-anim"; } using Blitter_32bppSSE2_Anim::LookupColourInPalette; }; diff --git a/src/blitter/32bpp_optimized.hpp b/src/blitter/32bpp_optimized.hpp index 3c332ceeda..b1e076faa4 100644 --- a/src/blitter/32bpp_optimized.hpp +++ b/src/blitter/32bpp_optimized.hpp @@ -24,7 +24,7 @@ public: void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override; Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator) override; - const char *GetName() override { return "32bpp-optimized"; } + std::string_view GetName() override { return "32bpp-optimized"; } template void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom); diff --git a/src/blitter/32bpp_simple.hpp b/src/blitter/32bpp_simple.hpp index df154ce57d..8c2dc3a346 100644 --- a/src/blitter/32bpp_simple.hpp +++ b/src/blitter/32bpp_simple.hpp @@ -28,7 +28,7 @@ public: void DrawColourMappingRect(void *dst, int width, int height, PaletteID pal) override; Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator) override; - const char *GetName() override { return "32bpp-simple"; } + std::string_view GetName() override { return "32bpp-simple"; } }; /** Factory for the simple 32 bpp blitter. */ diff --git a/src/blitter/32bpp_sse2.hpp b/src/blitter/32bpp_sse2.hpp index 85bfc6e027..402c732546 100644 --- a/src/blitter/32bpp_sse2.hpp +++ b/src/blitter/32bpp_sse2.hpp @@ -92,7 +92,7 @@ public: return Blitter_32bppSSE_Base::Encode(sprite, allocator); } - const char *GetName() override { return "32bpp-sse2"; } + std::string_view GetName() override { return "32bpp-sse2"; } }; /** Factory for the SSE2 32 bpp blitter (without palette animation). */ diff --git a/src/blitter/32bpp_sse4.hpp b/src/blitter/32bpp_sse4.hpp index deb4fbed92..7d8798c697 100644 --- a/src/blitter/32bpp_sse4.hpp +++ b/src/blitter/32bpp_sse4.hpp @@ -32,7 +32,7 @@ public: void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override; template void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom); - const char *GetName() override { return "32bpp-sse4"; } + std::string_view GetName() override { return "32bpp-sse4"; } }; /** Factory for the SSE4 32 bpp blitter (without palette animation). */ diff --git a/src/blitter/32bpp_ssse3.hpp b/src/blitter/32bpp_ssse3.hpp index c95095d4df..4ee475d45f 100644 --- a/src/blitter/32bpp_ssse3.hpp +++ b/src/blitter/32bpp_ssse3.hpp @@ -32,7 +32,7 @@ public: void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override; template void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom); - const char *GetName() override { return "32bpp-ssse3"; } + std::string_view GetName() override { return "32bpp-ssse3"; } }; /** Factory for the SSSE3 32 bpp blitter (without palette animation). */ diff --git a/src/blitter/40bpp_anim.hpp b/src/blitter/40bpp_anim.hpp index 4371100914..928af303c2 100644 --- a/src/blitter/40bpp_anim.hpp +++ b/src/blitter/40bpp_anim.hpp @@ -32,7 +32,7 @@ public: Blitter::PaletteAnimation UsePaletteAnimation() override; bool NeedsAnimationBuffer() override; - const char *GetName() override { return "40bpp-anim"; } + std::string_view GetName() override { return "40bpp-anim"; } template void Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom); diff --git a/src/blitter/8bpp_optimized.hpp b/src/blitter/8bpp_optimized.hpp index f55586170d..b999676648 100644 --- a/src/blitter/8bpp_optimized.hpp +++ b/src/blitter/8bpp_optimized.hpp @@ -25,7 +25,7 @@ public: void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override; Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator) override; - const char *GetName() override { return "8bpp-optimized"; } + std::string_view GetName() override { return "8bpp-optimized"; } }; /** Factory for the 8bpp blitter optimised for speed. */ diff --git a/src/blitter/8bpp_simple.hpp b/src/blitter/8bpp_simple.hpp index 23d49d7f91..eebccac158 100644 --- a/src/blitter/8bpp_simple.hpp +++ b/src/blitter/8bpp_simple.hpp @@ -19,7 +19,7 @@ public: void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override; Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator) override; - const char *GetName() override { return "8bpp-simple"; } + std::string_view GetName() override { return "8bpp-simple"; } }; /** Factory for the most trivial 8bpp blitter. */ diff --git a/src/blitter/base.hpp b/src/blitter/base.hpp index 9d79107bd3..24ccc3ac13 100644 --- a/src/blitter/base.hpp +++ b/src/blitter/base.hpp @@ -197,7 +197,7 @@ public: /** * Get the name of the blitter, the same as the Factory-instance returns. */ - virtual const char *GetName() = 0; + virtual std::string_view GetName() = 0; /** * Post resize event diff --git a/src/blitter/factory.hpp b/src/blitter/factory.hpp index 4daa4c42cd..5071a168ae 100644 --- a/src/blitter/factory.hpp +++ b/src/blitter/factory.hpp @@ -159,7 +159,7 @@ public: /** * Get the long, human readable, name for the Blitter-class. */ - const std::string &GetName() const + std::string_view GetName() const { return this->name; } @@ -167,7 +167,7 @@ public: /** * Get a nice description of the blitter-class. */ - const std::string &GetDescription() const + std::string_view GetDescription() const { return this->description; } diff --git a/src/blitter/null.hpp b/src/blitter/null.hpp index 61c5cab9de..5f5ed81646 100644 --- a/src/blitter/null.hpp +++ b/src/blitter/null.hpp @@ -31,7 +31,7 @@ public: void PaletteAnimate(const Palette &) override { }; Blitter::PaletteAnimation UsePaletteAnimation() override { return Blitter::PALETTE_ANIMATION_NONE; }; - const char *GetName() override { return "null"; } + std::string_view GetName() override { return "null"; } }; /** Factory for the blitter that does nothing. */ From 442daf58da862acc6a1f25415cd0eb34977d844b Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Wed, 10 Apr 2024 20:12:33 +0200 Subject: [PATCH 03/11] Codechange: replace lengthof with std::size in Windows specific code --- src/fileio.cpp | 2 +- src/music/dmusic.cpp | 4 ++-- src/network/core/http_winhttp.cpp | 8 ++++---- src/network/core/os_abstraction.cpp | 2 +- src/os/windows/library_loader_win.cpp | 2 +- src/os/windows/win32.cpp | 16 ++++++++-------- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/fileio.cpp b/src/fileio.cpp index fc892ed242..db2db572b0 100644 --- a/src/fileio.cpp +++ b/src/fileio.cpp @@ -203,7 +203,7 @@ static FILE *FioFOpenFileSp(const std::string &filename, const char *mode, Searc * a string, but a variable, it 'renames' the variable, * so make that variable to makes it compile happily */ wchar_t Lmode[5]; - MultiByteToWideChar(CP_ACP, 0, mode, -1, Lmode, lengthof(Lmode)); + MultiByteToWideChar(CP_ACP, 0, mode, -1, Lmode, static_cast(std::size(Lmode))); #endif FILE *f = nullptr; std::string buf; diff --git a/src/music/dmusic.cpp b/src/music/dmusic.cpp index 8d0919ceb3..c7c2d97642 100644 --- a/src/music/dmusic.cpp +++ b/src/music/dmusic.cpp @@ -870,7 +870,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls) DWORD buf_size = sizeof(dls_path); // Buffer size as to be given in bytes! if (SUCCEEDED(RegQueryValueEx(hkDM, L"GMFilePath", nullptr, nullptr, (LPBYTE)dls_path, &buf_size))) { wchar_t expand_path[MAX_PATH * 2]; - ExpandEnvironmentStrings(dls_path, expand_path, lengthof(expand_path)); + ExpandEnvironmentStrings(dls_path, expand_path, static_cast(std::size(expand_path))); if (!dls_file.LoadFile(expand_path)) Debug(driver, 1, "Failed to load default GM DLS file from registry"); } RegCloseKey(hkDM); @@ -880,7 +880,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls) if (dls_file.instruments.empty()) { static const wchar_t *DLS_GM_FILE = L"%windir%\\System32\\drivers\\gm.dls"; wchar_t path[MAX_PATH]; - ExpandEnvironmentStrings(DLS_GM_FILE, path, lengthof(path)); + ExpandEnvironmentStrings(DLS_GM_FILE, path, static_cast(std::size(path))); if (!dls_file.LoadFile(path)) return "Can't load GM DLS collection"; } diff --git a/src/network/core/http_winhttp.cpp b/src/network/core/http_winhttp.cpp index 0efcbe69df..ccba25ee62 100644 --- a/src/network/core/http_winhttp.cpp +++ b/src/network/core/http_winhttp.cpp @@ -78,7 +78,7 @@ static std::string GetLastErrorAsString() DWORD error_code = GetLastError(); if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS, GetModuleHandle(L"winhttp.dll"), error_code, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, lengthof(buffer), nullptr) == 0) { + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, static_cast(std::size(buffer)), nullptr) == 0) { return fmt::format("unknown error {}", error_code); } @@ -222,11 +222,11 @@ void NetworkHTTPRequest::Connect() /* Convert the URL to its components. */ url_components.dwStructSize = sizeof(url_components); url_components.lpszScheme = scheme; - url_components.dwSchemeLength = lengthof(scheme); + url_components.dwSchemeLength = static_cast(std::size(scheme)); url_components.lpszHostName = hostname; - url_components.dwHostNameLength = lengthof(hostname); + url_components.dwHostNameLength = static_cast(std::size(hostname)); url_components.lpszUrlPath = url_path; - url_components.dwUrlPathLength = lengthof(url_path); + url_components.dwUrlPathLength = static_cast(std::size(url_path)); WinHttpCrackUrl(this->uri.c_str(), 0, 0, &url_components); /* Create the HTTP connection. */ diff --git a/src/network/core/os_abstraction.cpp b/src/network/core/os_abstraction.cpp index 97647a4165..023fe5b116 100644 --- a/src/network/core/os_abstraction.cpp +++ b/src/network/core/os_abstraction.cpp @@ -83,7 +83,7 @@ const std::string &NetworkError::AsString() const #if defined(_WIN32) wchar_t buffer[512]; if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, this->error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, lengthof(buffer), nullptr) == 0) { + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, static_cast(std::size(buffer)), nullptr) == 0) { this->message.assign(fmt::format("Unknown error {}", this->error)); } else { this->message.assign(FS2OTTD(buffer)); diff --git a/src/os/windows/library_loader_win.cpp b/src/os/windows/library_loader_win.cpp index eea8f061f9..608b9349c9 100644 --- a/src/os/windows/library_loader_win.cpp +++ b/src/os/windows/library_loader_win.cpp @@ -22,7 +22,7 @@ static std::string GetLoadError() wchar_t buffer[512]; if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, lengthof(buffer), nullptr) == 0) { + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, static_cast(std::size(buffer)), nullptr) == 0) { return fmt::format("Unknown error {}", error_code); } diff --git a/src/os/windows/win32.cpp b/src/os/windows/win32.cpp index e5ddba94c0..18655c3d42 100644 --- a/src/os/windows/win32.cpp +++ b/src/os/windows/win32.cpp @@ -180,7 +180,7 @@ void FiosGetDrives(FileList &file_list) wchar_t drives[256]; const wchar_t *s; - GetLogicalDriveStrings(lengthof(drives), drives); + GetLogicalDriveStrings(static_cast(std::size(drives)), drives); for (s = drives; *s != '\0';) { FiosItem *fios = &file_list.emplace_back(); fios->type = FIOS_TYPE_DRIVE; @@ -400,7 +400,7 @@ void DetermineBasePaths(const char *exe) /* Use the folder of the config file as working directory. */ wchar_t config_dir[MAX_PATH]; wcsncpy(path, convert_to_fs(_config_file, path, lengthof(path)), lengthof(path)); - if (!GetFullPathName(path, lengthof(config_dir), config_dir, nullptr)) { + if (!GetFullPathName(path, static_cast(std::size(config_dir)), config_dir, nullptr)) { Debug(misc, 0, "GetFullPathName failed ({})", GetLastError()); _searchpaths[SP_WORKING_DIR].clear(); } else { @@ -412,13 +412,13 @@ void DetermineBasePaths(const char *exe) } } - if (!GetModuleFileName(nullptr, path, lengthof(path))) { + if (!GetModuleFileName(nullptr, path, static_cast(std::size(path)))) { Debug(misc, 0, "GetModuleFileName failed ({})", GetLastError()); _searchpaths[SP_BINARY_DIR].clear(); } else { wchar_t exec_dir[MAX_PATH]; - wcsncpy(path, convert_to_fs(exe, path, lengthof(path)), lengthof(path)); - if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, nullptr)) { + wcsncpy(path, convert_to_fs(exe, path, std::size(path)), std::size(path)); + if (!GetFullPathName(path, static_cast(std::size(exec_dir)), exec_dir, nullptr)) { Debug(misc, 0, "GetFullPathName failed ({})", GetLastError()); _searchpaths[SP_BINARY_DIR].clear(); } else { @@ -530,8 +530,8 @@ const char *GetCurrentLocale(const char *) const LCID userUiLocale = MAKELCID(userUiLang, SORT_DEFAULT); char lang[9], country[9]; - if (GetLocaleInfoA(userUiLocale, LOCALE_SISO639LANGNAME, lang, lengthof(lang)) == 0 || - GetLocaleInfoA(userUiLocale, LOCALE_SISO3166CTRYNAME, country, lengthof(country)) == 0) { + if (GetLocaleInfoA(userUiLocale, LOCALE_SISO639LANGNAME, lang, static_cast(std::size(lang))) == 0 || + GetLocaleInfoA(userUiLocale, LOCALE_SISO3166CTRYNAME, country, static_cast(std::size(country))) == 0) { /* Unable to retrieve the locale. */ return nullptr; } @@ -557,7 +557,7 @@ void Win32SetCurrentLocaleName(std::string iso_code) } } - MultiByteToWideChar(CP_UTF8, 0, iso_code.c_str(), -1, _cur_iso_locale, lengthof(_cur_iso_locale)); + MultiByteToWideChar(CP_UTF8, 0, iso_code.c_str(), -1, _cur_iso_locale, static_cast(std::size(_cur_iso_locale))); } int OTTDStringCompare(std::string_view s1, std::string_view s2) From 6cade18053c456512ef13fda23d690aed9276877 Mon Sep 17 00:00:00 2001 From: translators Date: Thu, 11 Apr 2024 04:41:57 +0000 Subject: [PATCH 04/11] Update: Translations from eints portuguese (brazilian): 1 change by pasantoro polish: 1 change by pAter-exe --- src/lang/brazilian_portuguese.txt | 2 +- src/lang/polish.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lang/brazilian_portuguese.txt b/src/lang/brazilian_portuguese.txt index 548f4c9894..336d63c4e9 100644 --- a/src/lang/brazilian_portuguese.txt +++ b/src/lang/brazilian_portuguese.txt @@ -188,7 +188,7 @@ STR_COLOUR_ORANGE :Laranja STR_COLOUR_BROWN :Marrom STR_COLOUR_GREY :Cinza STR_COLOUR_WHITE :Branco -STR_COLOUR_RANDOM :Aleatório +STR_COLOUR_RANDOM :Aleatória ###length 17 STR_COLOUR_SECONDARY_DARK_BLUE :Azul Escuro diff --git a/src/lang/polish.txt b/src/lang/polish.txt index 89b03df67f..3a0a8fd9fe 100644 --- a/src/lang/polish.txt +++ b/src/lang/polish.txt @@ -3921,7 +3921,7 @@ STR_NEWGRF_ERROR_MULTIPLE_ACTION_8 :Zawiera wiele w STR_NEWGRF_ERROR_READ_BOUNDS :Odczyt poza obszar pseudo-sprite'u (sprite {3:NUM}) STR_NEWGRF_ERROR_GRM_FAILED :Potrzebne źródło GRF nie jest dostępne (sprite {3:NUM}) STR_NEWGRF_ERROR_FORCEFULLY_DISABLED :{1:STRING} został wyłączony przez {STRING} -STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT :Niepoprawny/nieznany format układu sprite'u (sprite {3:NUM}) +STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT :Nieprawidłowy/nieznany format układu sprite'a (sprite {3:NUM}) STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG :Zbyt wiele elementów na liście wartości właściwości (sprite {3:NUM}, właściwość {4:HEX}) STR_NEWGRF_ERROR_INDPROD_CALLBACK :Nieprawidłowe wywołanie zwrotne produkcji przedsiębiorstwa (sprite {3:NUM}, „{2:STRING}”) From ff27b9e76a5d2c53ecdd2fde196ac609b8d176a9 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Tue, 9 Apr 2024 17:09:23 +0200 Subject: [PATCH 05/11] Codechange: use std::any_of instead of custom loop --- src/industry_gui.cpp | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/industry_gui.cpp b/src/industry_gui.cpp index e981f61daf..211bcf7e69 100644 --- a/src/industry_gui.cpp +++ b/src/industry_gui.cpp @@ -775,13 +775,7 @@ static void UpdateIndustryProduction(Industry *i); static inline bool IsProductionAlterable(const Industry *i) { const IndustrySpec *is = GetIndustrySpec(i->type); - bool has_prod = false; - for (size_t j = 0; j < lengthof(is->production_rate); j++) { - if (is->production_rate[j] != 0) { - has_prod = true; - break; - } - } + bool has_prod = std::any_of(std::begin(is->production_rate), std::end(is->production_rate), [](auto rate) { return rate != 0; }); return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) && (has_prod || is->IsRawIndustry()) && !_networking); From 2587a21400ed66647639ec0bf8761397c5720da7 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Tue, 9 Apr 2024 17:35:51 +0200 Subject: [PATCH 06/11] Codechange: use zero-initialization instead of C-style loop --- src/pathfinder/npf/queue.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/pathfinder/npf/queue.cpp b/src/pathfinder/npf/queue.cpp index 21ccd1ad9f..7bb0a06f22 100644 --- a/src/pathfinder/npf/queue.cpp +++ b/src/pathfinder/npf/queue.cpp @@ -284,11 +284,9 @@ void Hash::PrintStatistics() const uint used_buckets = 0; uint max_collision = 0; uint max_usage = 0; - uint usage[200]; - uint i; + uint usage[200] = {}; - for (i = 0; i < lengthof(usage); i++) usage[i] = 0; - for (i = 0; i < this->num_buckets; i++) { + for (uint i = 0; i < this->num_buckets; i++) { uint collision = 0; if (this->buckets_in_use[i]) { const HashNode *node; @@ -308,7 +306,7 @@ void Hash::PrintStatistics() const ); std::string line; line += "{ "; - for (i = 0; i <= max_collision; i++) { + for (uint i = 0; i <= max_collision; i++) { if (usage[i] > 0) { fmt::format_to(std::back_inserter(line), "{}:{} ", i, usage[i]); #if 0 From 4f2412a272a048b5d212f62af9e7a0b8ca5e677a Mon Sep 17 00:00:00 2001 From: Rubidium Date: Tue, 9 Apr 2024 17:18:35 +0200 Subject: [PATCH 07/11] Codechange: range based for loops instead of C-style for loops --- src/cheat_gui.cpp | 17 ++++++++--------- src/company_gui.cpp | 4 ++-- src/fileio.cpp | 16 ++++++++-------- src/fontcache/spritefontcache.cpp | 8 ++++---- src/group_gui.cpp | 4 ++-- src/linkgraph/linkgraphschedule.cpp | 8 ++++---- src/music_gui.cpp | 2 +- src/newgrf_engine.cpp | 6 +++--- src/newgrf_generic.cpp | 4 ++-- src/order_gui.cpp | 8 ++++---- src/saveload/afterload.cpp | 14 +++++++------- src/script/script_info.cpp | 4 ++-- src/settings_gui.cpp | 4 ++-- src/smallmap_gui.cpp | 8 ++++---- src/spriteloader/sprite_file.cpp | 4 ++-- src/strgen/strgen.cpp | 4 ++-- src/vehicle_gui.cpp | 4 ++-- src/video/sdl_v.cpp | 6 +++--- src/viewport.cpp | 6 +++--- 19 files changed, 65 insertions(+), 66 deletions(-) diff --git a/src/cheat_gui.cpp b/src/cheat_gui.cpp index 9bafd9120c..1e7dbaa3d2 100644 --- a/src/cheat_gui.cpp +++ b/src/cheat_gui.cpp @@ -303,33 +303,32 @@ struct CheatWindow : Window { if (widget != WID_C_PANEL) return; uint width = 0; - for (int i = 0; i != lengthof(_cheats_ui); i++) { - const CheatEntry *ce = &_cheats_ui[i]; - switch (ce->type) { + for (const auto &ce : _cheats_ui) { + switch (ce.type) { case SLE_BOOL: SetDParam(0, STR_CONFIG_SETTING_ON); - width = std::max(width, GetStringBoundingBox(ce->str).width); + width = std::max(width, GetStringBoundingBox(ce.str).width); SetDParam(0, STR_CONFIG_SETTING_OFF); - width = std::max(width, GetStringBoundingBox(ce->str).width); + width = std::max(width, GetStringBoundingBox(ce.str).width); break; default: - switch (ce->str) { + switch (ce.str) { /* Display date for change date cheat */ case STR_CHEAT_CHANGE_DATE: SetDParam(0, TimerGameCalendar::ConvertYMDToDate(CalendarTime::MAX_YEAR, 11, 31)); - width = std::max(width, GetStringBoundingBox(ce->str).width); + width = std::max(width, GetStringBoundingBox(ce.str).width); break; /* Draw coloured flag for change company cheat */ case STR_CHEAT_CHANGE_COMPANY: SetDParamMaxValue(0, MAX_COMPANIES); - width = std::max(width, GetStringBoundingBox(ce->str).width + WidgetDimensions::scaled.hsep_wide); + width = std::max(width, GetStringBoundingBox(ce.str).width + WidgetDimensions::scaled.hsep_wide); break; default: SetDParam(0, INT64_MAX); - width = std::max(width, GetStringBoundingBox(ce->str).width); + width = std::max(width, GetStringBoundingBox(ce.str).width); break; } break; diff --git a/src/company_gui.cpp b/src/company_gui.cpp index c0a2ba6094..2e387b4996 100644 --- a/src/company_gui.cpp +++ b/src/company_gui.cpp @@ -2272,8 +2272,8 @@ struct CompanyWindow : Window case WID_C_DESC_VEHICLE_COUNTS: SetDParamMaxValue(0, 5000); // Maximum number of vehicles - for (uint i = 0; i < lengthof(_company_view_vehicle_count_strings); i++) { - size.width = std::max(size.width, GetStringBoundingBox(_company_view_vehicle_count_strings[i]).width + padding.width); + for (const auto &count_string : _company_view_vehicle_count_strings) { + size.width = std::max(size.width, GetStringBoundingBox(count_string).width + padding.width); } break; diff --git a/src/fileio.cpp b/src/fileio.cpp index db2db572b0..e2c7281513 100644 --- a/src/fileio.cpp +++ b/src/fileio.cpp @@ -1008,9 +1008,9 @@ void DeterminePaths(const char *exe, bool only_local_path) }; config_dir.clear(); - for (uint i = 0; i < lengthof(new_openttd_cfg_order); i++) { - if (IsValidSearchPath(new_openttd_cfg_order[i])) { - config_dir = _searchpaths[new_openttd_cfg_order[i]]; + for (const auto &searchpath : new_openttd_cfg_order) { + if (IsValidSearchPath(searchpath)) { + config_dir = _searchpaths[searchpath]; break; } } @@ -1061,8 +1061,8 @@ void DeterminePaths(const char *exe, bool only_local_path) SAVE_DIR, AUTOSAVE_DIR, SCENARIO_DIR, HEIGHTMAP_DIR, BASESET_DIR, NEWGRF_DIR, AI_DIR, AI_LIBRARY_DIR, GAME_DIR, GAME_LIBRARY_DIR, SCREENSHOT_DIR, SOCIAL_INTEGRATION_DIR }; - for (uint i = 0; i < lengthof(default_subdirs); i++) { - FioCreateDirectory(_personal_dir + _subdirs[default_subdirs[i]]); + for (const auto &default_subdir : default_subdirs) { + FioCreateDirectory(_personal_dir + _subdirs[default_subdir]); } /* If we have network we make a directory for the autodownloading of content */ @@ -1072,9 +1072,9 @@ void DeterminePaths(const char *exe, bool only_local_path) FillValidSearchPaths(only_local_path); /* Create the directory for each of the types of content */ - const Subdirectory dirs[] = { SCENARIO_DIR, HEIGHTMAP_DIR, BASESET_DIR, NEWGRF_DIR, AI_DIR, AI_LIBRARY_DIR, GAME_DIR, GAME_LIBRARY_DIR, SOCIAL_INTEGRATION_DIR }; - for (uint i = 0; i < lengthof(dirs); i++) { - FioCreateDirectory(FioGetDirectory(SP_AUTODOWNLOAD_DIR, dirs[i])); + const Subdirectory subdirs[] = { SCENARIO_DIR, HEIGHTMAP_DIR, BASESET_DIR, NEWGRF_DIR, AI_DIR, AI_LIBRARY_DIR, GAME_DIR, GAME_LIBRARY_DIR, SOCIAL_INTEGRATION_DIR }; + for (const auto &subdir : subdirs) { + FioCreateDirectory(FioGetDirectory(SP_AUTODOWNLOAD_DIR, subdir)); } extern std::string _log_file; diff --git a/src/fontcache/spritefontcache.cpp b/src/fontcache/spritefontcache.cpp index 264a691526..d9ad15d55e 100644 --- a/src/fontcache/spritefontcache.cpp +++ b/src/fontcache/spritefontcache.cpp @@ -84,16 +84,16 @@ void SpriteFontCache::InitializeUnicodeGlyphMap() this->SetUnicodeGlyph(i + SCC_SPRITE_START, sprite); } - for (uint i = 0; i < lengthof(_default_unicode_map); i++) { - uint8_t key = _default_unicode_map[i].key; + for (const auto &unicode_map : _default_unicode_map) { + uint8_t key = unicode_map.key; if (key == CLRA) { /* Clear the glyph. This happens if the glyph at this code point * is non-standard and should be accessed by an SCC_xxx enum * entry only. */ - this->SetUnicodeGlyph(_default_unicode_map[i].code, 0); + this->SetUnicodeGlyph(unicode_map.code, 0); } else { SpriteID sprite = base + key - ASCII_LETTERSTART; - this->SetUnicodeGlyph(_default_unicode_map[i].code, sprite); + this->SetUnicodeGlyph(unicode_map.code, sprite); } } } diff --git a/src/group_gui.cpp b/src/group_gui.cpp index c4b3998102..40924c18d8 100644 --- a/src/group_gui.cpp +++ b/src/group_gui.cpp @@ -240,8 +240,8 @@ private: this->column_size[VGC_PROFIT].width = 0; this->column_size[VGC_PROFIT].height = 0; static const SpriteID profit_sprites[] = {SPR_PROFIT_NA, SPR_PROFIT_NEGATIVE, SPR_PROFIT_SOME, SPR_PROFIT_LOT}; - for (uint i = 0; i < lengthof(profit_sprites); i++) { - Dimension d = GetSpriteSize(profit_sprites[i]); + for (const auto &profit_sprite : profit_sprites) { + Dimension d = GetSpriteSize(profit_sprite); this->column_size[VGC_PROFIT] = maxdim(this->column_size[VGC_PROFIT], d); } this->tiny_step_height = std::max(this->tiny_step_height, this->column_size[VGC_PROFIT].height); diff --git a/src/linkgraph/linkgraphschedule.cpp b/src/linkgraph/linkgraphschedule.cpp index aef287c439..d03300ad98 100644 --- a/src/linkgraph/linkgraphschedule.cpp +++ b/src/linkgraph/linkgraphschedule.cpp @@ -86,9 +86,9 @@ void LinkGraphSchedule::JoinNext() */ /* static */ void LinkGraphSchedule::Run(LinkGraphJob *job) { - for (uint i = 0; i < lengthof(instance.handlers); ++i) { + for (const auto &handler : instance.handlers) { if (job->IsJobAborted()) return; - instance.handlers[i]->Run(*job); + handler->Run(*job); } /* @@ -157,8 +157,8 @@ LinkGraphSchedule::LinkGraphSchedule() LinkGraphSchedule::~LinkGraphSchedule() { this->Clear(); - for (uint i = 0; i < lengthof(this->handlers); ++i) { - delete this->handlers[i]; + for (const auto &handler : this->handlers) { + delete handler; } } diff --git a/src/music_gui.cpp b/src/music_gui.cpp index 36817ae150..c31bfca711 100644 --- a/src/music_gui.cpp +++ b/src/music_gui.cpp @@ -106,7 +106,7 @@ void MusicSystem::BuildPlaylists() const MusicSet *set = BaseMusic::GetUsedSet(); /* Clear current playlists */ - for (size_t i = 0; i < lengthof(this->standard_playlists); ++i) this->standard_playlists[i].clear(); + for (auto &playlist : this->standard_playlists) playlist.clear(); this->music_set.clear(); /* Build standard playlists, and a list of available music */ diff --git a/src/newgrf_engine.cpp b/src/newgrf_engine.cpp index 1739835475..08e461d06c 100644 --- a/src/newgrf_engine.cpp +++ b/src/newgrf_engine.cpp @@ -1394,11 +1394,11 @@ void FillNewGRFVehicleCache(const Vehicle *v) static_assert(NCVV_END == lengthof(cache_entries)); /* Resolve all the variables, so their caches are set. */ - for (size_t i = 0; i < lengthof(cache_entries); i++) { + for (const auto &cache_entry : cache_entries) { /* Only resolve when the cache isn't valid. */ - if (HasBit(v->grf_cache.cache_valid, cache_entries[i][1])) continue; + if (HasBit(v->grf_cache.cache_valid, cache_entry[1])) continue; bool stub; - ro.GetScope(VSG_SCOPE_SELF)->GetVariable(cache_entries[i][0], 0, &stub); + ro.GetScope(VSG_SCOPE_SELF)->GetVariable(cache_entry[0], 0, &stub); } /* Make sure really all bits are set. */ diff --git a/src/newgrf_generic.cpp b/src/newgrf_generic.cpp index 6b4dcf2fbb..30e3d840fe 100644 --- a/src/newgrf_generic.cpp +++ b/src/newgrf_generic.cpp @@ -93,8 +93,8 @@ static GenericCallbackList _gcl[GSF_END]; */ void ResetGenericCallbacks() { - for (uint8_t feature = 0; feature < lengthof(_gcl); feature++) { - _gcl[feature].clear(); + for (auto &gcl : _gcl) { + gcl.clear(); } } diff --git a/src/order_gui.cpp b/src/order_gui.cpp index 44979fd75a..7bc44e810a 100644 --- a/src/order_gui.cpp +++ b/src/order_gui.cpp @@ -846,8 +846,8 @@ public: case WID_O_COND_VARIABLE: { Dimension d = {0, 0}; - for (uint i = 0; i < lengthof(_order_conditional_variable); i++) { - d = maxdim(d, GetStringBoundingBox(STR_ORDER_CONDITIONAL_LOAD_PERCENTAGE + _order_conditional_variable[i])); + for (const auto &ocv : _order_conditional_variable) { + d = maxdim(d, GetStringBoundingBox(STR_ORDER_CONDITIONAL_LOAD_PERCENTAGE + ocv)); } d.width += padding.width; d.height += padding.height; @@ -1349,8 +1349,8 @@ public: case WID_O_COND_VARIABLE: { DropDownList list; - for (uint i = 0; i < lengthof(_order_conditional_variable); i++) { - list.push_back(MakeDropDownListStringItem(STR_ORDER_CONDITIONAL_LOAD_PERCENTAGE + _order_conditional_variable[i], _order_conditional_variable[i])); + for (const auto &ocv : _order_conditional_variable) { + list.push_back(MakeDropDownListStringItem(STR_ORDER_CONDITIONAL_LOAD_PERCENTAGE + ocv, ocv)); } ShowDropDownList(this, std::move(list), this->vehicle->GetOrder(this->OrderGetSel())->GetConditionVariable(), WID_O_COND_VARIABLE); break; diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 9bfb99506b..75f062fc4b 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -2369,7 +2369,7 @@ bool AfterLoadGame() uint8_t old_start; uint8_t num_frames; }; - static const AirportTileConversion atc[] = { + static const AirportTileConversion atcs[] = { {31, 12}, // APT_RADAR_GRASS_FENCE_SW {50, 4}, // APT_GRASS_FENCE_NE_FLAG {62, 2}, // 1 unused tile @@ -2384,17 +2384,17 @@ bool AfterLoadGame() if (IsAirportTile(t)) { StationGfx old_gfx = GetStationGfx(t); uint8_t offset = 0; - for (uint i = 0; i < lengthof(atc); i++) { - if (old_gfx < atc[i].old_start) { + for (const auto &atc : atcs) { + if (old_gfx < atc.old_start) { SetStationGfx(t, old_gfx - offset); break; } - if (old_gfx < atc[i].old_start + atc[i].num_frames) { - SetAnimationFrame(t, old_gfx - atc[i].old_start); - SetStationGfx(t, atc[i].old_start - offset); + if (old_gfx < atc.old_start + atc.num_frames) { + SetAnimationFrame(t, old_gfx - atc.old_start); + SetStationGfx(t, atc.old_start - offset); break; } - offset += atc[i].num_frames - 1; + offset += atc.num_frames - 1; } } } diff --git a/src/script/script_info.cpp b/src/script/script_info.cpp index 3c732f6ecc..e086495781 100644 --- a/src/script/script_info.cpp +++ b/src/script/script_info.cpp @@ -47,8 +47,8 @@ bool ScriptInfo::CheckMethod(const char *name) const "GetDate", "CreateInstance", }; - for (size_t i = 0; i < lengthof(required_functions); i++) { - if (!info->CheckMethod(required_functions[i])) return SQ_ERROR; + for (const auto &required_function : required_functions) { + if (!info->CheckMethod(required_function)) return SQ_ERROR; } /* Get location information of the scanner */ diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index f1117563bc..7dac948470 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -2380,8 +2380,8 @@ struct GameSettingsWindow : Window { STR_CONFIG_SETTING_TYPE_COMPANY_MENU, STR_CONFIG_SETTING_TYPE_COMPANY_INGAME, STR_CONFIG_SETTING_TYPE_GAME_MENU, STR_CONFIG_SETTING_TYPE_GAME_INGAME, }; - for (uint i = 0; i < lengthof(setting_types); i++) { - SetDParam(0, setting_types[i]); + for (const auto &setting_type : setting_types) { + SetDParam(0, setting_type); size.width = std::max(size.width, GetStringBoundingBox(STR_CONFIG_SETTING_TYPE).width + padding.width); } size.height = 2 * GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal + diff --git a/src/smallmap_gui.cpp b/src/smallmap_gui.cpp index 18d25d7083..7727478fd1 100644 --- a/src/smallmap_gui.cpp +++ b/src/smallmap_gui.cpp @@ -747,16 +747,16 @@ protected: /* Rebuild colour indices if necessary. */ if (SmallMapWindow::map_height_limit == _settings_game.construction.map_height_limit) return; - for (uint n = 0; n < lengthof(_heightmap_schemes); n++) { + for (auto &heightmap_scheme : _heightmap_schemes) { /* The heights go from 0 up to and including maximum. */ int heights = _settings_game.construction.map_height_limit + 1; - _heightmap_schemes[n].height_colours = ReallocT(_heightmap_schemes[n].height_colours, heights); + heightmap_scheme.height_colours = ReallocT(heightmap_scheme.height_colours, heights); for (int z = 0; z < heights; z++) { - size_t access_index = (_heightmap_schemes[n].colour_count * z) / heights; + size_t access_index = (heightmap_scheme.colour_count * z) / heights; /* Choose colour by mapping the range (0..max heightlevel) on the complete colour table. */ - _heightmap_schemes[n].height_colours[z] = _heightmap_schemes[n].height_colours_base[access_index]; + heightmap_scheme.height_colours[z] = heightmap_scheme.height_colours_base[access_index]; } } diff --git a/src/spriteloader/sprite_file.cpp b/src/spriteloader/sprite_file.cpp index e5a701ecba..82498cf83e 100644 --- a/src/spriteloader/sprite_file.cpp +++ b/src/spriteloader/sprite_file.cpp @@ -24,8 +24,8 @@ static uint8_t GetGRFContainerVersion(SpriteFile &file) if (file.ReadWord() == 0) { /* Check for GRF container version 2, which is identified by the bytes * '47 52 46 82 0D 0A 1A 0A' at the start of the file. */ - for (uint i = 0; i < lengthof(_grf_cont_v2_sig); i++) { - if (file.ReadByte() != _grf_cont_v2_sig[i]) return 0; // Invalid format + for (const auto &expected_sig_byte : _grf_cont_v2_sig) { + if (file.ReadByte() != expected_sig_byte) return 0; // Invalid format } return 2; diff --git a/src/strgen/strgen.cpp b/src/strgen/strgen.cpp index bac30b9de9..63d52fb865 100644 --- a/src/strgen/strgen.cpp +++ b/src/strgen/strgen.cpp @@ -361,9 +361,9 @@ int CDECL main(int argc, char *argv[]) case 'P': fmt::print("name\tflags\tdefault\tdescription\n"); - for (size_t j = 0; j < lengthof(_pragmas); j++) { + for (const auto &pragma : _pragmas) { fmt::print("\"{}\"\t{}\t\"{}\"\t\"{}\"\n", - _pragmas[j][0], _pragmas[j][1], _pragmas[j][2], _pragmas[j][3]); + pragma[0], pragma[1], pragma[2], pragma[3]); } return 0; diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp index 7f4ce36146..58ee59459e 100644 --- a/src/vehicle_gui.cpp +++ b/src/vehicle_gui.cpp @@ -2440,8 +2440,8 @@ struct VehicleDetailsWindow : Window { STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD_MIN_PERFORMANCE, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS }; - for (uint i = 0; i < lengthof(info_strings); i++) { - dim = maxdim(dim, GetStringBoundingBox(info_strings[i])); + for (const auto &info_string : info_strings) { + dim = maxdim(dim, GetStringBoundingBox(info_string)); } SetDParam(0, STR_VEHICLE_INFO_AGE); dim = maxdim(dim, GetStringBoundingBox(TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_AGE_RUNNING_COST_PERIOD : STR_VEHICLE_INFO_AGE_RUNNING_COST_YR)); diff --git a/src/video/sdl_v.cpp b/src/video/sdl_v.cpp index c4f53ec9c8..3619b61fd2 100644 --- a/src/video/sdl_v.cpp +++ b/src/video/sdl_v.cpp @@ -182,9 +182,9 @@ static void GetVideoModes() _all_modes = (SDL_ListModes(nullptr, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1); if (modes == (void*)-1) { - for (uint i = 0; i < lengthof(_default_resolutions); i++) { - if (SDL_VideoModeOK(_default_resolutions[i].width, _default_resolutions[i].height, 8, SDL_FULLSCREEN) != 0) { - _resolutions.push_back(_default_resolutions[i]); + for (const auto &default_resolution : _default_resolutions) { + if (SDL_VideoModeOK(default_resolution.width, default_resolution.height, 8, SDL_FULLSCREEN) != 0) { + _resolutions.push_back(default_resolution); } } } else { diff --git a/src/viewport.cpp b/src/viewport.cpp index 98f40b2a42..8110bc4224 100644 --- a/src/viewport.cpp +++ b/src/viewport.cpp @@ -3517,9 +3517,9 @@ static ViewportSSCSS _vp_sprite_sorters[] = { /** Choose the "best" sprite sorter and set _vp_sprite_sorter. */ void InitializeSpriteSorter() { - for (uint i = 0; i < lengthof(_vp_sprite_sorters); i++) { - if (_vp_sprite_sorters[i].fct_checker()) { - _vp_sprite_sorter = _vp_sprite_sorters[i].fct_sorter; + for (const auto &sprite_sorter : _vp_sprite_sorters) { + if (sprite_sorter.fct_checker()) { + _vp_sprite_sorter = sprite_sorter.fct_sorter; break; } } From e8a56db21dc00e09bff792a9c9fb66bcb51aa2cf Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 10 Apr 2024 21:49:39 +0200 Subject: [PATCH 08/11] Codechange: use designated initializers for OptionData and pass as span --- src/misc/getoptdata.cpp | 12 +++--- src/misc/getoptdata.h | 71 ++++----------------------------- src/openttd.cpp | 50 ++++++++++------------- src/settingsgen/settingsgen.cpp | 11 +++-- src/strgen/strgen.cpp | 19 +++++---- 5 files changed, 49 insertions(+), 114 deletions(-) diff --git a/src/misc/getoptdata.cpp b/src/misc/getoptdata.cpp index df54391232..b4cb5df3d1 100644 --- a/src/misc/getoptdata.cpp +++ b/src/misc/getoptdata.cpp @@ -21,7 +21,7 @@ */ int GetOptData::GetOpt() { - const OptionData *odata; + OptionSpan::iterator odata; char *s = this->cont; if (s == nullptr) { @@ -34,7 +34,7 @@ int GetOptData::GetOpt() this->numleft--; /* Is it a long option? */ - for (odata = this->options; odata->flags != ODF_END; odata++) { + for (odata = std::begin(this->options); odata != std::end(this->options); odata++) { if (odata->longname != nullptr && !strcmp(odata->longname, s)) { // Long options always use the entire argument. this->cont = nullptr; goto set_optval; @@ -45,13 +45,13 @@ int GetOptData::GetOpt() } /* Is it a short option? */ - for (odata = this->options; odata->flags != ODF_END; odata++) { + for (odata = std::begin(this->options); odata != std::end(this->options); odata++) { if (odata->shortname != '\0' && *s == odata->shortname) { this->cont = (s[1] != '\0') ? s + 1 : nullptr; set_optval: // Handle option value of *odata . this->opt = nullptr; - switch (odata->flags) { + switch (odata->type) { case ODF_NO_VALUE: return odata->id; @@ -63,10 +63,10 @@ set_optval: // Handle option value of *odata . return odata->id; } /* No more arguments, either return an error or a value-less option. */ - if (this->numleft == 0) return (odata->flags == ODF_HAS_VALUE) ? -2 : odata->id; + if (this->numleft == 0) return (odata->type == ODF_HAS_VALUE) ? -2 : odata->id; /* Next argument looks like another option, let's not return it as option value. */ - if (odata->flags == ODF_OPTIONAL_VALUE && this->argv[0][0] == '-') return odata->id; + if (odata->type == ODF_OPTIONAL_VALUE && this->argv[0][0] == '-') return odata->id; this->opt = this->argv[0]; // Next argument is the option value. this->argv++; diff --git a/src/misc/getoptdata.h b/src/misc/getoptdata.h index e9a8e824a2..d6df8f218e 100644 --- a/src/misc/getoptdata.h +++ b/src/misc/getoptdata.h @@ -11,27 +11,27 @@ #define GETOPTDATA_H /** Flags of an option. */ -enum OptionDataFlags { +enum OptionDataType : uint8_t { ODF_NO_VALUE, ///< A plain option (no value attached to it). ODF_HAS_VALUE, ///< An option with a value. ODF_OPTIONAL_VALUE, ///< An option with an optional value. - ODF_END, ///< Terminator (data is not parsed further). }; /** Data of an option. */ struct OptionData { - uint8_t id; ///< Unique identification of this option data, often the same as #shortname. - char shortname; ///< Short option letter if available, else use \c '\0'. - uint16_t flags; ///< Option data flags. @see OptionDataFlags - const char *longname; ///< Long option name including '-'/'--' prefix, use \c nullptr if not available. + OptionDataType type; ///< The type of option. + char id; ///< Unique identification of this option data, often the same as #shortname. + char shortname = '\0'; ///< Short option letter if available, else use \c '\0'. + const char *longname = nullptr; ///< Long option name including '-'/'--' prefix, use \c nullptr if not available. }; /** Data storage for parsing command line options. */ struct GetOptData { + using OptionSpan = std::span; char *opt; ///< Option value, if available (else \c nullptr). int numleft; ///< Number of arguments left in #argv. char **argv; ///< Remaining command line arguments. - const OptionData *options; ///< Command line option descriptions. + OptionSpan options; ///< Command line option descriptions. char *cont; ///< Next call to #GetOpt should start here (in the middle of an argument). /** @@ -40,7 +40,7 @@ struct GetOptData { * @param argv Command line arguments, excluding the program name. * @param options Command line option descriptions. */ - GetOptData(int argc, char **argv, const OptionData *options) : + GetOptData(int argc, char **argv, OptionSpan options) : opt(nullptr), numleft(argc), argv(argv), @@ -52,59 +52,4 @@ struct GetOptData { int GetOpt(); }; -/** - * General macro for creating an option. - * @param id Identification of the option. - * @param shortname Short option name. Use \c '\0' if not used. - * @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used. - * @param flags Flags of the option. - */ -#define GETOPT_GENERAL(id, shortname, longname, flags) { id, shortname, flags, longname } - -/** - * Short option without value. - * @param shortname Short option name. Use \c '\0' if not used. - * @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used. - */ -#define GETOPT_NOVAL(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_NO_VALUE) - -/** - * Short option with value. - * @param shortname Short option name. Use \c '\0' if not used. - * @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used. - */ -#define GETOPT_VALUE(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_HAS_VALUE) - -/** - * Short option with optional value. - * @param shortname Short option name. Use \c '\0' if not used. - * @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used. - * @note Options with optional values are hopelessly ambiguous, eg "-opt -value", avoid them. - */ -#define GETOPT_OPTVAL(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_OPTIONAL_VALUE) - - -/** - * Short option without value. - * @param shortname Short option name. Use \c '\0' if not used. - */ -#define GETOPT_SHORT_NOVAL(shortname) GETOPT_NOVAL(shortname, nullptr) - -/** - * Short option with value. - * @param shortname Short option name. Use \c '\0' if not used. - */ -#define GETOPT_SHORT_VALUE(shortname) GETOPT_VALUE(shortname, nullptr) - -/** - * Short option with optional value. - * @param shortname Short option name. Use \c '\0' if not used. - * @note Options with optional values are hopelessly ambiguous, eg "-opt -value", avoid them. - */ -#define GETOPT_SHORT_OPTVAL(shortname) GETOPT_OPTVAL(shortname, nullptr) - -/** Option terminator. */ -#define GETOPT_END() { '\0', '\0', ODF_END, nullptr} - - #endif /* GETOPTDATA_H */ diff --git a/src/openttd.cpp b/src/openttd.cpp index 7ae3cba92d..bece97833e 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -478,36 +478,27 @@ void PostMainLoop() extern void DedicatedFork(); #endif -/** Options of OpenTTD. */ -static const OptionData _options[] = { - GETOPT_SHORT_VALUE('I'), - GETOPT_SHORT_VALUE('S'), - GETOPT_SHORT_VALUE('M'), - GETOPT_SHORT_VALUE('m'), - GETOPT_SHORT_VALUE('s'), - GETOPT_SHORT_VALUE('v'), - GETOPT_SHORT_VALUE('b'), - GETOPT_SHORT_OPTVAL('D'), - GETOPT_SHORT_VALUE('n'), - GETOPT_SHORT_VALUE('p'), - GETOPT_SHORT_VALUE('P'), +/** + * Create all the options that OpenTTD supports. Each option is + * always a single character with no, an optional or a required value. + * @return The available options. + */ +static std::vector CreateOptions() +{ + std::vector options; + /* Options that require a parameter. */ + for (char c : "GIMPSbcmnpqrstv") options.push_back({ .type = ODF_HAS_VALUE, .id = c, .shortname = c }); #if !defined(_WIN32) - GETOPT_SHORT_NOVAL('f'), + options.push_back({ .type = ODF_HAS_VALUE, .id = 'f', .shortname = 'f' }); #endif - GETOPT_SHORT_VALUE('r'), - GETOPT_SHORT_VALUE('t'), - GETOPT_SHORT_OPTVAL('d'), - GETOPT_SHORT_NOVAL('e'), - GETOPT_SHORT_OPTVAL('g'), - GETOPT_SHORT_VALUE('G'), - GETOPT_SHORT_VALUE('c'), - GETOPT_SHORT_NOVAL('x'), - GETOPT_SHORT_NOVAL('X'), - GETOPT_SHORT_VALUE('q'), - GETOPT_SHORT_NOVAL('h'), - GETOPT_SHORT_NOVAL('Q'), - GETOPT_END() -}; + + /* Options with an optional parameter. */ + for (char c : "Ddg") options.push_back({ .type = ODF_OPTIONAL_VALUE, .id = c, .shortname = c }); + + /* Options without a parameter. */ + for (char c : "QXehx") options.push_back({ .type = ODF_NO_VALUE, .id = c, .shortname = c }); + return options; +} /** * Main entry point for this lovely game. @@ -538,7 +529,8 @@ int openttd_main(int argc, char *argv[]) _game_mode = GM_MENU; _switch_mode = SM_MENU; - GetOptData mgo(argc - 1, argv + 1, _options); + auto options = CreateOptions(); + GetOptData mgo(argc - 1, argv + 1, options); int ret = 0; int i; diff --git a/src/settingsgen/settingsgen.cpp b/src/settingsgen/settingsgen.cpp index 0ab4d5bd43..cb161033b8 100644 --- a/src/settingsgen/settingsgen.cpp +++ b/src/settingsgen/settingsgen.cpp @@ -385,12 +385,11 @@ static bool CompareFiles(const char *n1, const char *n2) /** Options of settingsgen. */ static const OptionData _opts[] = { - GETOPT_NOVAL( 'h', "--help"), - GETOPT_GENERAL('h', '?', nullptr, ODF_NO_VALUE), - GETOPT_VALUE( 'o', "--output"), - GETOPT_VALUE( 'b', "--before"), - GETOPT_VALUE( 'a', "--after"), - GETOPT_END(), + { .type = ODF_NO_VALUE, .id = 'h', .shortname = 'h', .longname = "--help" }, + { .type = ODF_NO_VALUE, .id = 'h', .shortname = '?' }, + { .type = ODF_HAS_VALUE, .id = 'o', .shortname = 'o', .longname = "--output" }, + { .type = ODF_HAS_VALUE, .id = 'b', .shortname = 'b', .longname = "--before" }, + { .type = ODF_HAS_VALUE, .id = 'a', .shortname = 'a', .longname = "--after" }, }; /** diff --git a/src/strgen/strgen.cpp b/src/strgen/strgen.cpp index 63d52fb865..306a4f8c63 100644 --- a/src/strgen/strgen.cpp +++ b/src/strgen/strgen.cpp @@ -312,16 +312,15 @@ struct LanguageFileWriter : LanguageWriter, FileWriter { /** Options of strgen. */ static const OptionData _opts[] = { - GETOPT_GENERAL('C', '\0', "-export-commands", ODF_NO_VALUE), - GETOPT_GENERAL('L', '\0', "-export-plurals", ODF_NO_VALUE), - GETOPT_GENERAL('P', '\0', "-export-pragmas", ODF_NO_VALUE), - GETOPT_NOVAL( 't', "--todo"), - GETOPT_NOVAL( 'w', "--warning"), - GETOPT_NOVAL( 'h', "--help"), - GETOPT_GENERAL('h', '?', nullptr, ODF_NO_VALUE), - GETOPT_VALUE( 's', "--source_dir"), - GETOPT_VALUE( 'd', "--dest_dir"), - GETOPT_END(), + { .type = ODF_NO_VALUE, .id = 'C', .longname = "-export-commands" }, + { .type = ODF_NO_VALUE, .id = 'L', .longname = "-export-plurals" }, + { .type = ODF_NO_VALUE, .id = 'P', .longname = "-export-pragmas" }, + { .type = ODF_NO_VALUE, .id = 't', .shortname = 't', .longname = "--todo" }, + { .type = ODF_NO_VALUE, .id = 'w', .shortname = 'w', .longname = "--warning" }, + { .type = ODF_NO_VALUE, .id = 'h', .shortname = 'h', .longname = "--help" }, + { .type = ODF_NO_VALUE, .id = 'h', .shortname = '?' }, + { .type = ODF_HAS_VALUE, .id = 's', .shortname = 's', .longname = "--source_dir" }, + { .type = ODF_HAS_VALUE, .id = 'd', .shortname = 'd', .longname = "--dest_dir" }, }; int CDECL main(int argc, char *argv[]) From 5592b4409bf1212f3be045e9f3b3f6ce976ad81d Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 10 Apr 2024 21:57:27 +0200 Subject: [PATCH 09/11] Codechange: use ranged for loop and separate function instead of goto --- src/misc/getoptdata.cpp | 69 +++++++++++++++++++++-------------------- src/misc/getoptdata.h | 1 + 2 files changed, 36 insertions(+), 34 deletions(-) diff --git a/src/misc/getoptdata.cpp b/src/misc/getoptdata.cpp index b4cb5df3d1..a8fdc9d2b5 100644 --- a/src/misc/getoptdata.cpp +++ b/src/misc/getoptdata.cpp @@ -21,8 +21,6 @@ */ int GetOptData::GetOpt() { - OptionSpan::iterator odata; - char *s = this->cont; if (s == nullptr) { if (this->numleft == 0) return -1; // No arguments left -> finished. @@ -34,10 +32,10 @@ int GetOptData::GetOpt() this->numleft--; /* Is it a long option? */ - for (odata = std::begin(this->options); odata != std::end(this->options); odata++) { - if (odata->longname != nullptr && !strcmp(odata->longname, s)) { // Long options always use the entire argument. + for (auto &option : this->options) { + if (option.longname != nullptr && !strcmp(option.longname, s)) { // Long options always use the entire argument. this->cont = nullptr; - goto set_optval; + return this->GetOpt(option); } } @@ -45,39 +43,42 @@ int GetOptData::GetOpt() } /* Is it a short option? */ - for (odata = std::begin(this->options); odata != std::end(this->options); odata++) { - if (odata->shortname != '\0' && *s == odata->shortname) { + for (auto &option : this->options) { + if (option.shortname != '\0' && *s == option.shortname) { this->cont = (s[1] != '\0') ? s + 1 : nullptr; - -set_optval: // Handle option value of *odata . - this->opt = nullptr; - switch (odata->type) { - case ODF_NO_VALUE: - return odata->id; - - case ODF_HAS_VALUE: - case ODF_OPTIONAL_VALUE: - if (this->cont != nullptr) { // Remainder of the argument is the option value. - this->opt = this->cont; - this->cont = nullptr; - return odata->id; - } - /* No more arguments, either return an error or a value-less option. */ - if (this->numleft == 0) return (odata->type == ODF_HAS_VALUE) ? -2 : odata->id; - - /* Next argument looks like another option, let's not return it as option value. */ - if (odata->type == ODF_OPTIONAL_VALUE && this->argv[0][0] == '-') return odata->id; - - this->opt = this->argv[0]; // Next argument is the option value. - this->argv++; - this->numleft--; - return odata->id; - - default: NOT_REACHED(); - } + return this->GetOpt(option); } } return -2; // No other ways to interpret the text -> error. } +int GetOptData::GetOpt(const OptionData &option) +{ + this->opt = nullptr; + switch (option.type) { + case ODF_NO_VALUE: + return option.id; + + case ODF_HAS_VALUE: + case ODF_OPTIONAL_VALUE: + if (this->cont != nullptr) { // Remainder of the argument is the option value. + this->opt = this->cont; + this->cont = nullptr; + return option.id; + } + /* No more arguments, either return an error or a value-less option. */ + if (this->numleft == 0) return (option.type == ODF_HAS_VALUE) ? -2 : option.id; + + /* Next argument looks like another option, let's not return it as option value. */ + if (option.type == ODF_OPTIONAL_VALUE && this->argv[0][0] == '-') return option.id; + + this->opt = this->argv[0]; // Next argument is the option value. + this->argv++; + this->numleft--; + return option.id; + + default: NOT_REACHED(); + } +} + diff --git a/src/misc/getoptdata.h b/src/misc/getoptdata.h index d6df8f218e..40950e0078 100644 --- a/src/misc/getoptdata.h +++ b/src/misc/getoptdata.h @@ -50,6 +50,7 @@ struct GetOptData { } int GetOpt(); + int GetOpt(const OptionData &option); }; #endif /* GETOPTDATA_H */ From afd7878de087701358a3d22c9632a0d707375685 Mon Sep 17 00:00:00 2001 From: Rubidium Date: Wed, 10 Apr 2024 22:21:56 +0200 Subject: [PATCH 10/11] Codechange: internally use a span of arguments for GetOptData --- src/misc/getoptdata.cpp | 18 ++++++++---------- src/misc/getoptdata.h | 23 ++++++++--------------- src/openttd.cpp | 4 ++-- src/settingsgen/settingsgen.cpp | 4 ++-- src/strgen/strgen.cpp | 10 +++++----- 5 files changed, 25 insertions(+), 34 deletions(-) diff --git a/src/misc/getoptdata.cpp b/src/misc/getoptdata.cpp index a8fdc9d2b5..fbc4907375 100644 --- a/src/misc/getoptdata.cpp +++ b/src/misc/getoptdata.cpp @@ -21,15 +21,14 @@ */ int GetOptData::GetOpt() { - char *s = this->cont; + const char *s = this->cont; if (s == nullptr) { - if (this->numleft == 0) return -1; // No arguments left -> finished. + if (this->arguments.empty()) return -1; // No arguments left -> finished. - s = this->argv[0]; + s = this->arguments[0]; if (*s != '-') return -1; // No leading '-' -> not an option -> finished. - this->argv++; - this->numleft--; + this->arguments = this->arguments.subspan(1); /* Is it a long option? */ for (auto &option : this->options) { @@ -68,14 +67,13 @@ int GetOptData::GetOpt(const OptionData &option) return option.id; } /* No more arguments, either return an error or a value-less option. */ - if (this->numleft == 0) return (option.type == ODF_HAS_VALUE) ? -2 : option.id; + if (this->arguments.empty()) return (option.type == ODF_HAS_VALUE) ? -2 : option.id; /* Next argument looks like another option, let's not return it as option value. */ - if (option.type == ODF_OPTIONAL_VALUE && this->argv[0][0] == '-') return option.id; + if (option.type == ODF_OPTIONAL_VALUE && this->arguments[0][0] == '-') return option.id; - this->opt = this->argv[0]; // Next argument is the option value. - this->argv++; - this->numleft--; + this->opt = this->arguments[0]; // Next argument is the option value. + this->arguments = this->arguments.subspan(1); return option.id; default: NOT_REACHED(); diff --git a/src/misc/getoptdata.h b/src/misc/getoptdata.h index 40950e0078..244c96358b 100644 --- a/src/misc/getoptdata.h +++ b/src/misc/getoptdata.h @@ -28,26 +28,19 @@ struct OptionData { /** Data storage for parsing command line options. */ struct GetOptData { using OptionSpan = std::span; - char *opt; ///< Option value, if available (else \c nullptr). - int numleft; ///< Number of arguments left in #argv. - char **argv; ///< Remaining command line arguments. - OptionSpan options; ///< Command line option descriptions. - char *cont; ///< Next call to #GetOpt should start here (in the middle of an argument). + using ArgumentSpan = std::span; + + ArgumentSpan arguments; ///< Remaining command line arguments. + const OptionSpan options; ///< Command line option descriptions. + const char *opt = nullptr; ///< Option value, if available (else \c nullptr). + const char *cont = nullptr; ///< Next call to #GetOpt should start here (in the middle of an argument). /** * Constructor of the data store. - * @param argc Number of command line arguments, excluding the program name. - * @param argv Command line arguments, excluding the program name. + * @param argument The command line arguments, excluding the program name. * @param options Command line option descriptions. */ - GetOptData(int argc, char **argv, OptionSpan options) : - opt(nullptr), - numleft(argc), - argv(argv), - options(options), - cont(nullptr) - { - } + GetOptData(ArgumentSpan arguments, OptionSpan options) : arguments(arguments), options(options) {} int GetOpt(); int GetOpt(const OptionData &option); diff --git a/src/openttd.cpp b/src/openttd.cpp index bece97833e..55862f6ba3 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -530,7 +530,7 @@ int openttd_main(int argc, char *argv[]) _switch_mode = SM_MENU; auto options = CreateOptions(); - GetOptData mgo(argc - 1, argv + 1, options); + GetOptData mgo(std::span(argv + 1, argc - 1), options); int ret = 0; int i; @@ -654,7 +654,7 @@ int openttd_main(int argc, char *argv[]) if (i == -2) break; } - if (i == -2 || mgo.numleft > 0) { + if (i == -2 || !mgo.arguments.empty()) { /* Either the user typed '-h', they made an error, or they added unrecognized command line arguments. * In all cases, print the help, and exit. * diff --git a/src/settingsgen/settingsgen.cpp b/src/settingsgen/settingsgen.cpp index cb161033b8..9a55d0d170 100644 --- a/src/settingsgen/settingsgen.cpp +++ b/src/settingsgen/settingsgen.cpp @@ -435,7 +435,7 @@ int CDECL main(int argc, char *argv[]) const char *before_file = nullptr; const char *after_file = nullptr; - GetOptData mgo(argc - 1, argv + 1, _opts); + GetOptData mgo(std::span(argv + 1, argc - 1), _opts); for (;;) { int i = mgo.GetOpt(); if (i == -1) break; @@ -472,7 +472,7 @@ int CDECL main(int argc, char *argv[]) _stored_output.Clear(); _post_amble_output.Clear(); - for (int i = 0; i < mgo.numleft; i++) ProcessIniFile(mgo.argv[i]); + for (auto &argument : mgo.arguments) ProcessIniFile(argument); /* Write output. */ if (output_file == nullptr) { diff --git a/src/strgen/strgen.cpp b/src/strgen/strgen.cpp index 306a4f8c63..8acb4dfbe5 100644 --- a/src/strgen/strgen.cpp +++ b/src/strgen/strgen.cpp @@ -328,7 +328,7 @@ int CDECL main(int argc, char *argv[]) std::filesystem::path src_dir("."); std::filesystem::path dest_dir; - GetOptData mgo(argc - 1, argv + 1, _opts); + GetOptData mgo(std::span(argv + 1, argc - 1), _opts); for (;;) { int i = mgo.GetOpt(); if (i == -1) break; @@ -412,7 +412,7 @@ int CDECL main(int argc, char *argv[]) * strgen generates strings.h to the destination directory. If it is supplied * with a (free) parameter the program will translate that language to destination * directory. As input english.txt is parsed from the source directory */ - if (mgo.numleft == 0) { + if (mgo.arguments.empty()) { std::filesystem::path input_path = src_dir; input_path /= "english.txt"; @@ -431,7 +431,7 @@ int CDECL main(int argc, char *argv[]) writer.WriteHeader(data); writer.Finalise(data); if (_errors != 0) return 1; - } else if (mgo.numleft >= 1) { + } else { std::filesystem::path input_path = src_dir; input_path /= "english.txt"; @@ -440,10 +440,10 @@ int CDECL main(int argc, char *argv[]) FileStringReader master_reader(data, input_path, true, false); master_reader.ParseFile(); - for (int i = 0; i < mgo.numleft; i++) { + for (auto &argument: mgo.arguments) { data.FreeTranslation(); - std::filesystem::path lang_file = mgo.argv[i]; + std::filesystem::path lang_file = argument; FileStringReader translation_reader(data, lang_file, false, lang_file.filename() != "english.txt"); translation_reader.ParseFile(); // target file if (_errors != 0) return 1; From 3316b274966b9628b3c91d932af198001b9e9039 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Thu, 11 Apr 2024 14:37:29 +0100 Subject: [PATCH 11/11] Fix: Signature validation did not close its file. (#12479) --- src/signature.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/signature.cpp b/src/signature.cpp index a329410e35..2b64676e5d 100644 --- a/src/signature.cpp +++ b/src/signature.cpp @@ -205,6 +205,7 @@ static bool _ValidateSignatureFile(const std::string &filename) std::string text(filesize, '\0'); size_t len = fread(text.data(), filesize, 1, f); + FioFCloseFile(f); if (len != 1) { Debug(misc, 0, "Failed to validate signature: failed to read file: {}", filename); return false;