Пример #1
0
        public Subtitle AdjustAllParagraphs(Subtitle subtitle)
        {
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                AdjustParagraph(p);
            }

            for (int i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                Paragraph p = subtitle.Paragraphs[i];
                Paragraph next = subtitle.GetParagraphOrDefault(i + 1);
                if (next != null)
                {
                    if (p.EndTime.TotalMilliseconds >= next.StartTime.TotalMilliseconds)
                        p.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 1;
                }
            }
            return subtitle;
        }
Пример #2
0
 private void checkBoxUseTimeCodesFromIdx_CheckedChanged(object sender, EventArgs e)
 {
     Subtitle oldSubtitle = new Subtitle(_subtitle);
     subtitleListView1.BeginUpdate();
     LoadVobRip();
     for (int i = 0; i < _subtitle.Paragraphs.Count; i++)
     {
         Paragraph p = oldSubtitle.GetParagraphOrDefault(i);
         if (p != null && p.Text.Length > 0)
         {
             _subtitle.Paragraphs[i].Text = p.Text;
         }
     }
     subtitleListView1.Fill(_subtitle);
     subtitleListView1.EndUpdate();
 }
Пример #3
0
        private void buttonConvert_Click(object sender, EventArgs e)
        {
            if (listViewInputFiles.Items.Count == 0)
            {
                MessageBox.Show(Configuration.Settings.Language.BatchConvert.NothingToConvert);
                return;
            }

            if (!checkBoxOverwriteOriginalFiles.Checked)
            {
                if (textBoxOutputFolder.Text.Length < 2)
                {
                    MessageBox.Show(Configuration.Settings.Language.BatchConvert.PleaseChooseOutputFolder);
                    return;
                }
                else if (!Directory.Exists(textBoxOutputFolder.Text))
                {
                    try
                    {
                        Directory.CreateDirectory(textBoxOutputFolder.Text);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                        return;
                    }
                }
            }

            _converting = true;
            buttonConvert.Enabled = false;
            buttonCancel.Enabled = false;
            progressBar1.Style = ProgressBarStyle.Blocks;
            progressBar1.Maximum = listViewInputFiles.Items.Count;
            progressBar1.Value = 0;
            progressBar1.Visible = progressBar1.Maximum > 2;
            string toFormat = comboBoxSubtitleFormats.Text;
            groupBoxOutput.Enabled = false;
            groupBoxConvertOptions.Enabled = false;
            buttonInputBrowse.Enabled = false;
            buttonSearchFolder.Enabled = false;
            _count = 0;
            _converted = 0;
            _errors = 0;
            _abort = false;

            BackgroundWorker worker1 = new BackgroundWorker();
            BackgroundWorker worker2 = new BackgroundWorker();
            BackgroundWorker worker3 = new BackgroundWorker();
            worker1.DoWork += DoThreadWork;
            worker1.RunWorkerCompleted += ThreadWorkerCompleted;
            worker2.DoWork += DoThreadWork;
            worker2.RunWorkerCompleted += ThreadWorkerCompleted;
            worker3.DoWork += DoThreadWork;
            worker3.RunWorkerCompleted += ThreadWorkerCompleted;

            listViewInputFiles.BeginUpdate();
            foreach (ListViewItem item in listViewInputFiles.Items)
                item.SubItems[3].Text = "-";
            listViewInputFiles.EndUpdate();
            Refresh();

            int index = 0;
            while (index < listViewInputFiles.Items.Count && _abort == false)
            {
                ListViewItem item = listViewInputFiles.Items[index];
                string fileName = item.Text;

                try
                {
                    SubtitleFormat format = null;
                    Encoding encoding;
                    var sub = new Subtitle();
                    var fi = new FileInfo(fileName);
                    if (fi.Length < 1024 * 1024) // max 1 mb
                    {
                        format = sub.LoadSubtitle(fileName, out encoding, null);

                        if (format == null)
                        {
                            var ebu = new Ebu();
                            if (ebu.IsMine(null, fileName))
                            {
                                ebu.LoadSubtitle(sub, null, fileName);
                                format = ebu;
                            }
                        }
                        if (format == null)
                        {
                            var pac = new Pac();
                            if (pac.IsMine(null, fileName))
                            {
                                pac.LoadSubtitle(sub, null, fileName);
                                format = pac;
                            }
                        }
                        if (format == null)
                        {
                            var cavena890 = new Cavena890();
                            if (cavena890.IsMine(null, fileName))
                            {
                                cavena890.LoadSubtitle(sub, null, fileName);
                                format = cavena890;
                            }
                        }
                        if (format == null)
                        {
                            var spt = new Spt();
                            if (spt.IsMine(null, fileName))
                            {
                                spt.LoadSubtitle(sub, null, fileName);
                                format = spt;
                            }
                        }
                        if (format == null)
                        {
                            var cheetahCaption = new CheetahCaption();
                            if (cheetahCaption.IsMine(null, fileName))
                            {
                                cheetahCaption.LoadSubtitle(sub, null, fileName);
                                format = cheetahCaption;
                            }
                        }
                        if (format == null)
                        {
                            var capMakerPlus = new CapMakerPlus();
                            if (capMakerPlus.IsMine(null, fileName))
                            {
                                capMakerPlus.LoadSubtitle(sub, null, fileName);
                                format = capMakerPlus;
                            }
                        }
                        if (format == null)
                        {
                            var captionate = new Captionate();
                            if (captionate.IsMine(null, fileName))
                            {
                                captionate.LoadSubtitle(sub, null, fileName);
                                format = captionate;
                            }
                        }
                        if (format == null)
                        {
                            var ultech130 = new Ultech130();
                            if (ultech130.IsMine(null, fileName))
                            {
                                ultech130.LoadSubtitle(sub, null, fileName);
                                format = ultech130;
                            }
                        }
                        if (format == null)
                        {
                            var nciCaption = new NciCaption();
                            if (nciCaption.IsMine(null, fileName))
                            {
                                nciCaption.LoadSubtitle(sub, null, fileName);
                                format = nciCaption;
                            }
                        }

                        if (format == null)
                        {
                            var avidStl = new AvidStl();
                            if (avidStl.IsMine(null, fileName))
                            {
                                avidStl.LoadSubtitle(sub, null, fileName);
                                format = avidStl;
                            }
                        }

                        if (format == null)
                        {
                            var elr = new ELRStudioClosedCaption();
                            if (elr.IsMine(null, fileName))
                            {
                                elr.LoadSubtitle(sub, null, fileName);
                                format = elr;
                            }
                        }

                        if (format != null && format.GetType() == typeof(MicroDvd))
                        {
                            if (sub != null && sub.Paragraphs.Count > 0 && sub.Paragraphs[0].Duration.TotalMilliseconds < 1001)
                            {
                                if (sub.Paragraphs[0].Text.StartsWith("29.") || sub.Paragraphs[0].Text.StartsWith("23.") ||
                                    sub.Paragraphs[0].Text.StartsWith("29,") || sub.Paragraphs[0].Text.StartsWith("23,") ||
                                    sub.Paragraphs[0].Text == "24" || sub.Paragraphs[0].Text == "25" ||
                                    sub.Paragraphs[0].Text == "30" || sub.Paragraphs[0].Text == "60")
                                    sub.Paragraphs.RemoveAt(0);
                            }
                        }

                    }

                    var bluRaySubtitles = new List<BluRaySupParser.PcsData>();
                    bool isVobSub = false;
                    bool isMatroska = false;
                    if (format == null && fileName.ToLower().EndsWith(".sup") && Main.IsBluRaySupFile(fileName))
                    {
                        var log = new StringBuilder();
                        bluRaySubtitles = BluRaySupParser.ParseBluRaySup(fileName, log);
                    }
                    else if (format == null && fileName.ToLower().EndsWith(".sub") && Main.HasVobSubHeader(fileName))
                    {
                        isVobSub = true;
                    }
                    else if (format == null && fileName.ToLower().EndsWith(".mkv") && item.SubItems[2].Text.StartsWith("Matroska"))
                    {
                        isMatroska = true;
                    }

                    if (format == null && bluRaySubtitles.Count == 0 && !isVobSub && !isMatroska)
                    {
                        if (progressBar1.Value < progressBar1.Maximum)
                            progressBar1.Value++;
                        labelStatus.Text = progressBar1.Value + " / " + progressBar1.Maximum;
                    }
                    else
                    {
                        if (isMatroska)
                        {
                            if (Path.GetExtension(fileName).ToLower() == ".mkv" || Path.GetExtension(fileName).ToLower() == ".mks")
                            {
                                Matroska mkv = new Matroska();
                                bool isValid = false;
                                bool hasConstantFrameRate = false;
                                double frameRate = 0;
                                int width = 0;
                                int height = 0;
                                double milliseconds = 0;
                                string videoCodec = string.Empty;
                                mkv.GetMatroskaInfo(fileName, ref isValid, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec);
                                if (isValid)
                                {
                                    var subtitleList = mkv.GetMatroskaSubtitleTracks(fileName, out isValid);
                                    if (subtitleList.Count > 0)
                                    {
                                        foreach (MatroskaSubtitleInfo x in subtitleList)
                                        {
                                            if (x.CodecId.ToUpper() == "S_VOBSUB")
                                            {
                                                //TODO: convert from VobSub image based format
                                            }
                                            else if (x.CodecId.ToUpper() == "S_HDMV/PGS")
                                            {
                                                //TODO: convert from Blu-ray image based format
                                            }
                                            else if (x.CodecId.ToUpper() == "S_TEXT/UTF8" || x.CodecId.ToUpper() == "S_TEXT/SSA" || x.CodecId.ToUpper() == "S_TEXT/ASS")
                                            {
                                                _matroskaListViewItem = item;
                                                List<SubtitleSequence> mkvSub = mkv.GetMatroskaSubtitle(fileName, (int)x.TrackNumber, out isValid, MatroskaProgress);

                                                bool isSsa = false;
                                                if (x.CodecPrivate.ToLower().Contains("[script info]"))
                                                {
                                                    if (x.CodecPrivate.ToLower().Contains("[V4 Styles]".ToLower()))
                                                        format = new SubStationAlpha();
                                                    else
                                                        format = new AdvancedSubStationAlpha();
                                                    isSsa = true;
                                                }
                                                else
                                                {
                                                    format = new SubRip();
                                                }

                                                if (isSsa)
                                                {
                                                    foreach (Paragraph p in Main.LoadMatroskaSSa(x, fileName, format, mkvSub).Paragraphs)
                                                    {
                                                        sub.Paragraphs.Add(p);
                                                    }
                                                }
                                                else
                                                {
                                                    foreach (SubtitleSequence p in mkvSub)
                                                    {
                                                        sub.Paragraphs.Add(new Paragraph(p.Text, p.StartMilliseconds, p.EndMilliseconds));
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else if (bluRaySubtitles.Count > 0)
                        {
                            item.SubItems[3].Text = "OCR...";
                            var vobSubOcr = new VobSubOcr();
                            vobSubOcr.FileName = Path.GetFileName(fileName);
                            vobSubOcr.InitializeBatch(bluRaySubtitles, Configuration.Settings.VobSubOcr, fileName);
                            sub = vobSubOcr.SubtitleFromOcr;
                        }
                        else if (isVobSub)
                        {
                            item.SubItems[3].Text = "OCR...";
                            var vobSubOcr = new VobSubOcr();
                            vobSubOcr.InitializeBatch(fileName, Configuration.Settings.VobSubOcr, true);
                            sub = vobSubOcr.SubtitleFromOcr;
                        }

                        if (comboBoxSubtitleFormats.Text == new AdvancedSubStationAlpha().Name && _assStyle != null)
                        {
                            sub.Header = _assStyle;
                        }
                        else if (comboBoxSubtitleFormats.Text == new SubStationAlpha().Name && _ssaStyle != null)
                        {
                            sub.Header = _ssaStyle;
                        }

                        int prevIndex = -1;
                        foreach (Paragraph p in sub.Paragraphs)
                        {
                            string prevText = string.Empty;
                            var prev = sub.GetParagraphOrDefault(prevIndex);
                            if (prev != null)
                                prevText = prev.Text;
                            prevIndex++;

                            if (checkBoxRemoveTextForHI.Checked)
                            {
                                p.Text = _removeForHI.RemoveTextFromHearImpaired(p.Text, prevText);
                            }
                            if (checkBoxRemoveFormatting.Checked)
                            {
                                p.Text = Utilities.RemoveHtmlTags(p.Text);
                                if (p.Text.StartsWith("{") && p.Text.Length > 6 && p.Text[5] == '}')
                                    p.Text = p.Text.Remove(0, 6);
                                if (p.Text.StartsWith("{") && p.Text.Length > 6 && p.Text[4] == '}')
                                    p.Text = p.Text.Remove(0, 5);
                            }
                        }
                        if (checkBoxFixCasing.Checked)
                        {
                            _changeCasing.FixCasing(sub, Utilities.AutoDetectGoogleLanguage(sub));
                            _changeCasingNames.Initialize(sub);
                            _changeCasingNames.FixCasing();
                        }

                        double fromFrameRate;
                        double toFrameRate;
                        if (double.TryParse(comboBoxFrameRateFrom.Text, out fromFrameRate) &&
                            double.TryParse(comboBoxFrameRateTo.Text, out toFrameRate))
                        {
                            sub.ChangeFramerate(fromFrameRate, toFrameRate);
                        }

                        if (timeUpDownAdjust.TimeCode.TotalMilliseconds > 0.00001)
                        {
                            var totalMilliseconds = timeUpDownAdjust.TimeCode.TotalMilliseconds;
                            if (radioButtonShowEarlier.Checked)
                                totalMilliseconds *= -1;
                            sub.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(totalMilliseconds));
                        }

                        while (worker1.IsBusy && worker2.IsBusy && worker3.IsBusy)
                        {
                            Application.DoEvents();
                            System.Threading.Thread.Sleep(100);
                        }

                        ThreadDoWorkParameter parameter = new ThreadDoWorkParameter(checkBoxFixCommonErrors.Checked, checkBoxMultipleReplace.Checked, checkBoxSplitLongLines.Checked, checkBoxAutoBalance.Checked, checkBoxSetMinimumDisplayTimeBetweenSubs.Checked, item, sub, GetCurrentSubtitleFormat(), GetCurrentEncoding(), Configuration.Settings.Tools.BatchConvertLanguage, fileName, toFormat, format);
                        if (!worker1.IsBusy)
                            worker1.RunWorkerAsync(parameter);
                        else if (!worker2.IsBusy)
                            worker2.RunWorkerAsync(parameter);
                        else if (!worker3.IsBusy)
                            worker3.RunWorkerAsync(parameter);
                    }

                }
                catch
                {
                    if (progressBar1.Value < progressBar1.Maximum)
                        progressBar1.Value++;
                    labelStatus.Text = progressBar1.Value + " / " + progressBar1.Maximum;
                }
                index++;
            }
            while (worker1.IsBusy || worker2.IsBusy || worker3.IsBusy)
            {
                try
                {
                    Application.DoEvents();
                }
                catch
                {
                }
                System.Threading.Thread.Sleep(100);
            }
            _converting = false;
            labelStatus.Text = string.Empty;
            progressBar1.Visible = false;
            buttonConvert.Enabled = true;
            buttonCancel.Enabled = true;
            groupBoxOutput.Enabled = true;
            groupBoxConvertOptions.Enabled = true;
            buttonInputBrowse.Enabled = true;
            buttonSearchFolder.Enabled = true;
        }
Пример #4
0
        private void toolStripMenuItemImportTimeCodes_Click(object sender, EventArgs e)
        {
            if (_subtitle.Paragraphs.Count < 1)
            {
                MessageBox.Show(_language.NoSubtitleLoaded, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            openFileDialog1.Title = _languageGeneral.OpenSubtitle;
            openFileDialog1.FileName = string.Empty;
            openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                Encoding encoding = null;
                Subtitle timeCodeSubtitle = new Subtitle();
                SubtitleFormat format = timeCodeSubtitle.LoadSubtitle(openFileDialog1.FileName, out encoding, encoding);
                if (format == null)
                {
                    ShowUnknownSubtitle();
                    return;
                }

                if (timeCodeSubtitle.Paragraphs.Count != _subtitle.Paragraphs.Count && !string.IsNullOrEmpty(_language.ImportTimeCodesDifferentNumberOfLinesWarning))
                {
                    if (MessageBox.Show(string.Format(_language.ImportTimeCodesDifferentNumberOfLinesWarning, timeCodeSubtitle.Paragraphs.Count, _subtitle.Paragraphs.Count), _title, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                        return;
                }

                MakeHistoryForUndo(_language.BeforeTimeCodeImport);

                if (GetCurrentSubtitleFormat().IsFrameBased)
                    timeCodeSubtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                else
                    timeCodeSubtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                int count = 0;
                for (int i = 0; i < timeCodeSubtitle.Paragraphs.Count; i++)
                {
                    Paragraph existing = _subtitle.GetParagraphOrDefault(i);
                    Paragraph newTimeCode = timeCodeSubtitle.GetParagraphOrDefault(i);
                    if (existing == null || newTimeCode == null)
                        break;
                    existing.StartTime.TotalMilliseconds = newTimeCode.StartTime.TotalMilliseconds;
                    existing.EndTime.TotalMilliseconds = newTimeCode.EndTime.TotalMilliseconds;
                    existing.StartFrame = newTimeCode.StartFrame;
                    existing.EndFrame = newTimeCode.EndFrame;
                    count++;

                }
                ShowStatus(string.Format(_language.TimeCodeImportedFromXY, Path.GetFileName(openFileDialog1.FileName), count));
                SaveSubtitleListviewIndexes();
                ShowSource();
                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                RestoreSubtitleListviewIndexes();
            }

        }
Пример #5
0
 public void SetPosition(double startPositionSeconds, Subtitle subtitle, double currentVideoPositionSeconds, int subtitleIndex, ListView.SelectedIndexCollection selectedIndices)
 {
     StartPositionSeconds = startPositionSeconds;
     _selectedIndices = selectedIndices;
     _subtitle = subtitle;
     _currentVideoPositionSeconds = currentVideoPositionSeconds;
     _selectedParagraph = _subtitle.GetParagraphOrDefault(subtitleIndex);
     NearestSubtitles(subtitle, currentVideoPositionSeconds, subtitleIndex);
     Invalidate();
 }
Пример #6
0
        public void NearestSubtitles(Subtitle subtitle, double currentVideoPositionSeconds, int subtitleIndex)
        {
            _previousAndNextParagraphs.Clear();
            _currentParagraph = null;

            int positionMilliseconds = (int)Math.Round(currentVideoPositionSeconds * 1000.0);
            if (_selectedParagraph != null && _selectedParagraph.StartTime.TotalMilliseconds < positionMilliseconds && _selectedParagraph.EndTime.TotalMilliseconds > positionMilliseconds)
            {
                _currentParagraph = _selectedParagraph;
                for (int j = 1; j < 12; j++)
                {
                    Paragraph nextParagraph = subtitle.GetParagraphOrDefault(subtitleIndex - j);
                    _previousAndNextParagraphs.Add(nextParagraph);
                }
                for (int j=1; j < 10; j++)
                {
                    Paragraph nextParagraph = subtitle.GetParagraphOrDefault(subtitleIndex + j);
                    _previousAndNextParagraphs.Add(nextParagraph);
                }
            }
            else
            {
                for (int i = 0; i < subtitle.Paragraphs.Count; i++)
                {
                    Paragraph p = subtitle.Paragraphs[i];
                    if (p.EndTime.TotalMilliseconds > positionMilliseconds)
                    {
                        _currentParagraph = p;
                        for (int j = 1; j < 10; j++)
                        {
                            Paragraph nextParagraph = subtitle.GetParagraphOrDefault(i - j);
                            _previousAndNextParagraphs.Add(nextParagraph);
                        }
                        for (int j = 1; j < 10; j++)
                        {
                            Paragraph nextParagraph = subtitle.GetParagraphOrDefault(i + j);
                            _previousAndNextParagraphs.Add(nextParagraph);
                        }

                        break;
                    }
                }
                if (_previousAndNextParagraphs.Count == 0)
                {
                    for (int i = 0; i < subtitle.Paragraphs.Count; i++)
                    {
                        Paragraph p = subtitle.Paragraphs[i];
                        if (p.EndTime.TotalMilliseconds > StartPositionSeconds * 1000)
                        {
                            _currentParagraph = p;
                            for (int j = 1; j < 10; j++)
                            {
                                Paragraph nextParagraph = subtitle.GetParagraphOrDefault(i - j);
                                _previousAndNextParagraphs.Add(nextParagraph);
                            }
                            for (int j = 1; j < 10; j++)
                            {
                                Paragraph nextParagraph = subtitle.GetParagraphOrDefault(i + j);
                                _previousAndNextParagraphs.Add(nextParagraph);
                            }

                            break;
                        }
                    }
                    if (_previousAndNextParagraphs.Count == 0 && _subtitle.Paragraphs.Count > 0)
                    {
                        int i = _subtitle.Paragraphs.Count;
                        for (int j = 1; j < 10; j++)
                        {
                            Paragraph nextParagraph = subtitle.GetParagraphOrDefault(i - j);
                            _previousAndNextParagraphs.Add(nextParagraph);
                        }
                    }
                }
            }
        }
Пример #7
0
        private static Subtitle ImportTimeCodesOnSameSeperateLine(string[] lines)
        {
            Paragraph p        = null;
            var       subtitle = new Subtitle();
            var       sb       = new StringBuilder();

            for (int idx = 0; idx < lines.Length; idx++)
            {
                string line = lines[idx];
                string lineWithPerhapsOnlyNumbers = line.Replace(" ", string.Empty).Replace(".", string.Empty).Replace(",", string.Empty).Replace("\t", string.Empty).Replace(":", string.Empty).Replace(";", string.Empty).Replace("{", string.Empty).Replace("}", string.Empty).Replace("[", string.Empty).Replace("]", string.Empty).Replace("-", string.Empty).Replace(">", string.Empty).Replace("<", string.Empty);
                bool   allNumbers = lineWithPerhapsOnlyNumbers.Length > 0;
                foreach (char c in lineWithPerhapsOnlyNumbers)
                {
                    if (!char.IsDigit(c))
                    {
                        allNumbers = false;
                    }
                }
                if (allNumbers && lineWithPerhapsOnlyNumbers.Length > 5)
                {
                    string[] arr = line.Replace("-", " ").Replace(">", " ").Replace("{", " ").Replace("}", " ").Replace("[", " ").Replace("]", " ").Trim().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length == 2)
                    {
                        string[] start = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] end   = arr[1].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                        {
                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                            }
                            p           = new Paragraph();
                            sb          = new StringBuilder();
                            p.StartTime = DecodeTime(start);
                            p.EndTime   = DecodeTime(end);
                        }
                    }
                    else if (arr.Length == 3)
                    {
                        string[] start    = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] end      = arr[1].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] duration = arr[2].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);

                        if (start.Length < 3)
                        {
                            start = end;
                            end   = duration;
                        }

                        if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                        {
                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                            }
                            p           = new Paragraph();
                            sb          = new StringBuilder();
                            p.StartTime = DecodeTime(start);
                            p.EndTime   = DecodeTime(end);
                        }
                    }
                }
                if (p != null && !allNumbers && line.Length > 1)
                {
                    line = line.Trim();
                    if (line.StartsWith("}{}") || line.StartsWith("][]"))
                    {
                        line = line.Remove(0, 3);
                    }
                    sb.AppendLine(line.Trim());
                }
            }
            if (p != null)
            {
                p.Text = sb.ToString().Trim();
                subtitle.Paragraphs.Add(p);
            }

            double averateDuration = 0;

            foreach (Paragraph a in subtitle.Paragraphs)
            {
                double d = a.Duration.TotalSeconds;
                if (d > 10)
                {
                    d = 8;
                }
                averateDuration += d;
            }
            averateDuration = averateDuration / subtitle.Paragraphs.Count;
            if (averateDuration < 0.2 || (averateDuration < 0.5 && subtitle.Paragraphs.Count > 100 && subtitle.Paragraphs[subtitle.Paragraphs.Count - 1].StartTime.TotalSeconds < 140 && subtitle.Paragraphs[subtitle.Paragraphs.Count - 2].StartTime.TotalSeconds < 140))
            {
                subtitle = ImportTimeCodesOnSameSeperateLineNoMilliseconds(lines);
                int i = 0;
                foreach (Paragraph a in subtitle.Paragraphs)
                {
                    i++;
                    var next = subtitle.GetParagraphOrDefault(i);
                    if (next != null && a.EndTime.TotalMilliseconds >= next.StartTime.TotalMilliseconds)
                    {
                        a.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                    }
                }
                return(subtitle);
            }

            subtitle.Renumber(1);
            return(subtitle);
        }
Пример #8
0
        public void ContinueSpellcheck(Subtitle subtitle)
        {
            _subtitle = subtitle;

            buttonUndo.Visible = false;
            _undoList = new List<UndoObject>();

            if (_currentIndex >= subtitle.Paragraphs.Count)
                _currentIndex = 0;

            _currentParagraph = _subtitle.GetParagraphOrDefault(_currentIndex);
            if (_currentParagraph == null)
                return;

            SetWords(_currentParagraph.Text);
            _wordsIndex = -1;

            PrepareNextWord();
        }
        public Subtitle MergeLinesWithSameTimeCodes(Subtitle subtitle, List<int> mergedIndexes, out int numberOfMerges, bool clearFixes, bool reBreak, int maxMsBetween)
        {
            listViewFixes.BeginUpdate();
            List<int> removed = new List<int>();
            if (!_loading)
                listViewFixes.ItemChecked -= listViewFixes_ItemChecked;
            if (clearFixes)
            {
                listViewFixes.Items.Clear();
                _isFixAllowedList = new Dictionary<int, bool>();
            }
            numberOfMerges = 0;
            var mergedSubtitle = new Subtitle();
            bool lastMerged = false;
            Paragraph p = null;
            var lineNumbers = new StringBuilder();
            for (int i = 1; i < subtitle.Paragraphs.Count; i++)
            {
                if (!lastMerged)
                {
                    p = new Paragraph(subtitle.GetParagraphOrDefault(i - 1));
                    mergedSubtitle.Paragraphs.Add(p);
                }
                Paragraph next = subtitle.GetParagraphOrDefault(i);
                Paragraph afterNext = subtitle.GetParagraphOrDefault(i + 1);
                if (next != null)
                {
                    if (QualifiesForMerge(p, next, maxMsBetween) && IsFixAllowed(p))
                    {
                        if (p.Text.StartsWith("<i>") && p.Text.EndsWith("</i>") && next.Text.StartsWith("<i>") && next.Text.EndsWith("</i>"))
                        {
                            p.Text = p.Text.Remove(p.Text.Length - 4) + Environment.NewLine + next.Text.Remove(0, 3);
                        }
                        else
                        {
                            p.Text = p.Text + Environment.NewLine + next.Text;
                        }
                        if (reBreak)
                            p.Text = Utilities.AutoBreakLine(p.Text, _language);
                        lastMerged = true;
                        removed.Add(i);
                        numberOfMerges++;
                        if (!mergedIndexes.Contains(i))
                            mergedIndexes.Add(i);
                        if (!mergedIndexes.Contains(i - 1))
                            mergedIndexes.Add(i - 1);

                        lineNumbers.Append(p.Number.ToString() + ", ");
                        lineNumbers.Append(next.Number.ToString());
                    }
                    else
                    {
                        lastMerged = false;
                    }
                }
                else
                {
                    lastMerged = false;
                }

                if (!removed.Contains(i) && lineNumbers.Length > 0 && clearFixes)
                {
                    AddToListView(p, lineNumbers.ToString(), p.Text);
                    lineNumbers = new StringBuilder();
                }
            }
            if (lineNumbers.Length > 0 && clearFixes)
            {
                AddToListView(p, lineNumbers.ToString(), p.Text);
            }
            if (!lastMerged)
                mergedSubtitle.Paragraphs.Add(new Paragraph(subtitle.GetParagraphOrDefault(subtitle.Paragraphs.Count - 1)));

            listViewFixes.EndUpdate();
            if (!_loading)
                listViewFixes.ItemChecked += listViewFixes_ItemChecked;

            mergedSubtitle.Renumber(1);
            return mergedSubtitle;
        }
        private static Subtitle ImportTimeCodesOnSameSeperateLine(string[] lines)
        {
            Paragraph paragraph = null;
            var subtitle = new Subtitle();
            var sb = new StringBuilder();
            for (int idx = 0; idx < lines.Length; idx++)
            {
                string line = lines[idx];
                string lineWithPerhapsOnlyNumbers = line
                    .Replace(" ", string.Empty)
                    .Replace(".", string.Empty)
                    .Replace(",", string.Empty)
                    .Replace("\t", string.Empty)
                    .Replace(":", string.Empty)
                    .Replace(";", string.Empty)
                    .Replace("{", string.Empty)
                    .Replace("}", string.Empty)
                    .Replace("[", string.Empty)
                    .Replace("]", string.Empty)
                    .Replace("-", string.Empty)
                    .Replace(">", string.Empty)
                    .Replace("<", string.Empty);

                bool allNumbers = lineWithPerhapsOnlyNumbers.Length > 0;
                foreach (char c in lineWithPerhapsOnlyNumbers.Where(c => !char.IsDigit(c)))
                {
                    allNumbers = false;
                }

                if (allNumbers && lineWithPerhapsOnlyNumbers.Length > 5)
                {
                    string[] arr = line
                        .Replace("-", " ")
                        .Replace(">", " ")
                        .Replace("{", " ")
                        .Replace("}", " ")
                        .Replace("[", " ")
                        .Replace("]", " ")
                        .Trim()
                        .Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                    if (arr.Length == 2)
                    {
                        string[] start = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] end = arr[1].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                        {
                            if (paragraph != null)
                            {
                                paragraph.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(paragraph);
                            }

                            paragraph = new Paragraph();
                            sb = new StringBuilder();
                            paragraph.StartTime = DecodeTime(start);
                            paragraph.EndTime = DecodeTime(end);
                        }
                    }
                    else if (arr.Length == 3)
                    {
                        string[] start = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] end = arr[1].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] duration = arr[2].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);

                        if (start.Length < 3)
                        {
                            start = end;
                            end = duration;
                        }

                        if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                        {
                            if (paragraph != null)
                            {
                                paragraph.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(paragraph);
                            }

                            paragraph = new Paragraph();
                            sb = new StringBuilder();
                            paragraph.StartTime = DecodeTime(start);
                            paragraph.EndTime = DecodeTime(end);
                        }
                    }
                }

                if (paragraph == null || allNumbers || line.Length <= 1)
                {
                    continue;
                }

                line = line.Trim();
                if (line.StartsWith("}{}") || line.StartsWith("][]"))
                {
                    line = line.Remove(0, 3);
                }

                sb.AppendLine(line.Trim());
            }

            if (paragraph != null)
            {
                paragraph.Text = sb.ToString().Trim();
                subtitle.Paragraphs.Add(paragraph);
            }

            double averateDuration = 0;
            foreach (Paragraph a in subtitle.Paragraphs)
            {
                double d = a.Duration.TotalSeconds;
                if (d > 10)
                {
                    d = 8;
                }

                averateDuration += d;
            }

            averateDuration = averateDuration / subtitle.Paragraphs.Count;
            if (averateDuration < 0.2 ||
                (averateDuration < 0.5 &&
                subtitle.Paragraphs.Count > 100 &&
                subtitle.Paragraphs[subtitle.Paragraphs.Count - 1].StartTime.TotalSeconds < 140 &&
                subtitle.Paragraphs[subtitle.Paragraphs.Count - 2].StartTime.TotalSeconds < 140))
            {
                subtitle = ImportTimeCodesOnSameSeperateLineNoMilliseconds(lines);
                int i = 0;
                foreach (Paragraph a in subtitle.Paragraphs)
                {
                    i++;
                    var next = subtitle.GetParagraphOrDefault(i);
                    if (next != null && a.EndTime.TotalMilliseconds >= next.StartTime.TotalMilliseconds)
                    {
                        a.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                    }
                }

                return subtitle;
            }

            subtitle.Renumber();
            return subtitle;
        }
Пример #11
0
        public Subtitle MergeShortLinesInSubtitle(Subtitle subtitle, List<int> mergedIndexes, out int numberOfMerges, double maxMillisecondsBetweenLines, int maxCharacters, bool clearFixes)
        {
            listViewFixes.ItemChecked -= listViewFixes_ItemChecked;
            if (clearFixes)
                listViewFixes.Items.Clear();
            numberOfMerges = 0;
            string language = Utilities.AutoDetectGoogleLanguage(subtitle);
            Subtitle mergedSubtitle = new Subtitle();
            bool lastMerged = false;
            Paragraph p = null;
            StringBuilder lineNumbers = new StringBuilder();
            for (int i = 1; i < subtitle.Paragraphs.Count; i++)
            {
                if (!lastMerged)
                {
                    p = new Paragraph(subtitle.GetParagraphOrDefault(i - 1));
                    mergedSubtitle.Paragraphs.Add(p);
                }
                Paragraph next = subtitle.GetParagraphOrDefault(i);
                if (next != null)
                {
                    if (QualifiesForMerge(p, next, maxMillisecondsBetweenLines, maxCharacters) && IsFixAllowed(p))
                    {
                        if (GetStartTag(p.Text) == GetStartTag(next.Text) &&
                            GetEndTag(p.Text) == GetEndTag(next.Text))
                        {
                            string s1 = p.Text.Trim();
                            s1 = s1.Substring(0, s1.Length - GetEndTag(s1).Length);
                            string s2 = next.Text.Trim();
                            s2 = s2.Substring(GetStartTag(s2).Length);
                            p.Text = Utilities.AutoBreakLine(s1 + Environment.NewLine + s2, language);
                        }
                        else
                        {
                            p.Text = Utilities.AutoBreakLine(p.Text + Environment.NewLine + next.Text, language);
                        }
                        p.EndTime = next.EndTime;

                        if (lastMerged)
                        {
                            lineNumbers.Append(next.Number.ToString() + ",");
                        }
                        else
                        {
                            lineNumbers.Append(p.Number.ToString() + ",");
                            lineNumbers.Append(next.Number.ToString() + ",");
                        }

                        lastMerged = true;
                        numberOfMerges++;
                        if (!mergedIndexes.Contains(i))
                            mergedIndexes.Add(i);
                        if (!mergedIndexes.Contains(i - 1))
                            mergedIndexes.Add(i - 1);
                    }
                    else
                    {
                        lastMerged = false;
                    }
                }
                else
                {
                    lastMerged = false;
                }
                if (!lastMerged && lineNumbers.Length > 0 && clearFixes)
                {
                    AddToListView(p, lineNumbers.ToString(), p.Text);
                    lineNumbers = new StringBuilder();
                }
            }
            if (!lastMerged)
                mergedSubtitle.Paragraphs.Add(new Paragraph(subtitle.GetParagraphOrDefault(subtitle.Paragraphs.Count - 1)));

            listViewFixes.ItemChecked += listViewFixes_ItemChecked;
            return mergedSubtitle;
        }
Пример #12
0
        public Subtitle SplitLongLinesInSubtitle(Subtitle subtitle, List<int> splittedIndexes, List<int> autoBreakedIndexes, out int numberOfSplits, int totalLineMaxCharacters, int singleLineMaxCharacters, bool clearFixes)
        {
            listViewFixes.ItemChecked -= listViewFixes_ItemChecked;
            if (clearFixes)
                listViewFixes.Items.Clear();
            numberOfSplits = 0;
            string language = Utilities.AutoDetectGoogleLanguage(subtitle);
            Subtitle splittedSubtitle = new Subtitle();
            Paragraph p = null;
            for (int i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                bool added = false;
                p = subtitle.GetParagraphOrDefault(i);
                if (p != null && p.Text != null)
                {
                    string oldText = Utilities.RemoveHtmlTags(p.Text);
                    if (SplitLongLinesHelper.QualifiesForSplit(p.Text, singleLineMaxCharacters, totalLineMaxCharacters) && IsFixAllowed(p))
                    {
                        if (!SplitLongLinesHelper.QualifiesForSplit(Utilities.AutoBreakLine(p.Text, language), singleLineMaxCharacters, totalLineMaxCharacters))
                        {
                            Paragraph newParagraph = new Paragraph(p);
                            newParagraph.Text = Utilities.AutoBreakLine(p.Text, language);
                            if (clearFixes)
                                AddToListView(p, (splittedSubtitle.Paragraphs.Count + 1).ToString(), oldText);
                            autoBreakedIndexes.Add(splittedSubtitle.Paragraphs.Count);
                            splittedSubtitle.Paragraphs.Add(newParagraph);
                            added = true;
                            numberOfSplits++;
                        }
                        else
                        {
                            string text = Utilities.AutoBreakLine(p.Text, language);
                            if (text.Contains(Environment.NewLine))
                            {
                                string[] arr = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                if (arr.Length == 2)
                                {
                                    int spacing1 = Configuration.Settings.General.MininumMillisecondsBetweenLines / 2;
                                    int spacing2 = Configuration.Settings.General.MininumMillisecondsBetweenLines / 2;
                                    if (Configuration.Settings.General.MininumMillisecondsBetweenLines % 2 == 1)
                                        spacing2++;

                                    double duration = p.Duration.TotalMilliseconds / 2.0;
                                    Paragraph newParagraph1 = new Paragraph(p);
                                    Paragraph newParagraph2 = new Paragraph(p);
                                    newParagraph1.Text = Utilities.AutoBreakLine(arr[0], language);
                                    newParagraph1.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + duration - spacing1;
                                    newParagraph2.Text = Utilities.AutoBreakLine(arr[1], language);
                                    newParagraph2.StartTime.TotalMilliseconds = newParagraph1.EndTime.TotalMilliseconds + spacing2;

                                    if (clearFixes)
                                        AddToListView(p, (splittedSubtitle.Paragraphs.Count + 1).ToString(), oldText);
                                    splittedIndexes.Add(splittedSubtitle.Paragraphs.Count);
                                    splittedIndexes.Add(splittedSubtitle.Paragraphs.Count + 1);

                                    string p1 = Utilities.RemoveHtmlTags(newParagraph1.Text);
                                    bool p1Ends = false;
                                    if (p1.EndsWith(".") || p1.EndsWith("!") || p1.EndsWith("?") || p1.EndsWith(":") || p1.EndsWith(")") || p1.EndsWith("]") || p1.EndsWith("♪"))
                                        p1Ends = true;

                                    if (p1Ends)
                                    {
                                        if (newParagraph1.Text.StartsWith("-") && newParagraph2.Text.StartsWith("-"))
                                        {
                                            newParagraph1.Text = newParagraph1.Text.Remove(0, 1).Trim();
                                            newParagraph2.Text = newParagraph2.Text.Remove(0, 1).Trim();
                                        }
                                        else if (newParagraph1.Text.StartsWith("<i>-") && newParagraph2.Text.StartsWith("-"))
                                        {
                                            newParagraph1.Text = newParagraph1.Text.Remove(3, 1).Trim();
                                            if (newParagraph1.Text.StartsWith("<i> "))
                                                newParagraph1.Text = newParagraph1.Text.Remove(3, 1).Trim();
                                            newParagraph2.Text = newParagraph2.Text.Remove(0, 1).Trim();
                                        }
                                    }
                                    else
                                    {
                                        string post = string.Empty;
                                        if (newParagraph1.Text.EndsWith("</i>"))
                                        {
                                            post = "</i>";
                                            newParagraph1.Text = newParagraph1.Text.Remove(newParagraph1.Text.Length - post.Length);
                                        }
                                        newParagraph1.Text += comboBoxLineContinuationEnd.Text.TrimEnd() + post;

                                        string pre = string.Empty;
                                        if (newParagraph2.Text.StartsWith("<i>"))
                                        {
                                            pre = "<i>";
                                            newParagraph2.Text = newParagraph2.Text.Remove(0, pre.Length);
                                        }
                                        newParagraph2.Text = pre + comboBoxLineContinuationBegin.Text + newParagraph2.Text;
                                    }

                                    if (newParagraph1.Text.IndexOf("<i>") >= 0 && newParagraph1.Text.IndexOf("<i>") < 10 & newParagraph1.Text.IndexOf("</i>") < 0 &&
                                        newParagraph2.Text.Contains("</i>") && newParagraph2.Text.IndexOf("<i>") < 0)
                                    {
                                        newParagraph1.Text += "</i>";
                                        newParagraph2.Text = "<i>" + newParagraph2.Text;
                                    }

                                    splittedSubtitle.Paragraphs.Add(newParagraph1);
                                    splittedSubtitle.Paragraphs.Add(newParagraph2);
                                    added = true;
                                    numberOfSplits++;
                                }
                            }
                        }
                    }
                }
                if (!added)
                    splittedSubtitle.Paragraphs.Add(new Paragraph(p));
            }
            listViewFixes.ItemChecked += listViewFixes_ItemChecked;
            splittedSubtitle.Renumber(1);
            return splittedSubtitle;
        }
        private void GeneratePreview()
        {
            List<int> fixes = new List<int>();
            if (_subtitle == null)
                return;

            FixedSubtitle = new Subtitle(_subtitle);
            var onlyFixedSubtitle = new Subtitle();

            double minumumMillisecondsBetweenLines = (double)numericUpDownMinMillisecondsBetweenLines.Value;
            for (int i = 0; i < FixedSubtitle.Paragraphs.Count - 1; i++)
            {
                Paragraph p = FixedSubtitle.GetParagraphOrDefault(i);
                Paragraph next = FixedSubtitle.GetParagraphOrDefault(i + 1);
                if (next.StartTime.TotalMilliseconds - p.EndTime.TotalMilliseconds < minumumMillisecondsBetweenLines)
                {
                    p.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - minumumMillisecondsBetweenLines;
                    fixes.Add(i);
                    onlyFixedSubtitle.Paragraphs.Add(new Paragraph(p));
                }
            }

            SubtitleListview1.BeginUpdate();
            groupBoxLinesFound.Text = string.Format(Configuration.Settings.Language.SetMinimumDisplayTimeBetweenParagraphs.PreviewLinesModifiedX, fixes.Count);
            if (checkBoxShowOnlyChangedLines.Checked)
            {
                SubtitleListview1.Fill(onlyFixedSubtitle);
            }
            else
            {
                SubtitleListview1.Fill(FixedSubtitle);
                foreach (int index in fixes)
                    SubtitleListview1.SetBackgroundColor(index, Color.Silver);
            }
            SubtitleListview1.EndUpdate();
            FixCount = fixes.Count;
        }
Пример #14
0
        public Subtitle MergeLineswithSameTextInSubtitle(Subtitle subtitle, List<int> mergedIndexes, out int numberOfMerges, bool clearFixes, bool fixIncrementing, bool lineAfterNext, int maxMsBetween)
        {
            List<int> removed = new List<int>();
            if (!loading)
                listViewFixes.ItemChecked -= listViewFixes_ItemChecked;
            if (clearFixes)
                listViewFixes.Items.Clear();
            numberOfMerges = 0;
            var mergedSubtitle = new Subtitle();
            bool lastMerged = false;
            Paragraph p = null;
            var lineNumbers = new StringBuilder();
            for (int i = 1; i < subtitle.Paragraphs.Count; i++)
            {
                if (!lastMerged)
                {
                    p = new Paragraph(subtitle.GetParagraphOrDefault(i - 1));
                    mergedSubtitle.Paragraphs.Add(p);
                }
                Paragraph next = subtitle.GetParagraphOrDefault(i);
                Paragraph afterNext = subtitle.GetParagraphOrDefault(i + 1);
                if (p != null && next != null)
                {
                    if ((QualifiesForMerge(p, next, maxMsBetween) || (fixIncrementing && QualifiesForMergeIncrement(p, next, maxMsBetween))) && IsFixAllowed(p))
                    {
                        p.Text = next.Text;
                        p.EndTime = next.EndTime;
                        if (lastMerged)
                        {
                            lineNumbers.Append(next.Number.ToString() + ",");
                        }
                        else
                        {
                            lineNumbers.Append(p.Number.ToString() + ",");
                            lineNumbers.Append(next.Number.ToString() + ",");
                        }

                        lastMerged = true;
                        removed.Add(i);
                        numberOfMerges++;
                        if (!mergedIndexes.Contains(i))
                            mergedIndexes.Add(i);
                        if (!mergedIndexes.Contains(i - 1))
                            mergedIndexes.Add(i - 1);
                    }
                    else if (lineAfterNext && QualifiesForMerge(p, afterNext, maxMsBetween) && p.Duration.TotalMilliseconds > afterNext.Duration.TotalMilliseconds && IsFixAllowed(p))
                    {
                        removed.Add(i + 2);
                        numberOfMerges++;
                        if (lastMerged)
                        {
                            lineNumbers.Append(afterNext.Number.ToString() + ",");
                        }
                        else
                        {
                            lineNumbers.Append(p.Number.ToString() + ",");
                            lineNumbers.Append(afterNext.Number.ToString() + ",");
                        }
                        lastMerged = true;
                        if (!mergedIndexes.Contains(i))
                            mergedIndexes.Add(i);
                        if (!mergedIndexes.Contains(i - 1))
                            mergedIndexes.Add(i - 1);
                    }
                    else
                    {
                        lastMerged = false;
                    }
                }
                else
                {
                    lastMerged = false;
                }

                if (!removed.Contains(i) && lineNumbers.Length > 0 && clearFixes)
                {
                    AddToListView(p, lineNumbers.ToString(), p.Text);
                    lineNumbers = new StringBuilder();
                }
            }
            if (lineNumbers.Length > 0 && clearFixes)
            {
                AddToListView(p, lineNumbers.ToString(), p.Text);
            }
            if (!lastMerged)
                mergedSubtitle.Paragraphs.Add(new Paragraph(subtitle.GetParagraphOrDefault(subtitle.Paragraphs.Count - 1)));

            if (!loading)
                listViewFixes.ItemChecked += listViewFixes_ItemChecked;

            mergedSubtitle.Renumber(1);
            return mergedSubtitle;
        }
Пример #15
0
        private void CompareSubtitles()
        {
            timer1.Stop();
            var sub1 = new Subtitle(_subtitle1);
            var sub2 = new Subtitle(_subtitle2);

            int index = 0;
            Paragraph p1 = sub1.GetParagraphOrDefault(index);
            Paragraph p2 = sub2.GetParagraphOrDefault(index);
            int max = sub1.Paragraphs.Count;
            if (max < sub2.Paragraphs.Count)
                max = sub2.Paragraphs.Count;
            while (index < max)
            {
                if (p1 != null && p2 != null)
                {
                    if (p1.ToString() == p2.ToString())
                    {
                    }
                    else
                    {
                        if (GetColumnsEqualExceptNumber(p1, p2) == 0)
                        {
                            int oldIndex = index;
                            for (int i = 1; oldIndex + i < max; i++)
                            {
                                if (GetColumnsEqualExceptNumber(sub1.GetParagraphOrDefault(index + i), p2) > 1)
                                {
                                    for (int j = 0; j < i; j++)
                                    {
                                        sub2.Paragraphs.Insert(index, new Paragraph());
                                        index++;
                                    }
                                    break;
                                }
                                else if (GetColumnsEqualExceptNumber(p1, sub2.GetParagraphOrDefault(index + i)) > 1)
                                {
                                    for (int j = 0; j < i; j++)
                                    {
                                        sub1.Paragraphs.Insert(index, new Paragraph());
                                        index++;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                index++;
                p1 = sub1.GetParagraphOrDefault(index);
                p2 = sub2.GetParagraphOrDefault(index);
            }
            subtitleListView1.Fill(sub1);
            subtitleListView2.Fill(sub2);

            // coloring + differences index list
            _differences = new List<int>();
            index = 0;
            p1 = sub1.GetParagraphOrDefault(index);
            p2 = sub2.GetParagraphOrDefault(index);
            int totalWords = 0;
            int wordsChanged = 0;
            if (checkBoxOnlyListDifferencesInText.Checked)
            {
                while (index < sub1.Paragraphs.Count || index < sub2.Paragraphs.Count)
                {
                    if (p1 != null && p2 != null)
                    {
                        Utilities.GetTotalAndChangedWords(p1.Text, p2.Text, ref totalWords, ref wordsChanged, checkBoxIgnoreLineBreaks.Checked, GetBreakToLetter());
                        if (FixWhitespace(p1.ToString()) == FixWhitespace(p2.ToString()) && p1.Number == p2.Number)
                        { // no differences
                        }
                        else if (p1.ToString() == new Paragraph().ToString())
                        {
                            _differences.Add(index);
                            subtitleListView1.ColorOut(index, Color.Salmon);
                        }
                        else if (p2.ToString() == new Paragraph().ToString())
                        {
                            _differences.Add(index);
                            subtitleListView2.ColorOut(index, Color.Salmon);
                        }
                        else if (FixWhitespace(p1.Text) != FixWhitespace(p2.Text))
                        {
                            _differences.Add(index);
                            subtitleListView1.SetBackgroundColor(index, Color.LightGreen, SubtitleListView.ColumnIndexText);
                        }
                    }
                    else
                    {
                        if (p1 != null && p1.Text != null)
                            totalWords += Utilities.SplitForChangedCalc(p1.Text, checkBoxIgnoreLineBreaks.Checked, GetBreakToLetter()).Length;
                        else if (p2 != null && p2.Text != null)
                            totalWords += Utilities.SplitForChangedCalc(p2.Text, checkBoxIgnoreLineBreaks.Checked, GetBreakToLetter()).Length;
                        _differences.Add(index);
                    }
                    index++;
                    p1 = sub1.GetParagraphOrDefault(index);
                    p2 = sub2.GetParagraphOrDefault(index);
                }
            }
            else
            {
                while (index < sub1.Paragraphs.Count || index < sub2.Paragraphs.Count)
                {
                    if (p1 != null && p2 != null)
                    {
                        Utilities.GetTotalAndChangedWords(p1.Text, p2.Text, ref totalWords, ref wordsChanged, checkBoxIgnoreLineBreaks.Checked, GetBreakToLetter());
                        if (FixWhitespace(p1.ToString()) != FixWhitespace(p2.ToString()))
                            _differences.Add(index);

                        if (FixWhitespace(p1.ToString()) == FixWhitespace(p2.ToString()) && p1.Number == p2.Number)
                        { // no differences
                        }
                        else if (p1.ToString() == new Paragraph().ToString())
                        {
                            subtitleListView1.ColorOut(index, Color.Salmon);
                        }
                        else if (p2.ToString() == new Paragraph().ToString())
                        {
                            subtitleListView2.ColorOut(index, Color.Salmon);
                        }
                        else
                        {
                            int columnsAlike = GetColumnsEqualExceptNumber(p1, p2);
                            if (columnsAlike > 0)
                            {
                                if (p1.StartTime.TotalMilliseconds != p2.StartTime.TotalMilliseconds)
                                {
                                    subtitleListView1.SetBackgroundColor(index, Color.LightGreen,
                                                                         SubtitleListView.ColumnIndexStart);
                                    subtitleListView2.SetBackgroundColor(index, Color.LightGreen,
                                                                         SubtitleListView.ColumnIndexStart);
                                }
                                if (p1.EndTime.TotalMilliseconds != p2.EndTime.TotalMilliseconds)
                                {
                                    subtitleListView1.SetBackgroundColor(index, Color.LightGreen,
                                                                         SubtitleListView.ColumnIndexEnd);
                                    subtitleListView2.SetBackgroundColor(index, Color.LightGreen,
                                                                         SubtitleListView.ColumnIndexEnd);
                                }
                                if (p1.Duration.TotalMilliseconds != p2.Duration.TotalMilliseconds)
                                {
                                    subtitleListView1.SetBackgroundColor(index, Color.LightGreen,
                                                                         SubtitleListView.ColumnIndexDuration);
                                    subtitleListView2.SetBackgroundColor(index, Color.LightGreen,
                                                                         SubtitleListView.ColumnIndexDuration);
                                }
                                if (FixWhitespace(p1.Text.Trim()) != FixWhitespace(p2.Text.Trim()))
                                {
                                    subtitleListView1.SetBackgroundColor(index, Color.LightGreen,
                                                                         SubtitleListView.ColumnIndexText);
                                    subtitleListView2.SetBackgroundColor(index, Color.LightGreen,
                                                                         SubtitleListView.ColumnIndexText);
                                }

                                if (p1.Number != p2.Number)
                                {
                                    subtitleListView1.SetBackgroundColor(index, Color.LightYellow,
                                                                         SubtitleListView.ColumnIndexNumber);
                                    subtitleListView2.SetBackgroundColor(index, Color.LightYellow,
                                                                         SubtitleListView.ColumnIndexNumber);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (p1 != null && p1.Text != null)
                            totalWords += Utilities.SplitForChangedCalc(p1.Text, checkBoxIgnoreLineBreaks.Checked, GetBreakToLetter()).Length;
                        else if (p2 != null && p2.Text != null)
                            totalWords += Utilities.SplitForChangedCalc(p2.Text, checkBoxIgnoreLineBreaks.Checked, GetBreakToLetter()).Length;
                        _differences.Add(index);
                    }
                    index++;
                    p1 = sub1.GetParagraphOrDefault(index);
                    p2 = sub2.GetParagraphOrDefault(index);
                }
            }
            UpdatePreviousAndNextButtons();

            if (max == _differences.Count)
            {
                labelStatus.Text = Configuration.Settings.Language.CompareSubtitles.SubtitlesNotAlike;
                labelStatus.Font = new Font(labelStatus.Font.FontFamily, labelStatus.Font.Size, FontStyle.Bold);
            }
            else
            {
                if (wordsChanged != totalWords && wordsChanged > 0 && !string.IsNullOrEmpty(Configuration.Settings.Language.CompareSubtitles.XNumberOfDifferenceAndPercentChanged))
                {
                    string formatString = Configuration.Settings.Language.CompareSubtitles.XNumberOfDifferenceAndPercentChanged;
                    if (GetBreakToLetter() && !string.IsNullOrEmpty(Configuration.Settings.Language.CompareSubtitles.XNumberOfDifferenceAndPercentLettersChanged))
                        formatString = Configuration.Settings.Language.CompareSubtitles.XNumberOfDifferenceAndPercentLettersChanged;

                    labelStatus.Text = string.Format(formatString, _differences.Count, wordsChanged * 100 / totalWords);
                }
                else
                {
                    labelStatus.Text = string.Format(Configuration.Settings.Language.CompareSubtitles.XNumberOfDifference, _differences.Count);
                }
                labelStatus.Font = new Font(labelStatus.Font.FontFamily, labelStatus.Font.Size);
            }

            if (checkBoxShowOnlyDifferences.Checked)
            { // Remove all lines with no difference
                subtitleListView1.BeginUpdate();
                subtitleListView2.BeginUpdate();
                if (max != _differences.Count)
                {
                    for (index = Math.Max(subtitleListView1.Items.Count, subtitleListView2.Items.Count); index >= 0; index--)
                    {
                        if (!_differences.Contains(index))
                        {
                            if (subtitleListView1.Items.Count > index)
                                subtitleListView1.Items.RemoveAt(index);
                            if (subtitleListView2.Items.Count > index)
                                subtitleListView2.Items.RemoveAt(index);
                        }
                    }
                }
                subtitleListView1.EndUpdate();
                subtitleListView2.EndUpdate();
                _differences = new List<int>();
                for (index = 0; index < Math.Max(subtitleListView1.Items.Count, subtitleListView2.Items.Count); index++)
                    _differences.Add(index);
            }
            timer1.Start();
            subtitleListView1.FirstVisibleIndex = -1;
            subtitleListView1.SelectIndexAndEnsureVisible(0);
        }
Пример #16
0
 public Paragraph GetSelectedParagraph(Subtitle subtitle)
 {
     if (subtitle != null && SelectedItems.Count > 0)
         return subtitle.GetParagraphOrDefault(SelectedItems[0].Index);
     return null;
 }
Пример #17
0
        private void AddWaterMark(Subtitle subtitle, string input)
        {
            if (subtitle == null || subtitle.Paragraphs.Count == 0)
            {
                return;
            }

            byte[] buffer = Encoding.ASCII.GetBytes(input);

            if (radioButtonCurrentLine.Checked)
            {
                StringBuilder sb = new StringBuilder();
                foreach (byte b in buffer)
                {
                    sb.Append(zeroWhiteSpace);
                    for (int i = 0; i < b; i++)
                        sb.Append(zeroWidthNoBreakSpace);
                }
                Paragraph p = subtitle.GetParagraphOrDefault(_firstSelectedIndex);
                if (p != null)
                {
                    if (p.Text.Length > 1)
                        p.Text = p.Text.Insert(p.Text.Length / 2, sb.ToString());
                    else
                        p.Text = sb.ToString() + p.Text;
                }
            }
            else
            {
                Random r = new Random();
                List<int> indices = new List<int>();
                foreach (byte b in buffer)
                {
                    int number = r.Next(subtitle.Paragraphs.Count - 1);
                    if (indices.Contains(number))
                        number = r.Next(subtitle.Paragraphs.Count - 1);
                    if (indices.Contains(number))
                        number = r.Next(subtitle.Paragraphs.Count - 1);
                    indices.Add(number);
                }

                indices.Sort();
                int j = 0;
                foreach (byte b in buffer)
                {
                    StringBuilder sb = new StringBuilder();
                    Paragraph p = subtitle.Paragraphs[indices[j]];
                    sb.Append(zeroWhiteSpace);
                    for (int i = 0; i < b; i++)
                        sb.Append(zeroWidthNoBreakSpace);
                    if (p.Text.Length > 1)
                        p.Text = p.Text.Insert(p.Text.Length / 2, sb.ToString());
                    else
                        p.Text = sb.ToString() + p.Text;
                    j++;
                }
            }
        }
Пример #18
0
        public Subtitle SplitLongLinesInSubtitle(Subtitle subtitle, List<int> splittedIndexes, List<int> autoBreakedIndexes, out int numberOfSplits, int totalLineMaxCharacters, int singleLineMaxCharacters, bool clearFixes)
        {
            listViewFixes.ItemChecked -= listViewFixes_ItemChecked;
            if (clearFixes)
                listViewFixes.Items.Clear();
            numberOfSplits = 0;
            string language = Utilities.AutoDetectGoogleLanguage(subtitle);
            Subtitle splittedSubtitle = new Subtitle();
            Paragraph p = null;
            for (int i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                bool added = false;
                p = subtitle.GetParagraphOrDefault(i);
                if (p != null && p.Text != null)
                {
                    string oldText = Utilities.RemoveHtmlTags(p.Text);
                    if (SplitLongLinesHelper.QualifiesForSplit(p.Text, singleLineMaxCharacters, totalLineMaxCharacters) && IsFixAllowed(p))
                    {
                        bool isDialog = false;
                        string dialogText = string.Empty;
                        if (p.Text.Contains('-'))
                        {
                            dialogText = Utilities.AutoBreakLine(p.Text, 5, 1, language);
                            string[] arr = dialogText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                            if (arr.Length == 2 && (arr[0].StartsWith('-') || arr[0].StartsWith("<i>-")) && (arr[1].StartsWith('-') || arr[1].StartsWith("<i>-")))
                                isDialog = true;

                        }

                        if (!isDialog && !SplitLongLinesHelper.QualifiesForSplit(Utilities.AutoBreakLine(p.Text, language), singleLineMaxCharacters, totalLineMaxCharacters))
                        {
                            Paragraph newParagraph = new Paragraph(p);
                            newParagraph.Text = Utilities.AutoBreakLine(p.Text, language);
                            if (clearFixes)
                                AddToListView(p, (splittedSubtitle.Paragraphs.Count + 1).ToString(), oldText);
                            autoBreakedIndexes.Add(splittedSubtitle.Paragraphs.Count);
                            splittedSubtitle.Paragraphs.Add(newParagraph);
                            added = true;
                            numberOfSplits++;
                        }
                        else
                        {
                            string text = Utilities.AutoBreakLine(p.Text, language);
                            if (isDialog)
                                text = dialogText;
                            if (text.Contains(Environment.NewLine))
                            {
                                string[] arr = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                if (arr.Length == 2)
                                {
                                    int spacing1 = Configuration.Settings.General.MininumMillisecondsBetweenLines / 2;
                                    int spacing2 = Configuration.Settings.General.MininumMillisecondsBetweenLines / 2;
                                    if (Configuration.Settings.General.MininumMillisecondsBetweenLines % 2 == 1)
                                        spacing2++;

                                    Paragraph newParagraph1 = new Paragraph(p);
                                    Paragraph newParagraph2 = new Paragraph(p);
                                    newParagraph1.Text = Utilities.AutoBreakLine(arr[0], language);

                                    double startFactor = 0;
                                    double middle = p.StartTime.TotalMilliseconds + (p.Duration.TotalMilliseconds / 2);
                                    if (Utilities.RemoveHtmlTags(oldText).Trim().Length > 0)
                                    {
                                        startFactor = (double)Utilities.RemoveHtmlTags(newParagraph1.Text).Length / Utilities.RemoveHtmlTags(oldText).Length;
                                        if (startFactor < 0.25)
                                            startFactor = 0.25;
                                        if (startFactor > 0.75)
                                            startFactor = 0.75;
                                        middle = p.StartTime.TotalMilliseconds + (p.Duration.TotalMilliseconds * startFactor);
                                    }

                                    newParagraph1.EndTime.TotalMilliseconds = middle - spacing1;
                                    newParagraph2.Text = Utilities.AutoBreakLine(arr[1], language);
                                    newParagraph2.StartTime.TotalMilliseconds = newParagraph1.EndTime.TotalMilliseconds + spacing2;

                                    if (clearFixes)
                                        AddToListView(p, (splittedSubtitle.Paragraphs.Count + 1).ToString(), oldText);
                                    splittedIndexes.Add(splittedSubtitle.Paragraphs.Count);
                                    splittedIndexes.Add(splittedSubtitle.Paragraphs.Count + 1);

                                    string p1 = Utilities.RemoveHtmlTags(newParagraph1.Text);
                                    if (p1.EndsWith('.') || p1.EndsWith('!') || p1.EndsWith('?') || p1.EndsWith(':') || p1.EndsWith(')') || p1.EndsWith(']') || p1.EndsWith('♪'))
                                    {
                                        if (newParagraph1.Text.StartsWith('-') && newParagraph2.Text.StartsWith('-'))
                                        {
                                            newParagraph1.Text = newParagraph1.Text.Remove(0, 1).Trim();
                                            newParagraph2.Text = newParagraph2.Text.Remove(0, 1).Trim();
                                        }
                                        else if (newParagraph1.Text.StartsWith("<i>-") && newParagraph2.Text.StartsWith('-'))
                                        {
                                            newParagraph1.Text = newParagraph1.Text.Remove(3, 1).Trim();
                                            if (newParagraph1.Text.StartsWith("<i> "))
                                                newParagraph1.Text = newParagraph1.Text.Remove(3, 1).Trim();
                                            newParagraph2.Text = newParagraph2.Text.Remove(0, 1).Trim();
                                        }
                                    }
                                    else
                                    {
                                        bool endsWithComma = newParagraph1.Text.EndsWith(',') || newParagraph1.Text.EndsWith(",</i>");

                                        string post = string.Empty;
                                        if (newParagraph1.Text.EndsWith("</i>"))
                                        {
                                            post = "</i>";
                                            newParagraph1.Text = newParagraph1.Text.Remove(newParagraph1.Text.Length - post.Length);
                                        }
                                        if (endsWithComma)
                                            newParagraph1.Text += post;
                                        else
                                            newParagraph1.Text += comboBoxLineContinuationEnd.Text.TrimEnd() + post;

                                        string pre = string.Empty;
                                        if (newParagraph2.Text.StartsWith("<i>"))
                                        {
                                            pre = "<i>";
                                            newParagraph2.Text = newParagraph2.Text.Remove(0, pre.Length);
                                        }
                                        if (endsWithComma)
                                            newParagraph2.Text = pre + newParagraph2.Text;
                                        else
                                            newParagraph2.Text = pre + comboBoxLineContinuationBegin.Text + newParagraph2.Text;
                                    }

                                    if (newParagraph1.Text.IndexOf("<i>") >= 0 && newParagraph1.Text.IndexOf("<i>") < 10 & newParagraph1.Text.IndexOf("</i>") < 0 &&
                                        newParagraph2.Text.Contains("</i>") && newParagraph2.Text.IndexOf("<i>") < 0)
                                    {
                                        newParagraph1.Text += "</i>";
                                        newParagraph2.Text = "<i>" + newParagraph2.Text;
                                    }

                                    splittedSubtitle.Paragraphs.Add(newParagraph1);
                                    splittedSubtitle.Paragraphs.Add(newParagraph2);
                                    added = true;
                                    numberOfSplits++;
                                }
                            }
                        }
                    }
                }
                if (!added)
                    splittedSubtitle.Paragraphs.Add(new Paragraph(p));
            }
            listViewFixes.ItemChecked += listViewFixes_ItemChecked;
            splittedSubtitle.Renumber(1);
            return splittedSubtitle;
        }
Пример #19
0
        public void ContinueSpellcheck(Subtitle subtitle)
        {
            _subtitle = subtitle;

            if (_currentIndex >= subtitle.Paragraphs.Count)
                _currentIndex = 0;

            _currentParagraph = _subtitle.GetParagraphOrDefault(_currentIndex);
            if (_currentParagraph == null)
                return;

            SetWords(_currentParagraph.Text);
            _wordsIndex = -1;

            PrepareNextWord();
        }