summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.MacOS/Cells/ImageCellRenderer.cs
blob: 8bd767727e981cd48971d56ca873bb89afe275b1 (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
´╗┐using System.ComponentModel;
using System.Threading.Tasks;
using AppKit;
using Foundation;

namespace Xamarin.Forms.Platform.MacOS
{
	public class ImageCellRenderer : TextCellRenderer
	{
		public override NSView GetCell(Cell item, NSView reusableView, NSTableView tv)
		{
			var tvc = reusableView as CellNSView ?? new CellNSView(NSTableViewCellStyle.ImageSubtitle);

			var result = (CellNSView)base.GetCell(item, tvc, tv);

			var imageCell = (ImageCell)item;

			WireUpForceUpdateSizeRequested(item, result, tv);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
			SetImage(imageCell, result);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

			return result;
		}

		protected override async void HandlePropertyChanged(object sender, PropertyChangedEventArgs args)
		{
			var tvc = (CellNSView)sender;
			var imageCell = (ImageCell)tvc.Cell;

			base.HandlePropertyChanged(sender, args);

			if (args.PropertyName == ImageCell.ImageSourceProperty.PropertyName)
				await SetImage(imageCell, tvc);
		}

		static async Task SetImage(ImageCell cell, CellNSView target)
		{
			var source = cell.ImageSource;

			target.ImageView.Image = null;

			IImageSourceHandler handler;

			if (source != null && (handler = Registrar.Registered.GetHandler<IImageSourceHandler>(source.GetType())) != null)
			{
				NSImage uiimage;
				try
				{
					uiimage = await handler.LoadImageAsync(source).ConfigureAwait(false);
				}
				catch (TaskCanceledException)
				{
					uiimage = null;
				}

				NSRunLoop.Main.BeginInvokeOnMainThread(() =>
				{
					target.ImageView.Image = uiimage;
					target.NeedsLayout = true;
				});
			}
			else
				target.ImageView.Image = null;
		}
	}
}