public Subtitles Create(Subtitles subtitles) { var subs = _context.Subtitles.Add(subtitles); _context.SaveChanges(); return(subs); }
/// <summary>Removes the entire translation from existing subtitles.</summary> /// <param name="subtitles">The subtitles to remove the translation from.</param> public void Clear(Subtitles subtitles) { foreach (Subtitle subtitle in subtitles.Collection) { subtitle.ClearTranslation(); } }
public void Map_Always_ReturnsUnvalidatedSubtitles() { var subsToMap = new Subtitles( new List <Subtitle> { SubtitleTests.CreateSubtitle1(), SubtitleTests.CreateSubtitle2() }); var stubMapper = Substitute.For <ISubtitleToUnvalidatedMapper>(); var expectedUnvalidatedSubs = new UnvalidatedSubtitles( new List <UnvalidatedSubtitle> { UnvalidatedSubtitleTests.CreateUnvalidatedSubtitle1(), UnvalidatedSubtitleTests.CreateUnvalidatedSubtitle2() }); stubMapper .Map(Arg.Is(subsToMap.Value.ElementAt(0))) .Returns(expectedUnvalidatedSubs.Value.ElementAt(0)); stubMapper .Map(Arg.Is(subsToMap.Value.ElementAt(1))) .Returns(expectedUnvalidatedSubs.Value.ElementAt(1)); var mapper = CreateMapper(stubMapper); var actualUnvalidatedSubs = mapper.Map(subsToMap); Assert.AreEqual( expectedUnvalidatedSubs, actualUnvalidatedSubs); }
public void Format_Always_ReturnsCostRelatedToGivenCurrency() { var stubProvider = Substitute.For <ICostForOneMillionCharactersProvider>(); stubProvider .GetCostIn(Arg.Is(Currency.Euro)) .Returns(20); var stubFormatter = Substitute.For <ISubtitleTextFormatter>(); stubFormatter .Format(Arg.Any <SubtitleText>()) .Returns("25 characters long string"); var calculator = CreateCalculator(stubProvider, stubFormatter); var twoSubtitles = new Subtitles( new List <Subtitle> { SubtitleTests.CreateSubtitle1(), SubtitleTests.CreateSubtitle2() }); var expectedCost = new Price(0.001m, Currency.Euro); var actualCost = calculator.Calculate(twoSubtitles, Currency.Euro); Assert.AreEqual(expectedCost, actualCost); }
/// <summary> /// Add translation to the list with original subtitles. /// </summary> /// <param name="translationSubtitles">List with translation.</param> private void addTranslation(Subtitles translationSubtitles) { if (savedAllChanged()) { int i = 0; foreach (Subtitle sub in subtitleList) { if (i < translationSubtitles.Count) { sub.Translation = translationSubtitles[i].Original; } else { sub.Translation = Properties.Settings.Default.newTranslationText; } i++; } // in the translation can be more than rows then in the original // it is not good to just ignore them for (int j = i; j < translationSubtitles.Count; j++) { Subtitle sub = new Subtitle(); sub.Translation = translationSubtitles[j].Original; subtitleList.Add(sub); } i++; } }
public Subtitles Delete(Subtitles subtitles) { var subs = _context.Subtitles.Remove(subtitles); _context.SaveChanges(); return(subs); }
internal void saveAsFunction(Subtitles subList) { if (getSaveFileName()) { SubFile.WriteSubFile(FileName, FileEncoding, subList, What); } }
internal bool saveFileChanged(Subtitles subList) { if (!Changed) { return(true); } string message; if (What == WhichText.Original) { message = "Original subtitles were changed. Save them?"; } else { message = "Translation subtitles were changed. Save them?"; } MessageBoxResult result = MessageBox.Show(message, "Attention!", MessageBoxButton.YesNoCancel); if (result == MessageBoxResult.Cancel) { return(false); } else if (result == MessageBoxResult.Yes) { if (!saveFunction(subList)) { return(false); } } Changed = false; return(true); }
/// <summary> /// Loads a subtitles file. /// </summary> /// <param name="filePath">The path to the file.</param> public void LoadSubtitles(string filePath) { if (!Player.GetComponent <MediaComponent>( ).HasMediaBeenLoaded) { throw new Exception("Unable to load subtitles before any media has been loaded."); } if (HaveSubtitlesBeenLoaded) { this.UnloadSubtitles( ); } FileInfo file = new FileInfo(filePath); Subtitles = Subtitles.LoadSubtitlesFile(filePath); enabled = Subtitles.SubtitlesParsedSuccesfully; if (Subtitles.SubtitlesParsedSuccesfully) { OnSubtitlesLoaded?.Invoke(this, new OnSubtitlesLoadedEventArgs(file)); this.CheckForSubtitles( ); } else { Subtitles = null; OnSubtitlesFailedToLoad?.Invoke(this, new OnSubtitlesFailedToLoadEventArgs(file)); } }
/// <summary> /// Metodo para crear un subtitulo que mezcle dos idiomas aleatoriamente /// </summary> /// <param name="id"> identificador del subtitulos</param> /// <returns></returns> public Subtitles MixLanguagesInSubtitles(int id) { currentLanguajeSub = new Subtitles(GameSubtitles.Single(x => x.Id == id)); if (idCurrentLanguage < 2)//Si estamos en castellano o ingles { //se mezclara con el ukraniano wrongLanguajeSub = languagesGame[2].Subtitles.Single(x => x.Id == id); } else //Si estamos en ucraniano { //se mezclara con el español wrongLanguajeSub = languagesGame[0].Subtitles.Single(x => x.Id == id); } //por cada linea de texto del subtitulo for (int i = 0; i < currentLanguajeSub.SubList.Count; i++) { ////obtiene las listas de palabras wordsRightIdiom = currentLanguajeSub.SubList[i].Txt.Split(' '); wordsWrongIdiom = wrongLanguajeSub.SubList[i].Txt.Split(' '); currentLanguajeSub.SubList[i].Txt = RandomMixTwoTexts(); } return(currentLanguajeSub); }
private string UpdateFilenameExtension(string filename, SubtitleType type) { SubtitleTypeInfo typeInfo = Subtitles.GetAvailableType(type); string newExtensionDotted = "." + typeInfo.PreferredExtension; int index = -1; string extensionDotted = "." + GetFilenameExtension(filename, out index); if (extensionDotted == newExtensionDotted) //filename already has the correct extension { return(filename); } else if (index == -1) //filename doesn't have an extension, appending { return(filename + newExtensionDotted); } else if (Subtitles.IsSubtitleExtension(extensionDotted)) //filename's extension is a subtitle extension { int dotIndex = index - 1; return(filename.Substring(0, dotIndex) + newExtensionDotted); } else //filename's extension is not a subtitle extension { return(filename + newExtensionDotted); } }
public void ShowEDMII() { Subtitles.show("I'm back", 15f, enermyColor); Subtitles.show("with a larger army", 15f, enermyColor); StartCoroutine(CreateEnermyInCircle()); }
private static bool AreSyncIndicesValid(Subtitles subtitles, int startIndex, int endIndex) { int subtitleCount = subtitles.Collection.Count; if (subtitleCount < 2) { return(false); } else if (!(startIndex < endIndex)) { return(false); } else if ((startIndex < 0) || (startIndex >= (subtitleCount - 1))) { return(false); } else if (endIndex >= subtitleCount) { return(false); } else { return(true); } }
/// <summary>Auto syncs a range of subtitles given their first and last correct frames.</summary> /// <remarks>The subtitles are first shifted to the first subtitle's correct frame, and then proportionally /// adjusted using the last subtitle's correct frame.</remarks> /// <param name="subtitles">The subtitles to sync.</param> /// <param name="startIndex">The subtitle index to start the adjustment with.</param> /// <param name="startFrame">The correct start frame for the first subtitle.</param> /// <param name="endIndex">The subtitle index to end the adjustment with.</param> /// <param name="endFrame">The correct start frame for the last subtitle.</param> /// <param name="syncLast">Whether to sync the last subtitle.</param> /// <returns>Whether the subtitles could be adjusted.</returns> public static bool Sync(Subtitles subtitles, int startIndex, int startFrame, int endIndex, int endFrame, bool syncLast) { if (!AreSyncArgsValid(subtitles, startIndex, startFrame, endIndex, endFrame)) { return(false); } /* Perform initial calculations */ int syncEndIndex = (syncLast ? endIndex : endIndex - 1); Subtitle startSubtitle = subtitles.Collection.Get(startIndex); int shift = (int)(startFrame - startSubtitle.Frames.PreciseStart); Subtitle endSubtitle = subtitles.Collection.Get(endIndex); double factor = (endFrame - startFrame) / (endSubtitle.Frames.PreciseStart - startFrame); /* Shift subtitles to the start point */ if (shift != 0) { ShiftOperator shiftOp = new ShiftOperator(subtitles); shiftOp.Shift(shift, startIndex, syncEndIndex); } /* Auto adjust timings with proportion */ for (int index = startIndex; index <= syncEndIndex; index++) { Subtitle subtitle = subtitles.Collection.Get(index); subtitle.Frames.Scale(factor, startFrame); } return(true); }
public void SetUpSingleSub(Subtitles sub) { ResetSubs(); FadeIn(); StartCoroutine(ShowSubs(sub.text, 0)); StartCoroutine(MyCoroutines.StartTimer(sub.duration, FadeOut)); }
public void Parse_SuccessfulParsing_ReturnsSubtitles() { var unvalidatedSubtitles = new UnvalidatedSubtitles( new List <UnvalidatedSubtitle> { UnvalidatedSubtitleTests.CreateUnvalidatedSubtitle1(), UnvalidatedSubtitleTests.CreateUnvalidatedSubtitle2() }); var expectedSubtitles = new Subtitles( new List <Subtitle> { SubtitleTests.CreateSubtitle1(), SubtitleTests.CreateSubtitle2() }); var stubParser = Substitute.For <ISubtitleParser>(); stubParser .Parse(Arg.Is(unvalidatedSubtitles.Value.ElementAt(0))) .Returns(expectedSubtitles.Value.ElementAt(0)); stubParser .Parse(Arg.Is(unvalidatedSubtitles.Value.ElementAt(1))) .Returns(expectedSubtitles.Value.ElementAt(1)); var parser = CreateParser(stubParser); var actualSubtitles = parser.Parse(unvalidatedSubtitles); Assert.AreEqual( expectedSubtitles, actualSubtitles); }
private IEnumerator Ending() { PernicekCtrl.TurnedOn = false; mover.InGame = false; foreach (IntroItem item in items) { audioSource.clip = item.clip; audioSource.Play(); camera.transform.DOMove(item.cameraEnd.position, item.clip.length).SetEase(Ease.InOutSine); camera.DOOrthoSize(item.cameraSize, item.clip.length).SetEase(Ease.InOutSine); Subtitles.ShowText(item.subtitle); yield return(new WaitForSeconds(item.clip.length)); } Subtitles.HideText(); camera.DOOrthoSize(finalSize, 1); camera.transform.DOMove(finalPosition.position, 1); yield return(new WaitForSeconds(1)); credits.gameObject.SetActive(true); credits.DOAnchorPosY(0, 50).SetEase(Ease.Linear); yield return(new WaitForSeconds(50)); playAgainButton.gameObject.SetActive(true); }
public void OnAssignedVehicle(Vehicle vehicle) { Debug.Log("Received a new vehicle:" + vehicle.name); if (hud == null) { var hudObject = Instantiate(hudPrefab) as GameObject; hud = hudObject.GetComponentInChildren <PlayerHud>(); hud.quitMinigameButton.gameObject.SetActiveRecursively1(false); minimap = hud.GetComponentInChildren <Minimap>(); subtitles = hud.GetComponentInChildren <Subtitles>(); var playerCamera = SetupGameplayCamera(vehicle.gameObject, vehicle.transform); minimap.cameraToFollow = playerCamera.GetComponent <Camera>(); var avatarQuest = vehicle.GetComponentInChildren <AvatarQuest>(); if (avatarQuest != null) { var minimapCamera = hud.GetComponentInChildren <MinimapCamera>(); minimapCamera.objectToFollow = avatarQuest; var minimapSurface = hud.GetComponentInChildren <MinimapSurface>(); minimapSurface.avatarToFollow = avatarQuest; } } }
void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { Subtitles.showByID("lorem"); } }
/// <summary> /// Muestra los subtitulos por pantalla en la parte de abajo /// </summary> /// <param name="subs">subtitulos que se quieren mostrar</param> /// <param name="isDaySub"> si es el subtitulo que muestra el dia le añadade su numero</param> /// <returns></returns> public IEnumerator ShowSubtitles(Subtitles subs, bool isDaySub) { int cont = 0; if (arrowBack.enabled) { arrowBack.interactable = false; } yield return(StartCoroutine(CorgiTools.FadeCanvasGroup(subtitlesGroup, 0.5f, 1f))); while (cont < subs.SubList.Count) { this.subtitleText.text = subs.SubList[cont].Txt; if (isDaySub) { this.subtitleText.text += (DaysManager.Instance.Day + 1); } yield return(new WaitForSeconds(subs.SubList[cont].Duration)); cont++; } this.subtitleText.text = ""; yield return(StartCoroutine(CorgiTools.FadeCanvasGroup(subtitlesGroup, 0.5f, 0f))); if (arrowBack.enabled) { arrowBack.interactable = true; } this.currentCorutine = null; }
/// <summary> /// Muestra los subtitulos por pantalla en la parte central de la pantalla /// </summary> /// <param name="id">identificador de los subtitulos que se quieren mostrar</param> /// <returns></returns> public IEnumerator ShowSubsInCartel(int id, bool endDay) { this.currentCartel = TextsManager.Instance.GameSubtitles.Single(x => x.Id == id); int cont = 0; yield return(StartCoroutine(FadeInOut.Instance.CrossFadeAlpha(1, 0.5f))); yield return(StartCoroutine(CorgiTools.FadeText(cartelText, 0.5f, Color.white))); while (cont < currentCartel.SubList.Count) { subDuration = currentCartel.SubList[cont].Duration; SkipSubtitles = false; timeWaitedSub = 0; this.cartelText.text = currentCartel.SubList[cont].Txt; while (timeWaitedSub < subDuration && SkipSubtitles == false) { timeWaitedSub += 0.3f; yield return(new WaitForSeconds(0.3f)); } cont++; } this.cartelText.text = ""; if (!endDay) { yield return(StartCoroutine(CorgiTools.FadeText(cartelText, 0.5f, Color.white))); yield return(StartCoroutine(FadeInOut.Instance.CrossFadeAlpha(0, 0.5f))); } this.currentCorutine = null; }
public ActionResult UploadForSeries(Subtitles subtitles, int itemId, int episodeId, HttpPostedFileBase file) { Logger.Log.InfoFormat(Logger.Format + "POST Request for UploadForSeries for series with id: " + itemId + " and episode with id: " + episodeId + " and subtitles: " + subtitles.ToString(), GetType().ToString()); SubtitlesManager.UploadForSeries(subtitles, itemId, episodeId, file); TempData["upload-success"] = true; return(RedirectToAction("Index", "Home")); }
protected override void InitLevelSpecific() { Music = new GameMusic(); Add(Music); SubtitleText t = new SubtitleText(); t.AddText("QUEST FOR THE\nPIXEL PRINCESS", 6f); t.AddText("You, The Golden Knight, must\nrescue the princess...", 5f); t.AddText("...from the clutches of\nthe evil Red Guard.", 5f); //t.AddText("...from the clutches of\nthe evil Red Guard.", 5f); Subtitles.Show(0, t); t = new SubtitleText("My ears! Hark the drums\nof the Red Guard!"); t.StartTime = 64.0f; t.Duration = 10.0f; Subtitles.Show(0, t); t = new SubtitleText(); t.AddText("Music 'The Never Ending Quest For The\nPrincess II' by Producer Snafu!\nCC-BY-NC producersnafu.bandcamp.com", 10f); t.AddText("FMOD Audio engine\n(c) Firelight Technologies Pty, Ltd. 2004-2009.", 6f); //t.Duration = 10f; Parent.Add(t); t.ScaleVector = new Vector2(1f, 1f); t.Motion.Scale = 0.35f;/// DEFAULT_SCALE; t.Motion.Position = new Vector2(0.35f, 0.25f); //t.DrawInfo.Center = Vector2.Zero; t.StartTime = 17f; }
public bool ParseLineFromFile(string line) { if (!string.IsNullOrWhiteSpace(line)) { var splitLine = line.Split(new[] { ' ' }, 2); if (HeaderKeys.Contains(splitLine[0]) && !this.ContainsKey(splitLine[0])) { Add(splitLine[0], splitLine[1]); } else if (line.StartsWith("subtitle") || line.StartsWith("sub")) { Subtitles.AddFromString(line); } else if (line.StartsWith("comment")) { Comments.Add(line.Substring(8, line.Length - 8)); } else if (line.StartsWith("|")) { return(false); } } return(true); }
protected void AddBk2Lumps(ZipStateSaver bs) { bs.PutLump(BinaryStateLump.Movieheader, tw => tw.WriteLine(Header.ToString())); bs.PutLump(BinaryStateLump.Comments, tw => tw.WriteLine(CommentsString())); bs.PutLump(BinaryStateLump.Subtitles, tw => tw.WriteLine(Subtitles.ToString())); bs.PutLump(BinaryStateLump.SyncSettings, tw => tw.WriteLine(SyncSettingsJson)); bs.PutLump(BinaryStateLump.Input, WriteInputLog); if (StartsFromSavestate) { if (TextSavestate != null) { bs.PutLump(BinaryStateLump.CorestateText, (TextWriter tw) => tw.Write(TextSavestate)); } else { bs.PutLump(BinaryStateLump.Corestate, (BinaryWriter bw) => bw.Write(BinarySavestate)); } if (SavestateFramebuffer != null) { bs.PutLump(BinaryStateLump.Framebuffer, (BinaryWriter bw) => bw.Write(SavestateFramebuffer)); } } else if (StartsFromSaveRam) { bs.PutLump(BinaryStateLump.MovieSaveRam, (BinaryWriter bw) => bw.Write(SaveRam)); } }
/// <summary>Auto syncs a range of subtitles given their first and last correct times.</summary> /// <remarks>The subtitles are first shifted to the first subtitle's correct time, and then proportionally /// adjusted using the last subtitle's correct time.</remarks> /// <param name="subtitles">The subtitles to sync.</param> /// <param name="startIndex">The subtitle index to start the adjustment with.</param> /// <param name="startTime">The correct start time for the first subtitle.</param> /// <param name="endIndex">The subtitle index to end the adjustment with.</param> /// <param name="endTime">The correct start time for the last subtitle.</param> /// <param name="syncLast">Whether to sync the last subtitle.</param> /// <returns>Whether the subtitles could be adjusted.</returns> public static bool Sync(Subtitles subtitles, int startIndex, TimeSpan startTime, int endIndex, TimeSpan endTime, bool syncLast) { if (!AreSyncArgsValid(subtitles, startIndex, startTime, endIndex, endTime)) { return(false); } /* Perform initial calculations */ int syncEndIndex = (syncLast ? endIndex : endIndex - 1); Subtitle startSubtitle = subtitles.Collection.Get(startIndex); TimeSpan shift = startTime - startSubtitle.Times.PreciseStart; Subtitle endSubtitle = subtitles.Collection.Get(endIndex); double factor = (endTime - startTime).TotalMilliseconds / (endSubtitle.Times.PreciseStart - startSubtitle.Times.PreciseStart).TotalMilliseconds; /* Shift subtitles to the start point */ if (shift != TimeSpan.Zero) { ShiftOperator shiftOp = new ShiftOperator(subtitles); shiftOp.Shift(shift, startIndex, syncEndIndex); } /* Sync timings with proportion */ for (int index = startIndex; index <= syncEndIndex; index++) { Subtitle subtitle = subtitles.Collection.Get(index); subtitle.Times.Scale(factor, startTime); } return(true); }
public void Awake() { DontDestroyOnLoad(this); MethodInfo processAndRequestMethod = typeof(UILabel).GetMethod("ProcessAndRequest"); processAndRequest = label => processAndRequestMethod?.Invoke(label, null); Memory = new TranslationMemory(DataPath); Clipboard = gameObject.AddComponent <Clipboard>(); Subtitles = gameObject.AddComponent <Subtitles>(); InitConfig(); Memory.LoadTranslations(); TranslationHooks.TranslateText += OnTranslateString; TranslationHooks.AssetTextureLoad += OnAssetTextureLoad; TranslationHooks.ArcTextureLoad += OnTextureLoad; TranslationHooks.SpriteLoad += OnTextureLoad; TranslationHooks.ArcTextureLoaded += OnArcTextureLoaded; TranslationHooks.TranslateGraphic += OnTranslateGraphic; TranslationHooks.PlaySound += OnPlaySound; TranslationHooks.GetOppositePair += OnGetOppositePair; TranslationHooks.GetOriginalText += OnGetOriginalText; Logger.WriteLine("Hooking complete"); }
void Start() { // Load the subtitles XML file Subtitles.loadFromXML("Subtitles"); // A Subtitles.xml file in a Resources/ folder // Show a first subtitle programmatically (not from the xml file) Subtitles.show("Welcome to the Subtitles and Closed Captions demo.", 4.0f, Color.green, true); }
public static bool CreateFileSubtitle(int index, List <string> texts) { try { Subtitles subtitle = new Subtitles(); // index là số thứ tự ảnh được chuyền vào từ lớp videocontroler qua hàm getsubfromvideo() subtitle.index = index; subtitle.timeStart = Process(index); subtitle.timeStart.milisecond = 0; subtitle.timeEnd = Process(index); subtitle.timeEnd.milisecond = 999; subtitle.contentSubtitle = texts; using (StreamWriter writer = new StreamWriter(@"Subtitles.txt", true)) { writer.WriteLine(subtitle.index); writer.WriteLine(subtitle.timeStart.ToString() + " --> " + subtitle.timeEnd.ToString()); foreach (string line in subtitle.contentSubtitle) { writer.WriteLine(line); } writer.WriteLine(); } return(true); } catch { return(false); } }
private Subtitles EmptySubtitles(string path) { Subtitles subtitles = New(); fileProperties = new FileProperties(path, Encoding.UTF8, SubtitleType.Unknown, TimingMode.Times); return(subtitles); }
/// <summary> /// Gets subtitles meta. /// </summary> /// <param name="releaseName">Name of the release.</param> /// <param name="language"></param> /// <returns>The query result.</returns> public override QueryResult<Subtitles> GetSubtitlesMeta(string releaseName, Language language) { var cultureInfo = language.GetCultureInfo(); var langString = cultureInfo == null ? "eng" : cultureInfo.ThreeLetterISOLanguageName; var subtitles = new Subtitles(); subtitles.AddRange(this.client.SearchSubtitlesFromQuery(langString, releaseName).Select(this.Convert)); return new QueryResult<Subtitles>(Status.Success, subtitles); }
void Awake () { if(instance == null) { instance = this; } else { Debug.LogError("There were two Subtitle objects. Destroying "+gameObject.name); Destroy(gameObject); } myAudioSource = GetComponent<AudioSource> (); subtitlesPanel.color = Color.clear; subtitlesText.color = Color.clear; hintsPanel.color = Color.clear; hintsText.color = Color.clear; }
public void LoadSubs(Button button, Subtitles subtitles) { if (CheckException.CheckNull(this.VideoName)) { OpenFileDialog Dialog1 = new OpenFileDialog(); Dialog1.InitialDirectory = "c:\\"; Dialog1.Filter = Formats; Dialog1.FilterIndex = 2; Dialog1.RestoreDirectory = true; if (Dialog1.ShowDialog() == DialogResult.OK) { if (Dialog1.OpenFile() != null) { this.SubsName = Dialog1.FileName; } } if (CheckException.CheckNull(this.SubsName)) { subtitles.Load(this.SubsName); } } }
private static string PickSub(int currentVideoTime, Subtitles subtitles) { string correctSubtitle = ""; for (int i = 0; i < subtitles.SubtitleLinesTotal; i++) { if (currentVideoTime >= subtitles.StartSubTime[i] && currentVideoTime <= subtitles.EndSubTime[i]) { correctSubtitle = subtitles.Subtitle[i]; } } return correctSubtitle; }
/// <summary> /// Save subtitles to file. /// Asks for name if it is a new file. /// </summary> /// <param name="subFile">File with subtitles.</param> /// <param name="what">if it is original or translation</param> /// <returns></returns> internal bool saveFunction(Subtitles subList) { if (subFile == null) { if (!getSaveFileName()) return (false); } SubFile.WriteSubFile(FileName, FileEncoding, subList,What); return (true); }
public MainWindow() { string org = null; string trans = null; string vid = null; string proj = null; string[] arg = Environment.GetCommandLineArgs(); if (arg.Length > 1) { if (arg[1] == "/h" || arg[1] == "/?") { Console.WriteLine("SFKSubEditor [project|original [translation] [movie]]"); Console.WriteLine("project - project file"); Console.WriteLine("original - original subtitles"); Console.WriteLine("translation - translation subtitles"); Console.WriteLine("video - video file"); Application.Current.Shutdown(); Environment.Exit(0); } if (arg[1].Substring(arg[1].LastIndexOf(".") + 1) == MainWindow.projectFileExtension) proj = arg[1]; else org = arg[1]; if (arg.Length > 2) trans = arg[2]; if (arg.Length > 3) vid = arg[3]; } InitializeComponent(); InitializeCommands(); if (org != null) { originalFile = new SubtitlesFile(SubtitlesFile.WhichText.Original,org); subtitleList = originalFile.fileOpen(subtitleList); if (trans != null) { translationFile = new SubtitlesFile(SubtitlesFile.WhichText.Translation,trans); Subtitles translationSubtitles = translationFile.fileOpen(null); addTranslation(translationSubtitles); } if (vid != null) { videoFile = vid; video.Source = new Uri(videoFile,UriKind.Relative); } else { videoFile = getVideoFileFromSubtitle(originalFile.FileName); if (videoFile != null) { video.Source = new Uri(videoFile, UriKind.Relative); } } } else if (proj != null) { } else { // from the beginning we have new subtitles newOriginalFunction(); } dataGrid1.ItemsSource = subtitleList; dataGrid1.DataContext = subtitleList; showColumns(); timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(50); timer.Tick += new EventHandler(timer_Tick); PlayVideo(); }
internal void saveAsFunction(Subtitles subList) { if (getSaveFileName()) SubFile.WriteSubFile(FileName, FileEncoding, subList, What); }
internal bool saveFileChanged(Subtitles subList) { if (!Changed) return(true); string message; if (What == WhichText.Original) message = "Original subtitles were changed. Save them?"; else message = "Translation subtitles were changed. Save them?"; MessageBoxResult result = MessageBox.Show(message, "Attention!", MessageBoxButton.YesNoCancel); if (result == MessageBoxResult.Cancel) { return (false); } else if (result == MessageBoxResult.Yes) { if (!saveFunction(subList)) return (false); } Changed = false; return (true); }
public Subtitles fileOpen(Subtitles subList) { if (subList != null) { subList.Clear(); } else { subList = new Subtitles(); } if (FileName == null) return(null); if (FileEncoding == null) { getFileEncoding(); } // type of subtiles depends on the extension // not perfect but practic string extension = getExtension(FileName); switch (extension) { case "srt": subFile = new SrtSubtitlesFile(); break; case "txt": case "sub": subFile = new SubSubtitlesFile(); break; default: // spatna/nepodporovany format //return (SubOpenStatus.BadFormat); return (null); } subFile.ReadSubFile(FileName, FileEncoding, subList); //SubtitleType = sub.SubtitleType; return (subList); }
internal Subtitles createNewSubtitles(Subtitles subList) { if (subList != null) subList.Clear(); else subList = new Subtitles(); subFile = new SrtSubtitlesFile(); FileEncoding = Encoding.UTF8; subList.Add(new Subtitle(new TimeSpan(0, 0, 0, 1), new TimeSpan(0, 0, 0, MainWindow.newSubtitleLength), "new")); return (subList); }
/* TODO: Not in use as we are not searching for movie title /// <summary>The parse query doc.</summary> /// <param name="htmlDoc">The html doc.</param> /// <returns>The <see cref="string"/>.</returns> private Tuple<result, string> ParseTitleDoc(HtmlDocument htmlDoc) { var resultNodes = htmlDoc.DocumentNode.SelectNodes("//div[@class='search-result']"); if (resultNodes == null) { return Tuple.Create(result.Failure, string.Empty); } var exactList = new List<ItemData>(); var popularList = new List<ItemData>(); var closeList = new List<ItemData>(); List<ItemData> activeList = null; foreach (var resultNode in resultNodes) { foreach (var childNode in resultNode.ChildNodes) { if (childNode.Name == "h2") { var nodeClass = childNode.GetAttributeValue("class", string.Empty); activeList = nodeClass == "exact" ? exactList : (nodeClass == "popular" ? popularList : (nodeClass == "close" ? closeList : null)); continue; } if (activeList != null && childNode.Name == "ul") { var titleNodes = childNode.SelectNodes(".//div[@class='title']"); if (titleNodes == null) { continue; } foreach (var titleNode in titleNodes) { var linkNode = titleNode.SelectNodes(".//a").FirstOrDefault(); if (linkNode == null) { continue; } var link = linkNode.GetAttributeValue("href", string.Empty).Trim(); if (!string.IsNullOrEmpty(link)) { string count = null; var countNode = titleNode.NextSibling; while (countNode != null) { if (countNode.GetAttributeValue("class", string.Empty).Contains("count")) { count = string.Format("({0})", countNode.InnerText.Trim()); break; } countNode = countNode.NextSibling; } var title = HttpUtility.HtmlDecode(titleNode.InnerText).Trim(); activeList.Add(new ItemData(title, link) { Description = HttpUtility.HtmlDecode(count) }); } } activeList = null; } } } var matchingUrl = this.GetSubtitlePageUrl(exactList, popularList, closeList); var itemData = matchingUrl.Item2; var url = itemData == null || string.IsNullOrEmpty(itemData.Tag as string) ? string.Empty : "http://subscene.com" + itemData.Tag; return Tuple.Create(matchingUrl.Item1, url); } /// <summary>The get matching url.</summary> /// <param name="exactList">The exact list.</param> /// <param name="popularList">The popular list.</param> /// <param name="closeList">The close list.</param> /// <returns>The <see cref="ItemData"/>.</returns> private Tuple<result, ItemData> GetSubtitlePageUrl(List<ItemData> exactList, List<ItemData> popularList, List<ItemData> closeList) { // Process the actual subtitle link foreach (var matchingTitle in exactList) { return Tuple.Create(result.Success, matchingTitle); } var comparer = new InlineComparer<ItemData>((a, b) => string.Equals(a.Name, b.Name), i => i == null ? 0 : i.GetHashCode()); var selections = popularList.Union(closeList, comparer).ToList(); if (!selections.Any()) { this.view.Notify(Literals.Data_No_matching_title_for + this.FilePath); return Tuple.Create<result, ItemData>(result.Failure, null); } var matchingUrl = this.view.GetSelection(selections, this.FilePath, Literals.Data_Select_matching_video_title); return matchingUrl; } */ /// <summary> /// Parses subtitle release document. /// </summary> /// <param name="htmlDoc">The HTML document.</param> /// <returns>The query result.</returns> private QueryResult<Subtitles> ParseSubtitleReleaseDoc(HtmlDocument htmlDoc) { var subtitleNodes = htmlDoc.DocumentNode.SelectNodes("//td[@class='a1']"); Subtitles subtitles = new Subtitles(); var result = Status.Failure; if (subtitleNodes != null) { foreach (var subtitleNode in subtitleNodes) { var linkNode = subtitleNode.SelectSingleNode(".//a"); if (linkNode == null) { continue; } var link = linkNode.GetAttributeValue("href", string.Empty); var rating = Rating.Dot; var linkSpanNodes = linkNode.SelectNodes(".//span"); var rateNode = linkSpanNodes.FirstOrDefault(); if (rateNode != null) { var rateClass = rateNode.GetAttributeValue("class", string.Empty).Split(' ').LastOrDefault(); if (!string.IsNullOrEmpty(rateClass) && rateClass.Contains("-icon")) { var rate = rateClass.Substring(0, rateClass.Length - 5); Enum.TryParse(rate, true, out rating); } } var titleNode = linkSpanNodes.LastOrDefault(); if (titleNode == null) { continue; } var title = titleNode.InnerText.Trim(); var commentNode = subtitleNode.ParentNode.SelectSingleNode(".//td[@class='a6']/div"); string description = string.Empty; if (commentNode != null) { description = commentNode.InnerText.Trim(); } description = HttpUtility.HtmlDecode(description.Replace(Environment.NewLine, " ")); title = HttpUtility.HtmlDecode(title); var url = BaseUrl + "/" + link; subtitles.Add(new Subtitle(title, description + " [Subscene.com]", url, rating, this)); } result = Status.Success; } return new QueryResult<Subtitles>(result, subtitles); }
void Awake() { instance = this; }
/* Private members */ /// <summary>Loads the subtitles</summary> private void Load (Subtitles subtitles) { this.subtitles = subtitles; tree.Model = subtitles.Model; Refresh(); tree.Model.RowInserted += OnModelRowInserted; tree.Model.RowDeleted += OnModelRowDeleted; EmitSubtitleCountChangedEvent(); }
/// <summary> /// Gets subtitles meta. /// </summary> /// <param name="releaseName">Name of the release.</param> /// <param name="language"></param> /// <returns>The query result.</returns> public override QueryResult<Subtitles> GetSubtitlesMeta(string releaseName, Language language) { var subtitles = new Subtitles(); var statuses = new List<Status>(Handlers.Count); Status status = Status.Success; var tasks = new List<Task>(Handlers.Count); var sb = new StringBuilder(); if (Handlers.Count > 0) { foreach (var subtitleDb in Handlers) { var db = subtitleDb; var dbTask = Task.Run( () => { Status dbStatus; try { var meta = db.GetSubtitlesMeta(releaseName, language); dbStatus = meta.Status; if (dbStatus == Status.Success && meta.Data != null && meta.Data.Count > 0) { subtitles.AddRange(meta.Data); } } catch (Exception ex) { Trace.TraceError(Literals.Data_Failed_to_get_subtitles_meta, releaseName, db, ex); dbStatus = Status.Fatal; sb.AppendLine(string.Format(Literals.Data_Failed_to_get_subtitles_meta, releaseName, db, ex.Message)); } statuses.Add(dbStatus); }); tasks.Add(dbTask); } Task.WaitAll(tasks.ToArray()); if (statuses.Distinct().Count() == statuses.Count) { status = statuses.First(); } else if (statuses.Any(s => s == Status.Success)) { status = Status.Success; } else if (statuses.Any(s => s == Status.Fatal)) { status = Status.Fatal; } else if (statuses.Any(s => s == Status.Failure)) { status = Status.Failure; } } return new QueryResult<Subtitles>(status, subtitles, sb.ToString()); }
void Awake() { m_Instance = this; Text = GetComponentInChildren<Text>(); gameObject.SetActive(false); }