public async Task<PhotosResponse> GetPhotosAsync(Photoset photoset, User user, Preferences preferences, int page, IProgress<ProgressUpdate> progress) { var progressUpdate = new ProgressUpdate { OperationText = "Getting list of photos...", ShowPercent = false }; progress.Report(progressUpdate); var methodName = GetPhotosetMethodName(photoset.Type); var extraParams = new Dictionary<string, string> { { ParameterNames.UserId, user.UserNsId }, { ParameterNames.SafeSearch, preferences.SafetyLevel }, { ParameterNames.PerPage, preferences.PhotosPerPage.ToString(CultureInfo.InvariantCulture) }, { ParameterNames.Page, page.ToString(CultureInfo.InvariantCulture) } }; var isAlbum = photoset.Type == PhotosetType.Album; if (isAlbum) { extraParams.Add(ParameterNames.PhotosetId, photoset.Id); } var photosResponse = (Dictionary<string, object>) await this._oAuthManager.MakeAuthenticatedRequestAsync(methodName, extraParams); return photosResponse.GetPhotosResponseFromDictionary(isAlbum); }
public async Task<PhotosetsResponse> GetPhotosetsAsync(string methodName, User user, Preferences preferences, int page, IProgress<ProgressUpdate> progress) { var progressUpdate = new ProgressUpdate { OperationText = "Getting list of albums...", ShowPercent = false }; progress.Report(progressUpdate); var extraParams = new Dictionary<string, string> { { ParameterNames.UserId, user.UserNsId }, { ParameterNames.SafeSearch, preferences.SafetyLevel }, { ParameterNames.PerPage, "21" }, { ParameterNames.Page, page.ToString(CultureInfo.InvariantCulture) } }; var photosetsResponseDictionary = (Dictionary<string, object>) await this._oAuthManager.MakeAuthenticatedRequestAsync(methodName, extraParams); return photosetsResponseDictionary.GetPhotosetsResponseFromDictionary(); }
private async Task DownloadPhotos(IEnumerable<Photo> photos, CancellationToken cancellationToken, IProgress<ProgressUpdate> progress, Preferences preferences, Photoset photoset) { var progressUpdate = new ProgressUpdate { Cancellable = true, OperationText = "Downloading photos...", PercentDone = 0, ShowPercent = true }; progress.Report(progressUpdate); var doneCount = 0; var photosList = photos as IList<Photo> ?? photos.ToList(); var totalCount = photosList.Count(); var imageDirectory = CreateDownloadFolder(preferences.DownloadLocation, photoset); foreach (var photo in photosList) { var photoUrl = photo.OriginalUrl; var photoExtension = "jpg"; switch (preferences.DownloadSize) { case PhotoDownloadSize.Medium: photoUrl = photo.Medium800Url; break; case PhotoDownloadSize.Large: photoUrl = photo.Large1024Url; break; case PhotoDownloadSize.Original: photoUrl = photo.OriginalUrl; photoExtension = photo.DownloadFormat; break; } var photoWithPreferredTags = photo; if (preferences.NeedOriginalTags) { photoWithPreferredTags = await this._originalTagsLogic.GetOriginalTagsTask(photo); } var photoName = preferences.TitleAsFilename ? GetSafeFilename(photo.Title) : photo.Id; var targetFileName = Path.Combine(imageDirectory.FullName, string.Format("{0}.{1}", photoName, photoExtension)); WriteMetaDataFile(photoWithPreferredTags, targetFileName, preferences); var request = WebRequest.Create(photoUrl); var buffer = new byte[4096]; await DownloadAndSavePhoto(targetFileName, request, buffer); doneCount++; progressUpdate.PercentDone = doneCount * 100 / totalCount; progressUpdate.DownloadedPath = imageDirectory.FullName; progress.Report(progressUpdate); if (doneCount != totalCount) { cancellationToken.ThrowIfCancellationRequested(); } } }
public static void RefreshMappings(Project project, ProgressUpdate progressUpdate) { int currentItem = -1; int totalItems = (2 * project.UserSettings.Connections.Count); foreach (var connection in project.UserSettings.Connections){ string description = connection.GetDescription(); DatabaseWorker worker = DatabaseWorker.GetInstance(connection); if (progressUpdate != null) progressUpdate($"{description}: Refreshing mappings...", ++currentItem, totalItems); worker.Refresh(project, connection); if (progressUpdate != null) progressUpdate($"{description}: Sorting...", ++currentItem, totalItems); project.SortAll(); if (progressUpdate != null) progressUpdate($"{description}: Refresh complete.", ++currentItem, totalItems); } }
public void GoAsync(string sourceDirectoryPath, ProgressUpdate onProgressUpdate) { BackgroundWorker backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerReportsProgress = true; backgroundWorker.DoWork += (sender, args) => { IEnumerable<string> files = Directory.EnumerateFiles(sourceDirectoryPath, "*.*", SearchOption.AllDirectories); //Directory.GetFiles(sourceDirectoryPath); int totalFiles = files.Count(); int i = 0; Log.Info(string.Format("Starting, {0} total files to process.", totalFiles)); foreach (string filePath in files) { Log.Info(string.Format("Processing: {0}", filePath)); backgroundWorker.ReportProgress((i * 100) / totalFiles, string.Format("Processing: {0}", filePath)); FileInfo fileInfo = new FileInfo(filePath); if (Configuration.SupportedExtensions.Contains(fileInfo.Extension, StringComparer.CurrentCultureIgnoreCase)) RenameFile(filePath); i++; } }; backgroundWorker.ProgressChanged += (sender, args) => onProgressUpdate(args.ProgressPercentage, args.UserState as string); backgroundWorker.RunWorkerCompleted += (sender, args) => { Log.Info("Completed"); onProgressUpdate(101, "Complete"); }; backgroundWorker.RunWorkerAsync(); }
//Handle Stream of Reports public async Task StreamReport() { UInt32 jid; //Start Stream Report try { //Prepare a Stream Report for usage using (var call = client.StreamReport(new StreamRequest())) { var responseStream = call.ResponseStream; //Loop the stream, consuming data while (await responseStream.MoveNext()) { ProgressUpdate prg = new ProgressUpdate(); bool isProgressUpdated = false; Report report = responseStream.Current; //Ignore report if window isn't focused //Console.WriteLine(report); if (Form1.GetInstance().processHandleWindow != w32.GetForegroundWindow()) { Form1.GetInstance().Text = "[" + Form1.GetInstance().GetProcessName() + "] GoBeam v" + Application.ProductVersion; //Form1.GetInstance().SetStatus("Window not visible"); //continue; } else { Form1.GetInstance().Text = ">[" + Form1.GetInstance().GetProcessName() + "]< GoBeam v" + Application.ProductVersion; //Form1.GetInstance().SetStatus(""); } //iterate keymap foreach (var key in Form1.config.keys) { if (!key.IsPressed && key.progress > 0) { key.progress -= 0.05; //Write an eventual cooldown of keys var tac = new ProgressUpdate.Types.TactileUpdate(); tac.Id = (UInt32)key.Index; tac.Fired = false; tac.Progress = key.progress; prg.Tactile.Add(tac); isProgressUpdated = true; } bool isAnyButtonPressed = false; //iterate touches foreach (var touch in report.Tactile) { if (key.Index != touch.Id) continue; if (touch.Holding > 0 || touch.PressFrequency > 0 || touch.ReleaseFrequency > 0) { //Console.WriteLine(touch.Id + ": " + touch.Holding + ", "+ touch.PressFrequency+ "," + touch.ReleaseFrequency); } //Press or release key based on report if ((touch.PressFrequency != 0 && !key.IsPressed) || (touch.ReleaseFrequency != 0 && key.IsPressed)) { key.IsPressed = !key.IsPressed; if (key.IsPressed) { key.IdleTime = 0; isAnyButtonPressed = true; Form1.SetLeftProgress(1); //If the key hasn't been pressed in some time, re-do halo effect if (key.progress == 0.0) key.progress = 1.0; } if (key.Type == "Tactile") { //Focus only required for keyboard if (Form1.GetInstance().processHandleWindow != w32.GetForegroundWindow()) continue; //Console.WriteLine("TactileKey" + touch.Id + " ("+key.KeyName+"), " + key.IsPressed); w32.keybd_event(key.KeyCode, 0, (key.IsPressed) ? 0 : w32.KEYEVENTF_KEYUP, 0); } else if (key.Type == "JoystickKey") { //It gets here if (key.joystickIndex < 1) { continue; } //Console.WriteLine("JoystickKey " + touch.Id + " (J: "+key.joystickIndex+", "+key.KeyName+"), " + key.IsPressed); foreach (var jKey in Form1.config.keys) { if (jKey.joystickIndex == key.joystickIndex && jKey.KeyCode == key.KeyCode) { //Find joystick, since after I made multiple joysticks available my old code got borked vJoy joystick = null; foreach (var joyKey in Form1.config.keys) { if (joyKey.joystick != null && joyKey.joystickIndex == jKey.joystickIndex && joyKey.IsEnabled) { joystick = joyKey.joystick; break; } } if (joystick == null) { MessageBox.Show("Invalid joystick passed for key" + jKey.Index); } joystick.SetBtn(key.IsPressed, (UInt32)key.joystickIndex, key.KeyCode); break; } } // w32.keybd_event(key.KeyCode, 0, (key.IsPressed) ? 0 : w32.KEYEVENTF_KEYUP, 0); } var tac = new ProgressUpdate.Types.TactileUpdate(); tac.Id = (UInt32)key.Index; tac.Fired = false; if (key.progress == 1.0) tac.Fired = true; tac.Progress = key.progress; prg.Tactile.Add(tac); isProgressUpdated = true; } } if (!isAnyButtonPressed) Form1.SetLeftProgress(0); foreach (var joy in report.Joystick) { if (key.Index != joy.Id) continue; if (key.joystick == null) continue; if (!key.IsEnabled) continue; jid = (UInt32)key.KeyCode; //Console.WriteLine("joy " + joy.Id + ": " + joy.CoordMean.X + ", " + joy.CoordMean.Y); if ((!double.Equals(joy.CoordMean.X, double.NaN) && !key.IsPressed) || (!double.Equals(joy.CoordMean.Y, double.NaN) && !key.IsPressed) || (double.Equals(joy.CoordMean.X, double.NaN) && key.IsPressed) || ( double.Equals(joy.CoordMean.Y, double.NaN) && key.IsPressed)) { //Form1.GetInstance().SetStatus("Joystick"); key.IsPressed = !key.IsPressed; var ju = new ProgressUpdate.Types.JoystickUpdate(); ju.Id = jid; ju.Intensity = (double)((key.IsPressed) ? 1.0 : 0.0); prg.Joystick.Add(ju); isProgressUpdated = true; } //Console.Write(joy.CoordMean.X + "," + joy.CoordMean.Y); //Form1.JoystickIdle(key.joystick, (byte)jid, (int)maxval); if (double.Equals(joy.CoordMean.X, double.NaN) && double.Equals(joy.CoordMean.Y, double.NaN)) { if (key.IdleTime < 3) key.IdleTime++; if (key.IdleTime > 2) { //Console.WriteLine("idle"); //Form1.GetInstance().SetStatus("Idle"); key.joystick.ResetVJD(jid); Form1.JoystickIdle(key.joystick, (byte)jid, (int)maxval); Form1.SetRightProgress(0); key.joystick.SetAxis((int)(maxval * 0.5f), jid, HID_USAGES.HID_USAGE_X); key.joystick.SetAxis((int)(maxval * 0.5f), jid, HID_USAGES.HID_USAGE_Y); } } else { Form1.SetRightProgress(1); key.IdleTime = 0; if (double.Equals(joy.CoordMean.X,double.NaN)) { key.joystick.SetAxis((int)(maxval * 0.5f), jid, HID_USAGES.HID_USAGE_X); } else { //Console.Write(" X: " + ", " + joy.CoordMean.X); key.joystick.SetAxis((int)(maxval * ((joy.CoordMean.X + 1.0f) / 2.0f)), jid, HID_USAGES.HID_USAGE_X); } if (double.Equals(joy.CoordMean.Y, double.NaN)) { key.joystick.SetAxis((int)(maxval * 0.5f), jid, HID_USAGES.HID_USAGE_Y); } else { //Console.Write(" Y: " + joy.CoordMean.Y); key.joystick.SetAxis((int)(maxval * ((joy.CoordMean.Y + 1.0f) / 2.0f)), jid, HID_USAGES.HID_USAGE_Y); } // Console.WriteLine(key.joystick); } } } if (isProgressUpdated) { //Console.WriteLine("Progress Update"); SendProgressUpdate(prg); } } } } catch (RpcException e) { Form1.GetInstance().DisconnectRPC(); MessageBox.Show("RPC Failed: " + e.Message); throw; } }
private void OnProgress(string message = null) { ProgressUpdate?.Invoke(this, new ProgressUpdateEventArgs(m_FilesProcessed, m_FilesSizeProcessed, m_FoldersProcessed, message)); }
private async Task DownloadPhotos(IEnumerable <Photo> photos, CancellationToken cancellationToken, IProgress <ProgressUpdate> progress, Preferences preferences) { var progressUpdate = new ProgressUpdate { Cancellable = true, OperationText = "Downloading photos...", PercentDone = 0, ShowPercent = true }; progress.Report(progressUpdate); var doneCount = 0; var photosList = photos as IList <Photo> ?? photos.ToList(); var totalCount = photosList.Count(); var imageDirectory = CreateDownloadFolder(preferences.DownloadLocation); foreach (var photo in photosList) { var photoUrl = photo.OriginalUrl; var photoExtension = "jpg"; switch (preferences.DownloadSize) { case PhotoDownloadSize.Medium: photoUrl = photo.Medium800Url; break; case PhotoDownloadSize.Large: photoUrl = photo.Large1024Url; break; case PhotoDownloadSize.Original: photoUrl = photo.OriginalUrl; photoExtension = photo.DownloadFormat; break; } var photoWithPreferredTags = photo; if (preferences.NeedOriginalTags) { photoWithPreferredTags = await _originalTagsLogic.GetOriginalTagsTask(photo); } var photoName = preferences.TitleAsFilename ? GetSafeFilename(photo.Title) : photo.Id; var targetFileName = Path.Combine(imageDirectory.FullName, string.Format("{0}.{1}", photoName, photoExtension)); WriteMetaDataFile(photoWithPreferredTags, targetFileName, preferences); var request = WebRequest.Create(photoUrl); var buffer = new byte[4096]; await DownloadAndSavePhoto(targetFileName, request, buffer); doneCount++; progressUpdate.PercentDone = doneCount * 100 / totalCount; progressUpdate.DownloadedPath = imageDirectory.FullName; progress.Report(progressUpdate); if (doneCount != totalCount) { cancellationToken.ThrowIfCancellationRequested(); } } }
private void UpdateProgress(int progress) => ProgressUpdate?.Invoke(this, progress);
private void OnProgressUpdate(ProgressEventArgs e) { ProgressUpdate?.Invoke(this, e); }
/// <summary> /// start fixing /// </summary> /// <param name="callback"><see cref="ProgressUpdate"/> callback</param> public override void StartFix(ProgressUpdate callback) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(CfgFile.Get("Lang")); this.callback = callback; CheckItems(true); RemoveItems(); IsResetPending = true; }
/// <summary> /// start scanning /// </summary> /// <param name="callback"></param> /// <param name="complete"></param> /// <param name="cancelComplete"></param> /// <param name="fixAfterScan"></param> public override void StartScan(ProgressUpdate callback, ScanComplete complete, CancelComplete cancelComplete, bool fixAfterScan) { FrmTrackSel.Callback = callback; FrmTrackSel.Complete = complete; FrmTrackSel.CancelComplete = cancelComplete; FrmTrackSel.ScanFiles(fixAfterScan); }
public static ProgressUpdate HasDate(this ProgressUpdate update, DateTime date) { update.Date.Should().Be(date); return(update); }
public override async Task RandomizeEncounters(Random taskRandom, ProgressNotifier progressNotifier, CancellationToken token) { var config = this.ValidateAndGetConfig().Encounters; if (!config.RandomizeEncounters) { return; } await this.LogAsync($"======== Beginning Encounter randomization ========{Environment.NewLine}"); progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing wild Pokémon encounters...")); var species = Species.ValidSpecies.ToList(); var speciesInfo = await this.Game.GetPokemonInfo(edited : true); var encounterData = await this.Game.GetEncounterData(); var encounterZones = encounterData.Cast <XyEncounterWild>().ToList(); var zoneNames = (await this.Game.GetTextFile(TextNames.EncounterZoneNames)).Lines; var speciesNames = (await this.Game.GetTextFile(TextNames.SpeciesNames)).Lines; (int zone, int subZone)dittoSpot = (-1, -1); // If "Ensure Dittos in Grass" is enabled, we need to make sure dittos appear in grass *somewhere* in the game. // Pick a random valid encounter zone/slot in which to place Ditto if (config.EnsureDittosInGrass) { var foundPlaceForDitto = false; while (!foundPlaceForDitto) { var dittoZone = encounterZones.GetRandom(taskRandom); if (dittoZone.GetAllEntries().Any(e => e != null)) { var entryArrays = dittoZone.EntryArrays; var dittoSubZone = entryArrays.FirstOrDefault(); // Grass is always first sub-zone if (dittoSubZone != null && !dittoSubZone.All(e => e.Species == Species.Egg.Id)) { var dittoEntry = taskRandom.Next(Math.Min(dittoSubZone.Length, GrassEntries)); // Store zone and entry index for later dittoSpot = (encounterZones.IndexOf(dittoZone), dittoEntry); foundPlaceForDitto = true; } } } } if (!config.AllowLegendaries) { species = species.Except(Legendaries.AllLegendaries) .ToList(); } foreach (var(iEncounter, encounterZone) in encounterZones.Pairs()) { var name = zoneNames[encounterZone.ZoneId]; if (!encounterZone.GetAllEntries().Any(e => e != null)) { continue; } progressNotifier?.NotifyUpdate(ProgressUpdate.Update($"Randomizing encounters...\n{name}", iEncounter / (double)encounterZones.Count)); PokemonType areaType = default; List <SpeciesType> speciesChoose; if (config.TypeThemedAreas) { areaType = PokemonTypes.AllPokemonTypes.ToArray().GetRandom(taskRandom); speciesChoose = species.Where(s => speciesInfo[s.Id].HasType(areaType)).ToList(); } else { speciesChoose = species.ToList(); } if (areaType == default || config.TypePerSubArea) { await this.LogAsync($"Randomizing zone: {name}"); } else { await this.LogAsync($"Randomizing zone: {name} ({areaType.Name}-type)"); } var subZoneArrays = encounterZone.EntryArrays; foreach (var(iSubZone, subZoneArray) in subZoneArrays.Pairs()) { if (subZoneArray.All(e => e.Species == Species.Egg.Id)) { continue; } if (areaType != default && config.TypePerSubArea) { await this.LogAsync($" Sub-zone {iSubZone + 1} ({areaType.Name}-type):"); } else { await this.LogAsync($" Sub-zone {iSubZone + 1}:"); } // In horde battles, one of the slots could be a different species, and we treat the value "5" as "all the same" var isHordeEncounter = HordeSubZones.Contains(iSubZone); var hordeSlot = isHordeEncounter ? taskRandom.Next(0, 6) : -1; var hordeSpecies = -1; foreach (var(iEntry, entry) in subZoneArray.Where(entry => entry.Species != Species.Egg.Id).Pairs()) { var(dittoEncounter, dittoEntry) = dittoSpot; if (config.EnsureDittosInGrass && iEncounter == dittoEncounter && iSubZone == GrassSubZone && iEntry == dittoEntry) { entry.Species = (ushort)Species.Ditto.Id; } else { if (config.ProperHordes && isHordeEncounter) { // For horde battles, every slot has the same species, except for optionally a random slot which can be unique if (iEntry == hordeSlot) { entry.Species = (ushort)this.GetRandomSpecies(taskRandom, speciesChoose).Id; } else { if (hordeSpecies < 0) { hordeSpecies = this.GetRandomSpecies(taskRandom, speciesChoose).Id; } entry.Species = (ushort)hordeSpecies; } } else { entry.Species = (ushort)this.GetRandomSpecies(taskRandom, speciesChoose).Id; } } if (config.LevelMultiplier != 1.0m) { entry.MinLevel = (byte)MathUtil.Clamp((int)(config.LevelMultiplier * entry.MinLevel), 2, 100); entry.MaxLevel = (byte)MathUtil.Clamp((int)(config.LevelMultiplier * entry.MaxLevel), 2, 100); } await this.LogAsync($" Entry: {speciesNames[ entry.Species ]}, levels {entry.MinLevel} to {entry.MaxLevel}"); } if (config.TypeThemedAreas && config.TypePerSubArea) // Re-generate type for the new sub-area { areaType = PokemonTypes.AllPokemonTypes.ToArray().GetRandom(taskRandom); speciesChoose = species.Where(s => speciesInfo[s.Id].HasType(areaType)).ToList(); } if (iSubZone != subZoneArrays.Length - 1) { await this.LogAsync(); } } await this.LogAsync(); encounterZone.EntryArrays = subZoneArrays; } await this.LogAsync(); progressNotifier?.NotifyUpdate(ProgressUpdate.Update("Randomizing encounters...\nCompressing encounter data...this may take a while", 1.0)); await this.Game.SaveEncounterData(encounterZones); await this.LogAsync($"======== Finished Encounter randomization ========{Environment.NewLine}"); }
public DeployTools(ProgressUpdate progressUpdate, string clientApi) { m_OnProgressUpdate = progressUpdate; m_ClientApi = clientApi; }
// Static Methods private static void OnProgressUpdated(ModbusPoller instance, ProgressUpdate update) { ProgressUpdated?.Invoke(instance, new EventArgs <ProgressUpdate>(update)); }
/// <summary> /// Deletes found spyware /// </summary> public override void StartFix(ProgressUpdate callback) { isCancel = false; this.callback = callback; fixBackgroundWorker = new BackgroundWorker(); fixBackgroundWorker.WorkerSupportsCancellation = true; fixBackgroundWorker.WorkerReportsProgress = true; fixBackgroundWorker.DoWork += FixBackgroundWorkerDoWork; fixBackgroundWorker.RunWorkerCompleted += fixBackgroundWorker_RunWorkerCompleted; fixBackgroundWorker.ProgressChanged += fixBackgroundWorker_ProgressChanged; fixBackgroundWorker.RunWorkerAsync(); }
/// <summary> /// Starts the scanning process /// </summary> /// <param name="callback">The callback method to update progress</param> public override void StartScan(ProgressUpdate callback, ScanComplete complete, CancelComplete cancelComplete, bool fixAfterScan) { this.callback = callback; this.complete = complete; this.cancelComplete = cancelComplete; this.fixAfterScan = fixAfterScan; isCancel = false; scanBackgroundWorker = new BackgroundWorker(); scanBackgroundWorker.WorkerSupportsCancellation = true; scanBackgroundWorker.WorkerReportsProgress = true; scanBackgroundWorker.DoWork += ScanBackgroundWorkerDoWork; scanBackgroundWorker.RunWorkerCompleted += scanBackgroundWorker_RunWorkerCompleted; scanBackgroundWorker.ProgressChanged += scanBackgroundWorker_ProgressChanged; scanBackgroundWorker.RunWorkerAsync(); }
public override Task <ProgressResult> UpdateProgress(ProgressUpdate request, ServerCallContext context) { UpdateJobProgress?.Invoke(request.JobId, request.Message, request.CurrentProgress, request.TotalProgress); return(Task.FromResult(new ProgressResult())); }
private async Task DownloadPhotos(IEnumerable <Photo> photos, CancellationToken cancellationToken, IProgress <ProgressUpdate> progress, Preferences preferences, Photoset photoset, string folderPrefix = null, string albumProgress = null) { var progressUpdate = new ProgressUpdate { Cancellable = true, OperationText = string.IsNullOrEmpty(albumProgress) ? "Downloading photos..." : "Downloading albums...", PercentDone = 0, ShowPercent = true, AlbumProgress = albumProgress }; progress.Report(progressUpdate); var doneCount = 0; var photosList = photos as IList <Photo> ?? photos.ToList(); var totalCount = photosList.Count(); var imageDirectory = CreateDownloadFolder(preferences.DownloadLocation, photoset, folderPrefix); var curCount = 0; foreach (var photo in photosList) { curCount++; var photoUrl = photo.OriginalUrl; var photoExtension = "jpg"; switch (preferences.DownloadSize) { case PhotoDownloadSize.Medium: photoUrl = photo.Medium800Url; break; case PhotoDownloadSize.Large: photoUrl = photo.Large1024Url; break; case PhotoDownloadSize.Original: photoUrl = photo.OriginalUrl; photoExtension = photo.DownloadFormat; break; } var photoWithPreferredTags = photo; if (preferences.NeedOriginalTags) { photoWithPreferredTags = await _originalTagsLogic.GetOriginalTagsTask(photo, preferences); } var photoName = preferences.FileNameMode == FileNameMode.Title ? GetSafeFilename(photo.Title) : photo.Id; if (preferences.FileNameMode == FileNameMode.OriginalOrder) { photoName = GetPadded(curCount); } var targetFileName = Path.Combine(imageDirectory.FullName, string.Format("{0}.{1}", photoName, photoExtension)); if (File.Exists(targetFileName)) { targetFileName = Path.Combine(imageDirectory.FullName, string.Format("{0}-{2}.{1}", photoName, photoExtension, GetPadded(curCount))); } WriteMetaDataFile(photoWithPreferredTags, targetFileName, preferences); var request = WebRequest.Create(photoUrl); var buffer = new byte[4096]; await DownloadAndSavePhoto(targetFileName, request, buffer); doneCount++; progressUpdate.PercentDone = doneCount * 100 / totalCount; progressUpdate.DownloadedPath = string.IsNullOrWhiteSpace(folderPrefix) ? imageDirectory.FullName : _currentTimestampFolder; progress.Report(progressUpdate); if (doneCount != totalCount) { cancellationToken.ThrowIfCancellationRequested(); } } }
/// <summary> /// start scanning /// </summary> /// <param name="callback"></param> /// <param name="complete"></param> /// <param name="cancelComplete"></param> /// <param name="fixAfterScan"></param> public override void StartScan(ProgressUpdate callback, ScanComplete complete, CancelComplete cancelComplete, bool fixAfterScan) { ABORT = false; try { this.callback = callback; this.complete = complete; this.cancelComplete = cancelComplete; this.fixAfterScan = fixAfterScan; List<ListViewItem> problems = new List<ListViewItem>(); FrmSrtUpMan.FillListview(); for (int i = 0; i < AppsToDelete.Count; i++) { if (ABORT) { cancelComplete(); return; } callback((int)(i + 1 / (double)AppsToDelete.Count * 100), AppsToDelete[i]); problems = FrmSrtUpMan.RemoveAppsFromReg(AppsToDelete[i]); ProblemsCount = problems.Count; LstVwItemLst = problems; LstProblems = ConvertLists(problems); } FrmDetails = new FrmDetails(problems); } catch (Exception) { // ToDo: send exception details via SmartAssembly bug reporting! } complete(fixAfterScan); }
public static ProgressUpdate HasFeedback(this ProgressUpdate update, string feedback) { update.Feedback.Should().Be(feedback); return(update); }
/// <see cref="IDiagramEditor.SaveAsync"/> public Task SaveAsync() { _autoSaveTimer.TryStop(); if (_saveExecuting) { return(Tasks.FromSuccess()); } _saveExecuting = true; IsIdle = false; CancelRefreshes(); // PlantUML seems to have a problem detecting encoding if the // first line is not an empty line. if (!Char.IsWhiteSpace(CodeEditor.Content, 0)) { CodeEditor.Content = Environment.NewLine + CodeEditor.Content; } Diagram.Content = CodeEditor.Content; Diagram.TryDeduceImageFile(); // Create a backup if this is the first time the diagram being modified // after opening. bool makeBackup = false; if (_firstSaveAfterOpen) { makeBackup = true; _firstSaveAfterOpen = false; } var progress = _notifications.StartProgress(false); progress.Report(new ProgressUpdate { PercentComplete = 100, Message = String.Format(CultureInfo.CurrentCulture, Resources.Progress_SavingDiagram, Diagram.File.Name) }); var saveTask = _diagramIO.SaveAsync(Diagram, makeBackup) .Then(() => _compiler.CompileToFileAsync(Diagram.File, ImageFormat)); saveTask.ContinueWith(t => { if (t.IsFaulted && t.Exception != null) { progress.Report(ProgressUpdate.Failed(t.Exception.InnerException)); } else if (!t.IsCanceled) { DiagramImage = _diagramRenderers[ImageFormat].Render(Diagram); Diagram.ImageFormat = ImageFormat; CodeEditor.IsModified = false; progress.Report(ProgressUpdate.Completed(Resources.Progress_DiagramSaved)); OnSaved(); } _saveExecuting = false; IsIdle = true; _refreshTimer.TryStop(); }, CancellationToken.None, TaskContinuationOptions.None, _uiScheduler); return(saveTask); }
public static ProgressUpdate HasFeeling(this ProgressUpdate update, Feeling feeling) { update.ProgressFeeling.Should().Be(feeling); return(update); }
public override async Task RandomizeTrainers(Random taskRandom, ProgressNotifier progressNotifier, CancellationToken token) { var config = this.ValidateAndGetConfig().Trainers; if (!config.RandomizeTrainers) { return; } await this.LogAsync($"======== Beginning Trainer randomization ========{Environment.NewLine}"); progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing trainer teams...")); var trainers = (await this.Game.GetTrainerData()).ToList(); var trainerNames = await this.Game.GetTextFile(TextNames.TrainerNames, languageOverride : Language.English); var localizedTrainerNames = await this.Game.GetTextFile(TextNames.TrainerNames); var speciesNames = await this.Game.GetTextFile(TextNames.SpeciesNames); var itemNames = await this.Game.GetTextFile(TextNames.ItemNames); var moveNames = await this.Game.GetTextFile(TextNames.MoveNames); var availableSpecies = Species.ValidSpecies.ToList(); var availableTypes = PokemonTypes.AllPokemonTypes.ToList(); // Get already-edited versions of the info so that we get the shuffled version var starters = await this.Game.GetStarters(edited : true); var pokeInfo = await this.Game.GetPokemonInfo(edited : true); var learnsets = (await this.Game.GetLearnsets(edited: true)).ToList(); // Decide a type for each gym for use later on if the user has chosen to type-theme entire gyms var gymTypes = Enumerable.Range(0, 8).Select(gymId => availableTypes.GetRandom(taskRandom)).ToArray(); var friendStarterGender = new[] { -1, -1, -1 }; var friendStarterAbility = new[] { -1, -1, -1 }; if (config.TypeThemed) { foreach (var(gymIndex, gymType) in gymTypes.Pairs()) { await this.LogAsync($"Gym {gymIndex + 1}: {gymType.Name}-type"); } await this.LogAsync(); } foreach (var(i, trainer) in trainers.Pairs()) { var name = i < trainerNames.LineCount ? trainerNames[i] : "UNKNOWN"; var localizedName = i < localizedTrainerNames.LineCount ? localizedTrainerNames[i] : "UNKNOWN"; await this.LogAsync($"{name}: "); progressNotifier?.NotifyUpdate(ProgressUpdate.Update($"Randomizing trainer teams...\n{localizedName}", i / (double)trainers.Count)); var isFriend = this.IsTrainerFriend(name); var gymId = this.GetGymId(name, i); var chooseFrom = availableSpecies; if (config.TypeThemed) { PokemonType type; if (config.TypeThemedGyms && gymId >= 0) { type = gymTypes[gymId]; } else { type = availableTypes.GetRandom(taskRandom); } chooseFrom = chooseFrom.Where(s => pokeInfo[s.Id].HasType(type)).ToList(); } if (!await this.HandleTrainerSpecificLogicAsync(taskRandom, name, trainer)) { // If there's no item specified for the trainer, randomize the move list instead for more variety // Otherwise, the game will pick moves at random if (!trainer.Item) { trainer.Moves = true; } foreach (var pokemon in trainer.Team) { if (config.FriendKeepsStarter && isFriend && this.IsStarter(pokemon.Species)) { // Figure out which battle scenario we're in (one per starter per story-battle with friend) // Then, get the starter from the slot this scenario represents and figure out // if it needs to be evolved at all var(starterSlot, starterEvo) = this.GetStarterIndexAndEvolution(pokemon.Species); var newStarterBaseSpecies = starters.StarterSpecies[this.MainStarterGen - 1][starterSlot]; var newStarter = await this.GetEvolutionOfAsync(taskRandom, newStarterBaseSpecies, starterEvo); var info = pokeInfo[newStarter]; pokemon.Species = newStarter; if (friendStarterGender[starterSlot] < 0) { friendStarterGender[starterSlot] = info.GetRandomGender(); } if (friendStarterAbility[starterSlot] < 0) { friendStarterAbility[starterSlot] = info.Abilities.GetRandom(taskRandom); } pokemon.Gender = friendStarterGender[starterSlot]; pokemon.Ability = friendStarterAbility[starterSlot]; } else { // Just pick a random species, making sure it conforms to any specified criteria pokemon.Species = (ushort)this.GetRandomSpecies(taskRandom, chooseFrom).Id; var info = pokeInfo[pokemon.Species]; pokemon.Gender = info.GetRandomGender(); pokemon.Ability = info.Abilities.GetRandom(taskRandom); } pokemon.Level = (ushort)MathUtil.Clamp((int)(pokemon.Level * config.LevelMultiplier), 2, 100); // Fill the Pokemon's available moves with random choices from its learnset (up to its current level) var moveset = learnsets[pokemon.Species].GetPossibleMoves(pokemon.Level).ToList(); if (trainer.Moves) { pokemon.HasItem = false; pokemon.HasMoves = true; pokemon.Moves = new ushort[] { 0, 0, 0, 0 }; for (var m = 0; m < Math.Min(moveset.Count, 4); m++) { pokemon.Moves[m] = moveset.Except(pokemon.Moves).ToList().GetRandom(taskRandom); } } } } foreach (var(pkIndex, pokemon) in trainer.Team.Pairs()) { var speciesName = speciesNames[pokemon.Species]; var genderChar = pokemon.Gender switch { 0 => "♂", // Male 1 => "♀", // Female _ => "", // Genderless }; var ability = Abilities.AllAbilities.Single(a => a.Id == pokemon.Ability); var abilityName = ability.Name; if (pokemon.HasItem) { var itemName = itemNames[pokemon.Item]; await this.LogAsync($" Pokémon {pkIndex + 1}: Lv. {pokemon.Level} {speciesName}{genderChar}, {abilityName}, holding {itemName}"); } else { await this.LogAsync($" Pokémon {pkIndex + 1}: Lv. {pokemon.Level} {speciesName}{genderChar}, {abilityName}: "); foreach (var move in pokemon.Moves) { await this.LogAsync($" - {moveNames[ move ]}"); } if (pkIndex != trainer.Team.Length - 1) { await this.LogAsync(); } } } await this.LogAsync(); } await this.Game.SaveTrainerData(trainers); await this.LogAsync($"======== Finished Trainer randomization ========{Environment.NewLine}"); }
public static ProgressUpdate HasMilestonesProgressCount(this ProgressUpdate update, int count) { update.MilestonesProgress.Should().HaveCount(count); return(update); }
public override async Task RandomizeLearnsets(Random taskRandom, ProgressNotifier progressNotifier, CancellationToken token) { var config = this.ValidateAndGetConfig().Learnsets; if (!config.RandomizeLearnsets) { return; } await this.LogAsync($"======== Beginning Learnset randomization ========{Environment.NewLine}"); progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing learnsets...")); var learnsets = (await this.Game.GetLearnsets()).ToList(); var speciesInfo = await this.Game.GetPokemonInfo(edited : true); var moves = (await this.Game.GetMoves()).ToList(); var pokeNames = (await this.Game.GetTextFile(TextNames.SpeciesNames)).Lines; var moveNames = (await this.Game.GetTextFile(TextNames.MoveNames)).Lines; var maxMoveNameLength = moveNames.Max(n => n.Length); for (var i = 0; i < learnsets.Count; i++) { var name = pokeNames[speciesInfo.GetSpeciesForEntry(i)]; await this.LogAsync($"{name}:"); progressNotifier?.NotifyUpdate(ProgressUpdate.Update($"Randomizing learnsets...\n{name}", i / (double)learnsets.Count)); var learnset = learnsets[i]; var species = speciesInfo[i]; var chooseFrom = moves.ToList(); // Clone list var chooseFromSameType = chooseFrom.Where(mv => species.HasType(PokemonTypes.GetValueFrom(mv.Type))).ToList(); ushort PickRandomMove() { var preferSameType = config.FavorSameType && taskRandom.NextDouble() < (double)config.SameTypePercentage; var move = (preferSameType ? chooseFromSameType : chooseFrom).GetRandom(taskRandom); var moveId = (ushort)moves.IndexOf(move); // We have to make sure the "-----" move is not picked because it breaks the game. Ideally // we would just exclude it from the list of considered moves, but to ensure seed-compatiblity // with the previous version of the randomizer, we need to keep the list of moves exactly // the same when we pull a random one. We then replace any "-----" choices with the first real // move. if (moveId == 0) { moveId++; } // Same logic as above but for One-Hit KO moves if (config.NoOneHitMoves && Legality.Moves.OneHitMoves.Contains(moveId)) { moveId++; } return(moveId); } for (var m = 0; m < learnset.Moves.Length; m++) { learnset.Moves[m] = PickRandomMove(); } if (config.RandomizeLevels) { learnset.Levels = learnset.Levels .Select(_ => (ushort)taskRandom.Next(1, MathUtil.Clamp(config.LearnAllMovesBy, 10, 100))) .OrderBy(l => l) .ToArray(); } if (learnset.Levels.Length > 0) { // Make sure there's always at least one move on the Pokemon learnset.Levels[0] = 1; // Pick a random STAB/Normal attack move var firstMoveChoose = moves.Where(m => m.Type == PokemonTypes.Normal.Id || species.HasType(PokemonTypes.GetValueFrom(m.Type))) .Where(m => m.Category == Move.CategoryPhysical || m.Category == Move.CategorySpecial) .ToList(); var move = firstMoveChoose.GetRandom(taskRandom); learnset.Moves[0] = (ushort)moves.IndexOf(move); if (config.AtLeast4Moves) { if (learnset.Levels.Length < 4) { learnset.Levels = new ushort[4]; } if (learnset.Moves.Length < 4) { learnset.Moves = new ushort[4]; } // Make sure every Pokemon has at least 4 moves at level 1 for (var m = 1; m < 4; m++) { learnset.Levels[m] = 1; learnset.Moves[m] = PickRandomMove(); } } // Go down the list and make sure there are no duplicates for (var m = learnset.Moves.Length - 1; m >= 0; m--) { while (Array.IndexOf(learnset.Moves, learnset.Moves[m], 0, m) >= 0) { learnset.Moves[m] = PickRandomMove(); } } } for (var m = 0; m < learnset.Moves.Length; m++) { await this.LogAsync($" - {moveNames[ learnset.Moves[ m ] ].PadLeft( maxMoveNameLength )} @ Lv. {learnset.Levels[ m ]}"); } await this.LogAsync(); learnsets[i] = learnset; } await this.Game.SaveLearnsets(learnsets); await this.LogAsync($"======== Finished Learnset randomization ========{Environment.NewLine}"); }
public static ProgressUpdate HasMilestoneProgressIdAt(this ProgressUpdate update, int index, int id) { update.MilestonesProgress.ElementAt(index).Id.Should().Be(id); return(update); }
public static ProgressUpdate HasMilestoneProgressRatingAt(this ProgressUpdate update, int index, Rating rating) { update.MilestonesProgress.ElementAt(index).Rating.Should().Be(rating); return(update); }
public static ProgressUpdate HasMilestoneProgressCommentAt(this ProgressUpdate update, int index, string comment) { update.MilestonesProgress.ElementAt(index).Comment.Should().Be(comment); return(update); }
public event EventHandler <EventArgs <YourStatus> > ProgressUpdate; // #5 public TestMethod(InputValues input) { //part 1 ProgressUpdate.Raise(this, status); // #6 - status is of type YourStatus //part 2 }
public MSmzML Produce(string path, ProgressUpdate updater, AveragineType type, ChargerType charger) { var model = new MSmzML(); // cvList model.cvList = new CVList(); CV[] cvArray = new CV[2]; cvArray[0] = new CV() { id = "MS", fullName = "Proteomics Standards Initiative Mass Spectrometry Ontology", version = "2.26.0", URI = "http://psidev.cvs.sourceforge.net/*checkout*/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo" }; cvArray[1] = new CV { id = "UO", fullName = "Unit Ontology", version = "14:07:2009", URI = "http://obo.cvs.sourceforge.net/*checkout*/obo/obo/ontology/phenotype/unit.obo" }; model.cvList.cv = cvArray; model.cvList.count = "2"; // fileDescription model.fileDescription = new FileDescription(); model.fileDescription.fileContent = new FileContent(); model.fileDescription.fileContent.cvParam = new CVParam[2]; model.fileDescription.fileContent.cvParam[0] = new CVParam { cvRef = "MS", accession = "MS:1000580", name = "MSn spectrum", value = "" }; model.fileDescription.fileContent.cvParam[1] = new CVParam { cvRef = "MS", accession = "MS:1000127", name = "centroid spectrum", value = "" }; model.fileDescription.sourceFileList = new SourceFileList(); model.fileDescription.sourceFileList.sourceFile = new SourceFile[1]; string fileName = Path.GetFileName(path); model.fileDescription.sourceFileList.sourceFile[0] = new SourceFile { id = fileName, name = fileName, location = path }; model.fileDescription.sourceFileList.count = "1"; model.fileDescription.contact = new Contact(); model.fileDescription.contact.cvParam = new CVParam[2]; model.fileDescription.contact.cvParam[0] = new CVParam { cvRef = "MS", accession = "MS:1000586", name = "contact name", value = contactPerson }; model.fileDescription.contact.cvParam[1] = new CVParam { cvRef = "MS", accession = "MS:1000589", name = "contact email", value = contactEmail }; // softwareList model.softwareList = new SoftwareList(); model.softwareList.software = new Software[1]; model.softwareList.software[0] = new Software { id = software, version = softwareVersion }; model.softwareList.count = "1"; // instrumentConfiguration string instrumentConfigurationID = "UNKNOWN"; model.instrumentConfigurationList = new InstrumentConfigurationList(); model.instrumentConfigurationList.instrumentConfiguration = new InstrumentConfiguration[1]; model.instrumentConfigurationList.instrumentConfiguration[0] = new InstrumentConfiguration() { id = instrumentConfigurationID }; model.instrumentConfigurationList.count = "1"; // data processing model.dataProcessingList = new DataProcessingList(); model.dataProcessingList.dataProcessing = new DataProcessing[1]; model.dataProcessingList.dataProcessing[0] = new DataProcessing(); model.dataProcessingList.dataProcessing[0].id = dataProcessingID; model.dataProcessingList.dataProcessing[0].processingMethod = new ProcessingMethod[1]; model.dataProcessingList.dataProcessing[0].processingMethod[0] = new ProcessingMethod() { order = "1", softwareRef = software }; model.dataProcessingList.dataProcessing[0].processingMethod[0].cvParam = new CVParam[2]; model.dataProcessingList.dataProcessing[0].processingMethod[0].cvParam[0] = new CVParam() { cvRef = "MS", accession = "MS:1000035", name = "peak picking", value = "" }; model.dataProcessingList.dataProcessing[0].processingMethod[0].cvParam[1] = new CVParam() { cvRef = "MS", accession = "MS:1000544", name = "Conversion to mzML", value = "" }; model.dataProcessingList.count = "1"; // spectrum data ThermoRawRunFactory factory = new ThermoRawRunFactory(); model.run = factory.Read(path, type, charger, model.dataProcessingList.dataProcessing[0].id, updater); model.run.id = Guid.NewGuid().ToString(); model.run.defaultInstrumentConfigurationRef = instrumentConfigurationID; return(model); }
public void SendProgressUpdate(ProgressUpdate progressUpdate) { try { var req = new ProgressUpdateRequest(); req.ProgressUpdate = progressUpdate; ProgressUpdateResponse resp = client.ProgressUpdate(req); } catch (RpcException e) { MessageBox.Show("Rpc ProgressUpdate Failed: " + e.Message); } }
/// <summary> /// Загружает данные с биржи /// </summary> public async Task LoadDataAsync(RequestData requestData, string fileName) { this.requestData = requestData; int lineCounter = 0; string line, lastLine = null; string lastLineInFile = null; bool SizeExceeded = false; isStart = true; var fileStream = new FileStream(fileName, FileMode.OpenOrCreate); StreamWriter file = new StreamWriter(fileStream); HttpClient client = new HttpClient() { Timeout = new TimeSpan(0, 10, 0) }; int maxProgress = ConvertDateTimeToInt(requestData.To) - ConvertDateTimeToInt(requestData.From); lastDateTime = new DateTime(requestData.From.Ticks); SetNextDate(); while (from.Ticks <= requestData.To.Ticks) { lineCounter = 0; lastLine = null; try { if (UseEvents) { StatusUpdate?.Invoke(this, new StatusEvent( $"Пакет данных загружается... {from.ToShortDateString()} - {to.ToShortDateString()}")); } var response = await client.GetAsync(requestData.GetRequestUrl(from, to)); using (var stream = new StreamReader(await response.Content.ReadAsStreamAsync())) { if (UseEvents) { StatusUpdate?.Invoke(this, new StatusEvent("Пакет данных сохраняется в файл")); } while (!string.IsNullOrEmpty(line = stream.ReadLine())) { if (!checkFormatter.IsMatch(line)) { continue; } if (SizeExceeded) { //читаем строчки в потоке до тех пор, пока не попадётся последняя записанная в файл if (line == lastLineInFile) { SizeExceeded = false; } continue; } lineCounter++; lastLine = line; lastLineInFile = line; file.WriteLine(line); } } } catch (Exception e) { if (UseEvents) { StatusUpdate?.Invoke(this, new StatusEvent("Произошла ошибка!")); } MessageBox.Show($"{e.Message}\n\n{e.StackTrace}", "Error"); } if (!string.IsNullOrEmpty(lastLine)) { lastLineInFile = lastLine; } SizeExceeded = lineCounter >= 990000; //Около миллиона if (lastLine == null) //Случаи выходных или праздничных дней { lastDateTime = new DateTime(to.Ticks + Day1.Ticks); } else if (SizeExceeded) //Случай, когда особый ажиотаж на рынке { lastDateTime = GetDateTime(lastLine.Split(';')[0]); } else { lastDateTime = new DateTime(to.Ticks + Day1.Ticks); } if (UseEvents) { ProgressUpdate?.Invoke(this, new ProgressEvent() { MaxProgress = maxProgress, CurrentProgress = ConvertDateTimeToInt(to) - ConvertDateTimeToInt(requestData.From), IsFinished = false }); } SetNextDate(); } file.Close(); if (UseEvents) { ProgressUpdate?.Invoke(this, new ProgressEvent() { MaxProgress = 100, CurrentProgress = 100, IsFinished = true }); } if (UseEvents) { StatusUpdate?.Invoke(this, new StatusEvent("Процесс загрузки данных закончен")); } }
private void ProgressUpdateMassSet(bool isPressed, double progress) { var prg = new ProgressUpdate(); foreach (var key in config.keys) { if (key.Type == "JoystickKey" || key.Type == "Tactile") { var tac = new ProgressUpdate.Types.TactileUpdate(); tac.Id = 0; tac.Fired = false; // isPressed; tac.Progress = progress; prg.Tactile.Add(tac); } if (key.Type == "Joystick") { var joy = new ProgressUpdate.Types.JoystickUpdate(); joy.Id = 0; joy.Intensity = progress; prg.Joystick.Add(joy); } } client.SendProgressUpdate(prg); }
/// <summary> /// start fixing /// </summary> /// <param name="callback"></param> public override void StartFix(ProgressUpdate callback) { ABORT = false; try { this.callback = callback; totalFilesCount = TmpFiles.Count + WinFiles.Count + IEFiles.Count + FFFiles.Count + ChromeFiles.Count; processed = 0; if (tmp) { StartFixSubMethod(TmpFiles); } else processed += TmpFiles.Count; if (win) { StartFixSubMethod(WinFiles); } else processed += WinFiles.Count; if (ie) { StartFixSubMethod(IEFiles); } else processed += IEFiles.Count; if (ff) { StartFixSubMethod(FFFiles); } else processed += FFFiles.Count; if (chrome) { StartFixSubMethod(ChromeFiles); } else processed += ChromeFiles.Count; } catch (Exception) { // ToDo: send exception details via SmartAssembly bug reporting! } complete(fixAfterScan); }
/// <summary> /// start fixing /// </summary> /// <param name="callback"></param> public override void StartFix(ProgressUpdate callback) { ABORT = false; try { this.callback = callback; //Scan and delete foreach (ListViewItem item in FrmSrtUpMan.LstProblems) { if (ABORT) { cancelComplete(); return; } FrmSrtUpMan.DeleteItem(item.SubItems[1].Text); } } catch (Exception) { // ToDo: send exception details via SmartAssembly bug reporting! } complete(fixAfterScan); }
/// <summary> /// Entry point of the data download thread. /// </summary> private void DownloadThread() { try { // Open up a connection to the binary phoenix software updater. if (_socket != null) { _socket.Close(); } try { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(new IPAddress(Dns.GetHostEntry(_host).AddressList[0].GetAddressBytes()), 80); _socket.ReceiveTimeout = 5000; } catch (SocketException) { _error = "Unable to connect to host \"" + _host + "\"."; Debug.DebugLogger.WriteLog("An error occured while downloading '" + _url + "', \"" + _error + "\" "); if (ErrorOccured != null) { ErrorOccured(this, _error); } return; } _stream = new NetworkStream(_socket); // Build the post variables. int var = 0; string postRequest = ""; foreach (string key in _postVariables.Keys) { postRequest += (var != 0 ? "&" : "") + key + "=" + System.Web.HttpUtility.UrlEncode(_postVariables[key] as string); var++; } // Try and access the php updater file with the given account. string getRequest = (_method == DownloadMethod.POST ? "POST " : "GET ") + (_file + (postRequest != "" ? "&" + postRequest : "")).Replace(" ", "%20") + " HTTP/1.0\n" + "host: " + _host + "\n" + "user-agent: FusionDownloader\n" + "accept: * /*\n" + "connection: keep-alive\n" + "Keep-Alive: 300\n" + "cache-control: no-cache\n" + "content-type: application/x-www-form-urlencoded\n" + (_method == DownloadMethod.POST ? "content-length: " + postRequest.Length : "") + "\n"; _socket.Send(Encoding.ASCII.GetBytes(getRequest)); // Check this request went through OK. string result = ReadLineFromSocket(_socket); if (result.IndexOf("200 OK") < 0) { _error = "File \"" + _file + "\" does not exist on host \"" + _host + "\"."; Debug.DebugLogger.WriteLog("An error occured while downloading '" + _url + "', \"" + _error + "\" "); if (ErrorOccured != null) { ErrorOccured(this, _error); } return; } // Skip the header as we don't require it. string header = "#"; while (header != "") { header = ReadLineFromSocket(_socket); if (header.ToLower().StartsWith("content-length:") == true) { _totalSize = int.Parse(header.Substring(15)); } } // Create an array to hold the data downloaded. _fileData = new byte[_totalSize]; // Create a timer to use when tracking the speed of the download. HighPreformanceTimer timer = new HighPreformanceTimer(); if (_totalSize != 0) { while (_downloadedBytes < _totalSize) { // If this download has been paused then go to sleep for a little bit. while (_paused == true) { Thread.Sleep(1); } // Read in the next lot of data and quit if we don't recieve any. int bytesRead = 0; try { bytesRead = _socket.Receive(_fileData, _downloadedBytes, _totalSize - _downloadedBytes < 1024 ? _totalSize - _downloadedBytes : 1024, 0); if (bytesRead == 0) { break; } } catch (SocketException) { _error = "Download of \"" + _url + "\" was forceable stopped by the remote host."; Debug.DebugLogger.WriteLog("Download of \"" + _url + "\" was forceable stopped by the remote host."); if (ErrorOccured != null) { ErrorOccured(this, _error); } return; } // Update the amount of bytes downloaded and break out // of this loop if we haven't read in a full buffer. _downloadedBytes += bytesRead; // Keep track of the current download speed. if (timer.DurationMillisecond >= 1000) { timer.Restart(); _speed = (int)(((float)_downloadedBytes - (float)_speedTracker) / 1024.0f); _speedTracker = _downloadedBytes; // Push this speed onto the average stack. _averageCounter.Add(_speed); if (_averageCounter.Count > 20) { _averageCounter.RemoveAt(0); } // Work out the average speed. int total = 0; foreach (int avgSpeed in _averageCounter) { total += avgSpeed; } _averageSpeed = total / _averageCounter.Count; } // Invoke the update progress notification event. _progress = (int)((100.0f / (float)_totalSize) * (float)_downloadedBytes); if (ProgressUpdate != null) { ProgressUpdate.Invoke(this, _progress); } } // Check we managed to download the whole file. if (_fileData.Length != _totalSize) { _error = "Unable to download all data for \"" + _file + "\" expecting " + _totalSize + " bytes but got " + _fileData.Length + " bytes."; Debug.DebugLogger.WriteLog("An error occured while downloading '" + _url + "', \"" + _error + "\" "); if (ErrorOccured != null) { ErrorOccured(this, _error); } return; } } else { while (true) { // If this download has been paused then go to sleep for a little bit. while (_paused == true) { Thread.Sleep(1); } // Read in the next lot of data and quit if we don't recieve any. byte[] dataBuffer = new byte[1024]; int bytesRead = 0; try { bytesRead = _socket.Receive(dataBuffer, 1024, 0); } catch { _error = "Unable to download all data for \"" + _file + "\", require timed out."; Debug.DebugLogger.WriteLog("An error occured while downloading '" + _url + "', \"" + _error + "\" "); if (ErrorOccured != null) { ErrorOccured(this, _error); } return; } if (bytesRead == 0) { break; } // Convert the bytes into characters and append it to the data. if (_downloadedBytes + bytesRead - 1 > _fileData.Length) { Array.Resize <byte>(ref _fileData, _downloadedBytes + bytesRead); } for (int i = 0; i < bytesRead; i++) { _fileData[_downloadedBytes + i] = dataBuffer[i]; } _downloadedBytes += bytesRead; } } // Close the stream. _stream.Close(); _socket.Close(); _complete = true; Debug.DebugLogger.WriteLog("Downloaded file of " + _fileData.Length + " bytes from '" + _url + "'..."); } catch (Exception) { _error = "The server forceably closed the connection."; } }
/// <summary> /// start erasing /// </summary> /// <param name="callback"></param> public override void StartFix(ProgressUpdate callback) { FrmTrackSel.StartFix(); }
public abstract void StartFix(ProgressUpdate callback);
/// <summary> /// /// </summary> private void OnProgressUpdate(int progress) { ProgressUpdate?.Invoke(progress); }
public override async Task RandomizeStarters(Random taskRandom, ProgressNotifier progressNotifier, CancellationToken token) { var config = this.ValidateAndGetConfig().Starters; if (!config.RandomizeStarters) { return; } await this.LogAsync($"======== Beginning Starter Pokémon randomization ========{Environment.NewLine}"); progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing starter Pokémon...")); var starters = await this.Game.GetStarters(); var species = Species.ValidSpecies.ToList(); var speciesInfo = await this.Game.GetPokemonInfo(true); var chosen = new List <SpeciesType>(); var speciesNames = (await this.Game.GetTextFile(TextNames.SpeciesNames)).Lines; if (config.StartersOnly) { species = species.Intersect(Starters.AllStarters) .ToList(); } else if (!config.AllowLegendaries) { species = species.Except(Legendaries.AllLegendaries) .ToList(); } foreach (var gen in starters.Generations) { for (int i = 0; i < 3; i++) { var thisSpecies = new List <SpeciesType>(species); if (config.ElementalTypeTriangle) { // All starters are ordered by Grass, Fire, Water in all Gen 6 games var requiredType = i switch { 0 => PokemonTypes.Grass, 1 => PokemonTypes.Fire, _ => PokemonTypes.Water, }; thisSpecies = species.Where(s => speciesInfo[s].HasType(requiredType)).ToList(); } var ret = this.GetRandomSpecies(taskRandom, thisSpecies.Except(chosen)); chosen.Add(ret); starters[gen][i] = (ushort)ret; } var generationName = gen == this.MainStarterGen ? "Main" : $"Generation {gen}"; await this.LogAsync($"{generationName} Starters: {string.Join( ", ", starters[ gen ].Select( s => speciesNames[ s ] ) )}"); } await this.Game.SaveStarters(starters); await this.LogAsync($"{Environment.NewLine}======== Finished Starter Pokémon randomization ========{Environment.NewLine}"); }
/// <summary> /// start scanning /// </summary> /// <param name="callback"></param> /// <param name="complete"></param> /// <param name="cancelComplete"></param> /// <param name="fixAfterScan"></param> public override void StartScan(ProgressUpdate callback, ScanComplete complete, CancelComplete cancelComplete, bool fixAfterScan) { ABORT = false; try { TmpFiles = new List<FileInfo>(); WinFiles = new List<FileInfo>(); IEFiles = new List<FileInfo>(); FFFiles = new List<FileInfo>(); ChromeFiles = new List<FileInfo>(); TmpSize = 0; WinSize = 0; IESize = 0; FFSize = 0; ChromeSize = 0; this.callback = callback; this.complete = complete; this.cancelComplete = cancelComplete; this.fixAfterScan = fixAfterScan; string winTempPath = Environment.GetEnvironmentVariable("Temp"); string IETempPath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); string ffCachePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Mozilla\\Firefox\\Profiles"; string chromeCachePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Google\\Chrome\\User Data\\Default"; DirectoryInfo windowsTemp = Directory.Exists(winTempPath) ? new DirectoryInfo(winTempPath) : null; DirectoryInfo IETemp = Directory.Exists(IETempPath) ? new DirectoryInfo(IETempPath) : null; DirectoryInfo ffCahce = Directory.Exists(ffCachePath) ? new DirectoryInfo(ffCachePath) : null; DirectoryInfo chromeCache = Directory.Exists(chromeCachePath) ? new DirectoryInfo(chromeCachePath) : null; int WinFilesCount = windowsTemp != null ? windowsTemp.GetDirectories().Length + windowsTemp.GetFiles().Length : 0; int IETempCount = IETemp != null ? IETemp.GetDirectories().Length + IETemp.GetFiles().Length : 0; int ffCahceCount = ffCahce != null ? ffCahce.GetDirectories().Length + ffCahce.GetFiles().Length : 0; int chromeCacheCount = chromeCache != null ? chromeCache.GetDirectories().Length + chromeCache.GetFiles().Length : 0; int filesCount = WinFilesCount + IETempCount + ffCahceCount + chromeCacheCount; List<DriveInfo> drives = null; try { drives = DriveInfo.GetDrives().Where(drive => drive.IsReady && (drive.DriveType == DriveType.Fixed || drive.DriveType == DriveType.Removable)).ToList(); } catch (IOException) { } catch (UnauthorizedAccessException) { } if (drives != null) { filesCount += drives.Count; scannedFilesCount = 0; foreach (DriveInfo drive in drives) { if (ABORT) { cancelComplete(); return; } try { FileInfo[] tmpFiles = drive.RootDirectory.GetFiles("*.tmp"); TmpFiles.AddRange(tmpFiles); } catch { } scannedFilesCount++; callback((int)((scannedFilesCount / (float)filesCount) * 100), drive.RootDirectory.FullName); } } if (windowsTemp != null) { if (ABORT) { cancelComplete(); return; } CollectFiles(windowsTemp, "win"); int firstLevelSubDirectoriesCount = windowsTemp.GetDirectories().Count() + 1; if (firstLevelSubDirectoriesCount < WinFilesCount) { int filesPerSubDirectory = WinFilesCount / firstLevelSubDirectoriesCount; int filesPerSubDirectoryMod = WinFilesCount % firstLevelSubDirectoriesCount; for (int i = 0; i < firstLevelSubDirectoriesCount - 1; i++) { scannedFilesCount += filesPerSubDirectory; callback((int)((scannedFilesCount / (float)filesCount) * 100), windowsTemp.FullName); Thread.Sleep(20); } scannedFilesCount += filesPerSubDirectory + filesPerSubDirectoryMod; callback((int)((scannedFilesCount / (float)filesCount) * 100), windowsTemp.FullName); } else { scannedFilesCount += WinFilesCount; callback((int)((scannedFilesCount / (float)filesCount) * 100), windowsTemp.FullName); } } if (IETemp != null) { if (ABORT) { cancelComplete(); return; } CollectFiles(IETemp, "ie"); scannedFilesCount += IETempCount; callback((int)((scannedFilesCount / (float)filesCount) * 100), windowsTemp.FullName); } if (ffCahce != null) { if (ABORT) { cancelComplete(); return; } CollectFiles(ffCahce, "ff"); scannedFilesCount += ffCahceCount; callback((int)((scannedFilesCount / (float)filesCount) * 100), windowsTemp.FullName); } if (chromeCache != null) { if (ABORT) { cancelComplete(); return; } CollectFiles(chromeCache, "chrome"); scannedFilesCount += chromeCacheCount; callback((int)((scannedFilesCount / (float)filesCount) * 100), windowsTemp.FullName); } } catch (Exception) { // ToDo: send exception details via SmartAssembly bug reporting! } complete(fixAfterScan); }
/// <summary> /// start fixing /// </summary> /// <param name="callback"></param> public override void StartFix(ProgressUpdate callback) { ABORT = false; this.callback = callback; int shortcutsProcessed = 0; foreach (Shortcut brokenShortcut in BrokenShortcuts) { if (ABORT) { cancelComplete(); return; } shortcutsProcessed++; try { string shortcutFullname = brokenShortcut.Location + "\\" + brokenShortcut.Name; if (File.Exists(shortcutFullname)) { File.Delete(shortcutFullname); callback((int)((double)shortcutsProcessed / BrokenShortcuts.Count * 100), shortcutFullname); } } catch (Exception e) { // ToDo: send exception details via SmartAssembly bug reporting! } } complete(fixAfterScan); }
/// <summary> /// start scanning /// </summary> /// <param name="callback"></param> /// <param name="complete"></param> /// <param name="cancelComplete"></param> /// <param name="fixAfterScan"></param> public override void StartScan(ProgressUpdate callback, ScanComplete complete, CancelComplete cancelComplete, bool fixAfterScan) { ABORT = false; BrokenShortcuts.Clear(); this.callback = callback; this.complete = complete; this.cancelComplete = cancelComplete; this.fixAfterScan = fixAfterScan; string root = Path.GetPathRoot(Environment.SystemDirectory); string user = Environment.UserName; HashSet<string> places = new HashSet<string>(); if (OSIsXP()) { places.Add(root + @"Documents and Settings\All Users\Desktop"); places.Add(root + @"Documents and Settings\All Users\Start Menu"); places.Add(root + @"Documents and Settings\Default User\Desktop"); places.Add(root + @"Documents and Settings\Default User\Start Menu"); places.Add(root + @"Documents and Settings\" + user + @"\Desktop"); places.Add(root + @"Documents and Settings\" + user + @"\Start Menu"); } places.Add(root + @"ProgramData\Desktop"); places.Add(root + @"ProgramData\Microsoft\Windows\Start Menu"); places.Add(root + @"ProgramData\Start Menu"); places.Add(root + @"Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu"); places.Add(root + @"Users\Default\Desktop"); places.Add(root + @"Users\Default\Start Menu"); places.Add(root + @"Users\Public\Desktop"); places.Add(root + @"Users\" + user + @"\AppData\Roaming\Microsoft\Windows\Start Menu"); places.Add(root + @"Users\" + user + @"\Desktop"); places.Add(root + @"Users\" + user + @"\Start Menu"); places.Add(GetSpecialFolderPath(CSIDL_COMMON_DESKTOPDIRECTORY)); places.Add(GetSpecialFolderPath(CSIDL_COMMON_STARTMENU)); places.Add(GetSpecialFolderPath(CSIDL_DESKTOP)); places.Add(GetSpecialFolderPath(CSIDL_DESKTOPDIRECTORY)); places.Add(GetSpecialFolderPath(CSIDL_STARTMENU)); List<FileInfo> shortcutList = new List<FileInfo>(); foreach (string s in places) { try { DirectoryInfo dir = new DirectoryInfo(s); FileAttributes att = dir.Attributes; if ((att & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint) { shortcutList.AddRange(dir.GetFiles("*.lnk", SearchOption.AllDirectories)); } } catch { } } int shortcutsFound = shortcutList.Count; int shortcutsProcessed = 0; foreach (FileInfo shortcut in shortcutList) { if (ABORT) { cancelComplete(); return; } try { WshShellClass wshShellClass = new WshShellClass(); IWshShortcut shortcutInfo = (IWshShortcut)wshShellClass.CreateShortcut(shortcut.FullName); string linkTarget = shortcutInfo.TargetPath; string linkfile = linkTarget; if (linkTarget.Contains("\\")) { linkfile = linkTarget.Substring(linkTarget.LastIndexOf("\\")); } if (string.IsNullOrEmpty(linkTarget)) { continue; } var drive = new DriveInfo(linkTarget.Substring(0, 1)); if (drive.DriveType == DriveType.CDRom) { continue; } if (shortcutInfo.TargetPath.Contains("Program Files")) { IWshShortcut shortcutInfox86 = (IWshShortcut)wshShellClass.CreateShortcut(shortcut.FullName); shortcutInfox86.TargetPath = shortcutInfox86.TargetPath.Replace(" (x86)", string.Empty); if (!File.Exists(shortcutInfo.TargetPath) && !Directory.Exists(shortcutInfo.TargetPath) && !File.Exists(shortcutInfox86.TargetPath.Replace(" (x86)", string.Empty)) && !Directory.Exists(shortcutInfox86.TargetPath.Replace(" (x86)", string.Empty))) { Shortcut brokenShortcut = new Shortcut { Name = shortcut.Name, Target = shortcutInfox86.TargetPath, Location = shortcut.DirectoryName, Description = shortcutInfox86.Description }; BrokenShortcuts.Add(brokenShortcut); ProblemsCount++; } } else { if (!string.IsNullOrEmpty(shortcutInfo.TargetPath) && !File.Exists(shortcutInfo.TargetPath) && !Directory.Exists(shortcutInfo.TargetPath) && !File.Exists(Environment.ExpandEnvironmentVariables(@"%systemroot%\Sysnative") + "\\" + linkfile) && !File.Exists(Environment.SystemDirectory + "\\" + linkfile) && !File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\" + linkfile)) { var brokenShortcut = new Shortcut { Name = shortcut.Name, Target = shortcutInfo.TargetPath, Location = shortcut.DirectoryName, Description = shortcutInfo.Description }; BrokenShortcuts.Add(brokenShortcut); ProblemsCount++; } } } catch (Exception) { // ToDo: send exception details via SmartAssembly bug reporting! } shortcutsProcessed++; callback((int)((double)shortcutsProcessed / shortcutsFound * 100), shortcut.FullName); } complete(fixAfterScan); }
public override async Task RandomizeEncounters(Random taskRandom, ProgressNotifier progressNotifier, CancellationToken token) { var config = this.ValidateAndGetConfig().Encounters; if (!config.RandomizeEncounters) { return; } await this.LogAsync($"======== Beginning Encounter randomization ========{Environment.NewLine}"); progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing wild Pokémon encounters...")); var species = Species.ValidSpecies.ToList(); var speciesInfo = await this.Game.GetPokemonInfo(edited : true); var encounterData = await this.Game.GetEncounterData(); var encounterZones = encounterData.Cast <OrasEncounterWild>().ToList(); var zoneNames = (await this.Game.GetTextFile(TextNames.EncounterZoneNames)).Lines; var speciesNames = (await this.Game.GetTextFile(TextNames.SpeciesNames)).Lines; (int zone, int subZone)dittoSpot = (-1, -1); // If "Ensure Dittos in Grass" is enabled, we need to make sure dittos appear in grass *somewhere* in the game. // Pick a random valid encounter zone/slot in which to place Ditto if (config.EnsureDittosInGrass) { var foundPlaceForDitto = false; while (!foundPlaceForDitto) { var dittoZone = encounterZones.GetRandom(taskRandom); if (dittoZone.GetAllEntries().Any(e => e != null)) { var entryArrays = dittoZone.EntryArrays; var dittoSubZone = entryArrays.FirstOrDefault(); // Grass is always first sub-zone if (dittoSubZone != null && !dittoSubZone.All(e => e.Species == Species.Egg.Id)) { var dittoEntry = taskRandom.Next(Math.Min(dittoSubZone.Length, GrassEntries)); // Store zone and entry index for later dittoSpot = (encounterZones.IndexOf(dittoZone), dittoEntry); foundPlaceForDitto = true; } } } } if (!config.AllowLegendaries) { species = species.Except(Legendaries.AllLegendaries) .ToList(); } foreach (var(iEncounter, encounterZone) in encounterZones.Pairs()) { var name = zoneNames[encounterZone.ZoneId]; if (!encounterZone.GetAllEntries().Any(e => e != null)) { continue; } progressNotifier?.NotifyUpdate(ProgressUpdate.Update($"Randomizing encounters...\n{name}", iEncounter / (double)encounterZones.Count)); PokemonType areaType = default; List <SpeciesType> speciesChoose; void UpdateChoiceList(IList <SpeciesType> choices) { var uniqueList = new List <SpeciesType>(); // DexNav can only handle up to 18 unique species per encounter area, // so we pick 18 random and unique species from our current choice list while (uniqueList.Count < MaxUniqueSpecies) { // Find a new unique species from our current determined list of choices uniqueList.Add(this.GetRandomSpecies(taskRandom, choices.Except(uniqueList))); } speciesChoose = uniqueList.ToList(); } if (config.TypeThemedAreas) { areaType = PokemonTypes.AllPokemonTypes.ToArray().GetRandom(taskRandom); UpdateChoiceList(species.Where(s => speciesInfo[s.Id].HasType(areaType)).ToList()); } else { UpdateChoiceList(species); } if (areaType == default || config.TypePerSubArea) { await this.LogAsync($"Randomizing zone: {name}"); } else { await this.LogAsync($"Randomizing zone: {name} ({areaType.Name}-type)"); } var subZoneArrays = encounterZone.EntryArrays; int[] orderedIndices = subZoneArrays.OrderByDescending(ea => ea.Length) .Select(ea => Array.IndexOf(subZoneArrays, ea)) .ToArray(); foreach (var(iSubZone, subZoneArray) in subZoneArrays.Pairs()) { if (subZoneArray.All(e => e.Species == Species.Egg.Id)) { continue; } if (areaType != default && config.TypePerSubArea) { await this.LogAsync($" Sub-zone {iSubZone + 1} ({areaType.Name}-type):"); } else { await this.LogAsync($" Sub-zone {iSubZone + 1}:"); } // In horde battles, one of the slots could be a different species, and we treat the value "5" as "all the same" var isHordeEncounter = HordeSubZones.Contains(iSubZone); var hordeSlot = isHordeEncounter ? taskRandom.Next(0, 6) : -1; var hordeSpecies = -1; foreach (var(iEntry, entry) in subZoneArray.Where(entry => entry.Species != Species.Egg.Id).Pairs()) { var(dittoEncounter, dittoEntry) = dittoSpot; if (config.EnsureDittosInGrass && iEncounter == dittoEncounter && iSubZone == GrassSubZone && iEntry == dittoEntry) { entry.Species = (ushort)Species.Ditto.Id; } else { if (config.ProperHordes && isHordeEncounter) { // For horde battles, every slot has the same species, except for optionally a random slot which can be unique if (iEntry == hordeSlot) { entry.Species = (ushort)this.GetRandomSpecies(taskRandom, speciesChoose).Id; } else { if (hordeSpecies < 0) { hordeSpecies = this.GetRandomSpecies(taskRandom, speciesChoose).Id; } entry.Species = (ushort)hordeSpecies; } } else { entry.Species = (ushort)this.GetRandomSpecies(taskRandom, speciesChoose).Id; } } if (config.LevelMultiplier != 1.0m) { entry.MinLevel = (byte)MathUtil.Clamp((int)(config.LevelMultiplier * entry.MinLevel), 2, 100); entry.MaxLevel = (byte)MathUtil.Clamp((int)(config.LevelMultiplier * entry.MaxLevel), 2, 100); } await this.LogAsync($" Entry: {speciesNames[ entry.Species ]}, levels {entry.MinLevel} to {entry.MaxLevel}"); } if (config.TypeThemedAreas && config.TypePerSubArea) // Re-generate type for the new sub-area { areaType = PokemonTypes.AllPokemonTypes.ToArray().GetRandom(taskRandom); UpdateChoiceList(species.Where(s => speciesInfo[s.Id].HasType(areaType)).ToList()); } if (iSubZone != subZoneArrays.Length - 1) { await this.LogAsync(); } } int GetUniqueAllSections() => subZoneArrays.Sum(ea => ea.Select(e => e.Species).Distinct().Count(sp => sp > 0)); // DexNav crashes if there are more than 18 unique species in an encounter zone. // If the same species appears in two different sub-zones, it counts as two // unique species. while (GetUniqueAllSections() > MaxUniqueSpecies) { // Starting with the largest array, reduce the number of unique species taken up by that array by one foreach (int i in orderedIndices) { var entryArray = subZoneArrays[i]; int uniqueThisSection = entryArray.Select(e => e.Species).Distinct().Count(sp => sp > 0); // If there are less than two unique species in this array, we don't have enough // species to reduce, so skip it. if (uniqueThisSection < 2) { continue; } // Pick a random slot to overwrite int randomTo = -1; while (randomTo < 0 || entryArray[randomTo].Species == 0) { randomTo = taskRandom.Next(entryArray.Length); } // Get a species that's different than the slot we're overwriting so we make a duplicate var donorEntry = entryArray.First(e => e.Species > 0 && e.Species != entryArray[randomTo].Species); entryArray[randomTo].Species = donorEntry.Species; subZoneArrays[i] = entryArray; // Don't bother with the rest of the arrays if we fixed the problem if (GetUniqueAllSections() == MaxUniqueSpecies) { break; } } } await this.LogAsync(); encounterZone.EntryArrays = subZoneArrays; } await this.LogAsync(); progressNotifier?.NotifyUpdate(ProgressUpdate.Update("Randomizing encounters...\nCompressing encounter data...this may take a while", 1.0)); await this.Game.SaveEncounterData(encounterZones); await this.LogAsync($"======== Finished Encounter randomization ========{Environment.NewLine}"); }
public abstract void StartScan(ProgressUpdate callback, ScanComplete complete, CancelComplete cancelComplete, bool fixAfterScan);
public virtual async Task RandomizeOverworldItems(Random taskRandom, ProgressNotifier progressNotifier, CancellationToken cancellationToken) { var config = this.ValidateAndGetConfig().OverworldItems; if (!config.RandomizeOverworldItems) { return; } await this.LogAsync($"======== Beginning Overworld Item randomization ========{Environment.NewLine}"); progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing overworld items...")); var availableItemIds = Legality.Items.GetValidOverworldItems(this.Game.Version) .Except(this.Game.Version.IsXY() ? Legality.Items.TM_XY : Legality.Items.TM_ORAS) .ToArray(); var availableTmItemIds = Legality.Items.GetValidOverworldItems(this.Game.Version) .Intersect(this.Game.Version.IsXY() ? Legality.Items.TM_XY : Legality.Items.TM_ORAS) .ToArray(); var overworldItems = await this.Game.GetOverworldItems(); var itemNames = (await this.Game.GetTextFile(TextNames.ItemNames)).Lines; if (!config.AllowMasterBalls) { availableItemIds = availableItemIds.Except(new[] { (ushort)Items.MasterBall.Id }).ToArray(); } if (!config.AllowMegaStones) { availableItemIds = availableItemIds.Except(Legality.Items.MegaStones).ToArray(); } foreach (var(i, item) in overworldItems.Items.Pairs()) { progressNotifier?.NotifyUpdate(ProgressUpdate.Update(progressNotifier.Status, i / (double)overworldItems.Items.Count)); var hmItems = this.Game.Version.IsXY() ? Legality.Items.HM_XY : Legality.Items.HM_ORAS; if (hmItems.Any(id => id == item.ItemId)) { // Don't randomize HMs! Might strand the player! continue; } var oldItemId = item.ItemId; var isTM = availableTmItemIds.Contains((ushort)oldItemId); if (isTM) { if (config.RandomizeTMs) { item.ItemId = availableTmItemIds.GetRandom(taskRandom); } } else { var newItemId = availableItemIds.GetRandom(taskRandom); if (item.ItemId != Items.MasterBall.Id) // OR/AS only: Don't get rid of possibly the only Master Ball in the game! { item.ItemId = newItemId; } } if (item.ItemId != oldItemId) { var oldItemName = itemNames[(int)oldItemId]; var newItemName = itemNames[(int)item.ItemId]; await this.LogAsync($"Changing {oldItemName.Article()} {oldItemName} to {newItemName.Article()} {newItemName}"); } } await this.Game.SaveOverworldItems(overworldItems); await this.LogAsync($"{Environment.NewLine}======== Finished Overworld Item randomization ========{Environment.NewLine}"); }
/// <summary> /// Starts scanning /// </summary> /// <param name="callback"><see cref="ProgressUpdate"/> callback</param> /// <param name="complete"><see cref="ScanComplete"/> callback</param> /// <param name="cancelComplete"><see cref="CancelComplete"/> callback</param> /// <param name="fixAfterScan">A bool flag that determines is the fixing needed after finishing the scan</param> public override void StartScan(ProgressUpdate callback, ScanComplete complete, CancelComplete cancelComplete, bool fixAfterScan) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(CfgFile.Get("Lang")); if (SelectedRegistryCategoriesCount() > 0) { this.callback = callback; this.complete = complete; this.cancelComplete = cancelComplete; this.fixAfterScan = fixAfterScan; Reset(); ABORT = false; ScanStart(); } else { MessageBox.Show(Resources.SelectAtLeastOneItem, Resources.InvalidSelection, MessageBoxButton.OK, MessageBoxImage.Exclamation); } }
private const int MinCatchRate = 0x19; // That of rare Pokémon such as Snorlax public override async Task RandomizePokemonInfo(Random taskRandom, ProgressNotifier progressNotifier, CancellationToken token) { var config = this.ValidateAndGetConfig().PokemonInfo; if (!config.RandomizeTypes && !config.RandomizeAbilities) { return; } await this.LogAsync($"======== Beginning Pokémon Info randomization ========{Environment.NewLine}"); progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing Pokémon personal information...")); var pokeInfoTable = await this.Game.GetPokemonInfo(); var avilableAbilities = Abilities.AllAbilities.ToList(); var availableTypes = PokemonTypes.AllPokemonTypes.ToList(); var pokeNames = (await this.Game.GetTextFile(TextNames.SpeciesNames)).Lines; var typeNames = (await this.Game.GetTextFile(TextNames.Types)).Lines; if (!config.AllowWonderGuard) { avilableAbilities = avilableAbilities.Where(a => a.Id != Abilities.WonderGuard.Id).ToList(); } // Randomize abilities for each entry in the Info table (which includes all forms) for (var i = 0; i < pokeInfoTable.Table.Length; i++) { var name = pokeNames[pokeInfoTable.GetSpeciesForEntry(i)]; var thisStatus = $"Randomizing Pokémon personal information...\n{name}"; var thisProgress = i / (double)pokeInfoTable.Table.Length; await this.LogAsync($"{name}: "); progressNotifier?.NotifyUpdate(ProgressUpdate.Update(thisStatus, thisProgress)); var pokeInfo = pokeInfoTable[i]; if (config.RandomizeAbilities) { progressNotifier?.NotifyUpdate(ProgressUpdate.Update($"{thisStatus}\nRandomizing abilities...", thisProgress)); var abilities = pokeInfo.Abilities; var abilityNames = new string[abilities.Length]; for (var a = 0; a < abilities.Length; a++) { var ability = avilableAbilities.GetRandom(taskRandom); abilities[a] = (byte)ability.Id; abilityNames[a] = ability.Name; } pokeInfo.Abilities = abilities; await this.LogAsync($" - Available abilities: {string.Join( ", ", abilityNames )}"); } if (config.RandomizeTypes) { progressNotifier?.NotifyUpdate(ProgressUpdate.Update($"{thisStatus}\nRandomizing types...", thisProgress)); var types = pokeInfo.Types; if (types.Length > 0) // Just to be safe { if (config.RandomizePrimaryTypes) { types[0] = (byte)availableTypes.GetRandom(taskRandom).Id; } if (config.RandomizeSecondaryTypes && types.Length > 1) { types[1] = (byte)availableTypes.Where(type => type.Id != types[0]) .ToList() .GetRandom(taskRandom) .Id; } if (config.RandomizePrimaryTypes || config.RandomizeSecondaryTypes) { await this.LogAsync($" - Types: {string.Join( "/", types.Select( t => typeNames[ t ] ) )}"); } } pokeInfo.Types = types; } if (config.EnsureMinimumCatchRate && i > 0 && pokeInfo.CatchRate < MinCatchRate) { await this.LogAsync($" - Increased catch rate from {pokeInfo.CatchRate:000} to {MinCatchRate:000}"); pokeInfo.CatchRate = MinCatchRate; } await this.LogAsync(); pokeInfoTable[i] = pokeInfo; } await this.Game.SavePokemonInfo(pokeInfoTable); await this.LogAsync($"======== Finished Pokémon Info randomization ========{Environment.NewLine}"); }