using System;
using System.CodeDom;
using System.Data;
using System.IO;
using System.Linq;
using Terminal.Gui.Resources;
namespace Terminal.Gui {
///
/// Interface for restrictions on which file type(s) the
/// user is allowed to select/enter.
///
public interface IAllowedType
{
///
/// Returns true if the file at is compatible with this
/// allow option. Note that the file may not exist (e.g. in the case of saving).
///
///
///
bool IsAllowed (string path);
}
///
/// that allows selection of any types (*.*).
///
public class AllowedTypeAny : IAllowedType {
///
public bool IsAllowed (string path)
{
return true;
}
///
public override string ToString ()
{
return Strings.fdAnyFiles + "(*.*)";
}
}
///
/// Describes a requirement on what can be selected.
/// This can be combined with other in a
/// to for example show only .csv files but let user change to open any if they want.
///
public class AllowedType : IAllowedType {
///
/// Initializes a new instance of the class.
///
/// The human readable text to display.
/// Extension(s) to match e.g. .csv.
public AllowedType (string description, params string [] extensions)
{
if (extensions.Length == 0) {
throw new ArgumentException ("You must supply at least one extension");
}
this.Description = description;
this.Extensions = extensions;
}
///
/// Gets or Sets the human readable description for the file type
/// e.g. "Comma Separated Values".
///
public string Description { get; set; }
///
/// Gets or Sets the permitted file extension(s) (e.g. ".csv").
///
public string [] Extensions { get; set; }
///
/// Returns plus all separated by semicolons.
///
public override string ToString ()
{
const int maxLength = 30;
var desc = $"{this.Description} ({string.Join (";", this.Extensions.Select (e => '*' + e).ToArray ())})";
if(desc.Length > maxLength) {
return desc.Substring (0, maxLength-2) + "…";
}
return desc;
}
///
public bool IsAllowed(string path)
{
var extension = Path.GetExtension (path);
// There is a requirement to have a particular extension and we have none
if (string.IsNullOrEmpty (extension)) {
return false;
}
return this.Extensions.Any (e => e.Equals (extension));
}
}
}