1
0
mirror of https://github.com/ppy/osu.git synced 2025-02-15 20:53:00 +08:00

Truncate rich presence status strings to 128 bytes (#7318)

Truncate rich presence status strings to 128 bytes

Co-authored-by: Dan Balasescu <smoogipoo@smgi.me>
This commit is contained in:
Dean Herbert 2019-12-25 12:28:44 +09:00 committed by GitHub
commit a5e30859a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,6 +1,8 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
using System;
using System.Text;
using DiscordRPC; using DiscordRPC;
using DiscordRPC.Message; using DiscordRPC.Message;
using osu.Framework.Allocation; using osu.Framework.Allocation;
@ -81,8 +83,8 @@ namespace osu.Desktop
if (status.Value is UserStatusOnline && activity.Value != null) if (status.Value is UserStatusOnline && activity.Value != null)
{ {
presence.State = activity.Value.Status; presence.State = truncate(activity.Value.Status);
presence.Details = getDetails(activity.Value); presence.Details = truncate(getDetails(activity.Value));
} }
else else
{ {
@ -100,6 +102,27 @@ namespace osu.Desktop
client.SetPresence(presence); client.SetPresence(presence);
} }
private static readonly int ellipsis_length = Encoding.UTF8.GetByteCount(new[] { '…' });
private string truncate(string str)
{
if (Encoding.UTF8.GetByteCount(str) <= 128)
return str;
ReadOnlyMemory<char> strMem = str.AsMemory();
do
{
strMem = strMem[..^1];
} while (Encoding.UTF8.GetByteCount(strMem.Span) + ellipsis_length > 128);
return string.Create(strMem.Length + 1, strMem, (span, mem) =>
{
mem.Span.CopyTo(span);
span[^1] = '…';
});
}
private string getDetails(UserActivity activity) private string getDetails(UserActivity activity)
{ {
switch (activity) switch (activity)