Merging the SubLib project with Gnome Subtitles
[gn-sub.git] / src / SubLib / IO / Input / PlainTextParser.cs
blob334f93c8944129cb91a946c5f3de0c801efd5aed
1 /*
2 * This file is part of SubLib.
3 * Copyright (C) 2007-2008 Pedro Castro
5 * SubLib is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * SubLib is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 using SubLib.Core.Domain;
21 using System;
22 using System.IO;
23 using System.Text;
24 using System.Text.RegularExpressions;
26 namespace SubLib.IO.Input {
28 internal class PlainTextParser {
30 private bool withCharacterNames = false;
31 private string lineSeparator = String.Empty;
32 private string text = String.Empty;
34 internal PlainTextParser(bool withCharacterNames, string lineSeparator) {
35 this.withCharacterNames = withCharacterNames;
36 this.lineSeparator = lineSeparator;
39 internal PlainTextParser(bool withCharacterNames) : this(withCharacterNames, @"\n") {
41 /// <summary>Parses the specified text.</summary>
42 /// <remarks>The created <see cref="SubtitleCollection" /> will have its <see cref="SubtitleProperties" /> property set to null.
43 /// It is mandatory to use <see cref="SubtitleCollection.SetPropertiesForAll" /> after.</remarks>
44 internal ParsingProperties Parse (string text, TimingMode timingMode, Encoding encoding, out SubtitleCollection collection) {
46 collection = new SubtitleCollection();
47 ParsingProperties properties = new ParsingProperties();
48 this.text = text;
49 properties.TimingMode = timingMode;
51 /* Read the subtitles */
52 ReadSubtitles(encoding, properties, collection);
54 return properties;
57 private void ReadSubtitles (Encoding encoding, ParsingProperties properties, SubtitleCollection collection) {
59 string[] lines = text.Split(new char[] {'\n'});
60 for (int i = 0; i < lines.Length; i++) {
61 SubtitleText stext = ParseSubtitleText(lines[i]);
62 Style style = new Style();
63 if(!stext.IsEmpty) {
64 Subtitle subtitle = new Subtitle(null, stext, style);
65 collection.Add(subtitle);
71 private SubtitleText ParseSubtitleText (string line) {
72 string text = String.Empty;
73 if (withCharacterNames) {
74 string[] pieces = line.Split(new char[] { ':' });
75 if (pieces.Length > 1)
76 text = pieces[1];
77 else
78 text = pieces[0];
80 else
81 text = line;
83 if (text.Length > 0)
84 return new SubtitleText(text, lineSeparator, true);
85 else return new SubtitleText();