using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace 原始碼修改
{
public class WriteSourceFile : IOperateSource
{
private ReadDocument readDocument;
private List<string> sourceFileContent;
private int amountOfChanges;
public int AmountOfChanges
{
get
{
return amountOfChanges;
}
}
public WriteSourceFile(ReadDocument readDocument)
{
this.readDocument = readDocument;
sourceFileContent = new List<string>();
amountOfChanges = 0;
}
// 精簡掉代碼中;後面的所有內容.
private void SimplifyALine(ref string aLine)
{
bool doubleQuotationHasOpend = false;
for (int i = 0; i != aLine.Length; ++i)
{
if (aLine[i] == '"')
doubleQuotationHasOpend = !doubleQuotationHasOpend;
else if (aLine[i] == ';')
{
if (doubleQuotationHasOpend)
{
// 在代碼中的字串常量中出現了;
continue;
}
else
{
// 此;是結束代碼的;
if (i + 1 != aLine.Length)
{
aLine = aLine.Remove(i + 1);
return;
}
// 否則,代碼不需要精簡
}
}
}
}
// 添加註釋之前去掉代碼;後的原所有注釋如果有
private void AddExegesis(ref string aProcessedLine, string originalString)
{
SimplifyALine(ref aProcessedLine);
aProcessedLine += ("// " + originalString);
}
private void ProcessALine(ref string aLine)
{
for (int i = 0; i < aLine.Length; ++i)
{
if (aLine[i] == KeyChar && i + 1 < aLine.Length && aLine[i + 1] == '"' && i + 2 < aLine.Length)
{
string originalString = null;
for (int j = i + 2; j < aLine.Length && aLine[j] != '"'; ++j)
originalString += aLine[j];
if (readDocument.ContainsOriginalString(originalString))
{
++amountOfChanges;
aLine = aLine.Replace(originalString, readDocument.GetTargetString(originalString));
AddExegesis(ref aLine, originalString);
}
// 用以應對一行中出現多個待翻譯字串的情況
i += (originalString.Length + 2);
}
}
}
override public void Go(FileInfo sourceFineInfo)
{
// 將想要被替換的資訊用文檔中的相應內容替換
StreamReader reader = sourceFineInfo.OpenText();
string aLine = reader.ReadLine();
while (aLine != null)
{
ProcessALine(ref aLine);
sourceFileContent.Add(aLine);
aLine = reader.ReadLine();
}
reader.Close();
StreamWriter writer = new StreamWriter(sourceFineInfo.FullName, false, Encoding.UTF8);
foreach (string aProcessedLine in sourceFileContent)
{
writer.WriteLine(aProcessedLine);
}
writer.Close();
sourceFileContent.Clear();
}
}
}