Core - Nullable refactoring

Core - Nullable refactoring


Core - Nullable refactoring (finish)
This commit is contained in:
SpoinkyNL committed 2020-11-17 22:50:38 +01:00
1 parent b185b28645
commit fb3466e102
61 files changed
+320 -272

No files matched your search

+13 -15
View File
@@ -23,7 +23,7 @@ namespace Artemis.Core.Services
/// </summary>
internal class CoreService : ICoreService
{
internal static IKernel Kernel;
internal static IKernel Kernel = null!;
private readonly Stopwatch _frameStopWatch;
private readonly ILogger _logger;
@@ -32,10 +32,10 @@ namespace Artemis.Core.Services
private readonly IProfileService _profileService;
private readonly IRgbService _rgbService;
private readonly ISurfaceService _surfaceService;
private List<BaseDataModelExpansion> _dataModelExpansions;
private List<Module> _modules;
private List<BaseDataModelExpansion> _dataModelExpansions = new List<BaseDataModelExpansion>();
private List<Module> _modules = new List<Module>();
// ReSharper disable once UnusedParameter.Local - Storage migration service is injected early to ensure it runs before anything else
// ReSharper disable UnusedParameter.Local - Storage migration and module service are injected early to ensure it runs before anything else
public CoreService(IKernel kernel, ILogger logger, StorageMigrationService _, ISettingsService settingsService, IPluginManagementService pluginManagementService,
IRgbService rgbService, ISurfaceService surfaceService, IProfileService profileService, IModuleService moduleService)
{
@@ -60,10 +60,11 @@ namespace Artemis.Core.Services
_pluginManagementService.PluginEnabled += (sender, args) => UpdatePluginCache();
_pluginManagementService.PluginDisabled += (sender, args) => UpdatePluginCache();
}
// ReSharper restore UnusedParameter.Local
public TimeSpan FrameTime { get; private set; }
public bool ModuleRenderingDisabled { get; set; }
public List<string> StartupArguments { get; set; }
public List<string>? StartupArguments { get; set; }
public void Dispose()
{
@@ -86,13 +87,10 @@ namespace Artemis.Core.Services
// Initialize the services
_pluginManagementService.CopyBuiltInPlugins();
_pluginManagementService.LoadPlugins(StartupArguments.Contains("--ignore-plugin-lock"));
_pluginManagementService.LoadPlugins(StartupArguments != null && StartupArguments.Contains("--ignore-plugin-lock"));
ArtemisSurface surfaceConfig = _surfaceService.ActiveSurface;
if (surfaceConfig != null)
_logger.Information("Initialized with active surface entity {surfaceConfig}-{guid}", surfaceConfig.Name, surfaceConfig.EntityId);
else
_logger.Information("Initialized without an active surface entity");
_logger.Information("Initialized with active surface entity {surfaceConfig}-{guid}", surfaceConfig.Name, surfaceConfig.EntityId);
PlayIntroAnimation();
OnInitialized();
@@ -121,7 +119,7 @@ namespace Artemis.Core.Services
FrameRendering += DrawOverlay;
// Stop rendering after the profile finishes (take 1 second extra in case of slow updates)
TimeSpan introLength = intro.AnimationProfile.GetAllLayers().Max(l => l.Timeline.Length);
TimeSpan introLength = intro.AnimationProfile.GetAllLayers().Max(l => l.Timeline.Length)!;
Task.Run(async () =>
{
await Task.Delay(introLength.Add(TimeSpan.FromSeconds(1)));
@@ -217,14 +215,14 @@ namespace Artemis.Core.Services
if (_rgbService.IsRenderPaused)
return;
OnFrameRendered(new FrameRenderedEventArgs(_rgbService.BitmapBrush, _rgbService.Surface));
OnFrameRendered(new FrameRenderedEventArgs(_rgbService.BitmapBrush!, _rgbService.Surface));
}
#region Events
public event EventHandler Initialized;
public event EventHandler<FrameRenderingEventArgs> FrameRendering;
public event EventHandler<FrameRenderedEventArgs> FrameRendered;
public event EventHandler? Initialized;
public event EventHandler<FrameRenderingEventArgs>? FrameRendering;
public event EventHandler<FrameRenderedEventArgs>? FrameRendered;
private void OnInitialized()
{
@@ -26,7 +26,7 @@ namespace Artemis.Core.Services
/// <summary>
/// Gets or sets a list of startup arguments
/// </summary>
List<string> StartupArguments { get; set; }
List<string>? StartupArguments { get; set; }
/// <summary>
/// Initializes the core, only call once
@@ -12,13 +12,13 @@ namespace Artemis.Core.Services
/// Gets the current active module override. If set, all other modules are deactivated and only the
/// <see cref="ActiveModuleOverride" /> is active.
/// </summary>
Module ActiveModuleOverride { get; }
Module? ActiveModuleOverride { get; }
/// <summary>
/// Changes the current <see cref="ActiveModuleOverride" /> and deactivates all other modules
/// </summary>
/// <param name="overrideModule"></param>
Task SetActiveModuleOverride(Module overrideModule);
Task SetActiveModuleOverride(Module? overrideModule);
/// <summary>
/// Evaluates every enabled module's activation requirements and activates/deactivates modules accordingly
@@ -17,7 +17,7 @@ namespace Artemis.Core.Services
/// <summary>
/// Gets the bitmap brush used to convert the rendered frame to LED-colors
/// </summary>
BitmapBrush BitmapBrush { get; }
BitmapBrush? BitmapBrush { get; }
/// <summary>
/// Gets the scale the frames are rendered on, a scale of 1.0 means 1 pixel = 1mm
+2 -2
View File
@@ -149,9 +149,9 @@ namespace Artemis.Core.Services
UpdateModulePriority(module, category, priority);
}
public Module ActiveModuleOverride { get; private set; }
public Module? ActiveModuleOverride { get; private set; }
public async Task SetActiveModuleOverride(Module overrideModule)
public async Task SetActiveModuleOverride(Module? overrideModule)
{
try
{
@@ -242,12 +242,10 @@ namespace Artemis.Core.Services
throw new ArtemisCoreException("Cannot load a plugin that is already loaded");
}
Plugin plugin = new Plugin(pluginInfo, directory);
OnPluginLoading(new PluginEventArgs(plugin));
// Load the entity and fall back on creating a new one
plugin.Entity = _pluginRepository.GetPluginByGuid(pluginInfo.Guid) ?? new PluginEntity {Id = plugin.Guid, IsEnabled = true};
Plugin plugin = new Plugin(pluginInfo, directory, _pluginRepository.GetPluginByGuid(pluginInfo.Guid));
OnPluginLoading(new PluginEventArgs(plugin));
// Locate the main assembly entry
string? mainFile = plugin.ResolveRelativePath(plugin.Info.Main);
if (!File.Exists(mainFile))
@@ -34,7 +34,7 @@ namespace Artemis.Core.Services
return ConditionOperatorStore.GetForType(type, side).Select(r => r.ConditionOperator).ToList();
}
public BaseConditionOperator GetConditionOperator(Guid operatorPluginGuid, string operatorType)
public BaseConditionOperator? GetConditionOperator(Guid operatorPluginGuid, string operatorType)
{
return ConditionOperatorStore.Get(operatorPluginGuid, operatorType)?.ConditionOperator;
}
@@ -34,7 +34,7 @@ namespace Artemis.Core.Services
return DataBindingModifierTypeStore.GetForType(type, part).Select(r => r.DataBindingModifierType).ToList();
}
public BaseDataBindingModifierType GetModifierType(Guid modifierTypePluginGuid, string modifierType)
public BaseDataBindingModifierType? GetModifierType(Guid modifierTypePluginGuid, string modifierType)
{
return DataBindingModifierTypeStore.Get(modifierTypePluginGuid, modifierType)?.DataBindingModifierType;
}
@@ -11,7 +11,7 @@ namespace Artemis.Core.Services
public DataModelService(IPluginManagementService pluginManagementService)
{
// Add data models of already loaded plugins
foreach (Module module in pluginManagementService.GetFeaturesOfType<Module>().Where(p => p.IsEnabled))
foreach (Module module in pluginManagementService.GetFeaturesOfType<Module>().Where(p => p.IsEnabled && p.InternalDataModel != null))
AddModuleDataModel(module);
foreach (BaseDataModelExpansion dataModelExpansion in pluginManagementService.GetFeaturesOfType<BaseDataModelExpansion>().Where(p => p.IsEnabled))
AddDataModelExpansionDataModel(dataModelExpansion);
@@ -40,9 +40,9 @@ namespace Artemis.Core.Services
return DataModelStore.GetAll().Select(d => d.DataModel).ToList();
}
public T GetDataModel<T>() where T : DataModel
public T? GetDataModel<T>() where T : DataModel
{
return (T) DataModelStore.GetAll().FirstOrDefault(d => d.DataModel is T)?.DataModel;
return (T?) DataModelStore.GetAll().FirstOrDefault(d => d.DataModel is T)?.DataModel;
}
public DataModel? GetPluginDataModel(PluginFeature pluginFeature)
@@ -61,8 +61,7 @@ namespace Artemis.Core.Services
private void AddModuleDataModel(Module module)
{
if (module.InternalDataModel == null)
return;
throw new ArtemisCoreException("Cannot add module data model that is not enabled");
if (module.InternalDataModel.DataModelDescription == null)
throw new ArtemisPluginFeatureException(module, "Module overrides GetDataModelDescription but returned null");
@@ -72,6 +71,8 @@ namespace Artemis.Core.Services
private void AddDataModelExpansionDataModel(BaseDataModelExpansion dataModelExpansion)
{
if (dataModelExpansion.InternalDataModel == null)
throw new ArtemisCoreException("Cannot add data model expansion that is not enabled");
if (dataModelExpansion.InternalDataModel.DataModelDescription == null)
throw new ArtemisPluginFeatureException(dataModelExpansion, "Data model expansion overrides GetDataModelDescription but returned null");
@@ -32,6 +32,6 @@ namespace Artemis.Core.Services
/// </summary>
/// <param name="operatorPluginGuid">The operator's plugin GUID</param>
/// <param name="operatorType">The type name of the operator</param>
BaseConditionOperator GetConditionOperator(Guid operatorPluginGuid, string operatorType);
BaseConditionOperator? GetConditionOperator(Guid operatorPluginGuid, string operatorType);
}
}
@@ -33,6 +33,6 @@ namespace Artemis.Core.Services
/// <param name="modifierTypePluginGuid">The modifier type's plugin GUID</param>
/// <param name="modifierType">The type name of the modifier type</param>
/// <returns></returns>
BaseDataBindingModifierType GetModifierType(Guid modifierTypePluginGuid, string modifierType);
BaseDataBindingModifierType? GetModifierType(Guid modifierTypePluginGuid, string modifierType);
}
}
@@ -29,7 +29,7 @@ namespace Artemis.Core.Services
/// If found, returns the registered data model of type <typeparamref name="T" />
/// </summary>
/// <typeparam name="T">The type of the data model to find</typeparam>
T GetDataModel<T>() where T : DataModel;
T? GetDataModel<T>() where T : DataModel;
/// <summary>
/// If found, returns the data model of the provided plugin
@@ -34,7 +34,7 @@ namespace Artemis.Core.Services
return LayerBrushStore.GetAll().Select(r => r.LayerBrushDescriptor).ToList();
}
public LayerBrushDescriptor GetDefaultLayerBrush()
public LayerBrushDescriptor? GetDefaultLayerBrush()
{
PluginSetting<LayerBrushReference> defaultReference = _settingsService.GetSetting("ProfileEditor.DefaultLayerBrushDescriptor", new LayerBrushReference
{
@@ -42,6 +42,8 @@ namespace Artemis.Core.Services
BrushType = "ColorBrush"
});
defaultReference.Value.LayerBrushProviderId ??= "Artemis.Plugins.LayerBrushes.Color.ColorBrushProvider-92a9d6ba";
defaultReference.Value.BrushType ??= "ColorBrush";
return LayerBrushStore.Get(defaultReference.Value.LayerBrushProviderId, defaultReference.Value.BrushType)?.LayerBrushDescriptor;
}
}
+3 -7
View File
@@ -17,7 +17,7 @@ namespace Artemis.Core.Services
private readonly PluginSetting<double> _renderScaleSetting;
private readonly PluginSetting<int> _sampleSizeSetting;
private readonly PluginSetting<int> _targetFrameRateSetting;
private ListLedGroup _surfaceLedGroup;
private ListLedGroup? _surfaceLedGroup;
public RgbService(ILogger logger, ISettingsService settingsService)
{
@@ -41,7 +41,7 @@ namespace Artemis.Core.Services
public RGBSurface Surface { get; set; }
public TimerUpdateTrigger UpdateTrigger { get; }
public BitmapBrush BitmapBrush { get; private set; }
public BitmapBrush? BitmapBrush { get; private set; }
public IReadOnlyCollection<IRGBDevice> LoadedDevices => _loadedDevices.AsReadOnly();
public double RenderScale => _renderScaleSetting.Value;
public bool IsRenderPaused { get; set; }
@@ -109,7 +109,7 @@ namespace Artemis.Core.Services
public void UpdateSurfaceLedGroup()
{
if (_surfaceLedGroup == null)
if (_surfaceLedGroup == null || BitmapBrush == null)
{
// Apply the application wide brush and decorator
BitmapBrush = new BitmapBrush(new Scale(_renderScaleSetting.Value), _sampleSizeSetting);
@@ -126,10 +126,6 @@ namespace Artemis.Core.Services
BitmapBrush.Scale = new Scale(_renderScaleSetting.Value);
_surfaceLedGroup = new ListLedGroup(Surface.Leds) {Brush = BitmapBrush};
}
lock (BitmapBrush)
{
}
}
private void OnDeviceLoaded(DeviceEventArgs e)
+1 -1
View File
@@ -14,7 +14,7 @@ namespace Artemis.Core.Services
public PluginSetting<T> GetSetting<T>(string name, T defaultValue = default)
{
return _pluginSettings.GetSetting(name, defaultValue);
return _pluginSettings.GetSetting(name, defaultValue!);
}
}
@@ -36,6 +36,40 @@ namespace Artemis.Core.Services
public JsonSerializerSettings MementoSettings { get; set; } = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.All};
public JsonSerializerSettings ExportSettings { get; set; } = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.All, Formatting = Formatting.Indented};
public ProfileDescriptor? GetLastActiveProfile(ProfileModule module)
{
List<ProfileEntity> moduleProfiles = _profileRepository.GetByModuleId(module.Id);
if (!moduleProfiles.Any())
return CreateProfileDescriptor(module, "Default");
ProfileEntity? profileEntity = moduleProfiles.FirstOrDefault(p => p.IsActive) ?? moduleProfiles.FirstOrDefault();
return profileEntity == null ? null : new ProfileDescriptor(module, profileEntity);
}
private void SaveActiveProfile(ProfileModule module)
{
if (module.ActiveProfile == null)
return;
List<ProfileEntity> profileEntities = _profileRepository.GetByModuleId(module.Id);
foreach (ProfileEntity profileEntity in profileEntities)
{
profileEntity.IsActive = module.ActiveProfile.EntityId == profileEntity.Id;
_profileRepository.Save(profileEntity);
}
}
/// <summary>
/// Populates all missing LEDs on all currently active profiles
/// </summary>
/// <param name="surface"></param>
private void ActiveProfilesPopulateLeds(ArtemisSurface surface)
{
List<ProfileModule> profileModules = _pluginManagementService.GetFeaturesOfType<ProfileModule>();
foreach (ProfileModule profileModule in profileModules.Where(p => p.ActiveProfile != null).ToList())
profileModule.ActiveProfile?.PopulateLeds(surface); // Avoid race condition
}
public List<ProfileDescriptor> GetProfileDescriptors(ProfileModule module)
{
List<ProfileEntity> profileEntities = _profileRepository.GetByModuleId(module.Id);
@@ -52,14 +86,14 @@ namespace Artemis.Core.Services
public void ActivateLastProfile(ProfileModule profileModule)
{
ProfileDescriptor activeProfile = GetLastActiveProfile(profileModule);
ProfileDescriptor? activeProfile = GetLastActiveProfile(profileModule);
if (activeProfile != null)
ActivateProfile(activeProfile);
}
public async Task ActivateLastProfileAnimated(ProfileModule profileModule)
{
ProfileDescriptor activeProfile = GetLastActiveProfile(profileModule);
ProfileDescriptor? activeProfile = GetLastActiveProfile(profileModule);
if (activeProfile != null)
await ActivateProfileAnimated(activeProfile);
}
@@ -196,7 +230,8 @@ namespace Artemis.Core.Services
string top = profile.UndoStack.Pop();
string memento = JsonConvert.SerializeObject(profile.ProfileEntity, MementoSettings);
profile.RedoStack.Push(memento);
profile.ProfileEntity = JsonConvert.DeserializeObject<ProfileEntity>(top, MementoSettings);
profile.ProfileEntity = JsonConvert.DeserializeObject<ProfileEntity>(top, MementoSettings)
?? throw new InvalidOperationException("Failed to deserialize memento");
profile.Load();
InstantiateProfile(profile);
@@ -220,7 +255,8 @@ namespace Artemis.Core.Services
string top = profile.RedoStack.Pop();
string memento = JsonConvert.SerializeObject(profile.ProfileEntity, MementoSettings);
profile.UndoStack.Push(memento);
profile.ProfileEntity = JsonConvert.DeserializeObject<ProfileEntity>(top, MementoSettings);
profile.ProfileEntity = JsonConvert.DeserializeObject<ProfileEntity>(top, MementoSettings)
?? throw new InvalidOperationException("Failed to deserialize memento");
profile.Load();
InstantiateProfile(profile);
@@ -246,7 +282,9 @@ namespace Artemis.Core.Services
public ProfileDescriptor ImportProfile(string json, ProfileModule profileModule)
{
ProfileEntity profileEntity = JsonConvert.DeserializeObject<ProfileEntity>(json, ExportSettings);
ProfileEntity? profileEntity = JsonConvert.DeserializeObject<ProfileEntity>(json, ExportSettings);
if (profileEntity == null)
throw new ArtemisCoreException("Failed to import profile but JSON.NET threw no error :(");
// Assign a new GUID to make sure it is unique in case of a previous import of the same content
profileEntity.UpdateGuid(Guid.NewGuid());
@@ -256,40 +294,6 @@ namespace Artemis.Core.Services
return new ProfileDescriptor(profileModule, profileEntity);
}
public ProfileDescriptor GetLastActiveProfile(ProfileModule module)
{
List<ProfileEntity> moduleProfiles = _profileRepository.GetByModuleId(module.Id);
if (!moduleProfiles.Any())
return CreateProfileDescriptor(module, "Default");
ProfileEntity profileEntity = moduleProfiles.FirstOrDefault(p => p.IsActive) ?? moduleProfiles.FirstOrDefault();
return profileEntity == null ? null : new ProfileDescriptor(module, profileEntity);
}
private void SaveActiveProfile(ProfileModule module)
{
if (module.ActiveProfile == null)
return;
List<ProfileEntity> profileEntities = _profileRepository.GetByModuleId(module.Id);
foreach (ProfileEntity profileEntity in profileEntities)
{
profileEntity.IsActive = module.ActiveProfile.EntityId == profileEntity.Id;
_profileRepository.Save(profileEntity);
}
}
/// <summary>
/// Populates all missing LEDs on all currently active profiles
/// </summary>
/// <param name="surface"></param>
private void ActiveProfilesPopulateLeds(ArtemisSurface surface)
{
List<ProfileModule> profileModules = _pluginManagementService.GetFeaturesOfType<ProfileModule>();
foreach (ProfileModule profileModule in profileModules.Where(p => p.ActiveProfile != null).ToList())
profileModule.ActiveProfile.PopulateLeds(surface);
}
#region Event handlers
private void OnActiveSurfaceConfigurationSelected(object? sender, SurfaceConfigurationEventArgs e)
@@ -28,6 +28,8 @@ namespace Artemis.Core.Services
_surfaceConfigurations = new List<ArtemisSurface>();
_renderScaleSetting = settingsService.GetSetting("Core.RenderScale", 0.5);
// LoadFromRepository is guaranteed to set the ActiveSurface
ActiveSurface = null!;
LoadFromRepository();
_rgbService.DeviceLoaded += RgbServiceOnDeviceLoaded;
@@ -61,6 +63,7 @@ namespace Artemis.Core.Services
public void SetActiveSurfaceConfiguration(ArtemisSurface surface)
{
if (surface == null) throw new ArgumentNullException(nameof(surface));
if (ActiveSurface == surface)
return;
@@ -81,11 +84,8 @@ namespace Artemis.Core.Services
}
// Apply the active surface entity to the devices
if (ActiveSurface != null)
{
foreach (ArtemisDevice device in ActiveSurface.Devices)
device.ApplyToRgbDevice();
}
foreach (ArtemisDevice device in ActiveSurface.Devices)
device.ApplyToRgbDevice();
// Update the RGB service's graphics decorator to work with the new surface entity
_rgbService.UpdateSurfaceLedGroup();
@@ -134,7 +134,7 @@ namespace Artemis.Core.Services
ArtemisSurface surfaceConfiguration = new ArtemisSurface(_rgbService.Surface, surfaceEntity, _renderScaleSetting.Value);
foreach (DeviceEntity position in surfaceEntity.DeviceEntities)
{
IRGBDevice device = _rgbService.Surface.Devices.FirstOrDefault(d => d.GetDeviceIdentifier() == position.DeviceIdentifier);
IRGBDevice? device = _rgbService.Surface.Devices.FirstOrDefault(d => d.GetDeviceIdentifier() == position.DeviceIdentifier);
if (device != null)
{
DeviceProvider deviceProvider = _pluginManagementService.GetDeviceProviderByDevice(device);
@@ -150,7 +150,7 @@ namespace Artemis.Core.Services
}
// When all surface configs are loaded, apply the active surface config
ArtemisSurface active = SurfaceConfigurations.FirstOrDefault(c => c.IsActive);
ArtemisSurface? active = SurfaceConfigurations.FirstOrDefault(c => c.IsActive);
if (active != null)
SetActiveSurfaceConfiguration(active);
else
@@ -170,13 +170,13 @@ namespace Artemis.Core.Services
private void AddDeviceIfMissing(IRGBDevice rgbDevice, ArtemisSurface surface)
{
string deviceIdentifier = rgbDevice.GetDeviceIdentifier();
ArtemisDevice device = surface.Devices.FirstOrDefault(d => d.DeviceEntity.DeviceIdentifier == deviceIdentifier);
ArtemisDevice? device = surface.Devices.FirstOrDefault(d => d.DeviceEntity.DeviceIdentifier == deviceIdentifier);
if (device != null)
return;
// Find an existing device config and use that
DeviceEntity existingDeviceConfig = surface.SurfaceEntity.DeviceEntities.FirstOrDefault(d => d.DeviceIdentifier == deviceIdentifier);
DeviceEntity? existingDeviceConfig = surface.SurfaceEntity.DeviceEntities.FirstOrDefault(d => d.DeviceIdentifier == deviceIdentifier);
if (existingDeviceConfig != null)
{
DeviceProvider deviceProvider = _pluginManagementService.GetDeviceProviderByDevice(rgbDevice);
@@ -225,8 +225,8 @@ namespace Artemis.Core.Services
#region Events
public event EventHandler<SurfaceConfigurationEventArgs> ActiveSurfaceConfigurationSelected;
public event EventHandler<SurfaceConfigurationEventArgs> SurfaceConfigurationUpdated;
public event EventHandler<SurfaceConfigurationEventArgs>? ActiveSurfaceConfigurationSelected;
public event EventHandler<SurfaceConfigurationEventArgs>? SurfaceConfigurationUpdated;
protected virtual void OnActiveSurfaceConfigurationChanged(SurfaceConfigurationEventArgs e)
{