private async void ServerThread() { while (!Cancellation.IsCancellationRequested) { try { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("ConvertZZ_Pipe", PipeDirection.InOut)) { await pipeServer.WaitForConnectionAsync(Cancellation.Token); Console.WriteLine("Client connected."); StreamString ss = new StreamString(pipeServer); string[] Args = (await ss.ReadStringAsync()).Split('|'); Window_DialogHost window_DialogHost = new Window_DialogHost(Args[0] == "/file" ? Enums.Enum_Mode.Mode.File_FileName : Enums.Enum_Mode.Mode.AutioTag, Args.Skip(1).ToArray()); window_DialogHost.Show(); await ss.WriteStringAsync("ACK"); pipeServer.WaitForPipeDrain(); pipeServer.Close(); } } catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } } }
private void MenuItem_Click(object sender, RoutedEventArgs e) { if (sender == null) { return; } if (((MenuItem)sender).Uid == null) { return; } string clip = ClipBoardHelper.GetClipBoard_UnicodeText(); if (!string.IsNullOrWhiteSpace((string)(((MenuItem)sender).ToolTip))) { clip = (string)(((MenuItem)sender).ToolTip); } StringBuilder sb = new StringBuilder(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Reset(); sw.Start(); switch (((MenuItem)sender).Uid) { case "1": this.Visibility = this.Visibility == Visibility.Visible ? Visibility.Hidden : Visibility.Visible; break; case "a1": if (App.Settings.RecognitionEncoding) { int encodingtype = EncodingAnalyzer.Analyze(clip); if (encodingtype == 0 || encodingtype == 1) { if (MessageBox.Show(this, "編碼似乎已是Big5,繼續轉換?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.No) { return; } } } clip = ConvertHelper.Convert(clip, new Encoding[] { Encoding.GetEncoding("GBK"), Encoding.GetEncoding("BIG5") }, 1); break; case "a2": if (App.Settings.RecognitionEncoding) { int encodingtype = EncodingAnalyzer.Analyze(clip); if (encodingtype == 2 || encodingtype == 3) { if (MessageBox.Show(this, "編碼似乎已是GBK,繼續轉換?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.No) { return; } } } clip = ConvertHelper.Convert(clip, new Encoding[] { Encoding.GetEncoding("BIG5"), Encoding.GetEncoding("GBK") }, 2); break; case "a3": clip = ConvertHelper.Convert(clip, 1); break; case "a4": clip = ConvertHelper.Convert(clip, 2); break; case "b1": Window_DialogHost window_File_FileNameConverter = new Window_DialogHost(Enums.Enum_Mode.Mode.File_FileName); window_File_FileNameConverter.Show(); break; case "b2": Window_DialogHost window_ClipBoard_Converter = new Window_DialogHost(Enums.Enum_Mode.Mode.ClipBoard); window_ClipBoard_Converter.Show(); break; case "c1": Window_DialogHost Window_DialogHost = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.ID3); Window_DialogHost.Show(); break; case "c2": Window_DialogHost Window_DialogHost2 = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.APE); Window_DialogHost2.Show(); break; case "c3": Window_DialogHost Window_DialogHost3 = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.OGG); Window_DialogHost3.Show(); break; case "za1": foreach (char c in clip) { if ((' ' <= c && c <= '~') || (c == '\r') || (c == '\n')) { if (c == '&') { sb.Append("&"); } else if (c == '<') { sb.Append("<"); } else if (c == '>') { sb.Append(">"); } else { sb.Append(c.ToString()); } } else { sb.Append("&#"); sb.Append(Convert.ToInt32(c)); sb.Append(";"); } } clip = sb.ToString(); break; case "za2": foreach (char c in clip) { if ((' ' <= c && c <= '~') || (c == '\r') || (c == '\n')) { if (c == '&') { sb.Append("&"); } else if (c == '<') { sb.Append("<"); } else if (c == '>') { sb.Append(">"); } else { sb.Append(c.ToString()); } } else { sb.Append("&#x"); sb.Append(Convert.ToInt32(c).ToString("X")); sb.Append(";"); } } clip = sb.ToString(); break; case "za3": clip.Replace("&", "&"); clip.Replace("<", "<"); clip.Replace(">", ">"); //以;將文字拆成陣列 string[] tmp = clip.Split(';'); //檢查最後一個字元是否為【;】,因為有【英文】、【阿拉伯數字】、【&#XXXX;】 //若最後一個要處理的字並非HTML UNICODE則不進行處理 bool Process_last = clip.Substring(clip.Length - 1, 1).Equals(";"); //Debug.WriteLine(tmp.Length + ""); for (int i = 0; i < tmp.Length; i++) { //以&#將文字拆成陣列 string[] tmp2 = tmp[i].Split(new string[] { "&#" }, StringSplitOptions.RemoveEmptyEntries); if (tmp2.Length == 1) { //如果長度為1則試圖轉換UNICODE回字符,若失敗則使用原本的字元 if (i != tmp.Length - 1) { try { if (tmp2[0].StartsWith("x")) { sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[0].Substring(1, tmp2[0].Length - 1), 16)).ToString()); } else { sb.Append(Convert.ToChar(Convert.ToInt32(int.Parse(tmp2[0]))).ToString()); } } catch { sb.Append(tmp2[0]); } } else { sb.Append(tmp2[0]); } } if (tmp2.Length == 2) { //若長度為2,則第一項不處理,只處理第二項即可 sb.Append(tmp2[0]); var g = Convert.ToInt32(tmp2[1].Substring(1, tmp2[1].Length - 1), 16); if (tmp2[1].StartsWith("x")) { sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[1].Substring(1, tmp2[1].Length - 1), 16)).ToString()); } else { sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[1])).ToString()); } } } clip = sb.ToString(); break; case "zb1": //Unicode>GBK clip = Encoding.Default.GetString(Encoding.GetEncoding("GBK").GetBytes(clip)); break; case "zb2": clip = Encoding.Default.GetString(Encoding.GetEncoding("BIG5").GetBytes(clip)); break; case "zb3": clip = Encoding.Default.GetString(Encoding.GetEncoding("Shift-JIS").GetBytes(clip)); break; case "zc1": //Shift-JIS>GBK clip = Encoding.GetEncoding("shift_jis").GetString(Encoding.GetEncoding("GBK").GetBytes(clip)); break; case "zc2": clip = Encoding.GetEncoding("shift_jis").GetString(Encoding.GetEncoding("BIG5").GetBytes(clip)); break; case "zc3": clip = Encoding.GetEncoding("GBK").GetString(Encoding.GetEncoding("shift_jis").GetBytes(clip)); break; case "zc4": clip = Encoding.GetEncoding("BIG5").GetString(Encoding.GetEncoding("shift_jis").GetBytes(clip)); break; case "zd1": //hz-gb-2312>GBK clip = Encoding.GetEncoding("hz-gb-2312").GetString(Encoding.GetEncoding("GBK").GetBytes(clip)); break; case "zd2": clip = Encoding.GetEncoding("hz-gb-2312").GetString(Encoding.GetEncoding("BIG5").GetBytes(clip)); break; case "zd3": clip = Encoding.GetEncoding("GBK").GetString(Encoding.GetEncoding("hz-gb-2312").GetBytes(clip)); break; case "zd4": clip = Encoding.GetEncoding("BIG5").GetString(Encoding.GetEncoding("hz-gb-2312").GetBytes(clip)); break; } ClipBoardHelper.SetClipBoard_UnicodeText(clip); sw.Stop(); //顯示提示 switch (((MenuItem)sender).Uid) { case "1": case "b1": case "b2": case "c1": case "c2": case "c3": break; default: if (App.Settings.Prompt && !(((MenuItem)sender).Visibility == Visibility.Hidden && (App.Settings.HotKey.AutoCopy || App.Settings.HotKey.AutoPaste))) { ContextMenu NotifyIconMenu = (ContextMenu)this.FindResource("NotifyIconMenu"); string ItemInfo = ((MenuItem)GetByUid(NotifyIconMenu, ((MenuItem)sender).Uid)).Header.ToString(); MessageBox.Show(this, String.Format("{0}轉換完成\r\n耗時:{1} ms", ItemInfo, sw.ElapsedMilliseconds)); } break; } }
private async void Application_Startup(object sender, StartupEventArgs e) { App.Reload(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ConvertZZ.json")); ShutdownMode = ShutdownMode.OnMainWindowClose; if (e.Args.Length > 0) { if (e.Args[0] == "/file" || e.Args[0] == "/audio") { var ps = Process.GetProcessesByName("ConvertZZ"); IntPtr hwndTest = IntPtr.Zero; if (ps.Length > 1) { long mini = ps.ToList().Min(x => x.StartTime.Ticks); hwndTest = ps.Where(x => x.StartTime.Ticks == mini).First().Handle; } else { ShowUI(); Window_DialogHost window_DialogHost = new Window_DialogHost(e.Args[0] == "/file" ? Enums.Enum_Mode.Mode.File_FileName : Enums.Enum_Mode.Mode.AutioTag, e.Args.Skip(1).ToArray()); window_DialogHost.Show(); return; } try { using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "ConvertZZ_Pipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { Console.WriteLine("Connecting to server...\n"); await pipeClient.ConnectAsync(1000); StreamString ss = new StreamString(pipeClient); // The client security token is sent with the first write. // Send the name of the file whose contents are returned // by the server. await ss.WriteStringAsync(string.Join("|", e.Args)); pipeClient.WaitForPipeDrain(); string returns = await ss.ReadStringAsync(); pipeClient.Close(); }; } catch { } Shutdown(1); return; } Encoding[] encoding = new Encoding[2]; bool EncodingSetted = false; int ToChinese = 0; string path1 = null, path2 = null; Regex Regex_path1 = null; int VocabularyCorrection = -1; Enum_Engine Engine = App.Settings.Engine; for (int i = 0; i < e.Args.Length; i++) { switch (e.Args[i]) { case "/i:ule": encoding[0] = Encoding.Unicode; EncodingSetted = true; break; case "/i:ube": encoding[0] = Encoding.BigEndianUnicode; EncodingSetted = true; break; case "/i:utf8": encoding[0] = Encoding.UTF8; EncodingSetted = true; break; case "/i:gbk": encoding[0] = Encoding.GetEncoding("GBK"); EncodingSetted = true; break; case "/i:big5": encoding[0] = Encoding.GetEncoding("Big5"); EncodingSetted = true; break; case "/o:ule": encoding[1] = Encoding.Unicode; break; case "/o:ube": encoding[1] = Encoding.BigEndianUnicode; break; case "/o:utf8": encoding[1] = Encoding.UTF8; break; case "/o:gbk": encoding[1] = Encoding.GetEncoding("GBK"); break; case "/o:big5": encoding[1] = Encoding.GetEncoding("Big5"); break; case "/f:t": ToChinese = 1; break; case "/f:s": ToChinese = 2; break; case "/f:d": ToChinese = 0; break; case "/d:t": VocabularyCorrection = 1; break; case "/d:f": VocabularyCorrection = 0; break; case "/d:s": VocabularyCorrection = -1; break; case "/e:l": Engine = Enum_Engine.Local; break; case "/e:f": Engine = Enum_Engine.Fanhuaji; break; default: if (path1 == null) { path1 = e.Args[i]; Regex_path1 = new Regex($"{Regex.Replace(path1.Replace("*", "(.*?)").Replace("\\", "\\\\"), "[\\/]", "[\\\\/]")}$"); } else { path2 = e.Args[i]; } break; } } if (VocabularyCorrection == 1 || (VocabularyCorrection == -1 && App.Settings.VocabularyCorrection)) { await LoadDictionary(Engine); } string s = ""; List <string> file = new List <string>(); bool ModeIsOneFile = true; if (path1.Contains("*")) { ModeIsOneFile = false; Directory.GetFiles(Path.GetDirectoryName(path1), Path.GetFileName(path1)).ToList().ForEach(x => file.Add(x) ); } else { if (File.Exists(path1)) { file.Add(path1); } else { Console.WriteLine($"檔案\"{path1}\" 不存在"); Console.Read(); Shutdown(1); return; } } if (encoding[1] == null || string.IsNullOrWhiteSpace(path1)) { Console.WriteLine("參數錯誤(目標編碼為空或來源檔案路徑未填寫)"); Console.Read(); Shutdown(1); return; } if (string.IsNullOrWhiteSpace(path2)) { path2 = path1; } if (path1.Count(x => x == '*') != path2.Count(x => x == '*') && path2.Contains("*")) { Console.WriteLine("參數錯誤(輸出路徑的萬用字元術與輸入路徑不同)"); Console.Read(); Shutdown(1); return; } if (path1.Contains("*") && !path2.Contains("*") && File.Exists(path2)) { Console.WriteLine("參數錯誤(輸入路徑具有萬用字元,但輸出路徑卻指向一個檔案)"); Console.Read(); Shutdown(1); return; } foreach (var f in file) { using (Stream stream = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (StreamReader streamReader = new StreamReader(stream, encoding[0], false)) { s = streamReader.ReadToEnd(); } } if (!EncodingSetted) { switch (EncodingAnalyzer.Analyze(s)) { case -1: encoding[0] = Encoding.Default; break; case 0: case 1: encoding[0] = Encoding.GetEncoding("BIG5"); break; case 2: case 3: encoding[0] = Encoding.GetEncoding("GBK"); break; } } try { s = await ConvertHelper.FileConvert(s, encoding, ToChinese, VocabularyCorrection); } catch (Fanhuaji.FanhuajiException ex) { Console.WriteLine($"[Error][{DateTime.Now.ToString()}][{ex.Message}] {f}"); continue; } if (ModeIsOneFile) { using (StreamWriter streamWriter = new StreamWriter(path2, false, encoding[1] == Encoding.UTF8 ? new UTF8Encoding(App.Settings.FileConvert.UnicodeAddBom) : encoding[1])) { streamWriter.Write(s); streamWriter.Flush(); } } else { var m1 = Regex_path1.Match(f); if (m1.Success) { if (path2.Contains("*")) { var array = path2.Split('*'); string @string = ""; for (int i = 0; i < array.Length; i++) { @string += array[i]; if (i + 1 <= m1.Groups.Count - 1) { @string += m1.Groups[i + 1].Value; } } Directory.CreateDirectory(Path.GetDirectoryName(@string)); using (StreamWriter streamWriter = new StreamWriter(@string, false, encoding[1] == Encoding.UTF8 ? new UTF8Encoding(App.Settings.FileConvert.UnicodeAddBom) : encoding[1])) { streamWriter.Write(s); streamWriter.Flush(); } } else { Directory.CreateDirectory(Path.GetDirectoryName(path2)); using (StreamWriter streamWriter = new StreamWriter(Path.Combine(Path.GetDirectoryName(path2), Path.GetFileName(f)), false, encoding[1] == Encoding.UTF8 ? new UTF8Encoding(App.Settings.FileConvert.UnicodeAddBom) : encoding[1])) { streamWriter.Write(s); streamWriter.Flush(); } } } } } Shutdown(1); return; } else { if ((Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)) { MessageBox.Show("應用程式 " + Process.GetCurrentProcess().ProcessName + " 己在執行中,請先關閉舊視窗。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning); Shutdown(1); return; } ShowUI(); } }