public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace) { SelectionData state = null; SegmentedList <HistoryMemento> actions = new SegmentedList <HistoryMemento>(); if (!historyWorkspace.Selection.IsEmpty) { state = historyWorkspace.Selection.Save(); HistoryMemento memento3 = new DeselectFunction().Execute(historyWorkspace); actions.Add(memento3); } ReplaceDocumentHistoryMemento item = new ReplaceDocumentHistoryMemento(null, null, historyWorkspace); actions.Add(item); CompoundHistoryMemento memento2 = new CompoundHistoryMemento(StaticName, PdnResources.GetImageResource("Icons.MenuImageFlattenIcon.png"), actions); Document document = RetryManager.RunMemorySensitiveOperation <Document>(() => historyWorkspace.Document.Flatten()); base.EnterCriticalRegion(); historyWorkspace.Document = document; if (state != null) { SelectionHistoryMemento newHA = new SelectionHistoryMemento(null, null, historyWorkspace); historyWorkspace.Selection.Restore(state); memento2.AddMemento(newHA); } return(memento2); }
public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace) { GeometryList cachedClippingMask = historyWorkspace.Selection.GetCachedClippingMask(); if (historyWorkspace.Selection.IsEmpty || (cachedClippingMask.Bounds.Area < 1.0)) { return(null); } Document document = historyWorkspace.Document; List <HistoryMemento> mementos = new List <HistoryMemento>(document.Layers.Count); RectInt32 b = cachedClippingMask.Bounds.GetInt32Bound(1E-05); RectInt32 sourceRect = RectInt32.Intersect(document.Bounds(), b); Document document2 = new Document(sourceRect.Width, sourceRect.Height); document2.ReplaceMetadataFrom(document); RectInt32 rect = new RectInt32(0, 0, sourceRect.Width, sourceRect.Height); IRenderer <ColorAlpha8> cachedClippingMaskRenderer = historyWorkspace.Selection.GetCachedClippingMaskRenderer(historyWorkspace.ToolSettings.Selection.RenderingQuality.Value); IRenderer <ColorAlpha8> newClipMaskRenderer = new ClippedRenderer <ColorAlpha8>(cachedClippingMaskRenderer, sourceRect); SelectionHistoryMemento item = new SelectionHistoryMemento(null, null, historyWorkspace); mementos.Add(item); base.EnterCriticalRegion(); int count = document.Layers.Count; while (document.Layers.Count > 0) { BitmapLayer layer = (BitmapLayer)document.Layers[0]; Surface croppedSurface = layer.Surface.CreateWindow(sourceRect); BitmapLayer newLayer = RetryManager.RunMemorySensitiveOperation <BitmapLayer>(() => new BitmapLayer(croppedSurface)); newLayer.LoadProperties(layer.SaveProperties()); HistoryMemento deleteLayerMemento = new DeleteLayerFunction(0).Execute(historyWorkspace); mementos.Add(deleteLayerMemento); Task task = Task.Factory.StartNew(delegate { deleteLayerMemento.Flush(); }, TaskCreationOptions.LongRunning); Parallel.ForEach <RectInt32>(rect.GetTiles(TilingStrategy.Tiles, 7), delegate(RectInt32 newTileRect) { ISurface <ColorBgra> surface = newLayer.Surface.CreateWindow(newTileRect); IRenderer <ColorAlpha8> mask = new ClippedRenderer <ColorAlpha8>(newClipMaskRenderer, newTileRect); surface.MultiplyAlphaChannel(mask); }); document2.Layers.Add(newLayer); task.Wait(); if (document2.Layers.Count > count) { ExceptionUtil.ThrowInternalErrorException("newDocument.Layers.Count > oldLayerCount"); } } ReplaceDocumentHistoryMemento memento2 = new ReplaceDocumentHistoryMemento(null, null, historyWorkspace); mementos.Add(memento2); historyWorkspace.Document = document2; return(HistoryMemento.Combine(HistoryMementoName, HistoryMementoImage, mementos)); }
public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace) { BitmapLayer layer = RetryManager.RunMemorySensitiveOperation <BitmapLayer>(() => new BitmapLayer(historyWorkspace.Document.Width, historyWorkspace.Document.Height)); string format = PdnResources.GetString("AddNewBlankLayer.LayerName.Format"); layer.Name = string.Format(format, (1 + historyWorkspace.Document.Layers.Count).ToString()); int layerIndex = historyWorkspace.ActiveLayerIndex + 1; NewLayerHistoryMemento memento = new NewLayerHistoryMemento(PdnResources.GetString("AddNewBlankLayer.HistoryMementoName"), PdnResources.GetImageResource("Icons.MenuLayersAddNewLayerIcon.png"), historyWorkspace, layerIndex); base.EnterCriticalRegion(); historyWorkspace.Document.Layers.Insert(layerIndex, layer); return(memento); }
public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace) { if ((this.layerIndex < 0) || (this.layerIndex >= historyWorkspace.Document.Layers.Count)) { object[] objArray1 = new object[] { "layerIndex = ", this.layerIndex, ", expected [0, ", historyWorkspace.Document.Layers.Count, ")" }; throw new ArgumentOutOfRangeException(string.Concat(objArray1)); } Layer item = null; item = RetryManager.RunMemorySensitiveOperation <Layer>(() => (Layer)historyWorkspace.ActiveLayer.Clone()); item.IsBackground = false; int layerIndex = 1 + this.layerIndex; HistoryMemento memento = new NewLayerHistoryMemento(StaticName, StaticImage, historyWorkspace, layerIndex); base.EnterCriticalRegion(); historyWorkspace.Document.Layers.Insert(layerIndex, item); item.Invalidate(); return(memento); }
private BitmapLayer RotateLayer(BitmapLayer layer, RotateType rotationType, int width, int height) { Surface surface = RetryManager.RunMemorySensitiveOperation <Surface>(() => new Surface(width, height)); if (rotationType == RotateType.Rotate180) { Parallel.For(0, height, delegate(int y) { for (int j = 0; j < width; j++) { surface[j, y] = layer.Surface[(width - j) - 1, (height - y) - 1]; } }); } else if (rotationType == RotateType.CounterClockwise90) { Parallel.For(0, height, delegate(int y) { for (int k = 0; k < width; k++) { surface[k, y] = layer.Surface[(height - y) - 1, k]; } }); } else if (rotationType == RotateType.Clockwise90) { Parallel.For(0, height, delegate(int y) { for (int m = 0; m < width; m++) { surface[m, y] = layer.Surface[y, (width - 1) - m]; } }); } BitmapLayer layer2 = new BitmapLayer(surface, true); layer2.LoadProperties(layer.SaveProperties()); return(layer2); }
public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace) { GeometryList cachedClippingMask = historyWorkspace.Selection.GetCachedClippingMask(); if (historyWorkspace.Selection.IsEmpty || (cachedClippingMask.Bounds.Area < 1.0)) { return(null); } Document oldDocument = historyWorkspace.Document; RectInt32 b = cachedClippingMask.Bounds.GetInt32Bound(1E-05); RectInt32 oldClipBounds = RectInt32.Intersect(oldDocument.Bounds(), b); Document document = new Document(oldClipBounds.Width, oldClipBounds.Height); document.ReplaceMetadataFrom(oldDocument); RectInt32 newClipBounds = new RectInt32(0, 0, oldClipBounds.Width, oldClipBounds.Height); SelectionRenderingQuality quality = historyWorkspace.ToolSettings.Selection.RenderingQuality.Value; Result <IRenderer <ColorAlpha8> > oldClipMaskRendererLazy = historyWorkspace.Selection.GetCachedLazyClippingMaskRenderer(quality); LazyResult <ClippedRenderer <ColorAlpha8> > newClipMaskRendererLazy = LazyResult.New <ClippedRenderer <ColorAlpha8> >(() => new ClippedRenderer <ColorAlpha8>(oldClipMaskRendererLazy.Value, oldClipBounds), LazyThreadSafetyMode.ExecutionAndPublication, new VistaCriticalSection(0)); SelectionData selectionData = historyWorkspace.Selection.Save(); System.Threading.Tasks.Task <SelectionHistoryMemento> task = System.Threading.Tasks.Task.Factory.StartNew <SelectionHistoryMemento>(() => new SelectionHistoryMemento(null, null, historyWorkspace, selectionData)); System.Threading.Tasks.Task <ReplaceDocumentHistoryMemento> task2 = System.Threading.Tasks.Task.Factory.StartNew <ReplaceDocumentHistoryMemento>(() => new ReplaceDocumentHistoryMemento(null, null, historyWorkspace, oldDocument), TaskCreationOptions.LongRunning); int count = oldDocument.Layers.Count; System.Threading.Tasks.Task <BitmapLayer>[] items = new System.Threading.Tasks.Task <BitmapLayer> [count]; for (int i = 0; i < count; i++) { int iP = i; items[iP] = System.Threading.Tasks.Task.Factory.StartNew <BitmapLayer>(delegate { if (iP == 0) { newClipMaskRendererLazy.EnsureEvaluated(); } BitmapLayer layer = (BitmapLayer)oldDocument.Layers[iP]; Surface croppedSurface = layer.Surface.CreateWindow(oldClipBounds); BitmapLayer newLayer = RetryManager.RunMemorySensitiveOperation <BitmapLayer>(() => new BitmapLayer(croppedSurface)); newLayer.LoadProperties(layer.SaveProperties()); Parallel.ForEach <RectInt32>(newClipBounds.GetTiles(TilingStrategy.Tiles, 7), delegate(RectInt32 newTileRect) { ISurface <ColorBgra> surface = newLayer.Surface.CreateWindow(newTileRect); IRenderer <ColorAlpha8> mask = new ClippedRenderer <ColorAlpha8>(newClipMaskRendererLazy.Value, newTileRect); surface.MultiplyAlphaChannel(mask); }); return(newLayer); }); } List <TupleStruct <System.Threading.Tasks.Task, double> > collection = new List <TupleStruct <System.Threading.Tasks.Task, double> >(); collection.AddTuple <System.Threading.Tasks.Task, double>(task, 0.1); collection.AddTuple <System.Threading.Tasks.Task, double>(task2, 1.0); for (int j = 0; j < items.Length; j++) { collection.AddTuple <System.Threading.Tasks.Task, double>(items[j], 0.1); } PaintDotNet.Threading.Tasks.Task <Unit> task3 = historyWorkspace.TaskManager.CreateFrameworkTasksWrapper(collection); historyWorkspace.WaitWithProgress(task3, HistoryMementoImage, HistoryMementoName, PdnResources.GetString("Effects.ApplyingDialog.Description")); document.Layers.AddRange <Layer>(items.Select <System.Threading.Tasks.Task <BitmapLayer>, BitmapLayer>(t => t.Result)); SelectionHistoryMemento result = task.Result; ReplaceDocumentHistoryMemento memento2 = task2.Result; base.EnterCriticalRegion(); historyWorkspace.Document = document; HistoryMemento[] mementos = new HistoryMemento[] { result, memento2 }; return(HistoryMemento.Combine(HistoryMementoName, HistoryMementoImage, mementos)); }
private void RedrawOnBackgroundThread() { if (base.CheckAccess()) { ExceptionUtil.ThrowInvalidOperationException(); } if (this.redrawThreadFactory == null) { this.redrawThreadFactory = new Direct2DFactory(Direct2DFactoryType.MultiThreaded, DebugLevel.None); } if ((this.redrawThreadGeometryCache == null) || (this.redrawThreadGeometryCache.SelectionSnapshot != this.redrawRenderParams.SelectionSnapshot)) { DisposableUtil.Free <SelectionGeometryCache>(ref this.redrawThreadGeometryCache); this.redrawThreadGeometryCache = new SelectionGeometryCache(this.redrawThreadFactory, this.redrawRenderParams.SelectionSnapshot); } double scaleRatio = this.redrawRenderParams.ScaleRatio; PointDouble location = this.redrawRenderParams.ViewportCanvasBounds.Location; SizeDouble viewportSize = this.redrawRenderParams.ViewportSize; SizeInt32 num5 = SizeDouble.Ceiling(viewportSize); RectDouble b = RectDouble.Inflate(CanvasCoordinateConversions.ConvertExtentToViewport(CanvasCoordinateConversions.ConvertCanvasToExtent(this.redrawRenderParams.SelectionSnapshot.GeometryList.Value.Bounds, scaleRatio), scaleRatio, location), (double)this.outlineStrokeWidthPx, (double)this.outlineStrokeWidthPx); RectDouble a = new RectDouble(PointDouble.Zero, viewportSize); RectDouble renderViewportBounds = RectDouble.Intersect(a, b); RectInt32 viewportRect = renderViewportBounds.Int32Bound; RectDouble extentRect = CanvasCoordinateConversions.ConvertViewportToExtent(viewportRect, scaleRatio, location); RectDouble renderCanvasBounds = CanvasCoordinateConversions.ConvertExtentToCanvas(extentRect, scaleRatio); if (!viewportRect.HasPositiveArea) { base.SyncContext.Post((SendOrPostCallback)(_ => this.EndRedraw(renderViewportBounds, RectFloat.Zero, null, null))); } else { IBitmap <ColorAlpha8> interiorMask; float scale; PointFloat offset; Result <IGeometry> lazyGeometry; IBitmap <ColorAlpha8>[] dashedOutlineMasks; RectFloat maskSourceRect; SelectionSnapshot selectionSnapshot = this.redrawRenderParams.SelectionSnapshot; SelectionGeometryCache redrawThreadGeometryCache = this.redrawThreadGeometryCache; bool flag = this.redrawRenderParams.SelectionRenderingQuality == SelectionRenderingQuality.Aliased; if (!flag) { lazyGeometry = redrawThreadGeometryCache.Geometry; } else { bool flag3 = selectionSnapshot.IsRectilinear.Value; bool flag4 = selectionSnapshot.IsPixelated.Value; if (flag3 & flag4) { lazyGeometry = redrawThreadGeometryCache.Geometry; } else { lazyGeometry = redrawThreadGeometryCache.PixelatedGeometry; } } bool flag2 = !flag && this.redrawRenderParams.IsOutlineAntialiased; AntialiasMode antialiasMode = ((flag || !flag2) || selectionSnapshot.IsRectilinear.Value) ? AntialiasMode.Aliased : AntialiasMode.PerPrimitive; if (this.CanContinueRedrawing(null, null)) { scale = (float)this.redrawRenderParams.ScaleRatio; float x = -((float)renderCanvasBounds.X); float y = -((float)renderCanvasBounds.Y); offset = new PointFloat(x, y); interiorMask = BitmapAllocator.Alpha8.Allocate(viewportRect.Size, AllocationOptions.ZeroFillNotRequired); try { RetryManager.RunMemorySensitiveOperation(delegate { using (IDrawingContext context = DrawingContext.FromBitmap(this.redrawThreadFactory, interiorMask)) { context.Clear(null); IBrush interiorBrush = context.GetCachedOrCreateResource <IBrush>(whiteBrush); this.RenderSelection(context, scale, offset, this.redrawRenderParams, lazyGeometry, interiorBrush, null, null, antialiasMode); } }); } catch (OutOfMemoryException) { } if (this.CanContinueRedrawing(interiorMask, null)) { int num15; dashedOutlineMasks = new IBitmap <ColorAlpha8> [SelectionCanvasLayer.DashLength]; for (int i = 0; i < dashedOutlineMasks.Length; i = num15) { if ((!this.redrawRenderParams.IsOutlineAnimated && (i != 0)) && (i != (SelectionCanvasLayer.DashLength / 2))) { dashedOutlineMasks[i] = null; } else { dashedOutlineMasks[i] = BitmapAllocator.Alpha8.Allocate(viewportRect.Size, AllocationOptions.ZeroFillNotRequired); try { RetryManager.RunMemorySensitiveOperation(delegate { using (IDrawingContext context = DrawingContext.FromBitmap(this.redrawThreadFactory, dashedOutlineMasks[i])) { context.Clear(null); StrokeStyle resourceSource = SelectionCanvasLayer.GetDashedStrokeStyle(i); IStrokeStyle outlineStrokeStyle = context.GetCachedOrCreateResource <IStrokeStyle>(resourceSource); IBrush cachedOrCreateResource = context.GetCachedOrCreateResource <IBrush>(whiteBrush); this.RenderSelection(context, scale, offset, this.redrawRenderParams, lazyGeometry, null, cachedOrCreateResource, outlineStrokeStyle, antialiasMode); } }); } catch (OutOfMemoryException) { } if (!this.CanContinueRedrawing(interiorMask, dashedOutlineMasks)) { return; } } num15 = i + 1; } maskSourceRect = new RectFloat(PointFloat.Zero, interiorMask.Size); base.SyncContext.Post(_ => this.EndRedraw(renderCanvasBounds, maskSourceRect, interiorMask, dashedOutlineMasks), null); } } } }
public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace) { historyWorkspace.VerifyAccess(); BitmapLayer layer = (BitmapLayer)historyWorkspace.Document.Layers[this.layerIndex]; Surface layerSurface = layer.Surface; TileMathHelper tileMathHelper = new TileMathHelper(layerSurface.Width, layerSurface.Height, this.rendererTileEdgeLog2); TileMathHelper tileGroupMathHelper = new TileMathHelper(layerSurface.Width, layerSurface.Height, this.rendererTileEdgeLog2 + 3); HistoryMemento actionHM = null; ManualResetEvent taskFinishedEvent = new ManualResetEvent(false); ThreadTask <Unit> commitTask = historyWorkspace.TaskManager.StartNewThreadTask(delegate(Task task) { SegmentedList <RectInt32> list = tileGroupMathHelper.EnumerateTilesClippedToSourceRect(this.rendererClipRect).ToSegmentedList <RectInt32>(); ListUtil.FisherYatesShuffle <RectInt32>(list); ConcurrentQueue <ISurface <ColorBgra> > queue = new ConcurrentQueue <ISurface <ColorBgra> >(); ConcurrentQueue <RectInt32> changedTiles = new ConcurrentQueue <RectInt32>(); ConcurrentQueue <TupleStruct <RectInt32, ISurface <ColorBgra> > > changedTileGroups = new ConcurrentQueue <TupleStruct <RectInt32, ISurface <ColorBgra> > >(); double progressIncrement = 1.0 / ((double)Math.Max(1, list.Count)); task.Progress = 0.0; Work.ParallelForEach <RectInt32>(WaitType.Blocking, list, delegate(RectInt32 tileGroupRect) { ISurface <ColorBgra> dst = RetryManager.RunMemorySensitiveOperation <ISurfaceRef <ColorBgra> >(() => SurfaceAllocator.Bgra.Allocate <ColorBgra>(tileGroupRect.Size, AllocationOptions.ZeroFillNotRequired)); this.renderer.Render(dst, tileGroupRect.Location); bool flag = false; foreach (RectInt32 num in tileMathHelper.EnumerateTilesClippedToSourceRect(tileGroupRect)) { RectInt32 bounds = RectInt32.Offset(num, -tileGroupRect.Location); using (ISurface <ColorBgra> surface2 = layerSurface.CreateWindow(num)) { using (ISurface <ColorBgra> surface3 = dst.CreateWindow <ColorBgra>(bounds)) { if (!SurfaceBgraUtil.ArePixelsEqual(surface2, surface3)) { flag = true; changedTiles.Enqueue(num); } } } } if (flag) { changedTileGroups.Enqueue(TupleStruct.Create <RectInt32, ISurface <ColorBgra> >(tileGroupRect, dst)); } else { DisposableUtil.Free <ISurface <ColorBgra> >(ref dst); } task.IncrementProgressBy(progressIncrement); }, WorkItemQueuePriority.Normal, null); task.Progress = null; if (changedTiles.Count == 0) { actionHM = null; } else { SegmentedList <RectInt32> scans = new SegmentedList <RectInt32>(changedTiles.Count, 7); scans.AddRange(changedTiles); ScansHelpers.SortScansByTopLeft(scans); ScansHelpers.ConsolidateSortedScansInPlace(scans); actionHM = new BitmapHistoryMemento(this.historyMementoName, this.historyMementoImage, historyWorkspace, this.layerIndex, scans); this.EnterCriticalRegion(); Work.ParallelForEach <TupleStruct <RectInt32, ISurface <ColorBgra> > >(WaitType.Blocking, changedTileGroups, delegate(TupleStruct <RectInt32, ISurface <ColorBgra> > tileInfo) { using (ISurface <ColorBgra> surface = layerSurface.CreateWindow(tileInfo.Item1)) { tileInfo.Item2.Render(surface, PointInt32.Zero); } tileInfo.Item2.Dispose(); }, WorkItemQueuePriority.Normal, null); foreach (RectInt32 num in scans) { layer.Invalidate(num); } } }, ApartmentState.MTA); commitTask.ResultAsync <Unit>().Receive(delegate(Result <Unit> r) { taskFinishedEvent.Set(); }).Observe(); if (!taskFinishedEvent.WaitOne(this.delayUntilProgressDialogMs)) { string headerText = PdnResources.GetString("ApplyRendererToBitmapLayerHistoryFunction.ProgressDialog.HeaderText"); string headerTextFormat = PdnResources.GetString("ApplyRendererToBitmapLayerHistoryFunction.ProgressDialog.HeaderText.Format"); using (TaskProgressDialog progressDialog = new TaskProgressDialog()) { Action updateHeaderText = delegate { progressDialog.VerifyAccess(); if (!progressDialog.IsDisposed) { string text1; double?progress = commitTask.Progress; if (!progress.HasValue) { text1 = headerText; } else { text1 = string.Format(headerTextFormat, (progress.Value * 100.0).ToString("N0")); } progressDialog.HeaderText = text1; } }; progressDialog.Text = this.historyMementoName; progressDialog.Icon = this.historyMementoImage.Reference.ToIcon(); progressDialog.CloseOnFinished = true; progressDialog.ShowCancelButton = false; progressDialog.Task = commitTask; updateHeaderText(); commitTask.ProgressChanged += delegate(object s, ValueEventArgs <double?> e) { PdnSynchronizationContext.Instance.EnsurePosted(updateHeaderText); }; progressDialog.ShowDialog(historyWorkspace.Window); } } if (!commitTask.TaskResult.IsError) { return(actionHM); } if (commitTask.TaskResult.Error is OutOfMemoryException) { throw new OutOfMemoryException(null, commitTask.TaskResult.Error); } throw new AggregateException(null, commitTask.TaskResult.Error); }