コード例 #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
ファイル: MyDocument.cs プロジェクト: Dynalon/tomboy.osx
        partial void DeleteNote(NSObject sender)
        {
            NSAlert alert = new NSAlert()
            {
                MessageText     = "Really delete this note?",
                InformativeText = "You are about to delete this note, this operation cannot be undone",
                AlertStyle      = NSAlertStyle.Warning
            };

            alert.AddButton("OK");
            alert.AddButton("Cancel");
            alert.BeginSheet(WindowForSheet,
                             this,
                             new MonoMac.ObjCRuntime.Selector("alertDidEnd:returnCode:contextInfo:"),
                             IntPtr.Zero);
        }
コード例 #4
0
 public void EditPerson(NSWindow window)
 {
     if (SelectedPerson == null)
     {
         var alert = new NSAlert()
         {
             AlertStyle      = NSAlertStyle.Informational,
             InformativeText = "Please select the person to edit from the list of people.",
             MessageText     = "Edit Person",
         };
         alert.BeginSheet(window);
     }
     else
     {
         // Display editor
         PerformSegue("EditorSegue", this);
     }
 }
コード例 #5
0
ファイル: AppDelegate.cs プロジェクト: brianmed/DiskReport
        public static void DebugModal(
            NSWindow window,
            string message = "HERE",
            [CallerLineNumber] int lineNumber = 0,
            [CallerMemberName] string caller  = null,
            [CallerFilePath] string file      = null)
        {
            Console.WriteLine(message + " at line " + lineNumber + " (" + caller + ") " + "[" + file + "]");

            var alert = new NSAlert()
            {
                AlertStyle      = NSAlertStyle.Informational,
                InformativeText = lineNumber + " (" + caller + ") " + "[" + file + "]",
                MessageText     = message,
            };

            alert.BeginSheet(window);
        }
コード例 #6
0
        private void SetResult(FingerprintAuthenticationResult result)
        {
            if (result.Authenticated)
            {
                var alert = new NSAlert
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    MessageText     = "Success",
                    InformativeText = "You have Fingers!"
                };

                alert.BeginSheet(this.View.Window);
            }
            else
            {
                lblStatus.StringValue = $"{result.Status}: {result.ErrorMessage}";
            }
        }
コード例 #7
0
 public void EditCheat(NSWindow window)
 {
     if (CheatTableView.SelectedRow == -1)
     {
         var alert = new NSAlert
         {
             AlertStyle      = NSAlertStyle.Informational,
             InformativeText = NSBundle.MainBundle.LocalizedString("Please select the cheat to edit from the list of cheats.", null),
             MessageText     = NSBundle.MainBundle.LocalizedString("Edit Cheat", null),
         };
         alert.BeginSheet(window);
     }
     else
     {
         SelectedCheat = _cheats.GetItem <CheatModel>((nuint)CheatTableView.SelectedRow);
         PerformSegue("EditorSegue", this);
     }
 }
コード例 #8
0
        partial void ExportNotesAction(NSObject sender)
        {
            if (ExportPathTextField.StringValue != null)
            {
                string rootDirectory = ExportPathTextField.StringValue;
                ExportNotes.Export(rootDirectory);

                NSAlert alert = new NSAlert()
                {
                    MessageText     = "Note Imported",
                    InformativeText = "All the notes have been imported to local storage. Please restart the Tomboy to see your old notes",
                    AlertStyle      = NSAlertStyle.Warning
                };
                alert.AddButton("OK");
                alert.BeginSheet(this.Window,
                                 this,
                                 null,
                                 IntPtr.Zero);
            }
        }
コード例 #9
0
        void Run(NSAlert alert)
        {
            switch (AlertOptions.SelectedTag)
            {
            case 0:
                alert.BeginSheet(Window, response => ShowResponse(alert, response));
                break;

            case 1:
                ShowResponse(alert, alert.RunSheetModal(Window));
                break;

            case 2:
                ShowResponse(alert, alert.RunModal());
                break;

            default:
                ResultLabel.StringValue = "Unknown Alert Option";
                break;
            }
        }
コード例 #10
0
        public void EditPerson(NSWindow window)
        {
            if (Table.SelectedRow == -1)
            {
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = "Please select the person to edit from the list of people.",
                    MessageText     = "Edit Person",
                };
                alert.BeginSheet(window);
            }
            else
            {
                // Grab person
                SelectedPerson = _people.GetItem <PersonModel> ((nuint)Table.SelectedRow);

                // Display editor
                PerformSegue("EditorSegue", this);
            }
        }
コード例 #11
0
        public static void Show(NSWindow window, string title, string message = null, NSAlertStyle style = NSAlertStyle.Informational)
        {
            if (string.IsNullOrEmpty(title) && string.IsNullOrEmpty(message))
            {
                return;
            }

            NSRunningApplication.CurrentApplication.Activate(NSApplicationActivationOptions.ActivateIgnoringOtherWindows);

            var alert = new NSAlert();

            alert.AlertStyle = style;
            if (message != null)
            {
                alert.InformativeText = message;
            }
            if (title != null)
            {
                alert.MessageText = title;
            }
            alert.BeginSheet(window);
        }
コード例 #12
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Fire the timer once a second
            MainTimer          = new Timer(1000);
            MainTimer.Elapsed += (sender, e) => {
                TimeLeft--;
                // Format the remaining time nicely for the label
                TimeSpan time       = TimeSpan.FromSeconds(TimeLeft);
                string   timeString = time.ToString(@"mm\:ss");
                InvokeOnMainThread(() => {
                    // We want to interact with the UI from a different thread,
                    // so we must invoke this change on the main thread
                    TimerLabel.StringValue = timeString;
                });

                // If 25 minutes have passed
                if (TimeLeft == 0)
                {
                    // Stop the timer and reset
                    MainTimer.Stop();
                    TimeLeft = 1500;
                    InvokeOnMainThread(() => {
                        // Reset the UI
                        TimerLabel.StringValue = "25:00";
                        StartStopButton.Title  = "Start";

                        NSAlert alert = new NSAlert();
                        // Set the style and message text
                        alert.AlertStyle  = NSAlertStyle.Informational;
                        alert.MessageText = "25 Minutes elapsed! Take a 5 minute break.";

                        // Display the NSAlert from the current view
                        alert.BeginSheet(View.Window);
                    });
                }
            };
        }
コード例 #13
0
        public void DeletePerson(NSWindow window)
        {
            if (View.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)View.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)
                    {
                        // Remove from database
                        SelectedPerson.Delete(_conn);

                        // Remove from screen
                        RemovePerson(View.SelectedRow);
                    }
                });
            }
        }
コード例 #14
0
        void GetSpoiler(NSObject sender)
        {
            var txt = seedField.StringValue;

            if (txt.Length == 0)
            {
                var alert = new NSAlert
                {
                    MessageText     = "No Seed",
                    InformativeText = "There is no seed specified in the seed field.\n\nThis is needed to generate a spoiler for that seed.",
                    AlertStyle      = NSAlertStyle.Warning
                };

                alert.BeginSheet(this.View.Window);
                WriteOutput("No seed specified.", true);
                return;
            }
            ClearOutput();
            var difficulty = GetRandomizerDifficulty();

            CreateSpoilerLog(difficulty);
        }
コード例 #15
0
        /// <summary>
        /// Log Exception/Error. To display alert requires source NSWindow
        /// </summary>
        /// <param name="exception">Exception.</param>
        /// <param name="message">Message.</param>
        /// <param name="displayAlert">If set to <c>true</c> display alert.</param>
        /// <param name="source">Source.</param>
        public static void AQ_Exception(AQ_EXCEPTION_CODE exception, string message, bool displayAlert = true, NSWindow source = null)
        {
            // build entry
            string sExceptionEntry = string.Format("{0} {1}{2}Exception: {3}{2}{4}"
                                                   , DateTime.Now.ToShortDateString()
                                                   , DateTime.Now.ToShortTimeString()
                                                   , Environment.NewLine
                                                   , exception
                                                   , message);

            // add to log
            m_sLog += sExceptionEntry + Environment.NewLine;

            // display alert
            if (displayAlert)
            {
                // create and display alert
                NSAlert alert = new NSAlert();
                alert.AlertStyle  = NSAlertStyle.Warning;
                alert.MessageText = sExceptionEntry;
                alert.BeginSheet(source);
            }
        }
コード例 #16
0
        public void EditPerson(NSWindow window)
        {
            if (View.SelectedRow == -1)
            {
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = "Please select the person to edit from the list of people.",
                    MessageText     = "Edit Person",
                };
                alert.BeginSheet(window);
            }
            else
            {
                // Grab person
                SelectedPerson = _people.GetItem <PersonModel> ((nuint)View.SelectedRow);

                var sheet = new PersonEditorSheetController(SelectedPerson, false);

                // Display sheet
                sheet.ShowSheet(window);
            }
        }
コード例 #17
0
        protected override void RunErrorDialog(bool isDownloadError, string message)
        {
            var alert = new NSAlert {
                AlertStyle  = NSAlertStyle.Critical,
                MessageText = isDownloadError
                    ? Catalog.GetString("Error Downloading Update")
                    : Catalog.GetString("Error Installing Update"),
                InformativeText = message
            };

            if (isDownloadError)
            {
                alert.AddButton(Catalog.GetString("Download & Install Manually"));
            }

            alert.AddButton(Catalog.GetString("Dismiss"));

            alert.BeginSheet(window, response => {
                if (isDownloadError && (int)response == 1000)
                {
                    NSWorkspace.SharedWorkspace.OpenUrl(UpdateItem.DownloadUrl);
                }
            });
        }
コード例 #18
0
        void GenerateRandomizedROM(Foundation.NSObject sender)
        {
            if (string.IsNullOrWhiteSpace(seedField.StringValue))
            {
                SetSeedBasedOnDifficulty();
            }

            ClearOutput();

            var options = GetOptions();

            if (options.Difficulty == RandomizerDifficulty.None)
            {
                options.NoRandomization = true;
                var randomizer = new Randomizer(0, new RomLocationsNoRandomization(), null);
                randomizer.CreateRom(options);
                WriteOutput("Non-randomized rom created.");

                return;
            }


            if (!int.TryParse(seedField.StringValue, out int parsedSeed))
            {
                var alert = new NSAlert
                {
                    MessageText     = "Seed Error",
                    InformativeText = "Seed must be numeric or blank.",
                    AlertStyle      = NSAlertStyle.Warning
                };

                alert.BeginSheet(this.View.Window);

                WriteOutput("Seed must be numeric or blank.", true);
            }
            else
            {
                try
                {
                    var           romLocations = RomLocationsFactory.GetRomLocations(options.Difficulty);
                    RandomizerLog log          = null;

                    if (spoilerLogCheck.State == NSCellStateValue.On)
                    {
                        log = new RandomizerLog(string.Format(romLocations.SeedFileString, parsedSeed));
                    }

                    seedField.StringValue = string.Format(romLocations.SeedFileString, parsedSeed);

                    if (options.Difficulty == RandomizerDifficulty.Casual)
                    {
                        WriteCasualMessage();
                    }

                    var complexity = CreateRom(romLocations, log, options, parsedSeed);

                    var outputString = new StringBuilder();

                    outputString.AppendFormat("Done!{0}{0}{0}Seed: ", Environment.NewLine);
                    outputString.AppendFormat(romLocations.SeedFileString, parsedSeed);
                    if (complexityCheck.State == NSCellStateValue.On)
                    {
                        outputString.AppendFormat(" ({0} Difficulty - Complexity {2}){1}{1}", romLocations.DifficultyName, Environment.NewLine, complexity);
                    }
                    else
                    {
                        outputString.AppendFormat(" ({0} Difficulty){1}{1}", romLocations.DifficultyName, Environment.NewLine);
                    }

                    WriteOutput(outputString.ToString());
                }
                catch (RandomizationException ex)
                {
                    WriteOutput(ex.ToString(), true);
                }
            }

            SaveRandomizerSettings();
        }
コード例 #19
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 = 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)
                {
                    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();
                        });

                        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;
                }

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

            return(true);
        }
コード例 #20
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)
                            {
                                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);
        }
コード例 #21
0
ファイル: ViewController.cs プロジェクト: srinz9/TripPhotos
        public void StartRenaming(string sourceDirectory, string destinationDirectory,
                                  bool renameSourceFiles, bool backup, bool prefixYear,
                                  bool processJpegs, bool processVideos)
        {
            string destFileFullName = string.Empty;
            string destFileName     = string.Empty;
            string temp             = string.Empty;
            string extension        = string.Empty;
            string newDirectory;
            string newDestFileName;
            int    totalFiles         = 0;
            int    tobeProcessedFiles = 0;
            int    processedFiles     = 0;
            //Image image = null;
            DateTime?dateTaken;
            DateTime?dtaken;
            bool     processing = false;

            try
            {
                sourceDirectory = sourceDirectory.TrimEnd(Path.DirectorySeparatorChar);

                // if rename source files, then destination directory is the same as source
                if (renameSourceFiles)
                {
                    destinationDirectory = sourceDirectory;
                }

                if (!(Directory.Exists(sourceDirectory) &&
                      Directory.Exists(destinationDirectory)))
                {
                    //https://developer.xamarin.com/guides/mac/user-interface/alert/
                    using (var alert = new NSAlert())
                    {
                        alert.AlertStyle      = NSAlertStyle.Critical;
                        alert.InformativeText = "Folder doesn't exist.";
                        alert.MessageText     = "Error";
                        alert.BeginSheet(this.View.Window);
                    }
                }

                DirectoryInfo di    = new DirectoryInfo(sourceDirectory);
                FileInfo[]    files = di.GetFiles("*.*", SearchOption.AllDirectories);
                totalFiles = files.Length;

                DirectoryInfo[] directories = di.GetDirectories("*", SearchOption.AllDirectories);

                // create backup folder in the destination folder
                if (backup)
                {
                    // if there are no sub directories, at least one BackUp has to be created
                    Directory.CreateDirectory(string.Format("{0}{1}{2}",
                                                            destinationDirectory,
                                                            Path.DirectorySeparatorChar,
                                                            "BackUp"));

                    foreach (DirectoryInfo directory in directories)
                    {
                        newDirectory = directory.FullName.Replace(sourceDirectory,
                                                                  string.Format("{0}{1}{2}",
                                                                                destinationDirectory,
                                                                                Path.DirectorySeparatorChar,
                                                                                "BackUp"));
                        Directory.CreateDirectory(newDirectory);
                    }
                }

                progressBar.MinValue    = 0;
                progressBar.MaxValue    = totalFiles;
                progressBar.DoubleValue = processedFiles;
                progressBar.Hidden      = false;

                foreach (FileInfo file in files)
                {
                    try
                    {
                        // if backup is needed, then copy file
                        // every file type
                        if (backup)
                        {
                            File.Copy(file.FullName, file.FullName.Replace(sourceDirectory,
                                                                           string.Format("{0}{1}{2}",
                                                                                         destinationDirectory,
                                                                                         Path.DirectorySeparatorChar,
                                                                                         "BackUp")));
                        }

                        extension    = file.Extension;
                        destFileName = file.Name;

                        // if jp*g then process
                        // else just move to destination
                        if ((string.Compare(file.Extension, ".jpg", true) == 0) ||
                            (string.Compare(file.Extension, ".jpeg", true) == 0) ||
                            (string.Compare(file.Extension, ".avi", true) == 0) ||
                            (string.Compare(file.Extension, ".mp4", true) == 0) ||
                            (string.Compare(file.Extension, ".mov", true) == 0) ||
                            (string.Compare(file.Extension, ".wav", true) == 0) ||
                            (string.Compare(file.Extension, ".heic", true) == 0)
                            //(string.Compare(file.Extension, ".cr2", true) == 0)
                            )
                        {
                            tobeProcessedFiles++;
                            dateTaken  = null;
                            dtaken     = null;
                            processing = false;

                            if (((string.Compare(file.Extension, ".jpg", true) == 0) ||
                                 (string.Compare(file.Extension, ".jpeg", true) == 0))
                                //(string.Compare(file.Extension, ".cr2", true) == 0))
                                &&
                                (processJpegs))
                            {
                                // images
                                try
                                {
                                    dtaken     = ExtractDateTimeTaken(file.FullName);
                                    dateTaken  = ActualGetDateTaken(dtaken);
                                    processing = true;
                                }
                                catch (Exception ex)
                                {
                                    richTextFailed.StringValue += string.Format("{0} - {1}\r\n", file.FullName, ex.Message);
                                }
                            }
                            else if (((string.Compare(file.Extension, ".avi", true) == 0) ||
                                      (string.Compare(file.Extension, ".mp4", true) == 0) ||
                                      (string.Compare(file.Extension, ".mov", true) == 0) ||
                                      (string.Compare(file.Extension, ".wav", true) == 0))
                                     &&
                                     (processVideos))
                            {
                                // videos
                                dtaken     = file.LastWriteTime;
                                dateTaken  = ActualGetDateTaken(dtaken);
                                processing = true;
                            }

                            if (processing)
                            {
                                if (dateTaken.HasValue)
                                {
                                    if (prefixYear)
                                    {
                                        destFileName = dateTaken.Value.ToString("yyyy_MMdd_HHmmss");
                                    }
                                    else
                                    {
                                        destFileName = dateTaken.Value.ToString("MMdd_HHmmss");
                                    }
                                }
                                else
                                {
                                    destFileName = Path.GetFileNameWithoutExtension(file.Name);
                                }

                                if (renameSourceFiles)
                                {
                                    destFileFullName = GetDestinationFileFullName(file.FullName,
                                                                                  Directory.GetParent(file.FullName).FullName,
                                                                                  destFileName,
                                                                                  extension);
                                }
                                else
                                {
                                    destFileFullName = GetDestinationFileFullName(file.FullName,
                                                                                  destinationDirectory,
                                                                                  destFileName,
                                                                                  extension);
                                }

                                // TODO: what if the random # is regenerated?
                                // then we will lose a file
                                if (File.Exists(destFileFullName))
                                {
                                    if (prefixYear)
                                    {
                                        newDestFileName = string.Format("{0}_{1}",
                                                                        dateTaken.Value.ToString("yyyy_MMdd_HHmmss"),
                                                                        new Random().Next(100));
                                    }
                                    else
                                    {
                                        newDestFileName = string.Format("{0}_{1}",
                                                                        dateTaken.Value.ToString("MMdd_HHmmss"),
                                                                        new Random().Next(100));
                                    }

                                    destFileFullName = destFileFullName.Replace(destFileName, newDestFileName);
                                }

                                //if (chkAdjustOrientation.Checked && !OrientImage (file.FullName, destFileFullName))
                                //{
                                File.Copy(file.FullName, destFileFullName, false);
                                //}

                                processedFiles++;

                                // if source files are to be deleted, then lets do it
                                if (renameSourceFiles)
                                {
                                    File.Delete(file.FullName);
                                }
                            }

                            destFileFullName = string.Empty;
                        }
                        else // not a jp*g or avi
                        {
                            if (!renameSourceFiles)
                            {
                                destFileFullName = GetDestinationFileFullName(file.FullName, destinationDirectory, destFileName, extension);
                                File.Copy(file.FullName, destFileFullName, false);
                            }
                            else
                            {
                                File.Delete(file.FullName);
                            }
                        }

                        progressBar.DoubleValue++;
                    }
                    catch (Exception ex)
                    {
                        richTextFailed.StringValue += string.Format("{0} - {1} - {2}\r\n", file.FullName, destFileFullName, ex.Message);
                    }
                }

                progressBar.Hidden = true;
                using (var alert = new NSAlert())
                {
                    alert.AlertStyle      = NSAlertStyle.Informational;
                    alert.InformativeText = string.Format("{0}/{1} files processed \r\n{2} total files", processedFiles, tobeProcessedFiles, totalFiles);
                    alert.MessageText     = "Done";
                    alert.BeginSheet(this.View.Window);
                }

                //if (chkOpenFolders.Checked)
                //{
                //    Process.Start(source);
                //    Process.Start(destinationDirectory);
                //}
                //}
            }
            catch (Exception ex)
            {
                using (var alert = new NSAlert())
                {
                    alert.AlertStyle      = NSAlertStyle.Critical;
                    alert.InformativeText = ex.Message;
                    alert.MessageText     = "Error";
                    alert.BeginSheet(this.View.Window);
                }
            }
        }
コード例 #22
0
		public void EditPerson(NSWindow window) {
			if (Table.SelectedRow == -1) {
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Informational,
					InformativeText = "Please select the person to edit from the list of people.",
					MessageText = "Edit Person",
				};
				alert.BeginSheet (window);
			} else {
				// Grab person
				SelectedPerson = _people.GetItem<PersonModel> ((nuint)Table.SelectedRow);

				// Display editor
				PerformSegue("EditorSegue", this);
			}
		}
コード例 #23
0
		public void EditPerson(NSWindow window) {
			if (View.SelectedRow == -1) {
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Informational,
					InformativeText = "Please select the person to edit from the list of people.",
					MessageText = "Edit Person",
				};
				alert.BeginSheet (window);
			} else {
				// Grab person
				SelectedPerson = _people.GetItem<PersonModel> ((nuint)View.SelectedRow);

				var sheet = new PersonEditorSheetController(SelectedPerson, false);

				// Display sheet
				sheet.ShowSheet(window);

			}
		}
コード例 #24
0
        void GenerateMultipleROMs(Foundation.NSObject sender)
        {
            NSAlert alert;

            if (!filename.Contains("<seed>"))
            {
                alert = new NSAlert
                {
                    MessageText     = "Filename Error",
                    InformativeText = "Bulk create requires \"<seed>\" be in the file name.",
                    AlertStyle      = NSAlertStyle.Critical
                };
                alert.BeginSheet(this.View.Window);
                WriteOutput("Bulk create requires \"<seed>\" be in the file name.", true);
            }
            else
            {
                ClearOutput();

                SetSeedBasedOnDifficulty();

                var difficulty = GetRandomizerDifficulty();

                if (difficulty == RandomizerDifficulty.None)
                {
                    return;
                }

                if (difficulty == RandomizerDifficulty.Casual)
                {
                    WriteCasualMessage();
                }

                int successCount = 0;
                int failCount    = 0;

                for (int seedNum = 0; seedNum < bulkStepper.IntValue; seedNum++)
                {
                    var           parsedSeed   = new SeedRandom().Next(10000000);
                    var           romLocations = RomLocationsFactory.GetRomLocations(difficulty);
                    RandomizerLog log          = null;

                    var outputString = new StringBuilder();
                    outputString.Append("Creating Seed: ");
                    outputString.AppendFormat(romLocations.SeedFileString, parsedSeed);
                    outputString.AppendFormat(" ({0} Difficulty){1}", romLocations.DifficultyName, Environment.NewLine);
                    WriteOutput(outputString.ToString());

                    if (spoilerLogCheck.State == NSCellStateValue.On)
                    {
                        log = new RandomizerLog(string.Format(romLocations.SeedFileString, parsedSeed));
                    }

                    seedField.StringValue = string.Format(romLocations.SeedFileString, parsedSeed);

                    try
                    {
                        var complexity = CreateRom(romLocations, log, GetOptions(), parsedSeed);

                        outputString = new StringBuilder();
                        outputString.AppendFormat("Completed Seed: ");
                        outputString.AppendFormat(romLocations.SeedFileString, parsedSeed);
                        if (complexityCheck.State == NSCellStateValue.On)
                        {
                            outputString.AppendFormat(" ({0} Difficulty - Complexity {2}){1}{1}", romLocations.DifficultyName, Environment.NewLine, complexity);
                        }
                        else
                        {
                            outputString.AppendFormat(" ({0} Difficulty){1}{1}", romLocations.DifficultyName, Environment.NewLine);
                        }
                        WriteOutput(outputString.ToString());

                        successCount++;
                    }
                    catch (RandomizationException ex)
                    {
                        outputString = new StringBuilder();
                        outputString.AppendFormat("FAILED Creating Seed: ");
                        outputString.AppendFormat(romLocations.SeedFileString, parsedSeed);
                        outputString.AppendFormat(" ({0} Difficulty) - {1}{2}{2}", romLocations.DifficultyName, ex.Message, Environment.NewLine);
                        WriteOutput(outputString.ToString());

                        failCount++;
                        seedNum--;

                        if (failCount >= 3)
                        {
                            WriteOutput(string.Format("Stopping bulk creation after {0} failures.{1}", failCount, Environment.NewLine), true);
                        }
                    }
                }

                var finishedString = new NSMutableAttributedString(string.Format("Completed! {0} successful", successCount));

                if (failCount > 0)
                {
                    finishedString.Append(new NSAttributedString(", "));
                    finishedString.Append(new NSAttributedString(string.Format("{0} failed. ", failCount), null, NSColor.Red));
                }
                else
                {
                    finishedString.Append(new NSAttributedString("."));
                }

                WriteOutput(finishedString);
                alert = new NSAlert
                {
                    MessageText     = "Bulk Creation Complete",
                    InformativeText = finishedString.Value,
                    AlertStyle      = failCount > 0 ? NSAlertStyle.Informational : NSAlertStyle.Warning
                };
                alert.BeginSheet(this.View.Window);
            }

            SaveRandomizerSettings();
        }
コード例 #25
0
		public void EditPerson(NSWindow window) {
			if (SelectedPerson == null) {
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Informational,
					InformativeText = "Please select the person to edit from the list of people.",
					MessageText = "Edit Person",
				};
				alert.BeginSheet (window);
			} else {
				// Display editor
				PerformSegue("EditorSegue", this);
			}
		}
コード例 #26
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            this.labeltime.Alignment       = NSTextAlignment.Center;
            this.txtRemain.StringValue     = "";
            this.txtRemain.BackgroundColor = NSColor.FromRgb(135 / 255f, 206 / 255f, 250 / 255f);
            this.txtRemain.Alignment       = NSTextAlignment.Center;
            this.txtminutes.Alignment      = NSTextAlignment.Right;

            SecondTimer          = new Timer(1000);
            SecondTimer.Elapsed += (sender, e) =>
            {
                TimeLeft--;
                TimeSpan time = TimeSpan.FromSeconds(TimeLeft);

                InvokeOnMainThread(() =>
                {
                    this.txtRemain.StringValue = $"剩:{TimeLeft / 60} 分鐘 ";
                });

                if (TimeLeft == 0)
                {
                    // Stop the timer and reset
                    //SecondTimer.Stop();
                    TimeLeft = this.orignTimeLeft;

                    InvokeOnMainThread(() =>
                    {
                        String path = NSBundle.MainBundle.PathForResource("fb", "mp3");

                        NSSound sound = new NSSound(path, true);

                        sound.Play();

                        NSAlert alert = new NSAlert();
                        // Set the style and message text
                        alert.AlertStyle  = NSAlertStyle.Informational;
                        alert.MessageText = "起來休息啦!!";
                        //NSImage image = NSImage.ImageNamed("clock.ico");
                        // Display the NSAlert from the current view
                        alert.BeginSheet(View.Window);
                        NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(5), (a) => {
                            this.View.Window.EndSheet(alert.Window);
                        });
                    });
                }
            };


            MainTimer          = new Timer(1000);
            MainTimer.Elapsed += (sender, e) =>
            {
                DateTime time       = DateTime.Now;
                string   timeString = time.ToString(@"HH\:mm\:ss");
                InvokeOnMainThread(() =>
                {
                    this.labeltime.StringValue = timeString;
                });
            };

            MainTimer.Start();

            thirdTimer          = new Timer(3000);
            thirdTimer.Elapsed += (sender, e) =>
            {
                imagenumber++;

                InvokeOnMainThread(() =>
                {
                    ChangeBackground((imagenumber));

                    NextSnowStartPosition();
                    //this.HideLayer();
                });


                if (imagenumber == 6)
                {
                    imagenumber = 1;
                }
            };

            thirdTimer.Start();
        }