From 8c9417366a46af5a2e93108703eb3cebb853ed60 Mon Sep 17 00:00:00 2001 From: Nikolaj Olsson Date: Sat, 19 Jan 2019 17:39:59 +0100 Subject: [PATCH] refactor - add braces --- libse/DvdSubtitleLanguage.cs | 4 +- .../Forms/FixCommonErrors/AddMissingQuotes.cs | 15 +- src/Controls/AudioVisualizer.cs | 228 +++++ src/Controls/SETextBox.cs | 20 + src/Controls/SubtitleListView.cs | 267 +++++ src/Controls/TimeUpDown.cs | 31 + src/Controls/VideoPlayerContainer.cs | 112 +- src/Forms/DCinema/DCinemaPropertiesInterop.cs | 32 + src/Forms/DCinema/DCinemaPropertiesSmpte.cs | 35 +- src/Forms/Main.cs | 1 + src/Forms/Networking/NetworkChat.Designer.cs | 2 +- src/Forms/Networking/NetworkChat.cs | 20 +- src/Forms/Networking/NetworkJoin.Designer.cs | 4 +- src/Forms/Networking/NetworkJoin.cs | 20 +- .../Networking/NetworkLogAndInfo.Designer.cs | 2 +- src/Forms/Networking/NetworkLogAndInfo.cs | 20 +- src/Forms/Networking/NetworkStart.Designer.cs | 2 +- src/Forms/Networking/NetworkStart.cs | 12 +- src/Forms/Ocr/AddBeterMultiMatch.cs | 25 +- src/Forms/Ocr/AddToOcrReplaceList.Designer.cs | 2 +- src/Forms/Ocr/AddToOcrReplaceList.cs | 10 +- src/Forms/Ocr/DownloadTesseract302.cs | 2 + src/Forms/Ocr/DownloadTesseract4.cs | 2 + src/Forms/Ocr/GetTesseract302Dictionaries.cs | 21 +- src/Forms/Ocr/GetTesseractDictionaries.cs | 9 + src/Forms/Ocr/OCRSpellCheck.cs | 23 +- src/Forms/Ocr/OcrPreprocessingSettings.cs | 13 +- src/Forms/Ocr/OcrPreprocessingT4.cs | 9 +- src/Forms/Ocr/VobSubCharactersImport.cs | 15 +- src/Forms/Ocr/VobSubEditCharacters.cs | 70 +- src/Forms/Ocr/VobSubNOcrCharacterInspect.cs | 30 +- src/Forms/Ocr/VobSubNOcrEdit.cs | 43 +- src/Forms/Ocr/VobSubNOcrTrain.cs | 17 + src/Forms/Ocr/VobSubOcr.cs | 960 +++++++++++++++++- src/Forms/Ocr/VobSubOcrCharacter.cs | 40 +- src/Forms/Ocr/VobSubOcrCharacterInspect.cs | 43 +- src/Forms/Ocr/VobSubOcrNOcrCharacter.cs | 59 +- src/Forms/Ocr/VobSubOcrNewFolder.cs | 6 +- src/Forms/Ocr/VobSubOcrSetItalicFactor.cs | 12 +- src/Forms/Styles/StylesForm.cs | 16 +- src/Forms/Styles/SubStationAlphaStyles.cs | 2 + .../SubStationAlphaStylesBatchConvert.cs | 167 ++- .../SubStationAlphaStylesExport.Designer.cs | 2 +- .../Styles/SubStationAlphaStylesExport.cs | 24 +- src/Forms/Styles/TimedTextStyles.cs | 21 +- 45 files changed, 2295 insertions(+), 175 deletions(-) diff --git a/libse/DvdSubtitleLanguage.cs b/libse/DvdSubtitleLanguage.cs index 1e59922d6..2e05ca7c0 100644 --- a/libse/DvdSubtitleLanguage.cs +++ b/libse/DvdSubtitleLanguage.cs @@ -116,8 +116,8 @@ namespace Nikse.SubtitleEdit.Core public static DvdSubtitleLanguage GetLanguageOrNull(string code) { - code = ConvertIsoToDvd(code.ToLowerInvariant()); - return CompliantLanguagesByCode.GetValueOrNull(code); + var dvdCode = ConvertIsoToDvd(code.ToLowerInvariant()); + return CompliantLanguagesByCode.GetValueOrNull(dvdCode); } private static string GetNonCompliantLocalLanguageName(string code) diff --git a/libse/Forms/FixCommonErrors/AddMissingQuotes.cs b/libse/Forms/FixCommonErrors/AddMissingQuotes.cs index 340775b2a..293ebafd6 100644 --- a/libse/Forms/FixCommonErrors/AddMissingQuotes.cs +++ b/libse/Forms/FixCommonErrors/AddMissingQuotes.cs @@ -37,15 +37,14 @@ namespace Nikse.SubtitleEdit.Core.Forms.FixCommonErrors if (prev != null) { double betweenMilliseconds = p.StartTime.TotalMilliseconds - prev.EndTime.TotalMilliseconds; - if (betweenMilliseconds > 1500) + if (betweenMilliseconds > 1500 || // cannot be quote spanning several lines of more than 1.5 seconds between lines! + + // seems to have valid quotes, so no spanning + prev.Text.Replace("", string.Empty).TrimStart().TrimStart('-').TrimStart().StartsWith('"') && + prev.Text.Replace("", string.Empty).TrimEnd().EndsWith('"') && + Utilities.CountTagInText(prev.Text, '"') == 2) { - prev = null; // cannot be quote spanning several lines of more than 1.5 seconds between lines! - } - else if (prev.Text.Replace("", string.Empty).TrimStart().TrimStart('-').TrimStart().StartsWith('"') && - prev.Text.Replace("", string.Empty).TrimEnd().EndsWith('"') && - Utilities.CountTagInText(prev.Text, '"') == 2) - { - prev = null; // seems to have valid quotes, so no spanning + prev = null; } } diff --git a/src/Controls/AudioVisualizer.cs b/src/Controls/AudioVisualizer.cs index db8af580f..e4f5ce5db 100644 --- a/src/Controls/AudioVisualizer.cs +++ b/src/Controls/AudioVisualizer.cs @@ -122,9 +122,15 @@ namespace Nikse.SubtitleEdit.Controls set { if (value < ZoomMinimum) + { value = ZoomMinimum; + } + if (value > ZoomMaximum) + { value = ZoomMaximum; + } + value = Math.Round(value, 2); // round to prevent accumulated rounding errors if (Math.Abs(_zoomFactor - value) > 0.01) { @@ -147,9 +153,15 @@ namespace Nikse.SubtitleEdit.Controls set { if (value < VerticalZoomMinimum) + { value = VerticalZoomMinimum; + } + if (value > VerticalZoomMaximum) + { value = VerticalZoomMaximum; + } + value = Math.Round(value, 2); // round to prevent accumulated rounding errors if (Math.Abs(_verticalZoomFactor - value) > 0.01) { @@ -237,10 +249,15 @@ namespace Nikse.SubtitleEdit.Controls { double endPositionSeconds = value + ((double)Width / _wavePeaks.SampleRate) / _zoomFactor; if (endPositionSeconds > _wavePeaks.LengthInSeconds) + { value -= endPositionSeconds - _wavePeaks.LengthInSeconds; + } } if (value < 0) + { value = 0; + } + if (Math.Abs(_startPositionSeconds - value) > 0.01) { _startPositionSeconds = value; @@ -352,7 +369,9 @@ namespace Nikse.SubtitleEdit.Controls _allSelectedParagraphs.Clear(); if (_wavePeaks == null) + { return; + } const double additionalSeconds = 15.0; // Helps when scrolling double startThresholdMilliseconds = (_startPositionSeconds - additionalSeconds) * TimeCode.BaseUnit; @@ -363,27 +382,39 @@ namespace Nikse.SubtitleEdit.Controls Paragraph p = subtitle.Paragraphs[i]; if (p.StartTime.IsMaxTime) + { continue; + } _subtitle.Paragraphs.Add(p); if (p.EndTime.TotalMilliseconds >= startThresholdMilliseconds && p.StartTime.TotalMilliseconds <= endThresholdMilliseconds) + { _displayableParagraphs.Add(p); + } } Action addSelection = (index, isPrimary) => { Paragraph p = subtitle.GetParagraphOrDefault(index); if (p == null || p.StartTime.IsMaxTime) + { return; + } + if (isPrimary) + { _selectedParagraph = p; + } + _allSelectedParagraphs.Add(p); }; addSelection(primarySelectedIndex, true); foreach (int selectedIndex in selectedIndexes) + { addSelection(selectedIndex, false); + } } public void SetPosition(double startPositionSeconds, Subtitle subtitle, double currentVideoPositionSeconds, int subtitleIndex, ListView.SelectedIndexCollection selectedIndexes) @@ -419,7 +450,9 @@ namespace Nikse.SubtitleEdit.Controls public bool IsSelected(int position) { if (position < _lastPosition || position > _nextSelection.End) + { FindNextSelection(position); + } _lastPosition = position; @@ -433,7 +466,9 @@ namespace Nikse.SubtitleEdit.Controls { SelectionRange range = _ranges[index]; if (range.End >= position && (range.Start < _nextSelection.Start || (range.Start == _nextSelection.Start && range.End > _nextSelection.End))) + { _nextSelection = range; + } } } @@ -490,9 +525,15 @@ namespace Nikse.SubtitleEdit.Controls { var offset = (value / baseHeight) * halfWaveformHeight; if (offset > halfWaveformHeight) + { offset = halfWaveformHeight; + } + if (offset < -halfWaveformHeight) + { offset = -halfWaveformHeight; + } + return (float)(halfWaveformHeight - offset); }; var div = _wavePeaks.SampleRate * _zoomFactor; @@ -503,7 +544,10 @@ namespace Nikse.SubtitleEdit.Controls int pos1 = pos0; pos1++; if (pos1 >= _wavePeaks.Peaks.Count) + { break; + } + var pos1Weight = pos - pos0; var pos0Weight = 1F - pos1Weight; var peak0 = _wavePeaks.Peaks[pos0]; @@ -543,14 +587,21 @@ namespace Nikse.SubtitleEdit.Controls { // scene change and current pos are the same - draw 2 pixels + current pos dotted currentPosDone = true; using (var p = new Pen(Color.AntiqueWhite, 2)) + { graphics.DrawLine(p, pos, 0, pos, Height); + } + using (var p = new Pen(Color.Turquoise, 2) { DashStyle = DashStyle.Dash }) + { graphics.DrawLine(p, currentPositionPos, 0, currentPositionPos, Height); + } } else { using (var p = new Pen(Color.AntiqueWhite)) + { graphics.DrawLine(p, pos, 0, pos, Height); + } } } } @@ -565,7 +616,9 @@ namespace Nikse.SubtitleEdit.Controls if (_currentVideoPositionSeconds > 0 && !currentPosDone && currentPositionPos > 0 && currentPositionPos < Width) { using (var p = new Pen(Color.Turquoise)) + { graphics.DrawLine(p, currentPositionPos, 0, currentPositionPos, Height); + } } // paragraphs @@ -588,7 +641,9 @@ namespace Nikse.SubtitleEdit.Controls if (currentRegionRight >= 0 && currentRegionLeft <= Width) { using (var brush = new SolidBrush(Color.FromArgb(128, 255, 255, 255))) + { graphics.FillRectangle(brush, currentRegionLeft, 0, currentRegionWidth, graphics.VisibleClipBounds.Height); + } if (currentRegionWidth > 40) { @@ -619,14 +674,18 @@ namespace Nikse.SubtitleEdit.Controls else { using (var stringFormat = new StringFormat(StringFormatFlags.DirectionVertical)) + { graphics.DrawString(WaveformNotLoadedText, textFont, textBrush, new PointF(1, 10), stringFormat); + } } } } if (Focused) { using (var p = new Pen(SelectedColor)) + { graphics.DrawRectangle(p, new Rectangle(0, 0, Width - 1, Height - 1)); + } } //_sw.Stop(); //_ticks.Add(_sw.ElapsedMilliseconds); @@ -688,7 +747,9 @@ namespace Nikse.SubtitleEdit.Controls position = SecondsToXPosition(seconds); if (n > 64) + { graphics.DrawLine(pen, position, imageHeight, position, imageHeight - 5); + } seconds += 0.5; position = SecondsToXPosition(seconds); @@ -700,9 +761,15 @@ namespace Nikse.SubtitleEdit.Controls { TimeSpan ts = TimeSpan.FromSeconds(seconds + Configuration.Settings.General.CurrentVideoOffsetInMs / TimeCode.BaseUnit); if (ts.Minutes == 0 && ts.Hours == 0) + { return ts.Seconds.ToString(CultureInfo.InvariantCulture); + } + if (ts.Hours == 0) + { return $"{ts.Minutes:00}:{ts.Seconds:00}"; + } + return $"{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}"; } @@ -714,15 +781,21 @@ namespace Nikse.SubtitleEdit.Controls // background using (var brush = new SolidBrush(Color.FromArgb(42, 255, 255, 255))) + { graphics.FillRectangle(brush, currentRegionLeft, 0, currentRegionWidth, graphics.VisibleClipBounds.Height); + } // left edge using (var pen = new Pen(new SolidBrush(Color.FromArgb(175, 0, 100, 0))) { DashStyle = DashStyle.Solid, Width = 2 }) + { graphics.DrawLine(pen, currentRegionLeft, 0, currentRegionLeft, graphics.VisibleClipBounds.Height); + } // right edge using (var pen = new Pen(new SolidBrush(Color.FromArgb(175, 110, 10, 10))) { DashStyle = DashStyle.Dash, Width = 2 }) + { graphics.DrawLine(pen, currentRegionRight - 1, 0, currentRegionRight - 1, graphics.VisibleClipBounds.Height); + } using (var font = new Font(Configuration.Settings.General.SubtitleFontName, TextSize, TextBold ? FontStyle.Bold : FontStyle.Regular)) using (var textBrush = new SolidBrush(TextColor)) @@ -751,7 +824,10 @@ namespace Nikse.SubtitleEdit.Controls { var textSize = graphics.MeasureString(paragraph.Bookmark, font); if (textSize.Width < 1) + { textSize = new SizeF(-2, 18); // empty bookmark text + } + graphics.FillRectangle(bookmarkBackBrush, x, y, textSize.Width + 20, textSize.Height + 10); } @@ -774,7 +850,10 @@ namespace Nikse.SubtitleEdit.Controls { string text = HtmlUtil.RemoveHtmlTags(paragraph.Text, true); if (Configuration.Settings.VideoControls.WaveformUnwrapText) + { text = text.Replace(Environment.NewLine, " "); + } + DrawParagraphText(graphics, text, font, currentRegionWidth, padding, drawStringOutlined, currentRegionLeft); } @@ -791,16 +870,26 @@ namespace Nikse.SubtitleEdit.Controls if (Configuration.Settings.VideoControls.WaveformHideWpmCpsLabels) { if (Configuration.Settings.VideoControls.WaveformDrawWpm) + { text = $"{paragraph.WordsPerMinute:0.00}" + Environment.NewLine + text; + } + if (Configuration.Settings.VideoControls.WaveformDrawCps) + { text = $"{Utilities.GetCharactersPerSecond(paragraph):0.00}" + Environment.NewLine + text; + } } else { if (Configuration.Settings.VideoControls.WaveformDrawWpm) + { text = string.Format(Configuration.Settings.Language.Waveform.WordsMinX, paragraph.WordsPerMinute) + Environment.NewLine + text; + } + if (Configuration.Settings.VideoControls.WaveformDrawCps) + { text = string.Format(Configuration.Settings.Language.Waveform.CharsSecX, Utilities.GetCharactersPerSecond(paragraph)) + Environment.NewLine + text; + } } } drawStringOutlined(text, currentRegionLeft + padding, Height - 14 - (int)graphics.MeasureString(text, font).Height); @@ -811,9 +900,15 @@ namespace Nikse.SubtitleEdit.Controls private void DrawParagraphText(Graphics graphics, string text, Font font, int currentRegionWidth, int padding, Action drawStringOutlined, int currentRegionLeft) { if (Configuration.Settings.General.RightToLeftMode && LanguageAutoDetect.CouldBeRightToLeftLanguge(new Subtitle(_displayableParagraphs))) + { text = Utilities.ReverseStartAndEndingForRightToLeft(text); + } + if (text.Length > 500) + { text = text.Substring(0, 500); // don't now allow very long texts as they can make SE unresponsive - see https://github.com/SubtitleEdit/subtitleedit/issues/2536 + } + int y = padding; var max = currentRegionWidth - padding - 1; foreach (var line in text.SplitToLines()) @@ -825,11 +920,18 @@ namespace Nikse.SubtitleEdit.Controls { text = text.Remove(text.Length - removeLength).TrimEnd() + "…"; if (text.Length > 200) + { removeLength = 21; + } else if (text.Length > 100) + { removeLength = 11; + } else + { removeLength = 2; + } + measureResult = graphics.MeasureString(text, font); } drawStringOutlined(text, currentRegionLeft + padding, y); @@ -861,7 +963,9 @@ namespace Nikse.SubtitleEdit.Controls private void WaveformMouseDown(object sender, MouseEventArgs e) { if (_wavePeaks == null) + { return; + } Paragraph oldMouseDownParagraph = null; _mouseDownParagraphType = MouseDownParagraphType.None; @@ -878,11 +982,17 @@ namespace Nikse.SubtitleEdit.Controls if (SetParagrapBorderHit(milliseconds, NewSelectionParagraph)) { if (_mouseDownParagraph != null) + { oldMouseDownParagraph = new Paragraph(_mouseDownParagraph); + } + if (_mouseDownParagraphType == MouseDownParagraphType.Start) { if (_mouseDownParagraph != null) + { _mouseDownParagraph.StartTime.TotalMilliseconds = milliseconds; + } + NewSelectionParagraph.StartTime.TotalMilliseconds = milliseconds; _mouseMoveStartX = e.X; _mouseMoveEndX = SecondsToXPosition(NewSelectionParagraph.EndTime.TotalSeconds - _startPositionSeconds); @@ -890,7 +1000,10 @@ namespace Nikse.SubtitleEdit.Controls else { if (_mouseDownParagraph != null) + { _mouseDownParagraph.EndTime.TotalMilliseconds = milliseconds; + } + NewSelectionParagraph.EndTime.TotalMilliseconds = milliseconds; _mouseMoveStartX = SecondsToXPosition(NewSelectionParagraph.StartTime.TotalSeconds - _startPositionSeconds); _mouseMoveEndX = e.X; @@ -911,7 +1024,9 @@ namespace Nikse.SubtitleEdit.Controls { var prev = _subtitle.Paragraphs[curIdx - 1]; if (prev.EndTime.TotalMilliseconds + Configuration.Settings.General.MinimumMillisecondsBetweenLines < milliseconds) + { _mouseDownParagraph.StartTime.TotalMilliseconds = milliseconds; + } } else { @@ -924,7 +1039,9 @@ namespace Nikse.SubtitleEdit.Controls { var next = _subtitle.Paragraphs[curIdx + 1]; if (milliseconds + Configuration.Settings.General.MinimumMillisecondsBetweenLines < next.StartTime.TotalMilliseconds) + { _mouseDownParagraph.EndTime.TotalMilliseconds = milliseconds; + } } else { @@ -952,7 +1069,10 @@ namespace Nikse.SubtitleEdit.Controls Cursor = Cursors.Default; } if (p == null) + { SetMinMaxViaSeconds(seconds); + } + NewSelectionParagraph = null; _mouseMoveStartX = e.X; _mouseMoveEndX = e.X; @@ -963,7 +1083,9 @@ namespace Nikse.SubtitleEdit.Controls { int curIdx = _subtitle.Paragraphs.IndexOf(_mouseDownParagraph); if (curIdx > 0 && oldMouseDownParagraph != null) + { _gapAtStart = oldMouseDownParagraph.StartTime.TotalMilliseconds - _subtitle.Paragraphs[curIdx - 1].EndTime.TotalMilliseconds; + } } } else if (_mouseDownParagraphType == MouseDownParagraphType.End) @@ -972,7 +1094,9 @@ namespace Nikse.SubtitleEdit.Controls { int curIdx = _subtitle.Paragraphs.IndexOf(_mouseDownParagraph); if (curIdx >= 0 && curIdx < _subtitle.Paragraphs.Count - 1 && oldMouseDownParagraph != null) + { _gapAtStart = _subtitle.Paragraphs[curIdx + 1].StartTime.TotalMilliseconds - oldMouseDownParagraph.EndTime.TotalMilliseconds; + } } } _mouseDown = true; @@ -997,9 +1121,14 @@ namespace Nikse.SubtitleEdit.Controls if (PreventOverlap) { if (paragraph.StartTime.TotalMilliseconds <= _wholeParagraphMinMilliseconds) + { paragraph.StartTime.TotalMilliseconds = _wholeParagraphMinMilliseconds + 1; + } + if (paragraph.EndTime.TotalMilliseconds >= _wholeParagraphMaxMilliseconds) + { paragraph.EndTime.TotalMilliseconds = _wholeParagraphMaxMilliseconds - 1; + } } OnNewSelectionRightClicked.Invoke(this, new ParagraphEventArgs(paragraph)); NewSelectionParagraph = paragraph; @@ -1053,9 +1182,14 @@ namespace Nikse.SubtitleEdit.Controls } } if (prev != null) + { _wholeParagraphMinMilliseconds = prev.EndTime.TotalMilliseconds + Configuration.Settings.General.MinimumMillisecondsBetweenLines; + } + if (next != null) + { _wholeParagraphMaxMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines; + } } } @@ -1119,7 +1253,9 @@ namespace Nikse.SubtitleEdit.Controls { bool hit = SetParagrapBorderHit(milliseconds, p); if (hit) + { return true; + } } return false; } @@ -1128,7 +1264,9 @@ namespace Nikse.SubtitleEdit.Controls { Paragraph p = null; if (IsParagrapHit(milliseconds, _selectedParagraph)) + { p = _selectedParagraph; + } if (p == null) { @@ -1148,7 +1286,9 @@ namespace Nikse.SubtitleEdit.Controls private bool SetParagrapBorderHit(int milliseconds, Paragraph paragraph) { if (paragraph == null) + { return false; + } if (IsParagrapBorderStartHit(milliseconds, paragraph.StartTime.TotalMilliseconds)) { @@ -1172,7 +1312,10 @@ namespace Nikse.SubtitleEdit.Controls get { if (ModifierKeys == Keys.Shift) + { return AllowOverlap; + } + return !AllowOverlap; } } @@ -1182,7 +1325,9 @@ namespace Nikse.SubtitleEdit.Controls private void WaveformMouseMove(object sender, MouseEventArgs e) { if (_wavePeaks == null) + { return; + } int oldMouseMoveLastX = _mouseMoveLastX; if (e.X < 0 && _startPositionSeconds > 0.1 && _mouseDown) @@ -1217,7 +1362,9 @@ namespace Nikse.SubtitleEdit.Controls _mouseMoveLastX = e.X; if (e.X < 0 || e.X > Width) + { return; + } if (e.Button == MouseButtons.None) { @@ -1225,7 +1372,9 @@ namespace Nikse.SubtitleEdit.Controls var milliseconds = (int)(seconds * TimeCode.BaseUnit); if (IsParagrapBorderHit(milliseconds, NewSelectionParagraph)) + { Cursor = Cursors.VSplit; + } else if (IsParagrapBorderHit(milliseconds, _selectedParagraph) || IsParagrapBorderHit(milliseconds, _displayableParagraphs)) { @@ -1239,7 +1388,9 @@ namespace Nikse.SubtitleEdit.Controls else if (e.Button == MouseButtons.Left) { if (oldMouseMoveLastX == e.X) + { return; // no horizontal movement + } if (_mouseDown) { @@ -1254,9 +1405,14 @@ namespace Nikse.SubtitleEdit.Controls if (_firstMove && Math.Abs(oldMouseMoveLastX - e.X) < Configuration.Settings.General.MinimumMillisecondsBetweenLines && GetParagraphAtMilliseconds(milliseconds) == null) { if (_mouseDownParagraphType == MouseDownParagraphType.Start && _prevParagraph != null && Math.Abs(_mouseDownParagraph.StartTime.TotalMilliseconds - _prevParagraph.EndTime.TotalMilliseconds) <= ClosenessForBorderSelection + 15) + { return; // do not decide which paragraph to move yet + } + if (_mouseDownParagraphType == MouseDownParagraphType.End && _nextParagraph != null && Math.Abs(_mouseDownParagraph.EndTime.TotalMilliseconds - _nextParagraph.StartTime.TotalMilliseconds) <= ClosenessForBorderSelection + 15) + { return; // do not decide which paragraph to move yet + } } if (ModifierKeys != Keys.Alt) @@ -1286,9 +1442,14 @@ namespace Nikse.SubtitleEdit.Controls if (_mouseDownParagraph.EndTime.TotalMilliseconds - milliseconds > MinimumSelectionMilliseconds) { if (AllowMovePrevOrNext) + { SetMinAndMaxMoveStart(); + } else + { SetMinAndMax(); + } + _mouseDownParagraph.StartTime.TotalMilliseconds = milliseconds; if (PreventOverlap && _mouseDownParagraph.StartTime.TotalMilliseconds <= _wholeParagraphMinMilliseconds) { @@ -1317,9 +1478,14 @@ namespace Nikse.SubtitleEdit.Controls if (milliseconds - _mouseDownParagraph.StartTime.TotalMilliseconds > MinimumSelectionMilliseconds) { if (AllowMovePrevOrNext) + { SetMinAndMaxMoveEnd(); + } else + { SetMinAndMax(); + } + _mouseDownParagraph.EndTime.TotalMilliseconds = milliseconds; if (PreventOverlap && _mouseDownParagraph.EndTime.TotalMilliseconds >= _wholeParagraphMaxMilliseconds) { @@ -1386,7 +1552,9 @@ namespace Nikse.SubtitleEdit.Controls if (NewSelectionParagraph == null && Math.Abs(_mouseMoveEndX - _mouseMoveStartX) > 2) { if (AllowNewSelection) + { NewSelectionParagraph = new Paragraph(); + } } if (NewSelectionParagraph != null) @@ -1424,7 +1592,9 @@ namespace Nikse.SubtitleEdit.Controls { bool hit = IsParagrapBorderHit(milliseconds, p); if (hit) + { return true; + } } return false; } @@ -1432,7 +1602,9 @@ namespace Nikse.SubtitleEdit.Controls private bool IsParagrapBorderHit(int milliseconds, Paragraph paragraph) { if (paragraph == null) + { return false; + } return IsParagrapBorderStartHit(milliseconds, paragraph.StartTime.TotalMilliseconds) || IsParagrapBorderEndHit(milliseconds, paragraph.EndTime.TotalMilliseconds); @@ -1478,7 +1650,9 @@ namespace Nikse.SubtitleEdit.Controls private void WaveformMouseEnter(object sender, EventArgs e) { if (_wavePeaks == null) + { return; + } if (_noClear) { @@ -1504,7 +1678,9 @@ namespace Nikse.SubtitleEdit.Controls private void WaveformMouseDoubleClick(object sender, MouseEventArgs e) { if (_wavePeaks == null) + { return; + } _mouseDown = false; _mouseDownParagraph = null; @@ -1530,7 +1706,9 @@ namespace Nikse.SubtitleEdit.Controls { double newStartPos = _startPositionSeconds + (endSeconds - EndPositionSeconds); // move later, so whole selected paragraph is visible if (newStartPos < seconds) // but only if visibile screen is wide enough + { _startPositionSeconds = newStartPos; + } } } @@ -1541,7 +1719,9 @@ namespace Nikse.SubtitleEdit.Controls private static bool IsParagrapHit(int milliseconds, Paragraph paragraph) { if (paragraph == null) + { return false; + } return milliseconds >= paragraph.StartTime.TotalMilliseconds && milliseconds <= paragraph.EndTime.TotalMilliseconds; } @@ -1613,7 +1793,9 @@ namespace Nikse.SubtitleEdit.Controls } if (_mouseDownParagraphType == MouseDownParagraphType.None || _mouseDownParagraphType == MouseDownParagraphType.Whole) + { OnSingleClick.Invoke(this, new ParagraphEventArgs(RelativeXPositionToSeconds(e.X), null)); + } } } } @@ -1621,7 +1803,9 @@ namespace Nikse.SubtitleEdit.Controls private void WaveformKeyDown(object sender, KeyEventArgs e) { if (_wavePeaks == null) + { return; + } if (e.Modifiers == Keys.None && e.KeyCode == Keys.Add) { @@ -1690,9 +1874,14 @@ namespace Nikse.SubtitleEdit.Controls for (int i = begin; i < _wavePeaks.Peaks.Count; i++) { if (i > 0 && i < _wavePeaks.Peaks.Count && _wavePeaks.Peaks[i].Abs <= threshold) + { hitCount++; + } else + { hitCount = 0; + } + if (hitCount > length) { double seconds = SampleIndexToSeconds(i - (length / 2)); @@ -1700,7 +1889,10 @@ namespace Nikse.SubtitleEdit.Controls { StartPositionSeconds = seconds; if (_startPositionSeconds > 1) + { StartPositionSeconds -= 1; + } + OnSingleClick?.Invoke(this, new ParagraphEventArgs(seconds, null)); Invalidate(); } @@ -1720,9 +1912,14 @@ namespace Nikse.SubtitleEdit.Controls for (int i = begin; i > 0; i--) { if (i > 0 && i < _wavePeaks.Peaks.Count && _wavePeaks.Peaks[i].Abs <= threshold) + { hitCount++; + } else + { hitCount = 0; + } + if (hitCount > length) { double seconds = SampleIndexToSeconds(i + (length / 2)); @@ -1730,9 +1927,14 @@ namespace Nikse.SubtitleEdit.Controls { StartPositionSeconds = seconds; if (_startPositionSeconds > 1) + { StartPositionSeconds -= 1; + } else + { StartPositionSeconds = 0; + } + OnSingleClick?.Invoke(this, new ParagraphEventArgs(seconds, null)); Invalidate(); } @@ -1770,14 +1972,20 @@ namespace Nikse.SubtitleEdit.Controls // just like dragging the slider, which does work without the waveform), but the // code below doesn't support it, so bail out until someone feels like fixing it. if (_wavePeaks == null) + { return; + } if (ModifierKeys == Keys.Control) { if (e.Delta > 0) + { ZoomIn(); + } else + { ZoomOut(); + } return; } @@ -1785,16 +1993,23 @@ namespace Nikse.SubtitleEdit.Controls if (ModifierKeys == (Keys.Control | Keys.Shift)) { if (e.Delta > 0) + { VerticalZoomIn(); + } else + { VerticalZoomOut(); + } return; } int delta = e.Delta; if (!MouseWheelScrollUpIsForward) + { delta = delta * -1; + } + if (Locked) { OnPositionSelected?.Invoke(this, new ParagraphEventArgs(_currentVideoPositionSeconds + (delta / 256.0), null)); @@ -1823,7 +2038,9 @@ namespace Nikse.SubtitleEdit.Controls } if (spectrogram == null) + { return; + } if (spectrogram.IsLoaded) { @@ -1845,7 +2062,9 @@ namespace Nikse.SubtitleEdit.Controls private void InitializeSpectrogramInternal(SpectrogramData spectrogram) { if (_spectrogram != null) + { return; + } _spectrogram = spectrogram; Invalidate(); @@ -1877,7 +2096,10 @@ namespace Nikse.SubtitleEdit.Controls { int length = SecondsToSampleIndex(milliseconds / TimeCode.BaseUnit); if (length < 9) + { length = 9; + } + double v = 0; int count = 0; for (int i = sampleIndex; i < sampleIndex + length; i++) @@ -1889,7 +2111,10 @@ namespace Nikse.SubtitleEdit.Controls } } if (count == 0) + { return 0; + } + return v / count; } @@ -1899,7 +2124,10 @@ namespace Nikse.SubtitleEdit.Controls double average = 0; for (int k = begin; k < _wavePeaks.Peaks.Count; k++) + { average += _wavePeaks.Peaks[k].Abs; + } + average /= _wavePeaks.Peaks.Count - begin; var maxThreshold = (int)(_wavePeaks.HighestPeak * (maximumVolumePercent / 100.0)); diff --git a/src/Controls/SETextBox.cs b/src/Controls/SETextBox.cs index 6b741a9cf..a22678798 100644 --- a/src/Controls/SETextBox.cs +++ b/src/Controls/SETextBox.cs @@ -97,9 +97,13 @@ namespace Nikse.SubtitleEdit.Controls string newText; if (e.Data.GetDataPresent(DataFormats.UnicodeText)) + { newText = (string)e.Data.GetData(DataFormats.UnicodeText); + } else + { newText = (string)e.Data.GetData(DataFormats.Text); + } if (string.IsNullOrWhiteSpace(Text)) { @@ -117,13 +121,18 @@ namespace Nikse.SubtitleEdit.Controls { SelectionLength = 0; if (justAppend) + { index++; + } + SelectionStart = index; return; // too fast - nobody can drag'n'drop this fast } if (index >= _dragStartFrom && index <= _dragStartFrom + _dragText.Length) + { return; // don't drop same text at same position + } if (_dragRemoveOld) { @@ -140,20 +149,29 @@ namespace Nikse.SubtitleEdit.Controls { Text = Text.Remove(_dragStartFrom, 1); if (_dragStartFrom < index) + { index--; + } } else if (_dragStartFrom > 0 && Text.Length > _dragStartFrom + 1 && Text[_dragStartFrom] == ' ' && expectedChars.Contains(Text[_dragStartFrom + 1])) { Text = Text.Remove(_dragStartFrom, 1); if (_dragStartFrom < index) + { index--; + } } // fix index if (index > _dragStartFrom) + { index -= _dragText.Length; + } + if (index < 0) + { index = 0; + } } } if (justAppend) @@ -184,7 +202,9 @@ namespace Nikse.SubtitleEdit.Controls { bool lastWord = expectedChars.Contains(Text[endIndex]); if (!lastWord) + { Text = Text.Insert(endIndex, " "); + } } else if (endIndex < Text.Length && newText.EndsWith(' ') && Text[endIndex] == ' ') { diff --git a/src/Controls/SubtitleListView.cs b/src/Controls/SubtitleListView.cs index 83c1f4952..453f63da2 100644 --- a/src/Controls/SubtitleListView.cs +++ b/src/Controls/SubtitleListView.cs @@ -64,9 +64,15 @@ namespace Nikse.SubtitleEdit.Controls { var hzAlignment = value ? HorizontalAlignment.Left : HorizontalAlignment.Right; if (ColumnIndexCps >= 0) + { Columns[ColumnIndexCps].TextAlign = hzAlignment; + } + if (ColumnIndexWpm >= 0) + { Columns[ColumnIndexWpm].TextAlign = hzAlignment; + } + base.RightToLeftLayout = value; } } @@ -115,52 +121,80 @@ namespace Nikse.SubtitleEdit.Controls { int idx = GetColumnIndex(SubtitleColumn.Number); if (idx >= 0) + { Columns[idx].Text = general.NumberSymbol; + } idx = GetColumnIndex(SubtitleColumn.Start); if (idx >= 0) + { Columns[idx].Text = general.StartTime; + } idx = GetColumnIndex(SubtitleColumn.End); if (idx >= 0) + { Columns[idx].Text = general.EndTime; + } idx = GetColumnIndex(SubtitleColumn.Duration); if (idx >= 0) + { Columns[idx].Text = general.Duration; + } idx = GetColumnIndex(SubtitleColumn.CharactersPerSeconds); if (idx >= 0) + { Columns[idx].Text = general.CharsPerSec; + } idx = GetColumnIndex(SubtitleColumn.WordsPerMinute); if (idx >= 0) + { Columns[idx].Text = general.WordsPerMin; + } idx = GetColumnIndex(SubtitleColumn.Gap); if (idx >= 0) + { Columns[idx].Text = general.Gap; + } idx = GetColumnIndex(SubtitleColumn.Actor); if (idx >= 0) + { Columns[idx].Text = general.Actor; + } idx = GetColumnIndex(SubtitleColumn.Region); if (idx >= 0) + { Columns[idx].Text = general.Region; + } idx = GetColumnIndex(SubtitleColumn.Text); if (idx >= 0) + { Columns[idx].Text = general.Text; + } if (settings.General.ListViewLineSeparatorString != null) + { _lineSeparatorString = settings.General.ListViewLineSeparatorString; + } if (!string.IsNullOrEmpty(settings.General.SubtitleFontName)) + { _subtitleFontName = settings.General.SubtitleFontName; + } + SubtitleFontBold = settings.General.SubtitleListViewFontBold; if (settings.General.SubtitleListViewFontSize > 6 && settings.General.SubtitleListViewFontSize < 72) + { SubtitleFontSize = settings.General.SubtitleListViewFontSize; + } + ForeColor = settings.General.SubtitleFontColor; BackColor = settings.General.SubtitleBackgroundColor; _settings = settings; @@ -173,43 +207,63 @@ namespace Nikse.SubtitleEdit.Controls { int idx = GetColumnIndex(SubtitleColumn.Number); if (idx >= 0) + { Columns[idx].Width = Configuration.Settings.General.ListViewNumberWidth; + } idx = GetColumnIndex(SubtitleColumn.Start); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewStartWidth; + } idx = GetColumnIndex(SubtitleColumn.End); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewEndWidth; + } idx = GetColumnIndex(SubtitleColumn.Duration); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewDurationWidth; + } idx = GetColumnIndex(SubtitleColumn.CharactersPerSeconds); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewCpsWidth; + } idx = GetColumnIndex(SubtitleColumn.WordsPerMinute); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewWpmWidth; + } idx = GetColumnIndex(SubtitleColumn.Gap); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewGapWidth; + } idx = GetColumnIndex(SubtitleColumn.Actor); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewActorWidth; + } idx = GetColumnIndex(SubtitleColumn.Region); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewRegionWidth; + } idx = GetColumnIndex(SubtitleColumn.Text); if (idx >= 0) + { Columns[idx].Width = _settings.General.ListViewTextWidth; + } _saveColumnWidthChanges = true; } @@ -222,15 +276,21 @@ namespace Nikse.SubtitleEdit.Controls var idx = GetColumnIndex(SubtitleColumn.Start); if (idx >= 0) + { Columns[idx].Width = timestampWidth; + } idx = GetColumnIndex(SubtitleColumn.End); if (idx >= 0) + { Columns[idx].Width = timestampWidth; + } idx = GetColumnIndex(SubtitleColumn.Duration); if (idx >= 0) + { Columns[idx].Width = (int)(timestampWidth * 0.8); + } } } @@ -293,19 +353,29 @@ namespace Nikse.SubtitleEdit.Controls } if (Configuration.Settings != null && !Configuration.Settings.Tools.ListViewShowColumnEndTime) + { HideColumn(SubtitleColumn.End); + } if (Configuration.Settings != null && !Configuration.Settings.Tools.ListViewShowColumnDuration) + { HideColumn(SubtitleColumn.Duration); + } if (Configuration.Settings != null && Configuration.Settings.Tools.ListViewShowColumnCharsPerSec) + { ShowCharsSecColumn(Configuration.Settings.Language.General.CharsPerSec); + } if (Configuration.Settings != null && Configuration.Settings.Tools.ListViewShowColumnWordsPerMin) + { ShowWordsMinColumn(Configuration.Settings.Language.General.WordsPerMin); + } if (Configuration.Settings != null && Configuration.Settings.Tools.ListViewShowColumnGap) + { ShowGapColumn(Configuration.Settings.Language.General.Gap); + } SubtitleListViewLastColumnFill(this, null); @@ -420,7 +490,9 @@ namespace Nikse.SubtitleEdit.Controls if (!Focused && (e.State & ListViewItemStates.Selected) != 0) { if (e.Item.Focused) + { e.DrawFocusRectangle(); + } } else { @@ -554,7 +626,9 @@ namespace Nikse.SubtitleEdit.Controls var column = SubtitleColumns[index]; int cw = Columns[index].Width; if (column != SubtitleColumn.Text && column != SubtitleColumn.TextAlternate) + { w += cw; + } } int lengthAvailable = Width - w; if (ColumnIndexTextAlternate >= 0) @@ -578,9 +652,13 @@ namespace Nikse.SubtitleEdit.Controls if (numberIdx >= 0) { if (_settings != null && _settings.General.ListViewColumnsRememberSize && _settings.General.ListViewNumberWidth > 1) + { Columns[numberIdx].Width = _settings.General.ListViewNumberWidth; + } else + { Columns[numberIdx].Width = 50; + } } var startIdx = GetColumnIndex(SubtitleColumn.Start); @@ -601,16 +679,24 @@ namespace Nikse.SubtitleEdit.Controls if (startIdx >= 0) { if (_settings != null && _settings.General.ListViewColumnsRememberSize && _settings.General.ListViewStartWidth > 1) + { Columns[startIdx].Width = _settings.General.ListViewStartWidth; + } else + { Columns[startIdx].Width = timeStampWidth; + } } if (endIdx >= 0) { if (_settings != null && _settings.General.ListViewColumnsRememberSize && _settings.General.ListViewEndWidth > 1) + { Columns[endIdx].Width = _settings.General.ListViewEndWidth; + } else + { Columns[endIdx].Width = timeStampWidth; + } } int w = 0; @@ -622,23 +708,38 @@ namespace Nikse.SubtitleEdit.Controls { cw = 55; if (column == SubtitleColumn.CharactersPerSeconds) + { cw = 65; + } else if (column == SubtitleColumn.WordsPerMinute) + { cw = 70; + } else if (column == SubtitleColumn.Gap) + { cw = 60; + } else if (column == SubtitleColumn.Actor) + { cw = 70; + } else if (column == SubtitleColumn.Region) + { cw = 60; + } else if (column != SubtitleColumn.Number) + { cw = 120; + } + Columns[index].Width = cw; Columns[index].Width = cw; Columns[index].Width = cw; } if (column != SubtitleColumn.Text && column != SubtitleColumn.TextAlternate) + { w += cw; + } } int lengthAvailable = Width - w; @@ -1045,7 +1146,9 @@ namespace Nikse.SubtitleEdit.Controls public void SaveFirstVisibleIndex() { if (TopItem != null) + { FirstVisibleIndex = Items.Count > 0 ? TopItem.Index : -1; + } } private void RestoreFirstVisibleIndex() @@ -1053,7 +1156,9 @@ namespace Nikse.SubtitleEdit.Controls if (IsValidIndex(FirstVisibleIndex)) { if (FirstVisibleIndex + 1 < Items.Count) + { FirstVisibleIndex++; + } Items[Items.Count - 1].EnsureVisible(); Items[FirstVisibleIndex].EnsureVisible(); @@ -1084,7 +1189,10 @@ namespace Nikse.SubtitleEdit.Controls { Paragraph next = null; if (i + 1 < paragraphs.Count) + { next = paragraphs[i + 1]; + } + Add(paragraph, next, null); SyntaxColorLine(paragraphs, i, paragraph); i++; @@ -1094,7 +1202,9 @@ namespace Nikse.SubtitleEdit.Controls EndUpdate(); if (FirstVisibleIndex == 0) + { FirstVisibleIndex = -1; + } } internal void Fill(List paragraphs, List paragraphsAlternate) @@ -1110,7 +1220,10 @@ namespace Nikse.SubtitleEdit.Controls Paragraph alternate = Utilities.GetOriginalParagraph(i, paragraph, paragraphsAlternate); Paragraph next = null; if (i + 1 < paragraphs.Count) + { next = paragraphs[i + 1]; + } + Add(paragraph, next, alternate); SyntaxColorLine(paragraphs, i, paragraph); i++; @@ -1120,7 +1233,9 @@ namespace Nikse.SubtitleEdit.Controls EndUpdate(); if (FirstVisibleIndex == 0) + { FirstVisibleIndex = -1; + } } public void SyntaxColorAllLines(Subtitle subtitle) @@ -1161,9 +1276,13 @@ namespace Nikse.SubtitleEdit.Controls if (charactersPerSecond > Configuration.Settings.General.SubtitleMaximumCharactersPerSeconds) { if (ColumnIndexCps >= 0) + { item.SubItems[ColumnIndexCps].BackColor = Configuration.Settings.Tools.ListViewSyntaxErrorColor; + } else if (ColumnIndexDuration >= 0) + { item.SubItems[ColumnIndexDuration].BackColor = Configuration.Settings.Tools.ListViewSyntaxErrorColor; + } } if (paragraph.Duration.TotalMilliseconds < Configuration.Settings.General.SubtitleMinimumDisplayMilliseconds && ColumnIndexDuration >= 0) { @@ -1188,9 +1307,14 @@ namespace Nikse.SubtitleEdit.Controls else { if (Items[i - 1].SubItems[ColumnIndexEnd].BackColor != BackColor) + { Items[i - 1].SubItems[ColumnIndexEnd].BackColor = BackColor; + } + if (item.SubItems[ColumnIndexStart].BackColor != BackColor) + { item.SubItems[ColumnIndexStart].BackColor = BackColor; + } } } @@ -1200,7 +1324,9 @@ namespace Nikse.SubtitleEdit.Controls } if (ColumnIndexText >= item.SubItems.Count) + { return; + } if (_settings.Tools.ListViewSyntaxColorLongLines) { @@ -1219,9 +1345,13 @@ namespace Nikse.SubtitleEdit.Controls if (len <= Configuration.Settings.General.SubtitleLineMaximumLength * noOfLines) { if (noOfLines > Configuration.Settings.Tools.ListViewSyntaxMoreThanXLinesX && _settings.Tools.ListViewSyntaxMoreThanXLines) + { item.SubItems[ColumnIndexText].BackColor = Configuration.Settings.Tools.ListViewSyntaxErrorColor; + } else if (item.SubItems[ColumnIndexText].BackColor != BackColor) + { item.SubItems[ColumnIndexText].BackColor = BackColor; + } } else { @@ -1232,7 +1362,9 @@ namespace Nikse.SubtitleEdit.Controls item.SubItems[ColumnIndexText].BackColor != Configuration.Settings.Tools.ListViewSyntaxErrorColor) { if (paragraph.NumberOfLines > Configuration.Settings.Tools.ListViewSyntaxMoreThanXLinesX) + { item.SubItems[ColumnIndexText].BackColor = Configuration.Settings.Tools.ListViewSyntaxErrorColor; + } } } } @@ -1240,7 +1372,10 @@ namespace Nikse.SubtitleEdit.Controls private string GetDisplayTime(TimeCode timeCode) { if (Configuration.Settings.General.CurrentVideoOffsetInMs > 0) + { return new TimeCode(timeCode.TotalMilliseconds + Configuration.Settings.General.CurrentVideoOffsetInMs).ToDisplayString(); + } + return timeCode.ToDisplayString(); } @@ -1299,7 +1434,9 @@ namespace Nikse.SubtitleEdit.Controls public void SelectNone() { for (var i = Items.Count - 1; i >= 0; i--) + { Items[i].Selected = false; + } } public void SelectIndexAndEnsureVisibleFaster(int index) @@ -1345,20 +1482,28 @@ namespace Nikse.SubtitleEdit.Controls public void SelectIndexAndEnsureVisible(int index, bool focus) { if (!IsValidIndex(index) || TopItem == null) + { return; + } int bottomIndex = TopItem.Index + (Height - 25) / 16; int itemsBeforeAfterCount = (bottomIndex - TopItem.Index) / 2 - 1; if (itemsBeforeAfterCount < 0) + { itemsBeforeAfterCount = 1; + } int beforeIndex = index - itemsBeforeAfterCount; if (beforeIndex < 0) + { beforeIndex = 0; + } int afterIndex = index + itemsBeforeAfterCount; if (afterIndex >= Items.Count) + { afterIndex = Items.Count - 1; + } SelectNone(); if (TopItem.Index <= beforeIndex && bottomIndex > afterIndex) @@ -1366,7 +1511,10 @@ namespace Nikse.SubtitleEdit.Controls Items[index].Selected = true; Items[index].EnsureVisible(); if (focus) + { Items[index].Focused = true; + } + return; } @@ -1377,7 +1525,9 @@ namespace Nikse.SubtitleEdit.Controls Items[index].Selected = true; Items[index].EnsureVisible(); if (focus) + { Items[index].Focused = true; + } } public void SelectIndexAndEnsureVisible(int index) @@ -1389,7 +1539,9 @@ namespace Nikse.SubtitleEdit.Controls { SelectNone(); if (p == null) + { return; + } for (int index = 0; index < Items.Count; index++) { @@ -1412,21 +1564,30 @@ namespace Nikse.SubtitleEdit.Controls public Paragraph GetSelectedParagraph(Subtitle subtitle) { if (subtitle != null && SelectedItems.Count > 0) + { return subtitle.GetParagraphOrDefault(SelectedItems[0].Index); + } + return null; } public string GetText(int index) { if (IsValidIndex(index)) + { return Items[index].SubItems[ColumnIndexText].Text.Replace(_lineSeparatorString, Environment.NewLine); + } + return null; } public string GetTextAlternate(int index) { if (IsValidIndex(index) && ColumnIndexTextAlternate >= 0) + { return Items[index].SubItems[ColumnIndexTextAlternate].Text.Replace(_lineSeparatorString, Environment.NewLine); + } + return null; } @@ -1436,10 +1597,15 @@ namespace Nikse.SubtitleEdit.Controls { ListViewItem item = Items[index]; if (ColumnIndexText >= 0) + { item.SubItems[ColumnIndexText].Text = text.Replace(Environment.NewLine, _lineSeparatorString); + } + var paragraph = item.Tag as Paragraph; if (paragraph != null) + { UpdateCpsAndWpm(item, paragraph); + } } } @@ -1449,19 +1615,40 @@ namespace Nikse.SubtitleEdit.Controls { ListViewItem item = Items[index]; if (ColumnIndexStart >= 0) + { item.SubItems[ColumnIndexStart].Text = GetDisplayTime(paragraph.StartTime); + } + if (ColumnIndexEnd >= 0) + { item.SubItems[ColumnIndexEnd].Text = GetDisplayTime(paragraph.EndTime); + } + if (ColumnIndexDuration >= 0) + { item.SubItems[ColumnIndexDuration].Text = paragraph.Duration.ToShortDisplayString(); + } + if (ColumnIndexGap >= 0) + { item.SubItems[ColumnIndexGap].Text = GetGap(paragraph, next); + } + if (ColumnIndexActor >= 0) + { item.SubItems[ColumnIndexActor].Text = paragraph.Actor; + } + if (ColumnIndexRegion >= 0) + { item.SubItems[ColumnIndexRegion].Text = paragraph.Region; + } + if (ColumnIndexText >= 0) + { item.SubItems[ColumnIndexText].Text = paragraph.Text.Replace(Environment.NewLine, _lineSeparatorString); + } + UpdateCpsAndWpm(item, paragraph); } } @@ -1487,7 +1674,9 @@ namespace Nikse.SubtitleEdit.Controls ShowExtraColumn(string.Empty); } while (ColumnIndexExtra >= Items[index].SubItems.Count) + { Items[index].SubItems.Add(string.Empty); + } if (ColumnIndexExtra >= 0) { @@ -1508,7 +1697,9 @@ namespace Nikse.SubtitleEdit.Controls ShowNetworkColumn(string.Empty); } while (ColumnIndexNetwork >= Items[index].SubItems.Count) + { Items[index].SubItems.Add(string.Empty); + } if (ColumnIndexNetwork >= 0) { @@ -1529,7 +1720,9 @@ namespace Nikse.SubtitleEdit.Controls ShowAlternateTextColumn(string.Empty); } while (ColumnIndexTextAlternate >= Items[index].SubItems.Count) + { Items[index].SubItems.Add(string.Empty); + } if (ColumnIndexTextAlternate >= 0) { @@ -1546,11 +1739,20 @@ namespace Nikse.SubtitleEdit.Controls { ListViewItem item = Items[index]; if (ColumnIndexEnd >= 0) + { item.SubItems[ColumnIndexEnd].Text = GetDisplayTime(paragraph.EndTime); + } + if (ColumnIndexDuration >= 0) + { item.SubItems[ColumnIndexDuration].Text = paragraph.Duration.ToShortDisplayString(); + } + if (ColumnIndexGap >= 0) + { item.SubItems[ColumnIndexGap].Text = GetGap(paragraph, next); + } + UpdateCpsAndWpm(item, paragraph); } } @@ -1575,11 +1777,19 @@ namespace Nikse.SubtitleEdit.Controls Paragraph p = subtitle.Paragraphs[i]; ListViewItem item = Items[i]; if (ColumnIndexStart >= 0) + { item.SubItems[ColumnIndexStart].Text = GetDisplayTime(p.StartTime); + } + if (ColumnIndexEnd >= 0) + { item.SubItems[ColumnIndexEnd].Text = GetDisplayTime(p.EndTime); + } + if (ColumnIndexDuration >= 0) + { item.SubItems[ColumnIndexDuration].Text = p.Duration.ToShortDisplayString(); + } } } EndUpdate(); @@ -1592,13 +1802,25 @@ namespace Nikse.SubtitleEdit.Controls { ListViewItem item = Items[index]; if (ColumnIndexStart >= 0) + { item.SubItems[ColumnIndexStart].Text = GetDisplayTime(paragraph.StartTime); + } + if (ColumnIndexEnd >= 0) + { item.SubItems[ColumnIndexEnd].Text = GetDisplayTime(paragraph.EndTime); + } + if (ColumnIndexDuration >= 0) + { item.SubItems[ColumnIndexDuration].Text = paragraph.Duration.ToShortDisplayString(); + } + if (ColumnIndexGap >= 0) + { item.SubItems[ColumnIndexGap].Text = GetGap(paragraph, next); + } + UpdateCpsAndWpm(item, paragraph); } SetGap(index - 1, prev, paragraph); @@ -1610,7 +1832,9 @@ namespace Nikse.SubtitleEdit.Controls { ListViewItem item = Items[index]; if (ColumnIndexGap >= 0) + { item.SubItems[ColumnIndexGap].Text = GetGap(paragraph, next); + } } } @@ -1630,9 +1854,14 @@ namespace Nikse.SubtitleEdit.Controls { ListViewItem item = Items[index]; if (item.UseItemStyleForSubItems) + { item.UseItemStyleForSubItems = false; + } + if (columnNumber >= 0 && columnNumber < item.SubItems.Count) + { item.SubItems[columnNumber].BackColor = color; + } } } @@ -1643,19 +1872,39 @@ namespace Nikse.SubtitleEdit.Controls ListViewItem item = Items[index]; item.BackColor = color; if (ColumnIndexStart >= 0) + { Items[index].SubItems[ColumnIndexStart].BackColor = color; + } + if (ColumnIndexEnd >= 0) + { Items[index].SubItems[ColumnIndexEnd].BackColor = color; + } + if (ColumnIndexDuration >= 0) + { Items[index].SubItems[ColumnIndexDuration].BackColor = color; + } + if (ColumnIndexCps >= 0) + { Items[index].SubItems[ColumnIndexCps].BackColor = color; + } + if (ColumnIndexWpm >= 0) + { Items[index].SubItems[ColumnIndexWpm].BackColor = color; + } + if (ColumnIndexText >= 0) + { Items[index].SubItems[ColumnIndexText].BackColor = color; + } + if (ColumnIndexTextAlternate >= 0) + { Items[index].SubItems[ColumnIndexTextAlternate].BackColor = color; + } } } @@ -1681,13 +1930,25 @@ namespace Nikse.SubtitleEdit.Controls ListViewItem item = Items[index]; item.Text = string.Empty; if (ColumnIndexStart >= 0) + { item.SubItems[ColumnIndexStart].Text = string.Empty; + } + if (ColumnIndexEnd >= 0) + { item.SubItems[ColumnIndexEnd].Text = string.Empty; + } + if (ColumnIndexDuration >= 0) + { item.SubItems[ColumnIndexDuration].Text = string.Empty; + } + if (ColumnIndexText >= 0) + { item.SubItems[ColumnIndexText].Text = string.Empty; + } + SetBackgroundColor(index, color); } } @@ -1696,7 +1957,10 @@ namespace Nikse.SubtitleEdit.Controls { var numberIdx = GetColumnIndex(SubtitleColumn.Number); if (numberIdx >= 0) + { Columns[numberIdx].Width = 0; + } + HideColumn(SubtitleColumn.End); HideColumn(SubtitleColumn.Duration); HideColumn(SubtitleColumn.CharactersPerSeconds); @@ -1706,7 +1970,10 @@ namespace Nikse.SubtitleEdit.Controls public void SetCustomResize(EventHandler handler) { if (handler == null) + { return; + } + Resize -= SubtitleListViewLastColumnFill; Resize += handler; } diff --git a/src/Controls/TimeUpDown.cs b/src/Controls/TimeUpDown.cs index 3a3f77bff..7b949189b 100644 --- a/src/Controls/TimeUpDown.cs +++ b/src/Controls/TimeUpDown.cs @@ -43,7 +43,10 @@ namespace Nikse.SubtitleEdit.Controls get { if (_forceHHMMSSFF || Configuration.Settings?.General.UseTimeFormatHHMMSSFF == true) + { return TimeMode.HHMMSSFF; + } + return TimeMode.HHMMSSMS; } } @@ -81,7 +84,9 @@ namespace Nikse.SubtitleEdit.Controls if (milliseconds.HasValue) { if (milliseconds.Value >= TimeCode.MaxTimeTotalMilliseconds - 0.1) + { milliseconds = 0; + } if (Mode == TimeMode.HHMMSSMS) { @@ -137,7 +142,9 @@ namespace Nikse.SubtitleEdit.Controls public double? GetTotalMilliseconds() { if (!_dirty) + { return _initialTotalMilliseconds; + } return TimeCode?.TotalMilliseconds; } @@ -147,13 +154,19 @@ namespace Nikse.SubtitleEdit.Controls get { if (_designMode) + { return new TimeCode(); + } if (string.IsNullOrWhiteSpace(maskedTextBox1.Text.RemoveChar('.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, string.Empty).RemoveChar(',').RemoveChar(':'))) + { return new TimeCode(TimeCode.MaxTimeTotalMilliseconds); + } if (!_dirty) + { return new TimeCode(_initialTotalMilliseconds); + } string startTime = maskedTextBox1.Text; bool isNegative = startTime.StartsWith('-'); @@ -161,7 +174,9 @@ namespace Nikse.SubtitleEdit.Controls if (Mode == TimeMode.HHMMSSMS) { if (startTime.EndsWith(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, StringComparison.Ordinal)) + { startTime += "000"; + } string[] times = startTime.Split(_splitChars, StringSplitOptions.RemoveEmptyEntries); @@ -173,12 +188,16 @@ namespace Nikse.SubtitleEdit.Controls int minutes; int.TryParse(times[1], out minutes); if (minutes > 59) + { minutes = 59; + } int seconds; int.TryParse(times[2], out seconds); if (seconds > 59) + { seconds = 59; + } int milliSeconds; int.TryParse(times[3].PadRight(3, '0'), out milliSeconds); @@ -190,14 +209,19 @@ namespace Nikse.SubtitleEdit.Controls } if (isNegative) + { tc.TotalMilliseconds *= -1; + } + return tc; } } else { if (startTime.EndsWith(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, StringComparison.Ordinal) || startTime.EndsWith(':')) + { startTime += "00"; + } string[] times = startTime.Split(_splitChars, StringSplitOptions.RemoveEmptyEntries); @@ -226,7 +250,10 @@ namespace Nikse.SubtitleEdit.Controls } if (isNegative) + { tc.TotalMilliseconds *= -1; + } + return tc; } } @@ -235,7 +262,9 @@ namespace Nikse.SubtitleEdit.Controls set { if (_designMode) + { return; + } if (value != null) { @@ -301,7 +330,9 @@ namespace Nikse.SubtitleEdit.Controls private void maskedTextBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) + { _dirty = true; + } } } } diff --git a/src/Controls/VideoPlayerContainer.cs b/src/Controls/VideoPlayerContainer.cs index 112752080..a73c67329 100644 --- a/src/Controls/VideoPlayerContainer.cs +++ b/src/Controls/VideoPlayerContainer.cs @@ -27,8 +27,16 @@ namespace Nikse.SubtitleEdit.Controls protected override void WndProc(ref Message m) { - if (m.Msg == 0x204) return; // WM_RBUTTONDOWN - if (m.Msg == 0x205) return; // WM_RBUTTONUP + if (m.Msg == 0x204) + { + return; // WM_RBUTTONDOWN + } + + if (m.Msg == 0x205) + { + return; // WM_RBUTTONUP + } + base.WndProc(ref m); } } @@ -45,12 +53,15 @@ namespace Nikse.SubtitleEdit.Controls public VideoPlayer VideoPlayer { - get { return _videoPlayer; } + get => _videoPlayer; set { _videoPlayer = value; if (_videoPlayer != null) + { SetPlayerName(_videoPlayer.PlayerName); + } + if (_videoPlayer is LibMpvDynamic && Configuration.Settings.General.MpvHandlesPreviewText) { _subtitlesHeight = 0; @@ -109,7 +120,7 @@ namespace Nikse.SubtitleEdit.Controls public RightToLeft TextRightToLeft { - get { return _subtitleTextBox.RightToLeft; } + get => _subtitleTextBox.RightToLeft; set { _subtitleTextBox.RightToLeft = value; @@ -120,7 +131,7 @@ namespace Nikse.SubtitleEdit.Controls public bool ShowStopButton { - get { return _pictureBoxStop.Visible || _pictureBoxStopOver.Visible || _pictureBoxStopDown.Visible; } + get => _pictureBoxStop.Visible || _pictureBoxStopOver.Visible || _pictureBoxStopDown.Visible; set { if (value) @@ -136,7 +147,7 @@ namespace Nikse.SubtitleEdit.Controls public bool ShowMuteButton { - get { return _pictureBoxMute.Visible || _pictureBoxMuteOver.Visible || _pictureBoxMuteDown.Visible; } + get => _pictureBoxMute.Visible || _pictureBoxMuteOver.Visible || _pictureBoxMuteDown.Visible; set { if (value) @@ -152,7 +163,7 @@ namespace Nikse.SubtitleEdit.Controls public bool ShowFullscreenButton { - get { return _pictureBoxFullscreen.Visible || _pictureBoxFullscreenOver.Visible || _pictureBoxFullscreenDown.Visible; } + get => _pictureBoxFullscreen.Visible || _pictureBoxFullscreenOver.Visible || _pictureBoxFullscreenDown.Visible; set { if (value) @@ -234,7 +245,9 @@ namespace Nikse.SubtitleEdit.Controls { control.MouseWheel += ControlMouseWheel; foreach (Control ctrl in control.Controls) + { AddMouseWheelEvent(ctrl); + } } private void ControlMouseWheel(object sender, MouseEventArgs e) @@ -242,9 +255,14 @@ namespace Nikse.SubtitleEdit.Controls int delta = e.Delta; double newPosition = CurrentPosition - (delta / 256.0); if (newPosition < 0) + { newPosition = 0; + } else if (newPosition > Duration) + { newPosition = Duration; + } + CurrentPosition = newPosition; } @@ -265,11 +283,19 @@ namespace Nikse.SubtitleEdit.Controls { var gs = Configuration.Settings.General; if (string.IsNullOrEmpty(gs.SubtitleFontName)) + { gs.SubtitleFontName = "Tahoma"; + } + if (gs.VideoPlayerPreviewFontBold) + { _subtitleTextBox.Font = new Font(gs.SubtitleFontName, gs.VideoPlayerPreviewFontSize * FontSizeFactor, FontStyle.Bold); + } else + { _subtitleTextBox.Font = new Font(gs.SubtitleFontName, gs.VideoPlayerPreviewFontSize * FontSizeFactor, FontStyle.Regular); + } + SubtitleText = _subtitleText; } @@ -294,7 +320,9 @@ namespace Nikse.SubtitleEdit.Controls _subtitleText = text; RefreshMpv(mpv, subtitle); if (_subtitleTextBox.Text.Length > 0) + { _subtitleTextBox.Text = string.Empty; + } } else { @@ -317,7 +345,9 @@ namespace Nikse.SubtitleEdit.Controls private void RefreshMpv(LibMpvDynamic mpv, Subtitle subtitle) { if (subtitle == null) + { return; + } try { @@ -403,7 +433,7 @@ namespace Nikse.SubtitleEdit.Controls public string SubtitleText { - get { return _subtitleText; } + get => _subtitleText; set { _subtitleText = value; @@ -511,9 +541,14 @@ namespace Nikse.SubtitleEdit.Controls if (colorEnd > 0 || colorEnd == -1) { if (colorEnd == -1) + { s = f.Substring(colorStart); + } else + { s = f.Substring(colorStart, colorEnd - colorStart); + } + s = s.Remove(0, " color=".Length); s = s.Trim('"'); s = s.Trim('\''); @@ -575,11 +610,19 @@ namespace Nikse.SubtitleEdit.Controls { var idx = _subtitleTextBox.TextLength + sb.Length; if (isBold) + { styleLookups[idx] |= FontStyle.Bold; + } + if (isItalic) + { styleLookups[idx] |= FontStyle.Italic; + } + if (isUnderline) + { styleLookups[idx] |= FontStyle.Underline; + } sb.Append(text[i]); letterCount++; @@ -590,11 +633,17 @@ namespace Nikse.SubtitleEdit.Controls _subtitleTextBox.SelectAll(); if (alignLeft) + { _subtitleTextBox.SelectionAlignment = HorizontalAlignment.Left; + } else if (alignRight) + { _subtitleTextBox.SelectionAlignment = HorizontalAlignment.Right; + } else + { _subtitleTextBox.SelectionAlignment = HorizontalAlignment.Center; + } _subtitleTextBox.DeselectAll(); @@ -620,7 +669,9 @@ namespace Nikse.SubtitleEdit.Controls private void PanelPlayerMouseDown(object sender, MouseEventArgs e) { if (VideoPlayer == null) + { OnEmptyPlayerClicked?.Invoke(sender, e); + } TogglePlayPause(); } @@ -645,7 +696,9 @@ namespace Nikse.SubtitleEdit.Controls _panelcontrols.Visible = false; } if (hideCursor) + { HideCursor(); + } } public void ShowControls() @@ -661,7 +714,9 @@ namespace Nikse.SubtitleEdit.Controls public void HideCursor() { if (_cursorStatus < 0) + { return; + } _cursorStatus--; if (VideoPlayer != null) @@ -677,7 +732,9 @@ namespace Nikse.SubtitleEdit.Controls public void ShowCursor() { if (_cursorStatus >= 0) + { return; + } _cursorStatus++; if (VideoPlayer != null) @@ -1244,9 +1301,13 @@ namespace Nikse.SubtitleEdit.Controls { HideAllMuteImages(); if (Mute) + { _pictureBoxMuteDown.Visible = true; + } else + { _pictureBoxMuteOver.Visible = true; + } } private void PictureBoxMuteOverMouseLeave(object sender, EventArgs e) @@ -1314,7 +1375,10 @@ namespace Nikse.SubtitleEdit.Controls { var newPosition = CurrentPosition - 3.0; if (newPosition < 0) + { newPosition = 0; + } + CurrentPosition = newPosition; } } @@ -1357,7 +1421,10 @@ namespace Nikse.SubtitleEdit.Controls { var newPosition = CurrentPosition + 3.0; if (newPosition < 0) + { newPosition = 0; + } + CurrentPosition = newPosition; } } @@ -1376,7 +1443,9 @@ namespace Nikse.SubtitleEdit.Controls { int max = _pictureBoxProgressbarBackground.Width - 9; if (mouseX > max) + { mouseX = max; + } double percent = mouseX * 100.0 / max; _pictureBoxProgressBar.Width = (int)(max * percent / 100.0); @@ -1417,11 +1486,15 @@ namespace Nikse.SubtitleEdit.Controls _pictureBoxProgressBar.Width = (int)(max * percent / 100.0); if (Convert.ToInt64(Duration) == 0) + { return; + } var pos = CurrentPosition; if (pos > 1000000) + { pos = 0; + } var dur = TimeCode.FromSeconds(Duration + Configuration.Settings.General.CurrentVideoOffsetInMs / TimeCode.BaseUnit); if (SmpteMode) @@ -1443,12 +1516,17 @@ namespace Nikse.SubtitleEdit.Controls { int max = _pictureBoxVolumeBarBackground.Width - 18; if (mouseX > max) + { mouseX = max; + } double percent = (mouseX * 100.0) / max; _pictureBoxVolumeBar.Width = (int)(max * percent / 100.0); if (_videoPlayer != null) + { _videoPlayer.Volume = (int)percent; + } + Configuration.Settings.General.VideoPlayerDefaultVolume = (int)percent; } @@ -1523,9 +1601,13 @@ namespace Nikse.SubtitleEdit.Controls if (VideoPlayer != null) { if (VideoPlayer.IsPaused) + { Play(); + } else + { Pause(); + } } } @@ -1536,7 +1618,10 @@ namespace Nikse.SubtitleEdit.Controls get { if (VideoPlayer != null) + { return VideoPlayer.Volume; + } + return 0; } set @@ -1544,14 +1629,22 @@ namespace Nikse.SubtitleEdit.Controls if (VideoPlayer != null) { if (value > 0) + { _muteOldVolume = null; + } if (value > 100) + { VideoPlayer.Volume = 100; + } else if (value < 0) + { VideoPlayer.Volume = 0; + } else + { VideoPlayer.Volume = (int)value; + } RefreshVolumeBar(); } @@ -1606,7 +1699,10 @@ namespace Nikse.SubtitleEdit.Controls get { if (VideoPlayer != null) + { return VideoPlayer.Duration; + } + return 0; } } diff --git a/src/Forms/DCinema/DCinemaPropertiesInterop.cs b/src/Forms/DCinema/DCinemaPropertiesInterop.cs index f3985da31..b7ae15ab9 100644 --- a/src/Forms/DCinema/DCinemaPropertiesInterop.cs +++ b/src/Forms/DCinema/DCinemaPropertiesInterop.cs @@ -51,44 +51,69 @@ namespace Nikse.SubtitleEdit.Forms.DCinema if (int.TryParse(ss.CurrentDCinemaReelNumber, out number)) { if (numericUpDownReelNumber.Minimum <= number && numericUpDownReelNumber.Maximum >= number) + { numericUpDownReelNumber.Value = number; + } } comboBoxLanguage.Text = ss.CurrentDCinemaLanguage; textBoxFontID.Text = ss.CurrentDCinemaFontId; textBoxFontUri.Text = ss.CurrentDCinemaFontUri; panelFontColor.BackColor = ss.CurrentDCinemaFontColor; if (ss.CurrentDCinemaFontEffect == "border") + { comboBoxFontEffect.SelectedIndex = 1; + } else if (ss.CurrentDCinemaFontEffect == "shadow") + { comboBoxFontEffect.SelectedIndex = 2; + } else + { comboBoxFontEffect.SelectedIndex = 0; + } + panelFontEffectColor.BackColor = ss.CurrentDCinemaFontEffectColor; numericUpDownFontSize.Value = ss.CurrentDCinemaFontSize; if (numericUpDownTopBottomMargin.Minimum <= ss.DCinemaBottomMargin && numericUpDownTopBottomMargin.Maximum >= ss.DCinemaBottomMargin) + { numericUpDownTopBottomMargin.Value = ss.DCinemaBottomMargin; + } else + { numericUpDownTopBottomMargin.Value = 8; + } if (numericUpDownFadeUp.Minimum <= ss.DCinemaFadeUpTime && numericUpDownFadeUp.Maximum >= ss.DCinemaFadeUpTime) + { numericUpDownFadeUp.Value = ss.DCinemaFadeUpTime; + } else + { numericUpDownFadeUp.Value = 0; + } if (numericUpDownFadeDown.Minimum <= ss.DCinemaFadeDownTime && numericUpDownFadeDown.Maximum >= ss.DCinemaFadeDownTime) + { numericUpDownFadeDown.Value = ss.DCinemaFadeDownTime; + } else + { numericUpDownFadeDown.Value = 0; + } decimal zPosition = (decimal)ss.DCinemaZPosition; if (numericUpDownZPosition.Minimum <= zPosition && numericUpDownZPosition.Maximum >= zPosition) + { numericUpDownZPosition.Value = zPosition; + } else + { numericUpDownZPosition.Value = 0; + } } UiUtil.FixLargeFonts(this, buttonCancel); } @@ -128,11 +153,18 @@ namespace Nikse.SubtitleEdit.Forms.DCinema ss.CurrentDCinemaFontUri = textBoxFontUri.Text; ss.CurrentDCinemaFontColor = panelFontColor.BackColor; if (comboBoxFontEffect.SelectedIndex == 1) + { ss.CurrentDCinemaFontEffect = "border"; + } else if (comboBoxFontEffect.SelectedIndex == 2) + { ss.CurrentDCinemaFontEffect = "shadow"; + } else + { ss.CurrentDCinemaFontEffect = string.Empty; + } + ss.CurrentDCinemaFontEffectColor = panelFontEffectColor.BackColor; ss.CurrentDCinemaFontSize = (int)numericUpDownFontSize.Value; ss.DCinemaBottomMargin = (int)numericUpDownTopBottomMargin.Value; diff --git a/src/Forms/DCinema/DCinemaPropertiesSmpte.cs b/src/Forms/DCinema/DCinemaPropertiesSmpte.cs index 0cf3dd074..23e796a4d 100644 --- a/src/Forms/DCinema/DCinemaPropertiesSmpte.cs +++ b/src/Forms/DCinema/DCinemaPropertiesSmpte.cs @@ -1,7 +1,6 @@ using Nikse.SubtitleEdit.Core; using Nikse.SubtitleEdit.Logic; using System; -using System.Drawing; using System.Globalization; using System.Windows.Forms; @@ -61,37 +60,59 @@ namespace Nikse.SubtitleEdit.Forms.DCinema timeUpDownStartTime.ForceHHMMSSFF(); if (string.IsNullOrEmpty(ss.CurrentDCinemaStartTime)) + { ss.CurrentDCinemaStartTime = "00:00:00:00"; + } + timeUpDownStartTime.MaskedTextBox.Text = ss.CurrentDCinemaStartTime; textBoxFontUri.Text = ss.CurrentDCinemaFontUri; textBoxIssueDate.Text = ss.CurrentDCinemaIssueDate; panelFontColor.BackColor = ss.CurrentDCinemaFontColor; if (ss.CurrentDCinemaFontEffect == "border") + { comboBoxFontEffect.SelectedIndex = 1; + } else if (ss.CurrentDCinemaFontEffect == "shadow") + { comboBoxFontEffect.SelectedIndex = 2; + } else + { comboBoxFontEffect.SelectedIndex = 0; + } + panelFontEffectColor.BackColor = ss.CurrentDCinemaFontEffectColor; numericUpDownFontSize.Value = ss.CurrentDCinemaFontSize; if (numericUpDownTopBottomMargin.Minimum <= ss.DCinemaBottomMargin && numericUpDownTopBottomMargin.Maximum >= ss.DCinemaBottomMargin) + { numericUpDownTopBottomMargin.Value = ss.DCinemaBottomMargin; + } else + { numericUpDownTopBottomMargin.Value = 8; + } if (numericUpDownFadeUp.Minimum <= ss.DCinemaFadeUpTime && numericUpDownFadeUp.Maximum >= ss.DCinemaFadeUpTime) + { numericUpDownFadeUp.Value = ss.DCinemaFadeUpTime; + } else + { numericUpDownFadeUp.Value = 0; + } if (numericUpDownFadeDown.Minimum <= ss.DCinemaFadeDownTime && numericUpDownFadeDown.Maximum >= ss.DCinemaFadeDownTime) + { numericUpDownFadeDown.Value = ss.DCinemaFadeDownTime; + } else + { numericUpDownFadeDown.Value = 0; + } } UiUtil.FixLargeFonts(this, buttonCancel); } @@ -134,19 +155,31 @@ namespace Nikse.SubtitleEdit.Forms.DCinema ss.CurrentDCinemaTimeCodeRate = comboBoxTimeCodeRate.Text; ss.CurrentDCinemaStartTime = timeUpDownStartTime.TimeCode.ToHHMMSSFF(); if (comboBoxLanguage.SelectedItem != null) + { ss.CurrentDCinemaLanguage = comboBoxLanguage.SelectedItem.ToString(); + } else + { ss.CurrentDCinemaLanguage = string.Empty; + } + ss.CurrentDCinemaIssueDate = textBoxIssueDate.Text; ss.CurrentDCinemaFontId = textBoxFontID.Text; ss.CurrentDCinemaFontUri = textBoxFontUri.Text; ss.CurrentDCinemaFontColor = panelFontColor.BackColor; if (comboBoxFontEffect.SelectedIndex == 1) + { ss.CurrentDCinemaFontEffect = "border"; + } else if (comboBoxFontEffect.SelectedIndex == 2) + { ss.CurrentDCinemaFontEffect = "shadow"; + } else + { ss.CurrentDCinemaFontEffect = string.Empty; + } + ss.CurrentDCinemaFontEffectColor = panelFontEffectColor.BackColor; ss.CurrentDCinemaFontSize = (int)numericUpDownFontSize.Value; ss.DCinemaBottomMargin = (int)numericUpDownTopBottomMargin.Value; diff --git a/src/Forms/Main.cs b/src/Forms/Main.cs index 456762049..e84be7464 100644 --- a/src/Forms/Main.cs +++ b/src/Forms/Main.cs @@ -29,6 +29,7 @@ using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; +using Nikse.SubtitleEdit.Forms.Networking; namespace Nikse.SubtitleEdit.Forms { diff --git a/src/Forms/Networking/NetworkChat.Designer.cs b/src/Forms/Networking/NetworkChat.Designer.cs index aecad344d..11320364f 100644 --- a/src/Forms/Networking/NetworkChat.Designer.cs +++ b/src/Forms/Networking/NetworkChat.Designer.cs @@ -1,4 +1,4 @@ -namespace Nikse.SubtitleEdit.Forms +namespace Nikse.SubtitleEdit.Forms.Networking { partial class NetworkChat { diff --git a/src/Forms/Networking/NetworkChat.cs b/src/Forms/Networking/NetworkChat.cs index d616d5199..1be201d6d 100644 --- a/src/Forms/Networking/NetworkChat.cs +++ b/src/Forms/Networking/NetworkChat.cs @@ -1,19 +1,16 @@ -using Nikse.SubtitleEdit.Core; +using System; +using System.Windows.Forms; +using Nikse.SubtitleEdit.Core; using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic.Networking; -using System; -using System.Windows.Forms; -namespace Nikse.SubtitleEdit.Forms +namespace Nikse.SubtitleEdit.Forms.Networking { public sealed partial class NetworkChat : Form { private Logic.Networking.NikseWebServiceSession _networkSession; - protected override bool ShowWithoutActivation - { - get { return true; } - } + protected override bool ShowWithoutActivation => true; public NetworkChat() { @@ -95,9 +92,14 @@ namespace Nikse.SubtitleEdit.Forms item.Tag = user; item.ForeColor = Utilities.GetColorFromUserName(user.UserName); if (DateTime.Now.Month == 12 && DateTime.Now.Day >= 23 && DateTime.Now.Day <= 25) + { item.ImageIndex = 7; + } else + { item.ImageIndex = Utilities.GetNumber0To7FromUserName(user.UserName); + } + item.SubItems.Add(new ListViewItem.ListViewSubItem(item, user.Ip)); listViewUsers.Items.Add(item); } @@ -113,7 +115,9 @@ namespace Nikse.SubtitleEdit.Forms } } if (removeItem != null) + { listViewUsers.Items.Remove(removeItem); + } } } } diff --git a/src/Forms/Networking/NetworkJoin.Designer.cs b/src/Forms/Networking/NetworkJoin.Designer.cs index 4e17c202b..e57ce215a 100644 --- a/src/Forms/Networking/NetworkJoin.Designer.cs +++ b/src/Forms/Networking/NetworkJoin.Designer.cs @@ -1,6 +1,6 @@ -namespace Nikse.SubtitleEdit.Forms +namespace Nikse.SubtitleEdit.Forms.Networking { - partial class NetworkJoin + sealed partial class NetworkJoin { /// /// Required designer variable. diff --git a/src/Forms/Networking/NetworkJoin.cs b/src/Forms/Networking/NetworkJoin.cs index 39e15575d..710b4a584 100644 --- a/src/Forms/Networking/NetworkJoin.cs +++ b/src/Forms/Networking/NetworkJoin.cs @@ -1,12 +1,12 @@ -using Nikse.SubtitleEdit.Core; -using Nikse.SubtitleEdit.Logic; -using System; +using System; using System.Net; using System.Windows.Forms; +using Nikse.SubtitleEdit.Core; +using Nikse.SubtitleEdit.Logic; -namespace Nikse.SubtitleEdit.Forms +namespace Nikse.SubtitleEdit.Forms.Networking { - public partial class NetworkJoin : Form + public sealed partial class NetworkJoin : Form { private Logic.Networking.NikseWebServiceSession _networkSession; @@ -35,12 +35,16 @@ namespace Nikse.SubtitleEdit.Forms textBoxSessionKey.Text = Configuration.Settings.NetworkSettings.SessionKey; if (textBoxSessionKey.Text.Trim().Length < 2) + { textBoxSessionKey.Text = Guid.NewGuid().ToString().RemoveChar('-'); + } comboBoxWebServiceUrl.Text = Configuration.Settings.NetworkSettings.WebServiceUrl; textBoxUserName.Text = Configuration.Settings.NetworkSettings.UserName; if (textBoxUserName.Text.Trim().Length < 2) + { textBoxUserName.Text = Dns.GetHostName(); + } } private void buttonJoin_Click(object sender, EventArgs e) @@ -68,11 +72,17 @@ namespace Nikse.SubtitleEdit.Forms else { if (message == "Session not found!") + { MessageBox.Show(string.Format(Configuration.Settings.Language.Main.XNotFound, textBoxSessionKey.Text)); + } else if (message == "Username already in use!") + { MessageBox.Show(string.Format(Configuration.Settings.Language.General.UserNameAlreadyInUse, textBoxSessionKey.Text)); + } else + { MessageBox.Show(message); + } } } catch (Exception exception) diff --git a/src/Forms/Networking/NetworkLogAndInfo.Designer.cs b/src/Forms/Networking/NetworkLogAndInfo.Designer.cs index 22ae80675..228fcf4bc 100644 --- a/src/Forms/Networking/NetworkLogAndInfo.Designer.cs +++ b/src/Forms/Networking/NetworkLogAndInfo.Designer.cs @@ -1,4 +1,4 @@ -namespace Nikse.SubtitleEdit.Forms +namespace Nikse.SubtitleEdit.Forms.Networking { partial class NetworkLogAndInfo { diff --git a/src/Forms/Networking/NetworkLogAndInfo.cs b/src/Forms/Networking/NetworkLogAndInfo.cs index f93757fcd..b56242c2e 100644 --- a/src/Forms/Networking/NetworkLogAndInfo.cs +++ b/src/Forms/Networking/NetworkLogAndInfo.cs @@ -1,9 +1,9 @@ -using Nikse.SubtitleEdit.Core; -using Nikse.SubtitleEdit.Logic; -using System; +using System; using System.Windows.Forms; +using Nikse.SubtitleEdit.Core; +using Nikse.SubtitleEdit.Logic; -namespace Nikse.SubtitleEdit.Forms +namespace Nikse.SubtitleEdit.Forms.Networking { public sealed partial class NetworkLogAndInfo : Form { @@ -21,12 +21,12 @@ namespace Nikse.SubtitleEdit.Forms buttonOK.Text = Configuration.Settings.Language.General.Ok; } - internal void Initialize(Logic.Networking.NikseWebServiceSession _networkSession) + internal void Initialize(Logic.Networking.NikseWebServiceSession networkSession) { - textBoxSessionKey.Text = _networkSession.SessionId; - textBoxUserName.Text = _networkSession.CurrentUser.UserName; - textBoxWebServiceUrl.Text = _networkSession.WebServiceUrl; - textBoxLog.Text = _networkSession.GetLog(); + textBoxSessionKey.Text = networkSession.SessionId; + textBoxUserName.Text = networkSession.CurrentUser.UserName; + textBoxWebServiceUrl.Text = networkSession.WebServiceUrl; + textBoxLog.Text = networkSession.GetLog(); } private void buttonOK_Click(object sender, EventArgs e) @@ -37,7 +37,9 @@ namespace Nikse.SubtitleEdit.Forms private void NetworkLogAndInfo_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } } } diff --git a/src/Forms/Networking/NetworkStart.Designer.cs b/src/Forms/Networking/NetworkStart.Designer.cs index 947386096..f619b361a 100644 --- a/src/Forms/Networking/NetworkStart.Designer.cs +++ b/src/Forms/Networking/NetworkStart.Designer.cs @@ -1,4 +1,4 @@ -namespace Nikse.SubtitleEdit.Forms +namespace Nikse.SubtitleEdit.Forms.Networking { partial class NetworkStart { diff --git a/src/Forms/Networking/NetworkStart.cs b/src/Forms/Networking/NetworkStart.cs index 4c09647ee..19cf43c7e 100644 --- a/src/Forms/Networking/NetworkStart.cs +++ b/src/Forms/Networking/NetworkStart.cs @@ -1,10 +1,10 @@ -using Nikse.SubtitleEdit.Core; -using Nikse.SubtitleEdit.Logic; -using System; +using System; using System.Net; using System.Windows.Forms; +using Nikse.SubtitleEdit.Core; +using Nikse.SubtitleEdit.Logic; -namespace Nikse.SubtitleEdit.Forms +namespace Nikse.SubtitleEdit.Forms.Networking { public sealed partial class NetworkStart : PositionAndSizeForm { @@ -36,12 +36,16 @@ namespace Nikse.SubtitleEdit.Forms textBoxSessionKey.Text = Configuration.Settings.NetworkSettings.SessionKey; if (textBoxSessionKey.Text.Trim().Length < 2) + { textBoxSessionKey.Text = Guid.NewGuid().ToString().RemoveChar('-'); + } comboBoxWebServiceUrl.Text = Configuration.Settings.NetworkSettings.WebServiceUrl; textBoxUserName.Text = Configuration.Settings.NetworkSettings.UserName; if (textBoxUserName.Text.Trim().Length < 2) + { textBoxUserName.Text = Dns.GetHostName(); + } } private void buttonStart_Click(object sender, EventArgs e) diff --git a/src/Forms/Ocr/AddBeterMultiMatch.cs b/src/Forms/Ocr/AddBeterMultiMatch.cs index dfc72828e..c2c118348 100644 --- a/src/Forms/Ocr/AddBeterMultiMatch.cs +++ b/src/Forms/Ocr/AddBeterMultiMatch.cs @@ -20,7 +20,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private List _matches; private List _splitterItems; private int _startIndex; - int _extraCount = 0; + int _extraCount; internal void Initialize(int selectedIndex, List matches, List splitterItems) { @@ -28,7 +28,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr for (int i = 0; i < selectedIndex; i++) { if (matches[i].Extra != null && matches[i].Extra.Count > 0) + { _extraCount += matches[i].Extra.Count -1; + } } _matches = matches; @@ -37,16 +39,27 @@ namespace Nikse.SubtitleEdit.Forms.Ocr for (int i = _startIndex; i < _splitterItems.Count - _extraCount; i++) { if (i >= _matches.Count) + { break; + } + var m = _matches[i]; if (m.Extra?.Count > 0) + { break; + } + if (m.Text != Configuration.Settings.Language.VobSubOcr.NoMatch && (m.ImageSplitterItem?.NikseBitmap == null || !string.IsNullOrWhiteSpace(m.ImageSplitterItem.SpecialCharacter))) + { break; + } + count++; listBoxInspectItems.Items.Add(m); if (count < 3) + { listBoxInspectItems.SetSelected(listBoxInspectItems.Items.Count - 1, true); + } } numericUpDownExpandCount.Maximum = listBoxInspectItems.Items.Count; MakeExpandImage(); @@ -65,7 +78,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var splitterItem = _splitterItems[_startIndex + _extraCount]; if (splitterItem.NikseBitmap == null) + { return; + } + ExpandedMatch = new BinaryOcrBitmap(new NikseBitmap(splitterItem.NikseBitmap), false, (int)numericUpDownExpandCount.Value, string.Empty, splitterItem.X, splitterItem.Y) { ExpandedList = new List() }; for (int i = 1; i < listBoxInspectItems.Items.Count; i++) { @@ -73,7 +89,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { splitterItem = _splitterItems[_startIndex + i + _extraCount]; if (splitterItem.NikseBitmap == null) + { break; + } + ExpandedMatch.ExpandedList.Add(new BinaryOcrBitmap(splitterItem.NikseBitmap, false, 0, null, splitterItem.X, splitterItem.Y)); } } @@ -87,7 +106,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void buttonOK_Click(object sender, System.EventArgs e) { if (string.IsNullOrWhiteSpace(textBoxText.Text)) + { return; + } ExpandedMatch.Italic = checkBoxItalic.Checked; ExpandedMatch.Text = textBoxText.Text; @@ -103,7 +124,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void AddBeterMultiMatch_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } } } diff --git a/src/Forms/Ocr/AddToOcrReplaceList.Designer.cs b/src/Forms/Ocr/AddToOcrReplaceList.Designer.cs index 545cf332f..8826f4bb3 100644 --- a/src/Forms/Ocr/AddToOcrReplaceList.Designer.cs +++ b/src/Forms/Ocr/AddToOcrReplaceList.Designer.cs @@ -1,6 +1,6 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { - partial class AddToOcrReplaceList + sealed partial class AddToOcrReplaceList { /// /// Required designer variable. diff --git a/src/Forms/Ocr/AddToOcrReplaceList.cs b/src/Forms/Ocr/AddToOcrReplaceList.cs index 5da6b85f6..82abddea9 100644 --- a/src/Forms/Ocr/AddToOcrReplaceList.cs +++ b/src/Forms/Ocr/AddToOcrReplaceList.cs @@ -7,7 +7,7 @@ using System.Windows.Forms; namespace Nikse.SubtitleEdit.Forms.Ocr { - public partial class AddToOcrReplaceList : Form + public sealed partial class AddToOcrReplaceList : Form { private string _threeLetterIsoLanguageName; @@ -29,7 +29,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string key = textBoxOcrFixKey.Text.RemoveControlCharacters().Trim(); string value = textBoxOcrFixValue.Text.RemoveControlCharacters().Trim(); if (key.Length == 0 || value.Length == 0 || key == value) + { return; + } var languageString = LanguageString; if (languageString == null) @@ -61,7 +63,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void AddToOcrReplaceList_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } public string NewSource { get; set; } @@ -70,14 +74,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr internal void Initialize(string languageId, string hunspellName, string source) { if (!string.IsNullOrEmpty(source)) + { textBoxOcrFixKey.Text = source; + } comboBoxDictionaries.Items.Clear(); foreach (string name in Utilities.GetDictionaryLanguages()) { comboBoxDictionaries.Items.Add(name); if (hunspellName != null && name.Equals(hunspellName, StringComparison.OrdinalIgnoreCase)) + { comboBoxDictionaries.SelectedIndex = comboBoxDictionaries.Items.Count - 1; + } } _threeLetterIsoLanguageName = languageId; } diff --git a/src/Forms/Ocr/DownloadTesseract302.cs b/src/Forms/Ocr/DownloadTesseract302.cs index 2b35358cf..b8c52c5c8 100644 --- a/src/Forms/Ocr/DownloadTesseract302.cs +++ b/src/Forms/Ocr/DownloadTesseract302.cs @@ -32,7 +32,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string dictionaryFolder = Configuration.Tesseract302Directory; if (!Directory.Exists(dictionaryFolder)) + { Directory.CreateDirectory(dictionaryFolder); + } var tempFileName = FileUtil.GetTempFileName(".tar"); using (var ms = new MemoryStream(e.Result)) diff --git a/src/Forms/Ocr/DownloadTesseract4.cs b/src/Forms/Ocr/DownloadTesseract4.cs index 2ffb356e6..895eb2f9d 100644 --- a/src/Forms/Ocr/DownloadTesseract4.cs +++ b/src/Forms/Ocr/DownloadTesseract4.cs @@ -34,7 +34,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string dictionaryFolder = Configuration.TesseractDirectory; if (!Directory.Exists(dictionaryFolder)) + { Directory.CreateDirectory(dictionaryFolder); + } var tempFileName = FileUtil.GetTempFileName(".tar"); using (var ms = new MemoryStream(e.Result)) diff --git a/src/Forms/Ocr/GetTesseract302Dictionaries.cs b/src/Forms/Ocr/GetTesseract302Dictionaries.cs index a25f8a190..218de8d98 100644 --- a/src/Forms/Ocr/GetTesseract302Dictionaries.cs +++ b/src/Forms/Ocr/GetTesseract302Dictionaries.cs @@ -14,9 +14,8 @@ namespace Nikse.SubtitleEdit.Forms.Ocr public sealed partial class GetTesseract302Dictionaries : Form { private List _dictionaryDownloadLinks = new List(); - private List _descriptions = new List(); - private string _xmlName = null; - private string _dictionaryFileName = null; + private string _xmlName; + private string _dictionaryFileName; internal string ChosenLanguage { get; private set; } public GetTesseract302Dictionaries() @@ -39,7 +38,6 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void LoadDictionaryList(string xmlRessourceName) { _dictionaryDownloadLinks = new List(); - _descriptions = new List(); _xmlName = xmlRessourceName; System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); Stream strm = asm.GetManifestResourceStream(_xmlName); @@ -67,18 +65,12 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string englishName = node.SelectSingleNode("EnglishName").InnerText; string downloadLink = node.SelectSingleNode("DownloadLink").InnerText; - - string description = string.Empty; - if (node.SelectSingleNode("Description") != null) - description = node.SelectSingleNode("Description").InnerText; - if (!string.IsNullOrEmpty(downloadLink)) { string name = englishName; comboBoxDictionaries.Items.Add(name); _dictionaryDownloadLinks.Add(downloadLink); - _descriptions.Add(description); } comboBoxDictionaries.SelectedIndex = 0; } @@ -90,7 +82,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void FixLargeFonts() { if (labelDescription1.Left + labelDescription1.Width + 5 > Width) + { Width = labelDescription1.Left + labelDescription1.Width + 5; + } + UiUtil.FixLargeFonts(this, buttonOK); } @@ -148,7 +143,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string dictionaryFolder = Configuration.Tesseract302DataDirectory; if (!Directory.Exists(dictionaryFolder)) + { Directory.CreateDirectory(dictionaryFolder); + } int index = comboBoxDictionaries.SelectedIndex; @@ -194,7 +191,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string dictionaryFolder = Configuration.Tesseract302DataDirectory; if (!Directory.Exists(dictionaryFolder)) + { Directory.CreateDirectory(dictionaryFolder); + } int index = comboBoxDictionaries.SelectedIndex; @@ -221,7 +220,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string dictionaryFolder = Configuration.Tesseract302DataDirectory; if (!Directory.Exists(dictionaryFolder)) + { Directory.CreateDirectory(dictionaryFolder); + } System.Diagnostics.Process.Start(dictionaryFolder); } diff --git a/src/Forms/Ocr/GetTesseractDictionaries.cs b/src/Forms/Ocr/GetTesseractDictionaries.cs index 78d25c5c4..edaa3c0fd 100644 --- a/src/Forms/Ocr/GetTesseractDictionaries.cs +++ b/src/Forms/Ocr/GetTesseractDictionaries.cs @@ -53,7 +53,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void FixLargeFonts() { if (labelDescription1.Left + labelDescription1.Width + 5 > Width) + { Width = labelDescription1.Left + labelDescription1.Width + 5; + } + UiUtil.FixLargeFonts(this, buttonOK); } @@ -111,7 +114,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string dictionaryFolder = Configuration.TesseractDataDirectory; if (!Directory.Exists(dictionaryFolder)) + { Directory.CreateDirectory(dictionaryFolder); + } int index = comboBoxDictionaries.SelectedIndex; @@ -157,7 +162,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string dictionaryFolder = Configuration.TesseractDataDirectory; if (!Directory.Exists(dictionaryFolder)) + { Directory.CreateDirectory(dictionaryFolder); + } int index = comboBoxDictionaries.SelectedIndex; @@ -184,7 +191,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string dictionaryFolder = Configuration.TesseractDataDirectory; if (!Directory.Exists(dictionaryFolder)) + { Directory.CreateDirectory(dictionaryFolder); + } System.Diagnostics.Process.Start(dictionaryFolder); } diff --git a/src/Forms/Ocr/OCRSpellCheck.cs b/src/Forms/Ocr/OCRSpellCheck.cs index 76c34f0a5..373e5b85d 100644 --- a/src/Forms/Ocr/OCRSpellCheck.cs +++ b/src/Forms/Ocr/OCRSpellCheck.cs @@ -29,14 +29,8 @@ namespace Nikse.SubtitleEdit.Forms.Ocr public bool IsBinaryImageCompare { - get - { - return buttonEditImageDb.Visible; - } - set - { - buttonEditImageDb.Visible = value; - } + get => buttonEditImageDb.Visible; + set => buttonEditImageDb.Visible = value; } public Action ActionResult { get; private set; } public string Word { get; private set; } @@ -98,9 +92,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr textBoxWholeText.Text = line; listBoxSuggestions.Items.Clear(); foreach (string suggestion in suggestions) + { listBoxSuggestions.Items.Add(suggestion); + } + if (listBoxSuggestions.Items.Count > 0) + { listBoxSuggestions.SelectedIndex = 0; + } HighLightWord(richTextBoxParagraph, word); ButtonEditWordClick(null, null); @@ -117,12 +116,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { bool startOk = i == 0; if (!startOk) + { startOk = expectedWordBoundaryChars.Contains(richTextBoxParagraph.Text[i - 1]); + } + if (startOk) { bool endOk = (i + word.Length == richTextBoxParagraph.Text.Length); if (!endOk) + { endOk = expectedWordBoundaryChars.Contains(richTextBoxParagraph.Text[i + word.Length]); + } + if (endOk) { richTextBoxParagraph.SelectionStart = i + 1; @@ -288,7 +293,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string text = textBoxWord.Text; if (!string.IsNullOrWhiteSpace(text)) + { System.Diagnostics.Process.Start("https://www.google.com/search?q=" + Utilities.UrlEncode(text)); + } } private void OcrSpellCheck_KeyDown(object sender, KeyEventArgs e) diff --git a/src/Forms/Ocr/OcrPreprocessingSettings.cs b/src/Forms/Ocr/OcrPreprocessingSettings.cs index 81c4ec272..14756426a 100644 --- a/src/Forms/Ocr/OcrPreprocessingSettings.cs +++ b/src/Forms/Ocr/OcrPreprocessingSettings.cs @@ -75,11 +75,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr n.ReplaceYellowWithWhite(); } if (panelColorToWhite.BackColor != Color.Transparent) + { n.ReplaceColor(panelColorToWhite.BackColor.A, panelColorToWhite.BackColor.R, panelColorToWhite.BackColor.G, panelColorToWhite.BackColor.B, 255, 255, 255, 255); + } if (panelColorToRemove.BackColor != Color.Transparent) + { n.ReplaceColor(panelColorToRemove.BackColor.A, panelColorToRemove.BackColor.R, panelColorToRemove.BackColor.G, panelColorToRemove.BackColor.B, Color.Transparent.A, Color.Transparent.R, Color.Transparent.G, Color.Transparent.B); + } if (_isBinaryImageCompare) + { n.MakeTwoColor((int)numericUpDownThreshold.Value); + } + pictureBox1.Image = n.GetBitmap(); } @@ -95,9 +102,11 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void pictureBoxSubtitleImage_Click(object sender, EventArgs e) { - var bmp = pictureBoxSubtitleImage.Image as Bitmap; - if (bmp == null) + if (!(pictureBoxSubtitleImage.Image is Bitmap)) + { return; + } + Text = MousePosition.X + ":" + MousePosition.Y; } diff --git a/src/Forms/Ocr/OcrPreprocessingT4.cs b/src/Forms/Ocr/OcrPreprocessingT4.cs index d11cab7f3..01ba21d92 100644 --- a/src/Forms/Ocr/OcrPreprocessingT4.cs +++ b/src/Forms/Ocr/OcrPreprocessingT4.cs @@ -9,13 +9,11 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { public partial class OcrPreprocessingT4 : Form { - private readonly bool _isBinaryImageCompare; private readonly NikseBitmap _source; public PreprocessingSettings PreprocessingSettings { get; } - public OcrPreprocessingT4(Bitmap bitmap, bool isBinaryImageCompare, PreprocessingSettings preprocessingSettings) + public OcrPreprocessingT4(Bitmap bitmap, PreprocessingSettings preprocessingSettings) { - _isBinaryImageCompare = isBinaryImageCompare; InitializeComponent(); _source = new NikseBitmap(bitmap); pictureBoxSubtitleImage.Image = bitmap; @@ -68,10 +66,5 @@ namespace Nikse.SubtitleEdit.Forms.Ocr DialogResult = DialogResult.Cancel; } } - - private void checkBoxCropTransparent_CheckedChanged(object sender, EventArgs e) - { - RefreshImage(); - } } } diff --git a/src/Forms/Ocr/VobSubCharactersImport.cs b/src/Forms/Ocr/VobSubCharactersImport.cs index 3bb4c079f..1d99978c7 100644 --- a/src/Forms/Ocr/VobSubCharactersImport.cs +++ b/src/Forms/Ocr/VobSubCharactersImport.cs @@ -102,7 +102,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void listView1_SelectedIndexChanged(object sender, EventArgs e) { if (listView1.SelectedItems.Count < 1) + { return; + } var item = listView1.SelectedItems[0]; var bob = (BinaryOcrBitmap)item.Tag; @@ -119,6 +121,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } catch (Exception) { + // ignored } } @@ -134,10 +137,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr listView1.ItemChecked -= listView1_ItemChecked; foreach (ListViewItem item in listView1.Items) + { item.Checked = true; + } foreach (ListViewData d in _data) + { d.Checked = true; + } UpdateSelectCount(); @@ -149,10 +156,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr listView1.ItemChecked -= listView1_ItemChecked; foreach (ListViewItem item in listView1.Items) + { item.Checked = !item.Checked; + } foreach (ListViewData d in _data) + { d.Checked = !d.Checked; + } UpdateSelectCount(); @@ -167,7 +178,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e) { if (e.Item == null) + { return; + } var idx = e.Item.Index; _data[idx].Checked = listView1.Items[idx].Checked; @@ -184,7 +197,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _selectCount++; } } - buttonImport.Text = string.Format("Import {0:#,##0}", _selectCount); + buttonImport.Text = $"Import {_selectCount:#,##0}"; } private void buttonImport_Click(object sender, EventArgs e) diff --git a/src/Forms/Ocr/VobSubEditCharacters.cs b/src/Forms/Ocr/VobSubEditCharacters.cs index 2fa61ad32..671a22f37 100644 --- a/src/Forms/Ocr/VobSubEditCharacters.cs +++ b/src/Forms/Ocr/VobSubEditCharacters.cs @@ -15,7 +15,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private readonly XmlDocument _compareDoc = new XmlDocument(); private readonly string _directoryPath; private List _italics = new List(); - internal List Additions { get; private set; } + internal List Additions { get; } private readonly BinaryOcrDb _binOcrDb; public XmlDocument ImageCompareDocument => _compareDoc; @@ -33,7 +33,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Additions = new List(); foreach (var a in additions) + { Additions.Add(a); + } const int makeHigher = 40; labelImageCompareFiles.Top = labelImageCompareFiles.Top - makeHigher; @@ -48,9 +50,13 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _directoryPath = Configuration.VobSubCompareDirectory + databaseFolderName + Path.DirectorySeparatorChar; if (!File.Exists(_directoryPath + "Images.xml")) + { _compareDoc.LoadXml(""); + } else + { _compareDoc.Load(_directoryPath + "Images.xml"); + } Refill(Additions); @@ -136,7 +142,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (listBoxFileNames.Items.Count > 0) + { listBoxFileNames.SelectedIndex = 0; + } } private void FillComboWithUniqueAndSortedTexts() @@ -150,14 +158,20 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string text = bob.Text; if (!texts.Contains(text) && text != null) + { texts.Add(text); + } + count++; } foreach (BinaryOcrBitmap bob in _binOcrDb.CompareImagesExpanded) { string text = bob.Text; if (!texts.Contains(text) && text != null) + { texts.Add(text); + } + count++; } } @@ -169,7 +183,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string text = node.Attributes["Text"].InnerText; if (!texts.Contains(text)) + { texts.Add(text); + } + count++; } } @@ -184,7 +201,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (comboBoxTexts.Items.Count > 0) + { comboBoxTexts.SelectedIndex = 0; + } } private void ComboBoxTextsSelectedIndexChanged(object sender, EventArgs e) @@ -232,14 +251,19 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (listBoxFileNames.Items.Count > 0) + { listBoxFileNames.SelectedIndex = 0; + } } private string GetSelectedFileName() { string fileName = listBoxFileNames.SelectedItem.ToString(); if (fileName.StartsWith('[')) + { fileName = fileName.Substring(fileName.IndexOf(']') + 1); + } + return fileName.Trim(); } @@ -247,7 +271,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { int idx = listBoxFileNames.SelectedIndex; if (idx < 0 || _binOcrDb == null) + { return null; + } return listBoxFileNames.Items[idx] as BinaryOcrBitmap; } @@ -256,7 +282,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string fileName = listBoxFileNames.Items[index].ToString(); if (fileName.StartsWith('[')) + { fileName = fileName.Substring(fileName.IndexOf(']') + 1); + } + return fileName.Trim(); } @@ -291,7 +320,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr using (var f = new FileStream(databaseName, FileMode.Open)) { if (name.Contains(']')) + { name = name.Substring(name.IndexOf(']') + 1).Trim(); + } + f.Position = Convert.ToInt64(name); bmp = new ManagedBitmap(f).ToOldBitmap(); } @@ -347,13 +379,17 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void VobSubEditCharacters_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } private void ButtonUpdateClick(object sender, EventArgs e) { if (listBoxFileNames.Items.Count == 0) + { return; + } string target = GetSelectedFileName(); string newText = textBoxText.Text; @@ -364,7 +400,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var bob = GetSelectedBinOcrBitmap(); if (bob == null) + { return; + } string oldText = bob.Text; bob.Text = newText; @@ -387,9 +425,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (oldText == newText) { if (oldTextItem >= 0 && oldTextItem < comboBoxTexts.Items.Count) + { comboBoxTexts.SelectedIndex = oldTextItem; + } + if (oldListBoxFileNamesIndex >= 0 && oldListBoxFileNamesIndex < listBoxFileNames.Items.Count) + { listBoxFileNames.SelectedIndex = oldListBoxFileNamesIndex; + } } else { @@ -467,7 +510,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr for (int j = 0; j < listBoxFileNames.Items.Count; j++) { if (GetFileName(j).StartsWith(target, StringComparison.Ordinal)) + { listBoxFileNames.SelectedIndex = j; + } } return; } @@ -490,7 +535,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void ButtonDeleteClick(object sender, EventArgs e) { if (listBoxFileNames.Items.Count == 0) + { return; + } int oldComboBoxIndex = comboBoxTexts.SelectedIndex; string target = GetSelectedFileName(); @@ -501,9 +548,13 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (bob != null) { if (bob.ExpandCount > 0) + { _binOcrDb.CompareImagesExpanded.Remove(bob); + } else + { _binOcrDb.CompareImages.Remove(bob); + } if (Additions != null && Additions.Count > 0) { @@ -520,7 +571,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Refill(Additions); } if (oldComboBoxIndex >= 0 && oldComboBoxIndex < comboBoxTexts.Items.Count) + { comboBoxTexts.SelectedIndex = oldComboBoxIndex; + } + return; } @@ -545,7 +599,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (Additions == null || Additions.Count == 0) { if (oldComboBoxIndex < comboBoxTexts.Items.Count) + { comboBoxTexts.SelectedIndex = oldComboBoxIndex; + } } } } @@ -564,7 +620,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr for (int j = 0; j < listBoxFileNames.Items.Count; j++) { if ((listBoxFileNames.Items[j] as BinaryOcrBitmap).Key == name) + { listBoxFileNames.SelectedIndex = j; + } } } else @@ -572,7 +630,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr for (int j = 0; j < listBoxFileNames.Items.Count; j++) { if (GetFileName(j).StartsWith(name, StringComparison.Ordinal)) + { listBoxFileNames.SelectedIndex = j; + } } } return; @@ -618,13 +678,21 @@ namespace Nikse.SubtitleEdit.Forms.Ocr try { if (saveFileDialog1.FilterIndex == 0) + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png); + } else if (saveFileDialog1.FilterIndex == 1) + { bmp.Save(saveFileDialog1.FileName); + } else if (saveFileDialog1.FilterIndex == 2) + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Gif); + } else + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Tiff); + } } catch (Exception exception) { diff --git a/src/Forms/Ocr/VobSubNOcrCharacterInspect.cs b/src/Forms/Ocr/VobSubNOcrCharacterInspect.cs index 60af6a3f3..89766e0ad 100644 --- a/src/Forms/Ocr/VobSubNOcrCharacterInspect.cs +++ b/src/Forms/Ocr/VobSubNOcrCharacterInspect.cs @@ -29,7 +29,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void VobSubNOcrCharacterInspect_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } internal void Initialize(Bitmap bitmap, int pixelsIsSpace, bool rightToLeft, NOcrDb nOcrDb, VobSubOcr vobSubOcr) @@ -45,7 +47,6 @@ namespace Nikse.SubtitleEdit.Forms.Ocr const int minLineHeight = 6; _imageList = NikseBitmapImageSplitter.SplitBitmapToLettersNew(nbmp, pixelsIsSpace, rightToLeft, Configuration.Settings.VobSubOcr.TopToBottom, minLineHeight); - // _imageList = NikseBitmapImageSplitter.SplitBitmapToLetters(nbmp, pixelsIsSpace, rightToLeft, Configuration.Settings.VobSubOcr.TopToBottom); int index = 0; while (index < _imageList.Count) @@ -84,7 +85,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void listBoxInspectItems_SelectedIndexChanged(object sender, EventArgs e) { if (listBoxInspectItems.SelectedIndex < 0) + { return; + } var img = _imageList[listBoxInspectItems.SelectedIndex]; if (img.NikseBitmap != null) @@ -150,7 +153,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void pictureBoxCharacter_Paint(object sender, PaintEventArgs e) { if (_nocrChar == null) + { return; + } var foreground = new Pen(new SolidBrush(Color.Green)); var background = new Pen(new SolidBrush(Color.Red)); @@ -169,16 +174,12 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void SizePictureBox() { - if (pictureBoxCharacter.Image != null) + if (pictureBoxCharacter.Image is Bitmap bmp) { - var bmp = pictureBoxCharacter.Image as Bitmap; - if (bmp != null) - { - pictureBoxCharacter.SizeMode = PictureBoxSizeMode.StretchImage; - pictureBoxCharacter.Width = (int)Math.Round(bmp.Width * _zoomFactor); - pictureBoxCharacter.Height = (int)Math.Round(bmp.Height * _zoomFactor); - pictureBoxCharacter.Invalidate(); - } + pictureBoxCharacter.SizeMode = PictureBoxSizeMode.StretchImage; + pictureBoxCharacter.Width = (int)Math.Round(bmp.Width * _zoomFactor); + pictureBoxCharacter.Height = (int)Math.Round(bmp.Height * _zoomFactor); + pictureBoxCharacter.Invalidate(); } } @@ -225,12 +226,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var expandSelectionList = new List(); if (listBoxInspectItems.SelectedIndex < 0) + { return; + } int index = listBoxInspectItems.SelectedIndex; var img = _imageList[index]; if (img.NikseBitmap == null) + { return; + } using (var vobSubOcrNOcrCharacter = new VobSubOcrNOcrCharacter()) { @@ -268,7 +273,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr shrinkSelection = true; index--; if (expandSelectionList.Count > 0) + { expandSelectionList.RemoveAt(expandSelectionList.Count - 1); + } } else if (result == DialogResult.OK && vobSubOcrNOcrCharacter.ExpandSelection) { @@ -280,7 +287,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (result == DialogResult.OK) { if (expandSelectionList.Count > 1) + { vobSubOcrNOcrCharacter.NOcrChar.ExpandCount = expandSelectionList.Count; + } + _nocrChars.Add(vobSubOcrNOcrCharacter.NOcrChar); _vobSubOcr.SaveNOcrWithCurrentLanguage(); DialogResult = DialogResult.OK; diff --git a/src/Forms/Ocr/VobSubNOcrEdit.cs b/src/Forms/Ocr/VobSubNOcrEdit.cs index cb9be3c75..670496420 100644 --- a/src/Forms/Ocr/VobSubNOcrEdit.cs +++ b/src/Forms/Ocr/VobSubNOcrEdit.cs @@ -10,8 +10,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { public partial class VobSubNOcrEdit : Form { - - private List _nocrChars; + private readonly List _nocrChars; private NOcrChar _nocrChar; private double _zoomFactor = 5.0; private bool _drawLineOn; @@ -20,7 +19,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private Point _end; private int _mx; private int _my; - private Bitmap _bitmap; + private readonly Bitmap _bitmap; private List _history = new List(); private int _historyIndex = -1; @@ -41,7 +40,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr SizePictureBox(); } - labelInfo.Text = string.Format("{0} elements in database", nocrChars.Count); + labelInfo.Text = $"{nocrChars.Count} elements in database"; labelNOcrCharInfo.Text = string.Empty; } @@ -51,7 +50,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr foreach (NOcrChar c in _nocrChars) { if (!list.Contains(c.Text)) + { list.Add(c.Text); + } } list.Sort(); comboBoxTexts.Items.Clear(); @@ -168,7 +169,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { labelNOcrCharInfo.Text = string.Empty; if (listBoxFileNames.SelectedIndex < 0) + { return; + } _nocrChar = listBoxFileNames.Items[listBoxFileNames.SelectedIndex] as NOcrChar; if (_nocrChar == null) @@ -194,7 +197,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } else { - groupBoxCurrentCompareImage.BackColor = Control.DefaultBackColor; + groupBoxCurrentCompareImage.BackColor = DefaultBackColor; } } _drawLineOn = false; @@ -217,7 +220,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void comboBoxTexts_SelectedIndexChanged(object sender, EventArgs e) { if (comboBoxTexts.SelectedIndex < 0) + { return; + } listBoxFileNames.Items.Clear(); string text = comboBoxTexts.Items[comboBoxTexts.SelectedIndex].ToString(); @@ -229,13 +234,17 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } } if (listBoxFileNames.Items.Count > 0) + { listBoxFileNames.SelectedIndex = 0; + } } private void pictureBoxCharacter_Paint(object sender, PaintEventArgs e) { if (_nocrChar == null) + { return; + } NOcrPoint selectedPoint = null; if (listBoxLinesForeground.Focused && listBoxLinesForeground.SelectedIndex >= 0) @@ -258,10 +267,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Point start = op.GetScaledStart(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height); Point end = op.GetScaledEnd(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height); if (start.X == end.X && start.Y == end.Y) + { end.X++; + } + e.Graphics.DrawLine(foreground, start, end); if (op == selectedPoint) + { e.Graphics.DrawLine(selPenF, op.GetScaledStart(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height), op.GetScaledEnd(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height)); + } } foreach (NOcrPoint op in _nocrChar.LinesBackground) { @@ -269,7 +283,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Point end = op.GetScaledEnd(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height); e.Graphics.DrawLine(background, start, end); if (op == selectedPoint) + { e.Graphics.DrawLine(selPenB, op.GetScaledStart(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height), op.GetScaledEnd(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height)); + } } } @@ -279,7 +295,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var p = foreground; if (radioButtonCold.Checked) + { p = background; + } + e.Graphics.DrawLine(p, new Point((int)Math.Round(_start.X * _zoomFactor), (int)Math.Round(_start.Y * _zoomFactor)), new Point(_mx, _my)); } } @@ -292,12 +311,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void buttonDelete_Click(object sender, EventArgs e) { if (listBoxFileNames.Items.Count == 0 || _nocrChar == null) + { return; + } _nocrChars.Remove(_nocrChar); FillComboBox(); if (comboBoxTexts.Items.Count > 0) + { comboBoxTexts.SelectedIndex = 0; + } } private void buttonOK_Click(object sender, EventArgs e) @@ -315,7 +338,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_historyIndex > 0 && _historyIndex < _history.Count - 1) { while (_history.Count > _historyIndex + 1) + { _history.RemoveAt(_history.Count - 1); + } + _historyIndex = _history.Count - 1; } _history.Add(new NOcrChar(nocrChar)); @@ -362,9 +388,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _nocrChar.Width = pictureBoxCharacter.Image.Width; _nocrChar.Height = pictureBoxCharacter.Image.Height; if (radioButtonHot.Checked) + { _nocrChar.LinesForeground.Add(new NOcrPoint(_start, _end)); + } else + { _nocrChar.LinesBackground.Add(new NOcrPoint(_start, _end)); + } + _drawLineOn = false; pictureBoxCharacter.Invalidate(); ShowOcrPoints(); @@ -508,7 +539,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr notImportedCount++; } } - MessageBox.Show(string.Format("Number of characters imported: {0}\r\nNumber of characters not imported (already present): {1}", importedCount, notImportedCount)); + MessageBox.Show($"Number of characters imported: {importedCount}\r\nNumber of characters not imported (already present): {notImportedCount}"); } } diff --git a/src/Forms/Ocr/VobSubNOcrTrain.cs b/src/Forms/Ocr/VobSubNOcrTrain.cs index a1e05b357..91646d25d 100644 --- a/src/Forms/Ocr/VobSubNOcrTrain.cs +++ b/src/Forms/Ocr/VobSubNOcrTrain.cs @@ -77,7 +77,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr var nOcrD = new NOcrDb(textBoxNOcrDb.Text); var lines = new List(); foreach (string line in File.ReadAllLines(textBoxInputFile.Text)) + { lines.Add(line); + } + var format = new SubRip(); var sub = new Subtitle(); format.LoadSubtitle(sub, lines, textBoxInputFile.Text); @@ -101,7 +104,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { TrainLetter(ref numberOfCharactersLeaned, ref numberOfCharactersSkipped, nOcrD, charactersLearned, s, false); if (checkBoxBold.Checked) + { TrainLetter(ref numberOfCharactersLeaned, ref numberOfCharactersSkipped, nOcrD, charactersLearned, s, true); + } } } } @@ -158,7 +163,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var fontStyle = FontStyle.Regular; if (subtitleFontBold) + { fontStyle = FontStyle.Bold; + } + font = new Font(_subtitleFontName, _subtitleFontSize, fontStyle); } catch (Exception exception) @@ -178,9 +186,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr int sizeX = (int)(textSize.Width * 0.8) + 40; int sizeY = (int)(textSize.Height * 0.8) + 30; if (sizeX < 1) + { sizeX = 1; + } + if (sizeY < 1) + { sizeY = 1; + } + bmp = new Bitmap(sizeX, sizeY); g = Graphics.FromImage(bmp); @@ -231,7 +245,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr i++; } if (sb.Length > 0) + { TextDraw.DrawText(font, sf, path, sb, false, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint); + } + sf.Dispose(); g.DrawPath(new Pen(_borderColor, BorderWidth), path); diff --git a/src/Forms/Ocr/VobSubOcr.cs b/src/Forms/Ocr/VobSubOcr.cs index f32eb6675..36620b576 100644 --- a/src/Forms/Ocr/VobSubOcr.cs +++ b/src/Forms/Ocr/VobSubOcr.cs @@ -161,10 +161,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr public override string ToString() { if (Italic) + { return Text + " (italic)"; + } if (Text == null) + { return string.Empty; + } return Text; } @@ -191,9 +195,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr public override string ToString() { if (Image == null) + { return Text; + } + if (Italic) + { return Text + " (" + Image.Width + "x" + Image.Height + ", italic)"; + } + return Text + " (" + Image.Width + "x" + Image.Height + ")"; } } @@ -322,7 +332,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { //Taxes: Remote Desktop Connection and painting http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx if (SystemInformation.TerminalServerSession) + { return; + } PropertyInfo aProp = typeof(Control).GetProperty("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance); aProp?.SetValue(c, true, null); @@ -408,7 +420,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr checkBoxRightToLeft.Text = language.RightToLeft; checkBoxRightToLeft.Left = numericUpDownPixelsIsSpace.Left; if (checkBoxRightToLeft.Left + checkBoxRightToLeft.Width > labelMinLineSplitHeight.Left) + { checkBoxRightToLeft.Left = labelMaxErrorPercent.Left; + } + labelMinLineSplitHeight.Text = language.MinLineSplitHeight; groupBoxOCRControls.Text = string.Empty; @@ -420,7 +435,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr comboBoxOcrMethod.Items.Add("Tesseract 3.02"); comboBoxOcrMethod.Items.Add("Tesseract 4.00"); if (_modiEnabled) + { comboBoxOcrMethod.Items.Add(language.OcrViaModi); + } + if (Configuration.Settings.General.ShowBetaStuff) { comboBoxOcrMethod.Items.Add(language.OcrViaNOCR); @@ -448,7 +466,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr checkBoxTesseractFallback.Checked = Configuration.Settings.VobSubOcr.UseTesseractFallback; if (Configuration.Settings.VobSubOcr.ItalicFactor >= 0.1 && Configuration.Settings.VobSubOcr.ItalicFactor < 1) + { _unItalicFactor = Configuration.Settings.VobSubOcr.ItalicFactor; + } + checkBoxShowOnlyForced.Text = language.ShowOnlyForcedSubtitles; checkBoxUseTimeCodesFromIdx.Text = language.UseTimeCodesFromIdx; @@ -577,10 +598,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr text = text.Replace(" " + Environment.NewLine, Environment.NewLine); text = text.Replace(Environment.NewLine + " ", Environment.NewLine); while (text.Contains(Environment.NewLine + Environment.NewLine)) + { text = text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); + } if (text.Replace(Environment.NewLine, "*").Length + 2 <= text.Length) + { text = Utilities.AutoBreakLine(text); + } } text = text.Trim(); @@ -654,7 +679,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _palette = palette; if (_palette == null) + { checkBoxCustomFourColors.Checked = true; + } SetTesseractLanguageFromLanguageString(languageString); _importLanguageString = languageString; @@ -708,11 +735,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _palette = palette; if (_palette == null) + { checkBoxCustomFourColors.Checked = true; + } _importLanguageString = languageString; if (_importLanguageString != null && _importLanguageString.Contains('(') && !_importLanguageString.StartsWith('(')) + { _importLanguageString = _importLanguageString.Substring(0, languageString.IndexOf('(') - 1).Trim(); + } } internal void InitializeBatch(List subtitles, VobSubOcrSettings vobSubOcrSettings, string fileName, bool forcedOnly, string language = null) @@ -784,10 +815,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr text = text.Replace(" " + Environment.NewLine, Environment.NewLine); text = text.Replace(Environment.NewLine + " ", Environment.NewLine); while (text.Contains(Environment.NewLine + Environment.NewLine)) + { text = text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); + } if (text.Replace(Environment.NewLine, "*").Length + 2 <= text.Length) + { text = Utilities.AutoBreakLine(text); + } } text = text.Trim(); @@ -855,7 +890,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (!string.IsNullOrEmpty(fileName)) { if (fileName.Length > 40) + { fileName = Path.GetFileName(fileName); + } + Text += " - " + fileName; FileName = fileName; _subtitle.FileName = fileName; @@ -872,7 +910,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string characterDatabasePath = Configuration.OcrDirectory.TrimEnd(Path.DirectorySeparatorChar); if (!Directory.Exists(characterDatabasePath)) + { Directory.CreateDirectory(characterDatabasePath); + } comboBoxCharacterDatabase.Items.Clear(); @@ -892,7 +932,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (comboBoxCharacterDatabase.SelectedIndex < 0 && comboBoxCharacterDatabase.Items.Count > 0) + { comboBoxCharacterDatabase.SelectedIndex = 0; + } for (int i = 0; i < comboBoxDictionaries.Items.Count; i++) { @@ -940,7 +982,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr foreach (var pack in _vobSubMergedPackist) { if (pack.SubPicture.Delay.TotalMilliseconds > 500 && !languageStreamIds.Contains(pack.StreamId)) + { languageStreamIds.Add(pack.StreamId); + } } if (languageStreamIds.Count > 1) { @@ -1095,7 +1139,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr numericUpDownStartNumber.Maximum = max; if (numericUpDownStartNumber.Maximum > 0 && numericUpDownStartNumber.Minimum <= 1) + { numericUpDownStartNumber.Value = 1; + } buttonOK.Enabled = true; buttonCancel.Enabled = true; @@ -1134,7 +1180,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr numericUpDownStartNumber.Maximum = max; if (numericUpDownStartNumber.Maximum > 0 && numericUpDownStartNumber.Minimum <= 1) + { numericUpDownStartNumber.Value = 1; + } buttonOK.Enabled = true; buttonCancel.Enabled = true; @@ -1176,7 +1224,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr numericUpDownStartNumber.Maximum = max; if (numericUpDownStartNumber.Maximum > 0 && numericUpDownStartNumber.Minimum <= 1) + { numericUpDownStartNumber.Value = 1; + } buttonOK.Enabled = true; buttonCancel.Enabled = true; @@ -1197,9 +1247,13 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Paragraph next = _subtitle.GetParagraphOrDefault(i + 1); double newEndTime = p.StartTime.TotalMilliseconds + Configuration.Settings.VobSubOcr.DefaultMillisecondsForUnknownDurations; if (next == null || (newEndTime < next.StartTime.TotalMilliseconds)) + { p.EndTime.TotalMilliseconds = newEndTime; + } else + { p.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 1; + } } } } @@ -1264,13 +1318,17 @@ namespace Nikse.SubtitleEdit.Forms.Ocr returnBmp = _mp4List[index].Picture.GetBitmap(null, background, pattern, emphasis1, emphasis2, true); if (checkBoxAutoTransparentBackground.Checked) + { returnBmp.MakeTransparent(); + } } else { returnBmp = _mp4List[index].Picture.GetBitmap(null, Color.Transparent, Color.Black, Color.White, Color.Black, false); if (checkBoxAutoTransparentBackground.Checked) + { returnBmp.MakeTransparent(); + } } } } @@ -1284,13 +1342,17 @@ namespace Nikse.SubtitleEdit.Forms.Ocr returnBmp = _spList[index].Picture.GetBitmap(null, background, pattern, emphasis1, emphasis2, true); if (checkBoxAutoTransparentBackground.Checked) + { returnBmp.MakeTransparent(); + } } else { returnBmp = _spList[index].Picture.GetBitmap(null, Color.Transparent, Color.Black, Color.White, Color.Black, false); if (checkBoxAutoTransparentBackground.Checked) + { returnBmp.MakeTransparent(); + } } } } @@ -1315,7 +1377,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { returnBmp = new Bitmap(fullFileName); if (checkBoxAutoTransparentBackground.Checked) + { returnBmp.MakeTransparent(); + } } catch { @@ -1348,7 +1412,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var temp = new Bitmap(fullFileName); if (temp.Width > maxWidth) + { maxWidth = temp.Width; + } + totalHeight += temp.Height; bitmaps.Add(temp); } @@ -1368,9 +1435,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Bitmap part = bitmaps[k]; if (checkBoxAutoTransparentBackground.Checked) + { part.MakeTransparent(); + } + using (var g = Graphics.FromImage(merged)) + { g.DrawImage(part, 0, y); + } + y += part.Height + 7; part.Dispose(); } @@ -1396,15 +1469,25 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Color c = fbmp.GetPixel(x, y); if (c.R == Color.Red.R && c.G == Color.Red.G && c.B == Color.Red.B) // normally anti-alias + { fbmp.SetPixel(x, y, emphasis2); + } else if (c.R == Color.Blue.R && c.G == Color.Blue.G && c.B == Color.Blue.B) // normally text? + { fbmp.SetPixel(x, y, pattern); + } else if (c.R == Color.White.R && c.G == Color.White.G && c.B == Color.White.B) // normally background + { fbmp.SetPixel(x, y, background); + } else if (c.R == Color.Black.R && c.G == Color.Black.G && c.B == Color.Black.B) // outline/border + { fbmp.SetPixel(x, y, emphasis1); + } else + { fbmp.SetPixel(x, y, c); + } } } @@ -1412,7 +1495,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (checkBoxAutoTransparentBackground.Checked) + { b.MakeTransparent(); + } + returnBmp = b; } } @@ -1442,11 +1528,20 @@ namespace Nikse.SubtitleEdit.Forms.Ocr nDvbBmp.CropTopTransparent(2); nDvbBmp.CropTransparentSidesAndBottom(2, true); if (checkBoxTransportStreamGetColorAndSplit.Checked) + { _dvbSubColor = nDvbBmp.GetBrightestColorWhiteIsTransparent(); + } + if (checkBoxAutoTransparentBackground.Checked) + { nDvbBmp.MakeBackgroundTransparent((int)numericUpDownAutoTransparentAlphaMax.Value); + } + if (checkBoxTransportStreamGrayscale.Checked) + { nDvbBmp.GrayScale(); + } + dvbBmp.Dispose(); returnBmp = nDvbBmp.GetBitmap(); } @@ -1460,11 +1555,20 @@ namespace Nikse.SubtitleEdit.Forms.Ocr nDvbBmp.CropTopTransparent(2); nDvbBmp.CropTransparentSidesAndBottom(2, true); if (checkBoxTransportStreamGetColorAndSplit.Checked) + { _dvbSubColor = nDvbBmp.GetBrightestColorWhiteIsTransparent(); + } + if (checkBoxAutoTransparentBackground.Checked) + { nDvbBmp.MakeBackgroundTransparent((int)numericUpDownAutoTransparentAlphaMax.Value); + } + if (checkBoxTransportStreamGrayscale.Checked) + { nDvbBmp.GrayScale(); + } + dvbBmp.Dispose(); returnBmp = nDvbBmp.GetBitmap(); } @@ -1484,18 +1588,24 @@ namespace Nikse.SubtitleEdit.Forms.Ocr returnBmp = _vobSubMergedPackist[index].SubPicture.GetBitmap(null, background, pattern, emphasis1, emphasis2, true); if (checkBoxAutoTransparentBackground.Checked) + { returnBmp.MakeTransparent(); + } } else { returnBmp = _vobSubMergedPackist[index].SubPicture.GetBitmap(_palette, Color.Transparent, Color.Black, Color.White, Color.Black, false); if (checkBoxAutoTransparentBackground.Checked) + { returnBmp.MakeTransparent(); + } } } if (returnBmp == null) + { return null; + } if (_ocrMethodIndex == _ocrMethodTesseract4 && !_fromMenuItem) { @@ -1509,7 +1619,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_binaryOcrDb == null && _nOcrDb == null || _fromMenuItem) { if (_preprocessingSettings == null || !_preprocessingSettings.Active) + { return returnBmp; + } var nb = new NikseBitmap(returnBmp); nb.CropSidesAndBottom(2, Color.FromArgb(0, 0, 0, 0), true); @@ -1517,13 +1629,25 @@ namespace Nikse.SubtitleEdit.Forms.Ocr nb.CropSidesAndBottom(2, Color.Transparent, true); nb.CropTop(2, Color.Transparent); if (_preprocessingSettings.InvertColors) + { nb.InvertColors(); + } + if (_preprocessingSettings.YellowToWhite) + { nb.ReplaceYellowWithWhite(); + } + if (_preprocessingSettings.ColorToWhite != Color.Transparent) + { nb.ReplaceColor(_preprocessingSettings.ColorToWhite.A, _preprocessingSettings.ColorToWhite.R, _preprocessingSettings.ColorToWhite.G, _preprocessingSettings.ColorToWhite.B, 255, 255, 255, 255); + } + if (_preprocessingSettings.ColorToRemove.A > 0) + { nb.ReplaceColor(_preprocessingSettings.ColorToRemove.A, _preprocessingSettings.ColorToRemove.R, _preprocessingSettings.ColorToRemove.G, _preprocessingSettings.ColorToRemove.B, Color.Transparent.A, Color.Transparent.R, Color.Transparent.G, Color.Transparent.B); + } + returnBmp.Dispose(); return nb.GetBitmap(); } @@ -1536,13 +1660,24 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_preprocessingSettings != null && _preprocessingSettings.Active) { if (_preprocessingSettings.InvertColors) + { n.InvertColors(); + } + if (_preprocessingSettings.YellowToWhite) + { n.ReplaceYellowWithWhite(); + } + if (_preprocessingSettings.ColorToWhite != Color.Transparent) + { n.ReplaceColor(_preprocessingSettings.ColorToWhite.A, _preprocessingSettings.ColorToWhite.R, _preprocessingSettings.ColorToWhite.G, _preprocessingSettings.ColorToWhite.B, 255, 255, 255, 255); + } + if (_preprocessingSettings.ColorToRemove.A > 0) + { n.ReplaceColor(_preprocessingSettings.ColorToRemove.A, _preprocessingSettings.ColorToRemove.R, _preprocessingSettings.ColorToRemove.G, _preprocessingSettings.ColorToRemove.B, Color.Transparent.A, Color.Transparent.R, Color.Transparent.G, Color.Transparent.B); + } } n.MakeTwoColor(Configuration.Settings.Tools.OcrBinaryImageCompareRgbThreshold); returnBmp.Dispose(); @@ -1557,13 +1692,24 @@ namespace Nikse.SubtitleEdit.Forms.Ocr emphasis2 = pictureBoxEmphasis2.BackColor; if (checkBoxBackgroundTransparent.Checked) + { background = Color.Transparent; + } + if (checkBoxPatternTransparent.Checked) + { pattern = Color.Transparent; + } + if (checkBoxEmphasis1Transparent.Checked) + { emphasis1 = Color.Transparent; + } + if (checkBoxEmphasis2Transparent.Checked) + { emphasis2 = Color.Transparent; + } } private void GetSubtitleTime(int index, out TimeCode start, out TimeCode end) @@ -1621,19 +1767,40 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private int GetSubtitleCount() { if (_mp4List != null) + { return _mp4List.Count; + } + if (_spList != null) + { return _spList.Count; + } + if (_bdnXmlSubtitle != null) + { return _bdnXmlSubtitle.Paragraphs.Count; + } + if (_bluRaySubtitlesOriginal != null) + { return _bluRaySubtitles.Count; + } + if (_xSubList != null) + { return _xSubList.Count; + } + if (_dvbSubtitles != null) + { return _dvbSubtitles.Count; + } + if (_dvbPesSubtitles != null) + { return _dvbPesSubtitles.Count; + } + return _vobSubMergedPackist.Count; } @@ -1645,7 +1812,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { bmp = GetSubtitleBitmap(index); if (bmp == null) + { bmp = new Bitmap(1, 1); + } + groupBoxSubtitleImage.Text = string.Format(Configuration.Settings.Language.VobSubOcr.SubtitleImageXofY, index + 1, numberOfImages) + " " + bmp.Width + "x" + bmp.Height; } else @@ -1739,7 +1909,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr index++; } if (ok) + { return oc; + } ok = true; index = 0; @@ -1784,7 +1956,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr index++; } if (ok) + { return oc; + } } } return null; @@ -1817,7 +1991,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Point p = new Point(point.X - 1, point.Y); if (p.X < 0) + { p.X = 1; + } + c = nbmp.GetPixel(p.X, p.Y); if (nbmp.Width > 20 && c.A > 150 && c.R + c.G + c.B > NocrMinColor) { @@ -1845,7 +2022,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Point p = new Point(point.X, point.Y); if (oc.Width > 19 && point.X > 0) + { p.X = p.X - 1; + } + c = nbmp.GetPixel(p.X, p.Y); if (c.A > 150 && c.R + c.G + c.B > NocrMinColor) { @@ -1858,7 +2038,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr index++; } if (ok) + { return oc; + } } } @@ -1909,7 +2091,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr index++; } if (ok) + { return oc; + } } } @@ -1962,7 +2146,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr index++; } if (ok) + { return oc; + } } } } @@ -2133,7 +2319,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } } if (ok) + { return oc; + } } } @@ -2176,7 +2364,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } } if (ok) + { return oc; + } } } @@ -2219,7 +2409,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } } if (ok) + { return oc; + } } } } @@ -2280,9 +2472,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr int maxMoveLeft = 9; if (nbmp.Width < 20) + { maxMoveLeft = 7; + } + if (nbmp.Width < 16) + { maxMoveLeft = 4; + } + for (int movePixelsLeft = 0; movePixelsLeft < maxMoveLeft; movePixelsLeft++) { foreach (NOcrChar oc in nOcrChars) @@ -2486,7 +2684,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Point p = new Point(point.X - 1, point.Y); if (p.X < 0) + { p.X = 1; + } + c = nbmp.GetPixel(p.X, p.Y); if (nbmp.Width > 20 && c.A > 150 && c.R + c.G + c.B > NocrMinColor) { @@ -2514,7 +2715,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Point p = new Point(point.X, point.Y); if (oc.Width > 19 && point.X > 0) + { p.X = p.X - 1; + } + c = nbmp.GetPixel(p.X, p.Y); if (c.A > 150 && c.R + c.G + c.B > NocrMinColor) { @@ -2527,7 +2731,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr index++; } if (ok) + { return oc; + } } } @@ -2578,7 +2784,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr index++; } if (ok) + { return oc; + } } } @@ -2631,7 +2839,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr index++; } if (ok) + { return oc; + } } } } @@ -2681,7 +2891,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } } if (ok) + { return oc; + } } } } @@ -2725,7 +2937,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } } if (ok) + { return oc; + } } } @@ -2768,7 +2982,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } } if (ok) + { return oc; + } } } } @@ -2854,42 +3070,63 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var expandedResult = NOcrFindExpandedMatch(parentBitmap, targetItem, nOcrDb.OcrCharacters); if (expandedResult != null) + { return new CompareMatch(expandedResult.Text, expandedResult.Italic, expandedResult.ExpandCount, null, expandedResult); + } var result = NOcrFindBestMatchNew(targetItem, targetItem.Y - targetItem.ParentY, out var italic, nOcrDb, tryItalicScaling, deepSeek); if (result == null) { if (checkBoxNOcrCorrect.Checked) + { return null; + } + return new CompareMatch("*", false, 0, null); } // Fix uppercase/lowercase issues (not I/l) if (result.Text == "e") + { _nocrLastLowercaseHeight = targetItem.NikseBitmap.Height; + } else if (_nocrLastLowercaseHeight == -1 && result.Text == "a") + { _nocrLastLowercaseHeight = targetItem.NikseBitmap.Height; + } if (result.Text == "E" || result.Text == "H" || result.Text == "R" || result.Text == "D" || result.Text == "T") + { _nocrLastUppercaseHeight = targetItem.NikseBitmap.Height; + } else if (_nocrLastUppercaseHeight == -1 && result.Text == "M") + { _nocrLastUppercaseHeight = targetItem.NikseBitmap.Height; + } if (result.Text == "V" || result.Text == "W" || result.Text == "U" || result.Text == "S" || result.Text == "Z" || result.Text == "O" || result.Text == "X" || result.Text == "Ø" || result.Text == "C") { if (_nocrLastLowercaseHeight > 3 && targetItem.NikseBitmap.Height - _nocrLastLowercaseHeight < 2) + { result.Text = result.Text.ToLower(); + } } else if (result.Text == "v" || result.Text == "w" || result.Text == "u" || result.Text == "s" || result.Text == "z" || result.Text == "o" || result.Text == "x" || result.Text == "ø" || result.Text == "c") { if (_nocrLastUppercaseHeight > 3 && _nocrLastUppercaseHeight - targetItem.NikseBitmap.Height < 2) + { result.Text = result.Text.ToUpper(); + } } if (italic) + { return new CompareMatch(result.Text, true, 0, null, result); + } else + { return new CompareMatch(result.Text, result.Italic, 0, null, result); + } } internal CompareMatch GetNOcrCompareMatchNew(ImageSplitterItem targetItem, NikseBitmap parentBitmap, NOcrDb nOcrDb, bool tryItalicScaling, bool deepSeek) @@ -2904,72 +3141,110 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (result == null) { if (checkBoxNOcrCorrect.Checked) + { return null; + } + return new CompareMatch("*", false, 0, null); } // Fix uppercase/lowercase issues (not I/l) if (result.Text == "e") + { _nocrLastLowercaseHeight = targetItem.NikseBitmap.Height; + } else if (_nocrLastLowercaseHeight == -1 && result.Text == "a") + { _nocrLastLowercaseHeight = targetItem.NikseBitmap.Height; + } if (result.Text == "E" || result.Text == "H" || result.Text == "R" || result.Text == "D" || result.Text == "T") + { _nocrLastUppercaseHeight = targetItem.NikseBitmap.Height; + } else if (_nocrLastUppercaseHeight == -1 && result.Text == "M") + { _nocrLastUppercaseHeight = targetItem.NikseBitmap.Height; + } if (result.Text == "V" || result.Text == "W" || result.Text == "U" || result.Text == "S" || result.Text == "Z" || result.Text == "O" || result.Text == "X" || result.Text == "Ø" || result.Text == "C") { if (_nocrLastLowercaseHeight > 3 && targetItem.NikseBitmap.Height - _nocrLastLowercaseHeight < 2) + { result.Text = result.Text.ToLower(); + } } else if (result.Text == "v" || result.Text == "w" || result.Text == "u" || result.Text == "s" || result.Text == "z" || result.Text == "o" || result.Text == "x" || result.Text == "ø" || result.Text == "c") { if (_nocrLastUppercaseHeight > 3 && _nocrLastUppercaseHeight - targetItem.NikseBitmap.Height < 2) + { result.Text = result.Text.ToUpper(); + } } if (italic) + { return new CompareMatch(result.Text, true, 0, null, result); + } else + { return new CompareMatch(result.Text, result.Italic, 0, null, result); + } } internal static CompareMatch GetNOcrCompareMatch(ImageSplitterItem targetItem, NikseBitmap parentBitmap, NOcrThreadParameter p) { var expandedResult = NOcrFindExpandedMatch(parentBitmap, targetItem, p.NOcrChars); if (expandedResult != null) + { return new CompareMatch(expandedResult.Text, expandedResult.Italic, expandedResult.ExpandCount, null, expandedResult); + } var result = NOcrFindBestMatch(targetItem, targetItem.Y - targetItem.ParentY, out var italic, p.NOcrChars, p.UnItalicFactor, p.AdvancedItalicDetection, true); if (result == null) + { return null; + } // Fix uppercase/lowercase issues (not I/l) if (result.Text == "e") + { p.NOcrLastLowercaseHeight = targetItem.NikseBitmap.Height; + } else if (p.NOcrLastLowercaseHeight == -1 && result.Text == "a") + { p.NOcrLastLowercaseHeight = targetItem.NikseBitmap.Height; + } if (result.Text == "E" || result.Text == "H" || result.Text == "R" || result.Text == "D" || result.Text == "T") + { p.NOcrLastUppercaseHeight = targetItem.NikseBitmap.Height; + } else if (p.NOcrLastUppercaseHeight == -1 && result.Text == "M") + { p.NOcrLastUppercaseHeight = targetItem.NikseBitmap.Height; + } if (result.Text == "V" || result.Text == "W" || result.Text == "U" || result.Text == "S" || result.Text == "Z" || result.Text == "O" || result.Text == "X" || result.Text == "Ø" || result.Text == "C") { if (p.NOcrLastLowercaseHeight > 3 && targetItem.NikseBitmap.Height - p.NOcrLastLowercaseHeight < 2) + { result.Text = result.Text.ToLower(); + } } else if (result.Text == "v" || result.Text == "w" || result.Text == "u" || result.Text == "s" || result.Text == "z" || result.Text == "o" || result.Text == "x" || result.Text == "ø" || result.Text == "c") { if (p.NOcrLastUppercaseHeight > 3 && p.NOcrLastUppercaseHeight - targetItem.NikseBitmap.Height < 2) + { result.Text = result.Text.ToUpper(); + } } if (italic) + { return new CompareMatch(result.Text, true, 0, null, result); + } + return new CompareMatch(result.Text, result.Italic, 0, null, result); } @@ -2995,7 +3270,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr for (int j = 1; j < compareItem.ExpandCount; j++) { if (list != null && list.Count > listIndex + j && list[listIndex + j].Y < minY) + { minY = list[listIndex + j].Y; + } } if (parentBitmap.Height >= compareItem.Bitmap.Height + minY) { @@ -3006,7 +3283,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3041,7 +3320,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr var cutBitmap = target.CopyRectangle(new Rectangle(1, 0, target.Width - 2, target.Height)); var cutBitmap2 = NikseBitmapImageSplitter.CropTopAndBottom(cutBitmap, out _, 2); if (cutBitmap2.Height != target.Height) + { FindBestMatch(out index, ref smallestDifference, ref smallestIndex, cutBitmap2, _compareBitmaps); + } } if (smallestDifference > 2 && target.Width > 15) @@ -3050,7 +3331,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr int topCrop = 0; var cutBitmap2 = NikseBitmapImageSplitter.CropTopAndBottom(cutBitmap, out topCrop); if (cutBitmap2.Height != target.Height) + { FindBestMatch(out index, ref smallestDifference, ref smallestIndex, cutBitmap2, _compareBitmaps); + } } if (smallestDifference > 2 && target.Width > 15) @@ -3059,7 +3342,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr int topCrop; var cutBitmap2 = NikseBitmapImageSplitter.CropTopAndBottom(cutBitmap, out topCrop); if (cutBitmap2.Height != target.Height) + { FindBestMatch(out index, ref smallestDifference, ref smallestIndex, cutBitmap2, _compareBitmaps); + } } } @@ -3174,12 +3459,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (text == "V" || text == "W" || text == "U" || text == "S" || text == "Z" || text == "O" || text == "X" || text == "Ø" || text == "C") { if (_binOcrLastLowercaseHeight > 3 && h - _binOcrLastLowercaseHeight < 2) + { text = text.ToLower(); + } } else if (text == "v" || text == "w" || text == "u" || text == "s" || text == "z" || text == "o" || text == "x" || text == "ø" || text == "c") { if (_binOcrLastUppercaseHeight > 3 && _binOcrLastUppercaseHeight - h < 2) + { text = text.ToUpper(); + } } } else @@ -3210,12 +3499,17 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (hit != null) { if (_binOcrLastLowercaseHeight < 0 && differencePercentage < 9 && (text == "e" || text == "d" || text == "a")) + { _binOcrLastLowercaseHeight = bob.Height; + } + return new CompareMatch(text, hit.Italic, hit.ExpandCount, hit.Key); } } if (hit != null) + { secondBestGuess = new CompareMatch(hit.Text, hit.Italic, hit.ExpandCount, hit.Key); + } } if (maxDiff > 1 && _isLatinDb) @@ -3224,27 +3518,39 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { ImageSplitterItem next = null; if (listIndex + 1 < list.Count) + { next = list[listIndex + 1]; + } if (next?.NikseBitmap == null) + { return new CompareMatch(".", false, 0, null); + } var nextBob = new BinaryOcrBitmap(next.NikseBitmap) { X = next.X, Y = next.Top }; if (!nextBob.IsPeriodAtTop(_binOcrLastLowercaseHeight)) // avoid italic ":" + { return new CompareMatch(".", false, 0, null); + } } if (bob.IsComma()) { ImageSplitterItem next = null; if (listIndex + 1 < list.Count) + { next = list[listIndex + 1]; + } if (next?.NikseBitmap == null) + { return new CompareMatch(",", false, 0, null); + } var nextBob = new BinaryOcrBitmap(next.NikseBitmap) { X = next.X, Y = next.Top }; if (!nextBob.IsPeriodAtTop(_binOcrLastLowercaseHeight)) // avoid italic ";" + { return new CompareMatch(",", false, 0, null); + } } if (bob.IsApostrophe()) { @@ -3280,7 +3586,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var difColoredPercentage = (Math.Abs(expanded.NumberOfColoredPixels - bobNext.NumberOfColoredPixels)) * 100.0 / (bobNext.Width * bobNext.Height); if (difColoredPercentage > 1 && expanded.Width < 3 || bobNext.Width < 3) + { return 100; + } int dif = int.MaxValue; if (expanded.Height == bobNext.Height && expanded.Width == bobNext.Width) @@ -3327,7 +3635,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (maxDiff < 0.2 || target.Width < 3 || target.Height < 5) + { return; + } int numberOfForegroundColors = bob.NumberOfColoredPixels; const int minForeColorMatch = 90; @@ -3342,7 +3652,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; @@ -3367,7 +3679,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; @@ -3393,12 +3707,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3416,12 +3734,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3440,12 +3762,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3464,12 +3790,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3488,12 +3818,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3512,12 +3846,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3536,12 +3874,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3560,12 +3902,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3584,12 +3930,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (dif < smallestDifference) { if (!BinaryOcrDb.AllowEqual(compareItem, bob)) + { continue; + } smallestDifference = dif; hit = compareItem; if (dif == 0) + { break; // foreach ending + } } } } @@ -3624,7 +3974,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width && compareItem.Bitmap.Height == target.Height) // precise math in size { if (compareItem.NumberOfForegroundColors < 1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < 3) { @@ -3651,7 +4003,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width && compareItem.Bitmap.Height == target.Height) // precise math in size { if (compareItem.NumberOfForegroundColors < 1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < 40) { @@ -3679,7 +4033,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width && compareItem.Bitmap.Height == target.Height - 1) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3689,7 +4045,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3704,7 +4062,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width && compareItem.Bitmap.Height == target.Height + 1) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3714,7 +4074,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3730,7 +4092,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width + 1 && compareItem.Bitmap.Height == target.Height + 1) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3740,7 +4104,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3756,7 +4122,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width - 1 && compareItem.Bitmap.Height == target.Height) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3766,7 +4134,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3782,7 +4152,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width - 1 && compareItem.Bitmap.Height == target.Height - 1) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3792,7 +4164,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3808,7 +4182,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width - 1 == target.Width && compareItem.Bitmap.Height == target.Height) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3818,7 +4194,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3834,7 +4212,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width - 2 && compareItem.Bitmap.Height == target.Height) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3844,7 +4224,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3860,7 +4242,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width - 3 && compareItem.Bitmap.Height == target.Height) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3870,7 +4254,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3886,7 +4272,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width == target.Width && compareItem.Bitmap.Height == target.Height - 3) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3896,7 +4284,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3912,7 +4302,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (compareItem.Bitmap.Width - 2 == target.Width && compareItem.Bitmap.Height == target.Height) { if (compareItem.NumberOfForegroundColors == -1) + { compareItem.NumberOfForegroundColors = CalculateNumberOfForegroundColors(compareItem.Bitmap); + } if (Math.Abs(compareItem.NumberOfForegroundColors - numberOfForegroundColors) < minForeColorMatch) { @@ -3922,7 +4314,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr smallestDifference = dif; smallestIndex = index; if (dif == 0) + { break; // foreach ending + } } } } @@ -3953,7 +4347,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Color c = nikseBitmap.GetPixel(x, y); if (c.A > 100 && c.R + c.G + c.B > 200) + { count++; + } } } return count; @@ -3968,7 +4364,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Color c = managedBitmap.GetPixel(x, y); if (c.A > 100 && c.R + c.G + c.B > 200) + { count++; + } } } return count; @@ -3978,7 +4376,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { int expandCount = 0; if (expandList != null) + { expandCount = expandList.Count; + } if (expandCount > 0) { @@ -4022,17 +4422,30 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void SetUnknownWordsColor(int index, int wordsNotFound, string line) { if (wordsNotFound >= 3) + { subtitleListView1.SetBackgroundColor(index, Color.Red); + } + if (wordsNotFound == 2) + { subtitleListView1.SetBackgroundColor(index, Color.Orange); + } else if (wordsNotFound == 1 || line.Length == 1 || line.Contains('_') || HasSingleLetters(line)) + { subtitleListView1.SetBackgroundColor(index, Color.Yellow); + } else if (wordsNotFound == 1) + { subtitleListView1.SetBackgroundColor(index, Color.Yellow); + } else if (string.IsNullOrWhiteSpace(line)) + { subtitleListView1.SetBackgroundColor(index, Color.Orange); + } else + { subtitleListView1.SetBackgroundColor(index, Color.LightGreen); + } } @@ -4045,13 +4458,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private string SplitAndOcrBinaryImageCompare(Bitmap bitmap, int listViewIndex) { if (_ocrFixEngine == null) + { LoadOcrFixEngine(null, LanguageString); + } var matches = new List(); var parentBitmap = new NikseBitmap(bitmap); int minLineHeight = _binOcrLastLowercaseHeight - 3; if (comboBoxLineSplitMinLineHeight.Visible && comboBoxLineSplitMinLineHeight.SelectedIndex > 0) + { minLineHeight = int.Parse(comboBoxLineSplitMinLineHeight.Text); + } + minLineHeight = Math.Max(minLineHeight, 6); if (_binOcrLastLowercaseHeight == -1 && _nocrLastLowercaseHeight == -1) { // try to guess lowercase height @@ -4059,20 +4477,30 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { minLineHeight = 25; if (LanguageString == "ar") + { minLineHeight = 30; + } } else { var letters = NikseBitmapImageSplitter.SplitBitmapToLettersNew(parentBitmap, _numericUpDownPixelsIsSpace, checkBoxRightToLeft.Checked, Configuration.Settings.VobSubOcr.TopToBottom, 20, _ocrCount > 20 ? _ocrHeight : -1); var actualLetters = letters.Where(p => p.NikseBitmap != null).ToList(); if (actualLetters.Any()) + { minLineHeight = (int)Math.Round(actualLetters.Average(p => p.NikseBitmap.Height) * 0.6); + } } } if (minLineHeight < 5) + { minLineHeight = _nocrLastLowercaseHeight; + } + if (minLineHeight < 5) + { minLineHeight = 6; + } + if (comboBoxLineSplitMinLineHeight.SelectedIndex > 0) { minLineHeight = int.Parse(comboBoxLineSplitMinLineHeight.Items[comboBoxLineSplitMinLineHeight.SelectedIndex].ToString()); @@ -4107,7 +4535,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr shrinkSelection = true; index--; if (expandSelectionList.Count > 0) + { expandSelectionList.RemoveAt(expandSelectionList.Count - 1); + } } else if (result == DialogResult.OK && _vobSubOcrCharacter.ExpandSelection) { @@ -4144,7 +4574,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (match == null) // Try line OCR if no image compare match { if (_nOcrDb != null && _nOcrDb.OcrCharacters.Count > 0 && _numericUpDownMaxErrorPct < 1) + { match = GetNOcrCompareMatchNew(item, parentBitmap, _nOcrDb, true, true); + } } if (match == null) @@ -4183,13 +4615,21 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { matches.Add(new CompareMatch(match.Text, match.Italic, 0, null, item)); if (match.ExpandCount > 0) + { index += match.ExpandCount - 1; + } } } if (_abort) + { return string.Empty; + } + if (!expandSelection && !shrinkSelection) + { index++; + } + if (shrinkSelection && expandSelectionList.Count < 2) { shrinkSelection = false; @@ -4200,10 +4640,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string line = MatchesToItalicStringConverter.GetStringWithItalicTags(matches); if (checkBoxAutoFixCommonErrors.Checked && _ocrFixEngine != null) + { line = _ocrFixEngine.FixOcrErrorsViaHardcodedRules(line, _lastLine, null); // TODO: Add abbreviations list + } if (checkBoxRightToLeft.Checked) + { line = ReverseNumberStrings(line); + } //OCR fix engine string textWithOutFixes = line; @@ -4211,10 +4655,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var autoGuessLevel = OcrFixEngine.AutoGuessLevel.None; if (checkBoxGuessUnknownWords.Checked) + { autoGuessLevel = OcrFixEngine.AutoGuessLevel.Aggressive; + } if (checkBoxAutoFixCommonErrors.Checked) + { line = _ocrFixEngine.FixOcrErrors(line, listViewIndex, _lastLine, true, autoGuessLevel); + } + int correctWords; int wordsNotFound = _ocrFixEngine.CountUnknownWordsViaDictionary(line, out correctWords); @@ -4237,7 +4686,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _ocrFixEngine.AutoGuessesUsed.Clear(); _ocrFixEngine.UnknownWordsFound.Clear(); if (checkBoxAutoFixCommonErrors.Checked) + { tempLine = _ocrFixEngine.FixOcrErrors(tempLine, listViewIndex, _lastLine, true, autoGuessLevel); + } + int tempCorrectWords; int tempWordsNotFound = _ocrFixEngine.CountUnknownWordsViaDictionary(tempLine, out tempCorrectWords); if (tempWordsNotFound == 0 && tempCorrectWords > 0) @@ -4266,14 +4718,19 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _ocrFixEngine.Abort = false; if (_ocrFixEngine.LastAction == OcrSpellCheck.Action.InspectCompareMatches) + { InspectImageCompareMatchesForCurrentImageToolStripMenuItem_Click(null, null); + } return string.Empty; } // Log used word guesses (via word replace list) foreach (string guess in _ocrFixEngine.AutoGuessesUsed) + { listBoxLogSuggestions.Items.Add(guess); + } + _ocrFixEngine.AutoGuessesUsed.Clear(); // Log unkown words guess (found via spelling dictionaries) @@ -4295,14 +4752,22 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void SetBinOcrLowercaseUppercase(int height, string text) { if (text == "e" && (height < _binOcrLastLowercaseHeight || _binOcrLastLowercaseHeight < 0)) + { _binOcrLastLowercaseHeight = height; + } else if (_binOcrLastLowercaseHeight == -1 && text == "a" && (height < _binOcrLastLowercaseHeight || _binOcrLastLowercaseHeight < 0)) + { _binOcrLastLowercaseHeight = height; + } if (text == "E" || text == "H" || text == "R" || text == "D" || text == "T" && height > _binOcrLastUppercaseHeight) + { _binOcrLastUppercaseHeight = height; + } else if (_binOcrLastUppercaseHeight == -1 && text == "M") + { _binOcrLastUppercaseHeight = height; + } } private void SaveNOcr() @@ -4345,11 +4810,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private string OcrViaNOCR(Bitmap bitmap, int listViewIndex) { if (_ocrFixEngine == null) + { comboBoxDictionaries_SelectedIndexChanged(null, null); + } string line = string.Empty; if (_nocrThreadResults != null) + { line = _nocrThreadResults[listViewIndex]; + } + if (string.IsNullOrEmpty(line)) { var nbmpInput = new NikseBitmap(bitmap); @@ -4358,9 +4828,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr int minLineHeight = _binOcrLastLowercaseHeight - 3; if (minLineHeight < 5) + { minLineHeight = _nocrLastLowercaseHeight - 3; + } + if (minLineHeight < 5) + { minLineHeight = 5; + } + List list = NikseBitmapImageSplitter.SplitBitmapToLettersNew(nbmpInput, (int)numericUpDownNumberOfPixelsIsSpaceNOCR.Value, checkBoxRightToLeft.Checked, Configuration.Settings.VobSubOcr.TopToBottom, minLineHeight); foreach (ImageSplitterItem item in list) @@ -4400,7 +4876,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr shrinkSelection = true; index--; if (expandSelectionList.Count > 0) + { expandSelectionList.RemoveAt(expandSelectionList.Count - 1); + } } else if (result == DialogResult.OK && _vobSubOcrNOcrCharacter.ExpandSelection) { @@ -4410,7 +4888,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var c = _vobSubOcrNOcrCharacter.NOcrChar; if (expandSelectionList.Count > 1) + { c.ExpandCount = expandSelectionList.Count; + } + _nOcrDb.Add(c); SaveNOcrWithCurrentLanguage(); string text = _vobSubOcrNOcrCharacter.NOcrChar.Text; @@ -4471,13 +4952,21 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { matches.Add(new CompareMatch(match.Text, match.Italic, 0, null)); if (match.ExpandCount > 0) + { index += match.ExpandCount - 1; + } } } if (_abort) + { return string.Empty; + } + if (!expandSelection && !shrinkSelection) + { index++; + } + if (shrinkSelection && expandSelectionList.Count < 2) { shrinkSelection = false; @@ -4494,7 +4983,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_ocrFixEngine.IsDictionaryLoaded) { if (checkBoxAutoFixCommonErrors.Checked) + { line = _ocrFixEngine.FixOcrErrors(line, listViewIndex, _lastLine, true, GetAutoGuessLevel()); + } + int wordsNotFound = _ocrFixEngine.CountUnknownWordsViaDictionary(line, out var correctWords); if (wordsNotFound > 0 || correctWords == 0 || textWithOutFixes != null && string.IsNullOrWhiteSpace(textWithOutFixes.Replace("~", string.Empty))) @@ -4513,7 +5005,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr // Log used word guesses (via word replace list) foreach (string guess in _ocrFixEngine.AutoGuessesUsed) + { listBoxLogSuggestions.Items.Add(guess); + } + _ocrFixEngine.AutoGuessesUsed.Clear(); // Log unkown words guess (found via spelling dictionaries) @@ -4539,9 +5034,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr while (start > 0) { if (start > 0 && char.IsLower(line[start - 1])) + { line = line.Remove(start, 1).Insert(start, "l"); + } else if (start < line.Length - 1 && char.IsLower(line[start + 1])) + { line = line.Remove(start, 1).Insert(start, "l"); + } + start++; start = line.IndexOf('I', start); } @@ -4549,20 +5049,35 @@ namespace Nikse.SubtitleEdit.Forms.Ocr while (start > 0) { if (start < line.Length - 1 && char.IsUpper(line[start + 1])) + { line = line.Remove(start, 1).Insert(start, "I"); + } + start++; start = line.IndexOf('l', start); } if (line.Contains('l')) { if (line.StartsWith('l')) + { line = @"I" + line.Substring(1); + } + if (line.StartsWith("l", StringComparison.Ordinal)) + { line = line.Remove(3, 1).Insert(3, "I"); + } + if (line.StartsWith("- l", StringComparison.Ordinal)) + { line = line.Remove(2, 1).Insert(2, "I"); + } + if (line.StartsWith("-l", StringComparison.Ordinal)) + { line = line.Remove(1, 1).Insert(1, "I"); + } + line = line.Replace(". l", ". I"); line = line.Replace("? l", "? I"); line = line.Replace("! l", "! I"); @@ -4609,7 +5124,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr line = line.Replace(". .", ".."); line = line.Replace(" ." + Environment.NewLine, "." + Environment.NewLine); if (line.EndsWith(" .", StringComparison.Ordinal)) + { line = line.Remove(line.Length - 2, 1); + } // fix no space before comma line = line.Replace(" ,", ","); @@ -4664,10 +5181,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (checkBoxAutoFixCommonErrors.Checked && _ocrFixEngine != null) + { line = _ocrFixEngine.FixOcrErrorsViaHardcodedRules(line, _lastLine, null); // TODO: Add abbreviations list + } if (checkBoxRightToLeft.Checked) + { line = ReverseNumberStrings(line); + } return line; } @@ -4702,9 +5223,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr foreach (ImageSplitterItem item in expandSelectionList) { if (item.Y < minimumY) + { minimumY = item.Y; + } + if (item.Y + item.NikseBitmap.Height > maximumY) + { maximumY = item.Y + item.NikseBitmap.Height; + } } var part = bitmap.CopyRectangle(new Rectangle(minimumX, minimumY, maximumX - minimumX, maximumY - minimumY)); return new ImageSplitterItem(minimumX, minimumY, part); @@ -4718,9 +5244,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr foreach (ImageSplitterItem item in expandSelectionList) { if (item.Y < minimumY) + { minimumY = item.Y; + } + if (item.Y + item.NikseBitmap.Height > maximumY) + { maximumY = item.Y + item.NikseBitmap.Height; + } } var part = bitmap.CopyRectangle(new Rectangle(minimumX, minimumY, maximumX - minimumX, maximumY - minimumY)); return new ImageSplitterItem(minimumX, minimumY, part); @@ -4742,17 +5273,30 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { int a = item.NikseBitmap.GetAlpha(x, y); if (a > 100) + { nbmp.SetPixel(item.X + x, item.Y + y, Color.White); + } } } if (item.Y < minimumY) + { minimumY = item.Y; + } + if (item.Y + item.NikseBitmap.Height > maximumY) + { maximumY = item.Y + item.NikseBitmap.Height; + } + if (item.X < minimumX) + { minimumX = item.X; + } + if (item.X + item.NikseBitmap.Width > maximumX) + { maximumX = item.X + item.NikseBitmap.Width; + } } nbmp.CropTransparentSidesAndBottom(0, true); nbmp = NikseBitmapImageSplitter.CropTopAndBottom(nbmp, out _); @@ -4882,14 +5426,22 @@ namespace Nikse.SubtitleEdit.Forms.Ocr bool hasIdxTimeCodes = false; bool hasForcedSubtitles = false; if (_vobSubMergedPackist == null) + { return null; + } + foreach (var x in _vobSubMergedPackist) { _vobSubMergedPackistOriginal.Add(x); if (x.IdxLine != null) + { hasIdxTimeCodes = true; + } + if (x.SubPicture.Forced) + { hasForcedSubtitles = true; + } } checkBoxUseTimeCodesFromIdx.CheckedChanged -= checkBoxUseTimeCodesFromIdx_CheckedChanged; checkBoxUseTimeCodesFromIdx.Visible = hasIdxTimeCodes; @@ -4904,7 +5456,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { _okClicked = true; // don't ask about discard changes if (_dvbSubtitles != null && checkBoxTransportStreamGetColorAndSplit.Checked) + { MergeDvbForEachSubImage(); + } DialogResult = DialogResult.OK; } @@ -4933,10 +5487,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr var matches = new List(); int minLineHeight = p.NOcrLastLowercaseHeight; if (minLineHeight < 10) + { minLineHeight = 22; + } + int maxLineHeight = p.NOcrLastUppercaseHeight; if (maxLineHeight < 10) + { minLineHeight = 80; + } List list = NikseBitmapImageSplitter.SplitBitmapToLettersNew(nbmpInput, p.NumberOfPixelsIsSpace, p.RightToLeft, Configuration.Settings.VobSubOcr.TopToBottom, minLineHeight); foreach (ImageSplitterItem item in list) @@ -4970,7 +5529,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { matches.Add(new CompareMatch(match.Text, match.Italic, 0, null)); if (match.ExpandCount > 0) + { index += match.ExpandCount - 1; + } } } index++; @@ -4985,7 +5546,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (!_nocrThreadsStop) { if (string.IsNullOrEmpty(_nocrThreadResults[p.Index])) + { _nocrThreadResults[p.Index] = p.Result; + } + p.Index += p.Increment; p.Picture.Dispose(); if (p.Index < _subtitle.Paragraphs.Count) @@ -5047,7 +5611,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr else if (_ocrMethodIndex == _ocrMethodNocr) { if (_nOcrDb == null) + { LoadNOcrWithCurrentLanguage(); + } if (_nOcrDb == null) { @@ -5060,7 +5626,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _nocrThreadResults = new string[_subtitle.Paragraphs.Count]; int noOfThreads = Environment.ProcessorCount - 1; if (noOfThreads >= max) + { noOfThreads = max - 1; + } + int start = (int)numericUpDownStartNumber.Value + 5; if (noOfThreads >= 1 && max > 5) { @@ -5141,17 +5710,23 @@ namespace Nikse.SubtitleEdit.Forms.Ocr text = text.Replace(" " + Environment.NewLine, Environment.NewLine); text = text.Replace(Environment.NewLine + " ", Environment.NewLine); while (text.Contains(Environment.NewLine + Environment.NewLine)) + { text = text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); + } if (text.Replace(Environment.NewLine, "*").Length + 2 <= text.Length) + { text = Utilities.AutoBreakLine(text); + } } if (_dvbSubtitles != null && checkBoxTransportStreamGetColorAndSplit.Checked) { text = Utilities.UnbreakLine(text); if (_dvbSubColor != Color.Transparent) + { text = "" + text + ""; + } } _linesOcred++; @@ -5171,18 +5746,28 @@ namespace Nikse.SubtitleEdit.Forms.Ocr text = text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); if (index >= subtitleListView1.Items.Count) + { return; + } + var item = subtitleListView1.Items[index]; item.Selected = true; item.EnsureVisible(); Paragraph p = _subtitle.GetParagraphOrDefault(index); if (p != null) + { p.Text = text; + } + if (subtitleListView1.SelectedItems.Count == 1 && subtitleListView1.SelectedItems[0].Index == index) + { textBoxCurrentText.Text = text; + } else + { subtitleListView1.SetText(index, text); + } var max = GetSubtitleCount(); GetSubtitleTime(index, out var startTime, out var endTime); @@ -5232,18 +5817,30 @@ namespace Nikse.SubtitleEdit.Forms.Ocr int j = i; subtitleListView1.Items[j].Selected = true; if (j < max - 1) + { j++; + } + if (j < max - 1) + { j++; + } + subtitleListView1.Items[j].EnsureVisible(); string text = string.Empty; if (_ocrMethodIndex == _ocrMethodBinaryImageCompare) + { text = SplitAndOcrBinaryImageCompare(bmp, i); + } else if (_ocrMethodIndex == _ocrMethodNocr) + { text = OcrViaNOCR(bmp, i); + } else if (_ocrMethodIndex == _ocrMethodModi) + { text = CallModi(i); + } _lastLine = text; @@ -5262,17 +5859,23 @@ namespace Nikse.SubtitleEdit.Forms.Ocr text = text.Replace(" " + Environment.NewLine, Environment.NewLine); text = text.Replace(Environment.NewLine + " ", Environment.NewLine); while (text.Contains(Environment.NewLine + Environment.NewLine)) + { text = text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); + } if (text.Replace(Environment.NewLine, "*").Length + 2 <= text.Length) + { text = Utilities.AutoBreakLine(text); + } } if (_dvbSubtitles != null && checkBoxTransportStreamGetColorAndSplit.Checked) { text = Utilities.UnbreakLine(text); if (_dvbSubColor != Color.Transparent) + { text = "" + text + ""; + } } _linesOcred++; @@ -5294,11 +5897,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Paragraph p = _subtitle.GetParagraphOrDefault(i); if (p != null) + { p.Text = text; + } + if (subtitleListView1.SelectedItems.Count == 1 && subtitleListView1.SelectedItems[0].Index == i) + { textBoxCurrentText.Text = text; + } else + { subtitleListView1.SetText(i, text); + } return false; } @@ -5360,7 +5970,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var result = new Bitmap(width, height); using (var g = Graphics.FromImage(result)) + { g.DrawImage(b, 0, 0, width, height); + } + return result; } @@ -5404,7 +6017,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private bool HasSingleLetters(string line) { if (!_ocrFixEngine.IsDictionaryLoaded || !_ocrFixEngine.SpellCheckDictionaryName.StartsWith("en_", StringComparison.Ordinal)) + { return false; + } line = line.Replace("[", string.Empty); line = line.Replace("]", string.Empty); @@ -5426,10 +6041,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private string OcrViaTesseract(Bitmap bitmap, int index) { if (bitmap == null) + { return string.Empty; + } if (_ocrFixEngine == null) + { comboBoxDictionaries_SelectedIndexChanged(null, null); + } const int badWords = 0; string textWithOutFixes; @@ -5440,7 +6059,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr else { if (_tesseractAsyncIndex <= index) + { _tesseractAsyncIndex = index + 10; + } + textWithOutFixes = Tesseract3DoOcrViaExe(bitmap, _languageId, "6", _tesseractEngineMode); // 6 = Assume a single uniform block of text. } @@ -5515,7 +6137,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } } if (!checkBoxTesseractItalicsOn.Checked) + { textWithOutFixes = HtmlUtil.RemoveOpenCloseTags(textWithOutFixes, HtmlUtil.TagItalic); + } // Sometimes Tesseract has problems with small fonts - it helps to make the image larger if (HtmlUtil.RemoveOpenCloseTags(textWithOutFixes, HtmlUtil.TagItalic).Replace("@", string.Empty).Replace("%", string.Empty).Replace("|", string.Empty).Trim().Length < 3 @@ -5524,7 +6148,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string rs = TesseractResizeAndRetry(bitmap); textWithOutFixes = rs; if (!checkBoxTesseractItalicsOn.Checked) + { textWithOutFixes = HtmlUtil.RemoveOpenCloseTags(textWithOutFixes, HtmlUtil.TagItalic); + } } // fix italics @@ -5536,7 +6162,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_ocrFixEngine.IsDictionaryLoaded) { if (checkBoxAutoFixCommonErrors.Checked) + { line = _ocrFixEngine.FixOcrErrors(line, index, _lastLine, true, GetAutoGuessLevel()); + } + int correctWords; int wordsNotFound = _ocrFixEngine.CountUnknownWordsViaDictionary(line, out correctWords); int oldCorrectWords = correctWords; @@ -5577,13 +6206,19 @@ namespace Nikse.SubtitleEdit.Forms.Ocr wordsNotFound = newWordsNotFound; if (textWithOutFixes.Length > 3 && textWithOutFixes.EndsWith("...", StringComparison.Ordinal) && !newText.EndsWith('.') && !newText.EndsWith(',') && !newText.EndsWith('!') && !newText.EndsWith('?') && !newText.EndsWith("", StringComparison.Ordinal)) + { newText = newText.TrimEnd() + "..."; + } else if (textWithOutFixes.Length > 0 && textWithOutFixes.EndsWith('.') && !newText.EndsWith('.') && !newText.EndsWith(',') && !newText.EndsWith('!') && !newText.EndsWith('?') && !newText.EndsWith("", StringComparison.Ordinal)) + { newText = newText.TrimEnd() + "."; + } else if (textWithOutFixes.Length > 0 && textWithOutFixes.EndsWith('?') && !newText.EndsWith('.') && !newText.EndsWith(',') && !newText.EndsWith('!') && !newText.EndsWith('?') && !newText.EndsWith("", StringComparison.Ordinal)) + { newText = newText.TrimEnd() + "?"; + } textWithOutFixes = newUnfixedText; line = FixItalics(newText); @@ -5632,7 +6267,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr int modiWordsNotFound = _ocrFixEngine.CountUnknownWordsViaDictionary(oneColorText, out modiCorrectWords); string modiTextOcrFixed = oneColorText; if (checkBoxAutoFixCommonErrors.Checked) + { modiTextOcrFixed = _ocrFixEngine.FixOcrErrors(oneColorText, index, _lastLine, false, GetAutoGuessLevel()); + } + int modiOcrCorrectedCorrectWords; int modiOcrCorrectedWordsNotFound = _ocrFixEngine.CountUnknownWordsViaDictionary(modiTextOcrFixed, out modiOcrCorrectedCorrectWords); if (modiOcrCorrectedWordsNotFound <= modiWordsNotFound) @@ -5648,7 +6286,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr wordsNotFound = modiWordsNotFound; correctWords = modiCorrectWords; if (checkBoxAutoFixCommonErrors.Checked) + { line = _ocrFixEngine.FixOcrErrors(line, index, _lastLine, true, GetAutoGuessLevel()); + } } else if (wordsNotFound == modiWordsNotFound && oneColorText.EndsWith('!') && (line.EndsWith('l') || line.EndsWith('fl'))) { @@ -5656,7 +6296,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr wordsNotFound = modiWordsNotFound; correctWords = modiCorrectWords; if (checkBoxAutoFixCommonErrors.Checked) + { line = _ocrFixEngine.FixOcrErrors(line, index, _lastLine, true, GetAutoGuessLevel()); + } } } } @@ -5680,7 +6322,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr int modiWordsNotFound = _ocrFixEngine.CountUnknownWordsViaDictionary(unItalicText, out modiCorrectWords); string modiTextOcrFixed = unItalicText; if (checkBoxAutoFixCommonErrors.Checked) + { modiTextOcrFixed = _ocrFixEngine.FixOcrErrors(unItalicText, index, _lastLine, false, GetAutoGuessLevel()); + } + int modiOcrCorrectedCorrectWords; int modiOcrCorrectedWordsNotFound = _ocrFixEngine.CountUnknownWordsViaDictionary(modiTextOcrFixed, out modiOcrCorrectedCorrectWords); if (modiOcrCorrectedWordsNotFound <= modiWordsNotFound) @@ -5693,25 +6338,49 @@ namespace Nikse.SubtitleEdit.Forms.Ocr bool ok = modiWordsNotFound < wordsNotFound || (textWithOutFixes.Length == 1 && modiWordsNotFound == 0); if (!ok) + { ok = wordsNotFound == modiWordsNotFound && unItalicText.EndsWith('!') && (line.EndsWith('l') || line.EndsWith('fl')); + } if (!ok) + { ok = wordsNotFound == modiWordsNotFound && line.StartsWith("", StringComparison.Ordinal) && line.EndsWith("", StringComparison.Ordinal); + } if (ok && Utilities.CountTagInText(unItalicText, '/') > Utilities.CountTagInText(line, '/') + 1) + { ok = false; + } + if (ok && Utilities.CountTagInText(unItalicText, '\\') > Utilities.CountTagInText(line, '\\')) + { ok = false; + } + if (ok && Utilities.CountTagInText(unItalicText, ')') > Utilities.CountTagInText(line, ')') + 1) + { ok = false; + } + if (ok && Utilities.CountTagInText(unItalicText, '(') > Utilities.CountTagInText(line, '(') + 1) + { ok = false; + } + if (ok && Utilities.CountTagInText(unItalicText, '$') > Utilities.CountTagInText(line, '$') + 1) + { ok = false; + } + if (ok && Utilities.CountTagInText(unItalicText, '€') > Utilities.CountTagInText(line, '€') + 1) + { ok = false; + } + if (ok && Utilities.CountTagInText(unItalicText, '•') > Utilities.CountTagInText(line, '•')) + { ok = false; + } if (ok) { @@ -5722,7 +6391,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (line.Length > 7 && unItalicText.Length > 7 && unItalicText.StartsWith("I ", StringComparison.Ordinal) && line.StartsWith(unItalicText.Remove(0, 2).Substring(0, 4), StringComparison.Ordinal)) + { unItalicText = unItalicText.Remove(0, 2); + } if (checkBoxTesseractMusicOn.Checked) { @@ -5736,7 +6407,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = HtmlUtil.RemoveHtmlTags(unItalicText); unItalicText = "♪ " + unItalicText.Remove(0, 2).TrimStart(); if (ita) + { unItalicText = "" + unItalicText + ""; + } } if ((line.StartsWith("J' ", StringComparison.Ordinal) || line.StartsWith("J“ ", StringComparison.Ordinal) || line.StartsWith("J* ", StringComparison.Ordinal) || line.StartsWith("♪ ", StringComparison.Ordinal)) && unItalicText.Length > 3 && HtmlUtil.RemoveOpenCloseTags(unItalicText, HtmlUtil.TagItalic)[2] == ' ') { @@ -5744,7 +6417,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = HtmlUtil.RemoveHtmlTags(unItalicText); unItalicText = "♪ " + unItalicText.Remove(0, 2).TrimStart(); if (ita) + { unItalicText = "" + unItalicText + ""; + } } if (unItalicText.StartsWith("J'", StringComparison.Ordinal) && (line.StartsWith('♪') || textWithOutFixes.StartsWith('♪') || textWithOutFixes.StartsWith("♪", StringComparison.Ordinal) || unItalicText.EndsWith('♪'))) { @@ -5752,7 +6427,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = HtmlUtil.RemoveHtmlTags(unItalicText); unItalicText = "♪ " + unItalicText.Remove(0, 2).TrimStart(); if (ita) + { unItalicText = "" + unItalicText + ""; + } } if ((line.StartsWith("J` ", StringComparison.Ordinal) || line.StartsWith("J“ ", StringComparison.Ordinal) || line.StartsWith("J' ", StringComparison.Ordinal) || line.StartsWith("J* ", StringComparison.Ordinal)) && unItalicText.StartsWith("S ", StringComparison.Ordinal)) { @@ -5760,7 +6437,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = HtmlUtil.RemoveHtmlTags(unItalicText); unItalicText = "♪ " + unItalicText.Remove(0, 2).TrimStart(); if (ita) + { unItalicText = "" + unItalicText + ""; + } } if ((line.StartsWith("J` ", StringComparison.Ordinal) || line.StartsWith("J“ ", StringComparison.Ordinal) || line.StartsWith("J' ", StringComparison.Ordinal) || line.StartsWith("J* ", StringComparison.Ordinal)) && unItalicText.StartsWith("S ", StringComparison.Ordinal)) { @@ -5768,7 +6447,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = HtmlUtil.RemoveHtmlTags(unItalicText); unItalicText = "♪ " + unItalicText.Remove(0, 8).TrimStart(); if (ita) + { unItalicText = "" + unItalicText + ""; + } } if (unItalicText.StartsWith(";'", StringComparison.Ordinal) && (line.StartsWith('♪') || textWithOutFixes.StartsWith('♪') || textWithOutFixes.StartsWith("♪", StringComparison.Ordinal) || unItalicText.EndsWith('♪'))) { @@ -5776,7 +6457,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = HtmlUtil.RemoveHtmlTags(unItalicText); unItalicText = "♪ " + unItalicText.Remove(0, 2).TrimStart(); if (ita) + { unItalicText = "" + unItalicText + ""; + } } if (unItalicText.StartsWith(",{*", StringComparison.Ordinal) && (line.StartsWith('♪') || textWithOutFixes.StartsWith('♪') || textWithOutFixes.StartsWith("♪", StringComparison.Ordinal) || unItalicText.EndsWith('♪'))) { @@ -5784,7 +6467,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = HtmlUtil.RemoveHtmlTags(unItalicText); unItalicText = "♪ " + unItalicText.Remove(0, 3).TrimStart(); if (ita) + { unItalicText = "" + unItalicText + ""; + } } if (unItalicText.EndsWith("J'", StringComparison.Ordinal) && (line.EndsWith('♪') || textWithOutFixes.EndsWith('♪') || textWithOutFixes.EndsWith("♪", StringComparison.Ordinal) || unItalicText.StartsWith('♪'))) @@ -5793,7 +6478,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = HtmlUtil.RemoveHtmlTags(unItalicText); unItalicText = unItalicText.Remove(unItalicText.Length - 3, 2).TrimEnd() + " ♪"; if (ita) + { unItalicText = "" + unItalicText + ""; + } } } @@ -5801,21 +6488,32 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { unItalicText = unItalicText.Remove(0, 1); if (unItalicText.EndsWith(']')) + { unItalicText = unItalicText.TrimEnd(']'); + } } if (unItalicText.StartsWith('{') && !line.StartsWith('{')) { unItalicText = unItalicText.Remove(0, 1); if (unItalicText.EndsWith('}')) + { unItalicText = unItalicText.TrimEnd('}'); + } } if (unItalicText.EndsWith('}') && !line.EndsWith('}')) + { unItalicText = unItalicText.TrimEnd('}'); + } if (line.EndsWith("...", StringComparison.Ordinal) && unItalicText.EndsWith("”!", StringComparison.Ordinal)) + { unItalicText = unItalicText.TrimEnd('!').TrimEnd('”') + "."; + } + if (line.EndsWith("...", StringComparison.Ordinal) && unItalicText.EndsWith("\"!", StringComparison.Ordinal)) + { unItalicText = unItalicText.TrimEnd('!').TrimEnd('"') + "."; + } if (line.EndsWith('.') && !unItalicText.EndsWith('.') && !unItalicText.EndsWith(".", StringComparison.Ordinal)) { @@ -5826,7 +6524,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr unItalicText = unItalicText.Remove(unItalicText.Length - 4); } if (unItalicText.EndsWith('\'') && !line.EndsWith("'.", StringComparison.Ordinal)) + { unItalicText = unItalicText.TrimEnd('\''); + } + unItalicText += "." + post; } if (unItalicText.EndsWith('.') && !unItalicText.EndsWith("...", StringComparison.Ordinal) && !unItalicText.EndsWith("...", StringComparison.Ordinal) && line.EndsWith("...", StringComparison.Ordinal)) @@ -5870,7 +6571,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { w = w.Substring(wIdx + 1); if (!_ocrFixEngine.DoSpell(w)) + { unItalicText = unItalicText.Remove(unItalicText.Length - 5, 1); + } } unItalicText = unItalicText.Insert(unItalicText.Length - 4, "!"); } @@ -5886,7 +6589,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { w = w.Substring(wIdx + 1); if (!_ocrFixEngine.DoSpell(w)) + { unItalicText = unItalicText.Remove(unItalicText.Length - 1, 1); + } } unItalicText += "!"; } @@ -5899,9 +6604,13 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (line.EndsWith('?') && !unItalicText.EndsWith('?') && !unItalicText.EndsWith("?", StringComparison.Ordinal)) { if (unItalicText.EndsWith("?'", StringComparison.Ordinal)) + { unItalicText = unItalicText.TrimEnd('\''); + } else + { unItalicText += "?"; + } } line = HtmlUtil.RemoveOpenCloseTags(unItalicText, HtmlUtil.TagItalic); @@ -5922,9 +6631,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { line = line.Remove(line.Length - 4, 4); if (line.EndsWith('-')) + { line = line.TrimEnd('-') + "."; + } + if (char.IsLetter(line[line.Length - 1])) + { line += "."; + } + line += ""; } } @@ -5935,7 +6650,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (checkBoxTesseractMusicOn.Checked) { if (line == "[J'J'J~]" || line == "[J'J'J']") + { line = "[ ♪ ♪ ♪ ]"; + } line = line.Replace(" J' ", " ♪ "); @@ -5991,7 +6708,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr // Log used word guesses (via word replace list) foreach (string guess in _ocrFixEngine.AutoGuessesUsed) + { listBoxLogSuggestions.Items.Add(guess); + } + _ocrFixEngine.AutoGuessesUsed.Clear(); // Log unkown words guess (found via spelling dictionaries) @@ -6002,7 +6722,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr else { // no dictionary :( if (checkBoxAutoFixCommonErrors.Checked) + { line = _ocrFixEngine.FixOcrErrors(line, index, _lastLine, true, GetAutoGuessLevel()); + } ColorLineByNumberOfUnknownWords(index, badWords, line); } @@ -6015,7 +6737,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (_vobSubMergedPackist != null) + { bitmap.Dispose(); + } return line; } @@ -6024,7 +6748,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { int italicStartCount = Utilities.CountTagInText(s, ""); if (italicStartCount == 0) + { return s; + } s = s.Replace(Environment.NewLine + " ", Environment.NewLine); s = s.Replace(Environment.NewLine + " ", Environment.NewLine); @@ -6040,14 +6766,25 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (s.Contains(" / ")) + { s = s.Replace(" / ", " I ").Replace(" ", " "); + } + if (s.StartsWith("/ ", StringComparison.Ordinal)) + { s = ("I " + s.Remove(0, 5)).Replace(" ", " "); + } + if (s.StartsWith("I ", StringComparison.Ordinal)) + { s = ("I " + s.Remove(0, 5)).Replace(" ", " "); + } else if (italicStartCount == 1 && s.Length > 20 && s.IndexOf("", StringComparison.Ordinal) > 1 && s.IndexOf("", StringComparison.Ordinal) < 10 && s.EndsWith("", StringComparison.Ordinal)) + { s = "" + HtmlUtil.RemoveOpenCloseTags(s, HtmlUtil.TagItalic) + ""; + } + s = s.Replace("" + Environment.NewLine + "", Environment.NewLine); s = s.Replace(" a ", " a "); @@ -6058,7 +6795,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void LogUnknownWords() { foreach (string unknownWord in _ocrFixEngine.UnknownWordsFound) + { listBoxUnknownWords.Items.Add(unknownWord); + } + _ocrFixEngine.UnknownWordsFound.Clear(); } @@ -6093,7 +6833,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var tmp = GetSubtitleBitmap(i); if (tmp == null) + { return string.Empty; + } + bmp = tmp.Clone() as Bitmap; tmp.Dispose(); } @@ -6110,7 +6853,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr modiThread.Abort(); if (!string.IsNullOrEmpty(mp.Text) && mp.Text.Length > 3 && mp.Text.EndsWith(";0]", StringComparison.Ordinal)) + { mp.Text = mp.Text.Substring(0, mp.Text.Length - 3); + } // Try to avoid blank lines by resizing image if (string.IsNullOrEmpty(mp.Text)) @@ -6126,6 +6871,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } int k = 0; while (string.IsNullOrEmpty(mp.Text) && k < 5) + { if (string.IsNullOrEmpty(mp.Text)) { bmp = ResizeBitmap(bmp, (int)(bmp.Width * 1.3), (int)(bmp.Height * 1.4)); // a bit scaling @@ -6138,10 +6884,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr modiThread.Abort(); k++; } + } + if (bmp != null) + { bmp.Dispose(); + } + if (mp.Text != null) + { mp.Text = mp.Text.Replace("•", "o"); + } + return mp.Text; } @@ -6187,7 +6941,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (ocrResult != null) + { paramter.Text = ocrResult.ToString().Trim(); + } } private void InitializeModi() @@ -6217,10 +6973,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Directory.Exists(Configuration.TesseractOriginalDirectory)) { foreach (string dirPath in Directory.GetDirectories(Configuration.TesseractOriginalDirectory, "*", SearchOption.AllDirectories)) + { Directory.CreateDirectory(dirPath.Replace(Configuration.TesseractOriginalDirectory, Configuration.Tesseract302Directory)); + } foreach (string newPath in Directory.GetFiles(Configuration.TesseractOriginalDirectory, "*.*", SearchOption.AllDirectories)) + { File.Copy(newPath, newPath.Replace(Configuration.TesseractOriginalDirectory, Configuration.Tesseract302Directory), true); + } } string dir = _ocrMethodIndex == _ocrMethodTesseract302 ? Configuration.Tesseract302DataDirectory : Configuration.TesseractDataDirectory; @@ -6233,18 +6993,30 @@ namespace Nikse.SubtitleEdit.Forms.Ocr string tesseractName = culture.ThreeLetterISOLanguageName; var trainDataFileName = Path.Combine(dir, tesseractName + ".traineddata"); if (culture.LCID == 0x4 && !File.Exists(trainDataFileName)) + { tesseractName = "chi_sim"; + } else if (culture.Name == "zh-CHT" && !File.Exists(trainDataFileName)) + { tesseractName = "chi_tra"; + } else if (tesseractName == "fas" && !File.Exists(trainDataFileName)) + { tesseractName = "per"; + } else if (tesseractName == "nob" && !File.Exists(trainDataFileName)) + { tesseractName = "nor"; + } + trainDataFileName = Path.Combine(dir, tesseractName + ".traineddata"); if (!list.Contains(culture.ThreeLetterISOLanguageName) && File.Exists(trainDataFileName)) { if (culture.ThreeLetterISOLanguageName != "zho") + { list.Add(culture.ThreeLetterISOLanguageName); + } + comboBoxTesseractLanguages.Items.Add(new TesseractLanguage { Id = tesseractName, Text = culture.EnglishName }); } } @@ -6270,7 +7042,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (comboBoxTesseractLanguages.SelectedIndex == -1) + { comboBoxTesseractLanguages.SelectedIndex = 0; + } } } @@ -6280,14 +7054,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { comboBoxModiLanguage.Items.Add(ml); if (ml.Id == _vobSubOcrSettings.LastModiLanguageId) + { comboBoxModiLanguage.SelectedIndex = comboBoxModiLanguage.Items.Count - 1; + } } } private int GetModiLanguage() { if (comboBoxModiLanguage.SelectedIndex < 0) + { return ModiLanguage.DefaultLanguageId; + } return ((ModiLanguage)comboBoxModiLanguage.SelectedItem).Id; } @@ -6350,9 +7128,13 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private static void FixVerticalScrollBars(TextBox tb) { if (Utilities.GetNumberOfLines(tb.Text) > 5) + { tb.ScrollBars = ScrollBars.Vertical; + } else + { tb.ScrollBars = ScrollBars.None; + } } private void ButtonNewCharacterDatabaseClick(object sender, EventArgs e) @@ -6400,7 +7182,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr LoadImageCompareBitmaps(); if (_vobSubOcrSettings != null) + { _vobSubOcrSettings.LastImageCompareFolder = comboBoxCharacterDatabase.SelectedItem.ToString(); + } bool lineWidthVisible = !comboBoxCharacterDatabase.SelectedItem.ToString().Equals("Latin", StringComparison.Ordinal); labelMinLineSplitHeight.Visible = lineWidthVisible; @@ -6436,14 +7220,20 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _compareDoc.Save(path + "Images.xml"); Cursor = Cursors.WaitCursor; if (formVobSubEditCharacters.ChangesMade) + { _binaryOcrDb.LoadCompareImages(); + } + Cursor = Cursors.Default; } return result; } Cursor = Cursors.WaitCursor; if (formVobSubEditCharacters.ChangesMade) + { _binaryOcrDb.LoadCompareImages(); + } + Cursor = Cursors.Default; return result; } @@ -6528,7 +7318,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr File.Exists(Path.Combine(Configuration.Tesseract302DataDirectory, l + ".traineddata")); checkBoxTesseractFallback.Visible = ok; if (!ok) + { checkBoxTesseractFallback.Checked = false; + } } else if (_ocrMethodIndex == _ocrMethodTesseract302) { @@ -6536,7 +7328,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr File.Exists(Path.Combine(Configuration.TesseractDataDirectory, l + ".traineddata")); checkBoxTesseractFallback.Visible = ok; if (!ok) + { checkBoxTesseractFallback.Checked = false; + } } } @@ -6606,9 +7400,13 @@ namespace Nikse.SubtitleEdit.Forms.Ocr else { if (comboBoxDictionaries.SelectedIndex < 0) + { comboBoxDictionaries.SelectedIndex = 0; + } else + { comboBoxDictionaries_SelectedIndexChanged(null, null); + } } comboBoxModiLanguage.SelectedIndex = -1; } @@ -6683,12 +7481,17 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string s = Path.GetFileNameWithoutExtension(fileName); if (s == Configuration.Settings.VobSubOcr.LineOcrLastLanguages) + { selIndex = index; + } + comboBoxNOcrLanguage.Items.Add(s); index++; } if (comboBoxNOcrLanguage.Items.Count > 0) + { comboBoxNOcrLanguage.SelectedIndex = selIndex; + } } else if (_ocrMethodIndex == _ocrMethodBinaryImageCompare) { @@ -6711,7 +7514,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private string GetNOcrLanguageFileName() { if (comboBoxNOcrLanguage.SelectedIndex < 0) + { return null; + } return Configuration.OcrDirectory + comboBoxNOcrLanguage.Items[comboBoxNOcrLanguage.SelectedIndex] + ".nocr"; } @@ -6733,7 +7538,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var lb = sender as ListBox; if (lb == null || lb.SelectedIndex < 0) + { return; + } string text = lb.Items[lb.SelectedIndex].ToString(); if (text.Contains(':')) @@ -6746,7 +7553,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void ContextMenuStripListviewOpening(object sender, CancelEventArgs e) { if (subtitleListView1.SelectedItems.Count == 0) + { e.Cancel = true; + } // Enable toolstrips if event was raised by Subtitle listview. bool enableIfRaisedBySubListView = contextMenuStripListview.SourceControl == subtitleListView1; @@ -6789,13 +7598,21 @@ namespace Nikse.SubtitleEdit.Forms.Ocr try { if (saveFileDialog1.FilterIndex == 0) + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png); + } else if (saveFileDialog1.FilterIndex == 1) + { bmp.Save(saveFileDialog1.FileName); + } else if (saveFileDialog1.FilterIndex == 2) + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Gif); + } else + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Tiff); + } } catch (Exception exception) { @@ -6820,7 +7637,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr p.Text = HtmlUtil.RemoveHtmlTags(p.Text); subtitleListView1.SetText(item.Index, p.Text); if (item.Index == _selectedIndex) + { textBoxCurrentText.Text = p.Text; + } } } } @@ -6844,7 +7663,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr p.Text = $"<{tag}>{p.Text}"; subtitleListView1.SetText(item.Index, p.Text); if (item.Index == _selectedIndex) + { textBoxCurrentText.Text = p.Text; + } } } } @@ -6882,7 +7703,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_tesseractAsyncStrings != null) { for (int i = 0; i < _tesseractAsyncStrings.Length; i++) + { _tesseractAsyncStrings[i] = string.Empty; + } } _tesseractAsyncIndex = 0; } @@ -6890,7 +7713,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void PictureBoxColorChooserClick(object sender, EventArgs e) { if (colorDialog1.ShowDialog(this) == DialogResult.OK) + { (sender as PictureBox).BackColor = colorDialog1.Color; + } + SubtitleListView1SelectedIndexChanged(null, null); ResetTesseractThread(); } @@ -6938,11 +7764,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr subtitleListView1.BeginUpdate(); if (_bdnXmlOriginal != null) + { LoadBdnXml(); + } else if (_bluRaySubtitlesOriginal != null) + { LoadBluRaySup(); + } else + { LoadVobRip(); + } + for (int i = 0; i < _subtitle.Paragraphs.Count; i++) { Paragraph current = _subtitle.Paragraphs[i]; @@ -6996,7 +7829,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr get { if (comboBoxDictionaries.SelectedItem == null) + { return null; + } string name = comboBoxDictionaries.SelectedItem.ToString(); int start = name.LastIndexOf('['); @@ -7014,13 +7849,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void SetSpellCheckLanguage(string languageString) { if (string.IsNullOrEmpty(languageString)) + { return; + } int i = 0; foreach (string item in comboBoxDictionaries.Items) { if (item.Contains("[" + languageString + "]")) + { comboBoxDictionaries.SelectedIndex = i; + } + i++; } } @@ -7029,7 +7869,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { Configuration.Settings.General.SpellCheckLanguage = LanguageString; if (_ocrMethodIndex == _ocrMethodTesseract4 || _ocrMethodIndex == _ocrMethodTesseract302) + { Configuration.Settings.VobSubOcr.LastTesseractSpellCheck = LanguageString; + } string threeLetterIsoLanguageName = string.Empty; if (LanguageString == null) @@ -7066,7 +7908,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr internal void Initialize(Subtitle bdnSubtitle, VobSubOcrSettings vobSubOcrSettings, bool isSon) { if (!string.IsNullOrEmpty(bdnSubtitle.FileName) && bdnSubtitle.FileName != new Subtitle().FileName) + { FileName = bdnSubtitle.FileName; + } + _bdnXmlOriginal = bdnSubtitle; _bdnFileName = bdnSubtitle.FileName; _isSon = isSon; @@ -7108,17 +7953,29 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void SetOcrMethod() { if (Configuration.Settings.VobSubOcr.LastOcrMethod == "BinaryImageCompare" && comboBoxOcrMethod.Items.Count > _ocrMethodBinaryImageCompare) + { comboBoxOcrMethod.SelectedIndex = _ocrMethodBinaryImageCompare; + } else if (Configuration.Settings.VobSubOcr.LastOcrMethod == "MODI" && comboBoxOcrMethod.Items.Count > _ocrMethodModi) + { comboBoxOcrMethod.SelectedIndex = _ocrMethodModi; + } else if (Configuration.Settings.VobSubOcr.LastOcrMethod == "nOCR" && comboBoxOcrMethod.Items.Count > _ocrMethodNocr) + { comboBoxOcrMethod.SelectedIndex = _ocrMethodNocr; + } else if (Configuration.Settings.VobSubOcr.LastOcrMethod == "Tesseract302" && comboBoxOcrMethod.Items.Count > _ocrMethodTesseract302) + { comboBoxOcrMethod.SelectedIndex = _ocrMethodTesseract302; + } else if (Configuration.Settings.VobSubOcr.LastOcrMethod == "Tesseract4" && comboBoxOcrMethod.Items.Count > _ocrMethodTesseract302) + { comboBoxOcrMethod.SelectedIndex = _ocrMethodTesseract4; + } else + { comboBoxOcrMethod.SelectedIndex = 0; + } } internal void StartOcrFromDelayed() @@ -7160,7 +8017,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string fileName = openFileDialog1.FileName; if (!File.Exists(fileName)) + { return; + } var fi = new FileInfo(fileName); if (fi.Length > 1024 * 1024 * 10) // max 10 mb @@ -7169,14 +8028,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Environment.NewLine + Configuration.Settings.Language.Main.ContinueAnyway, fileName), Text, MessageBoxButtons.YesNoCancel) != DialogResult.Yes) + { return; + } } Subtitle sub = new Subtitle(); Encoding encoding; SubtitleFormat format = sub.LoadSubtitle(fileName, out encoding, null); if (format == null) + { return; + } int index = 0; foreach (Paragraph p in sub.Paragraphs) @@ -7248,10 +8111,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void InspectImageCompareMatchesForCurrentImageToolStripMenuItem_Click(object sender, EventArgs e) { if (subtitleListView1.SelectedItems.Count != 1) + { return; + } if (_compareBitmaps == null) + { LoadImageCompareBitmaps(); + } Cursor = Cursors.WaitCursor; Bitmap bitmap = GetSubtitleBitmap(subtitleListView1.SelectedItems[0].Index); @@ -7267,7 +8134,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { int minLineHeight = _binOcrLastLowercaseHeight - 3; if (comboBoxLineSplitMinLineHeight.Visible && comboBoxLineSplitMinLineHeight.SelectedIndex > 0) + { minLineHeight = int.Parse(comboBoxLineSplitMinLineHeight.Text); + } + minLineHeight = Math.Max(minLineHeight, 6); sourceList = NikseBitmapImageSplitter.SplitBitmapToLettersNew(parentBitmap, (int)numericUpDownPixelsIsSpace.Value, checkBoxRightToLeft.Checked, Configuration.Settings.VobSubOcr.TopToBottom, minLineHeight); } @@ -7286,9 +8156,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { CompareMatch match; if (_binaryOcrDb != null) + { match = GetCompareMatchNew(item, out _, sourceList, index); + } else + { match = GetCompareMatch(item, parentBitmap, out _, sourceList, index); + } + if (match == null) { matches.Add(new CompareMatch(Configuration.Settings.Language.VobSubOcr.NoMatch, false, 0, null)); @@ -7314,7 +8189,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (match.ExpandCount > 0) + { index += match.ExpandCount - 1; + } } } index++; @@ -7370,9 +8247,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr ResetTesseractThread(); SubtitleListView1SelectedIndexChanged(null, null); if (checkBoxAutoTransparentBackground.Checked && _dvbSubtitles != null) + { numericUpDownAutoTransparentAlphaMax.Visible = true; + } else + { numericUpDownAutoTransparentAlphaMax.Visible = false; + } + labelMinAlpha.Visible = numericUpDownAutoTransparentAlphaMax.Visible; } @@ -7398,7 +8280,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _palette = palette; if (_palette == null) + { checkBoxCustomFourColors.Checked = true; + } SetOcrMethod(); @@ -7458,7 +8342,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr LoadImageCompareCharacterDatabaseList(); if (_palette == null) + { checkBoxCustomFourColors.Checked = true; + } SetOcrMethod(); @@ -7560,7 +8446,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Configuration.Settings.VobSubOcr.UseItalicsInTesseract = checkBoxTesseractItalicsOn.Checked; if (comboBoxTesseractEngineMode.SelectedIndex != -1) + { Configuration.Settings.VobSubOcr.TesseractEngineMode = comboBoxTesseractEngineMode.SelectedIndex; + } + Configuration.Settings.VobSubOcr.ItalicFactor = _unItalicFactor; Configuration.Settings.VobSubOcr.PromptForUnknownWords = checkBoxPromptForUnknownWords.Checked; Configuration.Settings.VobSubOcr.GuessUnknownWords = checkBoxGuessUnknownWords.Checked; @@ -7573,9 +8462,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_ocrMethodIndex == _ocrMethodBinaryImageCompare) { if (comboBoxCharacterDatabase.SelectedItem != null) + { Configuration.Settings.VobSubOcr.LastBinaryImageCompareDb = comboBoxCharacterDatabase.SelectedItem.ToString(); + } + if (comboBoxDictionaries.SelectedItem != null) + { Configuration.Settings.VobSubOcr.LastBinaryImageSpellCheck = comboBoxDictionaries.SelectedItem.ToString(); + } } if (_ocrMethodIndex == _ocrMethodTesseract4 || _ocrMethodTesseract4 == _ocrMethodTesseract302) @@ -7584,15 +8478,21 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (_bluRaySubtitlesOriginal != null) + { Configuration.Settings.VobSubOcr.BlurayAllowDifferenceInPercent = (double)numericUpDownMaxErrorPct.Value; + } else + { Configuration.Settings.VobSubOcr.AllowDifferenceInPercent = (double)numericUpDownMaxErrorPct.Value; + } if (_ocrMethodIndex == _ocrMethodNocr) { Configuration.Settings.VobSubOcr.LineOcrLastSpellCheck = LanguageString; if (comboBoxNOcrLanguage.Items.Count > 0 && comboBoxNOcrLanguage.SelectedIndex >= 0) + { Configuration.Settings.VobSubOcr.LineOcrLastLanguages = comboBoxNOcrLanguage.Items[comboBoxNOcrLanguage.SelectedIndex].ToString(); + } } } @@ -7634,53 +8534,77 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void DeleteToolStripMenuItemClick(object sender, EventArgs e) { if (subtitleListView1.SelectedItems.Count == 0) + { return; + } string askText; if (subtitleListView1.SelectedItems.Count > 1) + { askText = string.Format(Configuration.Settings.Language.Main.DeleteXLinesPrompt, subtitleListView1.SelectedItems.Count); + } else + { askText = Configuration.Settings.Language.Main.DeleteOneLinePrompt; + } + if (Configuration.Settings.General.PromptDeleteLines && MessageBox.Show(askText, "", MessageBoxButtons.YesNo) == DialogResult.No) + { return; + } ResetTesseractThread(); int selIdx = subtitleListView1.SelectedItems[0].Index; List indices = new List(); foreach (int idx in subtitleListView1.SelectedIndices) + { indices.Add(idx); + } + indices.Reverse(); if (_mp4List != null) { foreach (int idx in indices) + { _mp4List.RemoveAt(idx); + } } else if (_spList != null) { foreach (int idx in indices) + { _spList.RemoveAt(idx); + } } else if (_dvbSubtitles != null) { foreach (int idx in indices) + { _dvbSubtitles.RemoveAt(idx); + } } else if (_dvbPesSubtitles != null) { foreach (int idx in indices) + { _dvbPesSubtitles.RemoveAt(idx); + } } else if (_bdnXmlSubtitle != null) { foreach (int idx in indices) + { _bdnXmlSubtitle.Paragraphs.RemoveAt(idx); + } } else if (_xSubList != null) { foreach (int idx in indices) + { _xSubList.RemoveAt(idx); + } } else if (_bluRaySubtitlesOriginal != null) { @@ -7722,19 +8646,28 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } foreach (int idx in indices) + { _subtitle.Paragraphs.RemoveAt(idx); + } + subtitleListView1.Fill(_subtitle); if (selIdx < subtitleListView1.Items.Count) + { subtitleListView1.SelectIndexAndEnsureVisible(selIdx, true); + } else + { subtitleListView1.SelectIndexAndEnsureVisible(subtitleListView1.Items.Count - 1, true); + } subtitleListView1.BeginUpdate(); foreach (var p in _subtitle.Paragraphs) { if (_unknownWordsDictionary.ContainsKey(p.ID)) + { SetUnknownWordsColor(_subtitle.Paragraphs.IndexOf(p), _unknownWordsDictionary[p.ID], p.Text); + } } subtitleListView1.EndUpdate(); } @@ -7747,7 +8680,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (text.Contains(':')) { if (_ocrFixEngine == null) + { comboBoxDictionaries_SelectedIndexChanged(null, null); + } text = text.Substring(text.IndexOf(':') + 1).Trim(); using (var form = new AddToNameList()) @@ -7771,7 +8706,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void UpdateUnknownWordColoring(string name, StringComparison comparison) { if (string.IsNullOrEmpty(name)) + { return; + } for (int i = 0; i < _subtitle.Paragraphs.Count; i++) { @@ -7899,7 +8836,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_ocrMethodIndex == _ocrMethodTesseract4) { - using (var form = new OcrPreprocessingT4(bmp, _ocrMethodIndex == _ocrMethodBinaryImageCompare, new PreprocessingSettings { BinaryImageCompareThresshold = Configuration.Settings.Tools.OcrTesseract4RgbThreshold })) + using (var form = new OcrPreprocessingT4(bmp, new PreprocessingSettings { BinaryImageCompareThresshold = Configuration.Settings.Tools.OcrTesseract4RgbThreshold })) { if (form.ShowDialog(this) == DialogResult.OK) { @@ -7987,7 +8924,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void toolStripMenuItemInspectNOcrMatches_Click(object sender, EventArgs e) { if (subtitleListView1.SelectedItems.Count != 1) + { return; + } if (_nOcrDb == null) { @@ -8053,10 +8992,16 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string s = newFolder.FolderName; if (string.IsNullOrEmpty(s)) + { return; + } + s = s.RemoveChar('?').RemoveChar('/').RemoveChar('*').RemoveChar('\\'); if (string.IsNullOrEmpty(s)) + { return; + } + if (File.Exists(Configuration.DictionariesDirectory + "nOCR_" + newFolder.FolderName + ".xml")) { MessageBox.Show("Line OCR language file already exists!"); @@ -8096,7 +9041,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } if (comboBoxDictionaries.Items.Count > 0) + { comboBoxDictionaries.SelectedIndex = 0; + } } private void ShowStatus(string msg) @@ -8304,7 +9251,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var autoGuessLevel = OcrFixEngine.AutoGuessLevel.None; if (checkBoxGuessUnknownWords.Checked) + { autoGuessLevel = OcrFixEngine.AutoGuessLevel.Aggressive; + } + return autoGuessLevel; } @@ -8317,7 +9267,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { string fileName = openFileDialog1.FileName; if (!File.Exists(fileName)) + { return; + } var fi = new FileInfo(fileName); if (fi.Length > 1024 * 1024 * 10) // max 10 mb @@ -8326,13 +9278,17 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Environment.NewLine + Configuration.Settings.Language.Main.ContinueAnyway, fileName), Text, MessageBoxButtons.YesNoCancel) != DialogResult.Yes) + { return; + } } var sub = new Subtitle(); SubtitleFormat format = sub.LoadSubtitle(fileName, out _, null); if (format == null) + { return; + } int index = 0; int newSubCount = sub.Paragraphs.Count; @@ -8388,7 +9344,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void comboBoxTesseractEngineMode_SelectedIndexChanged(object sender, EventArgs e) { if (_tesseractAsyncStrings != null) + { _tesseractAsyncStrings = new string[GetSubtitleCount()]; + } } private void toolStripMenuItemSaveSubtitleAs_Click(object sender, EventArgs e) diff --git a/src/Forms/Ocr/VobSubOcrCharacter.cs b/src/Forms/Ocr/VobSubOcrCharacter.cs index 05e921f7d..2aff50e24 100644 --- a/src/Forms/Ocr/VobSubOcrCharacter.cs +++ b/src/Forms/Ocr/VobSubOcrCharacter.cs @@ -43,29 +43,11 @@ namespace Nikse.SubtitleEdit.Forms.Ocr UiUtil.FixLargeFonts(this, buttonCancel); } - public string ManualRecognizedCharacters - { - get - { - return textBoxCharacters.Text; - } - } + public string ManualRecognizedCharacters => textBoxCharacters.Text; - public bool IsItalic - { - get - { - return checkBoxItalic.Checked; - } - } + public bool IsItalic => checkBoxItalic.Checked; - public Point FormPosition - { - get - { - return new Point(Left, Top); - } - } + public Point FormPosition => new Point(Left, Top); public bool ExpandSelection { get; private set; } @@ -108,9 +90,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr var last = _additions[_additions.Count - 1]; buttonLastEdit.Visible = true; if (last.Italic) + { buttonLastEdit.Font = new Font(buttonLastEdit.Font.FontFamily, buttonLastEdit.Font.Size, FontStyle.Italic); + } else + { buttonLastEdit.Font = new Font(buttonLastEdit.Font.FontFamily, buttonLastEdit.Font.Size); + } + pictureBoxLastEdit.Visible = true; pictureBoxLastEdit.Image = last.Image.GetBitmap(); buttonLastEdit.Text = string.Format(Configuration.Settings.Language.VobSubOcrCharacter.EditLastX, last.Text); @@ -147,9 +134,13 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void TextBoxCharactersKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) + { DialogResult = DialogResult.OK; + } else if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } private void CheckBoxItalicCheckedChanged(object sender, EventArgs e) @@ -211,15 +202,18 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void InsertLanguageCharacter(object sender, EventArgs e) { - var toolStripMenuItem = sender as ToolStripMenuItem; - if (toolStripMenuItem != null) + if (sender is ToolStripMenuItem toolStripMenuItem) + { textBoxCharacters.Text = textBoxCharacters.Text.Insert(textBoxCharacters.SelectionStart, toolStripMenuItem.Text); + } } private void textBoxCharacters_TextChanged(object sender, EventArgs e) { if (checkBoxAutoSubmitOfFirstChar.Checked && textBoxCharacters.Text.Length > 0) + { DialogResult = DialogResult.OK; + } } private void VobSubOcrCharacter_Shown(object sender, EventArgs e) diff --git a/src/Forms/Ocr/VobSubOcrCharacterInspect.cs b/src/Forms/Ocr/VobSubOcrCharacterInspect.cs index 2970d0a93..3f5a6b0bc 100644 --- a/src/Forms/Ocr/VobSubOcrCharacterInspect.cs +++ b/src/Forms/Ocr/VobSubOcrCharacterInspect.cs @@ -58,15 +58,25 @@ namespace Nikse.SubtitleEdit.Forms.Ocr ImageCompareDocument = new XmlDocument(); _directoryPath = Configuration.VobSubCompareDirectory + databaseFolderName + Path.DirectorySeparatorChar; if (!File.Exists(_directoryPath + "Images.xml")) + { ImageCompareDocument.LoadXml(""); + } else + { ImageCompareDocument.Load(_directoryPath + "Images.xml"); + } } for (int i = 0; i < _matches.Count; i++) + { listBoxInspectItems.Items.Add(_matches[i]); + } + if (listBoxInspectItems.Items.Count > 0) + { listBoxInspectItems.SelectedIndex = 0; + } + ShowCount(); } @@ -76,7 +86,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr labelExpandCount.Text = string.Empty; if (listBoxInspectItems.SelectedIndex < 0) + { return; + } _selectedCompareNode = null; _selectedCompareBinaryOcrBitmap = null; @@ -208,14 +220,19 @@ namespace Nikse.SubtitleEdit.Forms.Ocr pictureBoxCompareBitmapDouble.Visible = false; labelDoubleSize.Visible = false; if (img == null) + { buttonAddBetterMatch.Enabled = false; + } } else { buttonUpdate.Enabled = true; buttonDelete.Enabled = true; if (_selectedCompareNode != null) + { buttonAddBetterMatch.Enabled = true; + } + textBoxText.Enabled = true; checkBoxItalic.Enabled = true; pictureBoxCompareBitmap.Visible = true; @@ -237,7 +254,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void buttonUpdate_Click(object sender, EventArgs e) { if (_selectedCompareNode == null && _selectedCompareBinaryOcrBitmap == null) + { return; + } string newText = textBoxText.Text; @@ -260,9 +279,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _selectedCompareBinaryOcrBitmap.Italic = checkBoxItalic.Checked; listBoxInspectItems.SelectedIndexChanged -= listBoxInspectItems_SelectedIndexChanged; if (checkBoxItalic.Checked) + { listBoxInspectItems.Items[listBoxInspectItems.SelectedIndex] = newText + " (italic)"; + } else + { listBoxInspectItems.Items[listBoxInspectItems.SelectedIndex] = newText; + } + listBoxInspectItems.SelectedIndexChanged += listBoxInspectItems_SelectedIndexChanged; } else @@ -281,7 +305,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void SetItalic(XmlNode node) { if (node?.Attributes == null || node.OwnerDocument == null) + { return; + } if (checkBoxItalic.Checked) { @@ -304,15 +330,22 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void buttonDelete_Click(object sender, EventArgs e) { if (_selectedCompareNode == null && _selectedCompareBinaryOcrBitmap == null) + { return; + } listBoxInspectItems.Items[listBoxInspectItems.SelectedIndex] = Configuration.Settings.Language.VobSubOcr.NoMatch; if (_selectedCompareBinaryOcrBitmap != null) { if (_selectedCompareBinaryOcrBitmap.ExpandCount > 0) + { _binOcrDb.CompareImagesExpanded.Remove(_selectedCompareBinaryOcrBitmap); + } else + { _binOcrDb.CompareImages.Remove(_selectedCompareBinaryOcrBitmap); + } + _selectedCompareBinaryOcrBitmap = null; _binOcrDb.Save(); } @@ -327,7 +360,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void buttonAddBetterMatch_Click(object sender, EventArgs e) { if (listBoxInspectItems.SelectedIndex < 0) + { return; + } if (listBoxInspectItems.Items[listBoxInspectItems.SelectedIndex].ToString().Replace(" (italic)", string.Empty) == textBoxText.Text) { @@ -382,7 +417,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _matches[index].Text = textBoxText.Text; listBoxInspectItems.Items.Clear(); for (int i = 0; i < _matches.Count; i++) + { listBoxInspectItems.Items.Add(_matches[i].Text); + } + listBoxInspectItems.SelectedIndex = index; listBoxInspectItems_SelectedIndexChanged(null, null); ShowCount(); @@ -446,7 +484,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _matches[index].Text = textBoxText.Text; listBoxInspectItems.Items.Clear(); for (int i = 0; i < _matches.Count; i++) + { listBoxInspectItems.Items.Add(_matches[i].Text); + } + listBoxInspectItems.SelectedIndex = index; ShowCount(); listBoxInspectItems_SelectedIndexChanged(null, null); @@ -471,7 +512,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (listBoxInspectItems.SelectedIndex < 0 || listBoxInspectItems.SelectedIndex == listBoxInspectItems.Items.Count - 1 || _binOcrDb == null || - (_selectedCompareBinaryOcrBitmap != null && _selectedCompareBinaryOcrBitmap.ExpandCount > 1)) + _selectedCompareBinaryOcrBitmap != null && _selectedCompareBinaryOcrBitmap.ExpandCount > 1) { e.Cancel = true; return; diff --git a/src/Forms/Ocr/VobSubOcrNOcrCharacter.cs b/src/Forms/Ocr/VobSubOcrNOcrCharacter.cs index 3e35072b1..4ddfdf157 100644 --- a/src/Forms/Ocr/VobSubOcrNOcrCharacter.cs +++ b/src/Forms/Ocr/VobSubOcrNOcrCharacter.cs @@ -10,7 +10,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { public partial class VobSubOcrNOcrCharacter : Form { - private NOcrChar _nocrChar = null; + private NOcrChar _nocrChar; private bool _drawLineOn; private bool _startDone; private Point _start; @@ -20,7 +20,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private int _imageHeight; private int _mx; private int _my; - private bool _warningNoNotForegroundLinesShown = false; + private bool _warningNoNotForegroundLinesShown; private List _history = new List(); private int _historyIndex = -1; @@ -33,33 +33,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr labelItalicOn.Visible = false; } - public NOcrChar NOcrChar - { - get - { - return _nocrChar; - } - } + public NOcrChar NOcrChar => _nocrChar; - public Point FormPosition - { - get - { - return new Point(Left, Top); - } - } + public Point FormPosition => new Point(Left, Top); public bool ExpandSelection { get; private set; } public bool ShrinkSelection { get; private set; } - public bool IsItalic - { - get - { - return checkBoxItalic.Checked; - } - } + public bool IsItalic => checkBoxItalic.Checked; internal void Initialize(Bitmap vobSubImage, ImageSplitterItem character, Point position, bool italicChecked, bool showShrink) { @@ -74,8 +56,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr ExpandSelection = false; textBoxCharacters.Text = string.Empty; - _nocrChar = new NOcrChar(); - _nocrChar.MarginTop = character.Y - character.ParentY; + _nocrChar = new NOcrChar { MarginTop = character.Y - character.ParentY }; _imageWidth = character.NikseBitmap.Width; _imageHeight = character.NikseBitmap.Height; _drawLineOn = false; @@ -215,10 +196,15 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Point start = op.GetScaledStart(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height); Point end = op.GetScaledEnd(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height); if (start.X == end.X && start.Y == end.Y) + { end.X++; + } + e.Graphics.DrawLine(foreground, start, end); if (op == selectedPoint) + { e.Graphics.DrawLine(selPenF, op.GetScaledStart(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height), op.GetScaledEnd(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height)); + } } foreach (NOcrPoint op in _nocrChar.LinesBackground) { @@ -226,7 +212,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr Point end = op.GetScaledEnd(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height); e.Graphics.DrawLine(background, start, end); if (op == selectedPoint) + { e.Graphics.DrawLine(selPenB, op.GetScaledStart(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height), op.GetScaledEnd(_nocrChar, pictureBoxCharacter.Width, pictureBoxCharacter.Height)); + } } } @@ -236,7 +224,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { var p = foreground; if (radioButtonCold.Checked) + { p = background; + } + e.Graphics.DrawLine(p, new Point((int)Math.Round(_start.X * _zoomFactor), (int)Math.Round(_start.Y * _zoomFactor)), new Point(_mx, _my)); } } @@ -297,9 +288,14 @@ namespace Nikse.SubtitleEdit.Forms.Ocr _nocrChar.Width = pictureBoxCharacter.Image.Width; _nocrChar.Height = pictureBoxCharacter.Image.Height; if (radioButtonHot.Checked) + { _nocrChar.LinesForeground.Add(new NOcrPoint(_start, _end)); + } else + { _nocrChar.LinesBackground.Add(new NOcrPoint(_start, _end)); + } + _drawLineOn = false; pictureBoxCharacter.Invalidate(); ShowOcrPoints(); @@ -335,7 +331,10 @@ namespace Nikse.SubtitleEdit.Forms.Ocr if (_historyIndex > 0 && _historyIndex < _history.Count - 1) { while (_history.Count > _historyIndex + 1) + { _history.RemoveAt(_history.Count - 1); + } + _historyIndex = _history.Count - 1; } _history.Add(new NOcrChar(nocrChar)); @@ -435,7 +434,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private static bool IsMatchPointForeGround(NOcrPoint op, bool loose, NikseBitmap nbmp, NOcrChar nOcrChar) { if (Math.Abs(op.Start.X - op.End.X) < 2 && Math.Abs(op.End.Y - op.Start.Y) < 2) + { return false; + } foreach (Point point in op.ScaledGetPoints(nOcrChar, nbmp.Width, nbmp.Height)) { @@ -607,7 +608,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { if (existingOp.Start.X == op.Start.X && existingOp.Start.Y == op.Start.Y && existingOp.End.X == op.End.X && existingOp.End.Y == op.End.Y) + { ok = false; + } } if (ok && IsMatchPointForeGround(op, !tempVeryPrecise, nbmp, nOcrChar)) { @@ -617,7 +620,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr } count++; if (count > giveUpCount - 100 && !tempVeryPrecise) + { tempVeryPrecise = true; + } } count = 0; @@ -663,7 +668,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { if (existingOp.Start.X == op.Start.X && existingOp.Start.Y == op.Start.Y && existingOp.End.X == op.End.X && existingOp.End.Y == op.End.Y) + { ok = false; + } } if (ok && IsMatchPointBackGround(op, !tempVeryPrecise, nbmp, nOcrChar)) { @@ -674,7 +681,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr count++; if (count > giveUpCount - 100 && !tempVeryPrecise) + { tempVeryPrecise = true; + } } } diff --git a/src/Forms/Ocr/VobSubOcrNewFolder.cs b/src/Forms/Ocr/VobSubOcrNewFolder.cs index 32375d696..c9e294e54 100644 --- a/src/Forms/Ocr/VobSubOcrNewFolder.cs +++ b/src/Forms/Ocr/VobSubOcrNewFolder.cs @@ -9,7 +9,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr public sealed partial class VobSubOcrNewFolder : Form { public string FolderName { get; set; } - private bool _vobSub = false; + private readonly bool _vobSub; public VobSubOcrNewFolder(bool vobsub) { UiUtil.PreInitialize(this); @@ -28,7 +28,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void FormVobSubOcrNewFolder_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } private void ButtonOkClick(object sender, EventArgs e) @@ -73,7 +75,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void TextBoxFolderKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) + { ButtonOkClick(null, null); + } } } } diff --git a/src/Forms/Ocr/VobSubOcrSetItalicFactor.cs b/src/Forms/Ocr/VobSubOcrSetItalicFactor.cs index c319a83bb..b70907f17 100644 --- a/src/Forms/Ocr/VobSubOcrSetItalicFactor.cs +++ b/src/Forms/Ocr/VobSubOcrSetItalicFactor.cs @@ -8,7 +8,7 @@ namespace Nikse.SubtitleEdit.Forms.Ocr { public sealed partial class VobSubOcrSetItalicFactor : Form { - private Bitmap _bmp; + private readonly Bitmap _bmp; private double _factor; public VobSubOcrSetItalicFactor(Bitmap bmp, double factor) @@ -52,7 +52,9 @@ namespace Nikse.SubtitleEdit.Forms.Ocr private void VobSubOcrSetItalicFactor_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } private void saveImageAsToolStripMenuItem_Click(object sender, EventArgs e) @@ -76,13 +78,21 @@ namespace Nikse.SubtitleEdit.Forms.Ocr try { if (saveFileDialog1.FilterIndex == 0) + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png); + } else if (saveFileDialog1.FilterIndex == 1) + { bmp.Save(saveFileDialog1.FileName); + } else if (saveFileDialog1.FilterIndex == 2) + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Gif); + } else + { bmp.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Tiff); + } } catch (Exception exception) { diff --git a/src/Forms/Styles/StylesForm.cs b/src/Forms/Styles/StylesForm.cs index 85411c7f9..b8ee80874 100644 --- a/src/Forms/Styles/StylesForm.cs +++ b/src/Forms/Styles/StylesForm.cs @@ -6,7 +6,6 @@ namespace Nikse.SubtitleEdit.Forms.Styles { public /* abstract */ class StylesForm : Form { - private readonly Subtitle _subtitle; private readonly Timer _previewTimer = new Timer(); private StylesForm() @@ -16,24 +15,15 @@ namespace Nikse.SubtitleEdit.Forms.Styles protected StylesForm(Subtitle subtitle) { - _subtitle = subtitle; + Subtitle = subtitle; _previewTimer.Interval = 200; _previewTimer.Tick += PreviewTimerTick; } - public virtual string Header - { - get - { - throw new NotImplementedException("This property getter has to be overridden."); - } - } + public virtual string Header => throw new NotImplementedException("This property getter has to be overridden."); - protected Subtitle Subtitle - { - get { return _subtitle; } - } + protected Subtitle Subtitle { get; } protected void GeneratePreview() { diff --git a/src/Forms/Styles/SubStationAlphaStyles.cs b/src/Forms/Styles/SubStationAlphaStyles.cs index f17fbcb70..d553f83ca 100644 --- a/src/Forms/Styles/SubStationAlphaStyles.cs +++ b/src/Forms/Styles/SubStationAlphaStyles.cs @@ -896,7 +896,9 @@ namespace Nikse.SubtitleEdit.Forms.Styles listViewStyles.SelectedItems[0].Text = textBoxStyleName.Text; bool found = SetSsaStyle(_oldSsaName, "name", textBoxStyleName.Text); if (!found) + { SetSsaStyle(_oldSsaName, "name", textBoxStyleName.Text, false); + } _oldSsaName = textBoxStyleName.Text; } diff --git a/src/Forms/Styles/SubStationAlphaStylesBatchConvert.cs b/src/Forms/Styles/SubStationAlphaStylesBatchConvert.cs index d01e82ede..b2bc70984 100644 --- a/src/Forms/Styles/SubStationAlphaStylesBatchConvert.cs +++ b/src/Forms/Styles/SubStationAlphaStylesBatchConvert.cs @@ -30,15 +30,18 @@ namespace Nikse.SubtitleEdit.Forms.Styles _header = subtitle.Header; _isSubStationAlpha = format.Name == SubStationAlpha.NameOfFormat; if (_header == null || !_header.Contains("style:", StringComparison.OrdinalIgnoreCase)) + { ResetHeader(); + } comboBoxFontName.Items.Clear(); foreach (var x in FontFamily.Families) + { comboBoxFontName.Items.Add(x.Name); + } var l = Configuration.Settings.Language.SubStationAlphaStyles; Text = l.Title; - // groupBoxStyles.Text = l.Styles; groupBoxProperties.Text = l.Properties; groupBoxFont.Text = l.Font; labelFontName.Text = l.FontName; @@ -96,9 +99,13 @@ namespace Nikse.SubtitleEdit.Forms.Styles comboBoxFontName.Left = labelFontName.Left + labelFontName.Width + 10; numericUpDownFontSize.Left = labelFontSize.Left + labelFontSize.Width + 10; if (comboBoxFontName.Left > numericUpDownFontSize.Left) + { numericUpDownFontSize.Left = comboBoxFontName.Left; + } else + { comboBoxFontName.Left = numericUpDownFontSize.Left; + } numericUpDownOutline.Left = radioButtonOutline.Left + radioButtonOutline.Width + 5; labelShadow.Left = numericUpDownOutline.Left + numericUpDownOutline.Width + 5; @@ -137,9 +144,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string f = format[i].Trim().ToLower(); if (f == "name") + { nameIndex = i; + } + if (f == propertyName) + { propertyIndex = i; + } } } sb.AppendLine(line); @@ -154,7 +166,9 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string f = format[i].Trim(); if (i == nameIndex) + { correctLine = f.Equals(styleName, StringComparison.OrdinalIgnoreCase); + } } if (correctLine) { @@ -164,11 +178,18 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string f = format[i].Trim(); if (i == propertyIndex) + { sb.Append(propertyValue); + } else + { sb.Append(f); + } + if (i < format.Length - 1) + { sb.Append(','); + } } sb.AppendLine(); } @@ -194,9 +215,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { SubtitleFormat format; if (_isSubStationAlpha) + { format = new SubStationAlpha(); + } else + { format = new AdvancedSubStationAlpha(); + } + var sub = new Subtitle(); string text = format.ToText(sub, string.Empty); var lines = text.SplitToLines(); @@ -217,7 +243,9 @@ namespace Nikse.SubtitleEdit.Forms.Styles private void SubStationAlphaStylesBatchConvert_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) + { DialogResult = DialogResult.Cancel; + } } private void buttonReset_Click(object sender, EventArgs e) @@ -252,7 +280,10 @@ namespace Nikse.SubtitleEdit.Forms.Styles private string GetSsaColorString(Color c) { if (_isSubStationAlpha) + { return Color.FromArgb(0, c.B, c.G, c.R).ToArgb().ToString(CultureInfo.InvariantCulture); + } + return AdvancedSubStationAlpha.GetSsaColorString(c); } @@ -382,7 +413,10 @@ namespace Nikse.SubtitleEdit.Forms.Styles string name = CurrentStyleName; var item = comboBoxFontName.SelectedItem; if (item != null) + { SetSsaStyle(name, "fontname", item.ToString()); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -403,9 +437,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (checkBoxFontBold.Checked) + { SetSsaStyle(name, "bold", "-1"); + } else + { SetSsaStyle(name, "bold", "0"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -416,9 +455,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (checkBoxFontItalic.Checked) + { SetSsaStyle(name, "italic", "-1"); + } else + { SetSsaStyle(name, "italic", "0"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -429,9 +473,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (checkBoxFontUnderline.Checked) + { SetSsaStyle(name, "underline", "-1"); + } else + { SetSsaStyle(name, "underline", "0"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -442,9 +491,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (_isSubStationAlpha) + { SetSsaStyle(name, "alignment", "5"); + } else + { SetSsaStyle(name, "alignment", "7"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -455,9 +509,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (_isSubStationAlpha) + { SetSsaStyle(name, "alignment", "6"); + } else + { SetSsaStyle(name, "alignment", "8"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -468,9 +527,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (_isSubStationAlpha) + { SetSsaStyle(name, "alignment", "7"); + } else + { SetSsaStyle(name, "alignment", "9"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -481,9 +545,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (_isSubStationAlpha) + { SetSsaStyle(name, "alignment", "9"); + } else + { SetSsaStyle(name, "alignment", "4"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -494,9 +563,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (_isSubStationAlpha) + { SetSsaStyle(name, "alignment", "10"); + } else + { SetSsaStyle(name, "alignment", "5"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -507,9 +581,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = CurrentStyleName; if (_isSubStationAlpha) + { SetSsaStyle(name, "alignment", "11"); + } else + { SetSsaStyle(name, "alignment", "6"); + } + GeneratePreviewAndUpdateRawHeader(); } } @@ -629,15 +708,21 @@ namespace Nikse.SubtitleEdit.Forms.Styles private void UpdateRawHeader() { if (_header == null) + { textBoxRawHeader.Text = string.Empty; + } else + { textBoxRawHeader.Text = _header.Replace("[Events]", string.Empty).TrimEnd(); + } } private void UpdatePropertiesTag(string tag, string text, bool remove) { if (_header == null) + { return; + } bool scriptInfoOn = false; var sb = new StringBuilder(); @@ -665,7 +750,10 @@ namespace Nikse.SubtitleEdit.Forms.Styles if (s.StartsWith(tag.ToLower() + ":")) { if (!remove) + { sb.AppendLine(line.Substring(0, tag.Length) + ": " + text); + } + found = true; } else @@ -685,9 +773,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles private void comboBoxCollision_SelectedIndexChanged(object sender, EventArgs e) { if (comboBoxCollision.SelectedIndex == 0) + { UpdatePropertiesTag("collisions", "Normal", false); // normal + } else + { UpdatePropertiesTag("collisions", "Reverse", false); // reverse + } + UpdateRawHeader(); } @@ -705,9 +798,13 @@ namespace Nikse.SubtitleEdit.Forms.Styles if (!_isSubStationAlpha) { if (checkBoxScaleBorderAndShadow.Checked) + { UpdatePropertiesTag("ScaledBorderAndShadow", "Yes", false); + } else + { UpdatePropertiesTag("ScaledBorderAndShadow", "No", false); + } } UpdateRawHeader(); } @@ -743,19 +840,25 @@ namespace Nikse.SubtitleEdit.Forms.Styles if (s.StartsWith("collisions:")) { if (s.Remove(0, 11).Trim() == "reverse") + { comboBoxCollision.SelectedIndex = 1; + } } else if (s.StartsWith("playresx:")) { int number; if (int.TryParse(s.Remove(0, 9).Trim(), out number)) + { numericUpDownVideoWidth.Value = number; + } } else if (s.StartsWith("playresy:")) { int number; if (int.TryParse(s.Remove(0, 9).Trim(), out number)) + { numericUpDownVideoHeight.Value = number; + } } else if (s.StartsWith("scaledborderandshadow:")) { @@ -784,27 +887,44 @@ namespace Nikse.SubtitleEdit.Forms.Styles checkBoxFontUnderline.Checked = style.Underline; if (style.FontSize > 0 && style.FontSize <= numericUpDownFontSize.Maximum) + { numericUpDownFontSize.Value = style.FontSize; + } else + { numericUpDownFontSize.Value = 20; + } panelPrimaryColor.BackColor = style.Primary; panelSecondaryColor.BackColor = style.Secondary; if (_isSubStationAlpha) + { panelOutlineColor.BackColor = style.Tertiary; + } else + { panelOutlineColor.BackColor = style.Outline; + } + panelBackColor.BackColor = style.Background; if (style.OutlineWidth >= 0 && style.OutlineWidth <= numericUpDownOutline.Maximum) + { numericUpDownOutline.Value = style.OutlineWidth; + } else + { numericUpDownOutline.Value = 2; + } if (style.ShadowWidth >= 0 && style.ShadowWidth <= numericUpDownShadowWidth.Maximum) + { numericUpDownShadowWidth.Value = style.ShadowWidth; + } else + { numericUpDownShadowWidth.Value = 1; + } if (_isSubStationAlpha) { @@ -874,19 +994,31 @@ namespace Nikse.SubtitleEdit.Forms.Styles } if (style.MarginLeft >= 0 && style.MarginLeft <= numericUpDownMarginLeft.Maximum) + { numericUpDownMarginLeft.Value = style.MarginLeft; + } else + { numericUpDownMarginLeft.Value = 10; + } if (style.MarginRight >= 0 && style.MarginRight <= numericUpDownMarginRight.Maximum) + { numericUpDownMarginRight.Value = style.MarginRight; + } else + { numericUpDownMarginRight.Value = 10; + } if (style.MarginVertical >= 0 && style.MarginVertical <= numericUpDownMarginVertical.Maximum) + { numericUpDownMarginVertical.Value = style.MarginVertical; + } else + { numericUpDownMarginVertical.Value = 10; + } if (style.BorderStyle == "3") { @@ -900,8 +1032,8 @@ namespace Nikse.SubtitleEdit.Forms.Styles protected override void GeneratePreviewReal() { - if (pictureBoxPreview.Image != null) - pictureBoxPreview.Image.Dispose(); + pictureBoxPreview.Image?.Dispose(); + var bmp = new Bitmap(pictureBoxPreview.Width, pictureBoxPreview.Height); using (Graphics g = Graphics.FromImage(bmp)) @@ -916,12 +1048,16 @@ namespace Nikse.SubtitleEdit.Forms.Styles if (y % (rectangleSize * 2) == 0) { if (x % (rectangleSize * 2) == 0) + { c = Color.LightGray; + } } else { if (x % (rectangleSize * 2) != 0) + { c = Color.LightGray; + } } g.FillRectangle(new SolidBrush(c), x, y, rectangleSize, rectangleSize); } @@ -951,22 +1087,37 @@ namespace Nikse.SubtitleEdit.Forms.Styles float left; if (radioButtonTopLeft.Checked || radioButtonMiddleLeft.Checked || radioButtonBottomLeft.Checked) + { left = (float)numericUpDownMarginLeft.Value; + } else if (radioButtonTopRight.Checked || radioButtonMiddleRight.Checked || radioButtonBottomRight.Checked) + { left = bmp.Width - (measuredWidth + ((float)numericUpDownMarginRight.Value)); + } else + { left = ((float)(bmp.Width - measuredWidth * 0.8 + 15) / 2); + } float top; if (radioButtonTopLeft.Checked || radioButtonTopCenter.Checked || radioButtonTopRight.Checked) + { top = (float)numericUpDownMarginVertical.Value; + } else if (radioButtonMiddleLeft.Checked || radioButtonMiddleCenter.Checked || radioButtonMiddleRight.Checked) + { top = (bmp.Height - measuredHeight) / 2; + } else + { top = bmp.Height - measuredHeight - ((int)numericUpDownMarginVertical.Value); + } + top -= (int)numericUpDownShadowWidth.Value; if (radioButtonTopCenter.Checked || radioButtonMiddleCenter.Checked || radioButtonBottomCenter.Checked) + { left -= (int)(numericUpDownShadowWidth.Value / 2); + } const int leftMargin = 0; int pathPointsStart = -1; @@ -974,9 +1125,13 @@ namespace Nikse.SubtitleEdit.Forms.Styles if (radioButtonOpaqueBox.Checked) { if (_isSubStationAlpha) + { g.FillRectangle(new SolidBrush(panelBackColor.BackColor), left, top, measuredWidth + 3, measuredHeight + 3); + } else + { g.FillRectangle(new SolidBrush(panelOutlineColor.BackColor), left, top, measuredWidth + 3, measuredHeight + 3); + } } TextDraw.DrawText(font, sf, path, sb, checkBoxFontItalic.Checked, checkBoxFontBold.Checked, checkBoxFontUnderline.Checked, left, top, ref newLine, leftMargin, ref pathPointsStart); @@ -994,16 +1149,22 @@ namespace Nikse.SubtitleEdit.Forms.Styles shadowPath.Transform(translateMatrix); using (var p1 = new Pen(Color.FromArgb(250, panelBackColor.BackColor), outline)) + { g.DrawPath(p1, shadowPath); + } } } if (outline > 0 && radioButtonOutline.Checked) { if (_isSubStationAlpha) + { g.DrawPath(new Pen(panelBackColor.BackColor, outline), path); + } else + { g.DrawPath(new Pen(panelOutlineColor.BackColor, outline), path); + } } g.FillPath(new SolidBrush(panelPrimaryColor.BackColor), path); } diff --git a/src/Forms/Styles/SubStationAlphaStylesExport.Designer.cs b/src/Forms/Styles/SubStationAlphaStylesExport.Designer.cs index 9ba3f039a..fe1c1bb52 100644 --- a/src/Forms/Styles/SubStationAlphaStylesExport.Designer.cs +++ b/src/Forms/Styles/SubStationAlphaStylesExport.Designer.cs @@ -1,6 +1,6 @@ namespace Nikse.SubtitleEdit.Forms.Styles { - partial class SubStationAlphaStylesExport + sealed partial class SubStationAlphaStylesExport { /// /// Required designer variable. diff --git a/src/Forms/Styles/SubStationAlphaStylesExport.cs b/src/Forms/Styles/SubStationAlphaStylesExport.cs index 89a126232..e8f1c2927 100644 --- a/src/Forms/Styles/SubStationAlphaStylesExport.cs +++ b/src/Forms/Styles/SubStationAlphaStylesExport.cs @@ -8,12 +8,12 @@ using System.Windows.Forms; namespace Nikse.SubtitleEdit.Forms.Styles { - public partial class SubStationAlphaStylesExport : Form + public sealed partial class SubStationAlphaStylesExport : Form { - private string _header; - private bool _isSubStationAlpha; - private SubtitleFormat _format; - private List _styles; + private readonly string _header; + private readonly bool _isSubStationAlpha; + private readonly SubtitleFormat _format; + private readonly List _styles; public List ExportedStyles { get; set; } public SubStationAlphaStylesExport(string header, bool isSubStationAlpha, SubtitleFormat format) @@ -43,7 +43,9 @@ namespace Nikse.SubtitleEdit.Forms.Styles foreach (ListViewItem item in listViewExportStyles.Items) { if (item.Checked) + { ExportedStyles.Add(item.Text); + } } if (ExportedStyles.Count == 0) { @@ -117,9 +119,14 @@ namespace Nikse.SubtitleEdit.Forms.Styles { var toLower = line.Trim().ToLowerInvariant(); while (toLower.Contains(": ")) + { toLower = toLower.Replace(": ", ":"); + } + while (toLower.Contains(" :")) + { toLower = toLower.Replace(" :", ":"); + } if (stylesOn && toLower.StartsWith("style:" + styleName.Trim() + ",", StringComparison.OrdinalIgnoreCase)) { @@ -142,12 +149,19 @@ namespace Nikse.SubtitleEdit.Forms.Styles { var toLower = line.Trim().ToLowerInvariant(); while (toLower.Contains(": ")) + { toLower = toLower.Replace(": ", ":"); + } + while (toLower.Contains(" :")) + { toLower = toLower.Replace(" :", ":"); + } if (toLower.StartsWith("style:" + styleName.ToLowerInvariant().Trim(), StringComparison.Ordinal)) + { sb.AppendLine(line); + } } } else diff --git a/src/Forms/Styles/TimedTextStyles.cs b/src/Forms/Styles/TimedTextStyles.cs index 042c2d082..516173319 100644 --- a/src/Forms/Styles/TimedTextStyles.cs +++ b/src/Forms/Styles/TimedTextStyles.cs @@ -75,7 +75,9 @@ namespace Nikse.SubtitleEdit.Forms.Styles protected override void GeneratePreviewReal() { if (listViewStyles.SelectedItems.Count != 1) + { return; + } pictureBoxPreview.Image?.Dispose(); var bmp = new Bitmap(pictureBoxPreview.Width, pictureBoxPreview.Height); @@ -112,8 +114,7 @@ namespace Nikse.SubtitleEdit.Forms.Styles try { var fontSize = 20.0f; - int fontSizeInt; - if (int.TryParse(textBoxFontSize.Text.Replace("px", string.Empty), out fontSizeInt)) + if (int.TryParse(textBoxFontSize.Text.Replace("px", string.Empty), out var fontSizeInt)) { fontSize = fontSizeInt; } @@ -200,34 +201,50 @@ namespace Nikse.SubtitleEdit.Forms.Styles { string name = "default"; if (node.Attributes["xml:id"] != null) + { name = node.Attributes["xml:id"].Value; + } else if (node.Attributes["id"] != null) + { name = node.Attributes["id"].Value; + } string fontFamily = "Arial"; if (node.Attributes["tts:fontFamily"] != null) + { fontFamily = node.Attributes["tts:fontFamily"].Value; + } string fontWeight = "normal"; if (node.Attributes["tts:fontWeight"] != null) + { fontWeight = node.Attributes["tts:fontWeight"].Value; + } string fontStyle = "normal"; if (node.Attributes["tts:fontStyle"] != null) + { fontStyle = node.Attributes["tts:fontStyle"].Value; + } string fontColor = "white"; if (node.Attributes["tts:color"] != null) + { fontColor = node.Attributes["tts:color"].Value; + } string fontSize = "100%"; if (node.Attributes["tts:fontSize"] != null) + { fontSize = node.Attributes["tts:fontSize"].Value; + } AddStyle(name, fontFamily, fontColor, fontSize); } if (listViewStyles.Items.Count > 0) + { listViewStyles.Items[0].Selected = true; + } } private void AddStyle(string name, string fontFamily, string color, string fontSize)