1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-14 20:22:55 +08:00

Split drawing and business logic of ChatOverlay

This commit is contained in:
miterosan 2018-04-08 18:21:48 +02:00
parent 525e50e8dd
commit a70b329155
11 changed files with 431 additions and 388 deletions

View File

@ -15,6 +15,7 @@ using System.Linq;
using NUnit.Framework;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.API;
using osu.Game.Overlays;
namespace osu.Game.Tests.Visual
@ -50,17 +51,14 @@ namespace osu.Game.Tests.Visual
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
private void load(OsuColour colours, IAPIProvider api)
{
linkColour = colours.Blue;
dependencies.Cache(new ChatOverlay
{
AvailableChannels =
{
new ChannelChat { Name = "#english" },
new ChannelChat { Name = "#japanese" }
}
});
dependencies.Cache(new ChatOverlay());
var chatManager = new ChatManager(Scheduler);
api.Register(chatManager);
dependencies.Cache(chatManager);
testLinksGeneral();
testEcho();

View File

@ -23,15 +23,15 @@ namespace osu.Game.Graphics.Containers
public override bool HandleMouseInput => true;
private OsuGame game;
private ChatManager chatManager;
private Action showNotImplementedError;
[BackgroundDependencyLoader(true)]
private void load(OsuGame game, NotificationOverlay notifications)
private void load(OsuGame game, NotificationOverlay notifications, ChatManager chatManager)
{
// will be null in tests
this.game = game;
this.chatManager = chatManager;
showNotImplementedError = () => notifications?.Post(new SimpleNotification
{
Text = @"This link type is not yet supported!",
@ -80,7 +80,9 @@ namespace osu.Game.Graphics.Containers
game?.ShowBeatmapSet(setId);
break;
case LinkAction.OpenChannel:
game?.OpenChannel(linkArgument);
var channel = chatManager.AvailableChannels.FirstOrDefault(c => c.Name == linkArgument);
if (channel != null)
chatManager.CurrentChat.Value = channel;
break;
case LinkAction.OpenEditorTimestamp:
case LinkAction.JoinMultiplayerMatch:

View File

@ -1,16 +1,11 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using osu.Framework.Configuration;
using osu.Framework.Lists;
namespace osu.Game.Online.Chat
{
public class ChannelChat
public class ChannelChat : ChatBase
{
[JsonProperty(@"name")]
public string Name;
@ -24,82 +19,13 @@ namespace osu.Game.Online.Chat
[JsonProperty(@"channel_id")]
public int Id;
public readonly SortedList<Message> Messages = new SortedList<Message>(Comparer<Message>.Default);
private readonly List<LocalEchoMessage> pendingMessages = new List<LocalEchoMessage>();
public Bindable<bool> Joined = new Bindable<bool>();
public bool ReadOnly => false;
public const int MAX_HISTORY = 300;
[JsonConstructor]
public ChannelChat()
{
}
public event Action<IEnumerable<Message>> NewMessagesArrived;
public event Action<LocalEchoMessage, Message> PendingMessageResolved;
public event Action<Message> MessageRemoved;
public void AddLocalEcho(LocalEchoMessage message)
{
pendingMessages.Add(message);
Messages.Add(message);
NewMessagesArrived?.Invoke(new[] { message });
}
public void AddNewMessages(params Message[] messages)
{
messages = messages.Except(Messages).ToArray();
Messages.AddRange(messages);
purgeOldMessages();
NewMessagesArrived?.Invoke(messages);
}
private void purgeOldMessages()
{
// never purge local echos
int messageCount = Messages.Count - pendingMessages.Count;
if (messageCount > MAX_HISTORY)
Messages.RemoveRange(0, messageCount - MAX_HISTORY);
}
/// <summary>
/// Replace or remove a message from the channel.
/// </summary>
/// <param name="echo">The local echo message (client-side).</param>
/// <param name="final">The response message, or null if the message became invalid.</param>
public void ReplaceMessage(LocalEchoMessage echo, Message final)
{
if (!pendingMessages.Remove(echo))
throw new InvalidOperationException("Attempted to remove echo that wasn't present");
Messages.Remove(echo);
if (final == null)
{
MessageRemoved?.Invoke(echo);
return;
}
if (Messages.Contains(final))
{
// message already inserted, so let's throw away this update.
// we may want to handle this better in the future, but for the time being api requests are single-threaded so order is assumed.
MessageRemoved?.Invoke(echo);
return;
}
Messages.Add(final);
PendingMessageResolved?.Invoke(echo, final);
}
public override string ToString() => Name;
public override long ChatID => Id;
public override TargetType Target => TargetType.Channel;
}
}

View File

@ -0,0 +1,85 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Configuration;
using osu.Framework.Lists;
namespace osu.Game.Online.Chat
{
public abstract class ChatBase
{
public const int MAX_HISTORY = 300;
public bool ReadOnly { get; } = false;
public abstract TargetType Target { get; }
public abstract long ChatID { get; }
public Bindable<bool> Joined = new Bindable<bool>();
public readonly SortedList<Message> Messages = new SortedList<Message>(Comparer<Message>.Default);
private readonly List<LocalEchoMessage> pendingMessages = new List<LocalEchoMessage>();
public event Action<IEnumerable<Message>> NewMessagesArrived;
public event Action<LocalEchoMessage, Message> PendingMessageResolved;
public event Action<Message> MessageRemoved;
public void AddLocalEcho(LocalEchoMessage message)
{
pendingMessages.Add(message);
Messages.Add(message);
NewMessagesArrived?.Invoke(new[] { message });
}
public void AddNewMessages(params Message[] messages)
{
messages = messages.Except(Messages).ToArray();
Messages.AddRange(messages);
purgeOldMessages();
NewMessagesArrived?.Invoke(messages);
}
private void purgeOldMessages()
{
// never purge local echos
int messageCount = Messages.Count - pendingMessages.Count;
if (messageCount > MAX_HISTORY)
Messages.RemoveRange(0, messageCount - MAX_HISTORY);
}
/// <summary>
/// Replace or remove a message from the chat.
/// </summary>
/// <param name="echo">The local echo message (client-side).</param>
/// <param name="final">The response message, or null if the message became invalid.</param>
public void ReplaceMessage(LocalEchoMessage echo, Message final)
{
if (!pendingMessages.Remove(echo))
throw new InvalidOperationException("Attempted to remove echo that wasn't present");
Messages.Remove(echo);
if (final == null)
{
MessageRemoved?.Invoke(echo);
return;
}
if (Messages.Contains(final))
{
// message already inserted, so let's throw away this update.
// we may want to handle this better in the future, but for the time being api requests are single-threaded so order is assumed.
MessageRemoved?.Invoke(echo);
return;
}
Messages.Add(final);
PendingMessageResolved?.Invoke(echo, final);
}
}
}

View File

@ -0,0 +1,193 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using osu.Framework.Configuration;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Logging;
using osu.Framework.Threading;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
namespace osu.Game.Online.Chat
{
/// <summary>
/// Manages everything chat related
/// </summary>
public sealed class ChatManager : IOnlineComponent
{
/// <summary>
/// The channels the player joins on startup
/// </summary>
private readonly string[] defaultChannels =
{
@"#lazer", @"#osu", @"#lobby"
};
/// <summary>
/// The currently opened chat
/// </summary>
public Bindable<ChatBase> CurrentChat { get; } = new Bindable<ChatBase>();
/// <summary>
/// The Channels the player has joined
/// </summary>
public ObservableCollection<ChannelChat> JoinedChannels { get; } = new ObservableCollection<ChannelChat>();
/// <summary>
/// The channels available for the player to join
/// </summary>
public ObservableCollection<ChannelChat> AvailableChannels { get; } = new ObservableCollection<ChannelChat>();
private APIAccess api;
private readonly Scheduler scheduler;
private ScheduledDelegate fetchMessagesScheduleder;
private GetChannelMessagesRequest fetchChannelMsgReq;
private long? lastChannelMsgId;
public ChatManager(Scheduler scheduler)
{
this.scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
CurrentChat.ValueChanged += currentChatChanged;
}
private void currentChatChanged(ChatBase chatBase)
{
if (chatBase is ChannelChat channel && !JoinedChannels.Contains(channel))
JoinedChannels.Add(channel);
}
/// <summary>
/// Posts a message to the currently opened chat.
/// </summary>
/// <param name="text">The message text that is going to be posted</param>
/// <param name="isAction">Is true if the message is an action, e.g.: user is currently eating </param>
public void PostMessage(string text, bool isAction = false)
{
if (CurrentChat.Value == null)
return;
if (!api.IsLoggedIn)
{
CurrentChat.Value.AddNewMessages(new ErrorMessage("Please sign in to participate in chat!"));
return;
}
var message = new LocalEchoMessage
{
Sender = api.LocalUser.Value,
Timestamp = DateTimeOffset.Now,
TargetType = CurrentChat.Value.Target,
TargetId = CurrentChat.Value.ChatID,
IsAction = isAction,
Content = text
};
CurrentChat.Value.AddLocalEcho(message);
var req = new PostMessageRequest(message);
req.Failure += e => CurrentChat.Value?.ReplaceMessage(message, null);
req.Success += m => CurrentChat.Value?.ReplaceMessage(message, m);
api.Queue(req);
}
public void PostCommand(string text)
{
if (CurrentChat.Value == null)
return;
var parameters = text.Split(new[] { ' ' }, 2);
string command = parameters[0];
string content = parameters.Length == 2 ? parameters[1] : string.Empty;
switch (command)
{
case "me":
if (string.IsNullOrWhiteSpace(content))
{
CurrentChat.Value.AddNewMessages(new ErrorMessage("Usage: /me [action]"));
break;
}
PostMessage(content, true);
break;
case "help":
CurrentChat.Value.AddNewMessages(new InfoMessage("Supported commands: /help, /me [action]"));
break;
default:
CurrentChat.Value.AddNewMessages(new ErrorMessage($@"""/{command}"" is not supported! For a list of supported commands see /help"));
break;
}
}
private void fetchNewMessages()
{
if (fetchChannelMsgReq == null)
fetchNewChannelMessages();
}
private void fetchNewChannelMessages()
{
fetchChannelMsgReq = new GetChannelMessagesRequest(JoinedChannels, lastChannelMsgId);
fetchChannelMsgReq.Success += messages =>
{
handleChannelMessages(messages);
lastChannelMsgId = messages.LastOrDefault()?.Id ?? lastChannelMsgId;
fetchChannelMsgReq = null;
};
fetchChannelMsgReq.Failure += exception => Logger.Error(exception, "Fetching channel messages failed.");
api.Queue(fetchChannelMsgReq);
}
private void handleChannelMessages(IEnumerable<Message> messages)
{
var channels = JoinedChannels.ToList();
foreach (var group in messages.GroupBy(m => m.TargetId))
channels.Find(c => c.Id == group.Key)?.AddNewMessages(group.ToArray());
}
private void initializeDefaultChannels()
{
var req = new ListChannelsRequest();
req.Success += channels =>
{
channels.Where(channel => AvailableChannels.All(c => c.ChatID != channel.ChatID))
.ForEach(channel => AvailableChannels.Add(channel));
channels.Where(channel => defaultChannels.Contains(channel.Name))
.Where(channel => JoinedChannels.All(c => c.ChatID != channel.ChatID))
.ForEach(channel => JoinedChannels.Add(channel));
fetchNewMessages();
};
req.Failure += error => Logger.Error(error, "Fetching channels failed");
api.Queue(req);
}
public void APIStateChanged(APIAccess api, APIState state)
{
this.api = api ?? throw new ArgumentNullException(nameof(api));
switch (state)
{
case APIState.Online:
if (JoinedChannels.Count == 0)
initializeDefaultChannels();
fetchMessagesScheduleder = scheduler.AddDelayed(fetchNewMessages, 1000, true);
break;
default:
fetchChannelMsgReq?.Cancel();
fetchMessagesScheduleder?.Cancel();
break;
}
}
}
}

View File

@ -22,7 +22,7 @@ namespace osu.Game.Online.Chat
public TargetType TargetType;
[JsonProperty(@"target_id")]
public int TargetId;
public long TargetId;
[JsonProperty(@"is_action")]
public bool IsAction;

View File

@ -29,6 +29,7 @@ using osu.Game.Overlays.Notifications;
using osu.Game.Rulesets;
using osu.Game.Screens.Play;
using osu.Game.Input.Bindings;
using osu.Game.Online.Chat;
using osu.Game.Rulesets.Mods;
using osu.Game.Skinning;
using OpenTK.Graphics;
@ -142,12 +143,6 @@ namespace osu.Game
private ScheduledDelegate scoreLoad;
/// <summary>
/// Open chat to a channel matching the provided name, if present.
/// </summary>
/// <param name="channelName">The name of the channel.</param>
public void OpenChannel(string channelName) => chat.OpenChannel(chat.AvailableChannels.Find(c => c.Name == channelName));
/// <summary>
/// Show a beatmap set as an overlay.
/// </summary>

View File

@ -28,6 +28,7 @@ using osu.Game.Graphics.Textures;
using osu.Game.Input;
using osu.Game.Input.Bindings;
using osu.Game.IO;
using osu.Game.Online.Chat;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;
@ -112,6 +113,11 @@ namespace osu.Game
dependencies.Cache(api);
dependencies.CacheAs<IAPIProvider>(api);
var chatManager = new ChatManager(Scheduler);
api.Register(chatManager);
dependencies.Cache(chatManager);
dependencies.Cache(RulesetStore = new RulesetStore(contextFactory));
dependencies.Cache(FileStore = new FileStore(contextFactory, Host.Storage));
dependencies.Cache(BeatmapManager = new BeatmapManager(Host.Storage, contextFactory, RulesetStore, api, Audio, Host));

View File

@ -81,6 +81,8 @@ namespace osu.Game.Overlays.Chat
Padding = new MarginPadding { Left = padding, Right = padding };
}
private ChatManager chatManager;
private Message message;
private OsuSpriteText username;
private LinkFlowContainer contentFlow;
@ -104,9 +106,9 @@ namespace osu.Game.Overlays.Chat
}
[BackgroundDependencyLoader(true)]
private void load(OsuColour colours, ChatOverlay chat)
private void load(OsuColour colours, ChatManager chatManager)
{
this.chat = chat;
this.chatManager = chatManager;
customUsernameColour = colours.ChatBlue;
}
@ -215,8 +217,6 @@ namespace osu.Game.Overlays.Chat
FinishTransforms(true);
}
private ChatOverlay chat;
private void updateMessageContent()
{
this.FadeTo(message is LocalEchoMessage ? 0.4f : 1.0f, 500, Easing.OutQuint);
@ -226,7 +226,7 @@ namespace osu.Game.Overlays.Chat
username.Text = $@"{message.Sender.Username}" + (senderHasBackground || message.IsAction ? "" : ":");
// remove non-existent channels from the link list
message.Links.RemoveAll(link => link.Action == LinkAction.OpenChannel && chat?.AvailableChannels.Any(c => c.Name == link.Argument) != true);
message.Links.RemoveAll(link => link.Action == LinkAction.OpenChannel && chatManager?.AvailableChannels.Any(c => c.Name == link.Argument) != true);
contentFlow.Clear();
contentFlow.AddLinks(message.DisplayContent, message.Links);

View File

@ -15,15 +15,15 @@ using osu.Game.Online.Chat;
namespace osu.Game.Overlays.Chat
{
public class DrawableChannel : Container
public class DrawableChat : Container
{
public readonly ChannelChat Channel;
public readonly ChatBase Chat;
private readonly ChatLineContainer flow;
private readonly ScrollContainer scroll;
public DrawableChannel(ChannelChat channel)
public DrawableChat(ChatBase chat)
{
Channel = channel;
Chat = chat;
RelativeSizeAxes = Axes.Both;
@ -50,15 +50,15 @@ namespace osu.Game.Overlays.Chat
}
};
Channel.NewMessagesArrived += newMessagesArrived;
Channel.MessageRemoved += messageRemoved;
Channel.PendingMessageResolved += pendingMessageResolved;
Chat.NewMessagesArrived += newMessagesArrived;
Chat.MessageRemoved += messageRemoved;
Chat.PendingMessageResolved += pendingMessageResolved;
}
[BackgroundDependencyLoader]
private void load()
{
newMessagesArrived(Channel.Messages);
newMessagesArrived(Chat.Messages);
}
protected override void LoadComplete()
@ -71,15 +71,15 @@ namespace osu.Game.Overlays.Chat
{
base.Dispose(isDisposing);
Channel.NewMessagesArrived -= newMessagesArrived;
Channel.MessageRemoved -= messageRemoved;
Channel.PendingMessageResolved -= pendingMessageResolved;
Chat.NewMessagesArrived -= newMessagesArrived;
Chat.MessageRemoved -= messageRemoved;
Chat.PendingMessageResolved -= pendingMessageResolved;
}
private void newMessagesArrived(IEnumerable<Message> newMessages)
{
// Add up to last Channel.MAX_HISTORY messages
var displayMessages = newMessages.Skip(Math.Max(0, newMessages.Count() - ChannelChat.MAX_HISTORY));
// Add up to last ChatBase.MAX_HISTORY messages
var displayMessages = newMessages.Skip(Math.Max(0, newMessages.Count() - ChatBase.MAX_HISTORY));
flow.AddRange(displayMessages.Select(m => new ChatLine(m)));
@ -89,7 +89,7 @@ namespace osu.Game.Overlays.Chat
scrollToEnd();
var staleMessages = flow.Children.Where(c => c.LifetimeEnd == double.MaxValue).ToArray();
int count = staleMessages.Length - ChannelChat.MAX_HISTORY;
int count = staleMessages.Length - ChatBase.MAX_HISTORY;
for (int i = 0; i < count; i++)
{

View File

@ -1,10 +1,9 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.Allocation;
@ -16,41 +15,36 @@ using osu.Framework.Graphics.Transforms;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input;
using osu.Framework.MathUtils;
using osu.Framework.Threading;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.Chat;
using osu.Game.Overlays.Chat;
namespace osu.Game.Overlays
{
public class ChatOverlay : OsuFocusedOverlayContainer, IOnlineComponent
public class ChatOverlay : OsuFocusedOverlayContainer
{
private const float textbox_height = 60;
private const float channel_selection_min_height = 0.3f;
private ScheduledDelegate messageRequest;
private ChatManager chatManager;
private readonly Container<DrawableChannel> currentChannelContainer;
private readonly Container<DrawableChat> currentChannelContainer;
private readonly List<DrawableChat> loadedChannels = new List<DrawableChat>();
private readonly LoadingAnimation loading;
private readonly FocusedTextBox textbox;
private APIAccess api;
private const int transition_length = 500;
public const float DEFAULT_HEIGHT = 0.4f;
public const float TAB_AREA_HEIGHT = 50;
private GetChannelMessagesRequest fetchReq;
private readonly ChatTabControl channelTabs;
private readonly Container chatContainer;
@ -60,10 +54,10 @@ namespace osu.Game.Overlays
public Bindable<double> ChatHeight { get; set; }
public List<ChannelChat> AvailableChannels { get; private set; } = new List<ChannelChat>();
private readonly Container channelSelectionContainer;
private readonly ChannelSelectionOverlay channelSelection;
public override bool Contains(Vector2 screenSpacePos) => chatContainer.ReceiveMouseInputAt(screenSpacePos) || channelSelection.State == Visibility.Visible && channelSelection.ReceiveMouseInputAt(screenSpacePos);
public ChatOverlay()
@ -110,7 +104,7 @@ namespace osu.Game.Overlays
{
RelativeSizeAxes = Axes.Both,
},
currentChannelContainer = new Container<DrawableChannel>
currentChannelContainer = new Container<DrawableChat>
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding
@ -163,7 +157,7 @@ namespace osu.Game.Overlays
channelTabs = new ChatTabControl
{
RelativeSizeAxes = Axes.Both,
OnRequestLeave = removeChannel,
OnRequestLeave = channel => chatManager.JoinedChannels.Remove(channel),
},
}
},
@ -171,7 +165,7 @@ namespace osu.Game.Overlays
},
};
channelTabs.Current.ValueChanged += newChannel => CurrentChannel = newChannel;
channelTabs.Current.ValueChanged += newChannel => chatManager.CurrentChat.Value = newChannel;
channelTabs.ChannelSelectorActive.ValueChanged += value => channelSelection.State = value ? Visibility.Visible : Visibility.Hidden;
channelSelection.StateChanged += state =>
{
@ -186,13 +180,97 @@ namespace osu.Game.Overlays
else
textbox.HoldFocus = true;
};
channelSelection.OnRequestJoin = channel =>
{
if (!chatManager.JoinedChannels.Contains(channel))
chatManager.JoinedChannels.Add(channel);
};
channelSelection.OnRequestLeave = channel => chatManager.JoinedChannels.Remove(channel);
}
private void availableChannelsChanged(object sender, NotifyCollectionChangedEventArgs args)
{
channelSelection.Sections = new[]
{
new ChannelSection
{
Header = "All Channels",
Channels = chatManager.AvailableChannels,
},
};
}
private void joinedChannelsChanged(object sender, NotifyCollectionChangedEventArgs args)
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (ChannelChat newChannel in args.NewItems)
{
channelTabs.AddItem(newChannel);
newChannel.Joined.Value = true;
if (chatManager.CurrentChat.Value == null)
{
chatManager.CurrentChat.Value = newChannel;
}
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (ChannelChat removedChannel in args.OldItems)
{
channelTabs.RemoveItem(removedChannel);
loadedChannels.Remove(loadedChannels.Find(c => c.Chat == removedChannel ));
removedChannel.Joined.Value = false;
if (chatManager.CurrentChat.Value == removedChannel)
chatManager.CurrentChat.Value = null;
}
break;
}
}
private void currentChatChanged(ChatBase chat)
{
if (chat == null)
{
textbox.Current.Disabled = true;
currentChannelContainer.Clear(false);
return;
}
textbox.Current.Disabled = chat.ReadOnly;
if (chat is ChannelChat channelChat)
channelTabs.Current.Value = channelChat;
var loaded = loadedChannels.Find(d => d.Chat == chat);
if (loaded == null)
{
currentChannelContainer.FadeOut(500, Easing.OutQuint);
loading.Show();
loaded = new DrawableChat(chat);
loadedChannels.Add(loaded);
LoadComponentAsync(loaded, l =>
{
loading.Hide();
currentChannelContainer.Clear(false);
currentChannelContainer.Add(loaded);
currentChannelContainer.FadeIn(500, Easing.OutQuint);
});
}
else
{
currentChannelContainer.Clear(false);
currentChannelContainer.Add(loaded);
}
}
private double startDragChatHeight;
private bool isDragging;
public void OpenChannel(ChannelChat channel) => addChannel(channel);
protected override bool OnDragStart(InputState state)
{
isDragging = tabsArea.IsHovered;
@ -229,19 +307,6 @@ namespace osu.Game.Overlays
return base.OnDragEnd(state);
}
public void APIStateChanged(APIAccess api, APIState state)
{
switch (state)
{
case APIState.Online:
initializeChannels();
break;
default:
messageRequest?.Cancel();
break;
}
}
public override bool AcceptsFocus => true;
protected override void OnFocus(InputState state)
@ -270,10 +335,9 @@ namespace osu.Game.Overlays
}
[BackgroundDependencyLoader]
private void load(APIAccess api, OsuConfigManager config, OsuColour colours)
private void load(APIAccess api, OsuConfigManager config, OsuColour colours, ChatManager chatManager)
{
this.api = api;
api.Register(this);
api.Register(chatManager);
ChatHeight = config.GetBindable<double>(OsuSetting.ChatDisplayHeight);
ChatHeight.ValueChanged += h =>
@ -285,253 +349,27 @@ namespace osu.Game.Overlays
ChatHeight.TriggerChange();
chatBackground.Colour = colours.ChatBlue;
}
private long? lastMessageId;
private readonly List<ChannelChat> careChannels = new List<ChannelChat>();
private readonly List<DrawableChannel> loadedChannels = new List<DrawableChannel>();
private void initializeChannels()
{
loading.Show();
messageRequest?.Cancel();
ListChannelsRequest req = new ListChannelsRequest();
req.Success += delegate (List<ChannelChat> channels)
{
AvailableChannels = channels;
Scheduler.Add(delegate
{
addChannel(channels.Find(c => c.Name == @"#lazer"));
addChannel(channels.Find(c => c.Name == @"#osu"));
addChannel(channels.Find(c => c.Name == @"#lobby"));
channelSelection.OnRequestJoin = addChannel;
channelSelection.OnRequestLeave = removeChannel;
channelSelection.Sections = new[]
{
new ChannelSection
{
Header = "All Channels",
Channels = channels,
},
};
});
messageRequest = Scheduler.AddDelayed(fetchNewMessages, 1000, true);
};
api.Queue(req);
}
private ChannelChat currentChannel;
protected ChannelChat CurrentChannel
{
get
{
return currentChannel;
}
set
{
if (currentChannel == value) return;
if (value == null)
{
currentChannel = null;
textbox.Current.Disabled = true;
currentChannelContainer.Clear(false);
return;
}
currentChannel = value;
textbox.Current.Disabled = currentChannel.ReadOnly;
channelTabs.Current.Value = value;
var loaded = loadedChannels.Find(d => d.Channel == value);
if (loaded == null)
{
currentChannelContainer.FadeOut(500, Easing.OutQuint);
loading.Show();
loaded = new DrawableChannel(currentChannel);
loadedChannels.Add(loaded);
LoadComponentAsync(loaded, l =>
{
if (currentChannel.Messages.Any())
loading.Hide();
currentChannelContainer.Clear(false);
currentChannelContainer.Add(loaded);
currentChannelContainer.FadeIn(500, Easing.OutQuint);
});
}
else
{
currentChannelContainer.Clear(false);
currentChannelContainer.Add(loaded);
}
}
}
private void addChannel(ChannelChat channel)
{
if (channel == null) return;
// ReSharper disable once AccessToModifiedClosure
var existing = careChannels.Find(c => c.Id == channel.Id);
if (existing != null)
{
// if we already have this channel loaded, we don't want to make a second one.
channel = existing;
}
else
{
careChannels.Add(channel);
channelTabs.AddItem(channel);
}
// let's fetch a small number of messages to bring us up-to-date with the backlog.
fetchInitialMessages(channel);
if (CurrentChannel == null)
CurrentChannel = channel;
channel.Joined.Value = true;
}
private void removeChannel(ChannelChat channel)
{
if (channel == null) return;
if (channel == CurrentChannel) CurrentChannel = null;
careChannels.Remove(channel);
loadedChannels.Remove(loadedChannels.Find(c => c.Channel == channel));
channelTabs.RemoveItem(channel);
channel.Joined.Value = false;
}
private void fetchInitialMessages(ChannelChat channel)
{
var req = new GetChannelMessagesRequest(new List<ChannelChat> { channel }, null);
req.Success += delegate (List<Message> messages)
{
loading.Hide();
channel.AddNewMessages(messages.ToArray());
Debug.Write("success!");
};
req.Failure += delegate
{
Debug.Write("failure!");
};
api.Queue(req);
}
private void fetchNewMessages()
{
if (fetchReq != null) return;
fetchReq = new GetChannelMessagesRequest(careChannels, lastMessageId);
fetchReq.Success += delegate (List<Message> messages)
{
foreach (var group in messages.Where(m => m.TargetType == TargetType.Channel).GroupBy(m => m.TargetId))
careChannels.Find(c => c.Id == group.Key)?.AddNewMessages(group.ToArray());
lastMessageId = messages.LastOrDefault()?.Id ?? lastMessageId;
Debug.Write("success!");
fetchReq = null;
};
fetchReq.Failure += delegate
{
Debug.Write("failure!");
fetchReq = null;
};
api.Queue(fetchReq);
this.chatManager = chatManager;
chatManager.CurrentChat.ValueChanged += currentChatChanged;
chatManager.JoinedChannels.CollectionChanged += joinedChannelsChanged;
chatManager.AvailableChannels.CollectionChanged += availableChannelsChanged;
}
private void postMessage(TextBox textbox, bool newText)
{
var postText = textbox.Text;
var text = textbox.Text.Trim();
if (string.IsNullOrWhiteSpace(text))
return;
if (text[0] == '/')
chatManager.PostCommand(text.Substring(1));
else
chatManager.PostMessage(text);
textbox.Text = string.Empty;
if (string.IsNullOrWhiteSpace(postText))
return;
var target = currentChannel;
if (target == null) return;
if (!api.IsLoggedIn)
{
target.AddNewMessages(new ErrorMessage("Please sign in to participate in chat!"));
return;
}
bool isAction = false;
if (postText[0] == '/')
{
string[] parameters = postText.Substring(1).Split(new[] { ' ' }, 2);
string command = parameters[0];
string content = parameters.Length == 2 ? parameters[1] : string.Empty;
switch (command)
{
case "me":
if (string.IsNullOrWhiteSpace(content))
{
currentChannel.AddNewMessages(new ErrorMessage("Usage: /me [action]"));
return;
}
isAction = true;
postText = content;
break;
case "help":
currentChannel.AddNewMessages(new InfoMessage("Supported commands: /help, /me [action]"));
return;
default:
currentChannel.AddNewMessages(new ErrorMessage($@"""/{command}"" is not supported! For a list of supported commands see /help"));
return;
}
}
var message = new LocalEchoMessage
{
Sender = api.LocalUser.Value,
Timestamp = DateTimeOffset.Now,
TargetType = TargetType.Channel, //TODO: read this from channel
TargetId = target.Id,
IsAction = isAction,
Content = postText
};
var req = new PostMessageRequest(message);
target.AddLocalEcho(message);
req.Failure += e => target.ReplaceMessage(message, null);
req.Success += m => target.ReplaceMessage(message, m);
api.Queue(req);
}
private void transformChatHeightTo(double newChatHeight, double duration = 0, Easing easing = Easing.None)