added text files preview.

This commit is contained in:
morkt 2015-05-12 13:31:27 +04:00
parent d77e3f0b4c
commit b5fa9cc105
13 changed files with 451 additions and 53 deletions

View File

@ -56,7 +56,7 @@
<value />
</setting>
<setting name="appTextEncoding" serializeAs="String">
<value>UTF-8</value>
<value>65001</value>
</setting>
<setting name="appLastDirectory" serializeAs="String">
<value />

View File

@ -155,6 +155,9 @@
<DesignTime>True</DesignTime>
<DependentUpon>guiStrings.resx</DependentUpon>
</Compile>
<Compile Include="TextViewer.xaml.cs">
<DependentUpon>TextViewer.xaml</DependentUpon>
</Compile>
<Compile Include="Utility.cs" />
<Compile Include="ViewModel.cs" />
<Page Include="AboutBox.xaml">
@ -193,6 +196,10 @@
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Page Include="TextViewer.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">

View File

@ -2,7 +2,7 @@
//! \date Sun Jul 06 06:34:56 2014
//! \brief preview images.
//
// Copyright (C) 2014 by morkt
// Copyright (C) 2014-2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
@ -37,6 +37,10 @@ using System.Windows.Threading;
using GARbro.GUI.Strings;
using GARbro.GUI.Properties;
using GameRes;
using System.Text;
using System.Windows.Documents;
using System.Windows.Media;
using System.Globalization;
namespace GARbro.GUI
{
@ -46,6 +50,29 @@ namespace GARbro.GUI
private PreviewFile m_current_preview = new PreviewFile();
private bool m_preview_pending = false;
private UIElement m_active_viewer;
public UIElement ActiveViewer
{
get { return m_active_viewer; }
set
{
if (value == m_active_viewer)
return;
m_active_viewer = value;
m_active_viewer.Visibility = Visibility.Visible;
bool exists = false;
foreach (var c in PreviewPane.Children.Cast<UIElement>())
{
if (c != m_active_viewer)
c.Visibility = Visibility.Collapsed;
else
exists = true;
}
if (!exists)
PreviewPane.Children.Add (m_active_viewer);
}
}
class PreviewFile
{
public string Path { get; set; }
@ -66,6 +93,31 @@ namespace GARbro.GUI
if (m_preview_pending)
RefreshPreviewPane();
};
ActiveViewer = ImageView;
}
private IEnumerable<Encoding> m_encoding_list = GetEncodingList();
public IEnumerable<Encoding> TextEncodings { get { return m_encoding_list; } }
private static IEnumerable<Encoding> GetEncodingList ()
{
var list = new HashSet<Encoding>();
list.Add (Encoding.Default);
var oem = CultureInfo.CurrentCulture.TextInfo.OEMCodePage;
list.Add (Encoding.GetEncoding (oem));
list.Add (Encoding.GetEncoding (932));
list.Add (Encoding.UTF8);
list.Add (Encoding.Unicode);
list.Add (Encoding.BigEndianUnicode);
return list;
}
private void OnEncodingSelect (object sender, SelectionChangedEventArgs e)
{
var enc = this.EncodingChoice.SelectedItem as Encoding;
if (null == enc || null == CurrentTextInput)
return;
TextView.CurrentEncoding = enc;
}
/// <summary>
@ -85,43 +137,110 @@ namespace GARbro.GUI
if (null != current)
UpdatePreviewPane (current.Source);
else
PreviewPane.Source = null;
ResetPreviewPane();
}
void ResetPreviewPane ()
{
ActiveViewer = ImageView;
ImageCanvas.Source = null;
TextView.Clear();
CurrentTextInput = null;
}
bool IsPreviewPossible (Entry entry)
{
return "image" == entry.Type || "script" == entry.Type
|| (string.IsNullOrEmpty (entry.Type) && entry.Size < 0x100000);
}
void UpdatePreviewPane (Entry entry)
{
SetStatusText ("");
var vm = ViewModel;
m_current_preview = new PreviewFile { Path = vm.Path, Name = entry.Name };
PreviewPane.Source = null;
if (entry.Type != "image")
return;
if (vm.IsArchive)
m_current_preview = new PreviewFile { Path = vm.Path, Name = entry.Name, Entry = entry };
ImageCanvas.Source = null;
TextView.Clear();
if (!IsPreviewPossible (entry))
{
m_current_preview.Archive = m_app.CurrentArchive;
m_current_preview.Entry = entry;
ActiveViewer = ImageView;
return;
}
if (!m_preview_worker.IsBusy)
if (vm.IsArchive)
m_current_preview.Archive = m_app.CurrentArchive;
if ("image" != entry.Type)
LoadPreviewText (m_current_preview);
else if (!m_preview_worker.IsBusy)
m_preview_worker.RunWorkerAsync (m_current_preview);
else
m_preview_pending = true;
}
private Stream m_current_text;
private Stream CurrentTextInput
{
get { return m_current_text; }
set
{
if (value == m_current_text)
return;
if (null != m_current_text)
m_current_text.Dispose();
m_current_text = value;
}
}
Stream OpenPreviewStream (PreviewFile preview)
{
if (null == preview.Archive)
{
string filename = Path.Combine (preview.Path, preview.Name);
return File.OpenRead (filename);
}
else
{
return preview.Archive.OpenEntry (preview.Entry);
}
}
void LoadPreviewText (PreviewFile preview)
{
Stream file = null;
try
{
file = OpenPreviewStream (preview);
if (!TextView.IsTextFile (file))
{
ActiveViewer = ImageView;
return;
}
var enc = EncodingChoice.SelectedItem as Encoding;
if (null == enc)
{
enc = TextView.GuessEncoding (file);
EncodingChoice.SelectedItem = enc;
}
TextView.DisplayStream (file, enc);
ActiveViewer = TextView;
CurrentTextInput = file;
file = null;
}
catch (Exception X)
{
SetStatusText (X.Message);
}
finally
{
if (file != null)
file.Dispose();
}
}
void LoadPreviewImage (PreviewFile preview)
{
try
{
Stream file;
if (null == preview.Archive)
{
string filename = Path.Combine (preview.Path, preview.Name);
file = new FileStream (filename, FileMode.Open, FileAccess.Read);
}
else
{
file = preview.Archive.OpenEntry (preview.Entry);
}
using (file)
using (var file = OpenPreviewStream (preview))
{
var data = ImageFormat.Read (file);
if (null != data)
@ -153,7 +272,8 @@ namespace GARbro.GUI
{
if (m_current_preview == preview) // compare by reference
{
PreviewPane.Source = bitmap;
ActiveViewer = ImageView;
ImageCanvas.Source = bitmap;
SetStatusText (string.Format (guiStrings.MsgImageSize, bitmap.PixelWidth,
bitmap.PixelHeight, bitmap.Format.BitsPerPixel));
}
@ -165,7 +285,7 @@ namespace GARbro.GUI
/// </summary>
private void FitWindowExec (object sender, ExecutedRoutedEventArgs e)
{
var image = PreviewPane.Source;
var image = ImageCanvas.Source;
if (null == image)
return;
var width = image.Width + Settings.Default.lvPanelWidth.Value + 1;

View File

@ -2,6 +2,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GARbro.GUI"
xmlns:jv="clr-namespace:JustView"
xmlns:s="clr-namespace:GARbro.GUI.Strings"
xmlns:p="clr-namespace:GARbro.GUI.Properties"
Title="GARbro" MinHeight="250" ResizeMode="CanResizeWithGrip"
@ -212,6 +213,15 @@
<Image Source="Images/48x48/refresh.png" Height="16" Width="16"/>
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal" x:Name="EncodingWidget" Visibility="{Binding ElementName=TextView, Path=Visibility}">
<Separator/>
<TextBlock Text="{x:Static s:guiStrings.LabelEncoding}" VerticalAlignment="Center" Margin="5,0,5,0"/>
<ComboBox x:Name="EncodingChoice" IsEditable="False" Height="22" DisplayMemberPath="EncodingName"
ItemsSource="{Binding ElementName=AppWindow, Path=TextEncodings}"
SelectedValue="{Binding Source={x:Static p:Settings.Default}, Path=appTextEncoding, Mode=TwoWay}"
SelectedValuePath="CodePage" SelectionChanged="OnEncodingSelect"/>
<Separator/>
</StackPanel>
<Button ToolTip="{x:Static s:guiStrings.MenuAbout}" DockPanel.Dock="Right" Margin="0,2,10,2"
Command="{x:Static local:Commands.About}">
<Image Source="{StaticResource Icon32x32Help}"/>
@ -323,11 +333,13 @@
</GridView>
</ListView.View>
</local:ListViewEx>
<ScrollViewer Grid.Column="2" Background="LightGray"
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<Image Name="PreviewPane" Stretch="None" UseLayoutRounding="True" SnapsToDevicePixels="True"
<Grid Grid.Column="2" Name="PreviewPane" SnapsToDevicePixels="True">
<ScrollViewer Name="ImageView" Background="LightGray" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<Image Name="ImageCanvas" Stretch="None" UseLayoutRounding="True" SnapsToDevicePixels="True"
local:TouchScrolling.IsEnabled="True"/>
</ScrollViewer>
<jv:TextViewer x:Name="TextView" Visibility="Collapsed" BorderThickness="1,0,0,0" BorderBrush="Black"/>
</Grid>
<!-- Margin and BorderThickness help to react early on mouse pointer -->
<GridSplitter Grid.Column="1" Background="Black" ShowsPreview="False" Focusable="False"
Margin="-3,0" BorderThickness="3,0" BorderBrush="Transparent"

View File

@ -120,11 +120,7 @@ namespace GARbro.GUI
/// </summary>
protected override void OnClosing (CancelEventArgs e)
{
if (null != m_audio)
{
m_audio.Dispose();
m_audio = null;
}
CurrentAudio = null;
SaveSettings();
base.OnClosing (e);
}
@ -816,6 +812,16 @@ namespace GARbro.GUI
}
WaveOutEvent m_audio;
WaveOutEvent CurrentAudio
{
get { return m_audio; }
set
{
if (m_audio != null)
m_audio.Dispose();
m_audio = value;
}
}
private void PlayFile (Entry entry)
{
@ -832,17 +838,16 @@ namespace GARbro.GUI
return;
}
if (m_audio != null)
if (CurrentAudio != null)
{
m_audio.PlaybackStopped -= OnPlaybackStopped;
m_audio.Dispose();
m_audio = null;
CurrentAudio.PlaybackStopped -= OnPlaybackStopped;
CurrentAudio = null;
}
var wave_stream = new WaveStreamImpl (sound);
m_audio = new WaveOutEvent();
m_audio.Init (wave_stream);
m_audio.PlaybackStopped += OnPlaybackStopped;
m_audio.Play();
CurrentAudio = new WaveOutEvent();
CurrentAudio.Init (wave_stream);
CurrentAudio.PlaybackStopped += OnPlaybackStopped;
CurrentAudio.Play();
var fmt = wave_stream.WaveFormat;
SetResourceText (string.Format ("Playing {0} / {2}bps / {1}Hz", entry.Name,
fmt.SampleRate, sound.SourceBitrate / 1000));
@ -1126,7 +1131,7 @@ namespace GARbro.GUI
private void CanExecuteFitWindow (object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = PreviewPane.Source != null;
e.CanExecute = ImageCanvas.Source != null;
}
private void HideStatusBarExec (object sender, ExecutedRoutedEventArgs e)

View File

@ -12,7 +12,7 @@ using System.Windows;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany ("mørkt")]
[assembly: AssemblyProduct("GARbro.GUI")]
[assembly: AssemblyCopyright("Copyright © 2014 mørkt")]
[assembly: AssemblyCopyright ("Copyright © 2014-2015 mørkt")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@ -51,5 +51,5 @@ using System.Windows;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion ("1.0.4.13")]
[assembly: AssemblyFileVersion ("1.0.3.13")]
[assembly: AssemblyVersion ("1.0.4.14")]
[assembly: AssemblyFileVersion ("1.0.4.14")]

View File

@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@ -205,10 +205,10 @@ namespace GARbro.GUI.Properties {
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("UTF-8")]
public string appTextEncoding {
[global::System.Configuration.DefaultSettingValueAttribute("65001")]
public int appTextEncoding {
get {
return ((string)(this["appTextEncoding"]));
return ((int)(this["appTextEncoding"]));
}
set {
this["appTextEncoding"] = value;

View File

@ -47,8 +47,8 @@
<Setting Name="appImageFormat" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
<Setting Name="appTextEncoding" Type="System.String" Scope="User">
<Value Profile="(Default)">UTF-8</Value>
<Setting Name="appTextEncoding" Type="System.Int32" Scope="User">
<Value Profile="(Default)">65001</Value>
</Setting>
<Setting Name="appLastDirectory" Type="System.String" Scope="User">
<Value Profile="(Default)" />

View File

@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@ -312,6 +312,15 @@ namespace GARbro.GUI.Strings {
}
}
/// <summary>
/// Looks up a localized string similar to Encoding.
/// </summary>
public static string LabelEncoding {
get {
return ResourceManager.GetString("LabelEncoding", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Extract files from {0} to.
/// </summary>

View File

@ -396,4 +396,7 @@ Overwrite?</value>
<data name="TextImageConvertError" xml:space="preserve">
<value>Image conversion error</value>
</data>
<data name="LabelEncoding" xml:space="preserve">
<value>Encoding</value>
</data>
</root>

View File

@ -411,4 +411,7 @@
<data name="TextImageConvertError" xml:space="preserve">
<value>Ошибка конверсии изображения</value>
</data>
<data name="LabelEncoding" xml:space="preserve">
<value>Кодировка</value>
</data>
</root>

5
TextViewer.xaml Normal file
View File

@ -0,0 +1,5 @@
<FlowDocumentScrollViewer x:Class="JustView.TextViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<FlowDocument PagePadding="2" TextAlignment="Left" IsHyphenationEnabled="False" FontFamily="Consolas, Courier New" FontSize="12"/>
</FlowDocumentScrollViewer>

234
TextViewer.xaml.cs Normal file
View File

@ -0,0 +1,234 @@
//! \file TextViewer.cs
//! \date Mon May 11 23:24:33 2015
//! \brief Text file viewer widget.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
namespace JustView
{
/// <summary>
/// Interaction logic for TextViewer.xaml
/// </summary>
public partial class TextViewer : FlowDocumentScrollViewer
{
Lazy<ScrollViewer> m_scroll_viewer;
Lazy<double> m_default_width;
public TextViewer ()
{
m_scroll_viewer = new Lazy<ScrollViewer> (FindScrollViewer);
m_default_width = new Lazy<double> (() => GetFixedWidth (80));
InitializeComponent();
DefaultZoom = 100;
}
public void Clear ()
{
this.Document.Blocks.Clear();
Input = null;
}
public ScrollViewer ScrollViewer { get { return m_scroll_viewer.Value; } }
public double DefaultWidth { get { return m_default_width.Value; } }
public double DefaultZoom { get; private set; }
public Stream Input { get; set; }
public double MaxLineWidth { get; set; }
private bool m_word_wrap;
public bool IsWordWrapEnabled
{
get { return m_word_wrap; }
set
{
m_word_wrap = value;
ApplyWordWrap (value);
}
}
private Encoding m_current_encoding;
public Encoding CurrentEncoding
{
get { return m_current_encoding; }
set
{
if (m_current_encoding != value)
{
m_current_encoding = value;
Refresh();
}
}
}
public void DisplayStream (Stream file, Encoding enc)
{
if (file.Length > 0xffffff)
throw new ApplicationException ("File is too long");
ReadStream (file, enc);
var sv = FindScrollViewer();
if (sv != null)
sv.ScrollToHome();
Input = file;
m_current_encoding = enc;
}
public void Refresh ()
{
if (Input != null)
{
Input.Position = 0;
ReadStream (Input, CurrentEncoding);
}
}
byte[] m_test_buf = new byte[0x400];
public Encoding GuessEncoding (Stream file)
{
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])
enc = Encoding.UTF8;
else if (0xfe == m_test_buf[0] && 0xff == m_test_buf[1])
enc = Encoding.BigEndianUnicode;
else if (0xff == m_test_buf[0] && 0xfe == m_test_buf[1])
enc = Encoding.Unicode;
}
file.Position = 0;
return enc;
}
public bool IsTextFile (Stream file)
{
int read = file.Read (m_test_buf, 0, m_test_buf.Length);
file.Position = 0;
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;
}
return found_eol || read < 80;
}
double GetFixedWidth (int char_width)
{
var block = new TextBlock();
block.FontFamily = this.Document.FontFamily;
block.FontSize = this.Document.FontSize;
block.Padding = this.Document.PagePadding;
block.Text = new string ('M', char_width);
block.Measure (new Size (double.PositiveInfinity, double.PositiveInfinity));
return block.DesiredSize.Width;
}
void ReadStream (Stream file, Encoding enc)
{
using (var reader = new StreamReader (file, enc, false, 0x400, true))
{
this.Document.Blocks.Clear();
var para = new Paragraph();
var block = new TextBlock();
block.FontFamily = this.Document.FontFamily;
block.FontSize = this.Document.FontSize;
block.Padding = this.Document.PagePadding;
double max_width = 0;
var max_size = new Size (double.PositiveInfinity, double.PositiveInfinity);
for (;;)
{
var line = reader.ReadLine();
if (null == line)
break;
if (line.Length > 0)
{
block.Text = line;
block.Measure (max_size);
var width = block.DesiredSize.Width;
if (width > max_width)
max_width = width;
para.Inlines.Add (new Run (line));
}
para.Inlines.Add (new LineBreak());
}
this.Document.Blocks.Add (para);
MaxLineWidth = max_width;
ApplyWordWrap (IsWordWrapEnabled);
}
}
public void ApplyWordWrap (bool word_wrap)
{
if (word_wrap)
{
var scroll = this.ScrollViewer;
if (scroll != null)
{
this.Document.PageWidth = scroll.ViewportWidth;
var width_binding = new Binding ("ViewportWidth");
width_binding.Source = scroll;
width_binding.Mode = BindingMode.OneWay;
width_binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding (this.Document, FlowDocument.PageWidthProperty, width_binding);
}
else
{
BindingOperations.ClearBinding (this.Document, FlowDocument.PageWidthProperty);
this.Document.PageWidth = this.ActualWidth;
}
}
else
{
BindingOperations.ClearBinding (this.Document, FlowDocument.PageWidthProperty);
this.Document.PageWidth = MaxLineWidth;
}
}
public ScrollViewer FindScrollViewer ()
{
if (VisualTreeHelper.GetChildrenCount (this) == 0)
return null;
// Border is the first child of first child of a ScrolldocumentViewer
var firstChild = VisualTreeHelper.GetChild (this, 0);
if (firstChild == null)
return null;
var border = VisualTreeHelper.GetChild (firstChild, 0) as Decorator;
if (border == null)
return null;
return border.Child as ScrollViewer;
}
}
}