Exemple #1
0
        protected override void OnDeactivate()
        {
            base.OnDeactivate();

            pencilToolCursor?.Dispose();
            pencilToolCursor = null;

            if (mouseDown)
            {
                Point lastTracePoint = (Point)tracePoints[tracePoints.Count - 1];
                OnMouseUp(new MouseEventArgs(mouseButton, 0, lastTracePoint.X, lastTracePoint.Y, 0));
            }

            this.savedRects  = null;
            this.tracePoints = null;
            this.bitmapLayer = null;

            renderArgs?.Dispose();
            renderArgs = null;

            this.mouseDown = false;

            clipRegion?.Dispose();
            clipRegion = null;
        }
Exemple #2
0
        protected override void OnLift(MouseEventArgs e)
        {
            PdnGraphicsPath liftPath   = Selection.CreatePath();
            PdnRegion       liftRegion = Selection.CreateRegion();

            this.ourContext.LiftedPixels = new MaskedSurface(activeLayer.Surface, liftPath);

            HistoryMemento bitmapAction = new BitmapHistoryMemento(
                Name,
                Image,
                DocumentWorkspace,
                ActiveLayerIndex,
                this.ourContext.poLiftedPixelsGuid);

            this.currentHistoryMementos.Add(bitmapAction);

            // If the user is holding down the control key, we want to *copy* the pixels
            // and not "lift and erase"
            if ((ModifierKeys & Keys.Control) == Keys.None)
            {
                ColorBgra fill = AppEnvironment.SecondaryColor;
                fill.A = 0;
                UnaryPixelOp op = new UnaryPixelOps.Constant(fill);
                op.Apply(this.renderArgs.Surface, liftRegion);
            }

            liftRegion.Dispose();
            liftRegion = null;

            liftPath.Dispose();
            liftPath = null;
        }
        protected override void OnStylusUp(StylusEventArgs e)
        {
            base.OnStylusUp(e);

            Cursor = cursorMouseUp;

            if (mouseDown)
            {
                this.previewRenderer.Visible = true;
                mouseDown = false;

                if (this.savedRects.Count > 0)
                {
                    PdnRegion      saveMeRegion = Utility.RectanglesToRegion(this.savedRects.ToArray());
                    HistoryMemento ha           = new BitmapHistoryMemento(Name, Image, DocumentWorkspace,
                                                                           ActiveLayerIndex, saveMeRegion, this.ScratchSurface);
                    HistoryStack.PushNewMemento(ha);
                    saveMeRegion.Dispose();
                    this.savedRects.Clear();
                    this.ClearSavedMemory();
                }

                this.brush.Dispose();
                this.brush = null;
            }
        }
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            if (historyWorkspace.Selection.IsEmpty)
            {
                return(null);
            }
            else
            {
                SelectionHistoryMemento sha = new SelectionHistoryMemento(
                    StaticName,
                    StaticImage,
                    historyWorkspace);

                PdnRegion selectedRegion = historyWorkspace.Selection.CreateRegion();
                selectedRegion.Xor(historyWorkspace.Document.Bounds);

                PdnGraphicsPath invertedSelection = PdnGraphicsPath.FromRegion(selectedRegion);
                selectedRegion.Dispose();

                EnterCriticalRegion();
                historyWorkspace.Selection.PerformChanging();
                historyWorkspace.Selection.Reset();
                historyWorkspace.Selection.SetContinuation(invertedSelection, CombineMode.Xor, true);
                historyWorkspace.Selection.CommitContinuation();
                historyWorkspace.Selection.PerformChanged();

                return(sha);
            }
        }
Exemple #5
0
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);

            if (mouseDown)
            {
                OnMouseMove(e);
                mouseDown = false;

                if (savedRects.Count > 0)
                {
                    Rectangle[] savedScans   = this.savedRects.ToArray();
                    PdnRegion   saveMeRegion = Utility.RectanglesToRegion(savedScans);

                    HistoryMemento ha = new BitmapHistoryMemento(Name, Image, DocumentWorkspace,
                                                                 ActiveLayerIndex, saveMeRegion, ScratchSurface);

                    HistoryStack.PushNewMemento(ha);
                    saveMeRegion.Dispose();
                    this.savedRects.Clear();
                    ClearSavedMemory();
                }

                tracePoints = null;
            }
        }
Exemple #6
0
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            if (historyWorkspace.Selection.IsEmpty)
            {
                return(null);
            }

            PdnRegion   region           = historyWorkspace.Selection.CreateRegion();
            BitmapLayer layer            = ((BitmapLayer)historyWorkspace.ActiveLayer);
            PdnRegion   simplifiedRegion = Utility.SimplifyAndInflateRegion(region);

            HistoryMemento hm = new BitmapHistoryMemento(
                StaticName,
                StaticImage,
                historyWorkspace,
                historyWorkspace.ActiveLayerIndex,
                simplifiedRegion);

            EnterCriticalRegion();

            layer.Surface.Clear(region, this.fillColor);
            layer.Invalidate(simplifiedRegion);

            simplifiedRegion.Dispose();
            region.Dispose();

            return(hm);
        }
Exemple #7
0
        protected override void Drop()
        {
            RestoreSavedRegion();

            PdnRegion regionCopy = Selection.CreateRegion();

            using (PdnRegion simplifiedRegion = Utility.SimplifyAndInflateRegion(regionCopy,
                                                                                 Utility.DefaultSimplificationFactor, 2))
            {
                HistoryMemento bitmapAction2 = new BitmapHistoryMemento(Name, Image, DocumentWorkspace,
                                                                        ActiveLayerIndex, simplifiedRegion);

                bool oldHQ = this.fullQuality;
                this.fullQuality = true;
                Render(this.context.offset, true);
                this.fullQuality = oldHQ;
                this.currentHistoryMementos.Add(bitmapAction2);

                activeLayer.Invalidate(simplifiedRegion);
                Update();
            }

            regionCopy.Dispose();
            regionCopy = null;

            ContextHistoryMemento cha = new ContextHistoryMemento(this.DocumentWorkspace, this.ourContext, this.Name, this.Image);

            this.currentHistoryMementos.Add(cha);

            string        name;
            ImageResource image;

            if (didPaste)
            {
                name  = EnumLocalizer.EnumValueToLocalizedName(typeof(CommonAction), CommonAction.Paste);
                image = PdnResources.GetImageResource("Icons.MenuEditPasteIcon.png");
            }
            else
            {
                name  = this.Name;
                image = this.Image;
            }

            didPaste = false;

            SelectionHistoryMemento sha = new SelectionHistoryMemento(this.Name, this.Image, this.DocumentWorkspace);

            this.currentHistoryMementos.Add(sha);

            this.context.Dispose();
            this.context = new MoveToolContext();

            this.FlushHistoryMementos(PdnResources.GetString("MoveTool.HistoryMemento.DropPixels"));
        }
Exemple #8
0
        protected override void OnDeactivate()
        {
            base.OnDeactivate();

            if (mouseDown)
            {
                PointF lastPoint = (PointF)points[points.Count - 1];
                OnStylusUp(new StylusEventArgs(mouseButton, 0, lastPoint.X, lastPoint.Y, 0));
            }

            if (!this.shapeWasCommited)
            {
                CommitShape();
            }

            bitmapLayer = null;

            if (renderArgs != null)
            {
                renderArgs.Dispose();
                renderArgs = null;
            }

            if (outlineSaveRegion != null)
            {
                outlineSaveRegion.Dispose();
                outlineSaveRegion = null;
            }

            if (interiorSaveRegion != null)
            {
                interiorSaveRegion.Dispose();
                interiorSaveRegion = null;
            }

            points = null;
        }
Exemple #9
0
        protected override void OnMouseUp(MouseEventArgs e)
        {
            mouseUp = true;

            if (!mouseDownSettingCloneSource)
            {
                Cursor = cursorMouseUp;
            }

            if (IsMouseLeftDown(e))
            {
                this.rendererDst.Visible = true;

                if (savedRegion != null)
                {
                    //RestoreRegion(this.savedRegion);
                    ActiveLayer.Invalidate(this.savedRegion.GetBoundsInt());
                    savedRegion.Dispose();
                    savedRegion = null;
                    Update();
                }

                if (GetStaticData().takeFrom == Point.Empty || GetStaticData().lastMoved == Point.Empty)
                {
                    return;
                }

                if (historyRects.Count > 0)
                {
                    PdnRegion saveMeRegion;

                    Rectangle[] rectsRO;
                    int         rectsROLength;
                    this.historyRects.GetArrayReadOnly(out rectsRO, out rectsROLength);
                    saveMeRegion = Utility.RectanglesToRegion(rectsRO, 0, rectsROLength);

                    PdnRegion simplifiedRegion = Utility.SimplifyAndInflateRegion(saveMeRegion);
                    SaveRegion(simplifiedRegion, simplifiedRegion.GetBoundsInt());

                    historyRects = new Vector <Rectangle>();

                    HistoryMemento ha = new BitmapHistoryMemento(Name, Image, DocumentWorkspace, ActiveLayerIndex,
                                                                 simplifiedRegion, this.ScratchSurface);

                    HistoryStack.PushNewMemento(ha);
                    this.ClearSavedMemory();
                }
            }
        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            Point pos = new Point(e.X, e.Y);

            this.contiguous = ((ModifierKeys & Keys.Shift) == 0);

            if (Document.Bounds.Contains(pos))
            {
                base.OnMouseDown(e);

                PdnRegion currentRegion = Selection.CreateRegion();

                // See if the mouse click is valid
                if (!currentRegion.IsVisible(pos) && limitToSelection)
                {
                    currentRegion.Dispose();
                    currentRegion = null;
                    return;
                }

                // Set the current surface, color picked and color to draw
                Surface surface = ((BitmapLayer)ActiveLayer).Surface;

                IBitVector2D stencilBuffer = new BitVector2DSurfaceAdapter(this.ScratchSurface);

                Rectangle boundingBox;
                int       tolerance = (int)(AppEnvironment.Tolerance * AppEnvironment.Tolerance * 256);

                if (contiguous)
                {
                    FillStencilFromPoint(surface, stencilBuffer, pos, tolerance, out boundingBox, currentRegion, limitToSelection);
                }
                else
                {
                    FillStencilByColor(surface, stencilBuffer, surface[pos], tolerance, out boundingBox, currentRegion, limitToSelection);
                }

                Point[][] polygonSet = PdnGraphicsPath.PolygonSetFromStencil(stencilBuffer, boundingBox, 0, 0);
                OnFillRegionComputed(polygonSet);
            }

            base.OnMouseDown(e);
        }
Exemple #11
0
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (undoImage != null)
                    {
                        undoImage.Dispose();
                        undoImage = null;
                    }

                    if (savedRegion != null)
                    {
                        savedRegion.Dispose();
                        savedRegion = null;
                    }
                }

                base.Dispose(disposing);
            }
Exemple #12
0
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            if (this.layerIndex < 1 || this.layerIndex >= historyWorkspace.Document.Layers.Count)
            {
                throw new ArgumentException("layerIndex must be greater than or equal to 1, and a valid layer index. layerIndex=" +
                                            layerIndex + ", allowableRange=[0," + historyWorkspace.Document.Layers.Count + ")");
            }

            int       bottomLayerIndex = this.layerIndex - 1;
            Rectangle bounds           = historyWorkspace.Document.Bounds;
            PdnRegion region           = new PdnRegion(bounds);

            BitmapHistoryMemento bhm = new BitmapHistoryMemento(
                null,
                null,
                historyWorkspace,
                bottomLayerIndex,
                region);

            BitmapLayer topLayer    = (BitmapLayer)historyWorkspace.Document.Layers[this.layerIndex];
            BitmapLayer bottomLayer = (BitmapLayer)historyWorkspace.Document.Layers[bottomLayerIndex];
            RenderArgs  bottomRA    = new RenderArgs(bottomLayer.Surface);

            EnterCriticalRegion();

            topLayer.Render(bottomRA, region);
            bottomLayer.Invalidate();

            bottomRA.Dispose();
            bottomRA = null;

            region.Dispose();
            region = null;

            DeleteLayerFunction dlf  = new DeleteLayerFunction(this.layerIndex);
            HistoryMemento      dlhm = dlf.Execute(historyWorkspace);

            CompoundHistoryMemento chm = new CompoundHistoryMemento(StaticName, StaticImage, new HistoryMemento[] { bhm, dlhm });

            return(chm);
        }
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            if (this.layerIndex < 1 || this.layerIndex >= historyWorkspace.Document.Layers.Count)
            {
                throw new ArgumentException("layerIndex must be greater than or equal to 1, and a valid layer index. layerIndex=" + 
                    layerIndex + ", allowableRange=[0," + historyWorkspace.Document.Layers.Count + ")");
            }

            int bottomLayerIndex = this.layerIndex - 1;
            Rectangle bounds = historyWorkspace.Document.Bounds;
            PdnRegion region = new PdnRegion(bounds);

            BitmapHistoryMemento bhm = new BitmapHistoryMemento(
                null,
                null,
                historyWorkspace,
                bottomLayerIndex,
                region);

            BitmapLayer topLayer = (BitmapLayer)historyWorkspace.Document.Layers[this.layerIndex];
            BitmapLayer bottomLayer = (BitmapLayer)historyWorkspace.Document.Layers[bottomLayerIndex];
            RenderArgs bottomRA = new RenderArgs(bottomLayer.Surface);

            EnterCriticalRegion();

            topLayer.Render(bottomRA, region);
            bottomLayer.Invalidate();

            bottomRA.Dispose();
            bottomRA = null;

            region.Dispose();
            region = null;

            DeleteLayerFunction dlf = new DeleteLayerFunction(this.layerIndex);
            HistoryMemento dlhm = dlf.Execute(historyWorkspace);

            CompoundHistoryMemento chm = new CompoundHistoryMemento(StaticName, StaticImage, new HistoryMemento[] { bhm, dlhm });
            return chm;
        }
Exemple #14
0
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            if (historyWorkspace.Selection.IsEmpty)
            {
                return(null);
            }

            SelectionHistoryMemento shm = new SelectionHistoryMemento(string.Empty, null, historyWorkspace);

            PdnRegion region = historyWorkspace.Selection.CreateRegion();

            BitmapLayer layer            = ((BitmapLayer)historyWorkspace.ActiveLayer);
            PdnRegion   simplifiedRegion = Utility.SimplifyAndInflateRegion(region);

            HistoryMemento hm = new BitmapHistoryMemento(
                null,
                null,
                historyWorkspace,
                historyWorkspace.ActiveLayerIndex,
                simplifiedRegion);

            HistoryMemento chm = new CompoundHistoryMemento(
                StaticName,
                StaticImage,
                new HistoryMemento[] { shm, hm });

            EnterCriticalRegion();

            layer.Surface.Clear(region, ColorBgra.FromBgra(255, 255, 255, 0));

            layer.Invalidate(simplifiedRegion);
            historyWorkspace.Document.Invalidate(simplifiedRegion);
            simplifiedRegion.Dispose();
            region.Dispose();
            historyWorkspace.Selection.Reset();

            return(chm);
        }
Exemple #15
0
        protected void Render(Point newOffset, bool useNewOffset, bool saveRegion)
        {
            Rectangle saveBounds       = Selection.GetBounds();
            PdnRegion selectedRegion   = Selection.CreateRegion();
            PdnRegion simplifiedRegion = Utility.SimplifyAndInflateRegion(selectedRegion);

            if (saveRegion)
            {
                SaveRegion(simplifiedRegion, saveBounds);
            }

            WaitCursorChanger wcc = null;

            if (this.fullQuality && AppEnvironment.ResamplingAlgorithm == ResamplingAlgorithm.Bilinear)
            {
                wcc = new WaitCursorChanger(DocumentWorkspace);
            }

            this.ourContext.LiftedPixels.Draw(
                this.renderArgs.Surface,
                this.context.deltaTransform,
                this.fullQuality ?
                AppEnvironment.ResamplingAlgorithm :
                ResamplingAlgorithm.NearestNeighbor);

            if (wcc != null)
            {
                wcc.Dispose();
                wcc = null;
            }

            activeLayer.Invalidate(simplifiedRegion);
            PositionNubs(this.context.currentMode);

            simplifiedRegion.Dispose();
            selectedRegion.Dispose();
        }
Exemple #16
0
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            this.Cursor = this.cursorMouseDown;

            if (((e.Button & MouseButtons.Left) == MouseButtons.Left) ||
                ((e.Button & MouseButtons.Right) == MouseButtons.Right))
            {
                this.previewRenderer.Visible = false;

                mouseDown   = true;
                mouseButton = e.Button;

                lastMouseXY.X = e.X;
                lastMouseXY.Y = e.Y;

                PdnRegion clipRegion = Selection.CreateRegion();
                renderArgs.Graphics.SetClip(clipRegion.GetRegionReadOnly(), CombineMode.Replace);
                clipRegion.Dispose();

                OnMouseMove(e);
            }
        }
        public bool PerformAction()
        {
            bool success = true;

            if (this.documentWorkspace.Selection.IsEmpty ||
                !(this.documentWorkspace.ActiveLayer is BitmapLayer))
            {
                return(false);
            }

            try
            {
                using (new WaitCursorChanger(this.documentWorkspace))
                {
                    Utility.GCFullCollect();
                    PdnRegion           selectionRegion     = this.documentWorkspace.Selection.CreateRegion();
                    PdnGraphicsPath     selectionOutline    = this.documentWorkspace.Selection.CreatePath();
                    BitmapLayer         activeLayer         = (BitmapLayer)this.documentWorkspace.ActiveLayer;
                    RenderArgs          renderArgs          = new RenderArgs(activeLayer.Surface);
                    MaskedSurface       maskedSurface       = new MaskedSurface(renderArgs.Surface, selectionOutline);
                    SurfaceForClipboard surfaceForClipboard = new SurfaceForClipboard(maskedSurface);
                    Rectangle           selectionBounds     = Utility.GetRegionBounds(selectionRegion);

                    if (selectionBounds.Width > 0 && selectionBounds.Height > 0)
                    {
                        Surface copySurface      = new Surface(selectionBounds.Width, selectionBounds.Height);
                        Bitmap  copyBitmap       = copySurface.CreateAliasedBitmap();
                        Bitmap  copyOpaqueBitmap = new Bitmap(copySurface.Width, copySurface.Height, PixelFormat.Format24bppRgb);

                        using (Graphics copyBitmapGraphics = Graphics.FromImage(copyBitmap))
                        {
                            copyBitmapGraphics.Clear(Color.White);
                        }

                        maskedSurface.Draw(copySurface, -selectionBounds.X, -selectionBounds.Y);

                        using (Graphics copyOpaqueBitmapGraphics = Graphics.FromImage(copyOpaqueBitmap))
                        {
                            copyOpaqueBitmapGraphics.Clear(Color.White);
                            copyOpaqueBitmapGraphics.DrawImage(copyBitmap, 0, 0);
                        }

                        DataObject dataObject = new DataObject();

                        dataObject.SetData(DataFormats.Bitmap, copyOpaqueBitmap);
                        dataObject.SetData(surfaceForClipboard);

                        int retryCount = 2;

                        while (retryCount >= 0)
                        {
                            try
                            {
                                using (new WaitCursorChanger(this.documentWorkspace))
                                {
                                    Clipboard.SetDataObject(dataObject, true);
                                }

                                break;
                            }

                            catch
                            {
                                if (retryCount == 0)
                                {
                                    success = false;
                                    Utility.ErrorBox(this.documentWorkspace,
                                                     PdnResources.GetString("CopyAction.Error.TransferToClipboard"));
                                }
                                else
                                {
                                    Thread.Sleep(200);
                                }
                            }

                            finally
                            {
                                --retryCount;
                            }
                        }

                        copySurface.Dispose();
                        copyBitmap.Dispose();
                        copyOpaqueBitmap.Dispose();
                    }

                    selectionRegion.Dispose();
                    selectionOutline.Dispose();
                    renderArgs.Dispose();
                    maskedSurface.Dispose();
                }
            }

            catch (OutOfMemoryException)
            {
                success = false;
                Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("CopyAction.Error.OutOfMemory"));
            }

            catch (Exception)
            {
                success = false;
                Utility.ErrorBox(this.documentWorkspace, PdnResources.GetString("CopyAction.Error.Generic"));
            }

            Utility.GCFullCollect();
            return(success);
        }
Exemple #18
0
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            if (historyWorkspace.Selection.IsEmpty)
            {
                return(null);
            }
            else
            {
                PdnRegion selectionRegion = historyWorkspace.Selection.CreateRegion();

                if (selectionRegion.GetArea() == 0)
                {
                    selectionRegion.Dispose();
                    return(null);
                }

                SelectionHistoryMemento       sha  = new SelectionHistoryMemento(StaticName, null, historyWorkspace);
                ReplaceDocumentHistoryMemento rdha = new ReplaceDocumentHistoryMemento(StaticName, null, historyWorkspace);
                Rectangle   boundingBox;
                Rectangle[] inverseRegionRects = null;

                boundingBox = Utility.GetRegionBounds(selectionRegion);

                using (PdnRegion inverseRegion = new PdnRegion(boundingBox))
                {
                    inverseRegion.Exclude(selectionRegion);

                    inverseRegionRects = Utility.TranslateRectangles(
                        inverseRegion.GetRegionScansReadOnlyInt(),
                        -boundingBox.X,
                        -boundingBox.Y);
                }

                selectionRegion.Dispose();
                selectionRegion = null;

                Document oldDocument = historyWorkspace.Document; // TODO: serialize this to disk so we don't *have* to store the full thing
                Document newDocument = new Document(boundingBox.Width, boundingBox.Height);

                // copy the document's meta data over
                newDocument.ReplaceMetaDataFrom(oldDocument);

                foreach (Layer layer in oldDocument.Layers)
                {
                    if (layer is BitmapLayer)
                    {
                        BitmapLayer oldLayer       = (BitmapLayer)layer;
                        Surface     croppedSurface = oldLayer.Surface.CreateWindow(boundingBox);
                        BitmapLayer newLayer       = new BitmapLayer(croppedSurface);

                        ColorBgra clearWhite = ColorBgra.White.NewAlpha(0);

                        foreach (Rectangle rect in inverseRegionRects)
                        {
                            newLayer.Surface.Clear(rect, clearWhite);
                        }

                        newLayer.LoadProperties(oldLayer.SaveProperties());
                        newDocument.Layers.Add(newLayer);
                    }
                    else
                    {
                        throw new InvalidOperationException("Crop does not support Layers that are not BitmapLayers");
                    }
                }

                CompoundHistoryMemento cha = new CompoundHistoryMemento(
                    StaticName,
                    PdnResources.GetImageResource("Icons.MenuImageCropIcon.png"),
                    new HistoryMemento[] { sha, rdha });

                EnterCriticalRegion();
                historyWorkspace.Document = newDocument;

                return(cha);
            }
        }
Exemple #19
0
        private void RenderGradient()
        {
            ColorBgra startColor = AppEnvironment.PrimaryColor;
            ColorBgra endColor   = AppEnvironment.SecondaryColor;

            if (this.shouldSwapColors)
            {
                if (AppEnvironment.GradientInfo.AlphaOnly)
                {
                    // In transparency mode, the color values don't matter. We just need to reverse
                    // and invert the alpha values.
                    byte startAlpha = startColor.A;
                    startColor.A = (byte)(255 - endColor.A);
                    endColor.A   = (byte)(255 - startAlpha);
                }
                else
                {
                    Utility.Swap(ref startColor, ref endColor);
                }
            }

            PointF startPointF = this.startPoint;
            PointF endPointF   = this.endPoint;

            if (this.shouldConstrain)
            {
                if (this.mouseNub == this.startNub)
                {
                    ConstrainPoints(endPointF, ref startPointF);
                }
                else
                {
                    ConstrainPoints(startPointF, ref endPointF);
                }
            }

            RestoreSavedRegion();

            Surface   surface    = ((BitmapLayer)DocumentWorkspace.ActiveLayer).Surface;
            PdnRegion clipRegion = DocumentWorkspace.Selection.CreateRegion();

            SaveRegion(clipRegion, clipRegion.GetBoundsInt());

            RenderGradient(surface, clipRegion, AppEnvironment.GetCompositingMode(), startPointF, startColor, endPointF, endColor);

            using (PdnRegion simplified = Utility.SimplifyAndInflateRegion(clipRegion, Utility.DefaultSimplificationFactor, 0))
            {
                DocumentWorkspace.ActiveLayer.Invalidate(simplified);
            }

            clipRegion.Dispose();

            // Set up status bar text
            double          angle                = -180.0 * Math.Atan2(endPointF.Y - startPointF.Y, endPointF.X - startPointF.X) / Math.PI;
            MeasurementUnit units                = AppWorkspace.Units;
            double          offsetXPhysical      = Document.PixelToPhysicalX(endPointF.X - startPointF.X, units);
            double          offsetYPhysical      = Document.PixelToPhysicalY(endPointF.Y - startPointF.Y, units);
            double          offsetLengthPhysical = Math.Sqrt(offsetXPhysical * offsetXPhysical + offsetYPhysical * offsetYPhysical);

            string numberFormat;
            string unitsAbbreviation;

            if (units != MeasurementUnit.Pixel)
            {
                string unitsAbbreviationName = "MeasurementUnit." + units.ToString() + ".Abbreviation";
                unitsAbbreviation = PdnResources.GetString(unitsAbbreviationName);
                numberFormat      = "F2";
            }
            else
            {
                unitsAbbreviation = string.Empty;
                numberFormat      = "F0";
            }

            string unitsString = PdnResources.GetString("MeasurementUnit." + units.ToString() + ".Plural");

            string statusText = string.Format(
                this.helpTextWhileAdjustingFormat,
                offsetXPhysical.ToString(numberFormat),
                unitsAbbreviation,
                offsetYPhysical.ToString(numberFormat),
                unitsAbbreviation,
                offsetLengthPhysical.ToString("F2"),
                unitsString,
                angle.ToString("F2"));

            SetStatus(this.toolIcon, statusText);

            // Make sure everything is on screen.
            Update();
        }
Exemple #20
0
        protected override void OnDeactivate()
        {
            base.OnDeactivate();

            if (mouseDown)
            {
                OnMouseUp(new MouseEventArgs(mouseButton, 0, lastMouseXY.X, lastMouseXY.Y, 0));
            }

            this.RendererList.Remove(this.previewRenderer);
            this.previewRenderer.Dispose();
            this.previewRenderer = null;

            if (savedSurfaces != null)
            {
                if (savedSurfaces != null)
                {
                    foreach (PlacedSurface ps in savedSurfaces)
                    {
                        ps.Dispose();
                    }
                }

                savedSurfaces.Clear();
                savedSurfaces = null;
            }

            renderArgs.Dispose();;
            renderArgs = null;

            aaPoints    = null;
            renderArgs  = null;
            bitmapLayer = null;

            if (clipRegion != null)
            {
                clipRegion.Dispose();
                clipRegion = null;
            }


            if (cursorMouseUp != null)
            {
                cursorMouseUp.Dispose();
                cursorMouseUp = null;
            }

            if (cursorMouseDown != null)
            {
                cursorMouseDown.Dispose();
                cursorMouseDown = null;
            }

            if (cursorMouseDownPickColor != null)
            {
                cursorMouseDownPickColor.Dispose();
                cursorMouseDownPickColor = null;
            }

            if (cursorMouseDownAdjustColor != null)
            {
                cursorMouseDownAdjustColor.Dispose();
                cursorMouseDownAdjustColor = null;
            }
        }
Exemple #21
0
        public void RunEffect(Type effectType)
        {
            bool oldDirtyValue   = AppWorkspace.ActiveDocumentWorkspace.Document.Dirty;
            bool resetDirtyValue = false;

            AppWorkspace.Update(); // make sure the window is done 'closing'
            AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
            DocumentWorkspace activeDW = AppWorkspace.ActiveDocumentWorkspace;

            PdnRegion selectedRegion;

            if (activeDW.Selection.IsEmpty)
            {
                selectedRegion = new PdnRegion(activeDW.Document.Bounds);
            }
            else
            {
                selectedRegion = activeDW.Selection.CreateRegion();
            }

            BitmapLayer layer = (BitmapLayer)activeDW.ActiveLayer;

            using (new PushNullToolMode(activeDW))
            {
                try
                {
                    Effect effect = (Effect)Activator.CreateInstance(effectType);

                    EffectEnvironmentParameters eep = new EffectEnvironmentParameters(
                        AppWorkspace.AppEnvironment.PrimaryColor,
                        AppWorkspace.AppEnvironment.SecondaryColor,
                        AppWorkspace.AppEnvironment.PenInfo.Width,
                        selectedRegion);

                    string            name         = effect.Name;
                    EffectConfigToken newLastToken = null;
                    effect.EnvironmentParameters = eep;

                    if (!(effect.IsConfigurable))
                    {
                        Surface copy = activeDW.BorrowScratchSurface(this.GetType() + ".RunEffect() using scratch surface for non-configurable rendering");

                        try
                        {
                            using (new WaitCursorChanger(AppWorkspace))
                            {
                                copy.CopySurface(layer.Surface);
                            }

                            DoEffect(effect, null, selectedRegion, selectedRegion, copy);
                        }

                        finally
                        {
                            activeDW.ReturnScratchSurface(copy);
                        }
                    }
                    else
                    {
                        PdnRegion previewRegion = (PdnRegion)selectedRegion.Clone();
                        previewRegion.Intersect(RectangleF.Inflate(activeDW.VisibleDocumentRectangleF, 1, 1));

                        Surface originalSurface = activeDW.BorrowScratchSurface(this.GetType() + ".RunEffect() using scratch surface for rendering during configuration");

                        try
                        {
                            using (new WaitCursorChanger(AppWorkspace))
                            {
                                originalSurface.CopySurface(layer.Surface);
                            }

                            //
                            AppWorkspace.SuspendThumbnailUpdates();
                            //

                            using (EffectConfigDialog configDialog = effect.CreateConfigDialog())
                            {
                                configDialog.Opacity             = 0.9;
                                configDialog.Effect              = effect;
                                configDialog.EffectSourceSurface = originalSurface;
                                configDialog.Selection           = selectedRegion;

                                EventHandler eh = new EventHandler(EffectConfigTokenChangedHandler);
                                configDialog.EffectTokenChanged += eh;

                                if (this.effectTokens.ContainsKey(effectType))
                                {
                                    EffectConfigToken oldToken = (EffectConfigToken)effectTokens[effectType].Clone();
                                    configDialog.EffectToken = oldToken;
                                }

                                BackgroundEffectRenderer ber = new BackgroundEffectRenderer(
                                    effect,
                                    configDialog.EffectToken,
                                    new RenderArgs(layer.Surface),
                                    new RenderArgs(originalSurface),
                                    previewRegion,
                                    tilesPerCpu * renderingThreadCount,
                                    renderingThreadCount);

                                ber.RenderedTile      += new RenderedTileEventHandler(RenderedTileHandler);
                                ber.StartingRendering += new EventHandler(StartingRenderingHandler);
                                ber.FinishedRendering += new EventHandler(FinishedRenderingHandler);
                                configDialog.Tag       = ber;

                                invalidateTimer.Enabled = true;
                                DialogResult dr = Utility.ShowDialog(configDialog, AppWorkspace);
                                invalidateTimer.Enabled = false;

                                this.InvalidateTimer_Tick(invalidateTimer, EventArgs.Empty);

                                if (dr == DialogResult.OK)
                                {
                                    this.effectTokens[effectType] = (EffectConfigToken)configDialog.EffectToken.Clone();
                                }

                                using (new WaitCursorChanger(AppWorkspace))
                                {
                                    ber.Abort();
                                    ber.Join();
                                    ber.Dispose();
                                    ber = null;

                                    if (dr != DialogResult.OK)
                                    {
                                        ((BitmapLayer)activeDW.ActiveLayer).Surface.CopySurface(originalSurface);
                                        activeDW.ActiveLayer.Invalidate();
                                    }

                                    configDialog.EffectTokenChanged -= eh;
                                    configDialog.Hide();
                                    AppWorkspace.Update();
                                    previewRegion.Dispose();
                                }

                                //
                                AppWorkspace.ResumeThumbnailUpdates();
                                //

                                if (dr == DialogResult.OK)
                                {
                                    PdnRegion remainingToRender = selectedRegion.Clone();
                                    PdnRegion alreadyRendered   = PdnRegion.CreateEmpty();

                                    for (int i = 0; i < this.progressRegions.Length; ++i)
                                    {
                                        if (this.progressRegions[i] == null)
                                        {
                                            break;
                                        }
                                        else
                                        {
                                            remainingToRender.Exclude(this.progressRegions[i]);
                                            alreadyRendered.Union(this.progressRegions[i]);
                                        }
                                    }

                                    activeDW.ActiveLayer.Invalidate(alreadyRendered);
                                    newLastToken = (EffectConfigToken)configDialog.EffectToken.Clone();
                                    AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
                                    DoEffect(effect, newLastToken, selectedRegion, remainingToRender, originalSurface);
                                }
                                else // if (dr == DialogResult.Cancel)
                                {
                                    using (new WaitCursorChanger(AppWorkspace))
                                    {
                                        activeDW.ActiveLayer.Invalidate();
                                        Utility.GCFullCollect();
                                    }

                                    resetDirtyValue = true;
                                    return;
                                }
                            }
                        }

                        finally
                        {
                            activeDW.ReturnScratchSurface(originalSurface);
                        }
                    }

                    // if it was from the Effects menu, save it as the "Repeat ...." item
                    if (effect.Category == EffectCategory.Effect)
                    {
                        this.lastEffect = effect;

                        if (newLastToken == null)
                        {
                            this.lastEffectToken = null;
                        }
                        else
                        {
                            this.lastEffectToken = (EffectConfigToken)newLastToken.Clone();
                        }

                        PopulateMenu(true);
                    }
                }

                finally
                {
                    selectedRegion.Dispose();
                    AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
                    AppWorkspace.Widgets.StatusBarProgress.EraseProgressStatusBar();
                    AppWorkspace.ActiveDocumentWorkspace.EnableOutlineAnimation = true;

                    for (int i = 0; i < this.progressRegions.Length; ++i)
                    {
                        if (this.progressRegions[i] != null)
                        {
                            this.progressRegions[i].Dispose();
                            this.progressRegions[i] = null;
                        }
                    }

                    if (resetDirtyValue)
                    {
                        AppWorkspace.ActiveDocumentWorkspace.Document.Dirty = oldDirtyValue;
                    }
                }
            }
        }
Exemple #22
0
        protected void CommitShape()
        {
            OnShapeCommitting();

            mouseDown = false;

            ArrayList has          = new ArrayList();
            PdnRegion activeRegion = Selection.CreateRegion();

            if (outlineSaveRegion != null)
            {
                using (PdnRegion clipTest = activeRegion.Clone())
                {
                    clipTest.Intersect(outlineSaveRegion);

                    if (!clipTest.IsEmpty())
                    {
                        BitmapHistoryMemento bha = new BitmapHistoryMemento(Name, Image, this.DocumentWorkspace,
                                                                            ActiveLayerIndex, outlineSaveRegion, this.ScratchSurface);

                        has.Add(bha);
                        outlineSaveRegion.Dispose();
                        outlineSaveRegion = null;
                    }
                }
            }

            if (interiorSaveRegion != null)
            {
                using (PdnRegion clipTest = activeRegion.Clone())
                {
                    clipTest.Intersect(interiorSaveRegion);

                    if (!clipTest.IsEmpty())
                    {
                        BitmapHistoryMemento bha = new BitmapHistoryMemento(Name, Image, this.DocumentWorkspace,
                                                                            ActiveLayerIndex, interiorSaveRegion, this.ScratchSurface);

                        has.Add(bha);
                        interiorSaveRegion.Dispose();
                        interiorSaveRegion = null;
                    }
                }
            }

            if (has.Count > 0)
            {
                CompoundHistoryMemento cha = new CompoundHistoryMemento(Name, Image, (HistoryMemento[])has.ToArray(typeof(HistoryMemento)));

                if (this.chaAlreadyOnStack == null)
                {
                    HistoryStack.PushNewMemento(cha);
                }
                else
                {
                    this.chaAlreadyOnStack.PushNewAction(cha);
                    this.chaAlreadyOnStack = null;
                }
            }

            activeRegion.Dispose();
            points = null;
            Update();
            this.shapeWasCommited = true;
        }
Exemple #23
0
        protected void RenderShape()
        {
            // create the Pen we will use to draw with
            Pen       outlinePen    = null;
            Brush     interiorBrush = null;
            PenInfo   pi            = AppEnvironment.PenInfo;
            BrushInfo bi            = AppEnvironment.BrushInfo;

            ColorBgra primary   = AppEnvironment.PrimaryColor;
            ColorBgra secondary = AppEnvironment.SecondaryColor;

            if (!ForceShapeDrawType && AppEnvironment.ShapeDrawType == ShapeDrawType.Interior)
            {
                Utility.Swap(ref primary, ref secondary);
            }

            // Initialize pens and brushes to the correct colors
            if ((mouseButton & MouseButtons.Left) == MouseButtons.Left)
            {
                outlinePen    = pi.CreatePen(AppEnvironment.BrushInfo, primary.ToColor(), secondary.ToColor());
                interiorBrush = bi.CreateBrush(secondary.ToColor(), primary.ToColor());
            }
            else if ((mouseButton & MouseButtons.Right) == MouseButtons.Right)
            {
                outlinePen    = pi.CreatePen(AppEnvironment.BrushInfo, secondary.ToColor(), primary.ToColor());
                interiorBrush = bi.CreateBrush(primary.ToColor(), secondary.ToColor());
            }

            if (!this.UseDashStyle)
            {
                outlinePen.DashStyle = DashStyle.Solid;
            }

            outlinePen.LineJoin   = LineJoin.MiterClipped;
            outlinePen.MiterLimit = 2;

            // redraw the old saveSurface
            if (interiorSaveRegion != null)
            {
                RestoreRegion(interiorSaveRegion);
                interiorSaveRegion.Dispose();
                interiorSaveRegion = null;
            }

            if (outlineSaveRegion != null)
            {
                RestoreRegion(outlineSaveRegion);
                outlineSaveRegion.Dispose();
                outlineSaveRegion = null;
            }

            // anti-aliasing? Don't mind if I do
            if (AppEnvironment.AntiAliasing)
            {
                renderArgs.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            }
            else
            {
                renderArgs.Graphics.SmoothingMode = SmoothingMode.None;
            }

            // also set the pixel offset mode
            renderArgs.Graphics.PixelOffsetMode = GetPixelOffsetMode();

            // figure out how we're going to draw
            ShapeDrawType drawType;

            if (ForceShapeDrawType)
            {
                drawType = ForcedShapeDrawType;
            }
            else
            {
                drawType = AppEnvironment.ShapeDrawType;
            }

            // get the region we want to save
            points = this.TrimShapePath(points);
            PointF[]        pointsArray = points.ToArray();
            PdnGraphicsPath shapePath   = CreateShapePath(pointsArray);

            if (shapePath != null)
            {
                // create non-optimized interior region
                PdnRegion interiorRegion = new PdnRegion(shapePath);

                // create non-optimized outline region
                PdnRegion outlineRegion;

                using (PdnGraphicsPath outlinePath = (PdnGraphicsPath)shapePath.Clone())
                {
                    try
                    {
                        outlinePath.Widen(outlinePen);
                        outlineRegion = new PdnRegion(outlinePath);
                    }

                    // Sometimes GDI+ gets cranky if we have a very small shape (e.g. all points
                    // are coincident).
                    catch (OutOfMemoryException)
                    {
                        outlineRegion = new PdnRegion(shapePath);
                    }
                }

                // create optimized outlineRegion for purposes of rendering, if it is possible to do so
                // shapes will often provide an "optimized" region that circumvents the fact that
                // we'd otherwise get a region that encompasses the outline *and* the interior, thus
                // slowing rendering significantly in many cases.
                RectangleF[] optimizedOutlineRegion = GetOptimizedShapeOutlineRegion(pointsArray, shapePath);
                PdnRegion    invalidOutlineRegion;

                if (optimizedOutlineRegion != null)
                {
                    Utility.InflateRectanglesInPlace(optimizedOutlineRegion, (int)(outlinePen.Width + 2));
                    invalidOutlineRegion = Utility.RectanglesToRegion(optimizedOutlineRegion);
                }
                else
                {
                    invalidOutlineRegion = Utility.SimplifyAndInflateRegion(outlineRegion, Utility.DefaultSimplificationFactor, (int)(outlinePen.Width + 2));
                }

                // create optimized interior region
                PdnRegion invalidInteriorRegion = Utility.SimplifyAndInflateRegion(interiorRegion, Utility.DefaultSimplificationFactor, 3);

                PdnRegion invalidRegion = new PdnRegion();
                invalidRegion.MakeEmpty();

                // set up alpha blending
                renderArgs.Graphics.CompositingMode = AppEnvironment.GetCompositingMode();

                SaveRegion(invalidOutlineRegion, invalidOutlineRegion.GetBoundsInt());
                this.outlineSaveRegion = invalidOutlineRegion;
                if ((drawType & ShapeDrawType.Outline) != 0)
                {
                    shapePath.Draw(renderArgs.Graphics, outlinePen);
                }

                invalidRegion.Union(invalidOutlineRegion);

                // draw shape
                if ((drawType & ShapeDrawType.Interior) != 0)
                {
                    SaveRegion(invalidInteriorRegion, invalidInteriorRegion.GetBoundsInt());
                    this.interiorSaveRegion = invalidInteriorRegion;
                    renderArgs.Graphics.FillPath(interiorBrush, shapePath);
                    invalidRegion.Union(invalidInteriorRegion);
                }
                else
                {
                    invalidInteriorRegion.Dispose();
                    invalidInteriorRegion = null;
                }

                bitmapLayer.Invalidate(invalidRegion);

                invalidRegion.Dispose();
                invalidRegion = null;

                outlineRegion.Dispose();
                outlineRegion = null;

                interiorRegion.Dispose();
                interiorRegion = null;
            }

            Update();

            if (shapePath != null)
            {
                shapePath.Dispose();
                shapePath = null;
            }

            outlinePen.Dispose();
            interiorBrush.Dispose();
        }
Exemple #24
0
        public void RunEffect(Type effectType)
        {
            bool oldDirtyValue   = AppWorkspace.ActiveDocumentWorkspace.Document.Dirty;
            bool resetDirtyValue = false;

            AppWorkspace.Update(); // make sure the window is done 'closing'
            AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
            DocumentWorkspace activeDW = AppWorkspace.ActiveDocumentWorkspace;

            PdnRegion selectedRegion;

            if (activeDW.Selection.IsEmpty)
            {
                selectedRegion = new PdnRegion(activeDW.Document.Bounds);
            }
            else
            {
                selectedRegion = activeDW.Selection.CreateRegion();
            }

            Exception   exception = null;
            Effect      effect    = null;
            BitmapLayer layer     = (BitmapLayer)activeDW.ActiveLayer;

            using (new PushNullToolMode(activeDW))
            {
                try
                {
                    effect = (Effect)Activator.CreateInstance(effectType);

                    string            name         = effect.Name;
                    EffectConfigToken newLastToken = null;

                    if (!(effect.CheckForEffectFlags(EffectFlags.Configurable)))
                    {
                        Surface copy = activeDW.BorrowScratchSurface(GetType() +
                                                                     ".RunEffect() using scratch surface for non-configurable rendering");

                        try
                        {
                            using (new WaitCursorChanger(AppWorkspace))
                            {
                                copy.CopySurface(layer.Surface);
                            }

                            EffectEnvironmentParameters eep = new EffectEnvironmentParameters(
                                AppWorkspace.AppEnvironment.PrimaryColor,
                                AppWorkspace.AppEnvironment.SecondaryColor,
                                AppWorkspace.AppEnvironment.PenInfo.Width,
                                selectedRegion,
                                copy);

                            effect.EnvironmentParameters = eep;

                            DoEffect(effect, null, selectedRegion, selectedRegion, copy, out exception);
                        }

                        finally
                        {
                            activeDW.ReturnScratchSurface(copy);
                        }
                    }
                    else
                    {
                        PdnRegion previewRegion = (PdnRegion)selectedRegion.Clone();
                        previewRegion.Intersect(RectangleF.Inflate(activeDW.VisibleDocumentRectangleF, 1, 1));

                        Surface originalSurface = activeDW.BorrowScratchSurface(GetType() +
                                                                                ".RunEffect() using scratch surface for rendering during configuration");

                        try
                        {
                            using (new WaitCursorChanger(AppWorkspace))
                            {
                                originalSurface.CopySurface(layer.Surface);
                            }

                            EffectEnvironmentParameters eep = new EffectEnvironmentParameters(
                                AppWorkspace.AppEnvironment.PrimaryColor,
                                AppWorkspace.AppEnvironment.SecondaryColor,
                                AppWorkspace.AppEnvironment.PenInfo.Width,
                                selectedRegion,
                                originalSurface);

                            effect.EnvironmentParameters = eep;

                            //
                            IDisposable resumeTUFn = AppWorkspace.SuspendThumbnailUpdates();
                            //

                            using (EffectConfigDialog configDialog = effect.CreateConfigDialog())
                            {
                                configDialog.Opacity             = 0.9;
                                configDialog.Effect              = effect;
                                configDialog.EffectSourceSurface = originalSurface;
                                configDialog.Selection           = selectedRegion;

                                BackgroundEffectRenderer ber = null;

                                void OnEffectTokenChanged(object sender, EventArgs e)
                                {
                                    EffectConfigDialog ecf = (EffectConfigDialog)sender;

                                    if (ber != null)
                                    {
                                        AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBarAsync();

                                        try
                                        {
                                            ber.Start();
                                        }

                                        catch (Exception ex)
                                        {
                                            exception = ex;
                                            ecf.Close();
                                        }
                                    }
                                }

                                configDialog.EffectTokenChanged += OnEffectTokenChanged;

                                if (EffectTokens.ContainsKey(effectType))
                                {
                                    EffectConfigToken oldToken = (EffectConfigToken)EffectTokens[effectType].Clone();
                                    configDialog.EffectToken = oldToken;
                                }

                                int pixelCount  = layer.Surface.Height;
                                int threadCount = effect.CheckForEffectFlags(EffectFlags.SingleThreaded) ? 1 : RenderingThreadCount;
                                int maxTiles    = TilesPerCpu * threadCount;
                                int tileCount   = Math.Min(maxTiles, pixelCount);
                                ber = new BackgroundEffectRenderer(
                                    effect,
                                    configDialog.EffectToken,
                                    new RenderArgs(layer.Surface),
                                    new RenderArgs(originalSurface),
                                    previewRegion,
                                    tileCount,
                                    threadCount);

                                ber.RenderedTile      += new RenderedTileEventHandler(RenderedTileHandler);
                                ber.StartingRendering += new EventHandler(StartingRenderingHandler);
                                ber.FinishedRendering += new EventHandler(FinishedRenderingHandler);

                                InvalidateTimer.Enabled = true;

                                DialogResult dr;

                                try
                                {
                                    dr = Utility.ShowDialog(configDialog, AppWorkspace);
                                }

                                catch (Exception ex)
                                {
                                    dr        = DialogResult.None;
                                    exception = ex;
                                }

                                InvalidateTimer.Enabled = false;

                                InvalidateTimer_Tick(InvalidateTimer, EventArgs.Empty);

                                if (dr == DialogResult.OK)
                                {
                                    EffectTokens[effectType] = (EffectConfigToken)configDialog.EffectToken.Clone();
                                }

                                using (new WaitCursorChanger(AppWorkspace))
                                {
                                    try
                                    {
                                        ber.Abort();
                                        ber.Join();
                                    }

                                    catch (Exception ex)
                                    {
                                        exception = ex;
                                    }

                                    ber.Dispose();
                                    ber = null;

                                    if (dr != DialogResult.OK)
                                    {
                                        ((BitmapLayer)activeDW.ActiveLayer).Surface.CopySurface(originalSurface);
                                        activeDW.ActiveLayer.Invalidate();
                                    }

                                    configDialog.EffectTokenChanged -= OnEffectTokenChanged;
                                    configDialog.Hide();
                                    AppWorkspace.Update();
                                    previewRegion.Dispose();
                                }

                                //
                                resumeTUFn.Dispose();
                                resumeTUFn = null;
                                //

                                if (dr == DialogResult.OK)
                                {
                                    PdnRegion remainingToRender = selectedRegion.Clone();
                                    PdnRegion alreadyRendered   = PdnRegion.CreateEmpty();

                                    for (int i = 0; i < ProgressRegions.Length; ++i)
                                    {
                                        if (ProgressRegions[i] == null)
                                        {
                                            break;
                                        }
                                        else
                                        {
                                            remainingToRender.Exclude(ProgressRegions[i]);
                                            alreadyRendered.Union(ProgressRegions[i]);
                                        }
                                    }

                                    activeDW.ActiveLayer.Invalidate(alreadyRendered);
                                    newLastToken = (EffectConfigToken)configDialog.EffectToken.Clone();
                                    AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
                                    DoEffect(effect, newLastToken, selectedRegion, remainingToRender, originalSurface, out exception);
                                }
                                else // if (dr == DialogResult.Cancel)
                                {
                                    using (new WaitCursorChanger(AppWorkspace))
                                    {
                                        activeDW.ActiveLayer.Invalidate();
                                        Utility.GCFullCollect();
                                    }

                                    resetDirtyValue = true;
                                    return;
                                }
                            }
                        }

                        catch (Exception ex)
                        {
                            exception = ex;
                        }

                        finally
                        {
                            activeDW.ReturnScratchSurface(originalSurface);
                        }
                    }

                    // if it was from the Effects menu, save it as the "Repeat ...." item
                    if (effect.Category == EffectCategory.Effect)
                    {
                        LastEffect = effect;

                        LastEffectToken = newLastToken == null ? null :
                                          (EffectConfigToken)newLastToken.Clone();

                        PopulateMenu(true);
                    }
                }

                catch (Exception ex)
                {
                    exception = ex;
                }

                finally
                {
                    selectedRegion.Dispose();
                    AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
                    AppWorkspace.Widgets.StatusBarProgress.EraseProgressStatusBar();
                    AppWorkspace.ActiveDocumentWorkspace.EnableOutlineAnimation = true;

                    if (ProgressRegions != null)
                    {
                        for (int i = 0; i < ProgressRegions.Length; ++i)
                        {
                            ProgressRegions[i]?.Dispose();
                            ProgressRegions[i] = null;
                        }
                    }

                    if (resetDirtyValue)
                    {
                        AppWorkspace.ActiveDocumentWorkspace.Document.Dirty = oldDirtyValue;
                    }

                    if (exception != null)
                    {
                        HandleEffectException(AppWorkspace, effect, exception);
                    }
                }
            }
        }
 protected override void OnAfterExecute()
 {
     region.Dispose();
     dst.Dispose();
 }
Exemple #26
0
        private bool DoEffect(Effect effect, EffectConfigToken token, PdnRegion selectedRegion,
                              PdnRegion regionToRender, Surface originalSurface)
        {
            bool oldDirtyValue   = AppWorkspace.ActiveDocumentWorkspace.Document.Dirty;
            bool resetDirtyValue = false;

            bool returnVal = false;

            AppWorkspace.ActiveDocumentWorkspace.EnableOutlineAnimation = false;

            try
            {
                using (ProgressDialog aed = new ProgressDialog())
                {
                    if (effect.Image != null)
                    {
                        aed.Icon = Utility.ImageToIcon(effect.Image, Utility.TransparentKey);
                    }

                    aed.Opacity     = 0.9;
                    aed.Value       = 0;
                    aed.Text        = effect.Name;
                    aed.Description = string.Format(PdnResources.GetString("Effects.ApplyingDialog.Description"), effect.Name);

                    invalidateTimer.Enabled = true;

                    using (new WaitCursorChanger(AppWorkspace))
                    {
                        HistoryMemento ha     = null;
                        DialogResult   result = DialogResult.None;

                        AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
                        AppWorkspace.Widgets.LayerControl.SuspendLayerPreviewUpdates();

                        try
                        {
                            ManualResetEvent     saveEvent = new ManualResetEvent(false);
                            BitmapHistoryMemento bha       = null;

                            // perf bug #1445: save this data in a background thread
                            PdnRegion selectedRegionCopy = selectedRegion.Clone();
                            PaintDotNet.Threading.ThreadPool.Global.QueueUserWorkItem(
                                delegate(object context)
                            {
                                try
                                {
                                    ImageResource image;

                                    if (effect.Image == null)
                                    {
                                        image = null;
                                    }
                                    else
                                    {
                                        image = ImageResource.FromImage(effect.Image);
                                    }

                                    bha = new BitmapHistoryMemento(effect.Name, image, this.AppWorkspace.ActiveDocumentWorkspace,
                                                                   this.AppWorkspace.ActiveDocumentWorkspace.ActiveLayerIndex, selectedRegionCopy, originalSurface);
                                }

                                finally
                                {
                                    saveEvent.Set();
                                    selectedRegionCopy.Dispose();
                                    selectedRegionCopy = null;
                                }
                            });

                            BackgroundEffectRenderer ber = new BackgroundEffectRenderer(
                                effect,
                                token,
                                new RenderArgs(((BitmapLayer)AppWorkspace.ActiveDocumentWorkspace.ActiveLayer).Surface),
                                new RenderArgs(originalSurface),
                                regionToRender,
                                tilesPerCpu * renderingThreadCount,
                                renderingThreadCount);

                            aed.Tag                = ber;
                            ber.RenderedTile      += new RenderedTileEventHandler(aed.RenderedTileHandler);
                            ber.RenderedTile      += new RenderedTileEventHandler(RenderedTileHandler);
                            ber.StartingRendering += new EventHandler(StartingRenderingHandler);
                            ber.FinishedRendering += new EventHandler(aed.FinishedRenderingHandler);
                            ber.FinishedRendering += new EventHandler(FinishedRenderingHandler);
                            ber.Start();

                            result = Utility.ShowDialog(aed, AppWorkspace);

                            if (result == DialogResult.Cancel)
                            {
                                resetDirtyValue = true;

                                using (new WaitCursorChanger(AppWorkspace))
                                {
                                    ber.Abort();
                                    ber.Join();
                                    ((BitmapLayer)AppWorkspace.ActiveDocumentWorkspace.ActiveLayer).Surface.CopySurface(originalSurface);
                                }
                            }

                            invalidateTimer.Enabled = false;

                            ber.Join();
                            ber.Dispose();

                            saveEvent.WaitOne();
                            saveEvent.Close();
                            saveEvent = null;

                            ha = bha;
                        }

                        catch
                        {
                            using (new WaitCursorChanger(AppWorkspace))
                            {
                                ((BitmapLayer)AppWorkspace.ActiveDocumentWorkspace.ActiveLayer).Surface.CopySurface(originalSurface);
                                ha = null;
                            }
                        }

                        finally
                        {
                            AppWorkspace.Widgets.LayerControl.ResumeLayerPreviewUpdates();
                        }

                        using (PdnRegion simplifiedRenderRegion = Utility.SimplifyAndInflateRegion(selectedRegion))
                        {
                            using (new WaitCursorChanger(AppWorkspace))
                            {
                                AppWorkspace.ActiveDocumentWorkspace.ActiveLayer.Invalidate(simplifiedRenderRegion);
                            }
                        }

                        using (new WaitCursorChanger(AppWorkspace))
                        {
                            if (result == DialogResult.OK)
                            {
                                if (ha != null)
                                {
                                    AppWorkspace.ActiveDocumentWorkspace.History.PushNewMemento(ha);
                                }

                                AppWorkspace.Update();
                                returnVal = true;
                            }
                            else
                            {
                                Utility.GCFullCollect();
                            }
                        }
                    } // using
                }     // using
            }

            finally
            {
                AppWorkspace.ActiveDocumentWorkspace.EnableOutlineAnimation = true;

                if (resetDirtyValue)
                {
                    AppWorkspace.ActiveDocumentWorkspace.Document.Dirty = oldDirtyValue;
                }
            }

            AppWorkspace.Widgets.StatusBarProgress.EraseProgressStatusBarAsync();
            return(returnVal);
        }
Exemple #27
0
        protected override HistoryMemento OnUndo()
        {
            BitmapHistoryMementoData data = this.Data as BitmapHistoryMementoData;
            BitmapLayer layer             = (BitmapLayer)this.historyWorkspace.Document.Layers[this.layerIndex];

            PdnRegion     region;
            MaskedSurface maskedSurface = null;

            if (this.poMaskedSurfaceRef != Guid.Empty)
            {
                PersistedObject <MaskedSurface> poMS = PersistedObjectLocker.Get <MaskedSurface>(this.poMaskedSurfaceRef);
                maskedSurface = poMS.Object;
                region        = maskedSurface.CreateRegion();
            }
            else if (data.UndoImage == null)
            {
                region = data.SavedRegion;
            }
            else
            {
                region = data.UndoImage.Region;
            }

            BitmapHistoryMemento redo;

            if (this.poUndoMaskedSurfaceRef == Guid.Empty)
            {
                redo = new BitmapHistoryMemento(Name, Image, this.historyWorkspace, this.layerIndex, region);
                redo.poUndoMaskedSurfaceRef = this.poMaskedSurfaceRef;
            }
            else
            {
                redo = new BitmapHistoryMemento(Name, Image, this.historyWorkspace, this.layerIndex, this.poUndoMaskedSurfaceRef);
            }

            PdnRegion simplified = Utility.SimplifyAndInflateRegion(region);

            if (maskedSurface != null)
            {
                maskedSurface.Draw(layer.Surface);
            }
            else if (data.UndoImage == null)
            {
                using (FileStream input = FileSystem.OpenStreamingFile(this.tempFileName, FileAccess.Read))
                {
                    LoadSurfaceRegion(input, layer.Surface, data.SavedRegion);
                }

                data.SavedRegion.Dispose();
                this.tempFileHandle.Dispose();
                this.tempFileHandle = null;
            }
            else
            {
                data.UndoImage.Draw(layer.Surface);
                data.UndoImage.Dispose();
            }

            layer.Invalidate(simplified);
            simplified.Dispose();

            return(redo);
        }
Exemple #28
0
        protected void RenderShape()
        {
            // create the Pen we will use to draw with
            Pen outlinePen = null;
            Brush interiorBrush = null;
            PenInfo pi = AppEnvironment.PenInfo;
            BrushInfo bi = AppEnvironment.BrushInfo;

            ColorBgra primary = AppEnvironment.PrimaryColor;
            ColorBgra secondary = AppEnvironment.SecondaryColor;

            if (!ForceShapeDrawType && AppEnvironment.ShapeDrawType == ShapeDrawType.Interior)
            {
                Utility.Swap(ref primary, ref secondary);
            }

            // Initialize pens and brushes to the correct colors
            if ((mouseButton & MouseButtons.Left) == MouseButtons.Left)
            {
                outlinePen = pi.CreatePen(AppEnvironment.BrushInfo, primary.ToColor(), secondary.ToColor());
                interiorBrush = bi.CreateBrush(secondary.ToColor(), primary.ToColor());
            }
            else if ((mouseButton & MouseButtons.Right) == MouseButtons.Right)
            {
                outlinePen = pi.CreatePen(AppEnvironment.BrushInfo, secondary.ToColor(), primary.ToColor());
                interiorBrush = bi.CreateBrush(primary.ToColor(), secondary.ToColor());
            }

            if (!this.useDashStyle)
            {
                outlinePen.DashStyle = DashStyle.Solid;
            }

            outlinePen.LineJoin = LineJoin.MiterClipped;
            outlinePen.MiterLimit = 2;

            // redraw the old saveSurface
            if (interiorSaveRegion != null)
            {
                RestoreRegion(interiorSaveRegion);
                interiorSaveRegion.Dispose();
                interiorSaveRegion = null;
            }

            if (outlineSaveRegion != null)
            {
                RestoreRegion(outlineSaveRegion);
                outlineSaveRegion.Dispose();
                outlineSaveRegion = null;
            }

            // anti-aliasing? Don't mind if I do
            if (AppEnvironment.AntiAliasing)
            {
                renderArgs.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            }
            else
            {
                renderArgs.Graphics.SmoothingMode = SmoothingMode.None;
            }

            // also set the pixel offset mode
            renderArgs.Graphics.PixelOffsetMode = GetPixelOffsetMode();

            // figure out how we're going to draw
            ShapeDrawType drawType;

            if (ForceShapeDrawType)
            {
                drawType = ForcedShapeDrawType;
            }
            else
            {
                drawType = AppEnvironment.ShapeDrawType;
            }

            // get the region we want to save
            points = this.TrimShapePath(points);
            PointF[] pointsArray = points.ToArray();
            PdnGraphicsPath shapePath = CreateShapePath(pointsArray);

            if (shapePath != null)
            {
                // create non-optimized interior region
                PdnRegion interiorRegion = new PdnRegion(shapePath);

                // create non-optimized outline region
                PdnRegion outlineRegion;

                using (PdnGraphicsPath outlinePath = (PdnGraphicsPath)shapePath.Clone())
                {
                    try
                    {
                        outlinePath.Widen(outlinePen);
                        outlineRegion = new PdnRegion(outlinePath);
                    }

                    // Sometimes GDI+ gets cranky if we have a very small shape (e.g. all points
                    // are coincident). 
                    catch (OutOfMemoryException)
                    {
                        outlineRegion = new PdnRegion(shapePath);
                    }
                }

                // create optimized outlineRegion for purposes of rendering, if it is possible to do so
                // shapes will often provide an "optimized" region that circumvents the fact that
                // we'd otherwise get a region that encompasses the outline *and* the interior, thus
                // slowing rendering significantly in many cases.
                RectangleF[] optimizedOutlineRegion = GetOptimizedShapeOutlineRegion(pointsArray, shapePath);
                PdnRegion invalidOutlineRegion;

                if (optimizedOutlineRegion != null)
                {
                    Utility.InflateRectanglesInPlace(optimizedOutlineRegion, (int)(outlinePen.Width + 2));
                    invalidOutlineRegion = Utility.RectanglesToRegion(optimizedOutlineRegion);
                }
                else
                {
                    invalidOutlineRegion = Utility.SimplifyAndInflateRegion(outlineRegion, Utility.DefaultSimplificationFactor, (int)(outlinePen.Width + 2));
                }

                // create optimized interior region
                PdnRegion invalidInteriorRegion = Utility.SimplifyAndInflateRegion(interiorRegion, Utility.DefaultSimplificationFactor, 3);

                PdnRegion invalidRegion = new PdnRegion();
                invalidRegion.MakeEmpty();

                // set up alpha blending
                renderArgs.Graphics.CompositingMode = AppEnvironment.GetCompositingMode();

                SaveRegion(invalidOutlineRegion, invalidOutlineRegion.GetBoundsInt());
                this.outlineSaveRegion = invalidOutlineRegion;
                if ((drawType & ShapeDrawType.Outline) != 0)
                {
                    shapePath.Draw(renderArgs.Graphics, outlinePen);
                }

                invalidRegion.Union(invalidOutlineRegion);

                // draw shape
                if ((drawType & ShapeDrawType.Interior) != 0)
                {
                    SaveRegion(invalidInteriorRegion, invalidInteriorRegion.GetBoundsInt());
                    this.interiorSaveRegion = invalidInteriorRegion;
                    renderArgs.Graphics.FillPath(interiorBrush, shapePath);
                    invalidRegion.Union(invalidInteriorRegion);
                }
                else
                {
                    invalidInteriorRegion.Dispose();
                    invalidInteriorRegion = null;
                }

                bitmapLayer.Invalidate(invalidRegion);

                invalidRegion.Dispose();
                invalidRegion = null;

                outlineRegion.Dispose();
                outlineRegion = null;

                interiorRegion.Dispose();
                interiorRegion = null;
            }

            Update();

            if (shapePath != null)
            {
                shapePath.Dispose();
                shapePath = null;
            }

            outlinePen.Dispose();
            interiorBrush.Dispose();
        }