CssMedium
Represents a medium rule. More information available at:
http://www.w3.org/TR/css3-mediaqueries/
using AngleSharp.Css;
using AngleSharp.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
namespace AngleSharp.Dom.Css
{
internal sealed class CssMedium : IEnumerable<MediaFeature>, IEnumerable, IStyleFormattable
{
private static readonly string[] Types = new string[4] {
Keywords.Screen,
Keywords.Speech,
Keywords.Print,
Keywords.All
};
private readonly List<MediaFeature> _features;
public string Type { get; set; }
public bool IsExclusive { get; set; }
public bool IsInverse { get; set; }
public string Constraints {
get {
string[] array = new string[_features.Count];
for (int i = 0; i < _features.Count; i++) {
array[i] = _features[i].ToCss();
}
return string.Join(" and ", array);
}
}
internal CssMedium()
{
_features = new List<MediaFeature>();
}
public bool Validate(RenderDevice device)
{
if (!string.IsNullOrEmpty(Type) && Types.Contains(Type, StringComparison.Ordinal) == IsInverse)
return false;
if (IsInvalid(device, Keywords.Screen, RenderDevice.Kind.Screen) || IsInvalid(device, Keywords.Speech, RenderDevice.Kind.Speech) || IsInvalid(device, Keywords.Print, RenderDevice.Kind.Printer))
return false;
foreach (MediaFeature feature in _features) {
if (feature.Validate(device) == IsInverse)
return false;
}
return true;
}
public IEnumerator<MediaFeature> GetEnumerator()
{
return _features.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal void AddConstraint(MediaFeature feature)
{
_features.Add(feature);
}
public override bool Equals(object obj)
{
CssMedium cssMedium = obj as CssMedium;
if (cssMedium != null && cssMedium.IsExclusive == IsExclusive && cssMedium.IsInverse == IsInverse && cssMedium.Type == Type && cssMedium._features.Count == _features.Count) {
foreach (MediaFeature feature in cssMedium._features) {
List<MediaFeature> features = _features;
Predicate<MediaFeature> match = (MediaFeature m) => m.Name == feature.Name;
MediaFeature mediaFeature = features.Find(match);
if (mediaFeature == null || mediaFeature.Value != feature.Value)
return false;
}
return true;
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public string ToCss()
{
return ToCss(CssStyleFormatter.Instance);
}
public string ToCss(IStyleFormatter formatter)
{
string[] array = new string[_features.Count];
for (int i = 0; i < _features.Count; i++) {
array[i] = _features[i].ToCss(formatter);
}
return formatter.Medium(IsExclusive, IsInverse, Type, array);
}
private bool IsInvalid(RenderDevice device, string keyword, RenderDevice.Kind kind)
{
if (Type == keyword)
return device.DeviceType == kind == IsInverse;
return false;
}
}
}