Skip to content

Commit

Permalink
更新了OpenCC.NET版本;添加了对docx文档转换的支持
Browse files Browse the repository at this point in the history
  • Loading branch information
CosineG committed Apr 25, 2022
1 parent 82bb2f0 commit 9d87817
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 177 deletions.
122 changes: 0 additions & 122 deletions Dictionary/CNVariants.txt

This file was deleted.

3 changes: 1 addition & 2 deletions Enums/VariantType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ public enum VariantType
{
OpenCC,
TW,
HK,
CN
HK
}
}
23 changes: 16 additions & 7 deletions OpenCC.NET.GUI.csproj
Original file line number Diff line number Diff line change
@@ -1,27 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net6.0-windows10.0.18362.0</TargetFramework>
<UseWPF>true</UseWPF>
<SatelliteResourceLanguages>zh-CN;zh-TW</SatelliteResourceLanguages>
<ApplicationIcon>opencc-net-gui.ico</ApplicationIcon>
<Version>1.0.0</Version>
<Version>1.1.0</Version>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.16.0" />
<PackageReference Include="Microsoft.Toolkit.Mvvm" Version="7.1.2" />
<PackageReference Include="ModernWpfUI" Version="0.9.4" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.0" />
<PackageReference Include="OpenCCNET" Version="0.2.0" />
<PackageReference Include="OpenCCNET" Version="1.0.0" />
</ItemGroup>

<ItemGroup>
<Page Include="App.xaml" />
</ItemGroup>

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="xcopy /e /y /i &quot;$(SolutionDir)Dictionary&quot; &quot;$(ProjectDir)$(OutDir)Dictionary&quot;&#xD;&#xA;xcopy /e /y /i &quot;$(SolutionDir)JiebaResource&quot; &quot;$(ProjectDir)$(OutDir)JiebaResource&quot;" />
</Target>
<ItemGroup>
<Content Include="Dictionary\*.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>

<ItemGroup>
<Content Include="JiebaResource\*.*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion ViewModels/FileViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public ObservableCollection<File> Files
public void AddFile()
{
// 选择原文件
var openFileDialog = new OpenFileDialog {Filter = "文本文件(*.txt)|*.txt", Multiselect = true};
var openFileDialog = new OpenFileDialog {Filter = "纯文本 (*.txt)|*.txt;|Word 文档 (*.docx)|*.docx", Multiselect = true};
if (openFileDialog.ShowDialog() == false) return;
var dialogFilePaths = openFileDialog.FileNames;

Expand Down
138 changes: 100 additions & 38 deletions ViewModels/OptionViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices.ComTypes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using OpenCC.NET.GUI.Enums;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using OpenCCNET;

namespace OpenCC.NET.GUI.ViewModels
Expand Down Expand Up @@ -221,7 +222,6 @@ public string ConvertText(string text)
VariantType.OpenCC => text.ToHantFromHans(),
VariantType.TW => text.ToTWFromHans(IsIdiomConvert),
VariantType.HK => text.ToHKFromHans(),
VariantType.CN => text.ToCNFromHans(),
_ => result
};
}
Expand All @@ -238,7 +238,6 @@ public string ConvertText(string text)
VariantType.OpenCC => text.ToHantFromTW(),
VariantType.TW => text.ToTWFromHant(IsIdiomConvert),
VariantType.HK => text.ToHKFromHant(),
VariantType.CN => text.ToCNFromHant(),
_ => result
};
}
Expand All @@ -255,44 +254,44 @@ public string ConvertText(string text)
public async Task ConvertFileAsync(ICollection<File> files)
{
IsProcessing = true;
var task = Task.Run(() =>
var tasks = files.Select(async file =>
{
foreach (var file in files)
if (file.Status == FileStatus.Success)
{
if (file.Status == FileStatus.Success)
{
continue;
}
return;
}

try
{
// 指定输入输出路径
var filePath = file.Path;
var suffix = GetProcessSuffix();
var outputPath = Path.Combine(file.OutputFolder,
Path.GetFileNameWithoutExtension(filePath) + suffix + Path.GetExtension(filePath));
using var reader = new StreamReader(filePath);
using var writer = new StreamWriter(outputPath) {AutoFlush = true};

// 转换
Messenger.Send(file, "FileStatusRunning");
string originalLine;
while ((originalLine = reader.ReadLine()) != null)
{
var convertedLine = ConvertText(originalLine);
writer.WriteLine(convertedLine);
}
}
catch (Exception)
try
{
// 指定输入输出路径
var filePath = file.Path;
var suffix = GetProcessSuffix();
var extension = Path.GetExtension(filePath);
var outputPath = Path.Combine(file.OutputFolder,
Path.GetFileNameWithoutExtension(filePath) + suffix + extension);

Messenger.Send(file, "FileStatusRunning");

// 转换
switch (extension)
{
Messenger.Send(file, "FileStatusFail");
continue;
case ".txt":
await ConvertTextFileAsync(filePath, outputPath);
break;
case ".docx":
await ConvertDocxFileAsync(filePath, outputPath);
break;
}

Messenger.Send(file, "FileStatusSuccess");
}
catch (Exception)
{
Messenger.Send(file, "FileStatusFail");
return;
}

Messenger.Send(file, "FileStatusSuccess");
});
await Task.WhenAll(task);
await Task.WhenAll(tasks);
IsProcessing = false;
}

Expand All @@ -310,6 +309,8 @@ private string GetProcessSuffix()
case CharacterType.Traditional:
suffix.Append("_繁");
break;
default:
throw new ArgumentOutOfRangeException();
}

switch (TargetVariant)
Expand All @@ -323,9 +324,8 @@ private string GetProcessSuffix()
case VariantType.HK:
suffix.Append("_港");
break;
case VariantType.CN:
suffix.Append("_陆");
break;
default:
throw new ArgumentOutOfRangeException();
}

if (IsIdiomConvert)
Expand All @@ -335,5 +335,67 @@ private string GetProcessSuffix()

return suffix.ToString();
}

/// <summary>
/// 转换txt格式的文本文件
/// </summary>
/// <param name="filePath">输入文件路径</param>
/// <param name="outputPath">输出文件路径</param>
/// <returns></returns>
private async Task ConvertTextFileAsync(string filePath, string outputPath)
{
using var reader = new StreamReader(filePath);
await using var writer = new StreamWriter(outputPath);

var lines = new List<string>();
string originalLine;
while ((originalLine = await reader.ReadLineAsync()) != null)
{
lines.Add(originalLine);
}

var childTasks = Enumerable.Range(0, lines.Count).Select(async i =>
{
await Task.Run(() => lines[i] = ConvertText(lines[i]));
});

await Task.WhenAll(childTasks);

foreach (var line in lines)
{
await writer.WriteLineAsync(line);
}
}

/// <summary>
/// 转换docx格式的Word文档
/// </summary>
/// <param name="filePath">输入文件路径</param>
/// <param name="outputPath">输出文件路径</param>
/// <returns></returns>
private async Task ConvertDocxFileAsync(string filePath, string outputPath)
{
System.IO.File.Copy(filePath, outputPath);
try
{
using var docx = WordprocessingDocument.Open(outputPath, true);
if (docx.MainDocumentPart != null)
{
var document = docx.MainDocumentPart.Document;

var tasks = document.Descendants<Text>().Select(async text =>
{
await Task.Run(() => text.Text = ConvertText(text.Text));
});

await Task.WhenAll(tasks);
}
}
catch (Exception)
{
System.IO.File.Delete(outputPath);
throw;
}
}
}
}
2 changes: 1 addition & 1 deletion Views/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
try
{
ZhUtil.Initialize();
ZhConverter.Initialize();
}
catch (Exception)
{
Expand Down
Loading

0 comments on commit 9d87817

Please sign in to comment.