Files
tbd-station-14/Content.Server/GameObjects/Components/PDA/PDAComponent.cs
Paul Ritter 5c50b1f6ed Serialization v3 content PR (#3491)
* serv3 in shared pt 1

* beginning of deepclone api

* progress in implementing ideepclone & serv3 in content

* adds target

* its cant hurt you it cant hurt you

* more changes to content.server

* adds dataclasses

* almost there

* renamed & edited entry

* finishes refactoring content to use serv3

* gasmixture runtimes, next: reagentunit

* fucin hell that was an annoying one

* adds flags

* fixes some yaml errors

* removes comment

* fixes generic components for now

* removes todo
actually clones values my god paul
fixes bug involving resolving custom data classes from other proj
renames dataclass
fixes spritecomp
adds WithFormat.Constants support

* adds deepclone to ResistanceSet

* adds a bunch of deepclone implementations
adds a deepclone analyzer (TODO)
adds a deep clone fallback for classes & structs

* fixes a bunch of runtimes

* adds deepclone to entityuid

* adds generator to sln

* gets rid of warnings

* fixes

* argh

* componentdata refactors

* more deepclone impl

* heck me i reworked all of content deepclone

* renames custom dataclasstarget

* misc

* reworks prototypes

* deepclone nuke

* renamed customdataclass attribute

* fixes everything

* misc fixed

* the killcommit

* getting there

* changed yamlfieldattribute namespace

* adds back iselfserialize

* renames everything to data(field/definition)

* ouch

* Fix most errors on content

* Fix more errors in content

* Fix some components

* work on tests

* fixes some customdataclasses

* fuggin shit

* yes

* yeas

* Remove data classes

* Data field naming fixes

* arg

* Git resetti RobustToolbox

* Merge fixes

* General fixes

* Fix startup serialization errors

* Fix DamageContainerPrototype when supported classes or types are null

* Implement construction graph step type serializer

* Fix up construction serialization

* Fix up construction serialization part 2

* Fix null list in technology database component

* Fix body serialization

* Fix entity storage serialization

* Fix actions serialization

* Fix AI serialization

* Fix reaction serialization

* Fix body serialization

* Fix grid atmosphere serialization

* Rename IServ3Manager to ISerializationManager

* Convert every non generic serializer to the new format, general fixes

* Serialization and body system fix

* pushinheritance fix

* Update all prototypes to have a parent and have consistent id/parent properties

* Merge fixes

* smh my head

* cuddling slaps

* Content commit for engine PR

* stuff

* more fixes

* argh

* yes even you are fixed

* changelog fixes

* fixes seeds

* argh

* Test fixes

* Add writing for alert order prototype

* Fix alert order writing

* FIX

* its been alot ok

* Fix the rest of the visualizers

* Fix server alerts component tests

* Fix alert prototype tests not using the read value

* Fix alert prototype tests initializing serialization multiple times

* THIS IS AN AMERICAN CODEBASE GOD BLESS THE USA

* Add ImplicitDataDefinitionForInheritors to IMechanismBehavior
Fixes the behaviors not being found

* Fix NRE in strap component
Good night to the 1 buckle optimization

* Fix clothing component slot flags serialization tag

* Fix body component in all components test

* Merge fixes

* ffs

* Make construction graph prototype use serialization hooks

* human yaml linted

* a

* Do the thing for construction

* stuff

* a

* monke see yaml linter

* LINT HARDER

* Remove redundant todo

* yes

* Add skip hook argument to readers and copiers

* we gamin

* test/datafield fixes

* adds more verbose validation

* moves linter to action

* Improve construction graph step type serializer error message

* Fix ammo box component NRE

* gamin

* some updates to the linter

* yes

* removes that test

* misc fixes

* array fix
priority fix
misc fixes

* adds proper info the validation

* adds alwaysrelevant usa

* Make yaml linter take half as long to run (~50% less)

* Make yaml linter 5 times faster (~80% less execution time)

* based vera being based

* fixes mapsaving

* warning cleanup & moves surpressor

* removes old msbuild targets

* Revert "Make yaml linter 5 times faster (~80% less execution time)"

This reverts commit 3e6091359a26252c3e98828199553de668031c63.

* Add -nowarn to yaml linter run configuration

* Improve yaml linter message feedback

* Make dependencies an argument instead of a property on the serialization manager

* yamllinting slaps

* Clean up type serializers

* Move yaml linter code to its own method

* Fix yaml errors

* Change yaml linter action name and remove -nowarn

* yaml linter please shut

* Git resetti robust toolbox

Co-authored-by: Paul <ritter.paul1+git@googlemail.com>
Co-authored-by: DrSmugleaf <DrSmugleaf@users.noreply.github.com>
2021-03-05 01:08:38 +01:00

559 lines
18 KiB
C#

#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Content.Server.GameObjects.Components.Access;
using Content.Server.GameObjects.Components.GUI;
using Content.Server.GameObjects.Components.Items.Storage;
using Content.Server.GameObjects.Components.Paper;
using Content.Server.Interfaces;
using Content.Server.Interfaces.GameObjects.Components.Items;
using Content.Server.Interfaces.PDA;
using Content.Server.Utility;
using Content.Shared.GameObjects.Components.PDA;
using Content.Shared.GameObjects.Components.Tag;
using Content.Shared.GameObjects.EntitySystems.ActionBlocker;
using Content.Shared.GameObjects.Verbs;
using Content.Shared.Interfaces;
using Content.Shared.Interfaces.GameObjects.Components;
using Robust.Server.GameObjects;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.PDA
{
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
[ComponentReference(typeof(IAccess))]
public class PDAComponent : SharedPDAComponent, IInteractUsing, IActivate, IUse, IAccess, IMapInit
{
[Dependency] private readonly IPDAUplinkManager _uplinkManager = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
[ViewVariables] private ContainerSlot _idSlot = default!;
[ViewVariables] private ContainerSlot _penSlot = default!;
[ViewVariables] private bool _lightOn;
[ViewVariables] [DataField("idCard")] private string? _startingIdCard = "AssistantIDCard";
[ViewVariables] [DataField("pen")] private string? _startingPen = "Pen";
[ViewVariables] public string? OwnerName { get; private set; }
[ViewVariables] public IdCardComponent? ContainedID { get; private set; }
[ViewVariables] public bool IdSlotEmpty => _idSlot.ContainedEntity == null;
[ViewVariables] public bool PenSlotEmpty => _penSlot.ContainedEntity == null;
private UplinkAccount? _syndicateUplinkAccount;
[ViewVariables] public UplinkAccount? SyndicateUplinkAccount => _syndicateUplinkAccount;
[ViewVariables] private readonly PdaAccessSet _accessSet;
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(PDAUiKey.Key);
public PDAComponent()
{
_accessSet = new PdaAccessSet(this);
}
public override void Initialize()
{
base.Initialize();
_idSlot = ContainerHelpers.EnsureContainer<ContainerSlot>(Owner, "pda_entity_container");
_penSlot = ContainerHelpers.EnsureContainer<ContainerSlot>(Owner, "pda_pen_slot");
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += UserInterfaceOnReceiveMessage;
}
UpdatePDAAppearance();
}
public void MapInit()
{
if (!string.IsNullOrEmpty(_startingIdCard))
{
var idCard = _entityManager.SpawnEntity(_startingIdCard, Owner.Transform.Coordinates);
var idCardComponent = idCard.GetComponent<IdCardComponent>();
_idSlot.Insert(idCardComponent.Owner);
ContainedID = idCardComponent;
}
if (!string.IsNullOrEmpty(_startingPen))
{
var pen = _entityManager.SpawnEntity(_startingPen, Owner.Transform.Coordinates);
_penSlot.Insert(pen);
}
}
private void UserInterfaceOnReceiveMessage(ServerBoundUserInterfaceMessage message)
{
switch (message.Message)
{
case PDARequestUpdateInterfaceMessage _:
{
UpdatePDAUserInterface();
break;
}
case PDAToggleFlashlightMessage _:
{
ToggleLight();
break;
}
case PDAEjectIDMessage _:
{
HandleIDEjection(message.Session.AttachedEntity!);
break;
}
case PDAEjectPenMessage _:
{
HandlePenEjection(message.Session.AttachedEntity!);
break;
}
case PDAUplinkBuyListingMessage buyMsg:
{
if (message.Session.AttachedEntity == null)
break;
if (!_uplinkManager.TryPurchaseItem(_syndicateUplinkAccount, buyMsg.ItemId,
message.Session.AttachedEntity.Transform.Coordinates, out var entity))
{
SendNetworkMessage(new PDAUplinkInsufficientFundsMessage(), message.Session.ConnectedClient);
break;
}
HandsComponent.PutInHandOrDropStatic(
message.Session.AttachedEntity,
entity.GetComponent<ItemComponent>());
SendNetworkMessage(new PDAUplinkBuySuccessMessage(), message.Session.ConnectedClient);
break;
}
}
}
private void UpdatePDAUserInterface()
{
var ownerInfo = new PDAIdInfoText
{
ActualOwnerName = OwnerName,
IdOwner = ContainedID?.FullName,
JobTitle = ContainedID?.JobTitle
};
//Do we have an account? If so provide the info.
if (_syndicateUplinkAccount != null)
{
var accData = new UplinkAccountData(_syndicateUplinkAccount.AccountHolder,
_syndicateUplinkAccount.Balance);
var listings = _uplinkManager.FetchListings.Values.ToArray();
UserInterface?.SetState(new PDAUpdateState(_lightOn, !PenSlotEmpty, ownerInfo, accData, listings));
}
else
{
UserInterface?.SetState(new PDAUpdateState(_lightOn, !PenSlotEmpty, ownerInfo));
}
UpdatePDAAppearance();
}
private void UpdatePDAAppearance()
{
if (Owner.TryGetComponent(out AppearanceComponent? appearance))
{
appearance.SetData(PDAVisuals.FlashlightLit, _lightOn);
appearance.SetData(PDAVisuals.IDCardInserted, !IdSlotEmpty);
}
}
private bool TryInsertIdCard(InteractUsingEventArgs eventArgs, IdCardComponent idCardComponent)
{
var item = eventArgs.Using;
if (_idSlot.Contains(item))
return false;
if (!eventArgs.User.TryGetComponent(out IHandsComponent? hands))
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("You have no hands!"));
return true;
}
IEntity? swap = null;
if (!IdSlotEmpty)
{
// Swap
swap = _idSlot.ContainedEntities[0];
}
if (!hands.Drop(item))
{
return true;
}
if (swap != null)
{
hands.PutInHand(swap.GetComponent<ItemComponent>());
}
InsertIdCard(idCardComponent);
UpdatePDAUserInterface();
return true;
}
private bool TryInsertPen(InteractUsingEventArgs eventArgs)
{
var item = eventArgs.Using;
if (_penSlot.Contains(item))
return false;
if (!eventArgs.User.TryGetComponent(out IHandsComponent? hands))
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("You have no hands!"));
return true;
}
IEntity? swap = null;
if (!PenSlotEmpty)
{
// Swap
swap = _penSlot.ContainedEntities[0];
}
if (!hands.Drop(item))
{
return true;
}
if (swap != null)
{
hands.PutInHand(swap.GetComponent<ItemComponent>());
}
// Insert Pen
_penSlot.Insert(item);
UpdatePDAUserInterface();
return true;
}
async Task<bool> IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs)
{
var item = eventArgs.Using;
if (item.TryGetComponent<IdCardComponent>(out var idCardComponent))
{
return TryInsertIdCard(eventArgs, idCardComponent);
}
if (item.HasTag("Write"))
{
return TryInsertPen(eventArgs);
}
return false;
}
void IActivate.Activate(ActivateEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent(out IActorComponent? actor))
{
return;
}
UserInterface?.Toggle(actor.playerSession);
UpdatePDAAppearance();
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent(out IActorComponent? actor))
{
return false;
}
UserInterface?.Toggle(actor.playerSession);
UpdatePDAAppearance();
return true;
}
public void SetPDAOwner(string name)
{
OwnerName = name;
UpdatePDAUserInterface();
}
public void InsertIdCard(IdCardComponent card)
{
_idSlot.Insert(card.Owner);
ContainedID = card;
EntitySystem.Get<AudioSystem>().PlayFromEntity("/Audio/Weapons/Guns/MagIn/batrifle_magin.ogg", Owner);
}
/// <summary>
/// Initialize the PDA's syndicate uplink account.
/// </summary>
/// <param name="acc"></param>
public void InitUplinkAccount(UplinkAccount acc)
{
_syndicateUplinkAccount = acc;
_uplinkManager.AddNewAccount(_syndicateUplinkAccount);
_syndicateUplinkAccount.BalanceChanged += account =>
{
UpdatePDAUserInterface();
};
UpdatePDAUserInterface();
}
private void ToggleLight()
{
if (!Owner.TryGetComponent(out PointLightComponent? light))
{
return;
}
_lightOn = !_lightOn;
light.Enabled = _lightOn;
EntitySystem.Get<AudioSystem>().PlayFromEntity("/Audio/Items/flashlight_toggle.ogg", Owner);
UpdatePDAUserInterface();
}
private void HandleIDEjection(IEntity pdaUser)
{
if (ContainedID == null)
{
return;
}
var cardEntity = ContainedID.Owner;
_idSlot.Remove(cardEntity);
var hands = pdaUser.GetComponent<HandsComponent>();
var cardItemComponent = cardEntity.GetComponent<ItemComponent>();
hands.PutInHandOrDrop(cardItemComponent);
ContainedID = null;
EntitySystem.Get<AudioSystem>().PlayFromEntity("/Audio/Machines/id_swipe.ogg", Owner);
UpdatePDAUserInterface();
}
private void HandlePenEjection(IEntity pdaUser)
{
if (PenSlotEmpty)
return;
var pen = _penSlot.ContainedEntities[0];
_penSlot.Remove(pen);
var hands = pdaUser.GetComponent<HandsComponent>();
var itemComponent = pen.GetComponent<ItemComponent>();
hands.PutInHandOrDrop(itemComponent);
UpdatePDAUserInterface();
}
[Verb]
public sealed class EjectIDVerb : Verb<PDAComponent>
{
protected override void GetData(IEntity user, PDAComponent component, VerbData data)
{
if (!ActionBlockerSystem.CanInteract(user))
{
data.Visibility = VerbVisibility.Invisible;
return;
}
data.Text = Loc.GetString("Eject ID");
data.Visibility = component.IdSlotEmpty ? VerbVisibility.Invisible : VerbVisibility.Visible;
}
protected override void Activate(IEntity user, PDAComponent component)
{
component.HandleIDEjection(user);
}
}
[Verb]
public sealed class EjectPenVerb : Verb<PDAComponent>
{
protected override void GetData(IEntity user, PDAComponent component, VerbData data)
{
if (!ActionBlockerSystem.CanInteract(user))
{
data.Visibility = VerbVisibility.Invisible;
return;
}
data.Text = Loc.GetString("Eject Pen");
data.Visibility = component.PenSlotEmpty ? VerbVisibility.Invisible : VerbVisibility.Visible;
}
protected override void Activate(IEntity user, PDAComponent component)
{
component.HandlePenEjection(user);
}
}
[Verb]
public sealed class ToggleFlashlightVerb : Verb<PDAComponent>
{
protected override void GetData(IEntity user, PDAComponent component, VerbData data)
{
if (!ActionBlockerSystem.CanInteract(user))
{
data.Visibility = VerbVisibility.Invisible;
return;
}
data.Text = Loc.GetString("Toggle flashlight");
}
protected override void Activate(IEntity user, PDAComponent component)
{
component.ToggleLight();
}
}
private ISet<string>? GetContainedAccess()
{
return ContainedID?.Owner?.GetComponent<AccessComponent>()?.Tags;
}
ISet<string> IAccess.Tags => _accessSet;
bool IAccess.IsReadOnly => true;
void IAccess.SetTags(IEnumerable<string> newTags)
{
throw new NotSupportedException("PDA access list is read-only.");
}
private sealed class PdaAccessSet : ISet<string>
{
private readonly PDAComponent _pdaComponent;
private static readonly HashSet<string> EmptySet = new();
public PdaAccessSet(PDAComponent pdaComponent)
{
_pdaComponent = pdaComponent;
}
public IEnumerator<string> GetEnumerator()
{
var contained = _pdaComponent.GetContainedAccess() ?? EmptySet;
return contained.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void ICollection<string>.Add(string item)
{
throw new NotSupportedException("PDA access list is read-only.");
}
public void ExceptWith(IEnumerable<string> other)
{
throw new NotSupportedException("PDA access list is read-only.");
}
public void IntersectWith(IEnumerable<string> other)
{
throw new NotSupportedException("PDA access list is read-only.");
}
public bool IsProperSubsetOf(IEnumerable<string> other)
{
var set = _pdaComponent.GetContainedAccess() ?? EmptySet;
return set.IsProperSubsetOf(other);
}
public bool IsProperSupersetOf(IEnumerable<string> other)
{
var set = _pdaComponent.GetContainedAccess() ?? EmptySet;
return set.IsProperSupersetOf(other);
}
public bool IsSubsetOf(IEnumerable<string> other)
{
var set = _pdaComponent.GetContainedAccess() ?? EmptySet;
return set.IsSubsetOf(other);
}
public bool IsSupersetOf(IEnumerable<string> other)
{
var set = _pdaComponent.GetContainedAccess() ?? EmptySet;
return set.IsSupersetOf(other);
}
public bool Overlaps(IEnumerable<string> other)
{
var set = _pdaComponent.GetContainedAccess() ?? EmptySet;
return set.Overlaps(other);
}
public bool SetEquals(IEnumerable<string> other)
{
var set = _pdaComponent.GetContainedAccess() ?? EmptySet;
return set.SetEquals(other);
}
public void SymmetricExceptWith(IEnumerable<string> other)
{
throw new NotSupportedException("PDA access list is read-only.");
}
public void UnionWith(IEnumerable<string> other)
{
throw new NotSupportedException("PDA access list is read-only.");
}
bool ISet<string>.Add(string item)
{
throw new NotSupportedException("PDA access list is read-only.");
}
public void Clear()
{
throw new NotSupportedException("PDA access list is read-only.");
}
public bool Contains(string item)
{
return _pdaComponent.GetContainedAccess()?.Contains(item) ?? false;
}
public void CopyTo(string[] array, int arrayIndex)
{
var set = _pdaComponent.GetContainedAccess() ?? EmptySet;
set.CopyTo(array, arrayIndex);
}
public bool Remove(string item)
{
throw new NotSupportedException("PDA access list is read-only.");
}
public int Count => _pdaComponent.GetContainedAccess()?.Count ?? 0;
public bool IsReadOnly => true;
}
}
}