openpdn /src/Data/Layer.cs

Language C# Lines 630
MD5 Hash cea54dcc2f2f4b546cfcb0d5e85d120d Estimated Cost $10,703 (why?)
Repository https://bitbucket.org/tuldok89/openpdn View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET                                                                   //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors.     //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved.          //
// See src/Resources/Files/License.txt for full licensing and attribution      //
// details.                                                                    //
// .                                                                           //
/////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Runtime.Serialization;
using System.Threading;
using System.Windows.Forms;

namespace PaintDotNet
{
    /// <summary>
    /// A layer's properties are immutable. That is, you can modify the surface
    /// of a layer all you want, but to change its dimensions requires creating
    /// a new layer.
    /// </summary>
    [Serializable]
    public abstract class Layer
        : ICloneable,
          IDisposable,
          IThumbnailProvider
    {
        private readonly int _width;
        private readonly int _height;

        /// <summary>
        /// The background layer is generally opaque although it doesn't *have* to be. For
        /// example, the Canvas Size action distinguishes between background and non-background
        /// layers such that it fills the background layer with opaque and the non-background 
        /// layers with transparency.
        /// The value of this property should not be used to disallow the user from performing
        /// an action.
        /// </summary>
        public bool IsBackground
        {
            get
            {
                return _properties.isBackground;
            }

            set
            {
                bool oldValue = _properties.isBackground;

                if (oldValue == value) return;
                OnPropertyChanging(LayerProperties.IsBackgroundName);
                _properties.isBackground = value;
                OnPropertyChanged(LayerProperties.IsBackgroundName);
            }
        }

        /// <summary>
        /// If this value is non-0, then the PropertyChanged event will be
        /// suppressed. This is in place so that the Layer Properties dialog
        /// can tweak the properties without them filling up the undo stack.
        /// </summary>
        [NonSerialized]
        private int _suppressPropertyChanges;

        /// <summary>
        /// Encapsulates the mutable properties of the Layer class.
        /// </summary>
        [Serializable]
        internal sealed class LayerProperties
            : ICloneable,
              ISerializable
        {
            public string name;
            public NameValueCollection UserMetaData;
            public bool visible;
            public bool isBackground;
            public byte opacity;

            private const string NameTag = "name";
            private const string UserMetaDataTag = "userMetaData";
            private const string VisibleTag = "visible";
            private const string IsBackgroundTag = "isBackground";
            private const string OpacityTag = "opacity";

            public static string IsBackgroundName
            {
                get
                {
                    return PdnResources.GetString("Layer.Properties.IsBackground.Name");
                }
            }

            public static string NameName 
            {
                get
                {
                    return PdnResources.GetString("Layer.Properties.Name.Name");
                }
            }

            public static string VisibleName
            {
                get
                {
                    return PdnResources.GetString("Layer.Properties.Visible.Name");
                }
            }

            public static string OpacityName 
            {
                get
                {
                    return PdnResources.GetString("Layer.Properties.Opacity.Name");
                }
            }

            public LayerProperties(string name, NameValueCollection userMetaData, bool visible, bool isBackground, byte opacity)
            {
                this.name = name;
                UserMetaData = new NameValueCollection(userMetaData);
                this.visible = visible;
                this.isBackground = isBackground;
                this.opacity = opacity;
            }

            public LayerProperties(LayerProperties copyMe)
            {
                name = copyMe.name;
                UserMetaData = new NameValueCollection(copyMe.UserMetaData);
                visible = copyMe.visible;
                isBackground = copyMe.isBackground;
                opacity = copyMe.opacity;
            }

            public object Clone()
            {
                return new LayerProperties(this);
            }

            public LayerProperties(SerializationInfo info, StreamingContext context)
            {
                name = info.GetString(NameTag);
                UserMetaData = (NameValueCollection)info.GetValue(UserMetaDataTag, typeof(NameValueCollection));
                visible = info.GetBoolean(VisibleTag);
                isBackground = info.GetBoolean(IsBackgroundTag);
                
                // This property was added with v2.1. So as to allow loading old .PDN files,
                // this is an optional item.
                // (Historical note: this property was actually moved from the BitmapLayer
                //  properties to the base class because it was found to be a rather important
                //  property for rendering regardless of layer "type")
                try
                {
                    opacity = info.GetByte(OpacityTag);
                }

                catch (SerializationException)
                {
                    opacity = 255;
                }
            }

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue(NameTag, name);
                info.AddValue(UserMetaDataTag, UserMetaData);
                info.AddValue(VisibleTag, visible);
                info.AddValue(IsBackgroundTag, isBackground);
                info.AddValue(OpacityTag, opacity);
            }
        }

        private LayerProperties _properties;

        public byte Opacity
        {
            get
            {
                if (disposed)
                {
                    throw new ObjectDisposedException("Layer");
                }

                return _properties.opacity;
            }

            set
            {
                if (disposed)
                {
                    throw new ObjectDisposedException("Layer");
                }

                if (_properties.opacity == value) return;
                OnPropertyChanging(LayerProperties.OpacityName);
                _properties.opacity = value;
                OnPropertyChanged(LayerProperties.OpacityName);
                Invalidate();
            }
        }

        /// <summary>
        /// Allows you to save the mutable properties of the layer so you can restore them later
        /// (esp. important for undo!). Mutable properties include the layer's name, whether it's
        /// visible, and the metadata. This list might expand later.
        /// </summary>
        /// <returns>
        /// An object that can be used later in a call to LoadProperties.
        /// </returns>
        /// <remarks>
        /// It is important that derived classes call this in the correct fashion so as to 'chain'
        /// the properties list together. The following is the correct pattern:
        /// 
        ///     public override object SaveProperties()
        ///     {
        ///         object baseProperties = base.SaveProperties();
        ///         return new List(properties.Clone(), new List(baseProperties, null));
        ///     }
        /// </remarks>
        public virtual object SaveProperties()
        {
            return _properties.Clone();
        }

        public void LoadProperties(object oldState)
        {
            LoadProperties(oldState, false);
        }
        
        public virtual void LoadProperties(object oldState, bool suppressEvents)
        {
            var lp = (LayerProperties)oldState;
            var changed = new List<String>();

            if (!suppressEvents)
            {
                if (lp.name != _properties.name)
                {
                    changed.Add(LayerProperties.NameName);
                }

                if (lp.isBackground != _properties.isBackground)
                {
                    changed.Add(LayerProperties.IsBackgroundName);
                }

                if (lp.visible != _properties.visible)
                {
                    changed.Add(LayerProperties.VisibleName);
                }

                if (lp.opacity != _properties.opacity)
                {
                    changed.Add(LayerProperties.OpacityName);
                }
            }

            foreach (string propertyName in changed)
            {
                OnPropertyChanging(propertyName);
            }

            _properties = (LayerProperties)((LayerProperties)oldState).Clone();

            Invalidate();

            foreach (string propertyName in changed)
            {
                OnPropertyChanged(propertyName);
            }
        }

        public int Width
        {
            get
            {
                return _width;
            }
        }

        public int Height
        {
            get
            {
                return _height;
            }
        }

        public Size Size
        {
            get
            {
                return new Size(Width, Height);
            }
        }

        public Rectangle Bounds
        {
            get
            {
                return new Rectangle(new Point(0, 0), Size);
            }
        }

        public void PushSuppressPropertyChanged()
        {
            Interlocked.Increment(ref _suppressPropertyChanges);
        }

        public void PopSuppressPropertyChanged()
        {
            if (0 > Interlocked.Decrement(ref _suppressPropertyChanges))
            {
                throw new InvalidProgramException("suppressPreviewChanged is less than zero");
            }
        }

        [field: NonSerialized]
        public event EventHandler PreviewChanged;

        protected virtual void OnPreviewChanged()
        {
            if (PreviewChanged != null)
            {
                PreviewChanged(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// This event is raised before a property is changed. Note that the name given
        /// in the PropertyEventArgs is for descriptive (UI) purposes only and serves no
        /// programmatic purpose. When this event is raised you should not make any
        /// assumptions about which property was changed based on this description.
        /// </summary>
        [field: NonSerialized]
        public event PropertyEventHandler PropertyChanging;

        protected virtual void OnPropertyChanging(string propertyName)
        {
            if (_suppressPropertyChanges != 0) return;
            if (PropertyChanging != null)
            {
                PropertyChanging(this, new PropertyEventArgs(propertyName));
            }
        }

        /// <summary>
        /// This event is raised after a property is changed. Note that the name given
        /// in the PropertyEventArgs is for descriptive (UI) purposes only and serves no
        /// programmatic purpose. When this event is raised you should not make any
        /// assumptions about which property was changed based on this description.
        /// </summary>
        [field: NonSerialized]
        public event PropertyEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (_suppressPropertyChanges != 0) return;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyEventArgs(propertyName));
            }
        }

        /// <summary>
        /// You can call this to raise the PropertyChanged event. Note that is will
        /// raise the event with an empty string for the property name description.
        /// Thus it is useful only for syncing up UI elements that require notification
        /// of events but that otherwise don't really track it.
        /// </summary>
        public void PerformPropertyChanged()
        {
            OnPropertyChanged(string.Empty);
        }

        /// <summary>
        /// A user-definable name.
        /// </summary>
        public string Name
        {
            get
            {
                return _properties.name;
            }

            set
            {
                if (_properties.name == value) return;
                OnPropertyChanging(LayerProperties.NameName);
                _properties.name = value;
                OnPropertyChanged(LayerProperties.NameName);
            }
        }

        [NonSerialized]
        private Metadata _metadata;

        public Metadata Metadata
        {
            get { return _metadata ?? (_metadata = new Metadata(_properties.UserMetaData)); }
        }

        /// <summary>
        /// Determines whether the layer is part of a document's composition. If this
        /// property is false, the composition engine will ignore this layer.
        /// </summary>
        public bool Visible
        {
            get
            {
                return _properties.visible;
            }

            set
            {
                bool oldValue = _properties.visible;

                if (oldValue == value) return;
                OnPropertyChanging(LayerProperties.VisibleName);
                _properties.visible = value;
                OnPropertyChanged(LayerProperties.VisibleName);
                Invalidate();
            }
        }

        /// <summary>
        /// Determines whether a rectangle is fully in bounds or not. This is determined by checking
        /// to make sure the left, top, right, and bottom edges are within bounds.
        /// </summary>
        /// <param name="roi"></param>
        /// <returns></returns>
        private bool IsInBounds(Rectangle roi)
        {
            return ((((roi.Left >= 0 && roi.Top >= 0) && roi.Left < Width) && roi.Top < Height) && roi.Right <= Width) && roi.Bottom <= Height;
        }

        /// <summary>
        /// Implements IThumbnailProvider.RenderThumbnail().
        /// </summary>
        public abstract Surface RenderThumbnail(int maxEdgeLength);

        /// <summary>
        /// Causes the layer to render a given rectangle of interest (roi) to the given destination surface.
        /// </summary>
        /// <param name="args">Contains information about which objects to use for rendering</param>
        /// <param name="roi">The rectangular region to be rendered.</param>
        public void Render(RenderArgs args, Rectangle roi)
        {
            // the bitmap we're rendering to must match the size of the layer we're rendering from
            if (args.Surface.Width != Width || args.Surface.Height != Height)
            {
                throw new ArgumentException();
            }

            // the region of interest can not be out of bounds!
            if (!IsInBounds(roi))
            {
                throw new ArgumentOutOfRangeException("roi");
            }

            RenderImpl(args, roi);
        }

        /// <summary>
        /// Causes the layer to render a given region of interest (roi) to the given destination surface.
        /// </summary>
        /// <param name="args">Contains information about which objects to use for rendering</param>
        /// <param name="roi">The region to be rendered.</param>
        public void Render(RenderArgs args, PdnRegion roi)
        {
            Rectangle roiBounds = roi.GetBoundsInt();

            if (!IsInBounds(roiBounds))
            {
                throw new ArgumentOutOfRangeException("roi");
            }

            Rectangle[] rects = roi.GetRegionScansReadOnlyInt();
            RenderImpl(args, rects);
        }

        public void RenderUnchecked(RenderArgs args, Rectangle[] roi, int startIndex, int length)
        {
            RenderImpl(args, roi, startIndex, length);
        }

        /// <summary>
        /// Override this method to provide your layer's rendering capabilities.
        /// </summary>
        /// <param name="args">Contains information about which objects to use for rendering</param>
        /// <param name="roi">The rectangular region to be rendered.</param>
        protected abstract void RenderImpl(RenderArgs args, Rectangle roi);

        protected void RenderImpl(RenderArgs args, Rectangle[] roi)
        {
            RenderImpl(args, roi, 0, roi.Length);
        }

        protected virtual void RenderImpl(RenderArgs args, Rectangle[] roi, int startIndex, int length)
        {
            for (int i = startIndex; i < startIndex + length; ++i)
            {
                RenderImpl(args, roi[i]);
            }
        }
       
        [field: NonSerialized]
        public event InvalidateEventHandler Invalidated;

        protected virtual void OnInvalidated(InvalidateEventArgs e)
        {
            if (Invalidated != null)
            {
                Invalidated(this, e);
            }
        }

        /// <summary>
        /// Causes the entire layer surface to be invalidated.
        /// </summary>
        public void Invalidate()
        {
            var rect = new Rectangle(0, 0, Width, Height);
            OnInvalidated(new InvalidateEventArgs(rect));
        }

        /// <summary>
        /// Causes a portion of the layer surface to be invalidated.
        /// </summary>
        /// <param name="roi">The region of interest to be invalidated.</param>
        public void Invalidate(PdnRegion roi)
        {
            foreach (Rectangle rect in roi.GetRegionScansReadOnlyInt())
            {
                Invalidate(rect);
            }
        }

        /// <summary>
        /// Causes a portion of the layer surface to be invalidated.
        /// </summary>
        /// <param name="roi">The region of interest to be invalidated.</param>
        public void Invalidate(RectangleF[] roi)
        {
            foreach (RectangleF rectF in roi)
            {
                Invalidate(Rectangle.Truncate(rectF));
            }        
        }

        /// <summary>
        /// Causes a portion of the layer surface to be invalidated.
        /// </summary>
        /// <param name="roi">The rectangle of interest to be invalidated.</param>
        public void Invalidate(Rectangle roi)
        {
            Rectangle rect = Rectangle.Intersect(roi, Bounds);
            // TODO: this is horrible for performance w.r.t. complex invalidation regions. Lots of heap pollution.
            //       fix that!
            OnInvalidated(new InvalidateEventArgs(rect));
        }

        protected Layer(int width, int height)
        {
            _width = width;
            _height = height;
            _properties = new LayerProperties(null, new NameValueCollection(), true, false, 255);
        }

        protected Layer(Layer copyMe)
        {
            _width = copyMe._width;
            _height = copyMe._height;
            _properties = (LayerProperties)copyMe._properties.Clone();
        }

        // TODO: add "name" parameter, keep this for legacy and fill it in with "Background"
        //       goal is to put complete burden of loc on the client
        public static BitmapLayer CreateBackgroundLayer(int width, int height)
        {
            // set colors to 0xffffffff
            // note: we use alpha of 255 here so that "invert colors" works as expected
            // that is, for just 1 layer we invert the initial white->black
            // but on subsequent layers we invert transparent white -> transparent black, which shows up as white for the most part
            var layer = new BitmapLayer(width, height, ColorBgra.White)
                            {
                                Name = PdnResources.GetString("Layer.Background.Name"),
                                _properties = {isBackground = true}
                            };

            // tag it as a background layer

            return layer;
        }

        /// <summary>
        /// This allows a layer to provide a dialog for configuring
        /// the layer's properties.
        /// </summary>
        public abstract PdnBaseForm CreateConfigDialog();

        public abstract object Clone();

        ~Layer()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (disposed) return;
            disposed = true;

            if (disposing)
            {
            }
        }
    }
}
Back to Top