From 7983cd067475fa4a417268919a09263a384c1887 Mon Sep 17 00:00:00 2001 From: morkt Date: Sat, 3 Dec 2016 19:18:59 +0400 Subject: [PATCH] moved BOM detection to separate methods. --- GUI/TextViewer.xaml.cs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/GUI/TextViewer.xaml.cs b/GUI/TextViewer.xaml.cs index 71d4f20c..e666cd14 100644 --- a/GUI/TextViewer.xaml.cs +++ b/GUI/TextViewer.xaml.cs @@ -114,29 +114,45 @@ namespace JustView var enc = Encoding.Default; if (3 == file.Read (m_test_buf, 0, 3)) { - if (0xef == m_test_buf[0] && 0xbb == m_test_buf[1] && 0xbf == m_test_buf[2]) + if (IsUTF8()) enc = Encoding.UTF8; - else if (0xfe == m_test_buf[0] && 0xff == m_test_buf[1]) + else if (IsUTF16BE()) enc = Encoding.BigEndianUnicode; - else if (0xff == m_test_buf[0] && 0xfe == m_test_buf[1]) + else if (IsUTF16LE()) enc = Encoding.Unicode; } file.Position = 0; return enc; } + private bool IsUTF8 () + { + return 0xEF == m_test_buf[0] && 0xBB == m_test_buf[1] && 0xBF == m_test_buf[2]; + } + + private bool IsUTF16BE () + { + return 0xFE == m_test_buf[0] && 0xFF == m_test_buf[1]; + } + + private bool IsUTF16LE () + { + return 0xFF == m_test_buf[0] && 0xFE == m_test_buf[1]; + } + public bool IsTextFile (Stream file) { int read = file.Read (m_test_buf, 0, m_test_buf.Length); file.Position = 0; + if (read > 3 && (IsUTF8() || IsUTF16LE() || IsUTF16BE())) + return true; bool found_eol = false; for (int i = 0; i < read; ++i) { byte c = m_test_buf[i]; if (c < 9 || (c > 0x0d && c < 0x1a) || (c > 0x1b && c < 0x20)) return false; - if (!found_eol && 0x0a == c) - found_eol = true; + found_eol = found_eol || 0x0A == c; } return found_eol || read < 80; }