コード例 #1
0
		public void DeletePerson(NSWindow window) {
			if (Table.SelectedRow == -1) {
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = "Please select the person to remove from the list of people.",
					MessageText = "Delete Person",
				};
				alert.BeginSheet (window);
			} else {
				// Grab person
				SelectedPerson = _people.GetItem<PersonModel> ((nuint)Table.SelectedRow);

				// Confirm delete
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = string.Format("Are you sure you want to delete person `{0}` from the table?",SelectedPerson.Name),
					MessageText = "Delete Person",
				};
				alert.AddButton ("Ok");
				alert.AddButton ("Cancel");
				alert.BeginSheetForResponse (window, (result) => {
					// Delete?
					if (result == 1000) {
						RemovePerson(Table.SelectedRow);
					}
				});
			}
		}
コード例 #2
0
		public void DeletePerson(NSWindow window) {

			// Anything to process?
			if (SelectedPerson == null) {
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = "Please select the person to remove from the collection of people.",
					MessageText = "Delete Person",
				};
				alert.BeginSheet (window);
			} else {
				// Confirm delete
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = string.Format ("Are you sure you want to delete person `{0}` from the collection?", SelectedPerson.Name),
					MessageText = "Delete Person",
				};
				alert.AddButton ("Ok");
				alert.AddButton ("Cancel");
				alert.BeginSheetForResponse (window, (result) => {
					// Delete?
					if (result == 1000) {
						RemovePerson (View.SelectionIndex);
					}
				});
			}
		}
コード例 #3
0
ファイル: TableDelegate.cs プロジェクト: runecats/mac-samples
		public override void SelectionDidChange (NSNotification notification)
		{
			Console.WriteLine (notification);
			var table = notification.Object as NSTableView;
			var row = table.SelectedRow;

			// Anything to process
			if (row < 0)
				return;

			// Get current values from the data source
			var name = table.DataSource.GetObjectValue (table, new NSTableColumn("name"), row) + "";
			var id = table.DataSource.GetObjectValue (table, new NSTableColumn("id"), row) + "";

			// Confirm deletion of a todo item
			var alert = new NSAlert () {
				AlertStyle = NSAlertStyle.Critical,
				InformativeText = "Do you want to delete row " + name + "?",
				MessageText = "Delete Todo",
			};
			alert.AddButton ("Cancel");
			alert.AddButton ("Delete");
			alert.BeginSheetForResponse (windowController.Window, async (result) => {
				Console.WriteLine ("Alert Result: {0}", result);
				if (result == 1001) {
					await windowController.Delete(id);
				}
				table.DeselectAll(this);
			});
		}
コード例 #4
0
		/// <summary>
		/// Called before an <c>NSWindow</c> is closed. If the contents of the window has changed and
		/// not been saved, display a dialog allowing the user to: a) Cancel the closing, b) Close
		/// without saving, c) Save the changes to the document.
		/// </summary>
		/// <returns><c>true</c>, if the window can be closed, else <c>false</c> if it cannot.</returns>
		/// <param name="sender">The <c>NSWindowController</c> calling this method.</param>
		public override bool WindowShouldClose (Foundation.NSObject sender)
		{
			// is the window dirty?
			if (Window.DocumentEdited) {
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = "Save changes to document before closing window?",
					MessageText = "Save Document",
				};
				alert.AddButton ("Save");
				alert.AddButton ("Lose Changes");
				alert.AddButton ("Cancel");
				var result = alert.RunSheetModal (Window);

				// Take action based on resu;t
				switch (result) {
				case 1000:
					// Grab controller
					var viewController = Window.ContentViewController as ViewController;

					// Already saved?
					if (Window.RepresentedUrl != null) {
						var path = Window.RepresentedUrl.Path;

						// Save changes to file
						File.WriteAllText (path, viewController.Text);
						return true;
					} else {
						var dlg = new NSSavePanel ();
						dlg.Title = "Save Document";
						dlg.BeginSheet (Window, (rslt) => {
							// File selected?
							if (rslt == 1) {
								var path = dlg.Url.Path;
								File.WriteAllText (path, viewController.Text);
								Window.DocumentEdited = false;
								viewController.View.Window.SetTitleWithRepresentedFilename (Path.GetFileName(path));
								viewController.View.Window.RepresentedUrl = dlg.Url;
								Window.Close();
							}
						});
						return true;
					}
					return false;
				case 1001:
					// Lose Changes
					return true;
				case 1002:
					// Cancel
					return false;
				}
			}

			return true;
		}
コード例 #5
0
		public static bool ShowConfirm (String text, String caption)
		{
			var oAlert = new NSAlert();

			// Set the buttons
			oAlert.AddButton("Yes");
			oAlert.AddButton("No");

			// Show the message box and capture
			oAlert.MessageText = caption;
			oAlert.InformativeText = text;
			oAlert.AlertStyle = NSAlertStyle.Warning;
			oAlert.Icon = NSImage.ImageNamed (NSImageName.Caution);
			var responseAlert = oAlert.RunModal();
			return (responseAlert == 1000);
		}
コード例 #6
0
        public static bool ConfirmDeleteOperation (string confirmMessage)
        {
            try {
				var oAlert = new NSAlert();

				// Set the buttons
				oAlert.AddButton("Yes");
				oAlert.AddButton("No");

				// Show the message box and capture
				oAlert.MessageText = confirmMessage;
				oAlert.InformativeText = "Confirmation";
				oAlert.AlertStyle = NSAlertStyle.Warning;
				oAlert.Icon = NSImage.ImageNamed (NSImageName.Caution);
				var responseAlert = oAlert.RunModal();
				return (responseAlert == 1000); //returns 1001 for No and 1000 for Yes in this case
            } catch (Exception e) {
                throw e;
            }
        }
コード例 #7
0
		public override void AwakeFromNib ()
		{
			msgPort = CFMessagePort.CreateRemotePort (CFAllocator.Default, "com.example.app.port.server");
			if (msgPort == null) {
				var alert = new NSAlert {
					MessageText = "Unable to connect to port? Did you launch server first?",
				};
				alert.AddButton ("OK");
				alert.RunSheetModal (Window);
			}
			TheButton.Activated += SendMessage;
		}
コード例 #8
0
        static void Main(string[] args)
        {
            NSApplication.Init();
            NSApplication.SharedApplication.ActivationPolicy = NSApplicationActivationPolicy.Regular;

            var xPos       = NSScreen.MainScreen.Frame.Width / 2;  // NSWidth([[window screen] frame])/ 2 - NSWidth([window frame])/ 2;
            var yPos       = NSScreen.MainScreen.Frame.Height / 2; // NSHeight([[window screen] frame])/ 2 - NSHeight([window frame])/ 2;
            var mainWindow = new MacAccInspectorWindow(new CGRect(xPos, yPos, 300, 368), NSWindowStyle.Titled | NSWindowStyle.Resizable | NSWindowStyle.Closable, NSBackingStore.Buffered, false);

            var stackView = new NSStackView()
            {
                Orientation = NSUserInterfaceLayoutOrientation.Vertical
            };

            mainWindow.ContentView = stackView;
            stackView.AddArrangedSubview(new NSTextField {
                StringValue = "123"
            });

            stackView.AddArrangedSubview(new NSTextField {
                StringValue = "45"
            });
            stackView.AddArrangedSubview(new NSTextField {
                StringValue = "345"
            });
            var button = new NSButton {
                Title = "Press to show a message"
            };

            stackView.AddArrangedSubview(button);

            var hotizontalView = new NSStackView()
            {
                Orientation = NSUserInterfaceLayoutOrientation.Horizontal
            };

            hotizontalView.AddArrangedSubview(new NSTextField()
            {
                StringValue = "test"
            });

            stackView.AddArrangedSubview(hotizontalView);

            button.Activated += (sender, e) => {
                var alert = new NSAlert();
                alert.MessageText     = "You clicked the button!!!";
                alert.InformativeText = "Are you sure!?";
                alert.AddButton("OK!");
                alert.RunModal();
            };

            var button2 = new NSButton {
                Title = "Opens Localized text"
            };

            button2.Activated += (sender, e) => {
                var window = new NSWindow()
                {
                    StyleMask = NSWindowStyle.Titled | NSWindowStyle.Resizable | NSWindowStyle.Closable
                };
                var stack = NativeViewHelper.CreateHorizontalStackView();
                var label = NativeViewHelper.CreateLabel("hello");
                stack.AddArrangedSubview(label);
                window.ContentView = stack;
                window.WillClose  += (sender1, e1) =>
                {
                    window.Dispose();
                };
                window.MakeKeyAndOrderFront(mainWindow);
            };
            stackView.AddArrangedSubview(button2);
            button2.HeightAnchor.ConstraintEqualToConstant(100).Active = true;;

            mainWindow.Title = "Example Debug Xamarin.Mac";

            //mainWindow.MakeKeyWindow();
            mainWindow.MakeKeyAndOrderFront(null);
            NSApplication.SharedApplication.ActivateIgnoringOtherApps(true);
            NSApplication.SharedApplication.Run();
            //mainWindow.Dispose();
        }
コード例 #9
0
        public override NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, nint row)
        {
            // This pattern allows you reuse existing views when they are no-longer in use.
            // If the returned view is null, you instance up a new view
            // If a non-null view is returned, you modify it enough to reflect the new data
            NSTableCellView view = (NSTableCellView)tableView.MakeView(tableColumn.Title, this);

            if (view == null)
            {
                view = new NSTableCellView();

                // Configure the view
                view.Identifier = tableColumn.Title;

                // Take action based on title
                switch (tableColumn.Title)
                {
                case "Product":
                    view.ImageView = new NSImageView(new CGRect(0, 0, 16, 16));
                    view.AddSubview(view.ImageView);
                    view.TextField = new NSTextField(new CGRect(20, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Details":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Action":
                    // Create new button
                    var button = new NSButton(new CGRect(0, 0, 81, 16));
                    button.SetButtonType(NSButtonType.MomentaryPushIn);
                    button.Title = "Delete";
                    button.Tag   = row;

                    // Wireup events
                    button.Activated += (sender, e) => {
                        // Get button and product
                        var btn     = sender as NSButton;
                        var product = DataSource.Products [(int)btn.Tag];

                        // Configure alert
                        var alert = new NSAlert()
                        {
                            AlertStyle      = NSAlertStyle.Informational,
                            InformativeText = $"Are you sure you want to delete {product.Title}? This operation cannot be undone.",
                            MessageText     = $"Delete {product.Title}?",
                        };
                        alert.AddButton("Cancel");
                        alert.AddButton("Delete");
                        alert.BeginSheetForResponse(Controller.View.Window, (result) => {
                            // Should we delete the requested row?
                            if (result == 1001)
                            {
                                // Remove the given row from the dataset
                                DataSource.Products.RemoveAt((int)btn.Tag);
                                Controller.ReloadTable();
                            }
                        });
                    };

                    // Add to view
                    view.AddSubview(button);
                    break;
                }
            }

            // Setup view based on the column selected
            switch (tableColumn.Title)
            {
            case "Product":
                view.ImageView.Image       = NSImage.ImageNamed("tag.png");
                view.TextField.StringValue = DataSource.Products [(int)row].Title;
                view.TextField.Tag         = row;
                break;

            case "Details":
                view.TextField.StringValue = DataSource.Products [(int)row].Description;
                view.TextField.Tag         = row;
                break;

            case "Action":
                foreach (NSView subview in view.Subviews)
                {
                    var btn = subview as NSButton;
                    if (btn != null)
                    {
                        btn.Tag = row;
                    }
                }
                break;
            }

            return(view);
        }
コード例 #10
0
        public override NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, nint row)
        {
            // This pattern allows you reuse existing views when they are no-longer in use.
            // If the returned view is null, you instance up a new view
            // If a non-null view is returned, you modify it enough to reflect the new data
            NSTableCellView view = (NSTableCellView)tableView.MakeView(tableColumn.Title, this);

            view = new NSTableCellView();
            var showPassword = DataSource.Records[(int)row].ShowPassword;

            // Configure the view
            view.Identifier = tableColumn.Title;

            // Take action based on title
            switch (tableColumn.Title)
            {
            case "Website/Service":
            case "Account Name":
                view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                ConfigureTextField(view, row);
                break;

            case "Password":
                view.TextField = showPassword ? new NSTextField(new CGRect(0, 0, 400, 16)) : new NSSecureTextField(new CGRect(0, 0, 400, 16));
                ConfigureTextField(view, row);
                break;

            case "Actions":
                // Create new button
                var removeButton = new NSButton(new CGRect(0, 0, 60, 16));
                removeButton.Tag      = row;
                removeButton.Bordered = false;
                removeButton.Cell     = new NSButtonCell {
                    BackgroundColor = NSColor.DarkGray, Title = "Remove"
                };

                // Wireup events
                removeButton.Activated += (sender, e) =>
                {
                    // Get button and product
                    var btn        = sender as NSButton;
                    var record     = DataSource.Records[(int)btn.Tag];
                    var connection = SqliteManager.GetDatabaseConnection();

                    // Configure alert
                    var alert = new NSAlert()
                    {
                        AlertStyle      = NSAlertStyle.Informational,
                        InformativeText = $"Are you sure you want to delete data for {record.Website}? This operation cannot be undone.",
                        MessageText     = $"Delete data for {record.Website}?",
                    };
                    alert.AddButton("Cancel");
                    alert.AddButton("Delete");
                    alert.BeginSheetForResponse(Controller.View.Window, (result) =>
                    {
                        // Should we delete the requested row?
                        if (result == 1001)
                        {
                            // Remove the given row from the dataset
                            DataSource.RemoveRecord(record, connection);
                            Controller.PushView();
                        }
                    });
                };

                view.AddSubview(removeButton);

                var showButton = new NSButton(new CGRect(70, 0, 60, 16));
                showButton.Tag  = row;
                showButton.Cell = new NSButtonCell {
                    BackgroundColor = NSColor.DarkGray, Title = showPassword ? "Hide" : "Show"
                };

                showButton.Activated += (sender, e) =>
                {
                    var btn            = sender as NSButton;
                    var selectedRecord = DataSource.Records[(int)btn.Tag];

                    foreach (var record in DataSource.Records)
                    {
                        record.ShowPassword = false;
                    }

                    selectedRecord.ShowPassword = showPassword ? false : true;
                    Controller.PushView();
                };

                view.AddSubview(showButton);

                var copyButton = new NSButton(new CGRect(140, 0, 60, 16));
                copyButton.Tag  = row;
                copyButton.Cell = new NSButtonCell {
                    BackgroundColor = NSColor.DarkGray, Title = "Copy"
                };

                copyButton.Activated += (sender, e) =>
                {
                    var btn            = sender as NSButton;
                    var selectedRecord = DataSource.Records[(int)btn.Tag];

                    var pasteboard = NSPasteboard.GeneralPasteboard;
                    pasteboard.ClearContents();
                    pasteboard.WriteObjects(new NSString[] { (NSString)selectedRecord.Password });
                };

                view.AddSubview(copyButton);

                var editButton = new NSButton(new CGRect(210, 0, 60, 16));
                editButton.Tag  = row;
                editButton.Cell = new NSButtonCell {
                    BackgroundColor = NSColor.DarkGray, Title = "Edit"
                };

                editButton.Activated += (sender, e) =>
                {
                    var btn            = sender as NSButton;
                    var selectedRecord = DataSource.Records[(int)btn.Tag];
                    var connection     = SqliteManager.GetDatabaseConnection();

                    Controller.RefillRecord(selectedRecord, btn.Tag);
                    DataSource.RemoveRecord(selectedRecord, connection);
                };

                view.AddSubview(editButton);
                break;
            }

            // Setup view based on the column selected
            switch (tableColumn.Title)
            {
            case "Website/Service":
                view.TextField.StringValue = DataSource.Records[(int)row].Website;
                break;

            case "Account Name":
                view.TextField.StringValue = DataSource.Records[(int)row].AccountName;
                break;

            case "Password":
                view.TextField.StringValue = DataSource.Records[(int)row].Password;
                break;

            case "Actions":
                foreach (NSView subview in view.Subviews)
                {
                    var btn = subview as NSButton;
                    if (btn != null)
                    {
                        btn.Tag = row;
                    }
                }
                break;
            }

            return(view);
        }
コード例 #11
0
		partial void CustomImage (NSObject sender)
		{
			var alert = new NSAlert {
				MessageText = "The cat that started it all!"
			};
			
			var asm = Assembly.GetExecutingAssembly ();
			using (var stream = asm.GetManifestResourceStream ("NSAlertSample.i-can-has-cheezburger.jpg")) {
				alert.Icon = NSImage.FromStream (stream);
			}

			alert.AddButton ("No Can Has");

			Run (alert);
		}
コード例 #12
0
        void insertImage(NSObject sender)
        {
            var nodePath = EditorWindow.CurrentObject?.DocumentDirectory;

            if (nodePath == null)
            {
                return;
            }
            var nodeImageDir = Path.Combine(nodePath, "_images");

            try {
                if (!Directory.Exists(nodeImageDir))
                {
                    Directory.CreateDirectory(nodeImageDir);
                }
            } catch { }

            var dlg = NSOpenPanel.OpenPanel;

            dlg.CanChooseFiles          = true;
            dlg.CanChooseDirectories    = false;
            dlg.AllowsMultipleSelection = false;
            dlg.AllowedFileTypes        = new string[] { "png", "jpg", "gif" };

            if (dlg.RunModal() != 1)
            {
                return;
            }

            if (dlg.Urls.Length == 0)
            {
                return;
            }

            var path   = dlg.Urls.FirstOrDefault().Path;
            var target = Path.Combine(nodeImageDir, Path.GetFileName(path));



            if (File.Exists(target))
            {
                var alert = new NSAlert()
                {
                    MessageText     = "Overwrite the existing image?",
                    InformativeText = "There is already a file with the same name in the images folder, do you want to overwrite, or automatically rename the file?",
                    AlertStyle      = NSAlertStyle.Warning
                };
                alert.AddButton("Overwrite");
                alert.AddButton("Rename");
                var code = alert.RunModal();
                switch (code)
                {
                case 1000:                 // Overwrite
                    break;

                case 1001:                 // Rename
                    int i = 0;
                    do
                    {
                        target = Path.Combine(nodeImageDir, Path.GetFileNameWithoutExtension(path) + i + Path.GetExtension(path));
                        i++;
                    } while (File.Exists(target));
                    break;
                }
            }

            try {
                File.Copy(path, target);
            } catch (Exception e) {
                var a = new NSAlert()
                {
                    MessageText     = "Failure to copy the file",
                    InformativeText = e.ToString(),
                    AlertStyle      = NSAlertStyle.Critical
                };
                a.RunModal();
                return;
            }

            EditorWindow.InsertImage(target);
        }
コード例 #13
0
ファイル: MainWindow.cs プロジェクト: pbbpage/mac-samples
		void ShowAlert (NSObject sender) {
			if (ShowAlertAsSheet) {
				var input = new NSTextField (new CGRect (0, 0, 300, 20));

				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Informational,
					InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.",
					MessageText = "Alert Title",
				};
				alert.AddButton ("Ok");
				alert.AddButton ("Cancel");
				alert.AddButton ("Maybe");
				alert.ShowsSuppressionButton = true;
				alert.AccessoryView = input;
				alert.Layout ();
				alert.BeginSheetForResponse (this, (result) => {
					Console.WriteLine ("Alert Result: {0}, Suppress: {1}", result, alert.SuppressionButton.State == NSCellStateValue.On);
				});
			} else {
				var input = new NSTextField (new CGRect (0, 0, 300, 20));

				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Informational,
					InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.",
					MessageText = "Alert Title",
				};
				alert.AddButton ("Ok");
				alert.AddButton ("Cancel");
				alert.AddButton ("Maybe");
				alert.ShowsSuppressionButton = true;
				alert.AccessoryView = input;
				alert.Layout ();
				var result = alert.RunModal ();
				Console.WriteLine ("Alert Result: {0}, Suppress: {1}", result, alert.SuppressionButton.State == NSCellStateValue.On);
			}
		}
コード例 #14
0
        public bool ContinueIfChanged()
        {
            if (Window.Subtitle.Paragraphs.Count == 0 || Window.Subtitle.GetFastHashCode() == _subtitleOriginalHash)
            {
                return true;
            }

            NSAlert alert = new NSAlert();
            if (_subtitleFileName == null)
            {
                alert.MessageText = _language.SaveChangesToUntitled;
            }
            else
            {
                alert.MessageText = string.Format(_language.SaveChangesToX, _subtitleFileName);
            }
            alert.AddButton("Yes".Replace("&", string.Empty));
            alert.AddButton("No".Replace("&", string.Empty));
            alert.AddButton(_languageGeneral.Cancel.Replace("&", string.Empty));
            var result = alert.RunModal();
            if (result == (long)(NSAlertButtonReturn.First))
            {
                return SaveSubtitle();
            }
            else if (result == (long)(NSAlertButtonReturn.Second))
            {
                Window.Subtitle.Paragraphs.Clear(); 
                return true;
            }
            return false;
        }
コード例 #15
0
        private void doExtract()
        {
            string ext       = Path.GetExtension(txtFilename.StringValue).ToUpper();
            string extdir    = Path.GetDirectoryName(txtFilename.StringValue) + "/" + Path.GetFileNameWithoutExtension(txtFilename.StringValue) + "/";
            string arguments = string.Empty;
            string filename  = string.Empty;
            string pathres   = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) +
                               "/../Resources/Resources/";

            switch (ext)
            {
            case ".ZIP":
                //filename = "/usr/bin/unzip";

                var alert = new NSAlert {
                    MessageText = "Extract only this file or all the ZIP files in the directory?",
                    AlertStyle  = NSAlertStyle.Critical
                };

                alert.AddButton("This file only");
                alert.AddButton("All the files");

                string fileToExtract = "\\*.zip";
                if (alert.RunModal() == (int)NSAlertButtonReturn.First)
                {
                    fileToExtract = "\"" + txtFilename.StringValue + "\"";
                }

                filename  = pathres + "unzip";
                arguments = "-u -o " + fileToExtract + " -d \"" + extdir + "\"";
                break;

            case ".001":
            case ".RAR":
                filename  = pathres + "unrar";
                arguments = "x -y \"" + txtFilename.StringValue + "\" \"" + extdir + "\"";
                break;
            }

            string workingdir = Path.GetDirectoryName(txtFilename.StringValue);

            extractTask = new ExtractTask(filename, workingdir, arguments);

            _timerUi.Start();

            extractTask.messages.Add("-------- STARTED\n");
            extractTask.messages.Add("-------- Using: " + filename + "\n");

            var bw = new BackgroundWorker();

            bw.DoWork += (sender, args) => {
                Console.WriteLine("Worker has started");
                extractTask.Task();
            };

            bw.RunWorkerCompleted += (sender, args) => {
                Console.WriteLine("Worker has completed");
                extractTask.messages.Add("-------- DONE!\n");
                extractTask.messages.Add("-------- Extracted to: " + extdir);
                extractTask.done = true;
            };

            bw.RunWorkerAsync();
        }
コード例 #16
0
        public static void NewPassword(SqliteConnection connection, SqliteConnection _conn)
        {
            var newPasswordInput = new NSStackView(new CGRect(0, 0, 300, 50));

            var originalPassword = new NSSecureTextField(new CGRect(0, 25, 300, 20));

            originalPassword.PlaceholderAttributedString = new Foundation.NSAttributedString("Type new password...");
            var confirmedPassword = new NSSecureTextField(new CGRect(0, 0, 300, 20));

            confirmedPassword.PlaceholderAttributedString = new Foundation.NSAttributedString("Confirm password...");

            newPasswordInput.AddSubview(originalPassword);
            newPasswordInput.AddSubview(confirmedPassword);

            var newPasswordAlert = new NSAlert()
            {
                AlertStyle      = NSAlertStyle.Informational,
                InformativeText = "Enter new password to secure SittingDucks",
                MessageText     = "Adding New Password",
            };
            var enterButton = newPasswordAlert.AddButton("Enter");

            originalPassword.NextKeyView  = confirmedPassword;
            confirmedPassword.NextKeyView = enterButton;

            newPasswordAlert.AccessoryView = newPasswordInput;
            newPasswordAlert.Layout();
            var result = newPasswordAlert.RunModal();

            if (result == 1000 && originalPassword.StringValue == confirmedPassword.StringValue)
            {
                bool shouldClose;
                var  encryptedPassword = EncryptionTool.Encrypt(originalPassword.StringValue);

                (_conn, shouldClose) = SqliteManager.OpenConnection(connection);

                // Execute query
                using (var command = connection.CreateCommand())
                {
                    // Create new command
                    command.CommandText = "UPDATE [System] SET ID = @COL1, Password = @COL2, INIT = @COL3";

                    // Populate with data from the record
                    command.Parameters.AddWithValue("@COL1", new Guid());
                    command.Parameters.AddWithValue("@COL2", encryptedPassword);
                    command.Parameters.AddWithValue("@COL3", true);

                    // Write to database
                    command.ExecuteNonQuery();
                }

                _conn = SqliteManager.CloseConnection(shouldClose, connection);

                newPasswordAlert.Dispose();

                var confirmPasswordAlert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = "Remember this password, store it somewhere safe! You will not be able to recover it if lost.",
                    MessageText     = "Password sucessfully saved",
                };
                confirmPasswordAlert.AddButton("OK");
                var confirmResult = confirmPasswordAlert.RunModal();

                if (confirmResult == 1000)
                {
                    confirmPasswordAlert.Dispose();
                }
            }
            else if (result == 1000 && originalPassword.StringValue != confirmedPassword.StringValue)
            {
                newPasswordAlert.AlertStyle      = NSAlertStyle.Warning;
                newPasswordAlert.InformativeText = "Passwords do not match";
            }
        }
コード例 #17
0
        public void DeleteLines()
        {
            var selectedRows = Window.SubtitleTable.SelectedRows;
            if (selectedRows.Count == 0)
                return;

            if (Configuration.Settings.General.PromptDeleteLines)
            {
                NSAlert alert = new NSAlert();
                var count = selectedRows.Count;
                alert.MessageText = count == 1 ? _language.DeleteOneLinePrompt : string.Format(_language.DeleteXLinesPrompt, count);
                alert.AddButton(_languageGeneral.Ok.Replace("&", string.Empty));
                alert.AddButton(_languageGeneral.Cancel.Replace("&", string.Empty));
                var result = alert.RunModal();
                if (result != (long)(NSAlertButtonReturn.First))
                {
                    return;
                }
            }

            foreach (var row in selectedRows.Reverse())
            {
                Window.Subtitle.Paragraphs.RemoveAt((int)row);
            }
            Window.Subtitle.Renumber();
            Window.SubtitleTable.ReloadData();
            ShowSubtitleRow((nint)selectedRows.First());
        }
コード例 #18
0
        public override NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, nint row)
        {
            NSTableCellView view = (NSTableCellView)tableView.MakeView(tableColumn.Title, this);

            //if (view == null) //Need to recreate entire table if new books added
            if (true)
            {
                view = new NSTableCellView();

                // Configure the view
                view.Identifier = tableColumn.Title;

                // Take action based on title
                switch (tableColumn.Title)
                {
                case "Media":
                    ////view.ImageView = new NSImageView(new CGRect(0, 0, 16, 16));
                    //view.AddSubview(view.ImageView);
                    view.TextField = new NSTextField(new CGRect(20, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Title":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Creator":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Language":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Rating":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Date":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Completion":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Delete":
                    // Create new button
                    var button = new NSButton(new CGRect(0, 0, 81, 16));
                    button.SetButtonType(NSButtonType.MomentaryPushIn);
                    button.Title = "Delete";
                    button.Tag   = row;

                    // Wireup events
                    button.Activated += (sender, e) => {
                        // Get button and product
                        var btn    = sender as NSButton;
                        var record = DataSource.MediaRecords[(int)btn.Tag];

                        // Configure alert
                        var alert = new NSAlert()
                        {
                            AlertStyle      = NSAlertStyle.Informational,
                            InformativeText = $"Are you sure you want to delete the {record.Media.ToLower()} {record.Title} by {record.Creator}? This operation cannot be undone.",
                            MessageText     = $"Delete {record.Title}?",
                        };
                        alert.AddButton("Cancel");
                        alert.AddButton("Delete");
                        alert.BeginSheetForResponse(Controller.View.Window, (result) => {
                            // Should we delete the requested row?
                            if (result == 1001)
                            {
                                // Delete record from the database and remove the given row from the dataset
                                var connection = GetDatabaseConnection();
                                DataSource.MediaRecords[(int)btn.Tag].Delete(connection);
                                DataSource.MediaRecords.RemoveAt((int)btn.Tag);
                                //Controller.ReloadMediaTable();
                                Controller.SearchMedia();
                            }
                        });
                    };
                    // Add to view
                    view.AddSubview(button);
                    break;
                }
            }

            // Setup view based on the column selected
            switch (tableColumn.Title)
            {
            case "Media":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Media;
                break;

            case "Title":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Title;
                break;

            case "Creator":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Creator;
                break;

            case "Language":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Language;
                break;

            case "Rating":
                int rating = DataSource.MediaRecords[(int)row].Rating;
                if (rating == 0)
                {
                    view.TextField.StringValue = "";
                }
                else
                {
                    view.TextField.StringValue = rating.ToString();
                }
                break;

            case "Date":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Date;
                break;

            case "Completion":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Status;
                break;

            case "Delete":
                foreach (NSView subview in view.Subviews)
                {
                    var btn = subview as NSButton;
                    if (btn != null)
                    {
                        btn.Tag = row;
                    }
                }
                break;
            }

            return(view);
        }
コード例 #19
0
		partial void CustomSuppression (NSObject sender)
		{
			var alert = new NSAlert {
				MessageText = "Subscribe to CatOverflow.com",
				InformativeText = "CatOverflow.com features the best cats the Internet has to offer.\n\nUpdated regularly and curated by a professional cat analyist, CatOverflow.com cannot be missed. Make it part of your daily regimen now!\n",
				ShowsSuppressionButton = true
			};

			alert.SuppressionButton.Title = "Go away forever, meow";
			alert.SuppressionButton.Font = NSFont.ControlContentFontOfSize (NSFont.SmallSystemFontSize);
			
			alert.AddButton ("YES YES YES");
			alert.AddButton ("Remind me later");
			alert.AddButton ("I prefer DogOverflow.com");
			
			Run (alert);
		}
コード例 #20
0
		partial void DefaultSuppression (NSObject sender)
		{
			var alert = new NSAlert {
				MessageText = "Purchase More Gold!",
				InformativeText = "Would you like to purchase 30 more pounds of gold?",
				ShowsSuppressionButton = true
			};

			alert.AddButton ("Yes Please!");
			alert.AddButton ("Absolutely Not");

			Run (alert);
		}
コード例 #21
0
        private static OSMessageBoxResult PlatformShowCore(string message, string title, System.Exception exception, OSMessageBoxButton buttons, Dictionary <OSMessageBoxButton, string> customButtonLabels, OSMessageBoxIcon icon, OSMessageBoxResult defaultResult, System.Action <OSMessageBoxResult> onComplete)
        {
            var result = OSMessageBoxResult.None;

            if (onComplete == null)
            {
                INTV.Shared.Utility.OSDispatcher.Current.InvokeOnMainDispatcher(() =>
                {
                    using (var messageBox = new NSAlert())
                    {
                        messageBox.MessageText     = title;
                        messageBox.InformativeText = message;
                        messageBox.AlertStyle      = (NSAlertStyle)icon;
                        messageBox.AddButton(GetCustomTextForButton(OSMessageBoxButton.OK, customButtonLabels, buttons));
                        var defaultButton      = messageBox.Buttons[0];
                        var defaultButtonIndex = 0;
                        NSButton buttonTwo     = null;
                        NSButton buttonThree   = null;
                        switch (buttons)
                        {
                        case OSMessageBoxButton.OK:
                            break;

                        case OSMessageBoxButton.YesNo:
                            if (defaultResult == OSMessageBoxResult.No)
                            {
                                defaultButtonIndex = 1;
                            }
                            buttonTwo = messageBox.AddButton(GetCustomTextForButton(OSMessageBoxButton.YesNo, customButtonLabels, buttons));
                            break;

                        case OSMessageBoxButton.YesNoCancel:
                            if (defaultResult == OSMessageBoxResult.Cancel)
                            {
                                defaultButtonIndex = 2;
                            }
                            buttonTwo   = messageBox.AddButton(GetCustomTextForButton(OSMessageBoxButton.YesNo, customButtonLabels, buttons));
                            buttonThree = messageBox.AddButton(GetCustomTextForButton(OSMessageBoxButton.YesNoCancel, customButtonLabels, buttons));
                            break;
                        }
                        if (customButtonLabels != null)
                        {
                            var buttonText = string.Empty;
                            System.Diagnostics.Debug.WriteLineIf((defaultButton != null) && customButtonLabels.TryGetValue(OSMessageBoxButton.OK, out buttonText) && (buttonText != GetCustomTextForButton(OSMessageBoxButton.OK, customButtonLabels, buttons)), "Custom button1 text not used.");
                            System.Diagnostics.Debug.WriteLineIf((buttonTwo != null) && customButtonLabels.TryGetValue(OSMessageBoxButton.YesNo, out buttonText) && (buttonText != GetCustomTextForButton(OSMessageBoxButton.YesNo, customButtonLabels, buttons)), "Custom button2 text not used.");
                            System.Diagnostics.Debug.WriteLineIf((buttonThree != null) && customButtonLabels.TryGetValue(OSMessageBoxButton.YesNoCancel, out buttonText) && (buttonText != GetCustomTextForButton(OSMessageBoxButton.YesNoCancel, customButtonLabels, buttons)), "Custom button3 text not used.");
                        }
                        if (defaultButtonIndex != 0)
                        {
                            defaultButton.KeyEquivalent = string.Empty;
                            messageBox.Buttons[defaultButtonIndex].KeyEquivalent = "\r";
                        }
                        result = (OSMessageBoxResult)(int)messageBox.RunModal();
                    }
                });
            }
            else
            {
                INTV.Shared.Utility.SingleInstanceApplication.MainThreadDispatcher.BeginInvoke(() =>
                {
                    result = ShowCore(message, title, exception, null, buttons, customButtonLabels, icon, defaultResult, null);
                    onComplete(result);
                });
            }
            return(result);
        }
コード例 #22
0
        partial void ListSerialsClicked(NSObject sender)
        {
            try {
                var dlg = NSOpenPanel.OpenPanel;
                dlg.CanChooseFiles          = false;
                dlg.CanChooseDirectories    = true;
                dlg.AllowsMultipleSelection = false;
                dlg.CanCreateDirectories    = true;

                if (dlg.RunModal() == 1)
                {
                    string msg = "Are you sure you want to List Serials?";

                    var alert = new NSAlert()
                    {
                        AlertStyle      = NSAlertStyle.Warning,
                        InformativeText = msg,
                        MessageText     = "List CloudCoins Serials",
                    };
                    alert.AddButton("OK");
                    alert.AddButton("Cancel");

                    nint num = alert.RunModal();

                    if (num == 1000)
                    {
                        String backupDir = (dlg.Urls[0].Path);
                        //backupDir = System.Web.HttpUtility.UrlEncode("/Users/ivanolsak/Desktop/CC tests/MAC 1.0.3/CloudCoin/Export");
                        NSSavePanel panel = new NSSavePanel();
                        printLineDots();
                        updateLog("List Serials Path Selected - " + backupDir);
                        //panel.DirectoryUrl = new NSUrl(backupDir);
                        panel.DirectoryUrl = dlg.Urls[0];
                        String dirName         = new DirectoryInfo(backupDir).Name;
                        string destinationPath = "CoinList" + DateTime.Now.ToString("yyyy.MM.dd").ToLower() + "." + dirName + ".csv";

                        panel.NameFieldStringValue = destinationPath;
                        if (destinationPath.Length >= 219)
                        {
                            updateLog("The path you selected has a length more than 219 characters." +
                                      " Please move your folder to a different location or rename the folder, whichever is appropriate.");
                            return;
                        }
                        nint result = panel.RunModal();

                        if (result == 1)
                        {
                            var csv   = new StringBuilder();
                            var coins = FS.LoadFolderCoins(backupDir).OrderBy(x => x.sn);

                            var    headerLine     = string.Format("sn,denomination,nn,");
                            string headeranstring = "";
                            for (int i = 0; i < CloudCoinCore.Config.NodeCount; i++)
                            {
                                headeranstring += "an" + (i + 1) + ",";
                            }

                            // Write the Header Record
                            csv.AppendLine(headerLine + headeranstring);

                            // Write the Coin Serial Numbers
                            foreach (var coin in coins)
                            {
                                string anstring = "";
                                for (int i = 0; i < CloudCoinCore.Config.NodeCount; i++)
                                {
                                    anstring += coin.an[i] + ",";
                                }
                                var newLine = string.Format("{0},{1},{2},{3}", coin.sn, coin.denomination, coin.nn, anstring);
                                csv.AppendLine(newLine);
                            }

                            string targetPath = panel.Url.Path;
                            File.WriteAllText(targetPath, csv.ToString());
                            updateLog("CSV file " + targetPath + " saved.");
                            printLineDots();
                            NSWorkspace.SharedWorkspace.SelectFile(targetPath,
                                                                   targetPath);
                        }
                    }
                }
            }
            catch (Exception e) {
                logger.Error(e.Message);
            }
        }
コード例 #23
0
        public bool Run(AlertDialogData data)
        {
            using (var alert = new NSAlert()) {
                alert.Window.Title = data.Title ?? BrandingService.ApplicationName;
                IdeTheme.ApplyTheme(alert.Window);

                bool stockIcon;
                if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Error || data.Message.Icon == Gtk.Stock.DialogError)
                {
                    alert.AlertStyle = NSAlertStyle.Critical;
                    stockIcon        = true;
                }
                else if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Warning || data.Message.Icon == Gtk.Stock.DialogWarning)
                {
                    alert.AlertStyle = NSAlertStyle.Critical;
                    stockIcon        = true;
                }
                else
                {
                    alert.AlertStyle = NSAlertStyle.Informational;
                    stockIcon        = data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information;
                }

                if (!stockIcon && !string.IsNullOrEmpty(data.Message.Icon))
                {
                    var img = ImageService.GetIcon(data.Message.Icon, Gtk.IconSize.Dialog);
                    // HACK: The icon is not rendered in dark mode (VibrantDark or DarkAqua) correctly.
                    //       Use light variant and reder it here.
                    // TODO: Recheck rendering issues with DarkAqua on final Mojave
                    if (IdeTheme.UserInterfaceTheme == Theme.Dark)
                    {
                        alert.Icon = img.WithStyles("-dark").ToBitmap(GtkWorkarounds.GetScaleFactor()).ToNSImage();
                    }
                    else
                    {
                        alert.Icon = img.ToNSImage();
                    }
                }
                else
                {
                    //for some reason the NSAlert doesn't pick up the app icon by default
                    alert.Icon = MacPlatformService.ApplicationIcon;
                }

                alert.MessageText = data.Message.Text;

                if (!string.IsNullOrEmpty(data.Message.HelpUrl))
                {
                    alert.Delegate  = new AlertDelegate(data.Message.HelpUrl);
                    alert.ShowsHelp = true;
                }

                int accessoryViewItemsCount = data.Options.Count;

                string secondaryText = data.Message.SecondaryText ?? string.Empty;
                if (TryGetMessageView(secondaryText, out NSView messageView))
                {
                    accessoryViewItemsCount++;
                }
                else
                {
                    alert.InformativeText = secondaryText;
                }

                var accessoryViews      = accessoryViewItemsCount > 0 ? new NSView [accessoryViewItemsCount] : null;
                int accessoryViewsIndex = 0;

                if (messageView != null)
                {
                    accessoryViews [accessoryViewsIndex++] = messageView;
                }

                var buttons = data.Buttons.Reverse().ToList();

                for (int i = 0; i < buttons.Count - 1; i++)
                {
                    if (i == data.Message.DefaultButton)
                    {
                        var next = buttons[i];
                        for (int j = buttons.Count - 1; j >= i; j--)
                        {
                            var tmp = buttons[j];
                            buttons[j] = next;
                            next       = tmp;
                        }
                        break;
                    }
                }

                var wrappers = new List <AlertButtonWrapper> (buttons.Count);
                foreach (var button in buttons)
                {
                    var label = button.Label;
                    if (button.IsStockButton)
                    {
                        label = Gtk.Stock.Lookup(label).Label;
                    }
                    label = label.Replace("_", "");

                    //this message seems to be a standard Mac message since alert handles it specially
                    if (button == AlertButton.CloseWithoutSave)
                    {
                        label = GettextCatalog.GetString("Don't Save");
                    }

                    var nsbutton      = alert.AddButton(label);
                    var wrapperButton = new AlertButtonWrapper(nsbutton, data.Message, button, alert);
                    wrappers.Add(wrapperButton);
                    nsbutton.Target = wrapperButton;
                    nsbutton.Action = new ObjCRuntime.Selector("buttonActivatedAction");
                }

                NSButton [] optionButtons = null;
                if (data.Options.Count > 0)
                {
                    optionButtons = new NSButton [data.Options.Count];

                    for (int i = data.Options.Count - 1; i >= 0; i--)
                    {
                        var option = data.Options[i];
                        var button = new NSButton {
                            Title = option.Text,
                            Tag   = i,
                            State = option.Value? NSCellStateValue.On : NSCellStateValue.Off,
                        };
                        button.SetButtonType(NSButtonType.Switch);
                        button.SizeToFit();
                        optionButtons [i] = button;
                        accessoryViews [accessoryViewsIndex++] = button;
                    }
                }

                var accessoryView = ArrangeAccessoryViews(accessoryViews);
                if (accessoryView != null)
                {
                    if (accessoryViews?[0] == messageView)
                    {
                        accessoryView.SetCustomSpacing(accessoryView.Spacing * 2, messageView);
                        var size = accessoryView.Frame.Size;
                        size.Height += accessoryView.Spacing;
                        accessoryView.SetFrameSize(size);
                    }
                    alert.AccessoryView = accessoryView;
                }

                NSButton applyToAllCheck = null;
                if (data.Message.AllowApplyToAll)
                {
                    alert.ShowsSuppressionButton = true;
                    applyToAllCheck       = alert.SuppressionButton;
                    applyToAllCheck.Title = GettextCatalog.GetString("Apply to all");
                }

                // Hack up a slightly wider than normal alert dialog. I don't know how to do this in a nicer way
                // as the min size constraints are apparently ignored.
                var frame = alert.Window.Frame;
                alert.Window.SetFrame(new CGRect(frame.X, frame.Y, NMath.Max(frame.Width, 600), frame.Height), true);
                alert.Layout();

                bool completed = false;
                if (data.Message.CancellationToken.CanBeCanceled)
                {
                    data.Message.CancellationToken.Register(delegate {
                        alert.InvokeOnMainThread(() => {
                            if (!completed)
                            {
                                if (alert.Window.IsSheet && alert.Window.SheetParent != null)
                                {
                                    alert.Window.SheetParent.EndSheet(alert.Window);
                                }
                                else
                                {
                                    NSApplication.SharedApplication.AbortModal();
                                }
                            }
                        });
                    });
                }

                int response = -1000;

                var parent = data.TransientFor;
                if (parent == null && IdeApp.Workbench?.RootWindow?.Visible == true)
                {
                    parent = IdeApp.Workbench?.RootWindow;
                }
                NSWindow nativeParent;
                try {
                    nativeParent = parent;
                } catch (NotSupportedException) {
                    nativeParent = null;
                }
                if (!data.Message.CancellationToken.IsCancellationRequested)
                {
                    // sheeting is broken on High Sierra with dark NSAppearance
                    var sheet = IdeTheme.UserInterfaceTheme != Theme.Dark || MacSystemInformation.OsVersion != MacSystemInformation.HighSierra;

                    // We have an issue with accessibility when using sheets, so disable it here
                    sheet &= !IdeServices.DesktopService.AccessibilityInUse;

                    if (!sheet || nativeParent == null)
                    {
                        // Force the alert window to be focused for accessibility
                        NSApplication.SharedApplication.AccessibilityFocusedWindow = alert.Window;
                        alert.Window.AccessibilityFocused = true;

                        if (nativeParent != null)
                        {
                            nativeParent.AccessibilityFocused = false;
                        }

                        alert.Window.ReleasedWhenClosed = true;
                        response = (int)alert.RunModal();

                        // Focus the old window
                        NSApplication.SharedApplication.AccessibilityFocusedWindow = nativeParent;
                    }
                    else
                    {
                        alert.BeginSheet(nativeParent, (modalResponse) => {
                            response = (int)modalResponse;
                            NSApplication.SharedApplication.StopModal();
                        });

                        // pass parent and not alert so that the Runloop will change
                        // and processing will stop until the sheet is closed.
                        // If we pass alert, then it will run until a second alert is created
                        // which will be shown as a dialog and then the runloop changes and
                        // processing stops
                        NSApplication.SharedApplication.RunModalForWindow(parent);
                    }
                }

                var result = response - (long)(int)NSAlertButtonReturn.First;

                completed = true;

                if (result >= 0 && result < buttons.Count)
                {
                    data.ResultButton = buttons [(int)result];
                }
                else
                {
                    data.ResultButton = null;
                }

                if (data.ResultButton == null || data.Message.CancellationToken.IsCancellationRequested)
                {
                    data.SetResultToCancelled();
                }

                if (optionButtons != null)
                {
                    foreach (var button in optionButtons)
                    {
                        var option = data.Options[(int)button.Tag];
                        data.Message.SetOptionValue(option.Id, button.State != 0);
                    }
                }

                if (applyToAllCheck != null && applyToAllCheck.State != 0)
                {
                    data.ApplyToAll = true;
                }

                if (nativeParent != null)
                {
                    nativeParent.MakeKeyAndOrderFront(nativeParent);
                }
                else
                {
                    IdeServices.DesktopService.FocusWindow(parent);
                }
            }

            return(true);
        }
コード例 #24
0
        partial void BackupClicked(NSObject sender)
        {
            try{
                var bankCoins    = FS.LoadFolderCoins(FS.BankFolder);
                var frackedCoins = FS.LoadFolderCoins(FS.FrackedFolder);
                var partialCoins = FS.LoadFolderCoins(FS.PartialFolder);

                // Add them all up in a single list for backup

                bankCoins.AddRange(frackedCoins);
                bankCoins.AddRange(partialCoins);

                String[] bankFileNames = new DirectoryInfo(FS.BankFolder).
                                         GetFiles("*.stack").
                                         Select(o => o.Name).ToArray();                                                      //Get all files in suspect folder
                if (bankCoins.Count == 0)
                {
                    string msg = "No Coins found in bank for backup.";

                    var alert = new NSAlert()
                    {
                        AlertStyle      = NSAlertStyle.Warning,
                        InformativeText = msg,
                        MessageText     = "Backup",
                    };
                    alert.AddButton("OK");
                    nint num = alert.RunModal();
                    return;
                }
                Banker bank          = new Banker(FS);
                int[]  bankTotals    = bank.countCoins(FS.BankFolder);
                int[]  frackedTotals = bank.countCoins(FS.FrackedFolder);
                int[]  partialTotals = bank.countCoins(FS.PartialFolder);

                var dlg = NSOpenPanel.OpenPanel;
                dlg.CanChooseFiles          = false;
                dlg.CanChooseDirectories    = true;
                dlg.AllowsMultipleSelection = false;
                dlg.CanCreateDirectories    = true;

                //dlg.DirectoryUrl = new NSUrl(FS.RootPath,UriFormat.UriEscaped.ToString());

                var uri   = new Uri(FS.RootPath);
                var nsurl = new NSUrl(uri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.UriEscaped));
                dlg.DirectoryUrl = nsurl;

                if (dlg.RunModal() == 1)
                {
                    string msg = "Are you sure you want to backup your CloudCoin Directory?";

                    var alert = new NSAlert()
                    {
                        AlertStyle      = NSAlertStyle.Warning,
                        InformativeText = msg,
                        MessageText     = "Backup CloudCoins",
                    };
                    alert.AddButton("OK");
                    alert.AddButton("Cancel");

                    nint num = alert.RunModal();

                    if (num == 1000)
                    {
                        String backupDir = dlg.Urls[0].Path;

                        string backupFileName = "backup" + DateTime.Now.ToString("yyyyMMddHHmmss").ToLower();
                        FS.WriteCoinsToFile(bankCoins, dlg.Urls[0].Path + System.IO.Path.DirectorySeparatorChar +
                                            backupFileName);
                        printLineDots();
                        updateLog("Backup file " + backupFileName + " saved to " + backupDir + " .");
                        printLineDots();
                        //export(dlg.Urls[0].Path);
                        NSWorkspace.SharedWorkspace.SelectFile(backupDir,
                                                               backupDir);
                    }
                }
            }
            catch (Exception e) {
                logger.Error(e.Message);
            }
        }
コード例 #25
0
        public bool Run(ExceptionDialogData data)
        {
            using (var alert = new NSAlert {
                AlertStyle = NSAlertStyle.Critical
            }) {
                alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;

                alert.MessageText = data.Title ?? GettextCatalog.GetString("Error");

                if (!string.IsNullOrEmpty(data.Message))
                {
                    alert.InformativeText = data.Message;
                }

                List <AlertButton> buttons = null;
                if (data.Buttons != null && data.Buttons.Length > 0)
                {
                    buttons = data.Buttons.Reverse().ToList();
                }

                if (buttons != null)
                {
                    foreach (var button in buttons)
                    {
                        var label = button.Label;
                        if (button.IsStockButton)
                        {
                            label = Gtk.Stock.Lookup(label).Label;
                        }
                        label = label.Replace("_", "");

                        //this message seems to be a standard Mac message since alert handles it specially
                        if (button == AlertButton.CloseWithoutSave)
                        {
                            label = GettextCatalog.GetString("Don't Save");
                        }

                        alert.AddButton(label);
                    }
                }

                if (data.Exception != null)
                {
                    var   scrollSize = new SizeF(400, 130);
                    float spacing    = 4;

                    string title    = GettextCatalog.GetString("View details");
                    string altTitle = GettextCatalog.GetString("Hide details");

                    var buttonFrame = new RectangleF(0, 0, 0, 0);
                    var button      = new NSButton(buttonFrame)
                    {
                        BezelStyle     = NSBezelStyle.Disclosure,
                        Title          = "",
                        AlternateTitle = "",
                    };
                    button.SetButtonType(NSButtonType.OnOff);
                    button.SizeToFit();

                    var label = new MDClickableLabel(title)
                    {
                        Alignment = NSTextAlignment.Left,
                    };
                    label.SizeToFit();

                    button.SetFrameSize(new SizeF(button.Frame.Width, Math.Max(button.Frame.Height, label.Frame.Height)));
                    label.SetFrameOrigin(new PointF(button.Frame.Width + 5, button.Frame.Y));

                    var text = new MyTextView(new RectangleF(0, 0, float.MaxValue, float.MaxValue))
                    {
                        HorizontallyResizable = true,
                    };
                    text.TextContainer.ContainerSize       = new SizeF(float.MaxValue, float.MaxValue);
                    text.TextContainer.WidthTracksTextView = true;
                    text.InsertText(new NSString(data.Exception.ToString()));
                    text.Editable = false;

                    var scrollView = new NSScrollView(new RectangleF(PointF.Empty, SizeF.Empty))
                    {
                        HasHorizontalScroller = true,
                        HasVerticalScroller   = true,
                    };

                    var accessory = new NSView(new RectangleF(0, 0, scrollSize.Width, button.Frame.Height));
                    accessory.AddSubview(scrollView);
                    accessory.AddSubview(button);
                    accessory.AddSubview(label);

                    alert.AccessoryView = accessory;

                    button.Activated += delegate {
                        float change;
                        if (button.State == NSCellStateValue.On)
                        {
                            change                  = scrollSize.Height + spacing;
                            label.StringValue       = altTitle;
                            scrollView.Hidden       = false;
                            scrollView.Frame        = new RectangleF(PointF.Empty, scrollSize);
                            scrollView.DocumentView = text;
                        }
                        else
                        {
                            change            = -(scrollSize.Height + spacing);
                            label.StringValue = title;
                            scrollView.Hidden = true;
                            scrollView.Frame  = new RectangleF(PointF.Empty, SizeF.Empty);
                        }
                        var f = accessory.Frame;
                        f.Height       += change;
                        accessory.Frame = f;
                        var lf = label.Frame;
                        lf.Y       += change;
                        label.Frame = lf;
                        var bf = button.Frame;
                        bf.Y        += change;
                        button.Frame = bf;
                        label.SizeToFit();
                        var panel = (NSPanel)alert.Window;
                        var pf    = panel.Frame;
                        pf.Height += change;
                        pf.Y      -= change;
                        panel.SetFrame(pf, true, true);
                        //unless we assign the icon again, it starts nesting old icon into the warning icon
                        alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;
                        alert.Layout();
                    };
                    label.OnMouseUp += (sender, e) => button.PerformClick(e.Event);
                }

                int result = alert.RunModal() - (int)NSAlertButtonReturn.First;
                data.ResultButton = buttons != null ? buttons [result] : null;
                GtkQuartz.FocusWindow(data.TransientFor ?? MessageService.RootWindow);
            }

            return(true);
        }
コード例 #26
0
        public override WindowResponse Show(object parent, string message, string title, MessageWindowType type, MessageWindowButtons bType)
        {
            NSAlert al = new NSAlert();

            al.AlertStyle      = CocoaHelper.GetWinType(type);
            al.MessageText     = title;
            al.InformativeText = message;

            switch (bType)
            {
            case MessageWindowButtons.AbortRetryIgnore:
                al.AddButton(Message.GetString("Abort"));
                al.AddButton(Message.GetString("Retry"));
                al.AddButton(Message.GetString("Ignore"));
                break;

            case MessageWindowButtons.Cancel:
                al.AddButton(Message.GetString("Cancel"));
                break;

            case MessageWindowButtons.Close:
                al.AddButton(Message.GetString("Close"));
                break;

            case  MessageWindowButtons.Ok:
                al.AddButton(Message.GetString("Ok"));
                break;

            case MessageWindowButtons.OkCancel:
                al.AddButton(Message.GetString("Ok"));
                al.AddButton(Message.GetString("Cancel"));
                break;

            case MessageWindowButtons.RetryCancel:
                al.AddButton(Message.GetString("Retry"));
                al.AddButton(Message.GetString("Cancel"));
                break;

            case MessageWindowButtons.YesNo:
                al.AddButton(Message.GetString("Yes"));
                al.AddButton(Message.GetString("No"));
                break;

            case MessageWindowButtons.YesNoCancel:
                al.AddButton(Message.GetString("Yes"));
                al.AddButton(Message.GetString("No"));
                al.AddButton(Message.GetString("Cancel"));
                break;
            }

            WindowResponse resp = CocoaHelper.GetResponse(al.RunModal(), bType);

            al.Dispose();
            return(resp);
        }
コード例 #27
0
        public bool Run(AlertDialogData data)
        {
            using (var alert = new NSAlert()) {
                alert.Window.Title = data.Title ?? BrandingService.ApplicationName;

                bool stockIcon;
                if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Error || data.Message.Icon == Gtk.Stock.DialogError)
                {
                    alert.AlertStyle = NSAlertStyle.Critical;
                    stockIcon        = true;
                }
                else if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Warning || data.Message.Icon == Gtk.Stock.DialogWarning)
                {
                    alert.AlertStyle = NSAlertStyle.Critical;
                    stockIcon        = true;
                }
                else
                {
                    alert.AlertStyle = NSAlertStyle.Informational;
                    stockIcon        = data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information;
                }

                if (!stockIcon && !string.IsNullOrEmpty(data.Message.Icon))
                {
                    var img = ImageService.GetIcon(data.Message.Icon, Gtk.IconSize.Dialog);
                    alert.Icon = img.ToNSImage();
                }
                else
                {
                    //for some reason the NSAlert doesn't pick up the app icon by default
                    alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;
                }

                alert.MessageText     = data.Message.Text;
                alert.InformativeText = data.Message.SecondaryText ?? "";

                var buttons = data.Buttons.Reverse().ToList();

                for (int i = 0; i < buttons.Count - 1; i++)
                {
                    if (i == data.Message.DefaultButton)
                    {
                        var next = buttons[i];
                        for (int j = buttons.Count - 1; j >= i; j--)
                        {
                            var tmp = buttons[j];
                            buttons[j] = next;
                            next       = tmp;
                        }
                        break;
                    }
                }

                var wrappers = new List <AlertButtonWrapper> (buttons.Count);
                foreach (var button in buttons)
                {
                    var label = button.Label;
                    if (button.IsStockButton)
                    {
                        label = Gtk.Stock.Lookup(label).Label;
                    }
                    label = label.Replace("_", "");

                    //this message seems to be a standard Mac message since alert handles it specially
                    if (button == AlertButton.CloseWithoutSave)
                    {
                        label = GettextCatalog.GetString("Don't Save");
                    }

                    var nsbutton      = alert.AddButton(label);
                    var wrapperButton = new AlertButtonWrapper(nsbutton, data.Message, button, alert);
                    wrappers.Add(wrapperButton);
                    nsbutton.Target = wrapperButton;
                    nsbutton.Action = new ObjCRuntime.Selector("buttonActivatedAction");
                }


                NSButton[] optionButtons = null;
                if (data.Options.Count > 0)
                {
                    var box = new MDBox(LayoutDirection.Vertical, 2, 2);
                    optionButtons = new NSButton[data.Options.Count];

                    for (int i = data.Options.Count - 1; i >= 0; i--)
                    {
                        var option = data.Options[i];
                        var button = new NSButton {
                            Title = option.Text,
                            Tag   = i,
                            State = option.Value? NSCellStateValue.On : NSCellStateValue.Off,
                        };
                        button.SetButtonType(NSButtonType.Switch);
                        optionButtons[i] = button;
                        box.Add(new MDAlignment(button, true)
                        {
                            XAlign = LayoutAlign.Begin
                        });
                    }

                    box.Layout();
                    alert.AccessoryView = box.View;
                }

                NSButton applyToAllCheck = null;
                if (data.Message.AllowApplyToAll)
                {
                    alert.ShowsSuppressionButton = true;
                    applyToAllCheck       = alert.SuppressionButton;
                    applyToAllCheck.Title = GettextCatalog.GetString("Apply to all");
                }

                // Hack up a slightly wider than normal alert dialog. I don't know how to do this in a nicer way
                // as the min size constraints are apparently ignored.
                var frame = alert.Window.Frame;
                alert.Window.SetFrame(new CGRect(frame.X, frame.Y, NMath.Max(frame.Width, 600), frame.Height), true);
                alert.Layout();

                bool completed = false;
                if (data.Message.CancellationToken.CanBeCanceled)
                {
                    data.Message.CancellationToken.Register(delegate {
                        alert.InvokeOnMainThread(() => {
                            if (!completed)
                            {
                                NSApplication.SharedApplication.AbortModal();
                            }
                        });
                    });
                }

                if (!data.Message.CancellationToken.IsCancellationRequested)
                {
                    var result = (int)alert.RunModal() - (long)(int)NSAlertButtonReturn.First;
                    completed = true;
                    if (result >= 0 && result < buttons.Count)
                    {
                        data.ResultButton = buttons [(int)result];
                    }
                    else
                    {
                        data.ResultButton = null;
                    }
                }

                if (data.ResultButton == null || data.Message.CancellationToken.IsCancellationRequested)
                {
                    data.SetResultToCancelled();
                }

                if (optionButtons != null)
                {
                    foreach (var button in optionButtons)
                    {
                        var option = data.Options[(int)button.Tag];
                        data.Message.SetOptionValue(option.Id, button.State != 0);
                    }
                }

                if (applyToAllCheck != null && applyToAllCheck.State != 0)
                {
                    data.ApplyToAll = true;
                }

                GtkQuartz.FocusWindow(data.TransientFor ?? MessageService.RootWindow);
            }

            return(true);
        }
コード例 #28
0
        public static string ShowInputBoxEx(string title, string informativeText, string defaultValue, string placeholder = "", int width = 0, NSFormatter textFormatter = null)
        {
            NSAlert alert = new NSAlert();

            alert.AddButton("OK");
            alert.AddButton("Cancel");

            if (!string.IsNullOrEmpty(title))
            {
                alert.MessageText = title;
            }

            if (!string.IsNullOrEmpty(informativeText))
            {
                alert.InformativeText = informativeText;
            }

            CGRect textFieldRect;

            if (width <= 0)
            {
                width = 300;
            }
            textFieldRect = new CGRect(0, 0, width, 36);

            CustomTextField tf = new CustomTextField(textFieldRect);

            tf.Alignment = NSTextAlignment.Center;
            tf.Font      = NSFont.SystemFontOfSize(16);

            var dc = new NSDateComponentsFormatter();

            dc.UnitsStyle   = NSDateComponentsFormatterUnitsStyle.Full;
            dc.AllowedUnits = NSCalendarUnit.Minute;

            if (textFormatter != null)
            {
                tf.Formatter = textFormatter;
            }

            if (!string.IsNullOrEmpty(defaultValue))
            {
                tf.StringValue = defaultValue;
            }
            if (!string.IsNullOrEmpty(placeholder))
            {
                tf.PlaceholderString = placeholder;
            }

            alert.AccessoryView = tf;
            alert.Window.InitialFirstResponder = tf;


            nint result = alert.RunModal();

            if (result == (int)NSAlertButtonReturn.First)
            {
                return(tf.StringValue);
            }

            return(null);
        }
コード例 #29
0
ファイル: MessageDialog.cs プロジェクト: inthehand/Charming
        /// <summary>
        /// Begins an asynchronous operation showing a dialog.
        /// </summary>
        /// <returns>An object that represents the asynchronous operation.
        /// For more on the async pattern, see Asynchronous programming in the Windows Runtime.</returns>
        /// <remarks>In some cases, such as when the dialog is closed by the system out of your control, your result can be an empty command.
        /// Returns either the command selected which destroyed the dialog, or an empty command.
        /// For example, a dialog hosted in a charms window will return an empty command if the charms window has been dismissed.</remarks>
        public Task<IUICommand> ShowAsync()
        {
            if (Commands.Count > MaxCommands)
            {
                throw new InvalidOperationException();
            }

#if __ANDROID__
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity);
            Android.App.AlertDialog dialog = builder.Create();
            dialog.SetTitle(Title);
            dialog.SetMessage(Content);
            if (Commands.Count == 0)
            {
                dialog.SetButton(-1, Resources.System.GetString(Android.Resource.String.Cancel), new EventHandler<Android.Content.DialogClickEventArgs>(Clicked));
            }
            else
            {
                for (int i = 0; i < Commands.Count; i++)
                {
                    dialog.SetButton(-1 - i, Commands[i].Label, new EventHandler<Android.Content.DialogClickEventArgs>(Clicked));
                }
            }
            dialog.Show();

            return Task.Run<IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            });

#elif __IOS__ || __TVOS__
            uac = UIAlertController.Create(Title, Content, UIAlertControllerStyle.Alert);
            if (Commands.Count == 0)
            {
                uac.AddAction(UIAlertAction.Create("Close", UIAlertActionStyle.Cancel | UIAlertActionStyle.Default, ActionClicked));
            }
            else
            {
                for (int i = 0; i < Commands.Count; i++)
                {
                    UIAlertAction action = UIAlertAction.Create(Commands[i].Label, CancelCommandIndex == i ? UIAlertActionStyle.Cancel : UIAlertActionStyle.Default, ActionClicked);
                    uac.AddAction(action);
                }
            }
            UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (currentController.PresentedViewController != null)
                currentController = currentController.PresentedViewController;
            
            currentController.PresentViewController(uac, true, null);

            return Task.Run<IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            });

#elif __MAC__
            NSAlert alert = new NSAlert();
            alert.AlertStyle = NSAlertStyle.Informational;
            alert.InformativeText = Content;
            alert.MessageText = Title;

            foreach(IUICommand command in Commands)
            {
                var button = alert.AddButton(command.Label);
            }

            alert.BeginSheetForResponse(NSApplication.SharedApplication.MainWindow, NSAlert_onEnded);

            return Task.Run<IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            });

#elif WINDOWS_PHONE
            List<string> buttons = new List<string>();
            foreach(IUICommand uic in this.Commands)
            {
                buttons.Add(uic.Label);
            }

            if (buttons.Count == 0)
            {
                buttons.Add("Close");
            }

            MessageDialogAsyncOperation asyncOperation = new MessageDialogAsyncOperation(this);

            string contentText = Content;

            // trim message body to 255 chars
            if (contentText.Length > 255)
            {
                contentText = contentText.Substring(0, 255);
            }
            
            while(Microsoft.Xna.Framework.GamerServices.Guide.IsVisible)
            {
                Thread.Sleep(250);
            }

            Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(
                        string.IsNullOrEmpty(Title) ? " " : Title,
                        contentText,
                        buttons,
                        (int)DefaultCommandIndex, // can choose which button has the focus
                        Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None, // can play sounds
                        result =>
                        {
                            int? returned = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(result);
                            
                            // process and fire the required handler
                            if (returned.HasValue)
                            {
                                if (Commands.Count > returned.Value)
                                {
                                    IUICommand theCommand = Commands[returned.Value];
                                    asyncOperation.SetResults(theCommand);
                                    if (theCommand.Invoked != null)
                                    {
                                        theCommand.Invoked(theCommand);
                                    }
                                }
                                else
                                {
                                    asyncOperation.SetResults(null);
                                }
                            }
                            else
                            {
                                asyncOperation.SetResults(null);
                            }
                        }, null);

            return asyncOperation.AsTask<IUICommand>();
#elif WINDOWS_UWP
            if (Commands.Count < 3 && Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent("Windows.UI.ApplicationSettings.ApplicationsSettingsContract", 1))
            {
                Windows.UI.Xaml.Controls.ContentDialog cd = new Windows.UI.Xaml.Controls.ContentDialog();
                cd.Title = Title;
                cd.Content = Content;
                if(Commands.Count == 0)
                {
                    cd.PrimaryButtonText = "Close";
                }
                else
                {
                    cd.PrimaryButtonText = Commands[0].Label;
                    cd.PrimaryButtonClick += Cd_PrimaryButtonClick;
                    if(Commands.Count > 1)
                    {
                        cd.SecondaryButtonText = Commands[1].Label;
                        cd.SecondaryButtonClick += Cd_SecondaryButtonClick;
                    }
                }
                
                return Task.Run<IUICommand>(async () => 
                {
                    ManualResetEvent mre = new ManualResetEvent(false);
                    IUICommand command = null;

                    await cd.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                    {
                        ContentDialogResult dr = await cd.ShowAsync();
                        if (Commands.Count > 0)
                        {
                            switch (dr)
                            {
                                case ContentDialogResult.Primary:
                                    command = Commands[0];
                                    if(Commands[0].Invoked != null)
                                    {
                                        Commands[0].Invoked.Invoke(Commands[0]);
                                    }
                                    break;

                                case ContentDialogResult.Secondary:
                                    command = Commands[1];
                                    if (Commands[1].Invoked != null)
                                    {
                                        Commands[1].Invoked.Invoke(Commands[1]);
                                    }
                                    break;
                            }
                        }
                    });

                    mre.WaitOne();

                    return command;
                });
            }
            else
            {
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(Content, Title);
                foreach (IUICommand command in Commands)
                {
                    dialog.Commands.Add(new Windows.UI.Popups.UICommand(command.Label, (c)=> { command.Invoked(command); }, command.Id));
                }
                return Task.Run<IUICommand>(async () => {
                    Windows.UI.Popups.IUICommand command = await dialog.ShowAsync();
                    if (command != null)
                    {
                        int i = 0;
                        foreach(Windows.UI.Popups.IUICommand c in dialog.Commands)
                        {
                            if(command == c)
                            {
                                break;
                            }

                            i++;
                        }

                        return Commands[i];
                    }
                    return null;
                });
            }
#elif WIN32
            return Task.Run<IUICommand>(() =>
            {
                IUICommand cmd = ShowTaskDialog();
                if (cmd != null)
                {
                    cmd.Invoked?.Invoke(cmd);
                }

                return cmd;
            });
#else
            throw new PlatformNotSupportedException();
#endif
        }
コード例 #30
0
        private bool PickFiles()
        {
            var dlg = NSOpenPanel.OpenPanel;

            dlg.CanChooseFiles          = true;
            dlg.CanChooseDirectories    = false;
            dlg.AllowsMultipleSelection = true;

            dlg.AllowedFileTypes = new string[] { "stack", "jpg", "chest" };

            if (dlg.RunModal() == 1)
            {
                // Nab the first file
                var url = dlg.Urls[0];
                for (int i = 0; i < dlg.Urls.Length; i++)
                {
                    Console.WriteLine(dlg.Urls[i].Path);
                    updateLog("Selected " + dlg.Urls[i].Path);


                    var filename = dlg.Urls[i].Path;



                    //var filename = Path.GetFileName(path);
                    if (!File.Exists(FS.ImportFolder + Path.DirectorySeparatorChar + Path.GetFileName(filename)))
                    {
                        File.Copy(filename, FS.ImportFolder + Path.GetFileName(filename));
                    }
                    else
                    {
                        string msg = "File " + Path.GetFileName(filename) + " already exists. Do you want to overwrite it?";

                        var alert = new NSAlert()
                        {
                            AlertStyle      = NSAlertStyle.Warning,
                            InformativeText = msg,
                            MessageText     = "Import File",
                        };
                        alert.AddButton("OK");
                        alert.AddButton("Cancel");

                        nint num = alert.RunModal();

                        if (num == 1000)
                        {
                            File.Copy(filename, FS.ImportFolder + Path.GetFileName(filename), true);
                        }
                    }
                    File.Delete(filename);

                    updateLog("Copied " + filename + " to " +
                              FS.ImportFolder + Path.GetFileName(filename));
                }
            }
            else
            {
                return(false);
            }

            return(true);
        }
コード例 #31
0
        static ICredentials GetCredentialsFromUser(Uri uri, IWebProxy proxy, CredentialType credentialType)
        {
            NetworkCredential result = null;

            Runtime.RunInMainThread(() => {
                using (var ns = new NSAutoreleasePool()) {
                    var message = credentialType == CredentialType.ProxyCredentials
                                                ? GettextCatalog.GetString(
                        "{0} needs credentials to access the proxy server {1}.",
                        BrandingService.ApplicationName,
                        uri.Host
                        )
                                                : GettextCatalog.GetString(
                        "{0} needs credentials to access {1}.",
                        BrandingService.ApplicationName,
                        uri.Host
                        );

                    var alert = new NSAlert {
                        MessageText     = GettextCatalog.GetString("Credentials Required"),
                        InformativeText = message
                    };

                    var okButton     = alert.AddButton(GettextCatalog.GetString("OK"));
                    var cancelButton = alert.AddButton(GettextCatalog.GetString("Cancel"));

                    alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;

                    var view = new NSView(new CGRect(0, 0, 313, 91));

                    var usernameLabel = new NSTextField(new CGRect(17, 55, 71, 17))
                    {
                        Identifier      = "usernameLabel",
                        StringValue     = "Username:"******"Password:",
                        Alignment       = NSTextAlignment.Right,
                        Editable        = false,
                        Bordered        = false,
                        DrawsBackground = false,
                        Bezeled         = false,
                        Selectable      = false,
                    };
                    view.AddSubview(passwordLabel);

                    var passwordInput = new NSSecureTextField(new CGRect(93, 20, 200, 22));
                    view.AddSubview(passwordInput);

                    alert.AccessoryView                = view;
                    alert.Window.WeakDelegate          = new PasswordAlertWindowDelegate(usernameInput, passwordInput, cancelButton, okButton);
                    alert.Window.InitialFirstResponder = usernameInput;
                    if (alert.RunModal() != NSAlertFirstButtonReturn)
                    {
                        return;
                    }

                    var username = usernameInput.StringValue;
                    var password = passwordInput.StringValue;
                    result       = new NetworkCredential(username, password);
                }
            }).Wait();

            // store the obtained credentials in the keychain
            // but don't store for the root url since it may have other credentials
            if (result != null)
            {
                Keychain.AddInternetPassword(uri, result.UserName, result.Password);
            }

            return(result);
        }
コード例 #32
0
		partial void CustomButtons (NSObject sender)
		{
			var alert = new NSAlert {
				MessageText = "Pick a Number!",
				InformativeText = "Long description about why picking a number is important."
			};
			
			alert.AddButton ("One");
			alert.AddButton ("Two");
			alert.AddButton ("Three");
			alert.AddButton ("Four");
			alert.AddButton ("Five");
			alert.AddButton ("Six");

			Run (alert);
		}
コード例 #33
0
        public bool Run(AlertDialogData data)
        {
            using (var alert = new NSAlert()) {
                alert.Window.Title = data.Title ?? BrandingService.ApplicationName;

                if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information)
                {
                    alert.AlertStyle = NSAlertStyle.Critical;
                }
                else if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Warning)
                {
                    alert.AlertStyle = NSAlertStyle.Warning;
                }
                else                     //if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information) {
                {
                    alert.AlertStyle = NSAlertStyle.Informational;
                }

                //FIXME: use correct size so we don't get horrible scaling?
                if (!string.IsNullOrEmpty(data.Message.Icon))
                {
                    var    pix = ImageService.GetPixbuf(data.Message.Icon, Gtk.IconSize.Dialog);
                    byte[] buf = pix.SaveToBuffer("tiff");
                    unsafe
                    {
                        fixed(byte *b = buf)
                        {
                            alert.Icon = new NSImage(NSData.FromBytes((IntPtr)b, (uint)buf.Length));
                        }
                    }
                }
                else
                {
                    //for some reason the NSAlert doesn't pick up the app icon by default
                    alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;
                }

                alert.MessageText     = data.Message.Text;
                alert.InformativeText = data.Message.SecondaryText ?? "";

                var buttons = data.Buttons.Reverse().ToList();

                for (int i = 0; i < buttons.Count - 1; i++)
                {
                    if (i == data.Message.DefaultButton)
                    {
                        var next = buttons[i];
                        for (int j = buttons.Count - 1; j >= i; j--)
                        {
                            var tmp = buttons[j];
                            buttons[j] = next;
                            next       = tmp;
                        }
                        break;
                    }
                }

                foreach (var button in buttons)
                {
                    var label = button.Label;
                    if (button.IsStockButton)
                    {
                        label = Gtk.Stock.Lookup(label).Label;
                    }
                    label = label.Replace("_", "");

                    //this message seems to be a standard Mac message since alert handles it specially
                    if (button == AlertButton.CloseWithoutSave)
                    {
                        label = GettextCatalog.GetString("Don't Save");
                    }

                    alert.AddButton(label);
                }


                NSButton[] optionButtons = null;
                if (data.Options.Count > 0)
                {
                    var box = new MDBox(LayoutDirection.Vertical, 2, 2);
                    optionButtons = new NSButton[data.Options.Count];

                    for (int i = data.Options.Count - 1; i >= 0; i--)
                    {
                        var option = data.Options[i];
                        var button = new NSButton()
                        {
                            Title = option.Text,
                            Tag   = i,
                            State = option.Value? NSCellStateValue.On : NSCellStateValue.Off,
                        };
                        button.SetButtonType(NSButtonType.Switch);
                        optionButtons[i] = button;
                        box.Add(new MDAlignment(button, true)
                        {
                            XAlign = LayoutAlign.Begin
                        });
                    }

                    box.Layout();
                    alert.AccessoryView = box.View;
                }

                NSButton applyToAllCheck = null;
                if (data.Message.AllowApplyToAll)
                {
                    alert.ShowsSuppressionButton = true;
                    applyToAllCheck       = alert.SuppressionButton;
                    applyToAllCheck.Title = GettextCatalog.GetString("Apply to all");
                }

                // Hack up a slightly wider than normal alert dialog. I don't know how to do this in a nicer way
                // as the min size constraints are apparently ignored.
                var frame = ((NSPanel)alert.Window).Frame;
                ((NSPanel)alert.Window).SetFrame(new RectangleF(frame.X, frame.Y, Math.Max(frame.Width, 600), frame.Height), true);
                alert.Layout();

                bool completed = false;
                if (data.Message.CancellationToken.CanBeCanceled)
                {
                    data.Message.CancellationToken.Register(delegate {
                        alert.InvokeOnMainThread(() => {
                            if (!completed)
                            {
                                NSApplication.SharedApplication.AbortModal();
                            }
                        });
                    });
                }

                if (!data.Message.CancellationToken.IsCancellationRequested)
                {
                    int result = alert.RunModal() - (int)NSAlertButtonReturn.First;
                    completed = true;
                    if (result >= 0 && result < buttons.Count)
                    {
                        data.ResultButton = buttons [result];
                    }
                    else
                    {
                        data.ResultButton = null;
                    }
                }

                if (data.ResultButton == null || data.Message.CancellationToken.IsCancellationRequested)
                {
                    data.SetResultToCancelled();
                }

                if (optionButtons != null)
                {
                    foreach (var button in optionButtons)
                    {
                        var option = data.Options[button.Tag];
                        data.Message.SetOptionValue(option.Id, button.State != 0);
                    }
                }

                if (applyToAllCheck != null && applyToAllCheck.State != 0)
                {
                    data.ApplyToAll = true;
                }

                GtkQuartz.FocusWindow(data.TransientFor ?? MessageService.RootWindow);
            }

            return(true);
        }
コード例 #34
0
        /// <summary>
        /// Begins an asynchronous operation showing a dialog.
        /// </summary>
        /// <returns>An object that represents the asynchronous operation.
        /// For more on the async pattern, see Asynchronous programming in the Windows Runtime.</returns>
        /// <remarks>In some cases, such as when the dialog is closed by the system out of your control, your result can be an empty command.
        /// Returns either the command selected which destroyed the dialog, or an empty command.
        /// For example, a dialog hosted in a charms window will return an empty command if the charms window has been dismissed.</remarks>
        public Task <IUICommand> ShowAsync()
        {
            if (Commands.Count > MaxCommands)
            {
                throw new InvalidOperationException();
            }

#if __ANDROID__
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity);
            Android.App.AlertDialog         dialog  = builder.Create();
            dialog.SetTitle(Title);
            dialog.SetMessage(Content);
            if (Commands.Count == 0)
            {
                dialog.SetButton(-1, Resources.System.GetString(Android.Resource.String.Cancel), new EventHandler <Android.Content.DialogClickEventArgs>(Clicked));
            }
            else
            {
                for (int i = 0; i < Commands.Count; i++)
                {
                    dialog.SetButton(-1 - i, Commands[i].Label, new EventHandler <Android.Content.DialogClickEventArgs>(Clicked));
                }
            }
            dialog.Show();

            return(Task.Run <IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            }));
#elif __IOS__ || __TVOS__
            uac = UIAlertController.Create(Title, Content, UIAlertControllerStyle.Alert);
            if (Commands.Count == 0)
            {
                uac.AddAction(UIAlertAction.Create("Close", UIAlertActionStyle.Cancel | UIAlertActionStyle.Default, ActionClicked));
            }
            else
            {
                for (int i = 0; i < Commands.Count; i++)
                {
                    UIAlertAction action = UIAlertAction.Create(Commands[i].Label, CancelCommandIndex == i ? UIAlertActionStyle.Cancel : UIAlertActionStyle.Default, ActionClicked);
                    uac.AddAction(action);
                }
            }
            UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (currentController.PresentedViewController != null)
            {
                currentController = currentController.PresentedViewController;
            }

            currentController.PresentViewController(uac, true, null);

            return(Task.Run <IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            }));
#elif __MAC__
            NSAlert alert = new NSAlert();
            alert.AlertStyle      = NSAlertStyle.Informational;
            alert.InformativeText = Content;
            alert.MessageText     = Title;

            foreach (IUICommand command in Commands)
            {
                var button = alert.AddButton(command.Label);
            }

            alert.BeginSheetForResponse(NSApplication.SharedApplication.MainWindow, NSAlert_onEnded);

            return(Task.Run <IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            }));
#elif WINDOWS_PHONE
            List <string> buttons = new List <string>();
            foreach (IUICommand uic in Commands)
            {
                buttons.Add(uic.Label);
            }

            if (buttons.Count == 0)
            {
                buttons.Add("Close");
            }

            MessageDialogAsyncOperation asyncOperation = new MessageDialogAsyncOperation(this);

            string contentText = Content;

            // trim message body to 255 chars
            if (contentText.Length > 255)
            {
                contentText = contentText.Substring(0, 255);
            }

            while (Microsoft.Xna.Framework.GamerServices.Guide.IsVisible)
            {
                Thread.Sleep(100);
            }

            Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(
                string.IsNullOrEmpty(Title) ? " " : Title,
                contentText,
                buttons,
                DefaultCommandIndex == uint.MaxValue ? 0 : (int)DefaultCommandIndex, // can choose which button has the focus
                Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None,           // can play sounds
                result =>
            {
                int?returned = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(result);

                // process and fire the required handler
                if (returned.HasValue)
                {
                    if (Commands.Count > returned.Value)
                    {
                        IUICommand theCommand = Commands[returned.Value];
                        asyncOperation.SetResults(theCommand);
                        if (theCommand.Invoked != null)
                        {
                            theCommand.Invoked(theCommand);
                        }
                    }
                    else
                    {
                        asyncOperation.SetResults(null);
                    }
                }
                else
                {
                    asyncOperation.SetResults(null);
                }
            }, null);

            return(asyncOperation.AsTask <IUICommand>());
#elif WINDOWS_UWP
            if (Commands.Count < 3 && Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent("Windows.UI.ApplicationSettings.ApplicationsSettingsContract", 1))
            {
                Windows.UI.Xaml.Controls.ContentDialog cd = new Windows.UI.Xaml.Controls.ContentDialog();
                cd.Title   = Title;
                cd.Content = Content;
                if (Commands.Count == 0)
                {
                    cd.PrimaryButtonText = "Close";
                }
                else
                {
                    cd.PrimaryButtonText   = Commands[0].Label;
                    cd.PrimaryButtonClick += Cd_PrimaryButtonClick;
                    if (Commands.Count > 1)
                    {
                        cd.SecondaryButtonText   = Commands[1].Label;
                        cd.SecondaryButtonClick += Cd_SecondaryButtonClick;
                    }
                }

                return(Task.Run <IUICommand>(async() =>
                {
                    ManualResetEvent mre = new ManualResetEvent(false);
                    IUICommand command = null;

                    await cd.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        ContentDialogResult dr = await cd.ShowAsync();
                        if (Commands.Count > 0)
                        {
                            switch (dr)
                            {
                            case ContentDialogResult.Primary:
                                command = Commands[0];
                                if (Commands[0].Invoked != null)
                                {
                                    Commands[0].Invoked.Invoke(Commands[0]);
                                }
                                break;

                            case ContentDialogResult.Secondary:
                                command = Commands[1];
                                if (Commands[1].Invoked != null)
                                {
                                    Commands[1].Invoked.Invoke(Commands[1]);
                                }
                                break;
                            }
                        }
                    });

                    mre.WaitOne();

                    return command;
                }));
            }
            else
            {
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(Content, Title);
                foreach (IUICommand command in Commands)
                {
                    dialog.Commands.Add(new Windows.UI.Popups.UICommand(command.Label, (c) => { command.Invoked(command); }, command.Id));
                }
                return(Task.Run <IUICommand>(async() => {
                    Windows.UI.Popups.IUICommand command = await dialog.ShowAsync();
                    if (command != null)
                    {
                        int i = 0;
                        foreach (Windows.UI.Popups.IUICommand c in dialog.Commands)
                        {
                            if (command == c)
                            {
                                break;
                            }

                            i++;
                        }

                        return Commands[i];
                    }
                    return null;
                }));
            }
#elif WIN32
            return(Task.Run <IUICommand>(() =>
            {
                IUICommand cmd = ShowTaskDialog();
                if (cmd != null)
                {
                    cmd.Invoked?.Invoke(cmd);
                }

                return cmd;
            }));
#else
            throw new PlatformNotSupportedException();
#endif
        }
コード例 #35
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Do any additional setup after loading the view.
            GPUScrollView.DocumentView = GPUStackView;
            LoadStatList();
            InitDataInterView();
            InitInterTree();
            InterTreeSplitView.SetPositionOfDivider(0, 0);
            InterTreeSegmentController.SetSelected(false, 0);

            //---  Init alerts  ---//
            Alert = new NSAlert();

            RemoveAlert             = new NSAlert();
            NoButtonTag             = RemoveAlert.AddButton("Нет").Tag;
            YesButtonTag            = RemoveAlert.AddButton("Да").Tag;
            RemoveAlert.MessageText = "Вы уверены, что хотите " +
                                      "удалить выбранные статистики выполнения?";

            CompareList    = new StatCompareList();
            plotView.Model = new OxyPlot.PlotModel();

            //---  Init help button  ---//
            NSButton helpIntervalCompare = new NSButton
            {
                BezelStyle = NSBezelStyle.HelpButton,
                Title      = "",
                BezelColor = NSColor.White
            };

            helpIntervalCompare.SetButtonType(NSButtonType.MomentaryPushIn);
            helpIntervalCompare.SetFrameSize(helpIntervalCompare.FittingSize);
            helpIntervalCompare.SetFrameOrigin(new CGPoint(TableHeader.Frame.Width
                                                           - helpIntervalCompare.FittingSize.Width, 2));
            helpIntervalCompare.AutoresizingMask = NSViewResizingMask.MinXMargin;

            //---  Init help popover  ---//
            var helpWindowController = storyboard
                                       .InstantiateControllerWithIdentifier("Popover") as NSWindowController;
            var helpViewController = helpWindowController
                                     .ContentViewController as PopoverController;

            helpPopover = new NSPopover
            {
                ContentSize           = new CGSize(200, 180),
                Behavior              = NSPopoverBehavior.Transient,
                Animates              = true,
                ContentViewController = helpViewController
            };
            helpIntervalCompare.Activated += (object sender, EventArgs e)
                                             => helpPopover.Show(new CGRect(helpIntervalCompare.Frame.Location, new CGSize(200, 180)),
                                                                 TableHeader, NSRectEdge.MaxYEdge);

            TableHeader.AddSubview(helpIntervalCompare);

            //---  Init Compare Controls  ---//
            CompareSort.Enabled           = false;
            IntervalCompareButton.Enabled = false;
            CompareDiagramSelect.Enabled  = false;
            CompareSort.RemoveAllItems();
            string[] CompareItems = { "Кол-во процессоров", "Потерянное время",
                                      "Время выполнения",   "Коэф. эффективности" };
            CompareSort.AddItems(CompareItems);

            CompareSort.Activated += (object sender, EventArgs e)
                                     =>
            {
                // TODO: Мб, для этого есть нормальное решение?
                var selectedRow = (int)CompareIntervalTree.SelectedRow;
                CompareList.Sort(CompareSort.TitleOfSelectedItem, selectedRow);
                switch (plotView.Model.Title)
                {
                case "Потерянное время":
                    plotView.Model = PlotMaker.LostTimeComparePlot(selectedRow,
                                                                   plotView.Model.GetAxis("Time").ActualMaximum);
                    break;

                case "ГПУ":
                    plotView.Model = PlotMaker.GPUComparePlot(selectedRow,
                                                              plotView.Model.GetAxis("Time").ActualMaximum);
                    break;
                }
                CompareIntervalTree.ReloadData();
                CompareIntervalTree.SelectRow(selectedRow, false);
            };

            CompareIntervalTree.IntercellSpacing = new CGSize(10, 0);
            var dataSource = new IntervalOutlineDataSource();

            CompareIntervalTree.DataSource = dataSource;
            CompareIntervalTree.Delegate   = new IntervalCompareOutlineDelegate(CompareIntervalTree, plotView);

            IntervalCompareButton.Activated += IntervalCompareButton_Activated;
        }
コード例 #36
0
        void AddButtons(NSAlert alert)
        {
            switch (Buttons)
            {
            case MessageBoxButtons.OK:
                alert.AddButton(OkButton);
                break;

            case MessageBoxButtons.OKCancel:
            {
                var ok     = alert.AddButton(OkButton);
                var cancel = alert.AddButton(CancelButton);
                switch (DefaultButton)
                {
                case MessageBoxDefaultButton.Cancel:
                case MessageBoxDefaultButton.Default:
                    ok.KeyEquivalent     = string.Empty;
                    cancel.KeyEquivalent = "\r";
                    SetResponder(alert, ok);
                    SetCancelCode(alert, 1001);
                    break;
                }
            }
            break;

            case MessageBoxButtons.YesNo:
            {
                var yes = alert.AddButton(YesButton);
                var no  = alert.AddButton(NoButton);
                switch (DefaultButton)
                {
                case MessageBoxDefaultButton.No:
                case MessageBoxDefaultButton.Default:
                    yes.KeyEquivalent = string.Empty;
                    no.KeyEquivalent  = "\r";
                    SetResponder(alert, yes);
                    SetCancelCode(alert, 1001);
                    break;
                }
            }
            break;

            case MessageBoxButtons.YesNoCancel:
            {
                var yes    = alert.AddButton(YesButton);
                var cancel = alert.AddButton(CancelButton);
                var no     = alert.AddButton(NoButton);
                switch (DefaultButton)
                {
                case MessageBoxDefaultButton.Yes:
                    break;

                case MessageBoxDefaultButton.No:
                    yes.KeyEquivalent = string.Empty;
                    no.KeyEquivalent  = "\r";
                    SetResponder(alert, yes);
                    break;

                case MessageBoxDefaultButton.Cancel:
                case MessageBoxDefaultButton.Default:
                    yes.KeyEquivalent    = string.Empty;
                    cancel.KeyEquivalent = "\r";
                    SetResponder(alert, yes);
                    SetCancelCode(alert, 1001);
                    break;
                }
            }
            break;
            }
        }
コード例 #37
0
        void LaunchDocumentationUpdate(Dictionary <Product, Tuple <bool, bool> > toUpdate)
        {
            var outdatedProducts = string.Join(" and ", toUpdate.Where(kvp => kvp.Value.Item1 || kvp.Value.Item2).Select(kvp => ProductUtils.GetFriendlyName(kvp.Key)));
            var informative      = "We have detected your " + outdatedProducts + " documentation can be upgraded with Apple documentation.";

            // Check if we are going to be downloading stuff
            if (toUpdate.Any(kvp => kvp.Value.Item1))
            {
                informative += Environment.NewLine + Environment.NewLine + "Warning: we are going to download documentation from Apple servers which can take a long time depending on your Internet connection.";
            }
            informative += Environment.NewLine + Environment.NewLine + "Would you like to update the documentation now?";

            var infoDialog = new NSAlert {
                AlertStyle      = NSAlertStyle.Informational,
                MessageText     = "Documentation update available",
                InformativeText = informative
            };

            infoDialog.AddButton("Update now");
            infoDialog.AddButton("Remind me later");
            var dialogResult = infoDialog.RunModal();

            // If Cancel was clicked, just return
            if (dialogResult == (int)NSAlertButtonReturn.Second)
            {
                return;
            }

            // Launching AppleDocWizard as root
            var mergerTasks = toUpdate
                              .Where(kvp => kvp.Value.Item1 || kvp.Value.Item2)
                              .Select(kvp => Task.Factory.StartNew(() => {
                var mergeToolPath = ProductUtils.GetMergeToolForProduct(kvp.Key);
                var docOutdated   = kvp.Value.Item1;

                // If the script has its setuid bit on and user as root, then we launch it directly otherwise we first restore it
                if (!RootLauncher.IsRootEnabled(mergeToolPath))
                {
                    RootLauncher.LaunchExternalTool(mergeToolPath, new string[] { "--self-repair" });
                    // No good way to know when the process will finish, so wait a bit. Not ideal but since this is an unlikely codepath, shouldn't matter.
                    System.Threading.Thread.Sleep(1000);
                }
                var psi = new System.Diagnostics.ProcessStartInfo(mergeToolPath, docOutdated ? "--force-download" : null);
                return(ProcessUtils.StartProcess(psi, null, null, CancellationToken.None));
            }).Unwrap());
            // No Task.WhenAll yet
            var tcs = new TaskCompletionSource <int> ();

            Task.Factory.ContinueWhenAll(mergerTasks.ToArray(), ts => {
                var faulteds = ts.Where(t => t.IsFaulted);
                if (faulteds.Any())
                {
                    tcs.SetException(faulteds.Select(t => t.Exception));
                }
                else
                {
                    tcs.SetResult(ts.Select(t => t.Result).FirstOrDefault(r => r != 0));
                }
            });

            var mergeController = new AppleDocMergeWindowController();

            mergeController.TrackProcessTask(tcs.Task);
            mergeController.ShowWindow(this);
            mergeController.Window.Center();
        }
コード例 #38
0
ファイル: MainWindow.cs プロジェクト: chamons/mac-samples-1
        public MainWindow(CGRect contentRect, NSWindowStyle aStyle, NSBackingStore bufferingType, bool deferCreation) : base(contentRect, aStyle, bufferingType, deferCreation)
        {
            var windowSize     = new CGSize(640, 480);
            var windowLocation = new CGPoint(NSScreen.MainScreen.Frame.Width / 2 - windowSize.Width / 2, NSScreen.MainScreen.Frame.Height / 2 - windowSize.Height / 2);

            var centerRect = new CGRect(windowLocation, windowSize);

            Title = "Programmatic window";

            ContentView = new NSView(centerRect);

            var title = new NSTextField {
                StringValue        = "Title your problem",
                Editable           = true,
                UsesSingleLineMode = true,
                PlaceholderString  = "Title your problem"
            };

            title.AccessibilityLabel = title.PlaceholderString;

            title.TranslatesAutoresizingMaskIntoConstraints = false;
            ContentView.AddSubview(title);

            // There are three ways to set auto layout constraints programmatically.  The first is by setting layout anchors
            // https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html#//apple_ref/doc/uid/TP40010853-CH16-SW5
            // Don't forget to set .Active = true on the constraint or it won't show up
            title.LeadingAnchor.ConstraintEqualToAnchor(ContentView.LeadingAnchor, PADDING).Active    = true;
            title.TrailingAnchor.ConstraintEqualToAnchor(ContentView.TrailingAnchor, -PADDING).Active = true;
            title.TopAnchor.ConstraintEqualToAnchor(ContentView.TopAnchor, PADDING).Active            = true;

            var scroll = new NSScrollView(new CGRect(0, 0, ContentView.Frame.Width - PADDING - PADDING, 100));

            scroll.BorderType            = NSBorderType.BezelBorder;
            scroll.HasHorizontalScroller = false;
            scroll.HasVerticalScroller   = true;
            var scrollSize = scroll.ContentSize;

            var description = new NSTextView(new CGRect(0, 0, scrollSize.Width, scrollSize.Height));

            description.MinSize               = new CGSize(0, scrollSize.Height);
            description.MaxSize               = new CGSize(float.MaxValue, float.MaxValue);
            description.Editable              = true;
            description.Font                  = title.Font;
            description.VerticallyResizable   = true;
            description.HorizontallyResizable = false;
            description.AutoresizingMask      = NSViewResizingMask.WidthSizable;

            description.TextContainer.Size = new CGSize(scrollSize.Width, float.MaxValue);
            description.TextContainer.WidthTracksTextView = true;

            scroll.DocumentView = description;

            scroll.TranslatesAutoresizingMaskIntoConstraints = false;
            ContentView.AddSubview(scroll);

            // The second option is to create NSLayoutConstraints
            // https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html#//apple_ref/doc/uid/TP40010853-CH16-SW8
            ContentView.AddConstraints(new [] {
                NSLayoutConstraint.Create(scroll, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, ContentView, NSLayoutAttribute.Leading, 1, PADDING),
                NSLayoutConstraint.Create(scroll, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, ContentView, NSLayoutAttribute.Trailing, 1, -PADDING)
            });

            // Alternatively, you can create the constraints as shown here and set .Active = true, same as with the anchor method above
            NSLayoutConstraint.Create(scroll, NSLayoutAttribute.Top, NSLayoutRelation.Equal, title, NSLayoutAttribute.Bottom, 1, PADDING).Active = true;

            title.Activated += (sender, e) => MakeFirstResponder(description);

            var labelFont = NSFont.LabelFontOfSize(10);

            var publicLabel = new NSTextField {
                StringValue     = "Your title and description will be public",
                Editable        = false,
                Bezeled         = false,
                DrawsBackground = false,
                Selectable      = false,
                Font            = labelFont,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            ContentView.AddSubview(publicLabel);

            // You can also use different types of constraints for the same view
            ContentView.AddConstraints(new [] {
                NSLayoutConstraint.Create(publicLabel, NSLayoutAttribute.Leading, NSLayoutRelation.GreaterThanOrEqual, ContentView, NSLayoutAttribute.Leading, 1, 40),
                NSLayoutConstraint.Create(publicLabel, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, ContentView, NSLayoutAttribute.Trailing, 1, -PADDING)
            });
            publicLabel.TopAnchor.ConstraintEqualToAnchor(scroll.BottomAnchor, 5).Active = true;

            var email = new NSTextField {
                Editable          = true,
                PlaceholderString = "Optional email address"
            };

            email.AccessibilityLabel = email.PlaceholderString;

            email.TranslatesAutoresizingMaskIntoConstraints = false;
            ContentView.AddSubview(email);
            ContentView.AddConstraints(new [] {
                NSLayoutConstraint.Create(email, NSLayoutAttribute.Top, NSLayoutRelation.Equal, publicLabel, NSLayoutAttribute.Bottom, 1, PADDING)
            });

            // The third option for setting layout constraints is to use Visual Format Language
            // https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html#//apple_ref/doc/uid/TP40010853-CH16-SW9
            string emailFormat      = "|-10-[email]-10-|";
            var    emailViews       = NSDictionary.FromObjectAndKey(email, (NSString)"email");
            var    emailConstraints = NSLayoutConstraint.FromVisualFormat(emailFormat, NSLayoutFormatOptions.None, null, emailViews);

            NSLayoutConstraint.ActivateConstraints(emailConstraints);

            var sendButton = new NSButton {
                Title = "OK"
            };

            sendButton.Activated += (sender, e) => {
                var alert = new NSAlert {
                    MessageText = "Button pressed"
                };
                alert.AddButton("Okay");
                alert.RunModal();
                Dispose();
            };

            sendButton.TranslatesAutoresizingMaskIntoConstraints = false;
            ContentView.AddSubview(sendButton);
            ContentView.AddConstraints(new [] {
                NSLayoutConstraint.Create(sendButton, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, ContentView, NSLayoutAttribute.Trailing, 1, -PADDING),
                NSLayoutConstraint.Create(sendButton, NSLayoutAttribute.Leading, NSLayoutRelation.GreaterThanOrEqual, ContentView, NSLayoutAttribute.Leading, 1, 40)
            });

            //To do vertical constraints with visual format language, start the format string with V:"
            string sendButtonFormat      = "V:[email]-10-[sendButton]-10-|";
            var    sendButtonViews       = NSDictionary.FromObjectsAndKeys(new NSObject [] { email, sendButton }, new NSObject [] { (NSString)"email", (NSString)"sendButton" });
            var    sendButtonConstraints = NSLayoutConstraint.FromVisualFormat(sendButtonFormat, NSLayoutFormatOptions.None, null, sendButtonViews);

            NSLayoutConstraint.ActivateConstraints(sendButtonConstraints);

            email.Activated += (sender, e) => {
                if (sendButton.Enabled)
                {
                    MakeFirstResponder(sendButton);
                }
            };

            bool hasTitle       = false;
            bool hasDescription = false;

            title.Changed += (sender, e) => {
                var titleStr = title.StringValue;
                hasTitle           = !string.IsNullOrWhiteSpace(titleStr) && titleStr.Length > 5;
                sendButton.Enabled = hasTitle && hasDescription;
            };

            description.TextStorage.DidProcessEditing += (sender, e) => {
                hasDescription     = description.TextStorage.Length > 10;
                sendButton.Enabled = hasTitle && hasDescription;
            };
        }
コード例 #39
0
 bool AskYesNo(string message, string title)
 {
     var alert = new NSAlert {
         MessageText = title, InformativeText = message
     }; alert.AddButton("No"); alert.AddButton("Yes"); return(alert.RunModal() == (int)NSAlertButtonReturn.Second);
 }
コード例 #40
0
        void AddButtons(NSAlert alert)
        {
            var OkButton     = "OK";
            var CancelButton = "Cancel";
            var YesButton    = "Yes";
            var NoButton     = "No";

            switch (Buttons)
            {
            case MessageBoxButtons.OK:
                alert.AddButton(OkButton);
                break;

            case MessageBoxButtons.OKCancel:
            {
                var ok     = alert.AddButton(OkButton);
                var cancel = alert.AddButton(CancelButton);
                switch (DefaultButton)
                {
                case MessageBoxDefaultButton.OK:
                    ok.BecomeFirstResponder();
                    break;

                case MessageBoxDefaultButton.Cancel:
                case MessageBoxDefaultButton.Default:
                    cancel.BecomeFirstResponder();
                    break;
                }
            }
            break;

            case MessageBoxButtons.YesNo:
            {
                var yes = alert.AddButton(YesButton);
                var no  = alert.AddButton(NoButton);
                switch (DefaultButton)
                {
                case MessageBoxDefaultButton.Yes:
                    yes.BecomeFirstResponder();
                    break;

                case MessageBoxDefaultButton.No:
                case MessageBoxDefaultButton.Default:
                    no.BecomeFirstResponder();
                    break;
                }
            }
            break;

            case MessageBoxButtons.YesNoCancel:
            {
                var yes    = alert.AddButton(YesButton);
                var cancel = alert.AddButton(CancelButton);
                var no     = alert.AddButton(NoButton);
                switch (DefaultButton)
                {
                case MessageBoxDefaultButton.Yes:
                    yes.BecomeFirstResponder();
                    break;

                case MessageBoxDefaultButton.No:
                    no.BecomeFirstResponder();
                    break;

                case MessageBoxDefaultButton.Cancel:
                case MessageBoxDefaultButton.Default:
                    cancel.BecomeFirstResponder();
                    break;
                }
            }
            break;
            }
        }
コード例 #41
0
ファイル: Controller.cs プロジェクト: MoritakaSoma/CmisSync
        public Controller() : base()
        {
            using (var a = new NSAutoreleasePool())
            {
                NSApplication.Init();
            }

            // We get the Default notification Center
            notificationCenter = NSUserNotificationCenter.DefaultUserNotificationCenter;

            // Clear old notifications
            foreach (var n in notificationCenter.DeliveredNotifications)
            {
                notificationCenter.RemoveDeliveredNotification(n);
            }

            notificationCenter.DidDeliverNotification += (s, e) =>
            {
                Console.WriteLine("Notification Delivered");
            };

            // If the notification is clicked, displays the entire message.
            notificationCenter.DidActivateNotification += (object sender, UNCDidActivateNotificationEventArgs e) =>
            {
                var notification = (UserNotification)e.Notification;

                if (notification.Kind == UserNotification.NotificationKind.Normal)
                {
                    notificationCenter.RemoveDeliveredNotification(e.Notification);
                    string  msg   = notificationMessages[notification.Id];
                    NSAlert alert = NSAlert.WithMessage(notification.Title, "OK", null, null, msg);
                    notificationMessages.Remove(notification.Id);
                    alert.Icon = new NSImage(System.IO.Path.Combine(NSBundle.MainBundle.ResourcePath, "Pixmaps", "process-syncing-error.icns"));
                    alert.Window.OrderFrontRegardless();
                    alert.RunModal();
                }
                else
                {
                    LocalFolderClicked(Path.GetDirectoryName(e.Notification.InformativeText));
                }
            };

            // If we return true here, Notification will show up even if your app is TopMost.
            notificationCenter.ShouldPresentNotification = (c, n) => { return(true); };

            OnTransmissionListChanged += delegate {
                using (var a = new NSAutoreleasePool()) {
                    notificationCenter.BeginInvokeOnMainThread(delegate {
                        lock (transmissionLock) {
                            List <FileTransmissionEvent> transmissions      = ActiveTransmissions();
                            NSUserNotification[] notifications              = notificationCenter.DeliveredNotifications;
                            List <NSUserNotification> finishedNotifications = new List <NSUserNotification> ();
                            foreach (NSUserNotification notification in notifications)
                            {
                                FileTransmissionEvent transmission = transmissions.Find((FileTransmissionEvent e) => { return(e.Path == notification.InformativeText); });
                                if (transmission == null)
                                {
                                    finishedNotifications.Add(notification);
                                }
                                else
                                {
                                    if (transmissionFiles.ContainsKey(transmission.Path))
                                    {
                                        transmissions.Remove(transmission);
                                    }
                                    else
                                    {
                                        notificationCenter.RemoveDeliveredNotification(notification);
                                    }
                                }
                            }
                            finishedNotifications.Sort(new ComparerNSUserNotification());
                            for (int i = 0; i < (notifications.Length - notificationKeep) && i < finishedNotifications.Count; ++i)
                            {
                                notificationCenter.RemoveDeliveredNotification(finishedNotifications[i]);
                            }
                            foreach (FileTransmissionEvent transmission in transmissions)
                            {
                                if (transmission.Status.Aborted == true)
                                {
                                    continue;
                                }
                                if (transmission.Status.Completed == true)
                                {
                                    continue;
                                }
                                if (transmission.Status.FailedException != null)
                                {
                                    continue;
                                }
                                var notification = new UserNotification(UserNotification.NotificationKind.Transmission);
                                // NSUserNotification notification = new NSUserNotification();
                                notification.Title           = Path.GetFileName(transmission.Path);
                                notification.Subtitle        = TransmissionStatus(transmission);
                                notification.InformativeText = transmission.Path;
                                notificationMessages.Add(notification.Id, transmission.Path);
//                                notification.SoundName = NSUserNotification.NSUserNotificationDefaultSoundName;
                                transmission.TransmissionStatus += TransmissionReport;
                                // notification.DeliveryDate = NSDate.Now;
                                notificationCenter.DeliverNotification(notification);
                                transmissionFiles.Add(transmission.Path, notification.DeliveryDate);
                                UpdateFileStatus(transmission, null);
                            }
                        }
                    });
                }
            };

            AlertNotificationRaised += delegate(string title, string message) {
                var alert = new NSAlert {
                    MessageText = message,
                    AlertStyle  = NSAlertStyle.Informational
                };

                alert.AddButton("OK");

                alert.RunModal();
            };

            Utils.SetUserNotificationListener(this);
            PathRepresentationConverter.SetConverter(new OSXPathRepresentationConverter());
        }
コード例 #42
0
		public bool Run (AlertDialogData data)
		{
			using (var alert = new NSAlert ()) {
				alert.Window.Title = data.Title ?? BrandingService.ApplicationName;
				IdeTheme.ApplyTheme (alert.Window);

				bool stockIcon;
				if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Error || data.Message.Icon == Gtk.Stock.DialogError) {
					alert.AlertStyle = NSAlertStyle.Critical;
					stockIcon = true;
				} else if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Warning || data.Message.Icon == Gtk.Stock.DialogWarning) {
					alert.AlertStyle = NSAlertStyle.Critical;
					stockIcon = true;
				} else {
					alert.AlertStyle = NSAlertStyle.Informational;
					stockIcon = data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information;
				}

				if (!stockIcon && !string.IsNullOrEmpty (data.Message.Icon)) {
					var img = ImageService.GetIcon (data.Message.Icon, Gtk.IconSize.Dialog);
					// HACK: VK The icon is not rendered in dark style correctly
					//       Use light variant and reder it here
					//       as long as NSAppearance.NameVibrantDark is broken
					if (IdeTheme.UserInterfaceTheme == Theme.Dark)
						alert.Icon = img.WithStyles ("-dark").ToBitmap (GtkWorkarounds.GetScaleFactor ()).ToNSImage ();
					else
						alert.Icon = img.ToNSImage ();
				} else {
					//for some reason the NSAlert doesn't pick up the app icon by default
					alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;
				}

				alert.MessageText = data.Message.Text;
				alert.InformativeText = data.Message.SecondaryText ?? "";
				
				var buttons = data.Buttons.Reverse ().ToList ();
				
				for (int i = 0; i < buttons.Count - 1; i++) {
					if (i == data.Message.DefaultButton) {
						var next = buttons[i];
						for (int j = buttons.Count - 1; j >= i; j--) {
							var tmp = buttons[j];
							buttons[j] = next;
							next = tmp;
						}
						break;
					}
				}
				
				var wrappers = new List<AlertButtonWrapper> (buttons.Count);
				foreach (var button in buttons) {
					var label = button.Label;
					if (button.IsStockButton)
						label = Gtk.Stock.Lookup (label).Label;
					label = label.Replace ("_", "");

					//this message seems to be a standard Mac message since alert handles it specially
					if (button == AlertButton.CloseWithoutSave)
						label = GettextCatalog.GetString ("Don't Save");

					var nsbutton = alert.AddButton (label);
					var wrapperButton = new AlertButtonWrapper (nsbutton, data.Message, button, alert);
					wrappers.Add (wrapperButton);
					nsbutton.Target = wrapperButton;
					nsbutton.Action = new ObjCRuntime.Selector ("buttonActivatedAction");
				}
				
				
				NSButton[] optionButtons = null;
				if (data.Options.Count > 0) {
					var box = new MDBox (LayoutDirection.Vertical, 2, 2);
					optionButtons = new NSButton[data.Options.Count];
					
					for (int i = data.Options.Count - 1; i >= 0; i--) {
						var option = data.Options[i];
						var button = new NSButton {
							Title = option.Text,
							Tag = i,
							State = option.Value? NSCellStateValue.On : NSCellStateValue.Off,
						};
						button.SetButtonType (NSButtonType.Switch);
						optionButtons[i] = button;
						box.Add (new MDAlignment (button, true) { XAlign = LayoutAlign.Begin });
					}
					
					box.Layout ();
					alert.AccessoryView = box.View;
				}
				
				NSButton applyToAllCheck = null;
				if (data.Message.AllowApplyToAll) {
					alert.ShowsSuppressionButton = true;
					applyToAllCheck = alert.SuppressionButton;
					applyToAllCheck.Title = GettextCatalog.GetString ("Apply to all");
				}
				
				// Hack up a slightly wider than normal alert dialog. I don't know how to do this in a nicer way
				// as the min size constraints are apparently ignored.
				var frame = alert.Window.Frame;
				alert.Window.SetFrame (new CGRect (frame.X, frame.Y, NMath.Max (frame.Width, 600), frame.Height), true);
				alert.Layout ();
				
				bool completed = false;
				if (data.Message.CancellationToken.CanBeCanceled) {
					data.Message.CancellationToken.Register (delegate {
						alert.InvokeOnMainThread (() => {
							if (!completed) {
								NSApplication.SharedApplication.AbortModal ();
							}
						});
					});
				}
				
				if (!data.Message.CancellationToken.IsCancellationRequested) {

					var result = (int)alert.RunModal () - (long)(int)NSAlertButtonReturn.First;
					
					completed = true;
					if (result >= 0 && result < buttons.Count) {
						data.ResultButton = buttons [(int)result];
					} else {
						data.ResultButton = null;
					}
				}
				
				if (data.ResultButton == null || data.Message.CancellationToken.IsCancellationRequested) {
					data.SetResultToCancelled ();
				}
				
				if (optionButtons != null) {
					foreach (var button in optionButtons) {
						var option = data.Options[(int)button.Tag];
						data.Message.SetOptionValue (option.Id, button.State != 0);
					}
				}
				
				if (applyToAllCheck != null && applyToAllCheck.State != 0)
					data.ApplyToAll = true;



				GtkQuartz.FocusWindow (data.TransientFor ?? MessageService.RootWindow);
			}
			
			return true;
		}
コード例 #43
0
        public bool Run(AlertDialogData data)
        {
            using (var alert = new NSAlert()) {
                if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information)
                {
                    alert.AlertStyle = NSAlertStyle.Critical;
                }
                else if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Warning)
                {
                    alert.AlertStyle = NSAlertStyle.Warning;
                }
                else if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information)
                {
                    alert.AlertStyle = NSAlertStyle.Informational;
                }

                //FIXME: use correct size so we don't get horrible scaling?
                if (!string.IsNullOrEmpty(data.Message.Icon))
                {
                    var    pix = ImageService.GetPixbuf(data.Message.Icon, Gtk.IconSize.Dialog);
                    byte[] buf = pix.SaveToBuffer("tiff");
                    unsafe
                    {
                        fixed(byte *b = buf)
                        {
                            alert.Icon = new NSImage(NSData.FromBytes((IntPtr)b, (uint)buf.Length));
                        }
                    }
                }

                alert.MessageText     = data.Message.Text;
                alert.InformativeText = data.Message.SecondaryText ?? "";

                var buttons = data.Buttons.Reverse().ToList();

                for (int i = 0; i < buttons.Count - 1; i++)
                {
                    if (i == data.Message.DefaultButton)
                    {
                        var next = buttons[i];
                        for (int j = buttons.Count - 1; j >= i; j--)
                        {
                            var tmp = buttons[j];
                            buttons[j] = next;
                            next       = tmp;
                        }
                        break;
                    }
                }

                foreach (var button in buttons)
                {
                    var label = button.Label;
                    if (button.IsStockButton)
                    {
                        label = Gtk.Stock.Lookup(label).Label;
                    }
                    label = label.Replace("_", "");

                    //this message seems to be a standard Mac message since alert handles it specially
                    if (button == AlertButton.CloseWithoutSave)
                    {
                        label = GettextCatalog.GetString("Don't Save");
                    }

                    alert.AddButton(label);
                }


                NSButton[] optionButtons = null;
                if (data.Options.Count > 0)
                {
                    var box = new MDBox(LayoutDirection.Vertical, 2, 2);
                    optionButtons = new NSButton[data.Options.Count];

                    for (int i = data.Options.Count - 1; i >= 0; i--)
                    {
                        var option = data.Options[i];
                        var button = new NSButton()
                        {
                            Title = option.Text,
                            Tag   = i,
                            State = option.Value? NSCellStateValue.On : NSCellStateValue.Off,
                        };
                        button.SetButtonType(NSButtonType.Switch);
                        optionButtons[i] = button;
                        box.Add(new MDAlignment(button, true)
                        {
                            XAlign = LayoutAlign.Begin
                        });
                    }

                    box.Layout();
                    alert.AccessoryView = box.View;
                }

                NSButton applyToAllCheck = null;
                if (data.Message.AllowApplyToAll)
                {
                    alert.ShowsSuppressionButton = true;
                    applyToAllCheck       = alert.SuppressionButton;
                    applyToAllCheck.Title = GettextCatalog.GetString("Apply to all");
                }

                alert.Layout();

                int result = alert.RunModal() - (int)NSAlertButtonReturn.First;

                data.ResultButton = buttons [result];

                if (optionButtons != null)
                {
                    foreach (var button in optionButtons)
                    {
                        var option = data.Options[button.Tag];
                        data.Message.SetOptionValue(option.Id, button.State != 0);
                    }
                }

                if (applyToAllCheck != null && applyToAllCheck.State != 0)
                {
                    data.ApplyToAll = true;
                }

                GtkQuartz.FocusWindow(data.TransientFor ?? MessageService.RootWindow);
            }

            return(true);
        }
コード例 #44
0
		public override NSView GetViewForItem (NSTableView tableView, NSTableColumn tableColumn, nint row)
		{

			// This pattern allows you reuse existing views when they are no-longer in use.
			// If the returned view is null, you instance up a new view
			// If a non-null view is returned, you modify it enough to reflect the new data
			NSTableCellView view = (NSTableCellView)tableView.MakeView (tableColumn.Title, this);
			if (view == null) {
				view = new NSTableCellView ();

				// Configure the view
				view.Identifier = tableColumn.Title;

				// Take action based on title
				switch (tableColumn.Title) {
				case "Product":
					view.ImageView = new NSImageView (new CGRect (0, 0, 16, 16));
					view.AddSubview (view.ImageView);
					view.TextField = new NSTextField (new CGRect (20, 0, 400, 16));
					ConfigureTextField (view, row);
					break;
				case "Details":
					view.TextField = new NSTextField (new CGRect (0, 0, 400, 16));
					ConfigureTextField (view, row);
					break;
				case "Action":
					// Create new button
					var button = new NSButton (new CGRect (0, 0, 81, 16));
					button.SetButtonType (NSButtonType.MomentaryPushIn);
					button.Title = "Delete";
					button.Tag = row;

					// Wireup events
					button.Activated += (sender, e) => {
						// Get button and product
						var btn = sender as NSButton;
						var product = DataSource.Products [(int)btn.Tag];

						// Configure alert
						var alert = new NSAlert () {
							AlertStyle = NSAlertStyle.Informational,
							InformativeText = $"Are you sure you want to delete {product.Title}? This operation cannot be undone.",
							MessageText = $"Delete {product.Title}?",
						};
						alert.AddButton ("Cancel");
						alert.AddButton ("Delete");
						alert.BeginSheetForResponse (Controller.View.Window, (result) => {
							// Should we delete the requested row?
							if (result == 1001) {
								// Remove the given row from the dataset
								DataSource.Products.RemoveAt((int)btn.Tag);
								Controller.ReloadTable ();
							}
						});
					};

					// Add to view
					view.AddSubview (button);
					break;
				}

			}

			// Setup view based on the column selected
			switch (tableColumn.Title) {
			case "Product":
				view.ImageView.Image = NSImage.ImageNamed ("tag.png");
				view.TextField.StringValue = DataSource.Products [(int)row].Title;
				view.TextField.Tag = row;
				break;
			case "Details":
				view.TextField.StringValue = DataSource.Products [(int)row].Description;
				view.TextField.Tag = row;
				break;
			case "Action":
				foreach (NSView subview in view.Subviews) {
					var btn = subview as NSButton;
					if (btn != null) {
						btn.Tag = row;
					}
				}
				break;
			}

			return view;
		}
コード例 #45
0
        public bool Run(AlertDialogData data)
        {
            using (var alert = new NSAlert()) {
                alert.Window.Title = data.Title ?? BrandingService.ApplicationName;
                IdeTheme.ApplyTheme(alert.Window);

                bool stockIcon;
                if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Error || data.Message.Icon == Gtk.Stock.DialogError)
                {
                    alert.AlertStyle = NSAlertStyle.Critical;
                    stockIcon        = true;
                }
                else if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Warning || data.Message.Icon == Gtk.Stock.DialogWarning)
                {
                    alert.AlertStyle = NSAlertStyle.Critical;
                    stockIcon        = true;
                }
                else
                {
                    alert.AlertStyle = NSAlertStyle.Informational;
                    stockIcon        = data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information;
                }

                if (!stockIcon && !string.IsNullOrEmpty(data.Message.Icon))
                {
                    var img = ImageService.GetIcon(data.Message.Icon, Gtk.IconSize.Dialog);
                    // HACK: VK The icon is not rendered in dark style correctly
                    //       Use light variant and reder it here
                    //       as long as NSAppearance.NameVibrantDark is broken
                    if (IdeTheme.UserInterfaceTheme == Theme.Dark)
                    {
                        alert.Icon = img.WithStyles("-dark").ToBitmap(GtkWorkarounds.GetScaleFactor()).ToNSImage();
                    }
                    else
                    {
                        alert.Icon = img.ToNSImage();
                    }
                }
                else
                {
                    //for some reason the NSAlert doesn't pick up the app icon by default
                    alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;
                }

                alert.MessageText = data.Message.Text;

                int accessoryViewItemsCount = data.Options.Count;

                string secondaryText = data.Message.SecondaryText ?? string.Empty;
                if (TryGetMessageView(secondaryText, out NSView messageView))
                {
                    accessoryViewItemsCount++;
                }
                else
                {
                    alert.InformativeText = secondaryText;
                }

                var accessoryViews      = accessoryViewItemsCount > 0 ? new NSView [accessoryViewItemsCount] : null;
                int accessoryViewsIndex = 0;

                if (messageView != null)
                {
                    accessoryViews [accessoryViewsIndex++] = messageView;
                }

                var buttons = data.Buttons.Reverse().ToList();

                for (int i = 0; i < buttons.Count - 1; i++)
                {
                    if (i == data.Message.DefaultButton)
                    {
                        var next = buttons[i];
                        for (int j = buttons.Count - 1; j >= i; j--)
                        {
                            var tmp = buttons[j];
                            buttons[j] = next;
                            next       = tmp;
                        }
                        break;
                    }
                }

                var wrappers = new List <AlertButtonWrapper> (buttons.Count);
                foreach (var button in buttons)
                {
                    var label = button.Label;
                    if (button.IsStockButton)
                    {
                        label = Gtk.Stock.Lookup(label).Label;
                    }
                    label = label.Replace("_", "");

                    //this message seems to be a standard Mac message since alert handles it specially
                    if (button == AlertButton.CloseWithoutSave)
                    {
                        label = GettextCatalog.GetString("Don't Save");
                    }

                    var nsbutton      = alert.AddButton(label);
                    var wrapperButton = new AlertButtonWrapper(nsbutton, data.Message, button, alert);
                    wrappers.Add(wrapperButton);
                    nsbutton.Target = wrapperButton;
                    nsbutton.Action = new ObjCRuntime.Selector("buttonActivatedAction");
                }

                NSButton [] optionButtons = null;
                if (data.Options.Count > 0)
                {
                    optionButtons = new NSButton [data.Options.Count];

                    for (int i = data.Options.Count - 1; i >= 0; i--)
                    {
                        var option = data.Options[i];
                        var button = new NSButton {
                            Title = option.Text,
                            Tag   = i,
                            State = option.Value? NSCellStateValue.On : NSCellStateValue.Off,
                        };
                        button.SetButtonType(NSButtonType.Switch);
                        button.SizeToFit();
                        optionButtons [i] = button;
                        accessoryViews [accessoryViewsIndex++] = button;
                    }
                }

                var accessoryView = ArrangeAccessoryViews(accessoryViews);
                if (accessoryView != null)
                {
                    alert.AccessoryView = accessoryView;
                }

                NSButton applyToAllCheck = null;
                if (data.Message.AllowApplyToAll)
                {
                    alert.ShowsSuppressionButton = true;
                    applyToAllCheck       = alert.SuppressionButton;
                    applyToAllCheck.Title = GettextCatalog.GetString("Apply to all");
                }

                // Hack up a slightly wider than normal alert dialog. I don't know how to do this in a nicer way
                // as the min size constraints are apparently ignored.
                var frame = alert.Window.Frame;
                alert.Window.SetFrame(new CGRect(frame.X, frame.Y, NMath.Max(frame.Width, 600), frame.Height), true);
                alert.Layout();

                bool completed = false;
                if (data.Message.CancellationToken.CanBeCanceled)
                {
                    data.Message.CancellationToken.Register(delegate {
                        alert.InvokeOnMainThread(() => {
                            if (!completed)
                            {
                                if (alert.Window.IsSheet && alert.Window.SheetParent != null)
                                {
                                    alert.Window.SheetParent.EndSheet(alert.Window);
                                }
                                else
                                {
                                    NSApplication.SharedApplication.AbortModal();
                                }
                            }
                        });
                    });
                }

                int response = -1000;

                if (!data.Message.CancellationToken.IsCancellationRequested)
                {
                    NSWindow parent = null;
                    if (IdeTheme.UserInterfaceTheme != Theme.Dark || MacSystemInformation.OsVersion < MacSystemInformation.HighSierra)                     // sheeting is broken on High Sierra with dark NSAppearance
                    {
                        parent = data.TransientFor ?? IdeApp.Workbench.RootWindow;
                    }

                    if (parent == null)
                    {
                        response = (int)alert.RunModal();
                    }
                    else
                    {
                        alert.BeginSheet(parent, (modalResponse) => {
                            response = (int)modalResponse;
                            NSApplication.SharedApplication.StopModal();
                        });

                        NSApplication.SharedApplication.RunModalForWindow(alert.Window);
                    }
                }

                var result = response - (long)(int)NSAlertButtonReturn.First;

                completed = true;

                if (result >= 0 && result < buttons.Count)
                {
                    data.ResultButton = buttons [(int)result];
                }
                else
                {
                    data.ResultButton = null;
                }

                if (data.ResultButton == null || data.Message.CancellationToken.IsCancellationRequested)
                {
                    data.SetResultToCancelled();
                }

                if (optionButtons != null)
                {
                    foreach (var button in optionButtons)
                    {
                        var option = data.Options[(int)button.Tag];
                        data.Message.SetOptionValue(option.Id, button.State != 0);
                    }
                }

                if (applyToAllCheck != null && applyToAllCheck.State != 0)
                {
                    data.ApplyToAll = true;
                }


                GtkQuartz.FocusWindow(data.TransientFor ?? MessageService.RootWindow);
            }

            return(true);
        }
コード例 #46
0
        /// <summary>
        /// Called before an <c>NSWindow</c> is closed. If the contents of the window has changed and
        /// not been saved, display a dialog allowing the user to: a) Cancel the closing, b) Close
        /// without saving, c) Save the changes to the document.
        /// </summary>
        /// <returns><c>true</c>, if the window can be closed, else <c>false</c> if it cannot.</returns>
        /// <param name="sender">The <c>NSWindowController</c> calling this method.</param>
        public override bool WindowShouldClose(Foundation.NSObject sender)
        {
            // is the window dirty?
            if (Window.DocumentEdited)
            {
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Critical,
                    InformativeText = "Save changes to document before closing window?",
                    MessageText     = "Save Document",
                };
                alert.AddButton("Save");
                alert.AddButton("Lose Changes");
                alert.AddButton("Cancel");
                var result = alert.RunSheetModal(Window);

                // Take action based on resu;t
                switch (result)
                {
                case 1000:
                    // Grab controller
                    var viewController = Window.ContentViewController as ViewController;

                    // Already saved?
                    if (Window.RepresentedUrl != null)
                    {
                        var path = Window.RepresentedUrl.Path;

                        // Save changes to file
                        File.WriteAllText(path, viewController.Text);
                        return(true);
                    }
                    else
                    {
                        var dlg = new NSSavePanel();
                        dlg.Title = "Save Document";
                        dlg.BeginSheet(Window, (rslt) => {
                            // File selected?
                            if (rslt == 1)
                            {
                                var path = dlg.Url.Path;
                                File.WriteAllText(path, viewController.Text);
                                Window.DocumentEdited = false;
                                viewController.View.Window.SetTitleWithRepresentedFilename(Path.GetFileName(path));
                                viewController.View.Window.RepresentedUrl = dlg.Url;
                                Window.Close();
                            }
                        });
                        return(true);
                    }

                case 1001:
                    // Lose Changes
                    return(true);

                case 1002:
                    // Cancel
                    return(false);
                }
            }

            return(true);
        }
コード例 #47
0
		public bool Run (ExceptionDialogData data)
		{
			using (var alert = new NSAlert { AlertStyle = NSAlertStyle.Critical }) {
				alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;
				
				alert.MessageText = data.Title ?? GettextCatalog.GetString ("Error");
				
				if (!string.IsNullOrEmpty (data.Message)) {
					alert.InformativeText = data.Message;
				}

				List<AlertButton> buttons = null;
				if (data.Buttons != null && data.Buttons.Length > 0)
					buttons = data.Buttons.Reverse ().ToList ();

				if (buttons != null) {
					foreach (var button in buttons) {
						var label = button.Label;
						if (button.IsStockButton)
							label = Gtk.Stock.Lookup (label).Label;
						label = label.Replace ("_", "");

						//this message seems to be a standard Mac message since alert handles it specially
						if (button == AlertButton.CloseWithoutSave)
							label = GettextCatalog.GetString ("Don't Save");

						alert.AddButton (label);
					}
				}

				if (data.Exception != null) {
					var scrollSize = new CGSize (400, 130);
					const float spacing = 4;
					
					string title = GettextCatalog.GetString ("View details");
					string altTitle = GettextCatalog.GetString ("Hide details");
					
					var buttonFrame = new CGRect (0, 0, 0, 0);
					var button = new NSButton (buttonFrame) {
						BezelStyle = NSBezelStyle.Disclosure,
						Title = "",
						AlternateTitle = "",
					};
					button.SetButtonType (NSButtonType.OnOff);
					button.SizeToFit ();
					
					var label = new MDClickableLabel (title) {
						Alignment = NSTextAlignment.Left,
					};
					label.SizeToFit ();
					
					button.SetFrameSize (new CGSize (button.Frame.Width, NMath.Max (button.Frame.Height, label.Frame.Height)));
					label.SetFrameOrigin (new CGPoint (button.Frame.Width + 5, button.Frame.Y));
					
					var text = new MyTextView (new CGRect (0, 0, float.MaxValue, float.MaxValue)) {
						HorizontallyResizable = true,
					};
					text.TextContainer.ContainerSize = new CGSize (float.MaxValue, float.MaxValue);
					text.TextContainer.WidthTracksTextView = true;
					text.InsertText (new NSString (data.Exception.ToString ()));
					text.Editable = false;

					var scrollView = new NSScrollView (new CGRect (CGPoint.Empty, CGSize.Empty)) {
						HasHorizontalScroller = true,
						HasVerticalScroller = true,
					};
					
					var accessory = new NSView (new CGRect (0, 0, scrollSize.Width, button.Frame.Height));
					accessory.AddSubview (scrollView);
					accessory.AddSubview (button);
					accessory.AddSubview (label);
					
					alert.AccessoryView = accessory;
					
					button.Activated += delegate {
						nfloat change;
						if (button.State == NSCellStateValue.On) {
							change = scrollSize.Height + spacing;
							label.StringValue = altTitle;
							scrollView.Hidden = false;
							scrollView.Frame = new CGRect (CGPoint.Empty, scrollSize);
							scrollView.DocumentView = text;
						} else {
							change = -(scrollSize.Height + spacing);
							label.StringValue = title;
							scrollView.Hidden = true;
							scrollView.Frame = new CGRect (CGPoint.Empty, CGSize.Empty);
						}
						var f = accessory.Frame;
						f.Height += change;
						accessory.Frame = f;
						var lf = label.Frame;
						lf.Y += change;
						label.Frame = lf;
						var bf = button.Frame;
						bf.Y += change;
						button.Frame = bf;
						label.SizeToFit ();
						var panel = alert.Window;
						var pf = panel.Frame;
						pf.Height += change;
						pf.Y -= change;
						panel.SetFrame (pf, true, true);
						//unless we assign the icon again, it starts nesting old icon into the warning icon
						alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;
						alert.Layout ();
					};
					label.OnMouseUp += (sender, e) => button.PerformClick (e.Event);
				}

				var result = (int)(nint)alert.RunModal () - (int)(long)NSAlertButtonReturn.First;
				data.ResultButton = buttons != null ? buttons [result] : null;
				GtkQuartz.FocusWindow (data.TransientFor ?? MessageService.RootWindow);
			}
			
			return true;
		}
コード例 #48
0
        void AddButtons(NSAlert alert)
        {
            switch (_buttons)
            {
            case MessageBoxButtons.Ok:
                alert.AddButton("Ok");
                break;

            case MessageBoxButtons.OkCancel:
            {
                var ok     = alert.AddButton("Ok");
                var cancel = alert.AddButton("Cancel");
                switch (_defaultButton)
                {
                case MessageBoxDefaultButton.Ok:
                    ok.BecomeFirstResponder();
                    break;

                case MessageBoxDefaultButton.Cancel:
                case MessageBoxDefaultButton.Default:
                    cancel.BecomeFirstResponder();
                    break;
                }
            }
            break;

            case MessageBoxButtons.YesNo:
            {
                var yes = alert.AddButton("Yes");
                var no  = alert.AddButton("No");
                switch (_defaultButton)
                {
                case MessageBoxDefaultButton.Yes:
                    yes.BecomeFirstResponder();
                    break;

                case MessageBoxDefaultButton.No:
                case MessageBoxDefaultButton.Default:
                    no.BecomeFirstResponder();
                    break;
                }
            }
            break;

            case MessageBoxButtons.YesNoCancel:
            {
                var yes    = alert.AddButton("Yes");
                var no     = alert.AddButton("No");
                var cancel = alert.AddButton("Cancel");
                switch (_defaultButton)
                {
                case MessageBoxDefaultButton.Yes:
                    yes.BecomeFirstResponder();
                    break;

                case MessageBoxDefaultButton.No:
                    no.BecomeFirstResponder();
                    break;

                case MessageBoxDefaultButton.Cancel:
                case MessageBoxDefaultButton.Default:
                    cancel.BecomeFirstResponder();
                    break;
                }
            }
            break;

            default:
                throw new NotSupportedException();
            }
        }