summaryrefslogtreecommitdiff
path: root/ElmSharp/ElmSharp/Image.cs
blob: 6c98cb33cdb06f44994d196163ee81e68686fb8b (plain)
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/*
 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace ElmSharp
{
    /// <summary>
    /// The Image is a widget that allows one to load and display an image file on it,
    /// be it from a disk file or from a memory region.
    /// Inherits Widget
    /// </summary>
    public class Image : Widget
    {
        bool _canScaleUp = true;
        bool _canScaleDown = true;
        SmartEvent _clicked;
        Color _color = Color.Default;

        /// <summary>
        /// Creates and initializes a new instance of Image class.
        /// </summary>
        /// <param name="parent">The parent is a given container which will be attached by Image as a child. It's <see cref="EvasObject"/> type.</param>
        public Image(EvasObject parent) : base(parent)
        {
            _clicked = new SmartEvent(this, "clicked");
            _clicked.On += (s, e) => Clicked?.Invoke(this, EventArgs.Empty);
        }

        /// <summary>
        /// Clicked will be triggered when the image is clicked.
        /// </summary>
        public event EventHandler Clicked;

        /// <summary>
        /// LoadingCompleted will be triggered when the image is loaded completely.
        /// </summary>
        public event EventHandler LoadingCompleted;

        /// <summary>
        /// Clicked will be triggered when the image is fail to load.
        /// </summary>
        public event EventHandler LoadingFailed;

        /// <summary>
        /// Gets the file that is used as an image.
        /// </summary>
        public string File
        {
            get
            {
                return Interop.Elementary.elm_image_file_get(RealHandle);
            }
        }

        /// <summary>
        /// Sets or gets the smooth effect for an image.
        /// </summary>
        public bool IsSmooth
        {
            get
            {
                return Interop.Elementary.elm_image_smooth_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_smooth_set(RealHandle, value);
            }
        }

        /// <summary>
        /// Sets or gets whether scaling is disabled on the object.
        /// </summary>
        public bool IsScaling
        {
            get
            {
                return !Interop.Elementary.elm_image_no_scale_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_no_scale_set(RealHandle, !value);
            }
        }

        /// <summary>
        /// Sets or gets whether the object is down resizeable.
        /// </summary>
        public bool CanScaleDown
        {
            get
            {
                return _canScaleDown;
            }
            set
            {
                _canScaleDown = value;
                Interop.Elementary.elm_image_resizable_set(RealHandle, _canScaleUp, _canScaleDown);
            }
        }

        /// <summary>
        /// Sets or gets whether the object is up resizeable.
        /// </summary>
        public bool CanScaleUp
        {
            get
            {
                return _canScaleUp;
            }
            set
            {
                _canScaleUp = value;
                Interop.Elementary.elm_image_resizable_set(RealHandle, _canScaleUp, _canScaleDown);
            }
        }

        /// <summary>
        /// Sets or gets whether the image fills the entire object area, when keeping the aspect ratio.
        /// </summary>
        public bool CanFillOutside
        {
            get
            {
                return Interop.Elementary.elm_image_fill_outside_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_fill_outside_set(RealHandle, value);
            }
        }

        /// <summary>
        /// Sets or gets the prescale size for the image.
        /// </summary>
        public int PrescaleSize
        {
            get
            {
                return Interop.Elementary.elm_image_prescale_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_prescale_set(RealHandle, value);
            }
        }

        /// <summary>
        /// Sets or gets whether the original aspect ratio of the image should be kept on resize.
        /// </summary>
        public bool IsFixedAspect
        {
            get
            {
                return Interop.Elementary.elm_image_aspect_fixed_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_aspect_fixed_set(RealHandle, value);
            }
        }

        /// <summary>
        /// Sets or gets whether an image object (which supports animation) is to animate itself.
        /// </summary>
        public bool IsAnimated
        {
            get
            {
                return Interop.Elementary.elm_image_animated_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_animated_set(RealHandle, value);
            }
        }

        /// <summary>
        /// Gets whether an image object supports animation.
        /// </summary>
        public bool IsAnimatedAvailable
        {
            get
            {
                return Interop.Elementary.elm_image_animated_available_get(RealHandle);
            }
        }

        /// <summary>
        /// Sets or gets whether an image object is under animation.
        /// </summary>
        public bool IsAnimationPlaying
        {
            get
            {
                return Interop.Elementary.elm_image_animated_play_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_animated_play_set(RealHandle, value);
            }
        }

        /// <summary>
        /// Sets or gets whether the image is 'editable'.
        /// </summary>
        public bool IsEditable
        {
            get
            {
                return Interop.Elementary.elm_image_editable_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_editable_set(RealHandle, value);
            }
        }

        /// <summary>
        /// Gets the current size of the image.
        /// </summary>
        public Size ObjectSize
        {
            get
            {
                Interop.Elementary.elm_image_object_size_get(RealHandle, out int w, out int h);
                return new Size(w, h);
            }
        }

        /// <summary>
        /// Sets or gets whether alpha channel data is being used on the given image object.
        /// </summary>
        public bool IsOpaque
        {
            get
            {
                IntPtr evasObj = Interop.Elementary.elm_image_object_get(RealHandle);
                if (evasObj != IntPtr.Zero)
                {
                    return !Interop.Evas.evas_object_image_alpha_get(evasObj);
                }
                return false;
            }
            set
            {
                IntPtr evasObj = Interop.Elementary.elm_image_object_get(RealHandle);
                if (evasObj != IntPtr.Zero)
                {
                    Interop.Evas.evas_object_image_alpha_set(evasObj, !value);
                }
            }
        }

        /// <summary>
        /// Sets or gets the image orientation.
        /// </summary>
        public ImageOrientation Orientation
        {
            get
            {
                return (ImageOrientation)Interop.Elementary.elm_image_orient_get(RealHandle);
            }
            set
            {
                Interop.Elementary.elm_image_orient_set(RealHandle, (int)value);
            }
        }

        /// <summary>
        /// Sets or gets the image color
        /// </summary>
        public override Color Color
        {
            get
            {
                return _color;
            }
            set
            {
                IntPtr evasObj = Interop.Elementary.elm_image_object_get(RealHandle);
                if (evasObj != IntPtr.Zero)
                {
                    if (value.IsDefault)
                    {
                        // Currently, we assume the Image.Color property as a blending color (actually, multiply blending).
                        // Thus we are using Color.White (255,255,255,255) as a default color to ensure original image color. (255/255 * original = original)
                        Interop.Evas.evas_object_color_set(evasObj, 255, 255, 255, 255);
                    }
                    else
                    {
                        Interop.Evas.SetPremultipliedColor(evasObj, value.R, value.G, value.B, value.A);
                    }
                }
                _color = value;
            }
        }

        /// <summary>
        /// Sets the background color
        /// </summary>
        public override Color BackgroundColor
        {
            set
            {
                if (value.IsDefault)
                {
                    SetPartColor("bg", Color.Transparent);
                }
                else
                {
                    SetPartColor("bg", value);
                }
                _backgroundColor = value;
            }
        }

        /// <summary>
        /// Sets the dimensions for an image object's border, a region which is not scaled together with its center ever.
        /// </summary>
        /// <param name="left">The border's left width</param>
        /// <param name="right">The border's right width</param>
        /// <param name="top">The border's top width</param>
        /// <param name="bottom">The border's bottom width</param>
        public void SetBorder(int left, int right, int top, int bottom)
        {
            IntPtr evasObj = Interop.Elementary.elm_image_object_get(RealHandle);
            Interop.Evas.evas_object_image_border_set(evasObj, left, right, top, bottom);
        }

        /// <summary>
        /// Sets or gets if the center part of the given image object (not the border) should be drawn.
        /// </summary>
        /// <remarks>
        /// When rendering, the image may be scaled to fit the size of the image object.
        /// This function sets if the center part of the scaled image is to be drawn or left completely blank, or forced to be solid.
        /// Very useful for frames and decorations.
        /// </remarks>
        public ImageBorderFillMode BorderCenterFillMode
        {
            get
            {
                IntPtr evasObj = Interop.Elementary.elm_image_object_get(RealHandle);
                return (ImageBorderFillMode)Interop.Evas.evas_object_image_border_center_fill_get(evasObj);
            }
            set
            {
                IntPtr evasObj = Interop.Elementary.elm_image_object_get(RealHandle);
                Interop.Evas.evas_object_image_border_center_fill_set(evasObj, (int)value);
            }
        }

        /// <summary>
        /// Sets the file that is used as the image's source.
        /// </summary>
        /// <param name="file">The path to the file that is used as an image source</param>
        /// <returns>(true = success, false = error)</returns>
        public bool Load(string file)
        {
            if (file == null)
                throw new ArgumentNullException("file");

            Interop.Elementary.elm_image_async_open_set(RealHandle, false);
            Interop.Elementary.elm_image_preload_disabled_set(RealHandle, true);
            return Interop.Elementary.elm_image_file_set(RealHandle, file, null);
        }

        /// <summary>
        /// Sets the uri that is used as the image's source.
        /// </summary>
        /// <param name="uri">The uri to the file that is used as an image source</param>
        /// <returns>(true = success, false = error)</returns>
        public bool Load(Uri uri)
        {
            if (uri == null)
                throw new ArgumentNullException("uri");

            return Load(uri.IsFile ? uri.LocalPath : uri.AbsoluteUri);
        }

        /// <summary>
        /// Sets a location in the memory to be used as an image object's source bitmap.
        /// </summary>
        /// <remarks>
        /// This function is handy when the contents of an image file are mapped into the memory, for example.
        /// The format string should be something like "png", "jpg", "tga", "tiff", "bmp" etc, when provided (null, on the contrary).
        /// This improves the loader performance as it tries the "correct" loader first, before trying a range of other possible loaders until one succeeds.
        /// </remarks>
        /// <param name="img">The binary data that is used as an image source</param>
        /// <param name="size">The size of the binary data blob img</param>
        /// <returns>(true = success, false = error)</returns>
        [Obsolete("This method will be removed. Use Load(Stream stream) instead.")]
        public unsafe bool Load(byte* img, long size)
        {
            if (img == null)
                throw new ArgumentNullException("img");

            Interop.Elementary.elm_image_async_open_set(RealHandle, false);
            Interop.Elementary.elm_image_preload_disabled_set(RealHandle, true);
            return Interop.Elementary.elm_image_memfile_set(RealHandle, img, size, IntPtr.Zero, IntPtr.Zero);
        }

        /// <summary>
        /// Sets the stream that is used as the image's source.
        /// </summary>
        /// <param name="stream">The stream that is used as an image source</param>
        /// <returns>(true = success, false = error)</returns>
        public bool Load(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            Interop.Elementary.elm_image_async_open_set(RealHandle, false);
            Interop.Elementary.elm_image_preload_disabled_set(RealHandle, true);
            MemoryStream memstream = new MemoryStream();
            stream.CopyTo(memstream);
            unsafe
            {
                byte[] dataArr = memstream.ToArray();
                fixed (byte* data = &dataArr[0])
                {
                    return Interop.Elementary.elm_image_memfile_set(RealHandle, data, dataArr.Length, IntPtr.Zero, IntPtr.Zero);
                }
            }
        }

        /// <summary>
        /// Sets the file that is used as the image's source with async.
        /// </summary>
        /// <param name="file">The path to the file that is used as an image source</param>
        /// <param name="cancellationToken">cancellation token</param>
        /// <returns>(true = success, false = error)</returns>
        public Task<bool> LoadAsync(string file, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (file == null)
                throw new ArgumentNullException("file");

            Interop.Elementary.elm_image_async_open_set(RealHandle, true);
            Interop.Elementary.elm_image_preload_disabled_set(RealHandle, false);

            var tcs = new TaskCompletionSource<bool>();

            cancellationToken.Register(() =>
            {
                if (tcs != null && !tcs.Task.IsCompleted)
                {
                    tcs.SetCanceled();
                }
            });

            SmartEvent loadReady = new SmartEvent(this, RealHandle, "load,ready");
            loadReady.On += (s, e) =>
            {
                loadReady.Dispose();
                LoadingCompleted?.Invoke(this, EventArgs.Empty);
                if (tcs != null && !tcs.Task.IsCompleted)
                {
                    tcs.SetResult(true);
                }
            };

            SmartEvent loadError = new SmartEvent(this, RealHandle, "load,error");
            loadError.On += (s, e) =>
            {
                loadError.Dispose();
                LoadingFailed?.Invoke(this, EventArgs.Empty);
                if (tcs != null && !tcs.Task.IsCompleted)
                {
                    tcs.SetResult(false);
                }
            };

            bool ret = Interop.Elementary.elm_image_file_set(RealHandle, file, null);
            if (!ret)
            {
                throw new InvalidOperationException("Failed to set file to Image");
            }

            return tcs.Task;
        }

        /// <summary>
        /// Sets the uri that is used as the image's source with async.
        /// </summary>
        /// <param name="uri">The uri to the file that is used as an image source</param>
        /// <param name="cancellationToken">cancellation token</param>
        /// <returns>(true = success, false = error)</returns>
        public Task<bool> LoadAsync(Uri uri, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (uri == null)
                throw new ArgumentNullException("uri");

            return LoadAsync(uri.IsFile ? uri.LocalPath : uri.AbsoluteUri, cancellationToken);
        }

        /// <summary>
        /// Sets the stream that is used as the image's source with async.
        /// </summary>
        /// <param name="stream">The stream that is used as an image source</param>
        /// <param name="cancellationToken">cancellation token</param>
        /// <returns>(true = success, false = error)</returns>
        public async Task<bool> LoadAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            Interop.Elementary.elm_image_async_open_set(RealHandle, true);
            Interop.Elementary.elm_image_preload_disabled_set(RealHandle, false);

            var tcs = new TaskCompletionSource<bool>();

            cancellationToken.Register(() =>
            {
                if (tcs != null && !tcs.Task.IsCompleted)
                {
                    tcs.SetCanceled();
                }
            });

            SmartEvent loadReady = new SmartEvent(this, Handle, "load,ready");
            loadReady.On += (s, e) =>
            {
                loadReady.Dispose();
                LoadingCompleted?.Invoke(this, EventArgs.Empty);
                if (tcs != null && !tcs.Task.IsCompleted)
                {
                    tcs.SetResult(true);
                }
            };

            SmartEvent loadError = new SmartEvent(this, Handle, "load,error");
            loadError.On += (s, e) =>
            {
                loadError.Dispose();
                LoadingFailed?.Invoke(this, EventArgs.Empty);
                if (tcs != null && !tcs.Task.IsCompleted)
                {
                    tcs.SetResult(false);
                }
            };

            MemoryStream memstream = new MemoryStream();
            await stream.CopyToAsync(memstream);

            unsafe
            {
                byte[] dataArr = memstream.ToArray();
                fixed (byte* data = &dataArr[0])
                {
                    bool ret = Interop.Elementary.elm_image_memfile_set(RealHandle, data, dataArr.Length, IntPtr.Zero, IntPtr.Zero);
                    if (!ret)
                    {
                        return false;
                    }
                }
            }

            return await tcs.Task;
        }

        /// <summary>
        /// Sets the color of color class for a given widget.
        /// </summary>
        /// <param name="part">The name of color class.</param>
        /// <param name="color">The struct of color</param>
        public override void SetPartColor(string part, Color color)
        {
            Interop.Elementary.elm_object_color_class_color_set(Handle, part, color.R * color.A / 255,
                                                                              color.G * color.A / 255,
                                                                              color.B * color.A / 255,
                                                                              color.A);
        }

        /// <summary>
        /// Gets the color of color class for a given widget.
        /// </summary>
        /// <param name="part">The name of color class.</param>
        /// <returns>color object</returns>
        public override Color GetPartColor(string part)
        {
            Interop.Elementary.elm_object_color_class_color_get(Handle, part, out int r, out int g, out int b, out int a);
            return new Color((int)(r / (a / 255.0)), (int)(g / (a / 255.0)), (int)(b / (a / 255.0)), a);
        }

        /// <summary>
        /// Sets the content at a part of a given container widget.
        /// </summary>
        /// <param name="parent">The parent is a given container which will be attached by Image as a child. It's <see cref="EvasObject"/> type.</param>
        /// <returns>The new object, otherwise null if it cannot be created</returns>
        protected override IntPtr CreateHandle(EvasObject parent)
        {
            IntPtr handle = Interop.Elementary.elm_layout_add(parent);
            Interop.Elementary.elm_layout_theme_set(handle, "layout", "background", "default");

            RealHandle = Interop.Elementary.elm_image_add(handle);
            Interop.Elementary.elm_object_part_content_set(handle, "elm.swallow.content", RealHandle);

            return handle;
        }
    }

    /// <summary>
    /// Enumeration for the fill mode of image border
    /// </summary>
    public enum ImageBorderFillMode
    {
        /// <summary>
        /// None mode of image border
        /// </summary>
        None,
        /// <summary>
        /// Default mode of image border
        /// </summary>
        Default,
        /// <summary>
        /// Solid mode of image border
        /// </summary>
        Solid,
    }

    /// <summary>
    /// Enumeration for the possible orientation options
    /// </summary>
    public enum ImageOrientation : int
    {
        /// <summary>
        /// No orientation change
        /// </summary>
        None = 0,
        /// <summary>
        /// Rotate 90 degrees clockwise
        /// </summary>
        Rotate90,
        /// <summary>
        /// Rotate 180 degrees clockwise
        /// </summary>
        Rotate180,
        /// <summary>
        /// Rotate 90 degrees counter-clockwise (i.e. 270 degrees clockwise)
        /// </summary>
        Rotate270,
        /// <summary>
        /// Flip image horizontally
        /// </summary>
        FlipHorizontal,
        /// <summary>
        /// Flip image vertically
        /// </summary>
        FlipVertical,
        /// <summary>
        /// Flip the image along the y = (width - x) line (bottom-left to top-right)
        /// </summary>
        FlipTranspose,
        /// <summary>
        /// Flip the image along the y = x line (top-left to bottom-right)
        /// </summary>
        FlipTransverse
    }
}