private async void Button_Save_CheckedAsync(object sender, RoutedEventArgs e) { if (Window_MessageBoxEx.ShowDialog("注意!此操作將不可逆,請先做好備份(Dictionary.csv)", "儲存字典?", "儲存", "取消") == Window_MessageBoxEx.MessageBoxExResult.A) { await DictionaryFile_Helper.Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Dictionary.csv"), DataGrid_ItemSource); await App.ChineseConverter.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Dictionary.csv")); new Toast("已儲存!").Show(); } }
private async Task Preview() { try { Output = await ConvertHelper.ConvertAsync(ClipBoard, encoding, ToChinese); } catch (FanhuajiException val) { FanhuajiException fe = val; Window_MessageBoxEx.ShowDialog(((Exception)fe).Message, "繁化姬API", "確定"); } }
private async void Button_SelectFile_Clicked(object sender, RoutedEventArgs e) { OpenFileDialog fileDialog = new OpenFileDialog() { Multiselect = true, CheckFileExists = false, CheckPathExists = true, ValidateNames = false }; fileDialog.InitialDirectory = App.Settings.FileConvert.DefaultPath; fileDialog.FileName = " "; if (FileMode) { fileDialog.Filter = Combobox_Filter.SelectedValue.ToString(); } if (fileDialog.ShowDialog() == true) { OutputPath = Path.GetDirectoryName(fileDialog.FileNames.First()); if (!FileMode) { string a; try { treeview_nodes = new List <Node>() { GetChildPath(OutputPath, AccordingToChild, Combobox_Filter.Text) }; a = await CreateDictionary(); } catch (Exception ex) { a = $"[Error][{ex.Message}]StackTrace: {ex.StackTrace}"; } if (!string.IsNullOrWhiteSpace(a)) { PathParts = null; Window_MessageBoxEx.ShowDialog(a, "預覽轉換中出現錯誤", "我知道了"); } treeview_nodes.ForEach(x => x.PropertyChanged += Treeview_CheckedChanged); treeview.ItemSources = treeview_nodes; Treeview_CheckedChanged(null, new PropertyChangedEventArgs(nameof(Node.IsChecked))); } else { ImportFileNames(fileDialog.FileNames); } Combobox_Filter_SelectionChanged(Combobox_Filter, null); } }
private async 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.Restart(); try { 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 = await ConvertHelper.ConvertAsync(clip, new Encoding[2] { 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 = await ConvertHelper.ConvertAsync(clip, new Encoding[] { Encoding.GetEncoding("BIG5"), Encoding.GetEncoding("GBK") }, 2); break; case "a3": clip = await ConvertHelper.ConvertAsync(clip, 1); break; case "a4": clip = await ConvertHelper.ConvertAsync(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 "zb4": //GBK>Unicode clip = Encoding.GetEncoding("GBK").GetString(Encoding.Default.GetBytes(clip)); break; case "zb5": clip = Encoding.GetEncoding("BIG5").GetString(Encoding.Default.GetBytes(clip)); break; case "zb6": clip = Encoding.GetEncoding("Shift-JIS").GetString(Encoding.Default.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; case "ze1": clip = Moudle.ConvertHelper.ConvertSymbol(clip, 0); break; case "ze2": clip = Moudle.ConvertHelper.ConvertSymbol(clip, 1); 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(); new Toast(string.Format("轉換完成\r\n耗時:{0} ms", sw.ElapsedMilliseconds)).Show(); } break; } } catch (FanhuajiException fe) { Window_MessageBoxEx.ShowDialog(fe.Message, "繁化姬API出現錯誤", "確定"); } }
private async void Button_Convert_ClickAsync(object sender, RoutedEventArgs e) { if ((string)((Button)e.Source).Content == "停止中...") { return; } else if ((string)((Button)e.Source).Content == "停止") { cts.Cancel(); ((Button)e.Source).Content = "停止中..."; return; } else if ((string)((Button)e.Source).Content == "轉換") { cts = new CancellationTokenSource(); ((Button)e.Source).Content = "停止"; } Stopwatch stopwatch = new Stopwatch(); StringBuilder AppendLog = new StringBuilder(); switch (FileMode) { case true: { FileList.ToList().ForEach(x => x.IsReplace = false); var temp = FileList.Where(x => x.IsChecked).ToList(); double count_total = temp.Count, count_current = 0.0; DismissButtonProgress = 0; bool replaceALL = false; bool skip = false; foreach (var _temp in temp) { string TargetPath = Path.Combine(Path.Combine(OutputPath, _temp.Path.Substring(_temp.ParentPath.Length + (_temp.Path.Length == _temp.ParentPath.Length ? 0 : 1))), _temp.Name); if (!replaceALL && File.Exists(TargetPath)) { if (!skip) { switch (Moudle.Window_MessageBoxEx.ShowDialog(string.Format("{0}發生檔名衝突,是否取代?", _temp.Name), "警告", "取代", "略過", "取消", "套用到全部")) { case Moudle.Window_MessageBoxEx.MessageBoxExResult.A: break; case Moudle.Window_MessageBoxEx.MessageBoxExResult.B: continue; case Moudle.Window_MessageBoxEx.MessageBoxExResult.C: case Moudle.Window_MessageBoxEx.MessageBoxExResult.CO: DismissButtonProgress = 100.0; ResetConvertButton((Button)e.Source); listview.SelectedIndex = -1; return; case Moudle.Window_MessageBoxEx.MessageBoxExResult.AO: replaceALL = true; break; case Moudle.Window_MessageBoxEx.MessageBoxExResult.BO: skip = true; continue; case Moudle.Window_MessageBoxEx.MessageBoxExResult.NONE: continue; } } else { continue; } } _temp.IsReplace = true; } temp = FileList.Where(x => x.IsChecked && x.IsReplace).ToList(); count_current = count_total - temp.Count; DismissButtonProgress = count_current / count_total * 100.0; Mouse.OverrideCursor = Cursors.Wait; stopwatch.Start(); foreach (var _temp in temp) { if (cts.IsCancellationRequested) { ResetConvertButton((Button)e.Source); return; } string TargetPath = Path.Combine(Path.Combine(OutputPath, _temp.Path.Substring(_temp.ParentPath.Length + (_temp.Path.Length == _temp.ParentPath.Length ? 0 : 1))), _temp.Name); string str = ""; using (StreamReader sr = new StreamReader(Path.Combine(_temp.Path, _temp.Name), encoding[0], false)) { str = sr.ReadToEnd(); sr.Close(); } try { str = await ConvertHelper.ConvertAsync(str, ToChinese); if (!string.IsNullOrWhiteSpace(App.Settings.FileConvert.FixLabel)) { var list = App.Settings.FileConvert.FixLabel.Split('|').Select(x => x.ToLower()).ToList(); list.ForEach(x => { if (Path.GetExtension(_temp.Name).ToLower() == x) { switch (x) { //"*.htm|*.html|*.shtm|*.shtml|*.asp|*.apsx|*.php|*.pl|*.cgi|*.js" case ".html": case ".htm": case ".php": case ".shtm": case ".shtml": case ".asp": case ".aspx": //html5 str = Regex.Replace(str, "<meta(\\s+.*?)charset=\"(.*?)\"(.*?)>", string.Format("<meta$1charset=\"{0}\"$3>", encoding[1].WebName), RegexOptions.IgnoreCase); //html4 str = Regex.Replace(str, "<meta\\s+(.*?)content=\"(.*?)charset=(.*?)\"(.*?)>", string.Format("<meta $1content=\"$2charset={0}\"$4>", encoding[1].WebName), RegexOptions.IgnoreCase); //php str = Regex.Replace(str, @"header(""Content-Type:text/html;\s*charset=(.*?)"");", string.Format(@"header(""Content-Type:text/html; charset={0}"");", encoding[1].WebName), RegexOptions.IgnoreCase); break; case "css": str = Regex.Replace(str, "@charset \"(.*?)\"", string.Format("@charset \"{0}\"", encoding[1].WebName), RegexOptions.IgnoreCase); break; } } }); } if (cts.IsCancellationRequested) { ResetConvertButton((Button)e.Source); return; } Directory.CreateDirectory(Path.GetDirectoryName(TargetPath)); using (StreamWriter sw = new StreamWriter(TargetPath, false, encoding[1] == Encoding.UTF8 ? new UTF8Encoding(App.Settings.FileConvert.UnicodeAddBom) : encoding[1])) { sw.Write(str); sw.Flush(); } } catch (Exception ex) { AppendLog.AppendLine($"[Error][{ex.Message}] \"{Path.Combine(_temp.Path, _temp.Name)}\""); } finally { count_current++; DismissButtonProgress = count_current / count_total * 100.0; } } DismissButtonProgress = 0.0; stopwatch.Stop(); Mouse.OverrideCursor = null; } break; case false: { stopwatch.Start(); try { ConvertFolderAndFileName(true); } catch (NullReferenceException ex) { AppendLog.AppendLine(ex.Message); } stopwatch.Stop(); } break; } if (AppendLog.Length != 0) { Window_MessageBoxEx.ShowDialog(AppendLog.ToString(), "轉換過程中出現錯誤", "我知道了"); } else if (App.Settings.Prompt) { new Toast(string.Format("轉換完成\r\n耗時:{0} ms", stopwatch.ElapsedMilliseconds)).Show(); } ResetConvertButton((Button)e.Source); }
private async void Button_Convert_Click(object sender, RoutedEventArgs e) { ((Button)e.Source).IsEnabled = false; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var temp = FileList.Where(x => x.IsChecked).ToList(); string ErrorMessage = null; foreach (var _temp in temp) { Mouse.OverrideCursor = Cursors.Wait; stopwatch.Start(); try { var tfile = TagLib.File.Create(Path.Combine(_temp.Path, _temp.Name)); tfile.RemoveTags((Enable_ID3v1 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v1) | (Enable_ID3v2 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v2)); TagLib.Id3v1.Tag t = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1, Enable_ID3v1 ? true : false); TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2, Enable_ID3v2 ? true : false); SetID3v2Encoding(Encoding_Output_ID3v2); if (t != null) { var TagList = GetAllStringProperties(t); var Dic = TagList.ToDictionary(x => x.TagName, x => StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0])); var resoult = ConvertEncoding ? await ConvertHelper.ConvertDictionary(Dic, encoding, ToChinese1) : await ConvertHelper.ConvertDictionary(Dic, ToChinese1); resoult.ToList().ForEach(x => t.SetPropertiesValue(x.Key, Encoding.GetEncoding("ISO-8859-1").GetString(encoding[1].GetBytes(x.Value)))); } if (t2 != null) { var TagList = GetAllStringProperties(t2); var Dic = TagList.ToDictionary(x => x.TagName, x => { if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2)) { return(StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0])); } else { var _ = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault(); return(_ != null ? _.Value_Preview : ""); } }); var resoult = await ConvertHelper.ConvertDictionary(Dic, ToChinese2); resoult.ToList().ForEach(x => t.SetPropertiesValue(x.Key, x.Value)); t2.Version = (Combobox_ID3v2_Version.Text == "2.3") ? (byte)3 : (byte)4; } tfile.Save(); } catch (TagLib.UnsupportedFormatException) { ErrorMessage = string.Format("轉換{0}時出現錯誤,該檔案並非音訊檔", _temp.Name); } catch (FanhuajiException val) { ErrorMessage = ((Exception)val).Message; break; } catch { ErrorMessage = string.Format("轉換{0}時出現未知錯誤", _temp.Name); } } Mouse.OverrideCursor = null; stopwatch.Stop(); if (!string.IsNullOrEmpty(ErrorMessage)) { Window_MessageBoxEx.ShowDialog(ErrorMessage, "轉換過程中出現錯誤", "我知道了"); } else if (App.Settings.Prompt) { new Toast(string.Format("轉換完成\r\n耗時:{0} ms", stopwatch.ElapsedMilliseconds)).Show(); } ((Button)e.Source).IsEnabled = true; Listview_SelectionChanged(null, null); }