IEnumerator WaitForLoadLevel(int level, bool additive = false) { loadingScreen.Show(); OnLoadBegin.Dispatch(); #if (UNITY_5_2 || UNITY_5_1 || UNITY_5_0) AsyncOperation oper = additive ? Application.LoadLevelAdditiveAsync(level) : Application.LoadLevelAsync(level); #else AsyncOperation oper = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(level, additive ? LoadSceneMode.Additive : LoadSceneMode.Single); #endif OnProgress.Dispatch(oper.progress); while (!oper.isDone) { yield return(new WaitForFixedUpdate()); OnProgress.Dispatch(oper.progress); loadingScreen.OnProgress(oper.progress); } Resources.UnloadUnusedAssets(); OnLoadEnd.Dispatch(); loadingScreen.Hide(); }
private void OnFFMpegOutput(Process sender, DataReceivedEventArgs e, ref FFMpegProgressData data) { if (e.Data == null) { return; } //Debug.WriteLine("data: " + e.Data); //LogDebug(e.Data); Match m = DurationR.Match(e.Data); if (m.Success) { Util.TimeSpanLargeTryParse(m.Groups[1].Value, out TimeSpan time); data.Duration = time; } Match t = TimeR.Match(e.Data); if (t.Success) { Util.TimeSpanLargeTryParse(t.Groups[1].Value, out TimeSpan time); data.Time = time; OnProgress?.Invoke(this, new ProgressEventArgs(time.Ticks, data.Duration.Ticks, "f", data.StartTime)); } else if (!m.Success) { LogDebug(e.Data); } }
public XDocument Run(XDocument src) { var dst = new XDocument(src); var nsSys = XNamespace.Get(@"http://schemas.microsoft.com/winfx/2006/xaml"); int count = 0; foreach (XElement element in dst.Root.Descendants()) { OnProgress?.Invoke(count); count++; XAttribute attrKey = element.Attributes().FirstOrDefault(attr => attr.Name == nsSys.GetName("Key")); if (attrKey == null) { continue; } if (attrKey.Value.Contains("ResourceString") == false) { continue; } string translated = TranslateMsg(element.Value); element.Value = translated.EscapeXaml(); } OnProgress?.Invoke(count); return(dst); }
private void SendData() { if (!IsRunning) { Started = false; Done = false; return; } OnProgress?.Invoke(this, EventArgs.Empty); int chunkSize = Math.Min(256, Size - Position); byte[] chunk = new byte[chunkSize]; Array.Copy(data, Position, chunk, 0, chunkSize); byte hash = 0; foreach (byte b in chunk) { hash ^= b; } Drone.SendPacket(new PacketDataOTA(chunkSize, hash, chunk), true, (s, p) => { Position += chunkSize; if (Position >= Size) { Drone.SendPacket(new PacketEndOTA(false), true); Done = true; return; } SendData(); }); }
private void ReportProgress(TrackFile file) { _uiDispatcher.BeginInvoke(new Action(() => { OnProgress?.Invoke(file, 1, _files.Count); })); }
void Update() { m_CurrentTime += Time.deltaTime; if (!m_AlreadyTriggered) { Progress = Mathf.FloorToInt(m_CurrentTime); } if (m_CurrentTime >= m_Time) { ConditionMet(); m_CurrentTime -= m_Time; } else { if (m_PreviousProgress != Progress) { OnProgress?.Invoke(); } } m_PreviousProgress = Progress; }
protected void ProgressChanged(int current, int total, float progress) { if (OnProgress != null) { OnProgress.Invoke(current, total, progress); } }
public void Load() { OriginImages = new List<SKBitmap>(); for(var i = 0; i < Paths.Length; i++) { var path = Paths[i]; SKBitmap bitmap = null; using (var ms = new MemoryStream()) { using (var fs = new FileStream(path, FileMode.Open)) { fs.CopyTo(ms); ms.Flush(); fs.Close(); } ms.Position = 0; bitmap = SKBitmap.Decode(ms); OriginImages.Add(bitmap); OnProgress?.Invoke((double)(i + 1) / Paths.Length); } } PostProcess(); }
private void OnProgressionEvent(object sender, CfSaveEventArgs e) { if (sender is CfCabinet cabinet) { OnProgress?.Invoke(this, CabProgressionEventArgs.NewProgress(cabinet.CabPath, e.RelativePathInCab, Math.Round(e.TotalBytesDone / (double)e.TotalBytesToProcess * 100, 2))); } }
public void ReportProgress(int percentProgress) { lock (_lock) { OnProgress?.Invoke(this, new ProgressChangedEventArgs(percentProgress, null)); } }
// progress private async void Progress(object sender, DownloadProgressChangedEventArgs e) { double total = double.Parse(((WebClient)sender).ResponseHeaders["Content-Length"]); var percent = (int)((e.BytesReceived / total) * 100); OnProgress.Invoke(this, new ProgressEventArgs(percent)); }
private void pingCompleted(object sender, PingCompletedEventArgs e) { if (!Global.IPAddresses.isCompleted) { lock (_lockObject) { Global.IPAddresses.Increment(); Ping ping = (Ping)sender; ping.SendPingAsync(Global.IPAddresses.Current, Timeout); } } else { OnComplete?.Invoke(); (sender as Ping).Dispose(); } if (e.Reply.Status == IPStatus.Success) { Insert(e.Reply); lock (_lockObject) { Global.IPAddresses.RepliedCount++; } OnPingReply?.Invoke(e.Reply, Global.IPAddresses.RepliedCount); } OnProgress?.Invoke(Global.IPAddresses.Current, Global.IPAddresses.PingedCount); }
private IEnumerator loadWithResources( string[] bundle_names, OnPrefabGameObject cb, OnProgress op) { op(0, false); yield return(new WaitForEndOfFrame()); float total = bundle_names.Length; float process = 0; int len = bundle_names.Length; for (int i = 0; i < len; ++i) { GameObject obj = Resources.Load <GameObject>(bundle_names[i]); if (obj == null) { cb(null, bundle_names[i]); } else { cb(Instantiate(obj), bundle_names[i]); } op((++process) / total, false); yield return(new WaitForEndOfFrame()); } op(1, true); }
private void LogProgress(string message, int percent) { if (OnProgress != null) { OnProgress.Invoke(this, new NotificationMessage(message, percent)); } }
public void Execute(ParamsMergeModel[] fileMerge, string destinyDirectory, HeaderAction selectedHeaderAction) { if (fileMerge.Length <= 0) { return; } _destinyDirectory = destinyDirectory; _headerAction = selectedHeaderAction; _fileMerge = fileMerge; using (var mainWorkbook = new XLWorkbook(XLEventTracking.Disabled)) //new Workbook { var mainWorksheet = mainWorkbook.Worksheets.Add("Main"); for (_indexFile = 0; _indexFile < _fileMerge.Length; _indexFile++) // Loop in files { if (_cancel) { return; } using (var workBookFile = new XLWorkbook(_fileMerge[_indexFile].GetPath(), XLEventTracking.Disabled)) // Load from file { OnLog?.Invoke(this, new LogArgs(_fileMerge[_indexFile].FileName, EventLog.ReadFile)); OnProgress?.Invoke(this, new ProgressArgs(_indexFile + 1)); for (_indexSheet = 0; _indexSheet < workBookFile.Worksheets.Count; _indexSheet++) // Loop in sheets { if (_cancel) { return; } var worksheet = workBookFile.Worksheets.Worksheet(_indexSheet + 1); OnLog?.Invoke(this, new LogArgs(worksheet.Name, EventLog.ReadSheet)); if (_fileMerge[_indexFile].SeparatorCSV == null) { if (LoadFromWorksheet(worksheet, out IXLRange ragenUsed)) { mainWorksheet.Cell($"A{GetRowCount(mainWorksheet)}").Value = ragenUsed; } } else { if (LoadFromWorksheet(worksheet, out IList <string[]> list)) { mainWorksheet.Cell($"A{GetRowCount(mainWorksheet)}").Value = list; } } } } SaveFile(mainWorkbook); } } }
public void UpdateProgress(IProgress prog) { long total = 0; long value = 0; lock (tasks) { if (!tasks.ContainsKey(prog.Task)) { tasks.Add(prog.Task, prog); } else { tasks[prog.Task] = prog; } total = tasks.Values.Select(x => x.Total).Sum(); value = tasks.Values.Select(x => x.Value).Sum(); if (prog.Percentage == 1f) { tasks.Remove(prog.Task); } } progress.UpdateProgress(value, total, prog.Message); OnProgress?.Invoke(progress); }
/// <summary> /// Generates .apsimx files for each simulation in a runner. /// Returns any exceptions thrown. /// </summary> /// <param name="runner">A runner containing a set of simulations.</param> /// <param name="path">Path which the files will be saved to.</param> /// <param name="progressCallBack">Invoked when the method needs to indicate progress.</param> /// <returns>null for success or a list of exceptions.</returns> public static List <Exception> Generate(Runner runner, string path, OnProgress progressCallBack) { List <Exception> errors = null; if (runner.TotalNumberOfSimulations > 0) { Directory.CreateDirectory(path); int i = 0; foreach (var simulation in runner.Simulations()) { try { string st = FileFormat.WriteToString(simulation); File.WriteAllText(Path.Combine(path, simulation.Name + ".apsimx"), st); } catch (Exception err) { if (errors == null) { errors = new List <Exception>(); } errors.Add(err); } i++; progressCallBack?.Invoke(100 * i / runner.TotalNumberOfSimulations); } } return(errors); }
private void _Restore() { string root = Info.CurrentGamePath; Console.WriteLine($"STEP: RESTORE @ {root}"); OnProgress?.Invoke(Status.Restore, 0f); GameModInfo.ModBackup[] backups = Info.Backups; for (int i = 0; i < backups.Length; i++) { OnProgress?.Invoke(Status.Restore, (i + 1) / (float)backups.Length); GameModInfo.ModBackup backup = backups[i]; string from = Path.Combine(root, backup.From); string to = Path.Combine(root, backup.To); if (!File.Exists(to)) { Console.WriteLine($"File not found, skipping: {backup.From}"); continue; } Console.WriteLine($"{backup.From} <- {backup.To}"); string dir = Path.GetDirectoryName(from); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.Copy(to, from, true); } OnProgress?.Invoke(Status.Restore, 1f); }
private void CabManagerOnProgress(object sender, ICabProgressionEventArgs e) { if (e.EventType == CabEventType.GlobalProgression) { OnProgress?.Invoke(this, ArchiverEventArgs.NewProgress(e.CabPath, e.RelativePathInCab, e.PercentageDone)); } }
public void ReportProgress(int percentProgress, object userState) { lock (_lock) { OnProgress?.Invoke(this, new ProgressChangedEventArgs(percentProgress, userState)); } }
private void SafeProgressUpdate(int percent) { if (OnProgress != null) { OnProgress.Invoke(percent * 0.01f); } }
public ICommonResults Execute(IEnumerable <IFileSource> fileSources) { var list = fileSources.ToList(); _totalCurrent = 0; _totalSteps = 2; _localSteps = list.Count + 1; var results = new List <IProcessingResult>(); OnProgress?.Invoke(BuildProgress(_localSteps, "Поиск обращений к пропиетарным СУБД")); // поиск строк подключения FindConnectionStrings(list, results); _totalCurrent++; // поиск пространств имен FindNamespaces(list, results); _totalCurrent++; OnProgress?.Invoke(BuildProgress(_localSteps, "Поиск обращений к пропиетарным СУБД завершен")); return(new DatabaseHeuristicsReport(list) { Results = results }); }
private void InternalProgress(object stateObject) { AlBackgroundWorkProgress <TProgress> state = (AlBackgroundWorkProgress <TProgress>)stateObject; try { if (state.Finished) { WorkFinished?.Invoke(state.Result.Exception); } else { OnProgress?.Invoke(state.Percentage, state.Progress); } } catch (Exception ex) { ThrowUnhandledException(ex); } if (state.Finished) { NotifyOnAfterEnd(); task = null; } }
public override async Task Execute() { var state = GetLastMigrationState(); var migratedDocumentsOrAttachments = false; if (OperateOnTypes.HasFlag(DatabaseItemType.Documents)) { await MigrateDocuments(state?.LastDocsEtag ?? LastEtagsInfo.EtagEmpty); migratedDocumentsOrAttachments = true; } if (OperateOnTypes.HasFlag(DatabaseItemType.LegacyAttachments)) { await MigrateAttachments(state?.LastAttachmentsEtag ?? LastEtagsInfo.EtagEmpty); migratedDocumentsOrAttachments = true; } if (migratedDocumentsOrAttachments) { Result.Documents.Processed = true; OnProgress.Invoke(Result.Progress); await SaveLastOperationState(GenerateLastEtagsInfo()); } if (OperateOnTypes.HasFlag(DatabaseItemType.Indexes)) { await MigrateIndexes(); } DatabaseSmuggler.EnsureProcessed(Result); }
private void SafeProgress(float progress) { if (OnProgress != null) { OnProgress.Invoke(progress); } }
/// <inheritdoc cref="IArchiver.ArchiveFileSet"/> public int ArchiveFileSet(IEnumerable <IFileToArchive> filesToArchiveIn) { if (filesToArchiveIn == null) { return(0); } var fileToArchive = filesToArchiveIn.ToList(); fileToArchive.ForEach(f => f.Processed = false); int totalFiles = fileToArchive.Count; int totalFilesDone = 0; try { foreach (var file in fileToArchive) { _cancelToken?.ThrowIfCancellationRequested(); if (!File.Exists(file.SourcePath)) { continue; } ConvertFile(file.SourcePath, _encode, Path.Combine(file.ArchivePath ?? "", file.PathInArchive)); totalFilesDone++; file.Processed = true; OnProgress?.Invoke(this, ArchiverEventArgs.NewProgress(file.ArchivePath, file.PathInArchive, Math.Round(totalFilesDone / (double)totalFiles * 100, 2))); } } catch (OperationCanceledException) { throw; } catch (Exception e) { throw new ArchiverException($"Failed to archive. {e.Message}", e); } return(totalFilesDone); }
public static void AsyncCacheOrDownload(string url, ResultCallback callback, OnProgress progress, int version = 0) { Job job = new Job(url, HttpMethod.CACHEORDOWNLOAD, callback, progress, version, 0); int queueIndex = UnityEngine.Random.Range(0, _singleton.Length - 1); _singleton[queueIndex].Enqueue(job); }
private void OnProgressionEvent(object sender, ProLibrarySaveEventArgs e) { if (sender is ProLibrary library) { OnProgress?.Invoke(this, ArchiverEventArgs.NewProgress(library.FilePath, e.RelativePathInPl, Math.Round(e.TotalBytesDone / (double)e.TotalBytesToProcess * 100, 2))); } }
public void SetProgress(int currentIndex) { if (OnProgress != null) { OnProgress.Invoke(this, new EasyActionProgressEventArgs(MaximumItems, currentIndex)); } }
public async Task AudioConvert(AudioConversionItem fileToConvert, CancellationToken cancelToken) { var info = await GetInfo(fileToConvert.InputFile.FullName); IAudioStream audioStream = info.AudioStreams.FirstOrDefault() ?.SetCodec(AudioCodec.libvorbis) ?.SetSampleRate(fileToConvert.SampleRate); if (audioStream.Bitrate > fileToConvert.Bitrate) { audioStream = audioStream.SetBitrate(fileToConvert.Bitrate); } var conversion = FFmpeg.Conversions.New() .AddStream(audioStream) .SetOutput(fileToConvert.OutputPath); if (File.Exists(fileToConvert.OutputPath)) { File.Delete(fileToConvert.OutputPath); } conversion.OnProgress += (sender, args) => { OnProgress?.Invoke(this, fileToConvert, args); }; var result = await conversion.Start(cancelToken); OnConversionDone?.Invoke(this, fileToConvert, result); }
public override Stream Read(CloudFile cloudFile, OnProgress onProgress) { if (onProgress != null) { onProgress(cloudFile, ProcessTypes.Download, 0, cloudFile.Size); } var result = connector.Read(cloudFile, (pos, size) => { if (onProgress != null) { onProgress(cloudFile, ProcessTypes.Download, pos, size); } }); if (onProgress != null) { onProgress(cloudFile, ProcessTypes.Download, cloudFile.Size, cloudFile.Size); } return result; }
public Stream Read(CloudFile cloudFile, OnProgress onProgress) { if (cloudFile.Format == CloudFileFormat.Original) { return provider.Read(cloudFile, onProgress); } else { Stream stream = provider.Read(cloudFile, onProgress); using (var decoder = new SevenZip.SevenZipExtractor(stream, password)) { if (!decoder.Check()) { return stream; } else { Stream result = new MemoryStream(); if (decoder.FilesCount != 1) { throw new SevenZipProviderException("Cannot extract 7z package which contains no file or more than 1 file."); } decoder.Extracting += new EventHandler<ProgressEventArgs>( (o, p) => { if (onProgress != null) { onProgress(cloudFile, ProcessTypes.Decompress, (p.PercentDone * stream.Length), stream.Length); } }); decoder.ExtractFile(0, result); stream.Close(); result.Position = 0; return result; } } } }
public abstract Stream Read(CloudFile cloudFile, OnProgress onProgress);
/** on progress delegate will be called when full quality image is loading */ public void SetOnProgressDelegate(OnProgress p) { onProgress = p; }
public Texture load(string resource,OnLoadTexture onLoad,OnProgress progress=null, OnProgress error=null) { throw new NotImplementedException(); }
public Stream Read(CloudFile cloudFile, OnProgress onProgress) { string filePath = Path.Combine(this.rootPath, cloudFile.FullName().TrimStart('/')); var result = new FileStream(filePath, FileMode.Open, FileAccess.Read); cloudFile.Fingerprint = HashHelper.MD5(result); result.Position = 0; return result; }
public void Write(CloudFile cloudFile, Stream stream, OnProgress onProgress) { var path = Path.Combine(this.rootPath, cloudFile.FullName()); string directory = Path.GetDirectoryName(path); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } using (FileStream targetFileStream = new FileStream(path, FileMode.OpenOrCreate)) { stream.CopyTo(targetFileStream); } File.SetLastWriteTime(path, cloudFile.Timestamp); }
public void Write(CloudFile cloudFile, Stream stream, OnProgress onProgress = null) { PropertyParser.FormatProperties(cloudFile); var sameFile = cache.GetFileByFingerprint(cloudFile.Fingerprint); if (sameFile == null && !string.IsNullOrEmpty(cloudFile.MD5)) { sameFile = cache.GetFileByFingerprint(cloudFile.MD5); } if (sameFile != null) { logger.InfoFormat("Find same file, using copy instead of write. {0}", cloudFile.FullUniqueName()); Copy(sameFile, cloudFile); } else { RealWrite(cloudFile, stream, onProgress); } cache.AddItem(cloudFile); }
protected abstract void RealWrite(CloudFile cloudFile, Stream stream, OnProgress onProgress);
protected override void RealWrite(CloudFile cloudFile, Stream stream, OnProgress onProgress) { if (onProgress != null) { onProgress(cloudFile, ProcessTypes.Upload, 0, stream.Length); } connector.Write(cloudFile, stream, () => { if (onProgress != null) { onProgress(cloudFile, ProcessTypes.Upload, stream.Position, stream.Length); } }); if (onProgress != null) { onProgress(cloudFile, ProcessTypes.Upload, stream.Length, stream.Length); } }
public void Write(CloudFile cloudFile, Stream stream, OnProgress onProgress) { logger.DebugFormat("7zip, start writing [{0}]", cloudFile.FullName()); cloudFile.Format = CloudFileFormat.SevenZip; //cloudFile.Fingerprint = HashHelper.MD5(cloudFile.Fingerprint + password); stream.Position = 0; // set the name into the package Dictionary<String, Stream> dir = new Dictionary<string, Stream>(); dir[cloudFile.Name] = stream; // drive low level provider to write data using (MemoryStream compressedStream = new MemoryStream()) { SevenZipCompressor compressor = new SevenZipCompressor(); compressor.Compressing += new EventHandler<ProgressEventArgs>( (o, p) => { onProgress(cloudFile, ProcessTypes.Compress, (p.PercentDone * stream.Length / 100), stream.Length); logger.InfoFormat("Compressing [{0}], [{1}% of {2}MB]", cloudFile.Name, p.PercentDone, (int)(stream.Length / 1024 / 1024)); }); compressor.CompressStreamDictionary(dir, compressedStream, password); compressedStream.Position = 0; cloudFile.MD5 = cloudFile.Fingerprint; cloudFile.Fingerprint = HashHelper.MD5(cloudFile.Fingerprint+password); provider.Write(cloudFile, compressedStream, onProgress); } logger.DebugFormat("7zip, finish writing [{0}]", cloudFile.FullName()); }
public override Stream Read(CloudFile cloudFile, OnProgress onProgress) { string filePath = Path.Combine(this.rootPath, cloudFile.FullUniqueName()); return new FileStream(filePath, FileMode.Open, FileAccess.Read); }