2014-07-26 07:12:56 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.IO;
|
2014-08-12 13:33:13 +00:00
|
|
|
|
using RainmeterStudio.Core;
|
|
|
|
|
using RainmeterStudio.Core.Model;
|
|
|
|
|
using RainmeterStudio.Core.Storage;
|
2014-07-26 07:12:56 +00:00
|
|
|
|
|
2014-08-12 13:33:13 +00:00
|
|
|
|
namespace RainmeterStudio.TextEditorPlugin
|
2014-07-26 07:12:56 +00:00
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Storage for text files
|
2014-07-29 20:35:59 +00:00
|
|
|
|
/// </summary>
|
2014-08-12 13:33:13 +00:00
|
|
|
|
[PluginExport]
|
2014-07-26 07:12:56 +00:00
|
|
|
|
public class TextStorage : IDocumentStorage
|
|
|
|
|
{
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
IDocument IDocumentStorage.Read(string path)
|
|
|
|
|
{
|
|
|
|
|
TextDocument document = new TextDocument();
|
2014-07-29 16:42:52 +00:00
|
|
|
|
document.Reference.Path = path;
|
|
|
|
|
document.Reference.Name = Path.GetFileName(path);
|
2014-07-29 20:35:59 +00:00
|
|
|
|
document.Lines.AddRange(File.ReadAllLines(path));
|
2014-07-26 07:12:56 +00:00
|
|
|
|
|
|
|
|
|
return document;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
public void Write(string path, IDocument document)
|
|
|
|
|
{
|
|
|
|
|
TextDocument textDocument = document as TextDocument;
|
|
|
|
|
|
|
|
|
|
if (textDocument == null)
|
|
|
|
|
throw new ArgumentException("Provided document is not supported by this storage.");
|
|
|
|
|
|
2014-07-29 20:35:59 +00:00
|
|
|
|
File.WriteAllLines(path, textDocument.Lines);
|
2014-07-26 07:12:56 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
public bool CanRead(string path)
|
|
|
|
|
{
|
|
|
|
|
// Open the file
|
|
|
|
|
FileStream file = File.OpenRead(path);
|
|
|
|
|
|
|
|
|
|
// Read a small chunk (1kb should be enough)
|
|
|
|
|
byte[] buffer = new byte[1024];
|
|
|
|
|
int read = file.Read(buffer, 0, buffer.Length);
|
|
|
|
|
|
|
|
|
|
// Close file
|
|
|
|
|
file.Close();
|
|
|
|
|
|
|
|
|
|
// Find 4 consecutive zero bytes
|
|
|
|
|
int cnt = 0;
|
|
|
|
|
for (int i = 0; i < read; i++)
|
|
|
|
|
{
|
|
|
|
|
// Count zero bytes
|
|
|
|
|
if (buffer[i] == 0)
|
|
|
|
|
++cnt;
|
|
|
|
|
else cnt = 0;
|
|
|
|
|
|
|
|
|
|
// Found > 4? Most likely binary file
|
|
|
|
|
if (cnt >= 4)
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Not found, probably text file
|
|
|
|
|
return true;
|
|
|
|
|
}
|
2014-07-29 16:42:52 +00:00
|
|
|
|
|
|
|
|
|
public bool CanWrite(Type documentType)
|
|
|
|
|
{
|
|
|
|
|
return documentType.Equals(typeof(TextDocument));
|
|
|
|
|
}
|
2014-07-26 07:12:56 +00:00
|
|
|
|
}
|
|
|
|
|
}
|