示例#1
0
文件: MacModal.cs 项目: hultqvist/Eto
		public static int Run (NSSavePanel panel, Control parent)
		{
			int ret;
			if (parent != null) {
				var window = parent.ControlObject as NSWindow;
				if (window == null && parent.ControlObject is NSView)
					window = ((NSView)parent.ControlObject).Window;
				if (window == null || !panel.RespondsToSelector (new Selector ("beginSheetModalForWindow:completionHandler:")))
					ret = panel.RunModal ();
				else {
					panel.BeginSheet (window, delegate(int result) { 
						NSApplication.SharedApplication.StopModalWithCode (result); 
					});
					ret = NSApplication.SharedApplication.RunModalForWindow (window);
				}
			} else
				ret = panel.RunModal ();
			return ret;
		}
示例#2
0
        public override WindowResponse Show()
        {
            WindowResponse resp;
            List<string> filetypes = new List<string>();
            NSUrl initDir = null;
            if (Directory.Exists(InitialDirectory)) initDir = new NSUrl(InitialDirectory);

            switch(DialogType)
            {
                case FileDialogType.OpenFile:
                    ofdlg = new NSOpenPanel();
                    if (initDir != null) ofdlg.DirectoryUrl = initDir;
                    ofdlg.Title = Title;
                    ofdlg.CanChooseFiles = true;
                    ofdlg.CanChooseDirectories = false;
                    ofdlg.AllowsMultipleSelection = false;
                    if(filetypes.Count > 0)
                    {
                        foreach(FileTypeFilter arr in FileTypeFilters) filetypes.AddRange(arr.Filter);
                        ofdlg.AllowedFileTypes = filetypes.ToArray();
                    }

                    resp = CocoaHelper.GetResponse(ofdlg.RunModal());
                    SelectedPath = ofdlg.Url.Path;
                    return resp;

                case FileDialogType.SelectFolder:
                    ofdlg = new NSOpenPanel();
                    if (initDir != null) ofdlg.DirectoryUrl = initDir;
                    ofdlg.Title = Title;
                    ofdlg.CanChooseFiles = false;
                    ofdlg.CanChooseDirectories = true;
                    ofdlg.AllowsMultipleSelection = false;

                    resp = CocoaHelper.GetResponse(ofdlg.RunModal());
                    SelectedPath = ofdlg.Url.Path;
                    return resp;

                case FileDialogType.SaveFile:
                    sfdlg = new NSSavePanel();
                    if (initDir != null) sfdlg.DirectoryUrl = initDir;
                    sfdlg.Title = Title;
                    sfdlg.CanCreateDirectories = true;

                    resp = CocoaHelper.GetResponse(sfdlg.RunModal());
                    SelectedPath = sfdlg.Url.Path;
                    return resp;
            }

            return WindowResponse.None;
        }
示例#3
0
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            var currentDirectory = Environment.CurrentDirectory;

            try
            {
                using (var context = new ModalDialogContext())
                {
                    var panel = new NSSavePanel();

                    if (!String.IsNullOrWhiteSpace(InitialDirectory) && Directory.Exists(InitialDirectory))
                    {
                        panel.DirectoryUrl = NSUrl.FromFilename(InitialDirectory);
                        currentDirectory   = InitialDirectory;
                    }

                    if (!String.IsNullOrWhiteSpace(FileName))
                    {
                        panel.NameFieldStringValue = FileName;
                    }

                    if (NSPanelButtonType.Ok != (NSPanelButtonType)(int)panel.RunModal())
                    {
                        return(false);
                    }

                    FileName = SelectedPath = panel.Url.Path;

                    return(true);
                }
            }
            finally
            {
                if (RestoreDirectory && currentDirectory != null && Directory.Exists(currentDirectory))
                {
                    Environment.CurrentDirectory = currentDirectory;
                }
            }
        }
示例#4
0
        bool IDialogCreator.SaveFile(string title, string extensions, string filename, out string path)
        {
            path = null;

            var saveDialog = new NSSavePanel()
            {
                Title            = title,
                AllowedFileTypes = extensions.Split(',')
            };

            if (!string.IsNullOrWhiteSpace(filename))
            {
                saveDialog.NameFieldStringValue = filename;
            }

            if (saveDialog.RunModal() == 1 && saveDialog.Url != null)
            {
                path = saveDialog.Url.Path;
            }

            return(path != null);
        }
        public void SaveDocumentAs()
        {
            NSSavePanel saveDlg = new NSSavePanel();

            saveDlg.CanCreateDirectories = true;
            saveDlg.AllowedFileTypes     = new string[] { "xml", "PDF" };
            saveDlg.AllowsOtherFileTypes = true;

            if (FileNameOK)
            {
                //openDlg.Sta = FileName;
            }

            int result = saveDlg.RunModal();

            if (result == 1)
            {
                FileNameOK = true;
                FileName   = saveDlg.Url.Path;
                SaveSettings();
            }
        }
        async Task SaveExportedData()
        {
            if (syncController?.SyncState != SyncState.Finished)
            {
                return;
            }

            var dialog = new NSSavePanel {
                Title = "Save Exported Rdio Data",
                NameFieldStringValue = syncController.FileName
            };

            var window = Window;

            if (window == null)
            {
                await SaveExportedData(window, dialog.RunModal(), dialog.Url);
            }
            else
            {
                dialog.BeginSheet(window, async result => await SaveExportedData(window, result, dialog.Url));
            }
        }
示例#7
0
        public Task <string> SetFilePath(Tuple <string, string>[] AllowedTypes = null)
        {
            var tcs = new TaskCompletionSource <string>();

            var dlg = new NSSavePanel();

            dlg.Title            = "Save File";
            dlg.AllowedFileTypes = AllowedTypes.Select(t => (t.Item2.StartsWith(".") ? t.Item2.Substring(1) : t.Item2)).ToArray <string>();

            if (dlg.RunModal() == 1)
            {
                if (dlg.Url != null)
                {
                    tcs.SetResult(dlg.Url.Path);
                }
            }
            else
            {
                tcs.SetResult(string.Empty);
            }

            return(tcs.Task);
        }
示例#8
0
        public static string SaveFileDialog(string promt, string filters, string defaultExt)
        {
            var savePanel = new NSSavePanel();

            savePanel.ReleasedWhenClosed = true;
            savePanel.Prompt             = promt;

            var result = savePanel.RunModal();

            if (result == 1)
            {
                var path = savePanel.Url.AbsoluteString;

                if (path.StartsWith("file:"))
                {
                    path = '/' + path.Substring(5).TrimStart('/');
                }

                return(path);
            }

            return(null);
        }
示例#9
0
        private async Task <StorageFile?> PickSaveFileTaskAsync(CancellationToken token)
        {
            var savePicker = new NSSavePanel();

            savePicker.DirectoryUrl     = new NSUrl(GetStartPath(), true);
            savePicker.AllowedFileTypes = GetFileTypes();
            if (!string.IsNullOrEmpty(CommitButtonText))
            {
                savePicker.Prompt = CommitButtonText;
            }
            if (SuggestedFileName != null)
            {
                savePicker.NameFieldStringValue = SuggestedFileName;
            }
            if (savePicker.RunModal() == ModalResponseOk)
            {
                return(await StorageFile.GetFileFromPathAsync(savePicker.Url.Path));
            }
            else
            {
                return(null);
            }
        }
示例#10
0
        //save the script to an AIFF file
        partial void SaveVoiceButton(NSObject sender)
        {
            NSUrl savePath = null;

            using (var saveDialog = new NSSavePanel())
            {
                var result = saveDialog.RunModal();
                if (result == 1)
                {
                    if (!saveDialog.Url.RelativePath.EndsWith(".aif", StringComparison.CurrentCulture))
                    {
                        savePath = saveDialog.Url.AppendPathExtension("aif");
                    }
                }
            }
            if (savePath != null)
            {
                if (SpeechSynthesizer.SaveToFile(song.GetSpeechSynthesisScript(), SpeechSynthesizer.SystemVoices[SystemVoicesMenu.IndexOfSelectedItem], savePath))
                {
                    Alert.CreateAlert("Saved successfully.", AlertType.Info);
                }
            }
        }
示例#11
0
        public bool Save()
        {
            var dlg = new NSSavePanel();

            dlg.Title = "Save Tournament";

            List <string> filterTemp = new List <string>();

            for (int i = 0; i < filter.Count; i++)
            {
                filterTemp.Add(filter[0]);
            }

            dlg.AllowedFileTypes = filter.ToArray();

            bool result = dlg.RunModal() == 1;

            if (result == true)
            {
                FileName = dlg.Url.Path;
            }
            return(result);
        }
示例#12
0
        void ShowSaveDialogEventDelegate(string file_name, string target_folder_path)
        {
            SparkleShare.Controller.Invoke(() => {
                NSSavePanel panel = new NSSavePanel()
                {
                    DirectoryUrl         = new NSUrl(target_folder_path, isDir: true),
                    NameFieldStringValue = file_name,
                    ParentWindow         = this,
                    Title = "Restore from History",
                    PreventsApplicationTerminationWhenModal = false
                };

                if ((NSPanelButtonType)(int)panel.RunModal() == NSPanelButtonType.Ok)
                {
                    string target_file_path = Path.Combine(panel.DirectoryUrl.RelativePath, panel.NameFieldStringValue);
                    Controller.SaveDialogCompleted(target_file_path);
                }
                else
                {
                    Controller.SaveDialogCancelled();
                }
            });
        }
示例#13
0
        public void Save()
        {
            var dlg = new NSSavePanel();

            dlg.Title            = "Save Text File";
            dlg.AllowedFileTypes = new string[] { "txt" };
            dlg.Directory        = modelsDirectory;
            if (dlg.RunModal() == 1)
            {
                var path = "";
                try {
                    path = dlg.Url.Path;
                    File.WriteAllText(path, KGui.gui.GuiInputGetText(), System.Text.Encoding.Unicode);
                } catch {
                    var alert = new NSAlert()
                    {
                        AlertStyle      = NSAlertStyle.Critical,
                        MessageText     = "Could not write this file:",
                        InformativeText = path
                    };
                    alert.RunModal();
                }
            }
        }
示例#14
0
        partial void RomSaveButton(NSObject sender)
        {
            var savePanel = new NSSavePanel
            {
                Title = "Select Save Location for Corrupted ROM",
                NameFieldStringValue = "CorruptedROM.rom"
            };

            if (savePanel.RunModal() == 1)
            {
                RomSaveField.StringValue = savePanel.Url.Path;
            }


            //NSWindow window = new NSWindow { };
            //savePanel.BeginSheet(window, result =>
            //{
            //    if (result == 1)
            //    {
            //        RomSaveField.StringValue = savePanel.Url.Path;
            //    }
            //    savePanel.EndSheet()
            //});
        }
        public void SaveDocumentAs()
        {
            NSSavePanel saveDlg = new NSSavePanel();
            saveDlg.CanCreateDirectories = true;
            saveDlg.AllowedFileTypes = new string[] { "xml", "PDF" };
            saveDlg.AllowsOtherFileTypes = true;

            if (FileNameOK)
            {
                //openDlg.Sta = FileName;
            }

            int result = saveDlg.RunModal();

            if (result == 1)
            {
                FileNameOK = true;
                FileName = saveDlg.Url.Path;
                SaveSettings();
            }
        }
        public bool SaveAsSubtitlePrompt()
        {
            if (Window.Subtitle.Paragraphs.Count == 0)
            {
                MessageBox.Show(_language.NoSubtitlesFound);
                return true;
            }

            var dlg = new NSSavePanel();
            dlg.AllowedFileTypes = new string[] { GetCurrentSubtitleFormat().Extension.TrimStart('.') };
            dlg.AllowsOtherFileTypes = false;
            if (_subtitleFileName != null)
            {
                dlg.NameFieldStringValue = Path.GetFileNameWithoutExtension(_subtitleFileName);
            }
            dlg.Title = _language.SaveSubtitleAs;
            ;
            if (dlg.RunModal() == Constants.NSOpenPanelOK)
            {
                SaveSubtitle(dlg.Filename);
                return true;
            }
            return false;
        }
		internal static bool RunPanel (SelectFileDialogData data, NSSavePanel panel)
		{
			var dir = string.IsNullOrEmpty (data.CurrentFolder)? null : data.CurrentFolder;
			var file = string.IsNullOrEmpty (data.InitialFileName)? null : data.InitialFileName;
			if (panel is NSOpenPanel) {
				return ((NSOpenPanel)panel).RunModal (dir, file, null) != 0;
			} else {
				//FIXME: deprecated on 10.6, alternatives only on 10.6
				return panel.RunModal (dir, file) != 0;
			}
		}
示例#18
0
        public SparkleEventLog()
            : base()
        {
            using (var a = new NSAutoreleasePool ())
            {
                Title    = "Recent Changes";
                Delegate = new SparkleEventsDelegate ();

                int min_width  = 480;
                int min_height = 640;
                float x    = (float) (NSScreen.MainScreen.Frame.Width * 0.61);
                float y    = (float) (NSScreen.MainScreen.Frame.Height * 0.5 - (min_height * 0.5));

                SetFrame (
                    new RectangleF (
                        new PointF (x, y),
                        new SizeF (min_width, (int) (NSScreen.MainScreen.Frame.Height * 0.85))),
                    true);

                StyleMask = (NSWindowStyle.Closable | NSWindowStyle.Miniaturizable |
                             NSWindowStyle.Titled | NSWindowStyle.Resizable);

                MinSize        = new SizeF (min_width, min_height);
                HasShadow      = true;
                BackingType    = NSBackingStore.Buffered;
                TitlebarHeight = Frame.Height - ContentView.Frame.Height;

                this.web_view = new WebView (new RectangleF (0, 0, 481, 579), "", "") {
                    Frame = new RectangleF (new PointF (0, 0),
                        new SizeF (ContentView.Frame.Width, ContentView.Frame.Height - 39))
                };

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

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

                this.size_label = new NSTextField () {
                    Alignment       = NSTextAlignment.Right,
                    BackgroundColor = NSColor.WindowBackground,
                    Bordered        = false,
                    Editable        = false,
                    Frame           = new RectangleF (
                        new PointF (0, ContentView.Frame.Height - 30),
                        new SizeF (60, 20)),
                    StringValue     = "Size:",
                    Font            = SparkleUI.BoldFont
                };

                this.size_label_value = new NSTextField () {
                    Alignment       = NSTextAlignment.Left,
                    BackgroundColor = NSColor.WindowBackground,
                    Bordered        = false,
                    Editable        = false,
                    Frame           = new RectangleF (
                        new PointF (60, ContentView.Frame.Height - 30),
                        new SizeF (60, 20)),
                    StringValue     = "…",
                    Font            = SparkleUI.Font
                };

                this.history_label = new NSTextField () {
                    Alignment       = NSTextAlignment.Right,
                    BackgroundColor = NSColor.WindowBackground,
                    Bordered        = false,
                    Editable        = false,
                    Frame           = new RectangleF (
                        new PointF (130, ContentView.Frame.Height - 30),
                        new SizeF (60, 20)),
                    StringValue     = "History:",
                    Font            = SparkleUI.BoldFont
                };

                this.history_label_value = new NSTextField () {
                    Alignment       = NSTextAlignment.Left,
                    BackgroundColor = NSColor.WindowBackground,
                    Bordered        = false,
                    Editable        = false,
                    Frame           = new RectangleF (
                        new PointF (190, ContentView.Frame.Height - 30),
                        new SizeF (60, 20)
                    ),
                    StringValue     = "…",
                    Font            = SparkleUI.Font
                };

                this.popup_button = new NSPopUpButton () {
                    Frame = new RectangleF (
                        new PointF (ContentView.Frame.Width - 156 - 12, ContentView.Frame.Height - 33),
                        new SizeF (156, 26)),
                    PullsDown = false
                };

                this.background = new NSBox () {
                    Frame = new RectangleF (
                        new PointF (-1, -1),
                        new SizeF (Frame.Width + 2, this.web_view.Frame.Height + 2)),
                    FillColor = NSColor.White,
                    BorderColor = NSColor.LightGray,
                    BoxType = NSBoxType.NSBoxCustom
                };

                this.progress_indicator = new NSProgressIndicator () {
                    Frame = new RectangleF (
                        new PointF (Frame.Width / 2 - 10, this.web_view.Frame.Height / 2 + 10),
                        new SizeF (20, 20)),
                    Style = NSProgressIndicatorStyle.Spinning
                };

                this.progress_indicator.StartAnimation (this);

                ContentView.AddSubview (this.size_label);
                ContentView.AddSubview (this.size_label_value);
                ContentView.AddSubview (this.history_label);
                ContentView.AddSubview (this.history_label_value);
                ContentView.AddSubview (this.popup_button);
                ContentView.AddSubview (this.progress_indicator);
                ContentView.AddSubview (this.background);
                ContentView.AddSubview (this.hidden_close_button);

                (Delegate as SparkleEventsDelegate).WindowResized += Relayout;
            }

            // Hook up the controller events
            Controller.HideWindowEvent += delegate {
                using (var a = new NSAutoreleasePool ())
                {
                    InvokeOnMainThread (delegate {
                        this.progress_indicator.Hidden = true;
                        PerformClose (this);
                    });
                }
            };

            Controller.ShowWindowEvent += delegate {
                using (var a = new NSAutoreleasePool ())
                {
                    InvokeOnMainThread (delegate {
                        OrderFrontRegardless ();
                    });
                }
            };

            Controller.UpdateChooserEvent += delegate (string [] folders) {
                using (var a = new NSAutoreleasePool ())
                {
                    InvokeOnMainThread (delegate {
                        UpdateChooser (folders);
                    });
                }
            };

            Controller.UpdateChooserEnablementEvent += delegate (bool enabled) {
                using (var a = new NSAutoreleasePool ())
                {
                    InvokeOnMainThread (delegate {
                        this.popup_button.Enabled = enabled;
                    });
                }
            };

            Controller.UpdateContentEvent += delegate (string html) {
                using (var a = new NSAutoreleasePool ())
                {
                    InvokeOnMainThread (delegate {
                        this.progress_indicator.Hidden = true;
                        UpdateContent (html);
                    });
                }
            };

            Controller.ContentLoadingEvent += delegate {
                using (var a = new NSAutoreleasePool ())
                {
                    InvokeOnMainThread (delegate {
                        this.web_view.RemoveFromSuperview ();
                        this.progress_indicator.Hidden = false;

                        this.progress_indicator.StartAnimation (this);
                    });
                }
            };

            Controller.UpdateSizeInfoEvent += delegate (string size, string history_size) {
                using (var a = new NSAutoreleasePool ())
                {
                    InvokeOnMainThread (delegate {
                        this.size_label_value.StringValue    = size;
                        this.history_label_value.StringValue = history_size;
                    });
                }
            };

            Controller.ShowSaveDialogEvent += delegate (string file_name, string target_folder_path) {
                using (var a = new NSAutoreleasePool ())
                {
                    InvokeOnMainThread (() => {
                        // TODO: Make this a sheet
                        NSSavePanel panel = new NSSavePanel () {
                            DirectoryUrl         = new NSUrl (target_folder_path, true),
                            NameFieldStringValue = file_name,
                            ParentWindow         = this,
                            Title                = "Restore from History",
                            PreventsApplicationTerminationWhenModal = false
                        };

                        if ((NSPanelButtonType) panel.RunModal ()== NSPanelButtonType.Ok) {
                            string target_file_path = Path.Combine (panel.DirectoryUrl.RelativePath, panel.NameFieldStringValue);
                            Controller.SaveDialogCompleted (target_file_path);

                        } else {
                            Controller.SaveDialogCancelled ();
                        }
                    });
                }
            };
        }
示例#19
0
		void ShowSaveAs (NSObject sender)
		{
			var dlg = new NSSavePanel ();
			dlg.Title = "Save Text File";

			if (ShowSaveAsSheet) {
				dlg.BeginSheet(mainWindowController.Window,(result) => {
					var alert = new NSAlert () {
						AlertStyle = NSAlertStyle.Critical,
						InformativeText = "We need to save the document here...",
						MessageText = "Save Document",
					};
					alert.RunModal ();
				});
			} else {
				if (dlg.RunModal () == 1) {
					var alert = new NSAlert () {
						AlertStyle = NSAlertStyle.Critical,
						InformativeText = "We need to save the document here...",
						MessageText = "Save Document",
					};
					alert.RunModal ();
				}
			}

		}
示例#20
0
        public SparkleEventLog() : base()
        {
            Title    = "Recent Changes";
            Delegate = new SparkleEventsDelegate();

            int min_width  = 480;
            int min_height = 640;
            int height     = (int)(NSScreen.MainScreen.Frame.Height * 0.85);

            float x = (float)(NSScreen.MainScreen.Frame.Width * 0.61);
            float y = (float)(NSScreen.MainScreen.Frame.Height * 0.5 - (height * 0.5));

            SetFrame(
                new RectangleF(
                    new PointF(x, y),
                    new SizeF(min_width, height)),
                true);

            StyleMask = (NSWindowStyle.Closable | NSWindowStyle.Miniaturizable |
                         NSWindowStyle.Titled | NSWindowStyle.Resizable);

            MinSize        = new SizeF(min_width, min_height);
            HasShadow      = true;
            BackingType    = NSBackingStore.Buffered;
            TitlebarHeight = Frame.Height - ContentView.Frame.Height;
            Level          = NSWindowLevel.Floating;


            this.web_view = new WebView(new RectangleF(0, 0, 481, 579), "", "")
            {
                Frame = new RectangleF(new PointF(0, 0),
                                       new SizeF(ContentView.Frame.Width, ContentView.Frame.Height - 39))
            };

            this.web_view.Preferences.PlugInsEnabled = false;

            this.cover = new NSBox()
            {
                Frame = new RectangleF(
                    new PointF(-1, -1),
                    new SizeF(Frame.Width + 2, this.web_view.Frame.Height + 1)),
                FillColor  = NSColor.White,
                BorderType = NSBorderType.NoBorder,
                BoxType    = NSBoxType.NSBoxCustom
            };

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

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


            this.size_label = new NSTextField()
            {
                Alignment       = NSTextAlignment.Right,
                BackgroundColor = NSColor.WindowBackground,
                Bordered        = false,
                Editable        = false,
                Frame           = new RectangleF(
                    new PointF(0, ContentView.Frame.Height - 31),
                    new SizeF(60, 20)),
                StringValue = "Size:"
            };

            this.size_label_value = new NSTextField()
            {
                Alignment       = NSTextAlignment.Left,
                BackgroundColor = NSColor.WindowBackground,
                Bordered        = false,
                Editable        = false,
                Frame           = new RectangleF(
                    new PointF(60, ContentView.Frame.Height - 27),
                    new SizeF(60, 20)),
                StringValue = "…",
                Font        = NSFont.FromFontName(SparkleUI.FontName + " Bold", NSFont.SystemFontSize)
            };


            this.history_label = new NSTextField()
            {
                Alignment       = NSTextAlignment.Right,
                BackgroundColor = NSColor.WindowBackground,
                Bordered        = false,
                Editable        = false,
                Frame           = new RectangleF(
                    new PointF(130, ContentView.Frame.Height - 31),
                    new SizeF(60, 20)),
                StringValue = "History:"
            };

            this.history_label_value = new NSTextField()
            {
                Alignment       = NSTextAlignment.Left,
                BackgroundColor = NSColor.WindowBackground,
                Bordered        = false,
                Editable        = false,
                Frame           = new RectangleF(
                    new PointF(190, ContentView.Frame.Height - 27),
                    new SizeF(60, 20)
                    ),
                StringValue = "…",
                Font        = NSFont.FromFontName(SparkleUI.FontName + " Bold", NSFont.SystemFontSize)
            };

            this.popup_button = new NSPopUpButton()
            {
                Frame = new RectangleF(
                    new PointF(ContentView.Frame.Width - 156 - 12, ContentView.Frame.Height - 33),
                    new SizeF(156, 26)),
                PullsDown = false
            };

            this.background = new NSBox()
            {
                Frame = new RectangleF(
                    new PointF(-1, -1),
                    new SizeF(Frame.Width + 2, this.web_view.Frame.Height + 2)),
                FillColor   = NSColor.White,
                BorderColor = NSColor.LightGray,
                BoxType     = NSBoxType.NSBoxCustom
            };

            this.progress_indicator = new NSProgressIndicator()
            {
                Frame = new RectangleF(
                    new PointF(Frame.Width / 2 - 10, this.web_view.Frame.Height / 2 + 10),
                    new SizeF(20, 20)),
                Style = NSProgressIndicatorStyle.Spinning
            };

            this.progress_indicator.StartAnimation(this);

            ContentView.AddSubview(this.size_label);
            ContentView.AddSubview(this.size_label_value);
            ContentView.AddSubview(this.history_label);
            ContentView.AddSubview(this.history_label_value);
            ContentView.AddSubview(this.popup_button);
            ContentView.AddSubview(this.progress_indicator);
            ContentView.AddSubview(this.background);
            ContentView.AddSubview(this.hidden_close_button);

            (Delegate as SparkleEventsDelegate).WindowResized += delegate(SizeF new_window_size) {
                Program.Controller.Invoke(() => Relayout(new_window_size));
            };


            // Hook up the controller events
            Controller.HideWindowEvent += delegate {
                Program.Controller.Invoke(() => {
                    this.progress_indicator.Hidden = true;
                    PerformClose(this);
                });
            };

            Controller.ShowWindowEvent += delegate {
                Program.Controller.Invoke(() => OrderFrontRegardless());
            };

            Controller.UpdateChooserEvent += delegate(string [] folders) {
                Program.Controller.Invoke(() => UpdateChooser(folders));
            };

            Controller.UpdateChooserEnablementEvent += delegate(bool enabled) {
                Program.Controller.Invoke(() => { this.popup_button.Enabled = enabled; });
            };

            Controller.UpdateContentEvent += delegate(string html) {
                Program.Controller.Invoke(() => {
                    this.cover.RemoveFromSuperview();
                    this.progress_indicator.Hidden = true;
                    UpdateContent(html);
                });
            };

            Controller.ContentLoadingEvent += delegate {
                Program.Controller.Invoke(() => {
                    this.web_view.RemoveFromSuperview();
                    // FIXME: Hack to hide that the WebView sometimes doesn't disappear
                    ContentView.AddSubview(this.cover);
                    this.progress_indicator.Hidden = false;
                    this.progress_indicator.StartAnimation(this);
                });
            };

            Controller.UpdateSizeInfoEvent += delegate(string size, string history_size) {
                Program.Controller.Invoke(() => {
                    this.size_label_value.StringValue    = size;
                    this.history_label_value.StringValue = history_size;
                });
            };

            Controller.ShowSaveDialogEvent += delegate(string file_name, string target_folder_path) {
                Program.Controller.Invoke(() => {
                    NSSavePanel panel = new NSSavePanel()
                    {
                        DirectoryUrl         = new NSUrl(target_folder_path, true),
                        NameFieldStringValue = file_name,
                        ParentWindow         = this,
                        Title = "Restore from History",
                        PreventsApplicationTerminationWhenModal = false
                    };

                    if ((NSPanelButtonType)panel.RunModal() == NSPanelButtonType.Ok)
                    {
                        string target_file_path = Path.Combine(panel.DirectoryUrl.RelativePath, panel.NameFieldStringValue);
                        Controller.SaveDialogCompleted(target_file_path);
                    }
                    else
                    {
                        Controller.SaveDialogCancelled();
                    }
                });
            };
        }
示例#21
0
        private bool MacOpenFile()
        {
            NSOpenPanel nsOpenPanel = new NSOpenPanel();

            nsOpenPanel.Title = this.Title;
            switch (this.FileChooserAction)
            {
            case FileAction.Open:
                nsOpenPanel.CanChooseFiles       = true;
                nsOpenPanel.CanChooseDirectories = false;
                if (this.AllowedFileTypes != null)
                {
                    nsOpenPanel.AllowedFileTypes = this.AllowedFileTypes;
                    break;
                }
                break;

            case FileAction.Save:
                NSSavePanel savePanel = NSSavePanel.SavePanel;
                savePanel.AllowedFileTypes     = this.AllowedFileTypes;
                savePanel.CanCreateDirectories = true;
                savePanel.DirectoryUrl         = new NSUrl(this.InitialDirectory);
                // ISSUE: reference to a compiler-generated method
                if (savePanel.RunModal() == 1)
                {
                    this.Path = savePanel.Url.Path;
                    savePanel.Dispose();
                    return(true);
                }
                savePanel.Dispose();
                return(false);

            case FileAction.SelectFolder:
                nsOpenPanel.CanChooseDirectories = true;
                nsOpenPanel.CanChooseFiles       = false;
                break;

            case FileAction.SelectFiles:
                nsOpenPanel.CanChooseDirectories = true;
                nsOpenPanel.CanChooseFiles       = true;
                break;
            }
            nsOpenPanel.CanCreateDirectories    = false;
            nsOpenPanel.AllowsMultipleSelection = this.AllowMultipleSelect;
            nsOpenPanel.DirectoryUrl            = new NSUrl(this.InitialDirectory);
            // ISSUE: reference to a compiler-generated method
            if (nsOpenPanel.RunModal() == 1)
            {
                int      length   = nsOpenPanel.Urls.Length;
                string[] strArray = new string[length];
                for (int index = 0; index < length; ++index)
                {
                    strArray[index] = nsOpenPanel.Urls[index].Path.ToString();
                }
                this.Paths = strArray;
                this.Path  = this.Paths[0];
                nsOpenPanel.Dispose();
                return(true);
            }
            nsOpenPanel.Dispose();
            return(false);
        }
示例#22
0
        partial void actionExportPreset(NSObject sender)
        {
            if(tablePresets.SelectedRow < 0)
                return;

            string filePath = string.Empty;
            using(NSSavePanel savePanel = new NSSavePanel())
            {
                savePanel.AllowedFileTypes = new string[1] { "json" };
                savePanel.ReleasedWhenClosed = true;
                savePanel.Title = "Please choose a file path";
                savePanel.Prompt = "Export preset as JSON";

                // Check for cancel
                if(savePanel.RunModal() == 0)
                    return;

                filePath = savePanel.Url.Path;
            }

            var preset = _presets[tablePresets.SelectedRow];
            OnExportPreset(preset.EQPresetId, filePath);
        }
		async Task SaveExportedData ()
		{
			if (syncController?.SyncState != SyncState.Finished)
				return;

			var dialog = new NSSavePanel {
				Title = "Save Exported Rdio Data",
				NameFieldStringValue = syncController.FileName
			};

			var window = Window;
			if (window == null)
				await SaveExportedData (window, dialog.RunModal (), dialog.Url);
			else
				dialog.BeginSheet (window, async result => await SaveExportedData (window, result, dialog.Url));
		}
示例#24
0
        // https://docs.microsoft.com/en-us/xamarin/mac/app-fundamentals/copy-paste


        public /* Interface KGuiControl */ void GuiModelToSBML()
        {
            if (NSThread.IsMain)
            {
                string sbml = "";
                try { sbml = Export.SBML(); }
                catch (Error ex) {
                    var alert = new NSAlert()
                    {
                        AlertStyle      = NSAlertStyle.Critical,
                        MessageText     = "Error",
                        InformativeText = ex.Message
                    };
                    alert.RunModal();
                    return;
                }
                catch (Exception ex) {
                    var alert = new NSAlert()
                    {
                        AlertStyle      = NSAlertStyle.Critical,
                        MessageText     = "Something happened",
                        InformativeText = ex.Message
                    };
                    alert.RunModal();
                    return;
                }

                var dlg = new NSSavePanel();
                dlg.Title            = "Save SBML File";
                dlg.AllowedFileTypes = new string[] { "xml" };
                dlg.Directory        = MacControls.modelsDirectory;
                if (dlg.RunModal() == 1)
                {
                    var path = "";
                    try {
                        path = dlg.Url.Path;
                        File.WriteAllText(path, sbml, System.Text.Encoding.Unicode);
                    } catch {
                        var alert = new NSAlert()
                        {
                            AlertStyle      = NSAlertStyle.Critical,
                            MessageText     = "Could not write this file:",
                            InformativeText = path
                        };
                        alert.RunModal();
                    }
                }
            }
            else
            {
                _ = BeginInvokeOnMainThreadAsync(() => { GuiModelToSBML(); return(ack); }).Result;
            }

            //if (!this.InvokeRequired) {
            //    string sbml = "";
            //    try { sbml = Export.SBML(); }
            //    catch (Error ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK); return;  }
            //    catch (Exception ex) { MessageBox.Show(ex.Message, "Something happened", MessageBoxButtons.OK); return;  }

            //    SaveFileDialog saveFileDialog = new SaveFileDialog();
            //    saveFileDialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
            //    saveFileDialog.InitialDirectory = WinControls.modelsDirectory;
            //    saveFileDialog.FilterIndex = 1;
            //    saveFileDialog.RestoreDirectory = false;
            //    if (saveFileDialog.ShowDialog() == DialogResult.OK) {
            //        try {
            //            File.WriteAllText(saveFileDialog.FileName, sbml, System.Text.Encoding.UTF8); // use UTF8, not Unicode for SBML!
            //        } catch {
            //            MessageBox.Show(saveFileDialog.FileName, "Could not write this file:", MessageBoxButtons.OK);
            //        }
            //    }
            //} else this.Invoke((Action) delegate { GuiModelToSBML(); });
        }
        void LogsDoSave(bool selectedOnly)
        {
            string t = TableLogsController.GetBody (selectedOnly);
            if (t.Trim () != "") {
                //string filename = "AirVPN_" + DateTime.Now.ToString ("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture) + ".txt"; // TOCLEAN
                string filename = Engine.Logs.GetLogSuggestedFileName();

                NSSavePanel panel = new NSSavePanel ();
                panel.NameFieldStringValue = filename;
                panel.CanCreateDirectories = true;
                int result = panel.RunModal ();
                if (result == 1) {
                    Platform.Instance.FileContentsWriteText(panel.Url.Path, t);

                    GuiUtils.MessageBox (Messages.LogsSaveToFileDone);
                }
            }
        }
示例#26
0
        public override WindowResponse Show()
        {
            WindowResponse resp;
            List <string>  filetypes = new List <string>();
            NSUrl          initDir   = null;

            if (Directory.Exists(InitialDirectory))
            {
                initDir = new NSUrl(InitialDirectory);
            }

            switch (DialogType)
            {
            case FileDialogType.OpenFile:
                ofdlg = new NSOpenPanel();
                if (initDir != null)
                {
                    ofdlg.DirectoryUrl = initDir;
                }
                ofdlg.Title                   = Title;
                ofdlg.CanChooseFiles          = true;
                ofdlg.CanChooseDirectories    = false;
                ofdlg.AllowsMultipleSelection = false;
                if (filetypes.Count > 0)
                {
                    foreach (FileTypeFilter arr in FileTypeFilters)
                    {
                        filetypes.AddRange(arr.Filter);
                    }
                    ofdlg.AllowedFileTypes = filetypes.ToArray();
                }

                resp         = CocoaHelper.GetResponse(ofdlg.RunModal());
                SelectedPath = ofdlg.Url.Path;
                return(resp);

            case FileDialogType.SelectFolder:
                ofdlg = new NSOpenPanel();
                if (initDir != null)
                {
                    ofdlg.DirectoryUrl = initDir;
                }
                ofdlg.Title                   = Title;
                ofdlg.CanChooseFiles          = false;
                ofdlg.CanChooseDirectories    = true;
                ofdlg.AllowsMultipleSelection = false;

                resp         = CocoaHelper.GetResponse(ofdlg.RunModal());
                SelectedPath = ofdlg.Url.Path;
                return(resp);

            case FileDialogType.SaveFile:
                sfdlg = new NSSavePanel();
                if (initDir != null)
                {
                    sfdlg.DirectoryUrl = initDir;
                }
                sfdlg.Title = Title;
                sfdlg.CanCreateDirectories = true;

                resp         = CocoaHelper.GetResponse(sfdlg.RunModal());
                SelectedPath = sfdlg.Url.Path;
                return(resp);
            }

            return(WindowResponse.None);
        }
        partial void GenerateButtonAsync(NSObject sender)
        {
            if (FileTypeBox.IndexOfSelectedItem == 0)
            {
                ShowAlert("You must select File Type");
            }
            else
            {
                int fileSize = FileSizeField.IntValue;
                if (fileSize <= 0)
                {
                    ShowAlert("File Size must be bigger than 0");
                }
                else
                {
                    //TODO: Enable floats
                    if (FileSizeField.FloatValue != fileSize)
                    {
                        ShowAlert("Sorry but this version doesn't support decimal numbers. Please enter integer.");
                    }
                    else
                    {
                        switch (FileSizeUnitSegment.SelectedSegment)
                        {
                        case 0:
                            fileSize *= 1000000;
                            break;

                        case 1:
                            fileSize *= 1000;
                            break;
                        }
                        int requiredSize = formats[Convert.ToInt32(FileTypeBox.IndexOfSelectedItem) - 1].GetOffset() + formats[Convert.ToInt32(FileTypeBox.IndexOfSelectedItem) - 1].GetMagicNumbers().Length;
                        if (fileSize < requiredSize)
                        {
                            ShowAlert("For selected File Type you must enter size bigger than " + requiredSize + "b");
                        }
                        else
                        {
                            if (fileSize >= 200000000)
                            {
                                ShowAlert("For good reasons please enter size smaller than 200Mb...");
                            }
                            else
                            {
                                using (var dlg = new NSSavePanel())
                                {
                                    dlg.Title            = "Save File";
                                    dlg.AllowedFileTypes = new string[] { formats[Convert.ToInt32(FileTypeBox.IndexOfSelectedItem) - 1].GetFormatName() };

                                    if (dlg.RunModal() == 1)
                                    {
                                        string path   = dlg.Url.Path;
                                        Format format = formats[Convert.ToInt32(FileTypeBox.IndexOfSelectedItem) - 1];

                                        //TODO: Error handling
                                        Task[] tasks = new Task[2];
                                        tasks[0] = Task.Factory.StartNew(() => SaveFile(path, fileSize, format));
                                        tasks[1] = Task.Factory.StartNew(ShowProgress);
                                        Task.WaitAll(tasks);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
示例#28
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);
            }
        }