예제 #1
1
        public Bitmap(NSImage sourceImage)
        {
            Width = (int)sourceImage.CGImage.Width;
            Height = (int)sourceImage.CGImage.Height;
            _colors = new Color[Width * Height];

            var rawData = new byte[Width * Height * 4];
            var bytesPerPixel = 4;
            var bytesPerRow = bytesPerPixel * Width;
            var bitsPerComponent = 8;

            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
            {
                using (var context = new CGBitmapContext(rawData, Width, Height, bitsPerComponent, bytesPerRow, colorSpace, CGBitmapFlags.ByteOrder32Big | CGBitmapFlags.PremultipliedLast))
                {
                    context.DrawImage(new CGRect(0, 0, Width, Height), sourceImage.CGImage);

                    for (int y = 0; y < Height; y++)
                    {
                        for (int x = 0; x < Width; x++)
                        {
                            var i = bytesPerRow * y + bytesPerPixel * x;   
                            byte red = rawData[i + 0];
                            byte green = rawData[i + 1];
                            byte blue = rawData[i + 2];
                            byte alpha = rawData[i + 3];
                            SetPixel(x, y, Color.FromArgb(alpha, red, green, blue));
                        }
                    }
                }
            }
        }
        public override void AwakeFromNib ()
        {
            base.AwakeFromNib ();
            //load resources
            secretKeysIcon = NSImage.ImageNamed ("SecretKeys16.png");
            privateEntityIcon = NSImage.ImageNamed ("Privateentity_16x16.png");
            storeIcon = NSImage.ImageNamed ("certificate-store.png");
            storesIcon = NSImage.ImageNamed ("vecsStore_16x16.png");
            trustedCertsIcon = NSImage.ImageNamed ("TrustedCerts.png");
            genericIcon = NSImage.ImageNamed ("object.png");


            SetToolBarState (false);
            (NSApplication.SharedApplication.Delegate as AppDelegate).OpenConnectionMenuItem.Hidden = true;

            //Load SplitView
            splitViewController = new SplitViewMMCController ();
            splitViewController.MainOutlineView = new OutlineView ();
            splitViewController.MainTableView = new VMCertStoreTableView ();
            this.CustomView.AddSubview (splitViewController.View);

            //Notifications for OutlineView and Tableview to reload
            NSNotificationCenter.DefaultCenter.AddObserver ((NSString)"ReloadOutlineView", ReloadOutlineView);
            NSNotificationCenter.DefaultCenter.AddObserver ((NSString)"ReloadTableView", ReloadTableView);
            NSNotificationCenter.DefaultCenter.AddObserver ((NSString)"ReloadServerData", RefreshDataFromServer);
        }
예제 #3
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			// Populate Source List
			SourceList.Initialize ();

			var TableViews = new SourceListItem ("Table Based Views");
			TableViews.AddItem ("Table View", "calendar.png", () => {
				PerformSegue("TableSegue", this);
			});
			TableViews.AddItem ("Outline View", "calendar.png", () => {
				PerformSegue("OutlineSegue", this);
			});
			SourceList.AddItem (TableViews);

			var ImageViews = new SourceListItem ("Photos");
			ImageViews.AddItem ("First Person", "film-roll.png", () => {
				Picture = NSImage.ImageNamed("person01.jpg");
				PerformSegue("PictureSegue", this);
			});
			ImageViews.AddItem ("Second Person", "film-roll.png", () => {
				Picture = NSImage.ImageNamed("person02.jpg");
				PerformSegue("PictureSegue", this);
			});
			ImageViews.AddItem ("Third Person", "film-roll.png", () => {
				Picture = NSImage.ImageNamed("person03.jpg");
				PerformSegue("PictureSegue", this);
			});
			SourceList.AddItem (ImageViews);

			// Display Source List
			SourceList.ReloadData();
			SourceList.ExpandItem (null, true);
		}
예제 #4
0
		void GetImagaDataFromPath (string path)
		{
			NSImage src;
			CGImage image;
			CGContext context = null;

			src = new NSImage (path);

			var rect = CGRect.Empty;
			image = src.AsCGImage (ref rect, null, null);
			width =(int)image.Width;
			height = (int) image.Height;

			data = new byte[width * height * 4];

			CGImageAlphaInfo ai = CGImageAlphaInfo.PremultipliedLast;

			context = new CGBitmapContext (data, width, height, 8, 4 * width, image.ColorSpace, ai);

			// Core Graphics referential is upside-down compared to OpenGL referential
			// Flip the Core Graphics context here
			// An alternative is to use flipped OpenGL texture coordinates when drawing textures
			context.TranslateCTM (0, height);
			context.ScaleCTM (1, -1);

			// Set the blend mode to copy before drawing since the previous contents of memory aren't used. 
			// This avoids unnecessary blending.
			context.SetBlendMode (CGBlendMode.Copy);

			context.DrawImage (new CGRect (0, 0, width, height), image);
		}
예제 #5
0
		async Task LoadImage ()
		{
			NSData d = await Task.Factory.StartNew<NSData> (() => NSData.FromUrl (new NSUrl (Tweet.Image)));
			NSImage i = new NSImage (d);
			if (!cachedImages.ContainsKey (Tweet.Image))
				cachedImages.Add (Tweet.Image, i);
			Image.Image = i;
		}
예제 #6
0
		public void ImageOne (NSObject sender)
		{
			// Load image
			Image = NSImage.ImageNamed ("Image01.jpg");

			// Set image info
			Document.Info.Name = "city";
			Document.Info.ImageType = "jpg";
		}
예제 #7
0
		public void ImageTwo (NSObject sender)
		{
			// Load image
			Image = NSImage.ImageNamed ("Image02.jpg");

			// Set image info
			Document.Info.Name = "theater";
			Document.Info.ImageType = "jpg";
		}
예제 #8
0
		void UpdateIcons (object sender = null, EventArgs e = null)
		{
			stopIcon = MultiResImage.CreateMultiResImage ("stop", "");
			continueIcon = MultiResImage.CreateMultiResImage ("continue", "");
			buildIcon = MultiResImage.CreateMultiResImage ("build", "");

			// We can use Template images supported by NSButton, thus no reloading
			// on theme change is required.
			stopIcon.Template = continueIcon.Template = buildIcon.Template = true;
		}
 public override void DrawImage(NSImage image, CGRect frame, NSView controlView)
 {
     NSGraphicsContext.GlobalSaveGraphicsState ();
     {
         this.shadow.Set ();
         CGRect imgRect = frame.Inset ((frame.Size.Width - image.Size.Width) / 2.0f, (frame.Size.Height - image.Size.Height) / 2.0f);
         image.Flipped = true;
         image.DrawInRect (imgRect, CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
     }
     NSGraphicsContext.GlobalRestoreGraphicsState ();
 }
예제 #10
0
		public override void DraggingEnded (NSDraggingInfo sender)
		{
			// Update the dropped item counter and display
			dragCount++;
			UpdateDragCount ();

			// Pull the individual items from the drag package and write them to the console
			var i = new NSImage (sender.DraggingPasteboard.GetDataForType (NSPasteboard.NSTiffType));
			string s = NSString.FromData (sender.DraggingPasteboard.GetDataForType (NSPasteboard.NSStringType), NSStringEncoding.UTF8);
			Console.WriteLine ("String Data: {0}", s);
			Console.WriteLine ("Image Data: {0}", i.Size);
		}
예제 #11
0
 public static CGImage CreateCGImageFromFile(NSString path)
 {
     #if __IOS__
     var image = UIImage.FromFile (path);
     if (image == null)
         Console.WriteLine ("UIImage imageWithContentsOfFile failed on file {0}", path);
     return image.CGImage;
     #else
     var image = new NSImage (path);
     return image.CGImage;
     #endif
 }
예제 #12
0
		public static NSImage CreateMultiResImage (string filename, string style)
		{
			var image = new NSImage ();

			var image1x = NSImageFromResource (MakeResName (filename, style));
			var image2x = NSImageFromResource (MakeResName (filename, style, true));

			if (image1x != null) {
				image.AddRepresentations (image1x.Representations ());
			}

			if (image2x != null) {
				image.AddRepresentations (image2x.Representations ());
			}

			image.Size = new CoreGraphics.CGSize (0, 0);
			return image;
		}
예제 #13
0
		static NSImage Render (string value)
		{
			NSImage image = null;

			NSApplication.SharedApplication.InvokeOnMainThread (() =>
			{
				NSString text = new NSString (string.IsNullOrEmpty (value) ? " " : value);
				NSFont font = NSFont.FromFontName ("Arial", 20);
				var fontDictionary = NSDictionary.FromObjectsAndKeys (new NSObject[] { font, NSColor.Red }, new NSObject[] { NSStringAttributeKey.Font, NSStringAttributeKey.ForegroundColor });
				CGSize size = text.StringSize (fontDictionary);

				image = new NSImage (new CGSize (size));

				image.LockFocus ();
				text.DrawString (new CGPoint (0, 0), fontDictionary);
				image.UnlockFocus ();
			});

			return image;
		}
예제 #14
0
		public static Gdk.Pixbuf GetPixbufFromNSImage (NSImage icon, int width, int height)
		{
			var rect = new CGRect (0, 0, width, height);

			var rep = icon.BestRepresentation (rect, null, null);
			var bitmap = rep as NSBitmapImageRep;
			try {
				if (bitmap == null) {
					if (rep != null)
						rep.Dispose ();
					using (var cgi = icon.AsCGImage (ref rect, null, null)) {
						if (cgi == null)
							return null;
						bitmap = new NSBitmapImageRep (cgi);
					}
				}
				return GetPixbufFromNSBitmapImageRep (bitmap, width, height);
			} finally {
				if (bitmap != null)
					bitmap.Dispose ();
			}
		}
예제 #15
0
        public override void MouseDragged(NSEvent theEvent)
        {
            base.MouseDragged(theEvent);
            CGPoint down = mMouseDownEvent.LocationInWindow;
            CGPoint drag = theEvent.LocationInWindow;
            // Calculate the distance between this dragging position and the mouse down position
            double distance = Math.Sqrt( Math.Pow( down.X - drag.X ,2) + Math.Pow(down.Y - drag.Y, 2) );
            // Don't do too often
            if (distance < 3) {
                return;
            }

            // And not if there is no string to drag
            if (mLetter.Length == 0) {
                return;
            }

            // Get the size of the string
            CGSize size = mLetter.StringSize(mTextAttributes);

            // Create the image that will be dragged
            NSImage anImage = new NSImage(size);

            // Create a rect in which you will draw the letter
            // in the image
            CGRect imageBounds = CGRect.Empty;
            imageBounds.Location = new CGPoint(0.0f, 0.0f);
            imageBounds.Size = size;

            // Draw the letter on the image
            anImage.LockFocus();
            DrawStringCenteredInRectangle(mLetter, imageBounds);
            anImage.UnlockFocus();

            // Get the location of the mouse down event
            CGPoint p = this.ConvertPointFromView(down, null);

            // Drag from the center of theimage
            p = new CGPoint(p.X - size.Width/2, p.Y - size.Height/2);

            // Get the pasteboard
            NSPasteboard pb = NSPasteboard.FromName(NSPasteboard.NSDragPasteboardName);

            // Put the string and the pdf image in the pasteboard
            WriteToPasteBoard(pb);

            // Start the drag - deprecated, should use BeginDraggingSession, but need to wait for new Xam.Mac. Bug filed. #26941
            this.DragImage(anImage, p,CGSize.Empty, mMouseDownEvent, pb, this, true);
        }
예제 #16
0
		public IImage ImageFromFile (string filename)
		{
#if MONOMAC
			var img = new NSImage ("Images/" + filename);
			var rect = new NativeRect (NativePoint.Empty, img.Size);
			return new UIKitImage (img.AsCGImage (ref rect, NSGraphicsContext.CurrentContext, new Foundation.NSDictionary ()));
#else
			return new UIKitImage (UIImage.FromFile ("Images/" + filename).CGImage);
#endif
		}
예제 #17
0
		/// <summary>
		/// Adds the item.
		/// </summary>
		/// <param name="title">Title.</param>
		/// <param name="icon">Icon.</param>
		/// <param name="tag">Tag.</param>
		public void AddItem(string title, NSImage icon, string tag) {
			_items.Add (new SourceListItem (title, icon, tag));
		}
예제 #18
0
        /// <summary>
        /// Update GUI data according to ModelView
        /// </summary>
        private void UpdateGuiData()
        {
            if (!NSThread.IsMain)
            {
                InvokeOnMainThread(() => UpdateGuiData());
                return;
            }

            if (ViewLoaded != true || __MainViewModel == null)
            {
                return;
            }

            UpdateSessionStatusInfo(__MainViewModel.AppState.SessionStatusInfo);

            GuiPauseButton.Hidden       = true;
            GuiPauseLeftTimeText.Hidden = true;

            switch (__MainViewModel.ConnectionState)
            {
            case ServiceState.Connected:

                if (__MainViewModel.PauseStatus != MainViewModel.PauseStatusEnum.Resumed)
                {
                    switch (__MainViewModel.PauseStatus)
                    {
                    case MainViewModel.PauseStatusEnum.Pausing:
                        StopAllAnimations();
                        ShowDisconnectingAnimation(true);
                        __LastAnimation = AnimationType.Disconnecting;
                        break;

                    case MainViewModel.PauseStatusEnum.Resuming:
                        if (__LastAnimation == null || __LastAnimation != AnimationType.Connecting)
                        {
                            StopAllAnimations();
                            ShowConnectingAnimation(true);
                            __LastAnimation = AnimationType.Connecting;
                        }
                        break;

                    case MainViewModel.PauseStatusEnum.Paused:
                        GuiPauseButton.Image        = Colors.IsDarkMode ? NSImage.ImageNamed("buttonStopDark") : NSImage.ImageNamed("buttonStopLight");
                        GuiPauseButton.ToolTip      = "Stop";
                        GuiPauseButton.Hidden       = false;
                        GuiPauseLeftTimeText.Hidden = false;

                        StopAllAnimations();
                        ShowDisconnectedAnimation(true);
                        __LastAnimation = AnimationType.Disconnected;
                        break;
                    }
                }
                else
                {
                    GuiPauseButton.Image   = Colors.IsDarkMode ? NSImage.ImageNamed("buttonPauseDark") : NSImage.ImageNamed("buttonPauseLight");
                    GuiPauseButton.ToolTip = LocalizedStrings.Instance.LocalizedString("ToolTip_PauseBtn");
                    GuiPauseButton.Hidden  = false;

                    StopAllAnimations();
                    ShowConnectedAnimation();
                    __LastAnimation = AnimationType.Connected;
                }
                break;

            case ServiceState.Disconnected:
                if (__LastAnimation == null || __LastAnimation != AnimationType.Disconnected)
                {
                    StopAllAnimations();
                    ShowDisconnectedAnimation(false);
                    __LastAnimation = AnimationType.Disconnected;
                }
                else
                {
                    UpdateDisconnectedUITheme(false);
                }
                break;

            case ServiceState.Connecting:
            case ServiceState.ReconnectingOnService:
            case ServiceState.ReconnectingOnClient:
                if (__LastAnimation == null || __LastAnimation != AnimationType.Connecting)
                {
                    StopAllAnimations();
                    ShowConnectingAnimation();
                    __LastAnimation = AnimationType.Connecting;
                }
                break;

            case ServiceState.CancellingConnection:
            case ServiceState.Disconnecting:
                if (__LastAnimation == null || __LastAnimation != AnimationType.Disconnecting)
                {
                    StopAllAnimations();
                    ShowDisconnectingAnimation();
                    __LastAnimation = AnimationType.Disconnecting;
                }
                break;

            case ServiceState.Uninitialized:
                StopAllAnimations();
                // TODO: how to process this stage ???
                GuiConnectButtonImage.Hidden = true;
                __LastAnimation = null;
                return;
            }
        }
예제 #19
0
        void UpdateViewMetrics()
        {
            viewMetrics.RulersPanelHeight           = (int)searchTextBoxPlaceholder.Frame.Bottom;
            viewMetrics.ActivitiesViewWidth         = (int)activitiesView.Bounds.Width;
            viewMetrics.ActivitiesViewHeight        = (int)activitiesView.Bounds.Height;
            viewMetrics.ActivitesCaptionsViewWidth  = (int)captionsView.Bounds.Width;
            viewMetrics.ActivitesCaptionsViewHeight = (int)captionsView.Bounds.Height;
            viewMetrics.NavigationPanelWidth        = (int)navigatorView.Bounds.Width;
            viewMetrics.NavigationPanelHeight       = (int)navigatorView.Bounds.Height;

            if (viewMetrics.LineHeight == 0)              // very first update
            {
                var sysFont    = NSFont.SystemFontOfSize(NSFont.SystemFontSize);
                var normalFont = new LJD.Font(sysFont.FamilyName, (float)NSFont.SystemFontSize);
                var smallFont  = new LJD.Font(sysFont.FamilyName, (float)NSFont.SmallSystemFontSize);

                using (var g = new LJD.Graphics())
                    viewMetrics.LineHeight = (int)g.MeasureString("ABC012", normalFont).Height;

                viewMetrics.ActivitesCaptionsFont  = normalFont;
                viewMetrics.ActivitesCaptionsBrush = new LJD.Brush(Color.Black);

                var selectedLineColor = Color.FromArgb(187, 196, 221);
                viewMetrics.SelectedLineBrush = new LJD.Brush(selectedLineColor);

                viewMetrics.RulerLinePen   = new LJD.Pen(Color.LightGray, 1);
                viewMetrics.RulerMarkFont  = smallFont;
                viewMetrics.RulerMarkBrush = new LJD.Brush(Color.Black);

                viewMetrics.ActivitiesTopBoundPen = new LJD.Pen(Color.Gray, 1);

                viewMetrics.ProcedureBrush         = new LJD.Brush(Color.LightBlue);
                viewMetrics.LifetimeBrush          = new LJD.Brush(Color.LightGreen);
                viewMetrics.NetworkMessageBrush    = new LJD.Brush(Color.LightSalmon);
                viewMetrics.UnknownActivityBrush   = new LJD.Brush(Color.LightGray);
                viewMetrics.MilestonePen           = new LJD.Pen(Color.FromArgb(180, Color.SteelBlue), 3);
                viewMetrics.ActivityBarBoundsPen   = new LJD.Pen(Color.Gray, 0.5f);
                viewMetrics.ActivitiesConnectorPen = new LJD.Pen(Color.DarkGray, 1, new [] { 1f, 1f });

                viewMetrics.UserEventPen             = new LJD.Pen(Color.Salmon, 2);
                viewMetrics.EventRectBrush           = new LJD.Brush(Color.Salmon);
                viewMetrics.EventRectPen             = new LJD.Pen(Color.Gray, 1);
                viewMetrics.EventCaptionBrush        = new LJD.Brush(Color.Black);
                viewMetrics.EventCaptionFont         = smallFont;
                viewMetrics.ActionLebelHeight        = 17;
                viewMetrics.EventCaptionStringFormat = new LJD.StringFormat(StringAlignment.Center, StringAlignment.Far);
                viewMetrics.ActionCaptionFont        = smallFont;

                viewMetrics.BookmarkPen  = new LJD.Pen(Color.FromArgb(0x5b, 0x87, 0xe0), 1);
                viewMetrics.BookmarkIcon = new LJD.Image(NSImage.ImageNamed("TimelineBookmark.png"));
                viewMetrics.UserIcon     = new LJD.Image(NSImage.ImageNamed("UserAction.png"));
                viewMetrics.APIIcon      = new LJD.Image(NSImage.ImageNamed("APICall.png"));

                viewMetrics.FocusedMessageLineTop = new LJD.Image(NSImage.ImageNamed("FocusedMsgSlaveVert.png"));
                viewMetrics.FocusedMessagePen     = new LJD.Pen(Color.Blue, 1);

                viewMetrics.MeasurerTop          = 25;
                viewMetrics.MeasurerPen          = new LJD.Pen(Color.DarkGreen, 1f, new[] { 4f, 2f });
                viewMetrics.MeasurerTextFont     = smallFont;
                viewMetrics.MeasurerTextBrush    = new LJD.Brush(Color.Black);
                viewMetrics.MeasurerTextBoxBrush = new LJD.Brush(Color.White);
                viewMetrics.MeasurerTextBoxPen   = new LJD.Pen(Color.DarkGreen, 1f);
                viewMetrics.MeasurerTextFormat   = new LJD.StringFormat(StringAlignment.Center, StringAlignment.Center);

                viewMetrics.NavigationPanel_InvisibleBackground = new LJD.Brush(Color.FromArgb(235, 235, 235));
                viewMetrics.NavigationPanel_VisibleBackground   = new LJD.Brush(Color.White);
                viewMetrics.VisibleRangePen    = new LJD.Pen(Color.Gray, 1f);
                viewMetrics.SystemControlBrush = viewMetrics.NavigationPanel_InvisibleBackground;

                viewMetrics.ActivityBarRectPaddingY    = 5;
                viewMetrics.TriggerLinkWidth           = 8;
                viewMetrics.DistnanceBetweenRulerMarks = 40;
                viewMetrics.VisibleRangeResizerWidth   = 8;
            }

            viewMetrics.VScrollBarValue = (int)(vertScroller.DoubleValue * VertScrollerValueRange);
        }
예제 #20
0
        public void EnabledUI()
        {
            bool logged    = Engine.IsLogged();
            bool connected = Engine.IsConnected();
            bool waiting   = Engine.IsWaiting();

            MnuTrayRestore.Hidden = false;

            /* // 2.8
             * if (this.Window.IsVisible)
             *      MnuTrayRestore.Title = Messages.WindowsMainHide;
             * else
             */
            MnuTrayRestore.Title = Messages.WindowsMainShow;

            if (logged == false)
            {
                CmdLogin.Title = Messages.CommandLoginButton;
            }
            else
            {
                CmdLogin.Title = Messages.CommandLogout;
            }

            if (waiting)
            {
                MnuTrayConnect.Title = Messages.CommandCancel;
            }
            else if (connected)
            {
                MnuTrayConnect.Enabled = true;
                MnuTrayConnect.Title   = Messages.CommandDisconnect;
            }
            else if (logged)
            {
                MnuTrayConnect.Enabled = true;
                MnuTrayConnect.Title   = Messages.CommandConnect;
            }
            else
            {
                MnuTrayConnect.Enabled = true;
                MnuTrayConnect.Title   = Messages.CommandLoginMenu;
            }

            CmdLogin.Enabled = ((waiting == false) && (connected == false) && (TxtLogin.StringValue.Trim() != "") && (TxtPassword.StringValue.Trim() != ""));

            TxtLogin.Enabled    = (logged == false);
            TxtPassword.Enabled = (logged == false);

            if (logged)
            {
                CmdConnect.Enabled = true;
            }
            else
            {
                CmdConnect.Enabled = false;
            }

            CmdServersConnect.Enabled   = ((logged) && (TableServers.SelectedRowCount == 1));
            CmdServersWhiteList.Enabled = (TableServers.SelectedRowCount > 0);
            CmdServersBlackList.Enabled = CmdServersWhiteList.Enabled;
            CmdServersUndefined.Enabled = CmdServersWhiteList.Enabled;
            MnuServersConnect.Enabled   = CmdServersConnect.Enabled;
            MnuServersWhitelist.Enabled = CmdServersWhiteList.Enabled;
            MnuServersBlacklist.Enabled = CmdServersBlackList.Enabled;
            MnuServersUndefined.Enabled = CmdServersUndefined.Enabled;

            CmdAreasWhiteList.Enabled = (TableAreas.SelectedRowCount > 0);
            CmdAreasBlackList.Enabled = CmdAreasWhiteList.Enabled;
            CmdAreasUndefined.Enabled = CmdAreasWhiteList.Enabled;
            MnuAreasWhitelist.Enabled = CmdAreasWhiteList.Enabled;
            MnuAreasBlacklist.Enabled = CmdAreasBlackList.Enabled;
            MnuAreasUndefined.Enabled = CmdAreasUndefined.Enabled;

            CmdLogsOpenVpnManagement.Hidden  = (Engine.Storage.GetBool("advanced.expert") == false);
            CmdLogsOpenVpnManagement.Enabled = connected;

            if (Engine.Instance.NetworkLockManager != null)
            {
                CmdNetworkLock.Hidden = (Engine.Instance.NetworkLockManager.CanEnabled() == false);
                ImgNetworkLock.Hidden = CmdNetworkLock.Hidden;
                if (Engine.Instance.NetworkLockManager.IsActive())
                {
                    CmdNetworkLock.Title = Messages.NetworkLockButtonActive;
                    ImgNetworkLock.Image = NSImage.ImageNamed("netlock_on.png");
                }
                else
                {
                    CmdNetworkLock.Title = Messages.NetworkLockButtonDeactive;
                    ImgNetworkLock.Image = NSImage.ImageNamed("netlock_off.png");
                }
            }
        }
예제 #21
0
        public void GetData <T>(int level, Rectangle?rect, T[] data, int startIndex, int elementCount)
        {
            if (data == null)
            {
                throw new ArgumentException("data cannot be null");
            }

            if (data.Length < startIndex + elementCount)
            {
                throw new ArgumentException("The data passed has a length of " + data.Length + " but " + elementCount + " pixels have been requested.");
            }

            Rectangle r;

            if (rect != null)
            {
                r = rect.Value;
            }
            else
            {
                r = new Rectangle(0, 0, Width, Height);
            }

            int sz = 0;

            byte[] pixel = new byte[4];
            int    pos;
            IntPtr pixelOffset;

            // Get the Color values
            if ((typeof(T) == typeof(Color)))
            {
                // Load up texture into memory
                NSImage nsImage = NSImage.ImageNamed(this.Name);
                if (nsImage == null)
                {
                    throw new ContentLoadException("Error loading file via UIImage: " + Name);
                }

                CGImage image = nsImage.AsCGImage(RectangleF.Empty, null, null);
                if (image == null)
                {
                    throw new ContentLoadException("Error with CGIamge: " + Name);
                }

                int               width, height, i;
                CGContext         context = null;
                IntPtr            imageData;
                CGColorSpace      colorSpace;
                IntPtr            tempData;
                bool              hasAlpha;
                CGImageAlphaInfo  info;
                CGAffineTransform transform;
                Size              imageSize;
                SurfaceFormat     pixelFormat;
                bool              sizeToFit = false;

                info     = image.AlphaInfo;
                hasAlpha = ((info == CGImageAlphaInfo.PremultipliedLast) || (info == CGImageAlphaInfo.PremultipliedFirst) || (info == CGImageAlphaInfo.Last) || (info == CGImageAlphaInfo.First) ? true : false);

                if (image.ColorSpace != null)
                {
                    pixelFormat = SurfaceFormat.Color;
                }
                else
                {
                    pixelFormat = SurfaceFormat.Alpha8;
                }

                imageSize = new Size(image.Width, image.Height);
                transform = CGAffineTransform.MakeIdentity();
                width     = imageSize.Width;

                if ((width != 1) && ((width & (width - 1)) != 0))
                {
                    i = 1;
                    while ((sizeToFit ? 2 * i : i) < width)
                    {
                        i *= 2;
                    }
                    width = i;
                }
                height = imageSize.Height;
                if ((height != 1) && ((height & (height - 1)) != 0))
                {
                    i = 1;
                    while ((sizeToFit ? 2 * i : i) < height)
                    {
                        i *= 2;
                    }
                    height = i;
                }
                // TODO: kMaxTextureSize = 1024
                while ((width > 1024) || (height > 1024))
                {
                    width            /= 2;
                    height           /= 2;
                    transform         = CGAffineTransform.MakeScale(0.5f, 0.5f);
                    imageSize.Width  /= 2;
                    imageSize.Height /= 2;
                }

                switch (pixelFormat)
                {
                case SurfaceFormat.Color:
                    colorSpace = CGColorSpace.CreateDeviceRGB();
                    imageData  = Marshal.AllocHGlobal(height * width * 4);
                    context    = new CGBitmapContext(imageData, width, height, 8, 4 * width, colorSpace, CGImageAlphaInfo.PremultipliedLast);
                    colorSpace.Dispose();
                    break;

                case SurfaceFormat.Alpha8:
                    imageData = Marshal.AllocHGlobal(height * width);
                    context   = new CGBitmapContext(imageData, width, height, 8, width, null, CGImageAlphaInfo.Only);
                    break;

                default:
                    throw new NotSupportedException("Invalid pixel format");
                }

                context.ClearRect(new RectangleF(0, 0, width, height));
                context.TranslateCTM(0, height - imageSize.Height);

                if (!transform.IsIdentity)
                {
                    context.ConcatCTM(transform);
                }

                context.DrawImage(new RectangleF(0, 0, image.Width, image.Height), image);

                //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"

                /*
                 * if(pixelFormat == SurfaceFormat.Rgb32) {
                 *      tempData = Marshal.AllocHGlobal(height * width * 2);
                 *
                 *      int d32;
                 *      short d16;
                 *      int inPixel32Count=0,outPixel16Count=0;
                 *      for(i = 0; i < width * height; ++i, inPixel32Count+=sizeof(int))
                 *      {
                 *              d32 = Marshal.ReadInt32(imageData,inPixel32Count);
                 *              short R = (short)((((d32 >> 0) & 0xFF) >> 3) << 11);
                 *              short G = (short)((((d32 >> 8) & 0xFF) >> 2) << 5);
                 *              short B = (short)((((d32 >> 16) & 0xFF) >> 3) << 0);
                 *              d16 = (short)  (R | G | B);
                 *              Marshal.WriteInt16(tempData,outPixel16Count,d16);
                 *              outPixel16Count += sizeof(short);
                 *      }
                 *      Marshal.FreeHGlobal(imageData);
                 *      imageData = tempData;
                 * }
                 */

                int count = 0;

                // Loop through and extract the data
                for (int y = r.Top; y < r.Bottom; y++)
                {
                    for (int x = r.Left; x < r.Right; x++)
                    {
                        var result = new Color(0, 0, 0, 0);

                        switch (this.Format)
                        {
                        case SurfaceFormat.Color /*kTexture2DPixelFormat_RGBA8888*/:
                        case SurfaceFormat.Dxt3:
                            sz          = 4;
                            pos         = ((y * imageSize.Width) + x) * sz;
                            pixelOffset = new IntPtr(imageData.ToInt64() + pos);
                            Marshal.Copy(pixelOffset, pixel, 0, 4);
                            result.R = pixel[0];
                            result.G = pixel[1];
                            result.B = pixel[2];
                            result.A = pixel[3];
                            break;

                        case SurfaceFormat.Bgra4444 /*kTexture2DPixelFormat_RGBA4444*/:
                            sz          = 2;
                            pos         = ((y * imageSize.Width) + x) * sz;
                            pixelOffset = new IntPtr(imageData.ToInt64() + pos);

                            Marshal.Copy(pixelOffset, pixel, 0, 4);

                            result.R = pixel[0];
                            result.G = pixel[1];
                            result.B = pixel[2];
                            result.A = pixel[3];
                            break;

                        case SurfaceFormat.Bgra5551 /*kTexture2DPixelFormat_RGB5A1*/:
                            sz          = 2;
                            pos         = ((y * imageSize.Width) + x) * sz;
                            pixelOffset = new IntPtr(imageData.ToInt64() + pos);
                            Marshal.Copy(pixelOffset, pixel, 0, 4);

                            result.R = pixel[0];
                            result.G = pixel[1];
                            result.B = pixel[2];
                            result.A = pixel[3];
                            break;

                        case SurfaceFormat.Alpha8 /*kTexture2DPixelFormat_A8*/:
                            sz          = 1;
                            pos         = ((y * imageSize.Width) + x) * sz;
                            pixelOffset = new IntPtr(imageData.ToInt64() + pos);
                            Marshal.Copy(pixelOffset, pixel, 0, 4);

                            result.A = pixel[0];
                            break;

                        default:
                            throw new NotSupportedException("Texture format");
                        }
                        data[((y * imageSize.Width) + x)] = (T)(object)result;

                        count++;
                        if (count >= elementCount)
                        {
                            return;
                        }
                    }
                }

                context.Dispose();
                Marshal.FreeHGlobal(imageData);
            }
            else
            {
                throw new NotImplementedException();
            }
        }
예제 #22
0
 protected ImageSource(NSImage image)
 {
     _isOriginalSourceUIImage = true;
     ImageData = image;
 }
예제 #23
0
        internal async Task <NSImage> Open(CancellationToken ct)
        {
            using (
                _trace.WriteEventActivity(
                    TraceProvider.ImageSource_SetImageDecodeStart,
                    TraceProvider.ImageSource_SetImageDecodeStop,
                    new object[] { this.GetDependencyObjectId() }
                    )
                )
            {
                if (ct.IsCancellationRequested)
                {
                    return(null);
                }

                if (IsSourceReady && TryOpenSourceSync(out var img))
                {
                    return(ImageData = img);
                }

                if (IsSourceReady && TryOpenSourceAsync(out var asyncImg))
                {
                    return(ImageData = await asyncImg);
                }

                if (Stream != null)
                {
                    Stream.Position = 0;
                    return(ImageData = NSImage.FromStream(Stream));
                }

                if (FilePath.HasValue())
                {
                    using (var file = File.OpenRead(FilePath))
                    {
                        return(ImageData = NSImage.FromStream(file));
                    }
                }

                if (HasBundle)
                {
                    await CoreDispatcher.Main.RunAsync(
                        CoreDispatcherPriority.Normal,
                        async() =>
                    {
                        ImageData = OpenBundle();
                    }
                        );

                    return(ImageData);
                }

                if (Downloader == null)
                {
                    await OpenUsingPlatformDownloader(ct);
                }
                else
                {
                    var localFileUri = await Download(ct, WebUri);

                    if (localFileUri == null)
                    {
                        return(null);
                    }

                    await CoreDispatcher.Main.RunAsync(
                        CoreDispatcherPriority.Normal,
                        async() =>
                    {
                        ImageData = NSImage.ImageNamed(localFileUri.LocalPath);
                    }).AsTask(ct);
                }

                return(ImageData);
            }
        }
예제 #24
0
 private protected virtual bool TryOpenSourceSync(out NSImage image)
 {
     image = default;
     return(false);
 }
예제 #25
0
 public ImageWrapper(NSImage image)
 {
     this.image = image;
 }
예제 #26
0
        private void ShowConnectingAnimation(bool isResuming = false)
        {
            if (!NSThread.IsMain)
            {
                InvokeOnMainThread(() => ShowConnectingAnimation(isResuming));
                return;
            }
            // prepare GUI controls
            GuiConnectButtonImage.Hidden = false;
            GuiConnectButtonImage.Image  = Colors.IsDarkMode ? NSImage.ImageNamed("buttonConnectDark") : NSImage.ImageNamed("buttonConnecting");

            if (isResuming == false)
            {
                GuiConnectButtonText.AttributedStringValue = AttributedString.Create(
                    LocalizedStrings.Instance.LocalizedString("Button_Connecting"),
                    Colors.ConnectButtonTextColor,
                    NSTextAlignment.Center);
            }
            else
            {
                GuiConnectButtonText.AttributedStringValue = AttributedString.Create(
                    LocalizedStrings.Instance.LocalizedString("Button_Resuming"),
                    Colors.ConnectButtonTextColor,
                    NSTextAlignment.Center);
            }

            GuiConnectButtonText.AlphaValue = 1f;
            View.IsVisibleCircles           = false;

            // initialize animation
            NSColor startCircleColor = Colors.ConnectiongAnimationCircleColor;

            UpdateToDoLabelHiddenStatus(true);

            __animationLayer.FillColor   = NSColor.Clear.CGColor;
            __animationLayer.StrokeColor = startCircleColor.CGColor;

            var frame       = GuiConnectButtonImage.Frame;
            var startCircle = CGPath.EllipseFromRect(
                new CGRect(frame.X + 6,
                           frame.Y + 6,
                           frame.Width - 12,
                           frame.Height - 12)
                );

            var endCircle = CGPath.EllipseFromRect(
                new CGRect(frame.X + 3,
                           frame.Y + 3,
                           frame.Width - 6,
                           frame.Height - 6)
                );

            CABasicAnimation circleRadiusAnimation = CABasicAnimation.FromKeyPath("path");

            circleRadiusAnimation.From = FromObject(startCircle);
            circleRadiusAnimation.To   = FromObject(endCircle);

            CABasicAnimation lineWidthAnimation = CABasicAnimation.FromKeyPath("lineWidth");

            lineWidthAnimation.From = FromObject(1);
            lineWidthAnimation.To   = FromObject(8);

            CAAnimationGroup animationGroup = new CAAnimationGroup();

            animationGroup.Animations   = new CAAnimation[] { circleRadiusAnimation, lineWidthAnimation };
            animationGroup.Duration     = 1f;
            animationGroup.RepeatCount  = float.PositiveInfinity;
            animationGroup.AutoReverses = true;
            __animationLayer.AddAnimation(animationGroup, null);

            AnimateButtonTextBlinking();
        }
예제 #27
0
        private void UpdateDisconnectedUITheme(bool isPaused)
        {
            GuiConnectButtonImage.Image = Colors.IsDarkMode ? NSImage.ImageNamed("buttonConnectDark") : NSImage.ImageNamed("buttonConnect");

            if (isPaused == false)
            {
                GuiConnectButtonText.AttributedStringValue = AttributedString.Create(
                    LocalizedStrings.Instance.LocalizedString("Button_Connect"),
                    Colors.ConnectButtonTextColor,
                    NSTextAlignment.Center);

                GuiLabelToDoDescription.AttributedStringValue = AttributedString.Create(
                    LocalizedStrings.Instance.LocalizedString("Label_ClickToConnect"),
                    __ToDoDescriptionTextColor,
                    NSTextAlignment.Center);
            }
            else
            {
                GuiConnectButtonText.AttributedStringValue = AttributedString.Create(
                    LocalizedStrings.Instance.LocalizedString("Button_Resume"),
                    Colors.ConnectButtonTextColor,
                    NSTextAlignment.Center);

                GuiLabelToDoDescription.AttributedStringValue = AttributedString.Create(
                    LocalizedStrings.Instance.LocalizedString("Label_ClickToResume"),
                    __ToDoDescriptionTextColor,
                    NSTextAlignment.Center);
            }
        }
예제 #28
0
 public override void AwakeFromNib()
 {
     circle       = NSImage.ImageNamed("circle");
     pentagon     = NSImage.ImageNamed("pentagon");
     NeedsDisplay = true;
 }
예제 #29
0
		void LoadPixbuf (IconId iconId)
		{
			// We dont need to load the same image twice
			if (icon == iconId && iconLoaded)
				return;

			icon = iconId;
			iconAnimation = null;

			// clean up previous running animation
			if (xwtAnimation != null) {
				xwtAnimation.Dispose ();
				xwtAnimation = null;
			}

			// if we have nothing, use the default icon
			if (iconId == IconId.Null)
				iconId = Stock.StatusSteady;

			// load image now
			if (ImageService.IsAnimation (iconId, Gtk.IconSize.Menu)) {
				iconAnimation = ImageService.GetAnimatedIcon (iconId, Gtk.IconSize.Menu);
				image = iconAnimation.FirstFrame.ToNSImage ();
				xwtAnimation = iconAnimation.StartAnimation (p => {
					image = p.ToNSImage ();
					ReconstructString ();
				});
			} else {
				image = ImageService.GetIcon (iconId).ToNSImage ();
			}

			iconLoaded = true;
		}
예제 #30
0
        private void UpdateWiFiInfoGuiData()
        {
            if (!NSThread.IsMain)
            {
                InvokeOnMainThread(() => UpdateWiFiInfoGuiData());
                return;
            }

            try
            {
                UpdateToDoLabelHiddenStatus();

                WifiState state = __MainViewModel.WiFiState;
                if (__MainViewModel.Settings.IsNetworkActionsEnabled == false)
                {
                    GuiWiFiButton.Hidden            = true;
                    GuiNetworkActionPopUpBtn.Hidden = true;
                    return;
                }

                NSFont wifiLabelFont = UIUtils.GetSystemFontOfSize(14, NSFontWeight.Thin);

                if (state == null || string.IsNullOrEmpty(state.Network.SSID))
                {
                    GuiWiFiButton.AttributedTitle = AttributedString.Create(LocalizedStrings.Instance.LocalizedString("Label_NoWiFiConnection"), NSColor.SystemGrayColor, NSTextAlignment.Center, wifiLabelFont);
                    GuiWiFiButton.Image           = null;

                    GuiWiFiButton.Enabled           = false;
                    GuiWiFiButton.Hidden            = false;
                    GuiNetworkActionPopUpBtn.Hidden = true;
                }
                else
                {
                    if (state.ConnectedToInsecureNetwork)
                    {
                        GuiWiFiButton.Image = NSImage.ImageNamed("iconWiFiSmallRed");

                        string networkName = " " + state.Network.SSID + " ";
                        string fullText    = networkName + "(" + LocalizedStrings.Instance.LocalizedString("Label_InsecureWiFiConnection") + ") ";

                        NSMutableAttributedString attrTitle = new NSMutableAttributedString(fullText);

                        NSStringAttributes stringAttributes0 = new NSStringAttributes();
                        stringAttributes0.ForegroundColor = __ToDoDescriptionTextColor;
                        stringAttributes0.Font            = wifiLabelFont;

                        NSStringAttributes stringAttributes1 = new NSStringAttributes();
                        stringAttributes1.ForegroundColor = NSColor.SystemRedColor;
                        stringAttributes1.Font            = wifiLabelFont;

                        attrTitle.AddAttributes(stringAttributes0, new NSRange(0, networkName.Length));
                        attrTitle.AddAttributes(stringAttributes1, new NSRange(networkName.Length, fullText.Length - networkName.Length));
                        attrTitle.SetAlignment(NSTextAlignment.Center, new NSRange(0, fullText.Length));

                        GuiWiFiButton.AttributedTitle = attrTitle;
                    }
                    else
                    {
                        GuiWiFiButton.Image           = NSImage.ImageNamed("iconWiFiSmallBlue");
                        GuiWiFiButton.AttributedTitle = AttributedString.Create(" " + state.Network.SSID, __ToDoDescriptionTextColor, NSTextAlignment.Center, wifiLabelFont);
                    }

                    RecreateNetworkActionsButtonItems();

                    GuiWiFiButton.Enabled           = true;
                    GuiWiFiButton.Hidden            = false;
                    GuiNetworkActionPopUpBtn.Hidden = false;
                }
            }
            catch (Exception ex)
            {
                GuiWiFiButton.Hidden            = true;
                GuiNetworkActionPopUpBtn.Hidden = true;

                Logging.Info($"{ex}");
            }
        }
예제 #31
0
        private void CreateAbout()
        {
            string about_image_path = Path.Combine(NSBundle.MainBundle.ResourcePath,
                                                   "Pixmaps", "about.png");

            AboutImage = new NSImage(about_image_path)
            {
                Size = new SizeF(640, 260)
            };

            AboutImageView = new NSImageView()
            {
                Image = AboutImage,
                Frame = new RectangleF(0, 0, 640, 260)
            };


            VersionTextField = new NSTextField()
            {
                StringValue     = "version " + Controller.RunningVersion,
                Frame           = new RectangleF(295, 140, 318, 22),
                BackgroundColor = NSColor.White,
                Bordered        = false,
                Editable        = false,
                DrawsBackground = false,
                TextColor       = NSColor.White,
                Font            = NSFontManager.SharedFontManager.FontWithFamily
                                      ("Lucida Grande", NSFontTraitMask.Unbold, 0, 11)
            };

            UpdatesTextField = new NSTextField()
            {
                StringValue     = "Checking for updates...",
                Frame           = new RectangleF(295, Frame.Height - 232, 318, 98),
                Bordered        = false,
                Editable        = false,
                DrawsBackground = false,
                Font            = NSFontManager.SharedFontManager.FontWithFamily
                                      ("Lucida Grande", NSFontTraitMask.Unbold, 0, 11),
                TextColor =
                    NSColor.FromCalibratedRgba(0.45f, 0.62f, 0.81f, 1.0f)  // Tango Sky Blue #1
            };

            CreditsTextField = new NSTextField()
            {
                StringValue = @"Copyright © 2010–" + DateTime.Now.Year + " Hylke Bons and others." +
                              "\n" +
                              "\n" +
                              "SparkleShare is Free and Open Source Software. You are free to use, modify, and redistribute it " +
                              "under the GNU General Public License version 3 or later.",
                Frame           = new RectangleF(295, Frame.Height - 260, 318, 98),
                TextColor       = NSColor.White,
                DrawsBackground = false,
                Bordered        = false,
                Editable        = false,
                Font            = NSFontManager.SharedFontManager.FontWithFamily
                                      ("Lucida Grande", NSFontTraitMask.Unbold, 0, 11),
            };

//            WebsiteButton.Activated += delegate {
//                NSUrl url = new NSUrl ("http://www.sparkleshare.org/");
//                NSWorkspace.SharedWorkspace.OpenUrl (url);
//            };

//            CreditsButton.Activated += delegate {
//                NSUrl url = new NSUrl ("http://www.sparkleshare.org/credits/");
//                NSWorkspace.SharedWorkspace.OpenUrl (url);
//            };

            ContentView.AddSubview(AboutImageView);

            ContentView.AddSubview(VersionTextField);
            ContentView.AddSubview(UpdatesTextField);
            ContentView.AddSubview(CreditsTextField);
        }
예제 #32
0
 private void OnBackgroundImageBrushChanged(NSImage backgroundImage)
 {
     UpdateBackground(backgroundImage);
 }
예제 #33
0
        public void RefreshUi(Engine.RefreshUiMode mode)
        {
            if ((mode == Engine.RefreshUiMode.MainMessage) || (mode == Engine.RefreshUiMode.Full))
            {
                if (Engine.CurrentServer != null)
                {
                    ImgTopFlag.Image = NSImage.ImageNamed("flag_" + Engine.CurrentServer.CountryCode.ToLowerInvariant() + ".png");
                }
                else
                {
                    ImgTopFlag.Image = NSImage.ImageNamed("notconnected.png");
                }

                LblWaiting1.StringValue = Engine.WaitMessage;

                if (Engine.IsWaiting())
                {
                    ImgProgress.StartAnimation(this);
                    ImgTopPanel.Image        = NSImage.ImageNamed("topbar_osx_yellow.png");
                    MnuTrayStatus.Image      = NSImage.ImageNamed("status_yellow_16.png");
                    LblTopStatus.StringValue = Engine.WaitMessage;

                    TabOverview.SelectAt(1);

                    CmdCancel.Hidden       = (Engine.IsWaitingCancelAllowed() == false);
                    CmdCancel.Enabled      = (Engine.IsWaitingCancelPending() == false);
                    MnuTrayConnect.Enabled = CmdCancel.Enabled;
                }
                else if (Engine.IsConnected())
                {
                    ImgProgress.StopAnimation(this);
                    ImgTopPanel.Image        = NSImage.ImageNamed("topbar_osx_green.png");
                    MnuTrayStatus.Image      = NSImage.ImageNamed("status_green_16.png");
                    LblTopStatus.StringValue = Messages.Format(Messages.TopBarConnected, Engine.CurrentServer.PublicName);

                    TabOverview.SelectAt(2);

                    LblConnectedServerName.StringValue = Engine.CurrentServer.PublicName;
                    LblConnectedLocation.StringValue   = Engine.CurrentServer.CountryName + ", " + Engine.CurrentServer.Location;
                    TxtConnectedExitIp.StringValue     = Engine.CurrentServer.IpExit;
                    ImgConnectedCountry.Image          = NSImage.ImageNamed("flag_" + Engine.CurrentServer.CountryCode.ToLowerInvariant() + ".png");
                }
                else
                {
                    ImgProgress.StopAnimation(this);
                    ImgTopPanel.Image   = NSImage.ImageNamed("topbar_osx_red.png");
                    MnuTrayStatus.Image = NSImage.ImageNamed("status_red_16.png");
                    if (Engine.Instance.NetworkLockManager.IsActive())
                    {
                        LblTopStatus.StringValue = Messages.TopBarNotConnectedLocked;
                    }
                    else
                    {
                        LblTopStatus.StringValue = Messages.TopBarNotConnectedExposed;
                    }

                    TabOverview.SelectAt(0);
                }

                // Icon update
                if (StatusItem != null)
                {
                    //string colorMode = GuiUtils.InterfaceColorMode ();
                    string colorMode = Engine.Storage.Get("gui.osx.style");

                    if (Engine.IsConnected())
                    {
                        StatusItem.Image = NSImage.ImageNamed("menubar_" + colorMode.ToLowerInvariant() + "_green.png");
                        //NSApplication.SharedApplication.DockTile. =  DateTime.Now.ToString ();
                        NSApplication.SharedApplication.ApplicationIconImage = NSImage.ImageNamed("icon.png");
                    }
                    else
                    {
                        StatusItem.Image = NSImage.ImageNamed("menubar_" + colorMode.ToLowerInvariant() + "_red.png");
                        //NSApplication.SharedApplication.DockTile.Description =  DateTime.Now.ToString ();
                        NSApplication.SharedApplication.ApplicationIconImage = NSImage.ImageNamed("icon_gray.png");
                    }
                }

                EnabledUI();
            }

            if ((mode == Engine.RefreshUiMode.Log) || (mode == Engine.RefreshUiMode.Full))
            {
                lock (Engine.LogsPending) {
                    while (Engine.LogsPending.Count > 0)
                    {
                        LogEntry l = Engine.LogsPending [0];
                        Engine.LogsPending.RemoveAt(0);

                        Log(l);
                    }
                }
                LblWaiting2.StringValue = Engine.GetLogDetailTitle();
            }

            if ((mode == Engine.RefreshUiMode.Stats) || (mode == Engine.RefreshUiMode.Full))
            {
                if (Engine.IsConnected())
                {
                    TxtConnectedSince.StringValue = Engine.Stats.GetValue("VpnConnectionStart");

                    TxtConnectedDownload.StringValue = Core.Utils.FormatBytes(Engine.ConnectedLastDownloadStep, true, false);
                    TxtConnectedUpload.StringValue   = Core.Utils.FormatBytes(Engine.ConnectedLastUploadStep, true, false);

                    string msg  = Messages.Format(Messages.StatusTextConnected, Constants.Name, Core.Utils.FormatBytes(Engine.ConnectedLastDownloadStep, true, false), Core.Utils.FormatBytes(Engine.ConnectedLastUploadStep, true, false), Engine.CurrentServer.PublicName, Engine.CurrentServer.CountryName);
                    string tmsg = Constants.Name + " - " + msg;
                    this.Window.Title   = tmsg;
                    MnuTrayStatus.Title = "> " + msg;
                    StatusItem.ToolTip  = msg;
                }
            }

            if ((mode == Engine.RefreshUiMode.Full))
            {
                if (TableServersController != null)
                {
                    TableServersController.RefreshUI();
                }
                if (TableAreasController != null)
                {
                    TableAreasController.RefreshUI();
                }
            }
        }
        void IView.SetViewModel(IViewModel viewModel)
        {
            this.EnsureCreated();

            this.viewModel = viewModel;

            var fontSz = (NSFont.SystemFontSize + NSFont.SmallSystemFontSize) / 2f;

            this.resources = new Resources(
                viewModel,
                NSFont.SystemFontOfSize(NSFont.SystemFontSize).FamilyName,
                (float)fontSz)
            {
                BookmarkImage       = new LJD.Image(NSImage.ImageNamed("Bookmark.png")),
                FocusedMessageImage = new LJD.Image(NSImage.ImageNamed("FocusedMsgSlave.png")),
                FocusedMsgSlaveVert = new LJD.Image(NSImage.ImageNamed("FocusedMsgSlaveVert.png"))
            };

            this.drawingUtils = new DrawingUtils(viewModel, resources);

            var notificationsIconUpdater = Updaters.Create(
                () => viewModel.IsNotificationsIconVisibile,
                value => activeNotificationsButton.Hidden = !value
                );

            var updateCurrentArrowControls = Updaters.Create(
                () => viewModel.CurrentArrowInfo,
                value => {
                arrowNameTextField.StringValue = value.Caption;
                arrowDetailsLink.StringValue   = value.DescriptionText;
                arrowDetailsLink.Links         = (value.DescriptionLinks ?? Enumerable.Empty <Tuple <object, int, int> >())
                                                 .Select(l => new NSLinkLabel.Link(l.Item2, l.Item3, l.Item1)).ToArray();
            }
                );

            var updateCollapseResponsesCheckbox = Updaters.Create(
                () => viewModel.IsCollapseResponsesChecked,
                value => collapseResponsesCheckbox.State = value ? NSCellStateValue.On : NSCellStateValue.Off
                );

            var updateCollapseRoleInstancesCheckbox = Updaters.Create(
                () => viewModel.IsCollapseRoleInstancesChecked,
                value => collapseRoleInstancesCheckbox.State = value ? NSCellStateValue.On : NSCellStateValue.Off);

            var scrollBarsUpdater = Updaters.Create(
                () => viewModel.ScrollInfo,
                value => UpdateScrollBars(value.vMax, value.vChange, value.vValue,
                                          value.hMax, value.hChange, value.hValue)
                );

            var invalidateViews = Updaters.Create(
                () => viewModel.RolesDrawInfo,
                () => viewModel.ArrowsDrawInfo,
                (_1, _2) => {
                rolesCaptionsView.NeedsDisplay = true;
                arrowsView.NeedsDisplay        = true;
                leftPanelView.NeedsDisplay     = true;
            }
                );

            viewModel.ChangeNotification.CreateSubscription(() => {
                notificationsIconUpdater();
                updateCurrentArrowControls();
                updateCollapseResponsesCheckbox();
                updateCollapseRoleInstancesCheckbox();
                scrollBarsUpdater();
                invalidateViews();
            });
        }
        public override void AwakeFromNib()
        {
            // Create the root layer
            rootLayer = new CALayer();

            // Set the root layer;s background color to black
            rootLayer.BackgroundColor = new CGColor(0, 0, 0);

            // Create the fire emitter layer
            fireEmitter            = new CAEmitterLayer();
            fireEmitter.Position   = new System.Drawing.PointF(225, 50);
            fireEmitter.Mode       = CAEmitterLayer.ModeOutline;
            fireEmitter.Shape      = CAEmitterLayer.ShapeLine;
            fireEmitter.RenderMode = CAEmitterLayer.RenderAdditive;
            fireEmitter.Size       = new SizeF(0, 0);

            // Create the smoke emitter layer
            smokeEmitter          = new CAEmitterLayer();
            smokeEmitter.Position = new PointF(225, 50);
            smokeEmitter.Mode     = CAEmitterLayer.ModePoints;

            // Create the fire emitter cell
            CAEmitterCell fire = CAEmitterCell.EmitterCell();

            fire.EmissionLongitude = (float)Math.PI;
            fire.BirthRate         = 0;
            fire.Velocity          = 80;
            fire.VelocityRange     = 30;
            fire.EmissionRange     = 1.1f;
            fire.AccelerationY     = 200;
            fire.ScaleSpeed        = 0.3f;

            RectangleF rect  = RectangleF.Empty;
            CGColor    color = new CGColor(0.8f, 0.4f, 0.2f, 0.10f);

            fire.Color    = color;
            fire.Contents = NSImage.ImageNamed("fire.png").AsCGImage(ref rect, null, null);

            // Name the cell so that it can be animated later using keypaths
            fire.Name = "fire";

            // Add the fire emitter cell to the fire emitter layer
            fireEmitter.Cells = new CAEmitterCell[] { fire };

            //Create the smoke emitter cell
            CAEmitterCell smoke = CAEmitterCell.EmitterCell();

            smoke.BirthRate         = 11;
            smoke.EmissionLongitude = (float)Math.PI / 2;
            smoke.LifeTime          = 0;
            smoke.Velocity          = 40;
            smoke.VelocityRange     = 20;
            smoke.EmissionRange     = (float)Math.PI / 4;
            smoke.Spin          = 1;
            smoke.SpinRange     = 6;
            smoke.AccelerationY = 160;
            smoke.Scale         = 0.1f;
            smoke.AlphaSpeed    = -0.12f;
            smoke.ScaleSpeed    = 0.7f;
            smoke.Contents      = NSImage.ImageNamed("smoke.png").AsCGImage(ref rect, null, null);
            //Name the cell so that it can be animated later using keypaths
            smoke.Name = "smoke";

            // Add the smoke emitter cell to the smoke emitter layer
            smokeEmitter.Cells = new CAEmitterCell[] { smoke };

            // Add the two emitter layers to the root layer
            rootLayer.AddSublayer(smokeEmitter);
            rootLayer.AddSublayer(fireEmitter);

            // Set the view's layer to the base layer
            view.Layer      = rootLayer;
            view.WantsLayer = true;

            // Set the fire simulation to reflect the intial slider postion
            slidersChanged(this);

            // Force the view to update
            view.NeedsDisplay = true;
        }
예제 #36
0
        private void UpdateSessionStatusInfo(SessionStatus sessionStatus)
        {
            InvokeOnMainThread(() =>
            {
                try
                {
                    GuiNotificationButtonBottom.Hidden = true;
                    if (sessionStatus == null)
                    {
                        return;
                    }

                    if (!sessionStatus.IsActive)
                    {
                        string part1 = LocalizedStrings.Instance.LocalizedString("Label_SubscriptionExpired");
                        if (sessionStatus.IsOnFreeTrial)
                        {
                            part1 = LocalizedStrings.Instance.LocalizedString("Label_FreeTrialExpired");
                        }
                        string part2 = LocalizedStrings.Instance.LocalizedString("Label_AccountExpiredUpgradeNow");

                        string title = part1 + " " + part2;
                        CustomButtonStyles.ApplyStyleInfoButton(GuiNotificationButtonBottom, title, NSImage.ImageNamed("iconStatusBad"));

                        NSMutableAttributedString attrTitle = new NSMutableAttributedString(title);

                        NSStringAttributes stringAttributes0 = new NSStringAttributes();
                        stringAttributes0.Font            = GuiNotificationButtonBottom.TitleFont;
                        stringAttributes0.ForegroundColor = GuiNotificationButtonBottom.TitleForegroundColor;
                        stringAttributes0.ParagraphStyle  = new NSMutableParagraphStyle {
                            Alignment = NSTextAlignment.Center
                        };

                        NSStringAttributes stringAttributes1 = new NSStringAttributes();
                        stringAttributes1.ForegroundColor    = NSColor.FromRgb(59, 159, 230);

                        attrTitle.AddAttributes(stringAttributes0, new NSRange(0, title.Length));
                        attrTitle.AddAttributes(stringAttributes1, new NSRange(title.Length - part2.Length, part2.Length));

                        GuiNotificationButtonBottom.TitleTextAttributedString = attrTitle;

                        GuiNotificationButtonBottom.Hidden = false;
                    }
                    else
                    {
                        if (sessionStatus.WillAutoRebill)
                        {
                            return;
                        }

                        if ((sessionStatus.ActiveUtil - DateTime.Now).TotalMilliseconds < TimeSpan.FromDays(4).TotalMilliseconds)
                        {
                            int daysLeft = (int)(sessionStatus.ActiveUtil - DateTime.Now).TotalDays;
                            if (daysLeft < 0)
                            {
                                daysLeft = 0;
                            }

                            string notificationString;

                            if (daysLeft == 0)
                            {
                                notificationString = LocalizedStrings.Instance.LocalizedString("Label_AccountDaysLeft_LastDay");
                                if (sessionStatus.IsOnFreeTrial)
                                {
                                    notificationString = LocalizedStrings.Instance.LocalizedString("Label_FreeTrialDaysLeft_LastDay");
                                }
                            }
                            else if (daysLeft == 1)
                            {
                                notificationString = LocalizedStrings.Instance.LocalizedString("Label_AccountDaysLeft_OneDay");
                                if (sessionStatus.IsOnFreeTrial)
                                {
                                    notificationString = LocalizedStrings.Instance.LocalizedString("Label_FreeTrialDaysLeft_OneDay");
                                }
                            }
                            else
                            {
                                notificationString = LocalizedStrings.Instance.LocalizedString("Label_AccountDaysLeft_PARAMETRIZED");
                                if (sessionStatus.IsOnFreeTrial)
                                {
                                    notificationString = LocalizedStrings.Instance.LocalizedString("Label_FreeTrialDaysLeft_PARAMETRIZED");
                                }

                                notificationString = string.Format(notificationString, daysLeft);
                            }
                            CustomButtonStyles.ApplyStyleInfoButton(GuiNotificationButtonBottom, notificationString, NSImage.ImageNamed("iconStatusModerate"));

                            GuiNotificationButtonBottom.Hidden = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.Info(string.Format("{0}", ex));
                    GuiNotificationButtonBottom.Hidden = true;
                }
            });
        }
예제 #37
0
        private void CreateAbout()
        {
            string about_image_path = Path.Combine(NSBundle.MainBundle.ResourcePath, "Pixmaps", "about.png");

            this.about_image = new NSImage(about_image_path)
            {
                Size = new SizeF(640, 260)
            };

            this.about_image_view = new NSImageView()
            {
                Image = this.about_image,
                Frame = new RectangleF(0, 0, 640, 260)
            };

            this.version_text_field = new NSTextField()
            {
                StringValue     = "version " + Controller.RunningVersion,
                Frame           = new RectangleF(295, 140, 318, 22),
                BackgroundColor = NSColor.White,
                Bordered        = false,
                Editable        = false,
                DrawsBackground = false,
                TextColor       = NSColor.White,
                Font            = NSFontManager.SharedFontManager.FontWithFamily(
                    "Lucida Grande", NSFontTraitMask.Unbold, 0, 11)
            };

            this.updates_text_field = new NSTextField()
            {
                StringValue     = "Checking for updates...",
                Frame           = new RectangleF(295, Frame.Height - 232, 318, 98),
                Bordered        = false,
                Editable        = false,
                DrawsBackground = false,
                TextColor       = NSColor.FromCalibratedRgba(1.0f, 1.0f, 1.0f, 0.5f),
                Font            = NSFontManager.SharedFontManager.FontWithFamily(
                    "Lucida Grande", NSFontTraitMask.Unbold, 0, 11)
            };

            this.credits_text_field = new NSTextField()
            {
                StringValue = @"Copyright © 2010–" + DateTime.Now.Year + " Hylke Bons and others." +
                              "\n" +
                              "\n" +
                              "SparkleShare is Open Source software. You are free to use, modify, and redistribute it " +
                              "under the GNU General Public License version 3 or later.",
                Frame           = new RectangleF(295, Frame.Height - 260, 318, 98),
                TextColor       = NSColor.White,
                DrawsBackground = false,
                Bordered        = false,
                Editable        = false,
                Font            = NSFontManager.SharedFontManager.FontWithFamily(
                    "Lucida Grande", NSFontTraitMask.Unbold, 0, 11),
            };

            this.website_link       = new SparkleLink("Website", Controller.WebsiteLinkAddress);
            this.website_link.Frame = new RectangleF(new PointF(295, 25), this.website_link.Frame.Size);

            this.credits_link       = new SparkleLink("Credits", Controller.CreditsLinkAddress);
            this.credits_link.Frame = new RectangleF(
                new PointF(this.website_link.Frame.X + this.website_link.Frame.Width + 10, 25),
                this.credits_link.Frame.Size);

            this.report_problem_link       = new SparkleLink("Report a problem", Controller.ReportProblemLinkAddress);
            this.report_problem_link.Frame = new RectangleF(
                new PointF(this.credits_link.Frame.X + this.credits_link.Frame.Width + 10, 25),
                this.report_problem_link.Frame.Size);

            this.debug_log_link       = new SparkleLink("Debug log", Controller.DebugLogLinkAddress);
            this.debug_log_link.Frame = new RectangleF(
                new PointF(this.report_problem_link.Frame.X + this.report_problem_link.Frame.Width + 10, 25),
                this.debug_log_link.Frame.Size);

            this.hidden_close_button = new NSButton()
            {
                Frame = new RectangleF(0, 0, 0, 0),
                KeyEquivalentModifierMask = NSEventModifierMask.CommandKeyMask,
                KeyEquivalent             = "w"
            };


            this.hidden_close_button.Activated += delegate {
                Controller.WindowClosed();
            };


            ContentView.AddSubview(this.hidden_close_button);
            ContentView.AddSubview(this.about_image_view);
            ContentView.AddSubview(this.version_text_field);
            ContentView.AddSubview(this.updates_text_field);
            ContentView.AddSubview(this.credits_text_field);
            ContentView.AddSubview(this.website_link);
            ContentView.AddSubview(this.credits_link);
            ContentView.AddSubview(this.report_problem_link);
            ContentView.AddSubview(this.debug_log_link);
        }
예제 #38
0
        public override Size GetSize(object handle)
        {
            NSImage img = (NSImage)handle;

            return(new Size((int)img.Size.Width, (int)img.Size.Height));
        }
예제 #39
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            mtkView          = (MTKView)View;
            mtkView.Delegate = this;
            mtkView.Device   = device;

            mtkView.SampleCount              = 1;
            mtkView.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            mtkView.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            mtkView.PreferredFramesPerSecond = 60;
            mtkView.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction vertexProgram = defaultLibrary.CreateFunction("cube_vertex");

            // Load the fragment program into the library
            IMTLFunction fragmentProgram = defaultLibrary.CreateFunction("cube_fragment");

            // Create a vertex descriptor from the MTKMesh
            MTLVertexDescriptor vertexDescriptor = new MTLVertexDescriptor();

            vertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[0].BufferIndex = 0;
            vertexDescriptor.Attributes[0].Offset      = 0;
            vertexDescriptor.Attributes[1].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[1].BufferIndex = 0;
            vertexDescriptor.Attributes[1].Offset      = 4 * sizeof(float);
            vertexDescriptor.Attributes[2].Format      = MTLVertexFormat.Float2;
            vertexDescriptor.Attributes[2].BufferIndex = 0;
            vertexDescriptor.Attributes[2].Offset      = 8 * sizeof(float);

            vertexDescriptor.Layouts[0].Stride = 10 * sizeof(float);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            vertexBuffer = device.CreateBuffer(vertexData, MTLResourceOptions.CpuCacheModeDefault);// (MTLResourceOptions)0);

            this.clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            this.view = CreateLookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0), Vector3.UnitY);
            var aspect = (float)(View.Bounds.Size.Width / View.Bounds.Size.Height);

            proj = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspect, 0.1f, 100);

            constantBuffer = device.CreateBuffer(64, MTLResourceOptions.CpuCacheModeDefault);

            // Create a reusable pipeline state
            var pipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = mtkView.SampleCount,
                VertexFunction               = vertexProgram,
                FragmentFunction             = fragmentProgram,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = mtkView.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = mtkView.DepthStencilPixelFormat,
            };

            MTLRenderPipelineColorAttachmentDescriptor renderBufferAttachment = pipelineStateDescriptor.ColorAttachments[0];

            renderBufferAttachment.PixelFormat = mtkView.ColorPixelFormat;

            NSError error;

            pipelineState = device.CreateRenderPipelineState(pipelineStateDescriptor, out error);
            if (pipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStateDesc = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthState = device.CreateDepthStencilState(depthStateDesc);

            // Texture
            NSImage          image            = NSImage.ImageNamed("crate.png");
            MTKTextureLoader mTKTextureLoader = new MTKTextureLoader(device);

            this.texture = mTKTextureLoader.FromCGImage(image.CGImage, new MTKTextureLoaderOptions(), out error);

            MTLSamplerDescriptor samplerDescriptor = new MTLSamplerDescriptor()
            {
                MinFilter    = MTLSamplerMinMagFilter.Linear,
                MagFilter    = MTLSamplerMinMagFilter.Linear,
                SAddressMode = MTLSamplerAddressMode.Repeat,
                TAddressMode = MTLSamplerAddressMode.Repeat,
            };

            this.sampler = device.CreateSamplerState(samplerDescriptor);
        }
예제 #40
0
        public override bool IsBitmap(object handle)
        {
            NSImage img = handle as NSImage;

            return(img != null && img.Representations().OfType <NSBitmapImageRep> ().Any());
        }
        public void GoToSlide(int slideIndex)
        {
            int oldIndex = CurrentSlideIndex;

            // Load the slide at the specified index
            var slide = GetSlide(slideIndex, true);

            if (slide == null)
            {
                return;
            }

            // Compute the playback direction (did the user select next or previous?)
            var direction = slideIndex >= CurrentSlideIndex ? 1 : -1;

            // Update badge
            ShowsNewInSceneKitBadge(slide.IsNewIn10_9);

            // If we are playing backward, we need to use the slide we come from to play the correct transition (backward)
            int transitionSlideIndex = direction == 1 ? slideIndex : CurrentSlideIndex;
            var transitionSlide      = GetSlide(transitionSlideIndex, true);

            // Make sure that the next operations are synchronized by using a transaction
            SCNTransaction.Begin();
            SCNTransaction.AnimationDuration = 0;

            var rootNode      = slide.ContentNode;
            var textContainer = slide.TextManager.TextNode;

            var offset = new SCNVector3(transitionSlide.TransitionOffsetX, 0.0f, transitionSlide.TransitionOffsetZ);

            offset.X *= direction;
            offset.Z *= direction;

            // Rotate offset based on current yaw
            var cosa = Math.Cos(-CameraHandle.Rotation.W);
            var sina = Math.Sin(-CameraHandle.Rotation.W);

            var tmpX = offset.X * cosa - offset.Z * sina;

            offset.Z = (float)(offset.X * sina + offset.Z * cosa);
            offset.X = (float)tmpX;

            // If we don't move, fade in
            if (offset.X == 0 && offset.Y == 0 && offset.Z == 0 && transitionSlide.TransitionRotation == 0)
            {
                rootNode.Opacity = 0;
            }

            // Don't animate the first slide
            bool shouldAnimate = !(slideIndex == 0 && CurrentSlideIndex == 0);

            // Update current slide index
            CurrentSlideIndex = slideIndex;

            // Go to step 0
            GoToSlideStep(0);

            // Add the slide to the scene graph
            ((SCNView)View).Scene.RootNode.AddChildNode(rootNode);

            // Fade in, update paramters and notify on completion
            SCNTransaction.Begin();
            SCNTransaction.AnimationDuration = (shouldAnimate ? slide.TransitionDuration : 0);
            SCNTransaction.SetCompletionBlock(() => DidOrderInSlide(slideIndex));
            rootNode.Opacity = 1;

            CameraHandle.Position = new SCNVector3(CameraHandle.Position.X + offset.X, slide.Altitude, CameraHandle.Position.Z + offset.Z);
            CameraHandle.Rotation = new SCNVector4(0, 1, 0, (float)(CameraHandle.Rotation.W + transitionSlide.TransitionRotation * (Math.PI / 180.0f) * direction));
            CameraPitch.Rotation  = new SCNVector4(1, 0, 0, (float)(slide.Pitch * (Math.PI / 180.0f)));

            UpdateLightingForSlide(slideIndex);

            Floor.Reflectivity         = slide.FloorReflectivity;
            Floor.ReflectionFalloffEnd = slide.FloorFalloff;
            SCNTransaction.Commit();

            // Compute the position of the text (in world space, relative to the camera)
            var textWorldTransform = SCNMatrix4.Mult(SCNMatrix4.CreateTranslation(0, -3.3f, -28), CameraNode.WorldTransform);

            // Place the rest of the slide
            rootNode.Transform = textWorldTransform;
            rootNode.Position  = new SCNVector3(rootNode.Position.X, 0, rootNode.Position.Z);  // clear altitude
            rootNode.Rotation  = new SCNVector4(0, 1, 0, CameraHandle.Rotation.W);             // use same rotation as the camera to simplify the placement of the elements in slides

            // Place the text
            textContainer.Transform = textContainer.ParentNode.ConvertTransformFromNode(textWorldTransform, null);

            // Place the ground node
            var localPosition = new SCNVector3(0, 0, 0);
            var worldPosition = slide.GroundNode.ParentNode.ConvertPositionToNode(localPosition, null);

            worldPosition.Y = 0;             // make it touch the ground

            localPosition             = slide.GroundNode.ParentNode.ConvertPositionFromNode(worldPosition, null);
            slide.GroundNode.Position = localPosition;

            // Update the floor image if needed
            string  floorImagePath = null;
            NSImage floorImage     = null;

            if (slide.FloorImageName != null)
            {
                floorImagePath = NSBundle.MainBundle.PathForResource("SharedTextures/" + slide.FloorImageName, slide.FloorImageExtension);
                floorImage     = new NSImage(floorImagePath);
            }
            UpdateFloorImage(floorImage, slide);

            SCNTransaction.Commit();

            // Preload the next slide after some delay
            var delayInSeconds = 1.5;
            var popTime        = new DispatchTime(DispatchTime.Now, (long)(delayInSeconds * Utils.NSEC_PER_SEC));

            DispatchQueue.MainQueue.DispatchAfter(popTime, () => {
                PrepareSlide(slideIndex + 1);
            });

            // Order out previous slide if any
            if (oldIndex != CurrentSlideIndex)
            {
                WillOrderOutSlide(oldIndex);
            }
        }
예제 #42
0
        public ACSidebarItemCell AddItem(NSImage image, NSObject target, Selector sel)
        {
            ACSidebarItemCell cell = new ACSidebarItemCell(image);
            cell.Target = target;
            cell.Action = sel;

            return cell;
        }
예제 #43
0
		/// <summary>
		/// Initializes a new instance of the <see cref="Rotation.SourceListItem"/> class.
		/// </summary>
		/// <param name="title">Title.</param>
		/// <param name="icon">Icon.</param>
		/// <param name="tag">Tag.</param>
		/// <param name="clicked">Clicked.</param>
		public SourceListItem (string title, NSImage icon, string tag, ClickedDelegate clicked)
		{
			// Initialize
			this._title = title;
			this._icon = icon;
			this._tag = tag;
			this.Clicked = clicked;
		}
예제 #44
0
        public ACSidebarItemCell AddItem(NSImage image)
        {
            ACSidebarItemCell cell = new ACSidebarItemCell(image);
            this.AddCell(cell);

            return cell;
        }
예제 #45
0
		/// <summary>
		/// Adds the item.
		/// </summary>
		/// <param name="title">Title.</param>
		/// <param name="icon">Icon.</param>
		/// <param name="tag">Tag.</param>
		/// <param name="clicked">Clicked.</param>
		public void AddItem(string title, NSImage icon, string tag, ClickedDelegate clicked) {
			_items.Add (new SourceListItem (title, icon, tag, clicked));
		}
예제 #46
0
        public ACSidebarItemCell AddItem(NSImage image, EventHandler onSelect)
        {
            ACSidebarItemCell cell = this.AddItem(image);
            cell.itemSelected += onSelect;

            return cell;
        }
예제 #47
0
 public void DraggedImageEndedAtOperation(NSImage image, CGPoint screenPoint, NSDragOperation operation)
 {
     if (operation == NSDragOperation.Delete) {
         Letter = "";
     }
 }
예제 #48
0
		private static NSImage SCCopyWithResolution (NSImage image, float size)
		{
			var imageRep = image.BestRepresentation (new CGRect (0, 0, size, size), null, null);
			if (imageRep != null) {
				return new NSImage (imageRep.CGImage, imageRep.Size);
			}
			return image;
		}
예제 #49
0
        public override object ConvertToBitmap(ImageDescription idesc, double scaleFactor, ImageFormat format)
        {
            double width       = idesc.Size.Width;
            double height      = idesc.Size.Height;
            int    pixelWidth  = (int)(width * scaleFactor);
            int    pixelHeight = (int)(height * scaleFactor);

            if (idesc.Backend is CustomImage)
            {
                var flags = CGBitmapFlags.ByteOrderDefault;
                int bytesPerRow;
                switch (format)
                {
                case ImageFormat.ARGB32:
                    bytesPerRow = pixelWidth * 4;
                    flags      |= CGBitmapFlags.PremultipliedFirst;
                    break;

                case ImageFormat.RGB24:
                    bytesPerRow = pixelWidth * 3;
                    flags      |= CGBitmapFlags.None;
                    break;

                default:
                    throw new NotImplementedException("ImageFormat: " + format.ToString());
                }

                var bmp = new CGBitmapContext(IntPtr.Zero, pixelWidth, pixelHeight, 8, bytesPerRow, Util.DeviceRGBColorSpace, flags);
                bmp.TranslateCTM(0, pixelHeight);
                bmp.ScaleCTM((float)scaleFactor, (float)-scaleFactor);

                var ctx = new CGContextBackend {
                    Context = bmp,
                    Size    = new CGSize((nfloat)width, (nfloat)height),
                    InverseViewTransform = bmp.GetCTM().Invert(),
                    ScaleFactor          = scaleFactor
                };

                var ci = (CustomImage)idesc.Backend;
                ci.DrawInContext(ctx, idesc);

                var img       = new NSImage(((CGBitmapContext)bmp).ToImage(), new CGSize(pixelWidth, pixelHeight));
                var imageData = img.AsTiff();
                var imageRep  = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData);
                var im        = new NSImage();
                im.AddRepresentation(imageRep);
                im.Size = new CGSize((nfloat)width, (nfloat)height);
                bmp.Dispose();
                return(im);
            }
            else
            {
                NSImage          img    = (NSImage)idesc.Backend;
                NSBitmapImageRep bitmap = img.Representations().OfType <NSBitmapImageRep> ().FirstOrDefault();
                if (bitmap == null)
                {
                    var imageData = img.AsTiff();
                    var imageRep  = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData);
                    var im        = new NSImage();
                    im.AddRepresentation(imageRep);
                    im.Size = new CGSize((nfloat)width, (nfloat)height);
                    return(im);
                }
                return(idesc.Backend);
            }
        }
예제 #50
0
        // Shamelessly copied from React-Native: https://github.com/facebook/react-native/blob/2cbc9127560c5f0f89ae5aa6ff863b1818f1c7c3/Libraries/Image/RCTImageUtils.m
        public static NSImage ToImage(this NSData data, CGSize destSize, nfloat destScale, Configuration config, TaskParameter parameters, RCTResizeMode resizeMode = RCTResizeMode.ScaleAspectFit, ImageInformation imageinformation = null, bool allowUpscale = false)
        {
            using (var sourceRef = CGImageSource.FromData(data))
            {
                if (sourceRef == null)
                {
                    throw new BadImageFormatException("Decoded image is null or corrupted");
                }

                var imageProperties = sourceRef.GetProperties(0);

                if (imageProperties == null || !imageProperties.PixelWidth.HasValue || !imageProperties.PixelHeight.HasValue)
                {
                    throw new BadImageFormatException("Can't read image size properties. File corrupted?");
                }

                imageinformation.SetOriginalSize(imageProperties.PixelWidth.Value, imageProperties.PixelHeight.Value);

                var sourceSize = new CGSize(imageProperties.PixelWidth.Value, imageProperties.PixelHeight.Value);
                if (destSize.IsEmpty)
                {
                    destSize = sourceSize;
                    if (destScale <= 0)
                    {
                        destScale = 1;
                    }
                }
                else if (destScale <= 0)
                {
                    destScale = ScaleHelper.Scale;
                }

                // Calculate target size
                CGSize targetSize      = RCTTargetSize(sourceSize, 1, destSize, destScale, resizeMode, allowUpscale);
                CGSize targetPixelSize = RCTSizeInPixels(targetSize, destScale);
                int    maxPixelSize    = (int)Math.Max(
                    allowUpscale ? targetPixelSize.Width : Math.Min(sourceSize.Width, targetPixelSize.Width),
                    allowUpscale ? targetPixelSize.Height : Math.Min(sourceSize.Height, targetPixelSize.Height)
                    );

                var options = new CGImageThumbnailOptions()
                {
                    ShouldAllowFloat               = true,
                    CreateThumbnailWithTransform   = true,
                    CreateThumbnailFromImageAlways = true,
                    MaxPixelSize = maxPixelSize,
                    ShouldCache  = false,
                };

                NSImage image = null;

                // Get thumbnail
                using (var imageRef = sourceRef.CreateThumbnail(0, options))
                {
                    if (imageRef != null)
                    {
                        // Return image
                        image = new NSImage(imageRef, CGSize.Empty);
                    }
                }


                if (imageinformation != null && image != null)
                {
                    int width  = (int)image.Size.Width;
                    int height = (int)image.Size.Height;
                    imageinformation.SetCurrentSize(width.PointsToPixels(), height.PointsToPixels());
                }

                return(image);
            }
        }
예제 #51
0
        public ACSidebarItemCell AddItem(NSImage image, NSImage alternateImage, NSObject target, Selector sel)
        {
            ACSidebarItemCell cell = this.AddItem(image, target, sel);
            cell.AlternateImage = alternateImage;

            return cell;
        }
예제 #52
0
        public override bool HasMultipleSizes(object handle)
        {
            NSImage img = (NSImage)handle;

            return(img.Size.Width == 0 && img.Size.Height == 0);
        }
예제 #53
0
        public ACSidebarItemCell AddItem(NSImage image, NSImage alternateImage)
        {
            ACSidebarItemCell cell = this.AddItem(image);
            cell.AlternateImage = alternateImage;

            return cell;
        }
예제 #54
0
 public virtual NSView GetView(NSImage value)
 {
     return(new NSImageView {
         Image = value
     });
 }
예제 #55
0
		public static SCNNode SCPlaneNodeWithImage (NSImage image, nfloat size, bool isLit)
		{
			var node = SCNNode.Create ();

			var factor = size / (nfloat)(Math.Max (image.Size.Width, image.Size.Height));

			node.Geometry = SCNPlane.Create (image.Size.Width * factor, image.Size.Height * factor);
			node.Geometry.FirstMaterial.Diffuse.Contents = image;

			//if we don't want the image to be lit, set the lighting model to "constant"
			if (!isLit)
				node.Geometry.FirstMaterial.LightingModelName = SCNLightingModel.Constant;

			return node;
		}
예제 #56
0
 protected virtual NSImage GetTabViewItemIcon(string imageName) => GetTabViewItemIconImageSource(NSImage.ImageNamed(imageName));
예제 #57
0
		public static SCNNode SCBoxNode (string title, CGRect frame, NSColor color, float cornerRadius, bool centered)
		{
			NSMutableDictionary titleAttributes = null;
			NSMutableDictionary centeredTitleAttributes = null;

			// create and extrude a bezier path to build the box
			var path = NSBezierPath.FromRoundedRect (frame, cornerRadius, cornerRadius);
			path.Flatness = 0.05f;

			var shape = SCNShape.Create (path, 20);
			shape.ChamferRadius = 0.0f;

			var node = SCNNode.Create ();
			node.Geometry = shape;

			// create an image and fill with the color and text
			var textureSize = new CGSize ();
			textureSize.Width = NMath.Ceiling (frame.Size.Width * 1.5f);
			textureSize.Height = NMath.Ceiling (frame.Size.Height * 1.5f);

			var texture = new NSImage (textureSize);
			texture.LockFocus ();

			var drawFrame = new CGRect (0, 0, textureSize.Width, textureSize.Height);

			nfloat hue, saturation, brightness, alpha;

			(color.UsingColorSpace (NSColorSpace.DeviceRGBColorSpace)).GetHsba (out hue, out saturation, out brightness, out alpha);
			var lightColor = NSColor.FromDeviceHsba (hue, saturation - 0.2f, brightness + 0.3f, alpha);
			lightColor.Set ();

			NSGraphics.RectFill (drawFrame);

			NSBezierPath fillpath = null;

			if (cornerRadius == 0 && centered == false) {
				//special case for the "labs" slide
				drawFrame.Offset (0, -2);
				fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius);
			} else {
				drawFrame.Inflate (-3, -3);
				fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius);
			}

			color.Set ();
			fillpath.Fill ();

			// draw the title if any
			if (title != null) {
				if (titleAttributes == null) {
					var paraphStyle = new NSMutableParagraphStyle ();
					paraphStyle.LineBreakMode = NSLineBreakMode.ByWordWrapping;
					paraphStyle.Alignment = NSTextAlignment.Center;
					paraphStyle.MinimumLineHeight = 38;
					paraphStyle.MaximumLineHeight = 38;

					var font = NSFont.FromFontName ("Myriad Set Semibold", 34) != null ? NSFont.FromFontName ("Myriad Set Semibold", 34) : NSFont.FromFontName ("Avenir Medium", 34);

					var shadow = new NSShadow ();
					shadow.ShadowOffset = new CGSize (0, -2);
					shadow.ShadowBlurRadius = 4;
					shadow.ShadowColor = NSColor.FromDeviceWhite (0.0f, 0.5f);

					titleAttributes = new NSMutableDictionary ();
					titleAttributes.SetValueForKey (font, NSAttributedString.FontAttributeName);
					titleAttributes.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName);
					titleAttributes.SetValueForKey (shadow, NSAttributedString.ShadowAttributeName);
					titleAttributes.SetValueForKey (paraphStyle, NSAttributedString.ParagraphStyleAttributeName);

					var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy ();
					centeredParaphStyle.Alignment = NSTextAlignment.Center;

					centeredTitleAttributes = new NSMutableDictionary ();
					centeredTitleAttributes.SetValueForKey (font, NSAttributedString.FontAttributeName);
					centeredTitleAttributes.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName);
					centeredTitleAttributes.SetValueForKey (shadow, NSAttributedString.ShadowAttributeName);
					centeredTitleAttributes.SetValueForKey (paraphStyle, NSAttributedString.ParagraphStyleAttributeName);
				}

				var attrString = new NSAttributedString (title, centered ? centeredTitleAttributes : titleAttributes);
				var textSize = attrString.Size;

				//check if we need two lines to draw the text
				var twoLines = title.Contains ("\n");
				if (!twoLines)
					twoLines = textSize.Width > frame.Size.Width && title.Contains (" ");

				//if so, we need to adjust the size to center vertically
				if (twoLines)
					textSize.Height += 38;

				if (!centered)
					drawFrame.Inflate (-15, 0);

				//center vertically
				var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f;
				var drawFrameHeight = drawFrame.Size.Height;
				drawFrame.Size = new CGSize (drawFrame.Size.Width, drawFrame.Size.Height - dy);
				attrString.DrawString (drawFrame);
			}

			texture.UnlockFocus ();

			//set the created image as the diffuse texture of our 3D box
			var front = SCNMaterial.Create ();
			front.Diffuse.Contents = texture;
			front.LocksAmbientWithDiffuse = true;

			//use a lighter color for the chamfer and sides
			var sides = SCNMaterial.Create ();
			sides.Diffuse.Contents = lightColor;
			node.Geometry.Materials = new SCNMaterial[] {
				front,
				sides,
				sides,
				sides,
				sides
			};

			return node;
		}
 protected override NSImage Transform(NSImage sourceBitmap, string path, Work.ImageSource source, bool isPlaceholder, string key)
 {
     return(Helpers.MainThreadDispatcher.PostForResult <NSImage>(() => ToBlurred(sourceBitmap, (float)Radius)));
 }
		public CustomCatTextAttachmentCell (NSImage image) : base (image)
		{
			borderColor = NSColor.FromDeviceHsba ((float)random.NextDouble (), 1f, 1f, 1f);
		}
예제 #60
0
        public SparkleSetup() : base()
        {
            Controller.ChangePageEvent += delegate(PageType type, string [] warnings) {
                InvokeOnMainThread(delegate {
                    Reset();

                    switch (type)
                    {
                    case PageType.Setup: {
                        Header      = "Welcome to SparkleShare!";
                        Description = "We'll need some info to mark your changes in the event log. " +
                                      "Don't worry, this stays between you and your peers.";


                        FullNameLabel = new NSTextField()
                        {
                            Alignment       = NSTextAlignment.Right,
                            BackgroundColor = NSColor.WindowBackground,
                            Bordered        = false,
                            Editable        = false,
                            Frame           = new RectangleF(165, Frame.Height - 234, 160, 17),
                            StringValue     = "Full Name:",
                            Font            = SparkleUI.Font
                        };

                        FullNameTextField = new NSTextField()
                        {
                            Frame       = new RectangleF(330, Frame.Height - 238, 196, 22),
                            StringValue = Controller.GuessedUserName,
                            Delegate    = new SparkleTextFieldDelegate()
                        };

                        EmailLabel = new NSTextField()
                        {
                            Alignment       = NSTextAlignment.Right,
                            BackgroundColor = NSColor.WindowBackground,
                            Bordered        = false,
                            Editable        = false,
                            Frame           = new RectangleF(165, Frame.Height - 264, 160, 17),
                            StringValue     = "Email:",
                            Font            = SparkleUI.Font
                        };

                        EmailTextField = new NSTextField()
                        {
                            Frame       = new RectangleF(330, Frame.Height - 268, 196, 22),
                            StringValue = Controller.GuessedUserEmail,
                            Delegate    = new SparkleTextFieldDelegate()
                        };


                        (FullNameTextField.Delegate as SparkleTextFieldDelegate).StringValueChanged += delegate {
                            Controller.CheckSetupPage(
                                FullNameTextField.StringValue,
                                EmailTextField.StringValue
                                );
                        };

                        (EmailTextField.Delegate as SparkleTextFieldDelegate).StringValueChanged += delegate {
                            Controller.CheckSetupPage(
                                FullNameTextField.StringValue,
                                EmailTextField.StringValue
                                );
                        };


                        ContinueButton = new NSButton()
                        {
                            Title   = "Continue",
                            Enabled = false
                        };

                        ContinueButton.Activated += delegate {
                            string full_name = FullNameTextField.StringValue.Trim();
                            string email     = EmailTextField.StringValue.Trim();

                            Controller.SetupPageCompleted(full_name, email);
                        };

                        Controller.UpdateSetupContinueButtonEvent += delegate(bool button_enabled) {
                            InvokeOnMainThread(delegate {
                                    ContinueButton.Enabled = button_enabled;
                                });
                        };


                        ContentView.AddSubview(FullNameLabel);
                        ContentView.AddSubview(FullNameTextField);
                        ContentView.AddSubview(EmailLabel);
                        ContentView.AddSubview(EmailTextField);

                        Buttons.Add(ContinueButton);

                        Controller.CheckSetupPage(
                            FullNameTextField.StringValue,
                            EmailTextField.StringValue
                            );

                        break;
                    }

                    case PageType.Add: {
                        Header      = "Where's your project hosted?";
                        Description = "";

                        AddressLabel = new NSTextField()
                        {
                            Alignment       = NSTextAlignment.Left,
                            BackgroundColor = NSColor.WindowBackground,
                            Bordered        = false,
                            Editable        = false,
                            Frame           = new RectangleF(190, Frame.Height - 308, 160, 17),
                            StringValue     = "Address:",
                            Font            = SparkleUI.Font
                        };

                        AddressTextField = new NSTextField()
                        {
                            Frame       = new RectangleF(190, Frame.Height - 336, 196, 22),
                            Font        = SparkleUI.Font,
                            StringValue = Controller.PreviousAddress,
                            Enabled     = (Controller.SelectedPlugin.Address == null),
                            Delegate    = new SparkleTextFieldDelegate()
                        };


                        PathLabel = new NSTextField()
                        {
                            Alignment       = NSTextAlignment.Left,
                            BackgroundColor = NSColor.WindowBackground,
                            Bordered        = false,
                            Editable        = false,
                            Frame           = new RectangleF(190 + 196 + 16, Frame.Height - 308, 160, 17),
                            StringValue     = "Remote Path:",
                            Font            = SparkleUI.Font
                        };

                        PathTextField = new NSTextField()
                        {
                            Frame       = new RectangleF(190 + 196 + 16, Frame.Height - 336, 196, 22),
                            StringValue = Controller.PreviousPath,
                            Enabled     = (Controller.SelectedPlugin.Path == null),
                            Delegate    = new SparkleTextFieldDelegate()
                        };


                        AddressTextField.Cell.LineBreakMode = NSLineBreakMode.TruncatingTail;
                        PathTextField.Cell.LineBreakMode    = NSLineBreakMode.TruncatingTail;


                        PathHelpLabel = new NSTextField()
                        {
                            BackgroundColor = NSColor.WindowBackground,
                            Bordered        = false,
                            TextColor       = NSColor.DisabledControlText,
                            Editable        = false,
                            Frame           = new RectangleF(190 + 196 + 16, Frame.Height - 355, 204, 17),
                            StringValue     = "e.g. ‘rupert/website-design’",
                            Font            = NSFontManager.SharedFontManager.FontWithFamily
                                                  ("Lucida Grande", NSFontTraitMask.Condensed, 0, 11)
                        };


                        TableView = new NSTableView()
                        {
                            Frame            = new RectangleF(0, 0, 0, 0),
                            RowHeight        = 30,
                            IntercellSpacing = new SizeF(0, 12),
                            HeaderView       = null,
                            Delegate         = new SparkleTableViewDelegate()
                        };

                        ScrollView = new NSScrollView()
                        {
                            Frame               = new RectangleF(190, Frame.Height - 280, 408, 175),
                            DocumentView        = TableView,
                            HasVerticalScroller = true,
                            BorderType          = NSBorderType.BezelBorder
                        };

                        IconColumn = new NSTableColumn(new NSImage())
                        {
                            Width         = 42,
                            HeaderToolTip = "Icon",
                            DataCell      = new NSImageCell()
                        };

                        DescriptionColumn = new NSTableColumn()
                        {
                            Width         = 350,
                            HeaderToolTip = "Description",
                            Editable      = false
                        };

                        DescriptionColumn.DataCell.Font =
                            NSFontManager.SharedFontManager.FontWithFamily(
                                "Lucida Grande", NSFontTraitMask.Condensed, 0, 11);

                        TableView.AddColumn(IconColumn);
                        TableView.AddColumn(DescriptionColumn);

                        DataSource = new SparkleDataSource();

                        foreach (SparklePlugin plugin in Controller.Plugins)
                        {
                            DataSource.Items.Add(plugin);
                        }

                        TableView.DataSource = DataSource;
                        TableView.ReloadData();


                        Controller.ChangeAddressFieldEvent += delegate(string text,
                                                                       string example_text, FieldState state) {
                            InvokeOnMainThread(delegate {
                                    AddressTextField.StringValue = text;
                                    AddressTextField.Enabled     = (state == FieldState.Enabled);
                                });
                        };


                        Controller.ChangePathFieldEvent += delegate(string text,
                                                                    string example_text, FieldState state) {
                            InvokeOnMainThread(delegate {
                                    PathTextField.StringValue = text;
                                    PathTextField.Enabled     = (state == FieldState.Enabled);

                                    if (!string.IsNullOrEmpty(example_text))
                                    {
                                        PathHelpLabel.StringValue = "e.g. " + example_text;
                                    }
                                });
                        };


                        TableView.SelectRow(Controller.SelectedPluginIndex, false);


                        (AddressTextField.Delegate as SparkleTextFieldDelegate).StringValueChanged += delegate {
                            Controller.CheckAddPage(
                                AddressTextField.StringValue,
                                PathTextField.StringValue,
                                TableView.SelectedRow
                                );
                        };

                        (PathTextField.Delegate as SparkleTextFieldDelegate).StringValueChanged += delegate {
                            Controller.CheckAddPage(
                                AddressTextField.StringValue,
                                PathTextField.StringValue,
                                TableView.SelectedRow
                                );
                        };

                        (TableView.Delegate as SparkleTableViewDelegate).SelectionChanged += delegate {
                            Controller.SelectedPluginChanged(TableView.SelectedRow);

                            Controller.CheckAddPage(
                                AddressTextField.StringValue,
                                PathTextField.StringValue,
                                TableView.SelectedRow
                                );
                        };


                        Controller.UpdateAddProjectButtonEvent += delegate(bool button_enabled) {
                            InvokeOnMainThread(delegate {
                                    SyncButton.Enabled = button_enabled;
                                });
                        };


                        ContentView.AddSubview(ScrollView);
                        ContentView.AddSubview(AddressLabel);
                        ContentView.AddSubview(AddressTextField);
                        ContentView.AddSubview(PathLabel);
                        ContentView.AddSubview(PathTextField);
                        ContentView.AddSubview(PathHelpLabel);

                        SyncButton = new NSButton()
                        {
                            Title   = "Add",
                            Enabled = false
                        };

                        SyncButton.Activated += delegate {
                            Controller.AddPageCompleted(
                                AddressTextField.StringValue,
                                PathTextField.StringValue
                                );
                        };

                        Buttons.Add(SyncButton);

                        CancelButton = new NSButton()
                        {
                            Title = "Cancel"
                        };

                        CancelButton.Activated += delegate {
                            InvokeOnMainThread(delegate {
                                    PerformClose(this);
                                });
                        };

                        Buttons.Add(CancelButton);

                        Controller.CheckAddPage(
                            AddressTextField.StringValue,
                            PathTextField.StringValue,
                            TableView.SelectedRow
                            );


                        break;
                    }

                    case PageType.Syncing: {
                        Header      = "Adding project ‘" + Controller.SyncingFolder + "’…";
                        Description = "This may take a while.\n" +
                                      "Are you sure it’s not coffee o'clock?";

                        ProgressIndicator = new NSProgressIndicator()
                        {
                            Frame         = new RectangleF(190, Frame.Height - 200, 640 - 150 - 80, 20),
                            Style         = NSProgressIndicatorStyle.Bar,
                            MinValue      = 0.0,
                            MaxValue      = 100.0,
                            Indeterminate = false,
                            DoubleValue   = 1.0
                        };

                        ProgressIndicator.StartAnimation(this);

                        Controller.UpdateProgressBarEvent += delegate(double percentage) {
                            InvokeOnMainThread(delegate {
                                    ProgressIndicator.DoubleValue = percentage;
                                });
                        };

                        ContentView.AddSubview(ProgressIndicator);

                        FinishButton = new NSButton()
                        {
                            Title   = "Finish",
                            Enabled = false
                        };

                        CancelButton = new NSButton()
                        {
                            Title = "Cancel"
                        };

                        CancelButton.Activated += delegate {
                            Controller.SyncingCancelled();
                        };

                        Buttons.Add(FinishButton);
                        Buttons.Add(CancelButton);

                        break;
                    }

                    case PageType.Error: {
                        Header      = "Something went wrong…";
                        Description = "Please check the following:";

                        // Displaying marked up text with Cocoa is
                        // a pain, so we just use a webview instead
                        WebView web_view = new WebView();
                        web_view.Frame   = new RectangleF(190, Frame.Height - 525, 375, 400);

                        string html = "<style>" +
                                      "* {" +
                                      "  font-family: 'Lucida Grande';" +
                                      "  font-size: 12px; cursor: default;" +
                                      "}" +
                                      "body {" +
                                      "  -webkit-user-select: none;" +
                                      "  margin: 0;" +
                                      "  padding: 3px;" +
                                      "}" +
                                      "li {" +
                                      "  margin-bottom: 16px;" +
                                      "  margin-left: 0;" +
                                      "  padding-left: 0;" +
                                      "  line-height: 20px;" +
                                      "}" +
                                      "ul {" +
                                      "  padding-left: 24px;" +
                                      "}" +
                                      "</style>" +
                                      "<ul>" +
                                      "  <li>First, have you tried turning it off and on again?</li>" +
                                      "  <li><b>" + Controller.PreviousUrl + "</b> is the address we've compiled. Does this look alright?</li>" +
                                      "  <li>The host needs to know who you are. Did you upload the key that's in your SparkleShare folder?</li>" +
                                      "</ul>";

                        web_view.MainFrame.LoadHtmlString(html, new NSUrl(""));
                        web_view.DrawsBackground = false;

                        ContentView.AddSubview(web_view);

                        TryAgainButton = new NSButton()
                        {
                            Title = "Try again…"
                        };

                        TryAgainButton.Activated += delegate {
                            Controller.ErrorPageCompleted();
                        };

                        Buttons.Add(TryAgainButton);

                        break;
                    }

                    case PageType.Finished: {
                        Header      = "Project succesfully added!";
                        Description = "Now you can access the files from " +
                                      "‘" + Controller.SyncingFolder + "’ in " +
                                      "your SparkleShare folder.";

                        if (warnings != null)
                        {
                            WarningImage      = NSImage.ImageNamed("NSCaution");
                            WarningImage.Size = new SizeF(24, 24);

                            WarningImageView = new NSImageView()
                            {
                                Image = WarningImage,
                                Frame = new RectangleF(190, Frame.Height - 175, 24, 24)
                            };

                            WarningTextField = new NSTextField()
                            {
                                Frame           = new RectangleF(230, Frame.Height - 245, 325, 100),
                                StringValue     = warnings [0],
                                BackgroundColor = NSColor.WindowBackground,
                                Bordered        = false,
                                Editable        = false,
                                Font            = SparkleUI.Font
                            };

                            ContentView.AddSubview(WarningImageView);
                            ContentView.AddSubview(WarningTextField);
                        }

                        FinishButton = new NSButton()
                        {
                            Title = "Finish"
                        };

                        FinishButton.Activated += delegate {
                            InvokeOnMainThread(delegate {
                                    Controller.FinishedPageCompleted();
                                    PerformClose(this);
                                });
                        };

                        OpenFolderButton = new NSButton()
                        {
                            Title = "Open Folder"
                        };

                        OpenFolderButton.Activated += delegate {
                            Program.Controller.OpenSparkleShareFolder(Controller.SyncingFolder);
                        };

                        Buttons.Add(FinishButton);
                        Buttons.Add(OpenFolderButton);

                        NSApplication.SharedApplication.RequestUserAttention
                            (NSRequestUserAttentionType.CriticalRequest);

                        NSSound.FromName("Glass").Play();

                        break;
                    }

                    case PageType.Tutorial: {
                        switch (Controller.TutorialPageNumber)
                        {
                        case 1: {
                            Header      = "What's happening next?";
                            Description = "SparkleShare creates a special folder in your personal folder " +
                                          "that will keep track of your projects.";

                            SkipTutorialButton = new NSButton()
                            {
                                Title = "Skip Tutorial"
                            };

                            SkipTutorialButton.Activated += delegate {
                                Controller.TutorialSkipped();
                            };

                            ContinueButton = new NSButton()
                            {
                                Title = "Continue"
                            };

                            ContinueButton.Activated += delegate {
                                Controller.TutorialPageCompleted();
                            };

                            string slide_image_path = Path.Combine(NSBundle.MainBundle.ResourcePath,
                                                                   "Pixmaps", "tutorial-slide-1.png");

                            SlideImage = new NSImage(slide_image_path)
                            {
                                Size = new SizeF(350, 200)
                            };

                            SlideImageView = new NSImageView()
                            {
                                Image = SlideImage,
                                Frame = new RectangleF(215, Frame.Height - 350, 350, 200)
                            };

                            ContentView.AddSubview(SlideImageView);
                            Buttons.Add(ContinueButton);
                            Buttons.Add(SkipTutorialButton);

                            break;
                        }

                        case 2: {
                            Header      = "Sharing files with others";
                            Description = "All files added to your project folders are synced with the host " +
                                          "automatically, as well as with your collaborators.";

                            ContinueButton = new NSButton()
                            {
                                Title = "Continue"
                            };

                            ContinueButton.Activated += delegate {
                                Controller.TutorialPageCompleted();
                            };

                            string slide_image_path = Path.Combine(NSBundle.MainBundle.ResourcePath,
                                                                   "Pixmaps", "tutorial-slide-2.png");

                            SlideImage = new NSImage(slide_image_path)
                            {
                                Size = new SizeF(350, 200)
                            };

                            SlideImageView = new NSImageView()
                            {
                                Image = SlideImage,
                                Frame = new RectangleF(215, Frame.Height - 350, 350, 200)
                            };

                            ContentView.AddSubview(SlideImageView);
                            Buttons.Add(ContinueButton);

                            break;
                        }

                        case 3: {
                            Header      = "The status icon is here to help";
                            Description = "It shows the syncing process status, " +
                                          "and contains links to your projects and the event log.";

                            ContinueButton = new NSButton()
                            {
                                Title = "Continue"
                            };

                            ContinueButton.Activated += delegate {
                                Controller.TutorialPageCompleted();
                            };

                            string slide_image_path = Path.Combine(NSBundle.MainBundle.ResourcePath,
                                                                   "Pixmaps", "tutorial-slide-3.png");

                            SlideImage = new NSImage(slide_image_path)
                            {
                                Size = new SizeF(350, 200)
                            };

                            SlideImageView = new NSImageView()
                            {
                                Image = SlideImage,
                                Frame = new RectangleF(215, Frame.Height - 350, 350, 200)
                            };

                            ContentView.AddSubview(SlideImageView);
                            Buttons.Add(ContinueButton);

                            break;
                        }

                        case 4: {
                            Header      = "Adding projects to SparkleShare";
                            Description = "Just click this button when you see it on the web, and " +
                                          "the project will be automatically added:";

                            AddProjectTextField = new NSTextField()
                            {
                                Frame           = new RectangleF(190, Frame.Height - 290, 640 - 240, 44),
                                BackgroundColor = NSColor.WindowBackground,
                                Bordered        = false,
                                Editable        = false,
                                Font            = SparkleUI.Font,
                                StringValue     = "…or select ‘Add Hosted Project…’ from the status icon menu " +
                                                  "to add one by hand."
                            };

                            FinishButton = new NSButton()
                            {
                                Title = "Finish"
                            };

                            FinishButton.Activated += delegate {
                                InvokeOnMainThread(delegate {
                                            PerformClose(this);
                                        });
                            };

                            string slide_image_path = Path.Combine(NSBundle.MainBundle.ResourcePath,
                                                                   "Pixmaps", "tutorial-slide-4.png");

                            SlideImage = new NSImage(slide_image_path)
                            {
                                Size = new SizeF(350, 64)
                            };

                            SlideImageView = new NSImageView()
                            {
                                Image = SlideImage,
                                Frame = new RectangleF(215, Frame.Height - 215, 350, 64)
                            };

                            ContentView.AddSubview(SlideImageView);
                            ContentView.AddSubview(AddProjectTextField);
                            Buttons.Add(FinishButton);

                            break;
                        }
                        }

                        break;
                    }
                    }

                    ShowAll();
                });
            };
        }