private unsafe void RenderTileWorkItem(PointInt32 tileOffset) { IBitmap <ColorPbgra32> bitmap; bool isCancelled = false; bool flag = false; Exception error = null; isCancelled |= this.IsTileRenderingCancelled(tileOffset); if (isCancelled) { bitmap = null; } else { RectInt32 tileSourceRect = this.tileMathHelper.GetTileSourceRect(tileOffset); SizeInt32 tileBufferSize = this.GetTileBufferSize(tileOffset); bitmap = RetryManager.Eval <IBitmap <ColorPbgra32> >(3, () => BitmapAllocator.Pbgra32.Allocate(tileBufferSize, AllocationOptions.Default), delegate(Exception _) { CleanupManager.RequestCleanup(); Thread.Sleep(200); CleanupManager.WaitForPendingCleanup(); }, delegate(AggregateException ex) { throw new AggregateException($"could not allocate a bitmap of size {tileBufferSize.Width} x {tileBufferSize.Height}", ex).Flatten(); }); if (this.source != null) { try { isCancelled |= this.IsTileRenderingCancelled(tileOffset); if (!isCancelled) { using (IBitmapLock <ColorPbgra32> @lock = bitmap.Lock <ColorPbgra32>(BitmapLockOptions.ReadWrite)) { if (this.mipLevel == 0) { this.source.CopyPixels(new RectInt32?(tileSourceRect), @lock); RenderingKernels.ConvertBgra32ToPbgra32((uint *)@lock.Scan0, tileBufferSize.Width, tileBufferSize.Height, @lock.Stride); flag = true; } else { BitmapInterpolationMode linear; if (!this.isHighQuality) { linear = BitmapInterpolationMode.Linear; } else if (this.mipLevel == 1) { linear = BitmapInterpolationMode.Linear; } else { linear = BitmapInterpolationMode.Fant; } IImagingFactory instance = ImagingFactory.Instance; ICancellationToken cancelToken = CancellationTokenUtil.Create((Func <bool>)(() => (isCancelled | this.IsTileRenderingCancelled(tileOffset)))); int copyHeightLog2 = Math.Max(3, 7 - this.mipLevel); using (ClippedBitmapSource <ColorBgra32> source2 = new ClippedBitmapSource <ColorBgra32>(this.source, tileSourceRect)) { using (CancellableBitmapSource <ColorBgra32> source3 = new CancellableBitmapSource <ColorBgra32>(source2, r => this.tileMathHelper.EnumerateTilesClippedToSourceRect(r), null, cancelToken)) { using (IBitmapSource <ColorPbgra32> source4 = CreateBufferedTileScaler(instance, source3, tileBufferSize.Width, tileBufferSize.Height, linear)) { using (CancellableBitmapSource <ColorPbgra32> source5 = new CancellableBitmapSource <ColorPbgra32>(source4, r => TileRectSplitter(r, ((int)1) << copyHeightLog2), null, cancelToken)) { try { source5.CopyPixels <ColorPbgra32>(@lock); flag = true; } catch (OperationCanceledException exception2) { error = exception2; isCancelled = true; } catch (Exception exception3) { error = exception3; throw; } } } } } } isCancelled |= this.IsTileRenderingCancelled(tileOffset); if (isCancelled) { flag = false; } } if (!flag) { DisposableUtil.Free <IBitmap <ColorPbgra32> >(ref bitmap); } } } catch (OperationCanceledException exception4) { error = exception4; isCancelled = true; } catch (Exception exception5) { error = exception5; isCancelled |= this.IsTileRenderingCancelled(tileOffset); if (!isCancelled) { using (IDrawingContext context = DrawingContext.FromBitmap(bitmap, FactorySource.PerThread)) { context.Clear(new ColorRgba128Float?((ColorRgba128Float)Colors.White)); string text = exception5.ToString(); using (ISystemFonts fonts = new SystemFonts(true)) { TextLayout textLayout = UIText.CreateLayout(context, text, fonts.Caption, null, HotkeyRenderMode.Ignore, (double)bitmap.Size.Width, 65535.0); textLayout.FontSize *= 0.6; textLayout.WordWrapping = WordWrapping.Wrap; context.DrawTextLayout(PointDouble.Zero, textLayout, SolidColorBrushCache.Get((ColorRgba128Float)Colors.Black), DrawTextOptions.None); } } flag = true; } } } } isCancelled |= this.IsTileRenderingCancelled(tileOffset); if (isCancelled) { DisposableUtil.Free <IBitmap <ColorPbgra32> >(ref bitmap); } RenderedTileInfo info = new RenderedTileInfo(bitmap, !isCancelled && (bitmap > null), error); if (!this.tilesRenderedQueue.TryEnqueue(tileOffset, info)) { ExceptionUtil.ThrowInternalErrorException("Could not enqueue to this.tilesRenderedQueue"); } if (Interlocked.Exchange(ref this.isProcessTileRenderedQueueQueued, 1) == 0) { this.syncContext.Post(this.processTileRenderedQueueCallback); } }
internal void <CreateDeviceBitmap> b__25_1(Exception _) { CleanupManager.RequestCleanup(); Thread.Sleep(200); CleanupManager.WaitForPendingCleanup(); }
/// <summary> /// Processes the specified commands /// </summary> private void ProcessCommands(Object sender, DoWorkEventArgs e) { try { Int32 count = 0; Int32 total = this.commands.Entries.Count; foreach (Command command in this.commands.Entries) { if (command.Number > Globals.Settings.LatestCommand) { String data = this.ProcessArguments(command.Data); if (command.Action.ToLower() == "copy") { String[] args = data.Split(';'); if (Directory.Exists(args[0])) { FolderHelper.CopyFolder(args[0], args[1]); } else { if (File.Exists(args[0]) && args.Length == 3 && args[2] == "keep-old") { File.Copy(args[0], args[1], false); } else if (File.Exists(args[0])) { File.Copy(args[0], args[1], true); } } } else if (command.Action.ToLower() == "move") { String[] args = data.Split(';'); if (Directory.Exists(args[0])) { FolderHelper.CopyFolder(args[0], args[1]); Directory.Delete(args[0], true); } else if (File.Exists(args[0])) { File.Copy(args[0], args[1], true); File.Delete(args[0]); } } else if (command.Action.ToLower() == "delete") { if (Directory.Exists(data)) { Directory.Delete(data, true); } else if (File.Exists(data)) { File.Delete(data); } } else if (command.Action.ToLower() == "syntax") { CleanupManager.RevertConfiguration(false); } else if (command.Action.ToLower() == "create") { Directory.CreateDirectory(data); } } count++; Int32 percent = (100 * count) / total; this.worker.ReportProgress(percent); } e.Result = true; } catch (Exception ex) { e.Result = false; ErrorManager.AddToLog("Init failed.", ex); this.worker.CancelAsync(); } }
public static void HandleCharacterSelect(WorldSession session, ClientCharacterSelect characterSelect) { CharacterModel character = session.Characters.SingleOrDefault(c => c.Id == characterSelect.CharacterId); if (character == null) { session.EnqueueMessageEncrypted(new ServerCharacterSelectFail { Result = CharacterSelectResult.Failed }); return; } if (CleanupManager.HasPendingCleanup(session.Account)) { session.EnqueueMessageEncrypted(new ServerCharacterSelectFail { Result = CharacterSelectResult.FailedCharacterInWorld }); return; } session.Player = new Player(session, character); WorldEntry entry = GameTableManager.Instance.World.GetEntry(character.WorldId); if (entry == null) { throw new ArgumentOutOfRangeException(); } switch (entry.Type) { // housing map case 5: { // characters logging in to a housing map are returned to their own residence session.EnqueueEvent(new TaskGenericEvent <Residence>(ResidenceManager.Instance.GetResidence(session.Player.Name), residence => { if (residence == null) { residence = ResidenceManager.Instance.CreateResidence(session.Player); } ResidenceEntrance entrance = ResidenceManager.Instance.GetResidenceEntrance(residence); var mapInfo = new MapInfo(entrance.Entry, 0u, residence.Id); MapManager.Instance.AddToMap(session.Player, mapInfo, entrance.Position); })); break; } default: { var mapInfo = new MapInfo(entry); var vector3 = new Vector3(character.LocationX, character.LocationY, character.LocationZ); MapManager.Instance.AddToMap(session.Player, mapInfo, vector3); break; } } }
// Returns a dictionary of the database public async Task <ConcurrentDictionary <string, CacheDatabaseRecord> > Startup() { if (startupComplete) { throw new InvalidOperationException("Startup() can only be called once"); } startedAt = Stopwatch.GetTimestamp(); if (!Directory.Exists(databaseDir)) { Directory.CreateDirectory(databaseDir); } // Sort the log files numerically, since they are tick counts. var rawFiles = Directory.GetFiles(databaseDir, "*", SearchOption.TopDirectoryOnly); var orderedLogs = rawFiles.Select(path => { var filename = Path.GetFileNameWithoutExtension(path); return(long.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out long result) ? new Tuple <string, long>(path, result) : null); }) .Where(t => t != null) .OrderBy(t => t.Item2) .ToArray(); // Read in all the log files var openedFiles = new List <FileStream>(orderedLogs.Length); long openedLogFileBytes = 0; List <LogEntry>[] logSets; try { // Open all the input log files at once. We want to fail fast if there is a problem. var lastOpenPath = ""; try { foreach (var t in orderedLogs) { lastOpenPath = t.Item1; var fs = new FileStream(t.Item1, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan); openedFiles.Add(fs); openedLogFileBytes += CleanupManager.EstimateEntryBytesWithOverhead(fs.Length); } } catch (IOException ioException) { logger?.LogError(ioException, "Failed to open log file {Path} for reading in shard {ShardId}. Perhaps another process is still writing to the log?", lastOpenPath, shardId); throw; } // Open the write log file, even if we won't use it immediately. CreateWriteLog(startedAt); //Read all logs in logSets = await Task.WhenAll(openedFiles.Select(ReadLogEntries)); } finally { for (var ix = 0; ix < openedFiles.Count; ix++) { try { var stream = openedFiles[ix]; stream.Close(); stream.Dispose(); } catch (Exception e) { logger?.LogError(e, "Failed to close log file {Path}", orderedLogs[ix].Item1); } } } // Create dictionary from logs var totalEntryEst = logSets.Sum(set => set.Count); var dict = new ConcurrentDictionary <string, CacheDatabaseRecord>(Environment.ProcessorCount, totalEntryEst, StringComparer.Ordinal); foreach (var entry in logSets.SelectMany(l => l)) { if (entry.EntryType == LogEntryType.Delete) { if (!dict.TryRemove(entry.RelativePath, out var unused)) { logger?.LogWarning("Log entry deletion referred to nonexistent record: {Path}", entry.RelativePath); } } if (entry.EntryType == LogEntryType.Update) { if (!dict.ContainsKey(entry.RelativePath)) { logger?.LogWarning("Log entry update refers to non-existent record {Path}", entry.RelativePath); } dict[entry.RelativePath] = entry.ToRecord(); } if (entry.EntryType == LogEntryType.Create) { if (!dict.TryAdd(entry.RelativePath, entry.ToRecord())) { logger?.LogWarning("Log entry creation failed as record already exists {Path}", entry.RelativePath); } } } // Do consolidation if needed if (orderedLogs.Length >= options.MaxLogFilesPerShard) { //Write new file and delete old ones foreach (var record in dict.Values) { await WriteLogEntry(new LogEntry(LogEntryType.Create, record), false); } await writeLogStream.FlushAsync(); // Delete old logs foreach (var t in orderedLogs) { try { File.Delete(t.Item1); } catch (IOException ioException) { logger?.LogError(ioException, "Failed to delete log file {Path} after consolidation", t.Item1); } } } else { previousLogsBytes += openedLogFileBytes; diskBytes += dict.Values.Sum(r => r.DiskSize); } startupComplete = true; return(dict); }
private static Document ResizeDocument(DocumentWorkspace documentWorkspace, AnchorEdge initialAnchor, ColorBgra background, bool loadAndSaveMaintainAspect, bool saveAnchor) { Document document2; CleanupManager.RequestCleanup(); IWin32Window owner = documentWorkspace; Document document = documentWorkspace.Document; Size size = document.Size; using (CanvasSizeDialog dialog = new CanvasSizeDialog()) { bool flag; if (loadAndSaveMaintainAspect) { flag = AppSettings.Instance.Workspace.LastMaintainAspectRatioCS.Value; } else { flag = false; } dialog.OriginalSize = document.Size; dialog.OriginalDpuUnit = document.DpuUnit; dialog.OriginalDpu = document.DpuX; dialog.ImageWidth = size.Width; dialog.ImageHeight = size.Height; dialog.LayerCount = document.Layers.Count; dialog.AnchorEdge = initialAnchor; dialog.Units = dialog.OriginalDpuUnit; dialog.Resolution = document.DpuX; dialog.Units = AppSettings.Instance.Workspace.LastNonPixelUnits.Value; dialog.ConstrainToAspect = flag; DialogResult result = dialog.ShowDialog(owner); Size newSize = new Size(dialog.ImageWidth, dialog.ImageHeight); MeasurementUnit units = dialog.Units; double resolution = dialog.Resolution; if (result == DialogResult.Cancel) { return(null); } if (loadAndSaveMaintainAspect) { AppSettings.Instance.Workspace.LastMaintainAspectRatioCS.Value = dialog.ConstrainToAspect; } if (saveAnchor) { AppSettings.Instance.Workspace.LastCanvasSizeAnchorEdge.Value = dialog.AnchorEdge; } if (((newSize == document.Size) && (units == document.DpuUnit)) && (resolution == document.DpuX)) { document2 = null; } else { try { documentWorkspace.FlushTool(); CleanupManager.RequestCleanup(); Document document3 = ResizeDocument(document, newSize, dialog.AnchorEdge, background); document3.DpuUnit = units; document3.DpuX = resolution; document3.DpuY = resolution; document2 = document3; } catch (OutOfMemoryException exception) { ExceptionDialog.ShowErrorDialog(owner, PdnResources.GetString("CanvasSizeAction.ResizeDocument.OutOfMemory"), exception.ToString()); document2 = null; } catch (Exception) { document2 = null; } } } return(document2); }
public long GetDiskSize() { return(diskBytes + CleanupManager.EstimateEntryBytesWithOverhead(logBytes) + previousLogsBytes + directoryEntriesBytes); }
public MetaStore(MetaStoreOptions options, HybridCacheOptions cacheOptions, ILogger logger) { if (options.Shards <= 0 || options.Shards > 2048) { throw new ArgumentException("Shards must be between 1 and 2048"); } var pathBuilder = new HashBasedPathBuilder(cacheOptions.PhysicalCacheDir, cacheOptions.Subfolders, '/', ".jpg"); var directoryEntriesBytes = pathBuilder.GetDirectoryEntriesBytesTotal() + CleanupManager.DirectoryEntrySize(); var shardCount = options.Shards; shards = new Shard[shardCount]; for (var i = 0; i < shardCount; i++) { shards[i] = new Shard(i, options, Path.Combine(options.DatabaseDir, "db", i.ToString()), directoryEntriesBytes / shardCount, logger); } }
internal Shard(int shardId, MetaStoreOptions options, string databaseDir, long directoryEntriesBytes, ILogger logger) { this.shardId = shardId; this.logger = logger; writeLog = new WriteLog(shardId, databaseDir, options, directoryEntriesBytes + CleanupManager.DirectoryEntrySize(), logger); }
public override void PerformAction(AppWorkspace appWorkspace) { if (appWorkspace.CanSetActiveWorkspace) { try { SizeInt32? nullable; IPdnDataObject dataObject; MaskedSurface surface; try { using (new WaitCursorChanger(appWorkspace)) { CleanupManager.RequestCleanup(); dataObject = PdnClipboard.GetDataObject(); if (ClipboardUtil.IsClipboardImageMaybeAvailable(appWorkspace, dataObject)) { surface = ClipboardUtil.TryGetClipboardImage(appWorkspace, dataObject); if (surface != null) { nullable = new SizeInt32?(surface.GetCachedGeometryMaskScansBounds().Size); } else { nullable = null; } } else { surface = null; nullable = null; } } } catch (OutOfMemoryException exception) { ExceptionDialog.ShowErrorDialog(appWorkspace, PdnResources.GetString("PasteAction.Error.OutOfMemory"), exception); return; } catch (Exception exception2) { ExceptionDialog.ShowErrorDialog(appWorkspace, PdnResources.GetString("PasteAction.Error.TransferFromClipboard"), exception2); return; } if (!nullable.HasValue) { MessageBoxUtil.ErrorBox(appWorkspace, PdnResources.GetString("PasteInToNewImageAction.Error.NoClipboardImage")); } else { Type defaultToolType; SizeInt32 size = nullable.Value; Document document = null; if ((appWorkspace.ActiveDocumentWorkspace != null) && (appWorkspace.ActiveDocumentWorkspace.Tool != null)) { defaultToolType = appWorkspace.ActiveDocumentWorkspace.Tool.GetType(); } else { defaultToolType = appWorkspace.DefaultToolType; } using (new WaitCursorChanger(appWorkspace)) { document = new Document(size); DocumentWorkspace documentWorkspace = appWorkspace.AddNewDocumentWorkspace(); documentWorkspace.Document = document; documentWorkspace.History.PushNewMemento(new NullHistoryMemento(string.Empty, null)); PasteInToNewLayerAction action = new PasteInToNewLayerAction(documentWorkspace, dataObject, surface); if (action.PerformAction()) { using (new PushNullToolMode(documentWorkspace)) { documentWorkspace.Selection.Reset(); documentWorkspace.SetDocumentSaveOptions(null, null, null); documentWorkspace.History.ClearAll(); documentWorkspace.History.PushNewMemento(new NullHistoryMemento(PdnResources.GetString("Menu.Edit.PasteInToNewImage.Text"), PdnResources.GetImageResource("Icons.MenuEditPasteInToNewImageIcon.png"))); appWorkspace.ActiveDocumentWorkspace = documentWorkspace; } documentWorkspace.SetToolFromType(defaultToolType); } else { appWorkspace.RemoveDocumentWorkspace(documentWorkspace); document.Dispose(); } } } } catch (ExternalException exception3) { ExceptionDialog.ShowErrorDialog(appWorkspace, PdnResources.GetString("AcquireImageAction.Error.Clipboard.TransferError"), exception3); } catch (OutOfMemoryException exception4) { ExceptionDialog.ShowErrorDialog(appWorkspace, PdnResources.GetString("AcquireImageAction.Error.Clipboard.OutOfMemory"), exception4); } catch (ThreadStateException) { } } }
public bool PerformAction() { bool flag = true; if (!this.QueryCanPerformAction()) { return(false); } try { using (new WaitCursorChanger(this.documentWorkspace)) { IRenderer <ColorBgra> source = this.GetSource(); RectInt32 num = source.Bounds <ColorBgra>(); GeometryList cachedClippingMask = this.documentWorkspace.Selection.GetCachedClippingMask(); RectInt32 a = cachedClippingMask.Bounds.Int32Bound; IRenderer <ColorAlpha8> cachedClippingMaskRenderer = this.documentWorkspace.Selection.GetCachedClippingMaskRenderer(this.documentWorkspace.ToolSettings.Selection.RenderingQuality.Value); RectInt32 sourceRect = RectInt32.Intersect(a, source.Bounds <ColorBgra>()); IRenderer <ColorBgra> renderer3 = new ClippedRenderer <ColorBgra>(source, sourceRect); IRenderer <ColorAlpha8> alpha = new ClippedRenderer <ColorAlpha8>(cachedClippingMaskRenderer, sourceRect); IRenderer <ColorBgra> sourceRHS = new MultiplyAlphaChannelRendererBgra32(renderer3, alpha); IRenderer <ColorBgra> sourceLHS = new SolidColorRendererBgra(sourceRHS.Width, sourceRHS.Height, ColorBgra.White); IRenderer <ColorBgra> renderer = new BlendRendererBgra(sourceLHS, CompositionOps.Normal.Static, sourceRHS); if ((a.Width > 0) && (a.Height > 0)) { int num5 = 10; while (num5 >= 0) { try { try { using (Clipboard.Transaction transaction = Clipboard.Open(this.documentWorkspace)) { transaction.Empty(); using (MaskedSurface surface = MaskedSurface.CopyFrom(source, cachedClippingMask)) { transaction.AddManagedData(surface); using (Surface surface2 = surface.Surface.CreateWindow(new Rectangle(0, 0, a.Width, a.Height))) { sourceRHS.Parallelize <ColorBgra>(TilingStrategy.Tiles, 7, WorkItemQueuePriority.Normal).Render <ColorBgra>(surface2); using (Bitmap copyBitmap = surface2.CreateAliasedBitmap(true)) { transaction.AddRawNativeData("PNG", delegate(Stream dstStream) { copyBitmap.Save(dstStream, ImageFormat.Png); }); } renderer.Parallelize <ColorBgra>(TilingStrategy.Tiles, 7, WorkItemQueuePriority.Normal).Render <ColorBgra>(surface2); using (Bitmap bitmap = surface2.CreateAliasedBitmap(false)) { transaction.AddDibV5(bitmap); } } goto Label_0292; } } } catch (Exception exception) { if (num5 == 0) { flag = false; ExceptionDialog.ShowErrorDialog(this.documentWorkspace, PdnResources.GetString("CopyAction.Error.TransferToClipboard"), exception.ToString()); } else { CleanupManager.RequestCleanup(); CleanupManager.WaitForPendingCleanup(50); Thread.Sleep(50); } } continue; } finally { num5--; } } } } } catch (OutOfMemoryException exception2) { flag = false; ExceptionDialog.ShowErrorDialog(this.documentWorkspace, PdnResources.GetString("CopyAction.Error.OutOfMemory"), exception2.ToString()); } catch (Exception exception3) { flag = false; ExceptionDialog.ShowErrorDialog(this.documentWorkspace, PdnResources.GetString("CopyAction.Error.Generic"), exception3.ToString()); } Label_0292: CleanupManager.RequestCleanup(); return(flag); }