1
0
Fork 0

Codechange: return std::string_view for Textbuf::GetText()

pull/14165/head
Rubidium 2025-04-29 17:31:32 +02:00 committed by rubidium42
parent 261e09a549
commit ef71ce0a9d
12 changed files with 52 additions and 48 deletions

View File

@ -129,7 +129,7 @@ static inline void IConsoleResetHistoryPos()
} }
static const char *IConsoleHistoryAdd(const char *cmd); static std::optional<std::string_view> IConsoleHistoryAdd(std::string_view cmd);
static void IConsoleHistoryNavigate(int direction); static void IConsoleHistoryNavigate(int direction);
static constexpr NWidgetPart _nested_console_window_widgets[] = { static constexpr NWidgetPart _nested_console_window_widgets[] = {
@ -276,10 +276,10 @@ struct IConsoleWindow : Window
* aligned anyway. So enforce this in all cases by adding a left-to-right marker, * aligned anyway. So enforce this in all cases by adding a left-to-right marker,
* otherwise it will be drawn at the wrong side with right-to-left texts. */ * otherwise it will be drawn at the wrong side with right-to-left texts. */
IConsolePrint(CC_COMMAND, LRM "] {}", _iconsole_cmdline.GetText()); IConsolePrint(CC_COMMAND, LRM "] {}", _iconsole_cmdline.GetText());
const char *cmd = IConsoleHistoryAdd(_iconsole_cmdline.GetText()); auto cmd = IConsoleHistoryAdd(_iconsole_cmdline.GetText());
IConsoleClearCommand(); IConsoleClearCommand();
if (cmd != nullptr) IConsoleCmdExec(cmd); if (cmd.has_value()) IConsoleCmdExec(*cmd);
break; break;
} }
@ -448,13 +448,13 @@ void IConsoleClose()
* @param cmd Text to be entered into the 'history' * @param cmd Text to be entered into the 'history'
* @return the command to execute * @return the command to execute
*/ */
static const char *IConsoleHistoryAdd(const char *cmd) static std::optional<std::string_view> IConsoleHistoryAdd(std::string_view cmd)
{ {
/* Strip all spaces at the begin */ /* Strip all spaces at the begin */
while (IsWhitespace(*cmd)) cmd++; while (IsWhitespace(cmd[0])) cmd.remove_prefix(1);
/* Do not put empty command in history */ /* Do not put empty command in history */
if (StrEmpty(cmd)) return nullptr; if (cmd.empty()) return std::nullopt;
/* Do not put in history if command is same as previous */ /* Do not put in history if command is same as previous */
if (_iconsole_history.empty() || _iconsole_history.front() != cmd) { if (_iconsole_history.empty() || _iconsole_history.front() != cmd) {
@ -464,7 +464,7 @@ static const char *IConsoleHistoryAdd(const char *cmd)
/* Reset the history position */ /* Reset the history position */
IConsoleResetHistoryPos(); IConsoleResetHistoryPos();
return _iconsole_history.front().c_str(); return _iconsole_history.front();
} }
/** /**

View File

@ -744,7 +744,7 @@ void QueryString::DrawEditBox(const Window *w, WidgetID wid) const
DrawFrameRect(cr, wi->colour, wi->IsLowered() ? FrameFlag::Lowered : FrameFlags{}); DrawFrameRect(cr, wi->colour, wi->IsLowered() ? FrameFlag::Lowered : FrameFlags{});
DrawSpriteIgnorePadding(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT, PAL_NONE, cr, SA_CENTER); DrawSpriteIgnorePadding(rtl ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT, PAL_NONE, cr, SA_CENTER);
if (StrEmpty(this->text.GetText())) GfxFillRect(cr.Shrink(WidgetDimensions::scaled.bevel), GetColourGradient(wi->colour, SHADE_DARKER), FILLRECT_CHECKER); if (this->text.GetText().empty()) GfxFillRect(cr.Shrink(WidgetDimensions::scaled.bevel), GetColourGradient(wi->colour, SHADE_DARKER), FILLRECT_CHECKER);
DrawFrameRect(fr, wi->colour, {FrameFlag::Lowered, FrameFlag::Darkened}); DrawFrameRect(fr, wi->colour, {FrameFlag::Lowered, FrameFlag::Darkened});
GfxFillRect(fr.Shrink(WidgetDimensions::scaled.bevel), PC_BLACK); GfxFillRect(fr.Shrink(WidgetDimensions::scaled.bevel), PC_BLACK);
@ -877,7 +877,7 @@ void QueryString::ClickEditBox(Window *w, Point pt, WidgetID wid, int click_coun
Rect cr = wi->GetCurrentRect().WithWidth(clearbtn_width, !rtl); Rect cr = wi->GetCurrentRect().WithWidth(clearbtn_width, !rtl);
if (IsInsideMM(pt.x, cr.left, cr.right)) { if (IsInsideMM(pt.x, cr.left, cr.right)) {
if (!StrEmpty(this->text.GetText())) { if (!this->text.GetText().empty()) {
this->text.DeleteAll(); this->text.DeleteAll();
w->HandleButtonClick(wid); w->HandleButtonClick(wid);
w->OnEditboxChanged(wid); w->OnEditboxChanged(wid);
@ -942,7 +942,7 @@ struct QueryStringWindow : public Window
if (!this->editbox.orig.has_value() || this->editbox.text.GetText() != this->editbox.orig) { if (!this->editbox.orig.has_value() || this->editbox.text.GetText() != this->editbox.orig) {
assert(this->parent != nullptr); assert(this->parent != nullptr);
this->parent->OnQueryTextFinished(this->editbox.text.GetText()); this->parent->OnQueryTextFinished(std::string{this->editbox.text.GetText()});
this->editbox.handled = true; this->editbox.handled = true;
} }
} }

View File

@ -370,15 +370,15 @@ class NetworkContentListWindow : public Window, ContentCallback {
url += "do=searchtext&q="; url += "do=searchtext&q=";
/* Escape search term */ /* Escape search term */
for (const char *search = this->filter_editbox.text.GetText(); *search != '\0'; search++) { for (char search : this->filter_editbox.text.GetText()) {
/* Remove quotes */ /* Remove quotes */
if (*search == '\'' || *search == '"') continue; if (search == '\'' || search == '"') continue;
/* Escape special chars, such as &%,= */ /* Escape special chars, such as &%,= */
if (*search < 0x30) { if (static_cast<unsigned char>(search) < 0x30) {
format_append(url, "%{:02X}", *search); format_append(url, "%{:02X}", search);
} else { } else {
url.push_back(*search); url.push_back(search);
} }
} }
} }

View File

@ -1102,7 +1102,7 @@ struct NetworkStartServerWindow : public Window {
bool CheckServerName() bool CheckServerName()
{ {
std::string str = this->name_editbox.text.GetText(); std::string str{this->name_editbox.text.GetText()};
if (!NetworkValidateServerName(str)) return false; if (!NetworkValidateServerName(str)) return false;
SetSettingValue(GetSettingFromName("network.server_name")->AsStringSetting(), std::move(str)); SetSettingValue(GetSettingFromName("network.server_name")->AsStringSetting(), std::move(str));

View File

@ -2112,7 +2112,10 @@ struct SavePresetWindow : public Window {
case WID_SVP_SAVE: { case WID_SVP_SAVE: {
Window *w = FindWindowById(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE); Window *w = FindWindowById(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
if (w != nullptr && !StrEmpty(this->presetname_editbox.text.GetText())) w->OnQueryTextFinished(this->presetname_editbox.text.GetText()); if (w != nullptr) {
auto text = this->presetname_editbox.text.GetText();
if (!text.empty()) w->OnQueryTextFinished(std::string{text});
}
this->Close(); this->Close();
break; break;
} }

View File

@ -11,7 +11,7 @@
#define MACOS_H #define MACOS_H
/** Helper function displaying a message the best possible way. */ /** Helper function displaying a message the best possible way. */
void ShowMacDialog(const char *title, const char *message, const char *button_label); void ShowMacDialog(std::string_view title, std::string_view message, std::string_view button_label);
void GetMacOSVersion(int *return_major, int *return_minor, int *return_bugfix); void GetMacOSVersion(int *return_major, int *return_minor, int *return_bugfix);

View File

@ -95,7 +95,7 @@ void GetMacOSVersion(int *return_major, int *return_minor, int *return_bugfix)
#ifdef WITH_COCOA #ifdef WITH_COCOA
extern void CocoaDialog(const char *title, const char *message, const char *buttonLabel); extern void CocoaDialog(std::string_view title, std::string_view message, std::string_view buttonLabel);
/** /**
* Show the system dialogue message (Cocoa on MacOSX). * Show the system dialogue message (Cocoa on MacOSX).
@ -104,7 +104,7 @@ extern void CocoaDialog(const char *title, const char *message, const char *butt
* @param message Message text. * @param message Message text.
* @param buttonLabel Button text. * @param buttonLabel Button text.
*/ */
void ShowMacDialog(const char *title, const char *message, const char *buttonLabel) void ShowMacDialog(std::string_view title, std::string_view message, std::string_view buttonLabel)
{ {
CocoaDialog(title, message, buttonLabel); CocoaDialog(title, message, buttonLabel);
} }
@ -119,7 +119,7 @@ void ShowMacDialog(const char *title, const char *message, const char *buttonLab
* @param message Message text. * @param message Message text.
* @param buttonLabel Button text. * @param buttonLabel Button text.
*/ */
void ShowMacDialog(const char *title, const char *message, const char *buttonLabel) void ShowMacDialog(std::string_view title, std::string_view message, std::string_view buttonLabel)
{ {
fmt::print(stderr, "{}: {}\n", title, message); fmt::print(stderr, "{}: {}\n", title, message);
} }

View File

@ -177,7 +177,7 @@ struct SignListWindow : Window, SignList {
* new string is zero-length or not the clear button is made * new string is zero-length or not the clear button is made
* disabled/enabled. The sign list is updated according to the new filter. * disabled/enabled. The sign list is updated according to the new filter.
*/ */
void SetFilterString(const char *new_filter_string) void SetFilterString(std::string_view new_filter_string)
{ {
/* check if there is a new filter string */ /* check if there is a new filter string */
this->string_filter.SetFilterTerm(new_filter_string); this->string_filter.SetFilterTerm(new_filter_string);
@ -400,10 +400,10 @@ Window *ShowSignList()
* @param text the new name. * @param text the new name.
* @return true if the window will already be removed after returning. * @return true if the window will already be removed after returning.
*/ */
static bool RenameSign(SignID index, const char *text) static bool RenameSign(SignID index, std::string_view text)
{ {
bool remove = StrEmpty(text); bool remove = text.empty();
Command<CMD_RENAME_SIGN>::Post(StrEmpty(text) ? STR_ERROR_CAN_T_DELETE_SIGN : STR_ERROR_CAN_T_CHANGE_SIGN_NAME, index, text); Command<CMD_RENAME_SIGN>::Post(remove ? STR_ERROR_CAN_T_DELETE_SIGN : STR_ERROR_CAN_T_CHANGE_SIGN_NAME, index, std::string{text});
return remove; return remove;
} }

View File

@ -281,9 +281,9 @@ void Textbuf::DiscardMarkedText(bool update)
* Get the current text. * Get the current text.
* @return Current text. * @return Current text.
*/ */
const char *Textbuf::GetText() const std::string_view Textbuf::GetText() const
{ {
return this->buf.c_str(); return this->buf;
} }
/** Update the character iter after the text has changed. */ /** Update the character iter after the text has changed. */

View File

@ -61,7 +61,7 @@ struct Textbuf {
void DiscardMarkedText(bool update = true); void DiscardMarkedText(bool update = true);
const char *GetText() const; std::string_view GetText() const;
private: private:
std::string buf; ///< buffer in which text is saved std::string buf; ///< buffer in which text is saved

View File

@ -102,10 +102,10 @@ static OTTDMain *_ottd_main;
* @param to End of the range. * @param to End of the range.
* @return Number of UTF-16 code points in the range. * @return Number of UTF-16 code points in the range.
*/ */
static NSUInteger CountUtf16Units(const char *from, const char *to) static NSUInteger CountUtf16Units(std::string_view str)
{ {
NSUInteger i = 0; NSUInteger i = 0;
for (char32_t c : Utf8View(std::string_view(from, to))) { for (char32_t c : Utf8View(str)) {
i += c < 0x10000 ? 1 : 2; // Watch for surrogate pairs. i += c < 0x10000 ? 1 : 2; // Watch for surrogate pairs.
} }
return i; return i;
@ -117,7 +117,7 @@ static NSUInteger CountUtf16Units(const char *from, const char *to)
* @param count Number of UTF-16 code points to advance the string by. * @param count Number of UTF-16 code points to advance the string by.
* @return Advanced string pointer. * @return Advanced string pointer.
*/ */
static const char *Utf8AdvanceByUtf16Units(const char *str, NSUInteger count) static const char *Utf8AdvanceByUtf16Units(std::string_view str, NSUInteger count)
{ {
Utf8View view(str); Utf8View view(str);
auto it = view.begin(); auto it = view.begin();
@ -125,7 +125,7 @@ static const char *Utf8AdvanceByUtf16Units(const char *str, NSUInteger count)
for (NSUInteger i = 0; it != end && i < count; ++it) { for (NSUInteger i = 0; it != end && i < count; ++it) {
i += *it < 0x10000 ? 1 : 2; // Watch for surrogate pairs. i += *it < 0x10000 ? 1 : 2; // Watch for surrogate pairs.
} }
return str + it.GetByteOffset(); return str.data() + it.GetByteOffset();
} }
/** /**
@ -394,7 +394,7 @@ void CocoaExitApplication()
* *
* @note This is needed since sometimes assert is called before the videodriver is initialized . * @note This is needed since sometimes assert is called before the videodriver is initialized .
*/ */
void CocoaDialog(const char *title, const char *message, const char *buttonLabel) void CocoaDialog(std::string_view title, std::string_view message, std::string_view buttonLabel)
{ {
_cocoa_video_dialog = true; _cocoa_video_dialog = true;
@ -413,9 +413,9 @@ void CocoaDialog(const char *title, const char *message, const char *buttonLabel
#else #else
[ alert setAlertStyle: NSCriticalAlertStyle ]; [ alert setAlertStyle: NSCriticalAlertStyle ];
#endif #endif
[ alert setMessageText:[ NSString stringWithUTF8String:title ] ]; [ alert setMessageText:[ [ NSString alloc ] initWithBytes:title.data() length:title.size() encoding:NSUTF8StringEncoding ] ];
[ alert setInformativeText:[ NSString stringWithUTF8String:message ] ]; [ alert setInformativeText:[ [ NSString alloc ] initWithBytes:message.data() length:message.size() encoding:NSUTF8StringEncoding ] ];
[ alert addButtonWithTitle: [ NSString stringWithUTF8String:buttonLabel ] ]; [ alert addButtonWithTitle: [ [ NSString alloc ] initWithBytes:buttonLabel.data() length:buttonLabel.size() encoding:NSUTF8StringEncoding ] ];
[ alert runModal ]; [ alert runModal ];
[ alert release ]; [ alert release ];
} }
@ -462,7 +462,7 @@ void CocoaDialog(const char *title, const char *message, const char *buttonLabel
[ self setContentMinSize:NSMakeSize(64.0f, 64.0f) ]; [ self setContentMinSize:NSMakeSize(64.0f, 64.0f) ];
std::string caption = VideoDriver::GetCaption(); std::string caption = VideoDriver::GetCaption();
NSString *nsscaption = [ [ NSString alloc ] initWithUTF8String:caption.c_str() ]; NSString *nsscaption = [ [ NSString alloc ] initWithBytes:caption.data() length:caption.size() encoding:NSUTF8StringEncoding ];
[ self setTitle:nsscaption ]; [ self setTitle:nsscaption ];
[ self setMiniwindowTitle:nsscaption ]; [ self setMiniwindowTitle:nsscaption ];
[ nsscaption release ]; [ nsscaption release ];
@ -1001,8 +1001,8 @@ void CocoaDialog(const char *title, const char *message, const char *buttonLabel
if (!EditBoxInGlobalFocus()) return NSMakeRange(NSNotFound, 0); if (!EditBoxInGlobalFocus()) return NSMakeRange(NSNotFound, 0);
const Textbuf *text_buf = _focused_window->GetFocusedTextbuf(); const Textbuf *text_buf = _focused_window->GetFocusedTextbuf();
const char *text = text_buf->GetText(); std::string_view text = text_buf->GetText();
NSUInteger start = CountUtf16Units(text, text + text_buf->caretpos); NSUInteger start = CountUtf16Units(text.substr(0, text_buf->caretpos));
return NSMakeRange(start, 0); return NSMakeRange(start, 0);
} }
@ -1013,10 +1013,9 @@ void CocoaDialog(const char *title, const char *message, const char *buttonLabel
const Textbuf *text_buf = _focused_window->GetFocusedTextbuf(); const Textbuf *text_buf = _focused_window->GetFocusedTextbuf();
if (text_buf->markend != 0) { if (text_buf->markend != 0) {
const char *text = text_buf->GetText(); std::string_view text = text_buf->GetText();
const char *mark = text + text_buf->markpos; NSUInteger start = CountUtf16Units(text.substr(0, text_buf->markpos));
NSUInteger start = CountUtf16Units(text, mark); NSUInteger len = CountUtf16Units(text.substr(text_buf->markpos, text_buf->markend - text_buf->markpos));
NSUInteger len = CountUtf16Units(mark, text + text_buf->markend);
return NSMakeRange(start, len); return NSMakeRange(start, len);
} }
@ -1037,7 +1036,8 @@ void CocoaDialog(const char *title, const char *message, const char *buttonLabel
{ {
if (!EditBoxInGlobalFocus()) return nil; if (!EditBoxInGlobalFocus()) return nil;
NSString *s = [ NSString stringWithUTF8String:_focused_window->GetFocusedTextbuf()->GetText() ]; auto text = _focused_window->GetFocusedTextbuf()->GetText();
NSString *s = [ [ NSString alloc] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding ];
NSRange valid_range = NSIntersectionRange(NSMakeRange(0, [ s length ]), theRange); NSRange valid_range = NSIntersectionRange(NSMakeRange(0, [ s length ]), theRange);
if (actualRange != nullptr) *actualRange = valid_range; if (actualRange != nullptr) *actualRange = valid_range;
@ -1057,7 +1057,8 @@ void CocoaDialog(const char *title, const char *message, const char *buttonLabel
{ {
if (!EditBoxInGlobalFocus()) return [ [ [ NSAttributedString alloc ] initWithString:@"" ] autorelease ]; if (!EditBoxInGlobalFocus()) return [ [ [ NSAttributedString alloc ] initWithString:@"" ] autorelease ];
return [ [ [ NSAttributedString alloc ] initWithString:[ NSString stringWithUTF8String:_focused_window->GetFocusedTextbuf()->GetText() ] ] autorelease ]; auto text = _focused_window->GetFocusedTextbuf()->GetText();
return [ [ [ NSAttributedString alloc ] initWithString:[ [ NSString alloc ] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding ] ] autorelease ];
} }
/** Get the character that is rendered at the given point. */ /** Get the character that is rendered at the given point. */
@ -1073,7 +1074,7 @@ void CocoaDialog(const char *title, const char *message, const char *buttonLabel
if (index == -1) return NSNotFound; if (index == -1) return NSNotFound;
auto text = _focused_window->GetFocusedTextbuf()->GetText(); auto text = _focused_window->GetFocusedTextbuf()->GetText();
return CountUtf16Units(text, text + index); return CountUtf16Units(text.substr(0, index));
} }
/** Get the bounding rect for the given range. */ /** Get the bounding rect for the given range. */
@ -1081,7 +1082,7 @@ void CocoaDialog(const char *title, const char *message, const char *buttonLabel
{ {
if (!EditBoxInGlobalFocus()) return NSMakeRect(0, 0, 0, 0); if (!EditBoxInGlobalFocus()) return NSMakeRect(0, 0, 0, 0);
const char *focused_text = _focused_window->GetFocusedTextbuf()->GetText(); std::string_view focused_text = _focused_window->GetFocusedTextbuf()->GetText();
/* Convert range to UTF-8 string pointers. */ /* Convert range to UTF-8 string pointers. */
const char *start = Utf8AdvanceByUtf16Units(focused_text, aRange.location); const char *start = Utf8AdvanceByUtf16Units(focused_text, aRange.location);
const char *end = aRange.length != 0 ? Utf8AdvanceByUtf16Units(focused_text, aRange.location + aRange.length) : start; const char *end = aRange.length != 0 ? Utf8AdvanceByUtf16Units(focused_text, aRange.location + aRange.length) : start;

View File

@ -2540,7 +2540,7 @@ EventState Window::HandleEditBoxKey(WidgetID wid, char32_t key, uint16_t keycode
break; break;
case QueryString::ACTION_CLEAR: case QueryString::ACTION_CLEAR:
if (StrEmpty(query->text.GetText())) { if (query->text.GetText().empty()) {
/* If already empty, unfocus instead */ /* If already empty, unfocus instead */
this->UnfocusFocusedWidget(); this->UnfocusFocusedWidget();
} else { } else {