public static Dictionary <string, object> GetLatestReleasedVersion() { Dictionary <string, object> result; Debugger.WriteLine( LogLevel.Info, $"Getting info about the latest version from {MaidFiddler.RELEASES_LATEST_REQUEST_URL}"); HttpWebRequest releasesRequest = (HttpWebRequest)WebRequest.Create(MaidFiddler.RELEASES_LATEST_REQUEST_URL); releasesRequest.UserAgent = "Maid Fiddler Update Checker"; releasesRequest.Accept = "application/json"; HttpWebResponse wr = (HttpWebResponse)releasesRequest.GetResponse(); Debugger.WriteLine(LogLevel.Info, "Got a response!"); Debugger.WriteLine(LogLevel.Info, $"Response code: {wr.StatusCode}"); if (!wr.ContentType.StartsWith("application/json")) { Debugger.WriteLine( LogLevel.Error, $"Could not load version data! Content gotten: {wr.ContentType} Skipping version checking..."); return(null); } JsonReader jr = new JsonReader(wr.GetResponseStream()); result = jr.Deserialize <Dictionary <string, object> >(); wr.Close(); return(result); }
public void UpdateSelectedMaidValues() { if (InvokeRequired) { InvokeAsync((Action)UpdateSelectedMaidValues); return; } MaidChangeType cType = 0; Debugger.Assert( () => { int processingQueue = currentQueue; currentQueue = 1 - currentQueue; if (valueUpdateQueue[processingQueue].Count <= 0) { return; } Debugger.WriteLine(LogLevel.Info, $"Updating values (Queue {processingQueue})..."); foreach (KeyValuePair <MaidChangeType, Action> type in valueUpdateQueue[processingQueue]) { cType = type.Key; type.Value(); } valueUpdateQueue[processingQueue].Clear(); }, $"Failed to update scheduled maid value. Type: {cType}"); }
private void LoadTranslations(string selectedLanguageFile) { listBox_translations.Items.Clear(); Debugger.WriteLine( LogLevel.Info, $"Loading translation files. Selected language file: {selectedLanguageFile}"); string translationsPath = Path.Combine(MaidFiddler.DATA_PATH, Translation.TRANSLATIONS_PATH); if (!Directory.Exists(translationsPath)) { Debugger.WriteLine(LogLevel.Warning, "No translation folder found. Creating one..."); Directory.CreateDirectory(translationsPath); return; } string[] files = Directory.GetFiles(translationsPath, "*.txt"); int selected = -1; foreach (string filePath in files) { using (StreamReader sr = File.OpenText(filePath)) { TranslationData translationData = new TranslationData(); string line = sr.ReadLine(); if (line == null || line.Trim() == string.Empty) { continue; } Match match = Translation.TagPattern.Match(line); if (!match.Success) { continue; } translationData.FileName = Path.GetFileNameWithoutExtension(filePath); translationData.Language = match.Groups["lang"].Value; translationData.Version = match.Groups["ver"].Value; translationData.Author = match.Groups["auth"].Value; Debugger.WriteLine( LogLevel.Info, $"Found language: File={translationData.FileName}, Lang={translationData.Language}"); int i = listBox_translations.Items.Add(translationData); if (translationData.FileName == selectedLanguageFile) { selected = i; } } } if (selected != -1) { listBox_translations.SelectedIndex = selected; } }
static Resources() { Debugger.WriteLine("Loading original generic maid thumbnail..."); byte[] thumbnail = Convert.FromBase64String(ThumbnailBase64); using (MemoryStream ms = new MemoryStream()) { ms.Write(thumbnail, 0, thumbnail.Length); OriginalThumbnail = Image.FromStream(ms); } Debugger.WriteLine("Loading CM3D2 application icon"); }
private void OpenTranslationsFolder(object sender, EventArgs e) { string translationsPath = Path.Combine(MaidFiddler.DATA_PATH, Translation.TRANSLATIONS_PATH); Debugger.WriteLine(LogLevel.Info, $"Opening translation folder at {translationsPath}"); if (!Directory.Exists(translationsPath)) { Debugger.WriteLine(LogLevel.Warning, "No translation folder found. Creating one..."); Directory.CreateDirectory(translationsPath); } Process.Start(new ProcessStartInfo { FileName = translationsPath, UseShellExecute = true, Verb = "open" }); }
private void _UnloadMaids() { Debugger.Assert( () => { Debugger.WriteLine(LogLevel.Info, "Unloading maids!"); Debugger.WriteLine(LogLevel.Info, $"Loaded maids: {loadedMaids.Count}"); loadedMaids.Clear(); currentQueue = 0; valueUpdateQueue[0].Clear(); valueUpdateQueue[1].Clear(); if (maidThumbnails.Count > 0) { maidThumbnails.ForEach(thumb => thumb.Value.Dispose()); } maidThumbnails.Clear(); UpdateList(); }, "Failed to unload maids"); }
public static void InitThumbnail() { Debugger.Assert( () => { Debugger.WriteLine("Loading generic maid thumbnail..."); float size = Translation.GetTranslation("THUMB_TEXT_SIZE").Parse(10.0F); float posX = Translation.GetTranslation("THUMB_TEXT_POS_X").Parse(0.0F); float posY = Translation.GetTranslation("THUMB_TEXT_POS_Y").Parse(0.0F); Debugger.WriteLine(LogLevel.Info, $"Font size: {size}, posX: {posX}, posY: {posY}"); DefaultThumbnail = new Bitmap(OriginalThumbnail); using (Graphics g = Graphics.FromImage(DefaultThumbnail)) { Font f = new Font("Arial", size); g.DrawString(Translation.GetTranslation("THUMB_NONE"), f, new SolidBrush(Color.Black), posX, posY); } }, "Failed to load the generic maid thumbnail"); }
static EnumHelper() { Debugger.WriteLine("Initializing Maid and Yotogi class maps..."); CreateMaidClassAndYotogiClassMaps(); Debugger.WriteLine("Initializing enum values"); ContractTypes = GetValues <ContractType>(); Conditions = GetValues <Condition>(); Personalities = GetValues <Personal>(); MaidChangeTypes = GetValues <MaidChangeType>(); Propensities = GetValues <Propensity>(); Features = GetValues <Feature>(); MaxPersonality = Personalities[Personalities.Length - 1]; MaxCondition = Conditions[Conditions.Length - 1]; MaxContractType = ContractTypes[ContractTypes.Length - 1]; MaxPropensity = Propensities[Propensities.Length - 1]; MaxFeature = Features[Features.Length - 1]; MaxMaidClass = maidClassIDtoNameDic.Count; }
private void ReloadMaids(List <Maid> maids) { Debugger.Assert( () => { Debugger.WriteLine(LogLevel.Info, "Reloading maids!"); Debugger.WriteLine(LogLevel.Info, $"Maids: {maids.Count}"); Debugger.WriteLine(LogLevel.Info, $"Loaded maids: {loadedMaids.Count}"); loadedMaids.Clear(); currentQueue = 0; valueUpdateQueue[0].Clear(); valueUpdateQueue[1].Clear(); if (maidThumbnails.Count > 0) { maidThumbnails.ForEach(thumb => thumb.Value.Dispose()); } maidThumbnails.Clear(); loadedMaids = new SortedList <Maid, MaidInfo>( maids.ToDictionary(m => m, m => new MaidInfo(m, this)), comparer); loadedMaids.ForEach( m => { Texture2D thumb = m.Value.Maid.GetThumIcon(); if (thumb == null) { return; } using (MemoryStream stream = new MemoryStream(thumb.EncodeToPNG())) { Debugger.WriteLine("Loading PNG of size: " + stream.Length); maidThumbnails.Add(m.Key.Param.status.guid, Image.FromStream(stream)); } }); UpdateList(); }, "Failed to reload all maids"); }
public static void ApplyTranslation() { Debugger.WriteLine(LogLevel.Info, "Applying translation"); Debugger.Assert( () => { foreach (KeyValuePair <string, List <Action <string> > > translationItems in translatableControlsDictionary) { string translation; if (translationDictionary.TryGetValue(translationItems.Key, out translation)) { translationItems.Value.ForEach(a => a.Invoke(translation)); } else { translationItems.Value.ForEach(a => a.Invoke(translationItems.Key)); } } Resources.InitThumbnail(); }, "Failed to apply translation."); }
private void UpdateMaids(List <Maid> newMaids) { Debugger.Assert( () => { if (newMaids.Count != loadedMaids.Count) { goto update; } newMaids.Sort((m1, m2) => comparer.Compare(m1, m2)); if (newMaids.SequenceEqual(loadedMaids.Values.Select(m => m.Maid), comparer)) { return; } update: #if DEBUG Stopwatch sw = Stopwatch.StartNew(); #endif Debugger.WriteLine(LogLevel.Info, "Updating maid list!"); Debugger.WriteLine(LogLevel.Info, $" New count: {newMaids.Count}, Loaded count: {loadedMaids.Count}"); loadedMaids = new SortedList <Maid, MaidInfo>( loadedMaids.Where( m => { bool result = newMaids.Contains(m.Key); if (result) { newMaids.Remove(m.Key); } else { if (SelectedMaid != null && m.Value.Maid == SelectedMaid.Maid) { currentQueue = 0; valueUpdateQueue[0].Clear(); valueUpdateQueue[1].Clear(); } if (maidThumbnails.ContainsKey(m.Key.Param.status.guid)) { maidThumbnails[m.Key.Param.status.guid].Dispose(); } maidThumbnails.Remove(m.Key.Param.status.guid); } return(result); }).ToList().Union( newMaids.Select( m => { Debugger.WriteLine(LogLevel.Info, "Adding new maid info."); MaidInfo info = new MaidInfo(m, this); Debugger.WriteLine(LogLevel.Info, "Loading thumbnail"); Texture2D thumb = m.GetThumIcon(); if (thumb == null) { return(new KeyValuePair <Maid, MaidInfo>(m, info)); } using (MemoryStream stream = new MemoryStream(thumb.EncodeToPNG())) { Debugger.WriteLine("Loading PNG of size: " + stream.Length); maidThumbnails.Add(m.Param.status.guid, Image.FromStream(stream)); } return(new KeyValuePair <Maid, MaidInfo>(m, info)); })).ToDictionary(m => m.Key, m => m.Value), comparer); Debugger.WriteLine(LogLevel.Info, $"New loaded maids count: {loadedMaids.Count}"); #if DEBUG sw.Stop(); Debugger.WriteLine(LogLevel.Info, $"Updated maid list in {sw.Elapsed.TotalMilliseconds} ms"); newMaids.ForEach( m => Debugger.WriteLine($"Added {m.Param.status.first_name} {m.Param.status.last_name}")); Debugger.WriteLine(); #endif Debugger.WriteLine("Updating list."); UpdateList(); Debugger.WriteLine("Finished updating list."); }, "Failed to update maid list"); }
public static void LoadTranslation(string filename) { Debugger.Assert( () => { Debugger.WriteLine($"Loading translation: {filename}"); string filePath = Path.Combine(MaidFiddler.DATA_PATH, $@"{TRANSLATIONS_PATH}\{filename}.txt"); string version = string.Empty; Debugger.WriteLine(LogLevel.Info, $"File path: {filePath}"); if (!File.Exists(filePath)) { Debugger.WriteLine(LogLevel.Error, "Failed to find such translation file."); filename = string.Empty; } else { Debugger.WriteLine(LogLevel.Info, "Loading translation labels."); Dictionary <string, string> newTranslationDictionary = new Dictionary <string, string>(); using (TextReader reader = File.OpenText(filePath)) { string line = reader.ReadLine(); if (line != null) { Match match = TagPattern.Match(line); if (match.Success) { version = match.Groups["ver"].Value; Debugger.WriteLine( LogLevel.Info, $"Found translation tag! Language: '{match.Groups["lang"]}', Version: '{match.Groups["ver"]}', Author(s): '{match.Groups["auth"]}'"); } else { Debugger.WriteLine(LogLevel.Warning, "Did not find any translation tags!"); } } while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line == string.Empty || line.StartsWith(";")) { continue; } string[] parts = line.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { continue; } string text = parts[1].Replace(@"\n", "\n").Replace(@"\r", "\r"); if (text.Trim() == string.Empty) { Debugger.WriteLine( LogLevel.Warning, $"Translation for {parts[0]} is empty! Skipping..."); continue; } if (!newTranslationDictionary.ContainsKey(parts[0])) { newTranslationDictionary.Add(parts[0], text); } else { Debugger.WriteLine( LogLevel.Warning, $"Translation for {parts[0]} already exists! Replacing with a newer version..."); newTranslationDictionary[parts[0]] = text; } } } translationDictionary.Clear(); translationDictionary = newTranslationDictionary; } Debugger.WriteLine(LogLevel.Info, "Texts loaded"); CurrentTranslationFile = filename; CurrentTranslationVersion = version; ApplyTranslation(); }, "Failed to load texts"); }
public static void RunUpdateChecker() { Debugger.WriteLine(LogLevel.Info, "Checking for updates..."); UpdateInfo = new UpdateInfo(); Dictionary <string, object> versionInfo; try { versionInfo = GetLatestReleasedVersion(); if (versionInfo == null) { throw new Exception("No version data downloaded!"); } } catch (WebException e) { Debugger.WriteLine(LogLevel.Error, $"Failed to get latest version info! Reason: {e}"); Debugger.WriteLine( LogLevel.Error, $"Response: {new StreamReader(e.Response.GetResponseStream()).ReadToEnd()}"); UpdatesChecked = true; return; } catch (Exception e) { Debugger.WriteLine(LogLevel.Error, $"Failed to get latest version info! Reason: {e}"); UpdatesChecked = true; return; } Debugger.WriteLine(LogLevel.Info, "Got latest version info!"); Debugger.WriteLine(LogLevel.Info, $"Current version: {MaidFiddler.VERSION_TAG}"); Debugger.WriteLine(LogLevel.Info, $"Latest version: {versionInfo["tag_name"]}"); Match current = versionPattern.Match(MaidFiddler.VERSION_TAG); Match latest = versionPattern.Match((string)versionInfo["tag_name"]); if (!latest.Success) { Debugger.WriteLine( LogLevel.Error, "Could not process version tag. Tag is probably older than Beta 0.11 Skipping version check."); UpdatesChecked = true; return; } bool isNewAvailable; try { string currentVersionPrefix = current.Groups["prefix"].Value; int currentMajor = int.Parse(current.Groups["major"].Value); int currentMinor = int.Parse(current.Groups["minor"].Value); int currentPatch = current.Groups["patch"].Success ? int.Parse(current.Groups["patch"].Value) : 0; string latestVersionPrefix = latest.Groups["prefix"].Value; int latestMajor = int.Parse(latest.Groups["major"].Value); int latestMinor = int.Parse(latest.Groups["minor"].Value); int latestPatch = latest.Groups["patch"].Success ? int.Parse(latest.Groups["patch"].Value) : 0; bool samePrefix = latestVersionPrefix == currentVersionPrefix; bool sameMajor = latestMajor == currentMajor; bool sameMinor = latestMinor == currentMinor; isNewAvailable = latestVersionPrefix == "v" && currentVersionPrefix == "Beta-" || samePrefix && latestMajor > currentMajor || samePrefix && sameMajor && latestMinor > currentMinor || samePrefix && sameMajor && sameMinor && latestPatch > currentPatch; } catch (Exception e) { Debugger.WriteLine(LogLevel.Error, $"Failed to parse tool versions! Reason: {e}"); UpdatesChecked = true; return; } if (!isNewAvailable) { UpdatesChecked = true; return; } UpdateInfo newUpdateInfo = new UpdateInfo { IsAvailable = true, Version = (string)versionInfo["name"], Changelog = ((string)versionInfo["body"]).Replace("*", string.Empty) }; UpdateInfo = newUpdateInfo; UpdatesChecked = true; }
private void OpenTranslationDownloadUrl(object sender, EventArgs e) { Uri uri = null; TextDialog tdURL = new TextDialog( Translation.GetTranslation("TL_URL_TITLE"), Translation.GetTranslation("TL_URL_TEXT"), string.Empty, s => { try { uri = new Uri(s); return(uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps); } catch (Exception) { return(false); } }, Translation.GetTranslation("OK"), Translation.GetTranslation("CANCEL")); DialogResult promptDialog = tdURL.ShowDialog(this); tdURL.Dispose(); if (promptDialog != DialogResult.OK) { return; } string translationsPath = Path.Combine(MaidFiddler.DATA_PATH, Translation.TRANSLATIONS_PATH); LoadingBarGUI loadingBarGui = new LoadingBarGUI( Translation.GetTranslation("LOADING"), Translation.GetTranslation("TL_URL_DOWNLOADING"), true, g => { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri); g.Timer.Start(); Debugger.WriteLine(LogLevel.Info, "Getting translation..."); webRequest.BeginGetResponse( ar => { try { HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(ar); Debugger.WriteLine(LogLevel.Info, "Got response!"); Debugger.WriteLine(LogLevel.Info, $"Response: {response.StatusCode}"); if (response.StatusCode == HttpStatusCode.NotFound) { MessageBox.Show( "Failed to download the translation: File not found", "Boop!", MessageBoxButtons.OK, MessageBoxIcon.Error); g.DialogResult = DialogResult.Abort; g.Timer.Stop(); g.Close(); return; } Stream s = response.GetResponseStream(); Debugger.WriteLine(LogLevel.Info, "Reading response"); List <byte> resultBuffer = new List <byte>(); byte[] responseBuffer = new byte[1024]; int read; do { read = s.Read(responseBuffer, 0, responseBuffer.Length); resultBuffer.AddRange(responseBuffer, 0, read); } while (read > 0); string translationString = Encoding.UTF8.GetString(resultBuffer.ToArray()); using (TextReader tr = new StringReader(translationString)) { if (!Translation.TagPattern.Match(tr.ReadLine()).Success) { Debugger.WriteLine(LogLevel.Error, "Failed to parse the translation: No tag found!"); MessageBox.Show( "The file does not contain the translation tag and thus cannot be recognised as a Maid Fiddler translation file.\nThe file has not been saved.", "Boop!", MessageBoxButtons.OK, MessageBoxIcon.Error); g.DialogResult = DialogResult.Abort; g.Timer.Stop(); g.Close(); return; } } string tlFileName = Path.GetFileNameWithoutExtension(uri.AbsolutePath); Debugger.WriteLine($"File name: {tlFileName}"); if (tlFileName == string.Empty || File.Exists(Path.Combine(translationsPath, $"{tlFileName}.txt"))) { char[] invalidChars = Path.GetInvalidFileNameChars(); TextDialog tdFileName = new TextDialog( Translation.GetTranslation("TL_NAME_CHANGE_TITLE"), Translation.GetTranslation("TL_NAME_CHANGE"), tlFileName, s1 => !s1.Any(c => invalidChars.Contains(c)), Translation.GetTranslation("OK"), Translation.GetTranslation("CANCEL")); if (tdFileName.ShowDialog(g) == DialogResult.OK) { tlFileName = tdFileName.Input; } if (tlFileName == string.Empty) { tlFileName = FiddlerUtils.GenerateFileName(); } tdFileName.Dispose(); } string path = Path.Combine(translationsPath, $"{tlFileName}.txt"); Debugger.WriteLine($"Writing translation to {path}"); using (TextWriter tw = File.CreateText(path)) tw.Write(translationString); g.DialogResult = DialogResult.OK; } catch (WebException we) { MessageBox.Show( $"Failed to retreive translation.\nResponse: {we.Message}", "Boop!", MessageBoxButtons.OK, MessageBoxIcon.Error); g.DialogResult = DialogResult.Abort; } catch (Exception ex) { MessageBox.Show( $"Unknown error occurred.\nInfo: {ex.ToString()}", "Boop!", MessageBoxButtons.OK, MessageBoxIcon.Error); g.DialogResult = DialogResult.Abort; } finally { g.Timer.Stop(); g.Close(); } }, null); }); DialogResult result = loadingBarGui.ShowDialog(this); loadingBarGui.Dispose(); if (result != DialogResult.OK) { return; } MessageBox.Show( Translation.GetTranslation("TL_DOWNLOAD_DONE"), Translation.GetTranslation("TL_DOWNLOAD_DONE_TITLE"), MessageBoxButtons.OK); LoadTranslations(Translation.CurrentTranslationFile); }
private void OpenTranslationDownloadGithub(object sender, EventArgs e) { string list = string.Empty; LoadingBarGUI loadingBarGui = new LoadingBarGUI( Translation.GetTranslation("LOADING"), Translation.GetTranslation("TL_LIST_LOADING"), true, g => { HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create($"{MaidFiddler.RESOURCE_URL}/Resources/Translations/translation_list.txt"); g.Timer.Start(); Debugger.WriteLine(LogLevel.Info, "Getting translation list..."); webRequest.BeginGetResponse( ar => { try { HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(ar); Debugger.WriteLine(LogLevel.Info, "Got response!"); Debugger.WriteLine(LogLevel.Info, $"Response: {response.StatusCode}"); if (response.StatusCode == HttpStatusCode.NotFound) { MessageBox.Show( "Failed to retreive translation list: List not found.", "Boop!", MessageBoxButtons.OK, MessageBoxIcon.Error); } Stream s = response.GetResponseStream(); Debugger.WriteLine(LogLevel.Info, "Reading response"); byte[] responseBuffer = new byte[1024]; List <byte> byteBuffer = new List <byte>(); int read; do { read = s.Read(responseBuffer, 0, responseBuffer.Length); byteBuffer.AddRange(responseBuffer, 0, read); } while (read > 0); list = Encoding.UTF8.GetString(byteBuffer.ToArray()); g.DialogResult = DialogResult.OK; } catch (WebException we) { MessageBox.Show( $"Failed to retreive translation list.\nResponse: {we.Message}", "Boop!", MessageBoxButtons.OK, MessageBoxIcon.Error); g.DialogResult = DialogResult.Abort; } catch (Exception ex) { MessageBox.Show( $"Unknown error occurred.\nInfo: {ex.ToString()}", "Boop!", MessageBoxButtons.OK, MessageBoxIcon.Error); g.DialogResult = DialogResult.Abort; } finally { g.Timer.Stop(); g.Close(); } }, null); }); DialogResult result = loadingBarGui.ShowDialog(this); loadingBarGui.Dispose(); if (result != DialogResult.OK) { return; } GithubTranslationsGUI tlGui = new GithubTranslationsGUI(list.Remove(0, 1)); tlGui.ShowDialog(this); tlGui.Dispose(); LoadTranslations(Translation.CurrentTranslationFile); }