Files
ClubPenguinClient/MareSynchronos/UI/CompactUI.cs
Loporrit d601b6fcd1 Merge tag '0.9.17' into mare-classic
* tag '0.9.17':
  add census popup on connection
  api update
  census update
  heave fewer redraws as main method for data application, minor fixes
  remove unnecessary exists check
  add visibility for loaded mods size for pair, use menu bar for settings, remove settings button
  fix staging issues
  add download throttling, change header of mare, fix reverting players when going offline/paused when not visible
  use name for glamourer revert
  fix startup breaking
  add inner exception stacktraces
  calc correct button size
  wording
  add permission popup ui
  fix getting identifier during zoning
  indent nonscaled
  remove unnecessary usings
  ui icon boogaloo
  fix cache dict wtf
  add normalized icons
  add owner/moderator/pinned user icons
  check tokentime more precisely in both directions
  more cleanup
  fix sorting and cleanup
  make local groups more usable for pause/resume
  fix outlined font
  rework creation of popout windows into factory and some refactoring in general
  make syncshell admin ui to standalone window
  remove close button on intro ui
  do not allow to open main ui without finishing setup
  readonly bla
  wait for plugin disposal
  fix palette
  wording
  fix palette application and add experimental less redraws option
  some minor fixes
  check for timezone
  idk
  adjust token handling
  fix total user count in syncshell (distinct by UIDs)
  fix text alignment
  fix some shit maybe
  idk some fixes I guess
  fix offset for transfer bar at the bottom, use async collections, clear filter on tab change + add button to clear, require ctrl for align syncshells
  blah
  Some display options for DTR tooltip (#66)
  add ordering
  adjust api to latest
  rework main ui
  add total count on mouseover, make syncshell windows non-blocking
  fix token for character change, add online count to syncshells and groups
  argh
  fix broken font in header
  add more options for the compactui
  fix icons and text of buttons being static in place
  remove logspam
2023-12-08 16:35:14 +00:00

639 lines
28 KiB
C#

using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Reflection;
using Dalamud.Interface;
using Dalamud.Interface.Colors;
using Dalamud.Interface.Components;
using Dalamud.Interface.Utility;
using Dalamud.Interface.Utility.Raii;
using Dalamud.Utility;
using ImGuiNET;
using MareSynchronos.API.Data.Extensions;
using MareSynchronos.API.Dto.User;
using MareSynchronos.MareConfiguration;
using MareSynchronos.PlayerData.Handlers;
using MareSynchronos.PlayerData.Pairs;
using MareSynchronos.Services.Mediator;
using MareSynchronos.Services.ServerConfiguration;
using MareSynchronos.UI.Components;
using MareSynchronos.UI.Handlers;
using MareSynchronos.WebAPI;
using MareSynchronos.WebAPI.Files;
using MareSynchronos.WebAPI.Files.Models;
using MareSynchronos.WebAPI.SignalR.Utils;
using Microsoft.Extensions.Logging;
namespace MareSynchronos.UI;
public class CompactUi : WindowMediatorSubscriberBase
{
public float TransferPartHeight;
public float WindowContentWidth;
private readonly ApiController _apiController;
private readonly MareConfigService _configService;
private readonly ConcurrentDictionary<GameObjectHandler, Dictionary<string, FileDownloadStatus>> _currentDownloads = new();
private readonly FileUploadManager _fileTransferManager;
private readonly GroupPanel _groupPanel;
private readonly PairGroupsUi _pairGroupsUi;
private readonly PairManager _pairManager;
private readonly SelectGroupForPairUi _selectGroupForPairUi;
private readonly SelectPairForGroupUi _selectPairsForGroupUi;
private readonly ServerConfigurationManager _serverManager;
private readonly Stopwatch _timeout = new();
private readonly UidDisplayHandler _uidDisplayHandler;
private readonly UiSharedService _uiShared;
private bool _buttonState;
private string _characterOrCommentFilter = string.Empty;
private Pair? _lastAddedUser;
private string _lastAddedUserComment = string.Empty;
private Vector2 _lastPosition = Vector2.One;
private Vector2 _lastSize = Vector2.One;
private string _pairToAdd = string.Empty;
private int _secretKeyIdx = -1;
private bool _showModalForUserAddition;
private bool _showSyncShells;
private bool _wasOpen;
public CompactUi(ILogger<CompactUi> logger, UiSharedService uiShared, MareConfigService configService, ApiController apiController, PairManager pairManager,
ServerConfigurationManager serverManager, MareMediator mediator, FileUploadManager fileTransferManager, UidDisplayHandler uidDisplayHandler) : base(logger, mediator, "###MareSynchronosMainUI")
{
_uiShared = uiShared;
_configService = configService;
_apiController = apiController;
_pairManager = pairManager;
_serverManager = serverManager;
_fileTransferManager = fileTransferManager;
_uidDisplayHandler = uidDisplayHandler;
var tagHandler = new TagHandler(_serverManager);
_groupPanel = new(this, uiShared, _pairManager, uidDisplayHandler, _serverManager);
_selectGroupForPairUi = new(tagHandler, uidDisplayHandler);
_selectPairsForGroupUi = new(tagHandler, uidDisplayHandler);
_pairGroupsUi = new(configService, tagHandler, apiController, _selectPairsForGroupUi);
#if DEBUG
string dev = "Dev Build";
var ver = Assembly.GetExecutingAssembly().GetName().Version!;
WindowName = $"Mare Synchronos {dev} ({ver.Major}.{ver.Minor}.{ver.Build})###MareSynchronosMainUI";
Toggle();
#else
var ver = Assembly.GetExecutingAssembly().GetName().Version;
WindowName = "Mare Synchronos " + ver.Major + "." + ver.Minor + "." + ver.Build + "###MareSynchronosMainUI";
#endif
Mediator.Subscribe<SwitchToMainUiMessage>(this, (_) => IsOpen = true);
Mediator.Subscribe<SwitchToIntroUiMessage>(this, (_) => IsOpen = false);
Mediator.Subscribe<CutsceneStartMessage>(this, (_) => UiSharedService_GposeStart());
Mediator.Subscribe<CutsceneEndMessage>(this, (_) => UiSharedService_GposeEnd());
Mediator.Subscribe<DownloadStartedMessage>(this, (msg) => _currentDownloads[msg.DownloadId] = msg.DownloadStatus);
Mediator.Subscribe<DownloadFinishedMessage>(this, (msg) => _currentDownloads.TryRemove(msg.DownloadId, out _));
Flags |= ImGuiWindowFlags.NoDocking;
SizeConstraints = new WindowSizeConstraints()
{
MinimumSize = new Vector2(350, 400),
MaximumSize = new Vector2(350, 2000),
};
}
public override void Draw()
{
WindowContentWidth = UiSharedService.GetWindowContentRegionWidth();
if (!_apiController.IsCurrentVersion)
{
var ver = _apiController.CurrentClientVersion;
if (_uiShared.UidFontBuilt) ImGui.PushFont(_uiShared.UidFont);
var unsupported = "UNSUPPORTED VERSION";
var uidTextSize = ImGui.CalcTextSize(unsupported);
ImGui.SetCursorPosX((ImGui.GetWindowContentRegionMax().X + ImGui.GetWindowContentRegionMin().X) / 2 - uidTextSize.X / 2);
ImGui.TextColored(ImGuiColors.DalamudRed, unsupported);
if (_uiShared.UidFontBuilt) ImGui.PopFont();
UiSharedService.ColorTextWrapped($"Your Mare Synchronos installation is out of date, the current version is {ver.Major}.{ver.Minor}.{ver.Build}. " +
$"It is highly recommended to keep Mare Synchronos up to date. Open /xlplugins and update the plugin.", ImGuiColors.DalamudRed);
}
using (ImRaii.PushId("header")) DrawUIDHeader();
ImGui.Separator();
using (ImRaii.PushId("serverstatus")) DrawServerStatus();
if (_apiController.ServerState is ServerState.Connected)
{
var hasShownSyncShells = _showSyncShells;
ImGui.PushFont(UiBuilder.IconFont);
if (!hasShownSyncShells)
{
ImGui.PushStyleColor(ImGuiCol.Button, ImGui.GetStyle().Colors[(int)ImGuiCol.ButtonHovered]);
}
if (ImGui.Button(FontAwesomeIcon.User.ToIconString(), new Vector2((UiSharedService.GetWindowContentRegionWidth() - ImGui.GetWindowContentRegionMin().X) / 2, 30 * ImGuiHelpers.GlobalScale)))
{
_showSyncShells = false;
}
if (!hasShownSyncShells)
{
ImGui.PopStyleColor();
}
ImGui.PopFont();
UiSharedService.AttachToolTip("Individual pairs");
ImGui.SameLine();
ImGui.PushFont(UiBuilder.IconFont);
if (hasShownSyncShells)
{
ImGui.PushStyleColor(ImGuiCol.Button, ImGui.GetStyle().Colors[(int)ImGuiCol.ButtonHovered]);
}
if (ImGui.Button(FontAwesomeIcon.UserFriends.ToIconString(), new Vector2((UiSharedService.GetWindowContentRegionWidth() - ImGui.GetWindowContentRegionMin().X) / 2, 30 * ImGuiHelpers.GlobalScale)))
{
_showSyncShells = true;
}
if (hasShownSyncShells)
{
ImGui.PopStyleColor();
}
ImGui.PopFont();
UiSharedService.AttachToolTip("Syncshells");
ImGui.Separator();
if (!hasShownSyncShells)
{
using (ImRaii.PushId("pairlist")) DrawPairList();
}
else
{
using (ImRaii.PushId("syncshells")) _groupPanel.DrawSyncshells();
}
ImGui.Separator();
using (ImRaii.PushId("transfers")) DrawTransfers();
TransferPartHeight = ImGui.GetCursorPosY() - TransferPartHeight;
using (ImRaii.PushId("group-user-popup")) _selectPairsForGroupUi.Draw(_pairManager.DirectPairs);
using (ImRaii.PushId("grouping-popup")) _selectGroupForPairUi.Draw();
}
if (_configService.Current.OpenPopupOnAdd && _pairManager.LastAddedUser != null)
{
_lastAddedUser = _pairManager.LastAddedUser;
_pairManager.LastAddedUser = null;
ImGui.OpenPopup("Set Notes for New User");
_showModalForUserAddition = true;
_lastAddedUserComment = string.Empty;
}
if (ImGui.BeginPopupModal("Set Notes for New User", ref _showModalForUserAddition, UiSharedService.PopupWindowFlags))
{
if (_lastAddedUser == null)
{
_showModalForUserAddition = false;
}
else
{
UiSharedService.TextWrapped($"You have successfully added {_lastAddedUser.UserData.AliasOrUID}. Set a local note for the user in the field below:");
ImGui.InputTextWithHint("##noteforuser", $"Note for {_lastAddedUser.UserData.AliasOrUID}", ref _lastAddedUserComment, 100);
if (UiSharedService.NormalizedIconTextButton(FontAwesomeIcon.Save, "Save Note"))
{
_serverManager.SetNoteForUid(_lastAddedUser.UserData.UID, _lastAddedUserComment);
_lastAddedUser = null;
_lastAddedUserComment = string.Empty;
_showModalForUserAddition = false;
}
}
UiSharedService.SetScaledWindowSize(275);
ImGui.EndPopup();
}
var pos = ImGui.GetWindowPos();
var size = ImGui.GetWindowSize();
if (_lastSize != size || _lastPosition != pos)
{
_lastSize = size;
_lastPosition = pos;
Mediator.Publish(new CompactUiChange(_lastSize, _lastPosition));
}
}
public override void OnClose()
{
_uidDisplayHandler.Clear();
base.OnClose();
}
private void DrawAddCharacter()
{
ImGui.Dummy(new(10));
var keys = _serverManager.CurrentServer!.SecretKeys;
if (keys.Any())
{
if (_secretKeyIdx == -1) _secretKeyIdx = keys.First().Key;
if (UiSharedService.NormalizedIconTextButton(FontAwesomeIcon.Plus, "Add current character with secret key"))
{
_serverManager.CurrentServer!.Authentications.Add(new MareConfiguration.Models.Authentication()
{
CharacterName = _uiShared.PlayerName,
WorldId = _uiShared.WorldId,
SecretKeyIdx = _secretKeyIdx
});
_serverManager.Save();
_ = _apiController.CreateConnections();
}
_uiShared.DrawCombo("Secret Key##addCharacterSecretKey", keys, (f) => f.Value.FriendlyName, (f) => _secretKeyIdx = f.Key);
}
else
{
UiSharedService.ColorTextWrapped("No secret keys are configured for the current server.", ImGuiColors.DalamudYellow);
}
}
private void DrawAddPair()
{
var buttonSize = UiSharedService.GetIconButtonSize(FontAwesomeIcon.Plus);
ImGui.SetNextItemWidth(UiSharedService.GetWindowContentRegionWidth() - ImGui.GetWindowContentRegionMin().X - buttonSize.X);
ImGui.InputTextWithHint("##otheruid", "Other players UID/Alias", ref _pairToAdd, 20);
ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiSharedService.GetWindowContentRegionWidth() - buttonSize.X);
var canAdd = !_pairManager.DirectPairs.Any(p => string.Equals(p.UserData.UID, _pairToAdd, StringComparison.Ordinal) || string.Equals(p.UserData.Alias, _pairToAdd, StringComparison.Ordinal));
if (!canAdd)
{
ImGuiComponents.DisabledButton(FontAwesomeIcon.Plus);
}
else
{
if (ImGuiComponents.IconButton(FontAwesomeIcon.Plus))
{
_ = _apiController.UserAddPair(new(new(_pairToAdd)));
_pairToAdd = string.Empty;
}
UiSharedService.AttachToolTip("Pair with " + (_pairToAdd.IsNullOrEmpty() ? "other user" : _pairToAdd));
}
ImGuiHelpers.ScaledDummy(2);
}
private void DrawFilter()
{
var buttonSize = UiSharedService.GetIconButtonSize(FontAwesomeIcon.ArrowUp);
var playButtonSize = UiSharedService.GetIconButtonSize(FontAwesomeIcon.Play);
var users = GetFilteredUsers();
var userCount = users.Count;
var spacing = userCount > 0
? playButtonSize.X + ImGui.GetStyle().ItemSpacing.X
: 0;
ImGui.SetNextItemWidth(WindowContentWidth - spacing);
ImGui.InputTextWithHint("##filter", "Filter for UID/notes", ref _characterOrCommentFilter, 255);
if (userCount == 0) return;
var pausedUsers = users.Where(u => u.UserPair!.OwnPermissions.IsPaused() && u.UserPair.OtherPermissions.IsPaired()).ToList();
var resumedUsers = users.Where(u => !u.UserPair!.OwnPermissions.IsPaused() && u.UserPair.OtherPermissions.IsPaired()).ToList();
if (!pausedUsers.Any() && !resumedUsers.Any()) return;
ImGui.SameLine();
switch (_buttonState)
{
case true when !pausedUsers.Any():
_buttonState = false;
break;
case false when !resumedUsers.Any():
_buttonState = true;
break;
case true:
users = pausedUsers;
break;
case false:
users = resumedUsers;
break;
}
var button = _buttonState ? FontAwesomeIcon.Play : FontAwesomeIcon.Pause;
if (!_timeout.IsRunning || _timeout.ElapsedMilliseconds > 15000)
{
_timeout.Reset();
if (ImGuiComponents.IconButton(button) && UiSharedService.CtrlPressed())
{
foreach (var entry in users)
{
var perm = entry.UserPair!.OwnPermissions;
perm.SetPaused(!perm.IsPaused());
_ = _apiController.UserSetPairPermissions(new UserPermissionsDto(entry.UserData, perm));
}
_timeout.Start();
_buttonState = !_buttonState;
}
UiSharedService.AttachToolTip($"Hold Control to {(button == FontAwesomeIcon.Play ? "resume" : "pause")} pairing with {users.Count} out of {userCount} displayed users.");
}
else
{
var availableAt = (15000 - _timeout.ElapsedMilliseconds) / 1000;
ImGuiComponents.DisabledButton(button);
UiSharedService.AttachToolTip($"Next execution is available at {availableAt} seconds");
}
}
private void DrawPairList()
{
using (ImRaii.PushId("addpair")) DrawAddPair();
using (ImRaii.PushId("pairs")) DrawPairs();
TransferPartHeight = ImGui.GetCursorPosY();
using (ImRaii.PushId("filter")) DrawFilter();
}
private void DrawPairs()
{
var ySize = TransferPartHeight == 0
? 1
: (ImGui.GetWindowContentRegionMax().Y - ImGui.GetWindowContentRegionMin().Y) - TransferPartHeight - ImGui.GetCursorPosY();
var users = GetFilteredUsers()
.OrderBy(
u => _configService.Current.ShowCharacterNameInsteadOfNotesForVisible && !string.IsNullOrEmpty(u.PlayerName)
? (_configService.Current.PreferNotesOverNamesForVisible ? u.GetNote() : u.PlayerName)
: (u.GetNote() ?? u.UserData.AliasOrUID), StringComparer.OrdinalIgnoreCase).ToList();
var onlineUsers = users.Where(u => u.IsOnline || u.UserPair!.OwnPermissions.IsPaused()).Select(c => new DrawUserPair("Online" + c.UserData.UID, c, _uidDisplayHandler, _apiController, Mediator, _selectGroupForPairUi)).ToList();
var visibleUsers = users.Where(u => u.IsVisible).Select(c => new DrawUserPair("Visible" + c.UserData.UID, c, _uidDisplayHandler, _apiController, Mediator, _selectGroupForPairUi)).ToList();
var offlineUsers = users.Where(u => !u.IsOnline && !u.UserPair!.OwnPermissions.IsPaused()).Select(c => new DrawUserPair("Offline" + c.UserData.UID, c, _uidDisplayHandler, _apiController, Mediator, _selectGroupForPairUi)).ToList();
ImGui.BeginChild("list", new Vector2(WindowContentWidth, ySize), border: false);
_pairGroupsUi.Draw(visibleUsers, onlineUsers, offlineUsers);
ImGui.EndChild();
}
private void DrawServerStatus()
{
var buttonSize = UiSharedService.GetIconButtonSize(FontAwesomeIcon.Link);
var userCount = _apiController.OnlineUsers.ToString(CultureInfo.InvariantCulture);
var userSize = ImGui.CalcTextSize(userCount);
var textSize = ImGui.CalcTextSize("Users Online");
#if DEBUG
string shardConnection = $"Shard: {_apiController.ServerInfo.ShardName}";
#else
string shardConnection = string.Equals(_apiController.ServerInfo.ShardName, "Main", StringComparison.OrdinalIgnoreCase) ? string.Empty : $"Shard: {_apiController.ServerInfo.ShardName}";
#endif
var shardTextSize = ImGui.CalcTextSize(shardConnection);
var printShard = !string.IsNullOrEmpty(_apiController.ServerInfo.ShardName) && shardConnection != string.Empty;
if (_apiController.ServerState is ServerState.Connected)
{
ImGui.SetCursorPosX((ImGui.GetWindowContentRegionMin().X + UiSharedService.GetWindowContentRegionWidth()) / 2 - (userSize.X + textSize.X) / 2 - ImGui.GetStyle().ItemSpacing.X / 2);
if (!printShard) ImGui.AlignTextToFramePadding();
ImGui.TextColored(ImGuiColors.ParsedGreen, userCount);
ImGui.SameLine();
if (!printShard) ImGui.AlignTextToFramePadding();
ImGui.TextUnformatted("Users Online");
}
else
{
ImGui.AlignTextToFramePadding();
ImGui.TextColored(ImGuiColors.DalamudRed, "Not connected to any server");
}
if (printShard)
{
ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetStyle().ItemSpacing.Y);
ImGui.SetCursorPosX((ImGui.GetWindowContentRegionMin().X + UiSharedService.GetWindowContentRegionWidth()) / 2 - shardTextSize.X / 2);
ImGui.TextUnformatted(shardConnection);
}
ImGui.SameLine();
if (printShard)
{
ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ((userSize.Y + textSize.Y) / 2 + shardTextSize.Y) / 2 - ImGui.GetStyle().ItemSpacing.Y + buttonSize.Y / 2);
}
var color = UiSharedService.GetBoolColor(!_serverManager.CurrentServer!.FullPause);
var connectedIcon = !_serverManager.CurrentServer.FullPause ? FontAwesomeIcon.Link : FontAwesomeIcon.Unlink;
if (_apiController.ServerState is ServerState.Connected)
{
ImGui.SetCursorPosX(0 + ImGui.GetStyle().ItemSpacing.X);
if (ImGuiComponents.IconButton(FontAwesomeIcon.UserCircle))
{
Mediator.Publish(new UiToggleMessage(typeof(EditProfileUi)));
}
UiSharedService.AttachToolTip("Edit your Mare Profile");
}
ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiSharedService.GetWindowContentRegionWidth() - buttonSize.X);
if (printShard)
{
ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ((userSize.Y + textSize.Y) / 2 + shardTextSize.Y) / 2 - ImGui.GetStyle().ItemSpacing.Y + buttonSize.Y / 2);
}
if (_apiController.ServerState is not (ServerState.Reconnecting or ServerState.Disconnecting))
{
ImGui.PushStyleColor(ImGuiCol.Text, color);
if (ImGuiComponents.IconButton(connectedIcon))
{
_serverManager.CurrentServer.FullPause = !_serverManager.CurrentServer.FullPause;
_serverManager.Save();
_ = _apiController.CreateConnections();
}
ImGui.PopStyleColor();
UiSharedService.AttachToolTip(!_serverManager.CurrentServer.FullPause ? "Disconnect from " + _serverManager.CurrentServer.ServerName : "Connect to " + _serverManager.CurrentServer.ServerName);
}
}
private void DrawTransfers()
{
var currentUploads = _fileTransferManager.CurrentUploads.ToList();
ImGui.PushFont(UiBuilder.IconFont);
ImGui.TextUnformatted(FontAwesomeIcon.Upload.ToIconString());
ImGui.PopFont();
ImGui.SameLine(35 * ImGuiHelpers.GlobalScale);
if (currentUploads.Any())
{
var totalUploads = currentUploads.Count;
var doneUploads = currentUploads.Count(c => c.IsTransferred);
var totalUploaded = currentUploads.Sum(c => c.Transferred);
var totalToUpload = currentUploads.Sum(c => c.Total);
ImGui.TextUnformatted($"{doneUploads}/{totalUploads}");
var uploadText = $"({UiSharedService.ByteToString(totalUploaded)}/{UiSharedService.ByteToString(totalToUpload)})";
var textSize = ImGui.CalcTextSize(uploadText);
ImGui.SameLine(WindowContentWidth - textSize.X);
ImGui.TextUnformatted(uploadText);
}
else
{
ImGui.TextUnformatted("No uploads in progress");
}
var currentDownloads = _currentDownloads.SelectMany(d => d.Value.Values).ToList();
ImGui.PushFont(UiBuilder.IconFont);
ImGui.TextUnformatted(FontAwesomeIcon.Download.ToIconString());
ImGui.PopFont();
ImGui.SameLine(35 * ImGuiHelpers.GlobalScale);
if (currentDownloads.Any())
{
var totalDownloads = currentDownloads.Sum(c => c.TotalFiles);
var doneDownloads = currentDownloads.Sum(c => c.TransferredFiles);
var totalDownloaded = currentDownloads.Sum(c => c.TransferredBytes);
var totalToDownload = currentDownloads.Sum(c => c.TotalBytes);
ImGui.TextUnformatted($"{doneDownloads}/{totalDownloads}");
var downloadText =
$"({UiSharedService.ByteToString(totalDownloaded)}/{UiSharedService.ByteToString(totalToDownload)})";
var textSize = ImGui.CalcTextSize(downloadText);
ImGui.SameLine(WindowContentWidth - textSize.X);
ImGui.TextUnformatted(downloadText);
}
else
{
ImGui.TextUnformatted("No downloads in progress");
}
if (UiSharedService.NormalizedIconTextButton(FontAwesomeIcon.PersonCircleQuestion, "Mare Character Data Analysis", WindowContentWidth))
{
Mediator.Publish(new UiToggleMessage(typeof(DataAnalysisUi)));
}
ImGui.SameLine();
}
private void DrawUIDHeader()
{
var uidText = GetUidText();
var buttonSizeX = 0f;
if (_uiShared.UidFontBuilt) ImGui.PushFont(_uiShared.UidFont);
var uidTextSize = ImGui.CalcTextSize(uidText);
if (_uiShared.UidFontBuilt) ImGui.PopFont();
var originalPos = ImGui.GetCursorPos();
ImGui.SetWindowFontScale(1.5f);
var buttonSize = UiSharedService.GetIconButtonSize(FontAwesomeIcon.Cog);
buttonSizeX -= buttonSize.X - ImGui.GetStyle().ItemSpacing.X * 2;
ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiSharedService.GetWindowContentRegionWidth() - buttonSize.X);
ImGui.SetCursorPosY(originalPos.Y + uidTextSize.Y / 2 - buttonSize.Y / 2);
if (ImGuiComponents.IconButton(FontAwesomeIcon.Cog))
{
Mediator.Publish(new OpenSettingsUiMessage());
}
UiSharedService.AttachToolTip("Open the Mare Synchronos Settings");
ImGui.SameLine(); //Important to draw the uidText consistently
ImGui.SetCursorPos(originalPos);
if (_apiController.ServerState is ServerState.Connected)
{
buttonSizeX += UiSharedService.GetIconButtonSize(FontAwesomeIcon.Copy).X - ImGui.GetStyle().ItemSpacing.X * 2;
ImGui.SetCursorPosY(originalPos.Y + uidTextSize.Y / 2 - buttonSize.Y / 2);
if (ImGuiComponents.IconButton(FontAwesomeIcon.Copy))
{
ImGui.SetClipboardText(_apiController.DisplayName);
}
UiSharedService.AttachToolTip("Copy your UID to clipboard");
ImGui.SameLine();
}
ImGui.SetWindowFontScale(1f);
ImGui.SetCursorPosY(originalPos.Y + buttonSize.Y / 2 - uidTextSize.Y / 2 - ImGui.GetStyle().ItemSpacing.Y / 2);
ImGui.SetCursorPosX((ImGui.GetWindowContentRegionMax().X + ImGui.GetWindowContentRegionMin().X) / 2 + buttonSizeX - uidTextSize.X / 2);
if (_uiShared.UidFontBuilt) ImGui.PushFont(_uiShared.UidFont);
ImGui.TextColored(GetUidColor(), uidText);
if (_uiShared.UidFontBuilt) ImGui.PopFont();
if (_apiController.ServerState is not ServerState.Connected)
{
UiSharedService.ColorTextWrapped(GetServerError(), GetUidColor());
if (_apiController.ServerState is ServerState.NoSecretKey)
{
DrawAddCharacter();
}
}
}
private List<Pair> GetFilteredUsers()
{
return _pairManager.DirectPairs.Where(p =>
{
if (_characterOrCommentFilter.IsNullOrEmpty()) return true;
return p.UserData.AliasOrUID.Contains(_characterOrCommentFilter, StringComparison.OrdinalIgnoreCase) ||
(p.GetNote()?.Contains(_characterOrCommentFilter, StringComparison.OrdinalIgnoreCase) ?? false) ||
(p.PlayerName?.Contains(_characterOrCommentFilter, StringComparison.OrdinalIgnoreCase) ?? false);
}).ToList();
}
private string GetServerError()
{
return _apiController.ServerState switch
{
ServerState.Connecting => "Attempting to connect to the server.",
ServerState.Reconnecting => "Connection to server interrupted, attempting to reconnect to the server.",
ServerState.Disconnected => "You are currently disconnected from the Mare Synchronos server.",
ServerState.Disconnecting => "Disconnecting from the server",
ServerState.Unauthorized => "Server Response: " + _apiController.AuthFailureMessage,
ServerState.Offline => "Your selected Mare Synchronos server is currently offline.",
ServerState.VersionMisMatch =>
"Your plugin or the server you are connecting to is out of date. Please update your plugin now. If you already did so, contact the server provider to update their server to the latest version.",
ServerState.RateLimited => "You are rate limited for (re)connecting too often. Disconnect, wait 10 minutes and try again.",
ServerState.Connected => string.Empty,
ServerState.NoSecretKey => "You have no secret key set for this current character. Use the button below or open the settings and set a secret key for the current character. You can reuse the same secret key for multiple characters.",
_ => string.Empty
};
}
private Vector4 GetUidColor()
{
return _apiController.ServerState switch
{
ServerState.Connecting => ImGuiColors.DalamudYellow,
ServerState.Reconnecting => ImGuiColors.DalamudRed,
ServerState.Connected => ImGuiColors.ParsedGreen,
ServerState.Disconnected => ImGuiColors.DalamudYellow,
ServerState.Disconnecting => ImGuiColors.DalamudYellow,
ServerState.Unauthorized => ImGuiColors.DalamudRed,
ServerState.VersionMisMatch => ImGuiColors.DalamudRed,
ServerState.Offline => ImGuiColors.DalamudRed,
ServerState.RateLimited => ImGuiColors.DalamudYellow,
ServerState.NoSecretKey => ImGuiColors.DalamudYellow,
_ => ImGuiColors.DalamudRed
};
}
private string GetUidText()
{
return _apiController.ServerState switch
{
ServerState.Reconnecting => "Reconnecting",
ServerState.Connecting => "Connecting",
ServerState.Disconnected => "Disconnected",
ServerState.Disconnecting => "Disconnecting",
ServerState.Unauthorized => "Unauthorized",
ServerState.VersionMisMatch => "Version mismatch",
ServerState.Offline => "Unavailable",
ServerState.RateLimited => "Rate Limited",
ServerState.NoSecretKey => "No Secret Key",
ServerState.Connected => _apiController.DisplayName,
_ => string.Empty
};
}
private void UiSharedService_GposeEnd()
{
IsOpen = _wasOpen;
}
private void UiSharedService_GposeStart()
{
_wasOpen = IsOpen;
IsOpen = false;
}
}