public Task<string[]> ShowFileDialogAsync(FileDialog dialog, IWindowImpl parent) { var tcs = new TaskCompletionSource<string[]>(); var dlg = new global::Gtk.FileChooserDialog(dialog.Title, ((WindowImpl)parent), dialog is OpenFileDialog ? FileChooserAction.Open : FileChooserAction.Save, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept) { SelectMultiple = (dialog as OpenFileDialog)?.AllowMultiple ?? false, }; foreach (var filter in dialog.Filters) { var ffilter = new FileFilter() { Name = filter.Name + " (" + string.Join(";", filter.Extensions.Select(e => "*." + e)) + ")" }; foreach (var ext in filter.Extensions) ffilter.AddPattern("*." + ext); dlg.AddFilter(ffilter); } dlg.SetFilename(dialog.InitialFileName); dlg.Modal = true; dlg.Response += (_, args) => { if (args.ResponseId == ResponseType.Accept) tcs.TrySetResult(dlg.Filenames); dlg.Hide(); dlg.Dispose(); }; dlg.Close += delegate { tcs.TrySetResult(null); dlg.Dispose(); }; dlg.Show(); return tcs.Task; }
protected void InitializeWindow() { // gxml this.gxml = new Glade.XML(null, "ljarchive.glade", "MainWindow", null); this.gxml.Autoconnect(this); // cc cc = new CommandCollection(gxml, plugins); cc.MenuItem_Activated = this.MenuItem_Activated; cc.ToolButton_Clicked = this.ToolButton_Clicked; cc.CommandState = CommandStates.FileClosed; // TreeView this.tva = new Components.TreeViewAdvanced(); this.tva.Selection.Changed += TreeView_Selection_Changed; this.tva.SearchColumn = 3; this.tva.RulesHint = true; this.tva.Show(); // html this.html = new Components.HTMLAdvanced(); this.html.LoadFromString("Hey! Open a file."); html.Show(); // cmbSearchType this.cmbSearchType.Active = 0; // fcdOpen this.fcdOpen = new FileChooserDialog("Open ljArchive file", MainWindow, FileChooserAction.Open); this.fcdOpen.AddButton(Stock.Open, ResponseType.Accept); this.fcdOpen.AddButton(Stock.Cancel, ResponseType.Cancel); FileFilter ff = new FileFilter(); ff.Name = "ljArchive files"; ff.AddPattern("*.lja"); this.fcdOpen.AddFilter(ff); ff = new FileFilter(); ff.Name = "All files"; ff.AddPattern("*"); this.fcdOpen.AddFilter(ff); // StatusBar this.StatusBar.Push(1, "What up."); // swHTML this.swHTML.Add(html); // swTreeView this.swTreeView.Add(tva); // entriesColumns entriesColumns = new TreeViewColumn[] { new TreeViewColumn(string.Empty, new CellRendererText(), "text", 0), new TreeViewColumn("ID", new CellRendererText(), "text", 1), new TreeViewColumn("Date", new CellRendererText(), "text", 2), new TreeViewColumn("Subject", new CellRendererText(), "text", 3), new TreeViewColumn("Body", new CellRendererText(), "text", 4) }; entriesColumns[0].Sizing = TreeViewColumnSizing.Fixed; entriesColumns[0].FixedWidth = 24; entriesColumns[1].Sizing = TreeViewColumnSizing.Fixed; entriesColumns[1].FixedWidth = 100; entriesColumns[1].Resizable = true; entriesColumns[2].Sizing = TreeViewColumnSizing.Fixed; entriesColumns[2].FixedWidth = 100; entriesColumns[2].Resizable = true; entriesColumns[3].Sizing = TreeViewColumnSizing.Fixed; entriesColumns[3].FixedWidth = 100; entriesColumns[3].Resizable = true; entriesColumns[4].Sizing = TreeViewColumnSizing.Fixed; // commentsColumns commentsColumns = new TreeViewColumn[] { new TreeViewColumn(string.Empty, new CellRendererText(), "text", 0), new TreeViewColumn("ID", new CellRendererText(), "text", 1), new TreeViewColumn("UserName", new CellRendererText(), "text", 2), new TreeViewColumn("Date", new CellRendererText(), "text", 3), new TreeViewColumn("Subject", new CellRendererText(), "text", 4), new TreeViewColumn("Body", new CellRendererText(), "text", 5) }; commentsColumns[0].Sizing = TreeViewColumnSizing.Fixed; commentsColumns[0].FixedWidth = 24; commentsColumns[1].Sizing = TreeViewColumnSizing.Fixed; commentsColumns[1].FixedWidth = 100; commentsColumns[1].Resizable = true; commentsColumns[2].Sizing = TreeViewColumnSizing.Fixed; commentsColumns[2].FixedWidth = 100; commentsColumns[2].Resizable = true; commentsColumns[3].Sizing = TreeViewColumnSizing.Fixed; commentsColumns[3].FixedWidth = 100; commentsColumns[3].Resizable = true; commentsColumns[4].Sizing = TreeViewColumnSizing.Fixed; commentsColumns[4].FixedWidth = 100; commentsColumns[4].Resizable = true; commentsColumns[5].Sizing = TreeViewColumnSizing.Fixed; // TreeViewState this.TreeViewState = TreeViewStates.Hidden; // MainWindow this.MainWindow.DeleteEvent += MainWindow_Delete; this.MainWindow.IconList = new Gdk.Pixbuf[] { new Gdk.Pixbuf(null, "App16x16.xpm"), new Gdk.Pixbuf(null, "App32x32.xpm") }; MainWindow.Show(); }
private void OnProjectMenuNewItem( object sender, EventArgs e) { // We need an open file dialog box and use that to select the project. var dialog = new FileChooserDialog( "Choose Author Intrusion Project", this, FileChooserAction.Save, "Cancel", ResponseType.Cancel, "Save", ResponseType.Accept); // Set up the filter on the dialog. var filter = new FileFilter { Name = "Project Files" }; filter.AddMimeType("binary/x-author-intrusion"); filter.AddPattern("*.aiproj"); dialog.AddFilter(filter); // Show the dialog and process the results. try { // Show the dialog and get the button the user selected. int results = dialog.Run(); // If the user accepted a file, then use that to open the file. if (results != (int)ResponseType.Accept) { return; } // Create a project and (for now) add in every plugin. var project = new Project(); foreach (IPlugin plugin in project.Plugins.PluginManager.Plugins) { project.Plugins.Add(plugin.Key); } // Save the project to the given file. var file = new FileInfo(dialog.Filename); var savePlugin = (FilesystemPersistenceProjectPlugin) project.Plugins["Filesystem Persistence"]; savePlugin.Settings.SetIndividualDirectoryLayout(); savePlugin.Settings.ProjectDirectory = file.Directory.FullName; savePlugin.Save(file.Directory); // Set the project to the new plugin. string newProjectFilename = System.IO.Path.Combine( file.Directory.FullName, "Project.aiproj"); var projectFile = new FileInfo(newProjectFilename); projectManager.OpenProject(projectFile); } finally { // Destroy the dialog the box. dialog.Destroy(); } }
public MainWindow() : base(WindowType.Toplevel) { Build(); MonoGameContentProjectFileFilter = new FileFilter(); MonoGameContentProjectFileFilter.Name = "MonoGame Content Build Projects (*.mgcb)"; MonoGameContentProjectFileFilter.AddPattern("*.mgcb"); XnaContentProjectFileFilter = new FileFilter(); XnaContentProjectFileFilter.Name = "XNA Content Projects (*.contentproj)"; XnaContentProjectFileFilter.AddPattern("*.contentproj"); AllFilesFilter = new FileFilter(); AllFilesFilter.Name = "All Files (*.*)"; AllFilesFilter.AddPattern("*.*"); #if GTK3 Widget[] widgets = Global.UseHeaderBar ? menu2.Children : menubar1.Children; #else Widget[] widgets = menubar1.Children; #endif var column = new TreeViewColumn(); var textCell = new CellRendererText(); var dataCell = new CellRendererText(); dataCell.Visible = false; column.PackStart(textCell, false); column.PackStart(dataCell, false); treeview1.AppendColumn(column); column.AddAttribute(textCell, "markup", 0); column.AddAttribute(dataCell, "text", 1); recentListStore = new TreeStore(typeof(string), typeof(string)); treeview1.Model = recentListStore; foreach (Widget w in widgets) { if (w.Name == "FileAction") { var m = (Menu)((MenuItem)w).Submenu; foreach (Widget w2 in m.Children) { if (w2.Name == "OpenRecentAction") { recentMenu = (MenuItem)w2; break; } } break; } } treerebuild = new MenuItem("Rebuild"); treerebuild.Activated += delegate { projectview1.Rebuild(); }; //This is always returning false, and solves a bug if (projectview1 == null || propertiesview1 == null) { return; } projectview1.Initalize(this, treerebuild, propertiesview1); if (Assembly.GetEntryAssembly().FullName.Contains("Pipeline")) { BuildMenu(); } else { menubar1.Hide(); vbox2.Remove(menubar1); } propertiesview1.Initalize(this); }
private void ConfigureDlg() { ybuttonExport.Clicked += (sender, e) => { var parentWindow = GetParentWindow(this); var folderChooser = new FileChooserDialog("Выберите папку выгрузки", parentWindow, FileChooserAction.SelectFolder, Stock.Cancel, ResponseType.Cancel, Stock.Open, ResponseType.Accept) { DoOverwriteConfirmation = true, }; folderChooser.ShowAll(); if ((ResponseType)folderChooser.Run() == ResponseType.Accept) { if (folderChooser.CurrentFolder == null) { folderChooser.Destroy(); return; } ViewModel.FolderPath = folderChooser.CurrentFolder; var shortpath = folderChooser.CurrentFolder; if (folderChooser.CurrentFolder.Length > 25) { shortpath = "..." + shortpath.Substring(shortpath.Length - 25); } ybuttonExport.Label = shortpath; folderChooser.Destroy(); } else { folderChooser.Destroy(); } }; enummenubuttonExport.ItemsEnum = typeof(ExportType); enummenubuttonExport.EnumItemClicked += (sender, e) => { ViewModel.ExportCommand.Execute(e.ItemEnum); }; enummenubuttonLoadActions.ItemsEnum = typeof(LoadAction); enummenubuttonLoadActions.EnumItemClicked += (sender, e) => { ViewModel.LoadActionCommand.Execute(e.ItemEnum); }; enummenubuttonConfirmUpdate.ItemsEnum = typeof(ConfirmUpdateAction); enummenubuttonConfirmUpdate.EnumItemClicked += (sender, e) => { ViewModel.ConfirmUpdateDataCommand.Execute(e.ItemEnum); }; ycheckDontChangeSellPrice.Binding.AddBinding(ViewModel, vm => vm.DontChangeSellPrice, w => w.Active); ycheckDontChangeSellPrice.Active = true; ycheckDontChangeSellPrice.TooltipText = "При включении у всех заменяемых номенклатур будут удалены все старые цены и будет создана одна новая цена, указанная в файле"; ybuttonConfirmLoadNew.Clicked += (sender, e) => { ViewModel.ConfirmLoadNewCommand.Execute(); }; yfilechooserbuttonImport.Binding.AddBinding(ViewModel, vm => vm.FilePath, w => w.Filename); var fileFilter = new FileFilter(); fileFilter.AddPattern("*.csv"); yfilechooserbuttonImport.Filter = fileFilter; yfilechooserbuttonImport.Title = "Выберите csv файл"; ytreeviewNomenclatures.ColumnsConfig = FluentColumnsConfig <NomenclatureCatalogNode> .Create() .AddColumn("Действие") .MinWidth(120) .AddComboRenderer(x => x.ConflictSolveAction) .SetDisplayFunc(x => x.GetEnumTitle()) .FillItems(((ConflictSolveAction[])Enum.GetValues(typeof(ConflictSolveAction))).ToList()) .AddSetter((c, n) => { c.Editable = n.Source == Source.File && n.Status == NodeStatus.Conflict && n.DuplicateOf != null && ViewModel.CurrentState == LoadAction.LoadNew; switch (ViewModel.CurrentState) { case LoadAction.LoadNew: if (n.DuplicateOf == null || n.Source == Source.Base || !c.Editable) { c.Text = ""; } break; case LoadAction.UpdateData: if (n.ConflictSolveAction != ConflictSolveAction.Ignore) { c.Text = ""; } break; } }) .AddColumn("Источник") .AddEnumRenderer((x) => x.Source) .XAlign(0.5f) .AddColumn("Статус") .AddTextRenderer((x) => x.Status.GetEnumTitle()) .XAlign(0.5f) .AddColumn("ID номенклатуры") .AddTextRenderer(x => x.Id.ToString()) .AddSetter((c, n) => { if (n.Id == null) { c.Text = "Новый"; } }) .XAlign(0.5f) .AddColumn("Наименование") .AddTextRenderer(x => x.Name) .WrapMode(Pango.WrapMode.WordChar) .WrapWidth(400) .AddColumn("ID группы товаров") .AddNumericRenderer(x => x.GroupId) .XAlign(0.5f) .AddColumn("ID поставщика") .AddNumericRenderer(x => x.ShipperCounterpartyId) .XAlign(0.5f) .AddColumn("Цена продажи") .AddNumericRenderer(x => x.SellPrice).Digits(2).WidthChars(10) .XAlign(1) .AddColumn("Единицы измерения") .AddNumericRenderer(x => x.MeasurementUnit) .XAlign(0.5f) .AddColumn("Папка 1С") .HeaderAlignment(0.5f) .AddNumericRenderer(x => x.Folder1cName) .XAlign(0.5f) .AddColumn("Категория") .HeaderAlignment(0.5f) .AddTextRenderer(x => x.NomenclatureCategory) .XAlign(0.5f) .AddColumn("Объем тары") .HeaderAlignment(0.5f) .AddTextRenderer(x => x.TareVolume) .XAlign(0.5f) .AddColumn("Вид оборудования") .AddTextRenderer(x => x.EquipmentKindName) .XAlign(0.5f) .AddColumn("Доступность для продажи") .AddTextRenderer(x => x.SaleCategory) .XAlign(0.5f) .AddColumn("Тип залога") .AddTextRenderer(x => x.TypeOfDepositCategory) .XAlign(0.5f) .AddColumn("Тип топлива") .AddTextRenderer(x => x.FuelTypeName) .XAlign(0.5f) .RowCells() .AddSetter((CellRendererText c, NomenclatureCatalogNode n) => { c.CellBackgroundGdk = GetGdkColor(n.BackgroundColor); c.ForegroundGdk = GetGdkColor(n.ForegroundColor); }) .Finish(); ViewModel.PropertyChanged += (sender, e) => { Application.Invoke((s, args) => { if (e.PropertyName == nameof(ViewModel.ProgressBarValue)) { progressbar.Adjustment.Value = ViewModel.ProgressBarValue; } if (e.PropertyName == nameof(ViewModel.ProgressBarUpper)) { progressbar.Adjustment.Upper = ViewModel.ProgressBarUpper; } if (e.PropertyName == nameof(ViewModel.Items)) { ytreeviewNomenclatures.ItemsDataSource = ViewModel.Items; } if (e.PropertyName == nameof(ViewModel.IsConfirmUpdateDataButtonVisible)) { enummenubuttonConfirmUpdate.Visible = ViewModel.IsConfirmUpdateDataButtonVisible; } if (e.PropertyName == nameof(ViewModel.IsConfirmLoadNewButtonVisible)) { ycheckDontChangeSellPrice.Visible = ViewModel.IsConfirmUpdateDataButtonVisible; } if (e.PropertyName == nameof(ViewModel.IsConfirmLoadNewButtonVisible)) { ybuttonConfirmLoadNew.Visible = ViewModel.IsConfirmLoadNewButtonVisible; } }); }; TextTagTable textTags = new TextTagTable(); var darkredtag = new TextTag("DarkRed"); darkredtag.ForegroundGdk = GetGdkColor(ConsoleColor.DarkRed); textTags.Add(darkredtag); var redtag = new TextTag("red"); redtag.ForegroundGdk = GetGdkColor(ConsoleColor.Red); textTags.Add(redtag); var greentag = new TextTag("Green"); greentag.ForegroundGdk = GetGdkColor(ConsoleColor.Green); textTags.Add(greentag); var darkgreentag = new TextTag("DrakGreen"); darkgreentag.ForegroundGdk = GetGdkColor(ConsoleColor.DarkGreen); textTags.Add(darkgreentag); var blackTag = new TextTag("Black"); blackTag.ForegroundGdk = GetGdkColor(ConsoleColor.Black); textTags.Add(blackTag); var yellowTag = new TextTag("Yellow"); yellowTag.ForegroundGdk = GetGdkColor(ConsoleColor.DarkYellow); textTags.Add(yellowTag); ViewModel.ProgressBarMessagesUpdated += (aList, aIdx) => { Application.Invoke((s, args) => { TextBuffer tempBuffer = new TextBuffer(textTags); foreach (ColoredMessage message in ViewModel.ProgressBarMessages) { TextIter iter = tempBuffer.EndIter; switch (message.Color) { case ConsoleColor.Black: tempBuffer.InsertWithTags(ref iter, "\n" + message.Text, blackTag); break; case ConsoleColor.DarkRed: tempBuffer.InsertWithTags(ref iter, "\n" + message.Text, darkredtag); break; case ConsoleColor.Green: tempBuffer.InsertWithTags(ref iter, "\n" + message.Text, greentag); break; case ConsoleColor.Yellow: tempBuffer.InsertWithTags(ref iter, "\n" + message.Text, yellowTag); break; case ConsoleColor.DarkGreen: tempBuffer.InsertWithTags(ref iter, "\n" + message.Text, darkgreentag); break; case ConsoleColor.Red: tempBuffer.InsertWithTags(ref iter, "\n" + message.Text, redtag); break; default: throw new NotImplementedException("Цвет не настроен"); } } ytextviewProgressStatus.Buffer = tempBuffer; ScrollToEnd(); }); }; ytreeviewNomenclatures.Selection.Changed += (sender, e) => { Application.Invoke((s, args) => { ytextviewNodeMessages.Buffer.Clear(); TextBuffer tempBuffer = new TextBuffer(textTags); var node = ytreeviewNomenclatures.GetSelectedObject <NomenclatureCatalogNode>(); if (node == null) { ytextviewNodeMessages.Buffer.Text = "Выберите запись для просмотра ошибок"; return; } foreach (ColoredMessage message in node.ErrorMessages) { TextIter iter = tempBuffer.EndIter; switch (message.Color) { case ConsoleColor.Black: tempBuffer.InsertWithTags(ref iter, message.Text + "\n", blackTag); break; case ConsoleColor.DarkRed: tempBuffer.InsertWithTags(ref iter, message.Text + "\n", darkredtag); break; case ConsoleColor.Green: tempBuffer.InsertWithTags(ref iter, message.Text + "\n", greentag); break; case ConsoleColor.Yellow: tempBuffer.InsertWithTags(ref iter, message.Text + "\n", yellowTag); break; case ConsoleColor.DarkGreen: tempBuffer.InsertWithTags(ref iter, message.Text + "\n", darkgreentag); break; case ConsoleColor.Red: tempBuffer.InsertWithTags(ref iter, message.Text + "\n", redtag); break; default: throw new NotImplementedException("Цвет не настроен"); } } if (!node.ErrorMessages.Any() && node.Source == Source.File) { TextIter iter = tempBuffer.EndIter; tempBuffer.InsertWithTags(ref iter, "Ошибок нет\n", darkgreentag); } if (node.Source == Source.Base) { TextIter iter = tempBuffer.EndIter; tempBuffer.InsertWithTags(ref iter, "Данные из базы\n", blackTag); } ytextviewNodeMessages.Buffer = tempBuffer; ScrollToEnd(); }); }; }
public Import(Widgets.Window parent) : base("Import CDN Network", parent, FileChooserAction.Open) { AddButton(Gtk.Stock.Cancel, ResponseType.Cancel); AddButton("Import", ResponseType.Ok); LocalOnly = true; SelectMultiple = true; string path = parent.Network.Path; if (path != null) { SetCurrentFolder(System.IO.Path.GetDirectoryName(path)); } FileFilter cdn = new FileFilter(); cdn.AddPattern("*.cdn"); cdn.Name = "CDN Files (*.cdn)"; AddFilter(cdn); FileFilter all = new FileFilter(); all.AddPattern("*"); all.Name = "All Files (*)"; AddFilter(all); Table table = new Table(2, 2, false); table.ColumnSpacing = 6; table.RowSpacing = 3; Label lbl; lbl = new Label("Action:"); lbl.SetAlignment(0f, 0.5f); table.Attach(lbl, 0, 1, 0, 1, AttachOptions.Fill, AttachOptions.Fill, 0, 0); lbl = new Label("Selection:"); lbl.SetAlignment(0f, 0.5f); table.Attach(lbl, 0, 1, 1, 2, AttachOptions.Fill, AttachOptions.Fill, 0, 0); d_comboAction = new ComboBox(new string[] { "Copy objects from file", "Reference objects in file" }); table.Attach(d_comboAction, 1, 2, 0, 1, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Fill, 0, 0); d_comboAction.Changed += HandleActionChanged; d_comboSelection = new ComboBox(new string[] { "All objects", "Only templates" }); table.Attach(d_comboSelection, 1, 2, 1, 2, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Fill, 0, 0); d_comboSelection.Changed += HandleSelectionChanged; table.ShowAll(); ExtraWidget = table; d_comboAction.Active = 0; d_comboSelection.Active = 0; }
protected void onExportPNG(object sender, EventArgs e) { Gtk.Window window = null; Widget toplevel = Toplevel; if (toplevel.IsTopLevel) { window = toplevel as Gtk.Window; } Gtk.FileChooserDialog fileChooser = new Gtk.FileChooserDialog("Save PNG", window, FileChooserAction.Save, "Cancel", ResponseType.Cancel, "Save", ResponseType.Accept); var filter = new FileFilter(); filter.Name = "PNG Image (*.png)"; filter.AddPattern("*.png"); fileChooser.AddFilter(filter); if (fileChooser.Run() == (int)ResponseType.Accept) { if (decompressed != null) { ImageSurface buf; if (Atlas == null) { buf = new ImageSurface( decompressed, Format.Argb32, viewing.Texture.Width, viewing.Texture.Height, viewing.Texture.Width * 4); } else { int top = Atlas.Rect.Top; int left = Atlas.Rect.Left; int right = Atlas.Rect.Right; int bottom = Atlas.Rect.Bottom; unsafe { fixed(byte *dcu = decompressed) { buf = new ImageSurface( (IntPtr)(dcu + (top * viewing.Texture.Width + left) * 4), Format.Argb32, Atlas.Rect.Width, Atlas.Rect.Height, viewing.Texture.Width * 4); } } } var filename = fileChooser.Filename; if (!filename.EndsWith(".png")) { filename = fileChooser.Filename + ".png"; } buf.WriteToPng(filename); buf.Dispose(); } } fileChooser.Destroy(); }
private void SelectOutputFile(Action <string> doWithFile, string filter) { using (FileChooserDialog fc = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Save, "Cancel", ResponseType.Cancel, "Save", ResponseType.Accept)) { FileFilter filterWithExtension = new FileFilter(); { filterWithExtension.Name = filter; filterWithExtension.AddPattern(filter); fc.AddFilter(filterWithExtension); } { FileFilter f = new FileFilter(); f.Name = "All files"; f.AddPattern("*"); fc.AddFilter(f); } while (true) { if (fc.Run() == (int)ResponseType.Accept) { string filename = fc.Filename; if (fc.Filter == filterWithExtension) { string requiredExtension = filter.TrimStart('*'); if (System.IO.Path.GetExtension(filename).ToUpper(CultureInfo.InvariantCulture) != requiredExtension.ToUpper(CultureInfo.InvariantCulture)) { filename += requiredExtension; } } if (File.Exists(filename)) { MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, "File already exists. Overwrite?"); var response = md.Run(); md.Destroy(); if (response != (int)ResponseType.Yes) { continue; } } try { doWithFile(filename); MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, "Open?"); var response = md.Run(); md.Destroy(); if (response == (int)ResponseType.Yes) { try { System.Diagnostics.Process.Start(filename); } catch { } } } catch { MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "An error occurred. Check log messages for details."); md.Run(); md.Destroy(); } } break; } fc.Destroy(); } }
public MainWindowMenuBar() { GardenPlannerSettings settings = GardenPlannerSettings.GetSettings(); FileItem.Submenu = FileMenu; FileMenu.Add(MenuItemNew); FileMenu.Add(MenuItemLoad); FileMenu.Add(MenuItemSave); FileMenu.Add(MenuItemImportFamilies); FileMenu.Add(MenuItemClose); Append(FileItem); MenuItemClose.Activated += CloseAction; MenuItemNew.Activated += NewAction; MenuItemSave.Activated += SaveAction; MenuItemLoad.Activated += LoadAction; MenuItemImportFamilies.Activated += ImportFamiliesAction; SettingsItem.Submenu = SettingsMenu; SettingsMenu.Add(LanguageItem); LanguageItem.Submenu = LanguageMenu; RadioMenuItem group = null; bool init = true; foreach (KeyValuePair <string, Translation> pair in Translation.BuiltIn) { RadioMenuItem radioItem = group == null ? new RadioMenuItem(pair.Key) : new RadioMenuItem(group, pair.Key); group = radioItem; radioItem.Active = settings.Language.Equals(pair.Key); radioItem.Activated += (sender, e) => { if (init)//during program initialization this should not be executed { return; } settings.Language = pair.Key; Translation.GetTranslation(pair.Key); MainWindow.GetInstance().ResetForNewData(); }; LanguageMenu.Append(radioItem); } init = false; ShowAreaImagesItem.Active = settings.ShowAreaImages; ShowAreaImagesItem.Activated += (sender, e) => { settings.ShowAreaImages = ShowAreaImagesItem.Active; GardenDrawingArea.ActiveInstance?.Draw(); }; SettingsMenu.Append(ShowAreaImagesItem); ShowPlantNames.Active = settings.ShowPlantNames; ShowPlantNames.Activated += (sender, e) => { settings.ShowPlantNames = ShowPlantNames.Active; GardenDrawingArea.ActiveInstance?.Draw(); }; SettingsMenu.Append(ShowPlantNames); ShowVarietyNames.Active = settings.ShowVarietyNames; ShowVarietyNames.Activated += (sender, e) => { settings.ShowVarietyNames = ShowVarietyNames.Active; GardenDrawingArea.ActiveInstance?.Draw(); }; SettingsMenu.Append(ShowVarietyNames); Append(SettingsItem); ToolItem.Submenu = ToolMenu; ToolMenu.Add(ToolMenuShowCropRotation); Append(ToolItem); ToolMenuShowCropRotation.Activated += ViewMenuShowCropRotation_Activated; HelpItem.Submenu = HelpMenu; HelpMenu.Add(MenuItemAbout); Append(HelpItem); MenuItemAbout.Activated += ShowAboutDialog; f = new FileFilter(); f.AddPattern("*.gdata"); f.Name = "Garden data"; }
/// <summary> /// Builds up the main Window /// </summary> public CatalogueWindow() : base(Gtk.WindowType.Toplevel) { Build(); statusbar.Push((uint)Context.DEFAULT_CONTEXT, "Welcome to Catalogue " + Utils.GetVersion(true) + " !!"); this.Icon = new Gdk.Pixbuf(Utils.IconPath()); catalogueFilter = new FileFilter(); catalogueFilter.AddPattern("*.catalogue"); catalogueFilter.Name = "Catalogue files"; htmlFilter = new FileFilter(); htmlFilter.AddPattern("*.html"); htmlFilter.AddPattern("*.htm"); htmlFilter.Name = "HTML files"; /* TreeView creation and definition of the sorting algorhithms it'll be using */ tModel = new ListStore(typeof(int), typeof(string), typeof(int), typeof(bool)); /* Sort by ID */ tModel.SetSortFunc((int)Columns.COL_ID, delegate(TreeModel Model, TreeIter a, TreeIter b) { int firstVal = (int)Model.GetValue(a, (int)Columns.COL_ID); int secondVal = (int)Model.GetValue(b, (int)Columns.COL_ID); if (firstVal > secondVal) { return(1); } else if (firstVal < secondVal) { return(-1); } else { return(0); } }); /* Sort by Title */ tModel.SetSortFunc((int)Columns.COL_TITLE, delegate(TreeModel Model, TreeIter a, TreeIter b) { string firstVal = (string)Model.GetValue(a, (int)Columns.COL_TITLE); string secondVal = (string)Model.GetValue(b, (int)Columns.COL_TITLE); return(String.Compare(firstVal, secondVal)); }); /* Sort by Page number */ tModel.SetSortFunc((int)Columns.COL_PAGE, delegate(TreeModel Model, TreeIter a, TreeIter b) { int firstVal = (int)Model.GetValue(a, (int)Columns.COL_PAGE); int secondVal = (int)Model.GetValue(b, (int)Columns.COL_PAGE); if (firstVal > secondVal) { return(1); } else if (firstVal < secondVal) { return(-1); } else { return(0); } }); /* Sort by film status (working films are placed before the non working ones */ tModel.SetSortFunc((int)Columns.COL_WORKS, delegate(TreeModel Model, TreeIter a, TreeIter b) { bool firstVal = (bool)Model.GetValue(a, (int)Columns.COL_WORKS); bool secondVal = (bool)Model.GetValue(b, (int)Columns.COL_WORKS); if ((firstVal == true) && (secondVal == false)) { return(1); } else if ((firstVal == false) && (secondVal == true)) { return(-1); } else { return(0); } }); CellRendererText Render = new CellRendererText() { Editable = false, Ellipsize = Pango.EllipsizeMode.None }; TreeViewColumn ColumnSet; mainTreeView.Model = tModel; /* Create the four columns and connect the Clicked event to the sorting method */ mainTreeView.AppendColumn("ID", Render, "text", (int)Columns.COL_ID); ColumnSet = mainTreeView.GetColumn((int)Columns.COL_ID); ColumnSet.Expand = false; ColumnSet.Clickable = true; ColumnSet.Clicked += delegate(object sender, EventArgs e) { SwitchSortMethod(sender, (int)Columns.COL_ID); }; Render = new CellRendererText() { Editable = true, Ellipsize = Pango.EllipsizeMode.None }; Render.Edited += delegate(object o, EditedArgs args) { TreeIter iter; tModel.GetIterFromString(out iter, args.Path); tModel.SetValue(iter, (int)Columns.COL_TITLE, args.NewText); }; mainTreeView.AppendColumn("Title", Render, "text", (int)Columns.COL_TITLE); ColumnSet = mainTreeView.GetColumn((int)Columns.COL_TITLE); ColumnSet.Expand = true; ColumnSet.Clickable = true; ColumnSet.Clicked += delegate(object sender, EventArgs e) { SwitchSortMethod(sender, (int)Columns.COL_TITLE); }; Render = new CellRendererText() { Editable = true, Ellipsize = Pango.EllipsizeMode.None }; Render.Edited += delegate(object o, EditedArgs args) { TreeIter iter; int newPageNum; try { newPageNum = Int32.Parse(args.NewText); } catch (Exception e) { newPageNum = 0; Utils.PrintDebug("UNMANAGED EXCEPTION", e.Message); } tModel.GetIterFromString(out iter, args.Path); tModel.SetValue(iter, (int)Columns.COL_PAGE, newPageNum); }; mainTreeView.AppendColumn("#Page", Render, "text", (int)Columns.COL_PAGE); ColumnSet = mainTreeView.GetColumn((int)Columns.COL_PAGE); ColumnSet.Expand = false; ColumnSet.Clickable = true; ColumnSet.Clicked += delegate(object sender, EventArgs e) { SwitchSortMethod(sender, (int)Columns.COL_PAGE); }; CellRendererToggle RenderBool = new CellRendererToggle() { Sensitive = true, Activatable = true, }; RenderBool.Toggled += delegate(object o, ToggledArgs args) { TreeIter iter; tModel.GetIterFromString(out iter, args.Path); tModel.SetValue(iter, (int)Columns.COL_WORKS, (bool)!RenderBool.Active); }; mainTreeView.AppendColumn("Works", RenderBool, "active", (int)Columns.COL_WORKS); ColumnSet = mainTreeView.GetColumn((int)Columns.COL_WORKS); ColumnSet.Expand = false; ColumnSet.Clickable = true; ColumnSet.Clicked += delegate(object sender, EventArgs e) { SwitchSortMethod(sender, (int)Columns.COL_WORKS); }; }
protected override void OnActivated() { base.OnActivated(); Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog(MainClass.Languages.Translate("chose_file_open"), MainClass.MainWindow, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept); fc.SetCurrentFolder(MainClass.Workspace.RootDirectory); FileFilter filter = new FileFilter(); filter.Name = "Moscrif file (*.ms,*.mso,*.tab, *.msw)"; filter.AddMimeType("text/moscrif "); filter.AddPattern("*.ms"); filter.AddPattern("*.msw"); filter.AddPattern("*.mso"); filter.AddPattern("*.tab"); fc.AddFilter(filter); filter = new FileFilter(); filter.Name = "Moscrif Workspace (*.msw)"; filter.AddMimeType("text/moscrif "); filter.AddPattern("*.msw"); fc.AddFilter(filter); filter = new FileFilter(); filter.Name = "PNG and JPEG images (*.png,*.jpg)"; filter.AddMimeType("image/png"); filter.AddPattern("*.png"); filter.AddMimeType("image/jpeg"); filter.AddPattern("*.jpg"); fc.AddFilter(filter); filter = new FileFilter(); filter.Name = "Text file (*.txt)"; filter.AddMimeType("text/plain"); filter.AddPattern("*.txt"); fc.AddFilter(filter); filter = new FileFilter(); filter.Name = "Xml file (*.xml)"; filter.AddMimeType("text/xml"); filter.AddPattern("*.txt"); fc.AddFilter(filter); filter = new FileFilter(); filter.Name = "All file "; filter.AddPattern("*.*"); fc.AddFilter(filter); if (!String.IsNullOrEmpty(MainClass.Settings.LastOpenedFileDir)) { fc.SetCurrentFolder(MainClass.Settings.LastOpenedFileDir); } if (fc.Run() == (int)ResponseType.Accept) { MainClass.Settings.LastOpenedFileDir = System.IO.Path.GetDirectoryName(fc.Filename); if (Path.GetExtension(fc.Filename) == ".msp") { MainClass.MainWindow.OpenProject(fc.Filename, true); } else if (Path.GetExtension(fc.Filename) == ".msw") { Workspace.Workspace workspace = Workspace.Workspace.OpenWorkspace(fc.Filename); if (workspace != null) { //CloseActualWorkspace(); MainClass.MainWindow.ReloadWorkspace(workspace, true, true); } } else { MainClass.MainWindow.OpenFile(fc.Filename, true); } MainClass.MainWindow.SaveWorkspace(); } fc.Destroy(); }
// Load protected void OnButton16Pressed(object sender, EventArgs e) { FileChooserDialog openD = new FileChooserDialog("Open My Nes palette present file", this, FileChooserAction.Open, Stock.Cancel, ResponseType.Cancel, Stock.Open, ResponseType.Accept); FileFilter filter = new FileFilter(); filter.Name = "My Nes Palette Present (*.mnpp)"; filter.AddMimeType("mnpp"); filter.AddPattern("*.mnpp"); openD.AddFilter(filter); if (openD.Run() == (int)ResponseType.Accept) { string[] lines = File.ReadAllLines(openD.Filename); if (combobox_paletteOf.Active == 0) { for (int i = 0; i < lines.Length; i++) { string[] pars = lines[i].Split(new char[] { '=' }); switch (pars[0]) { case "Brightness": NTSCPaletteGenerator.brightness = float.Parse(pars[1]); hscale_Brightness.Value = (int)(NTSCPaletteGenerator.brightness * 1000); break; case "Contrast": NTSCPaletteGenerator.contrast = float.Parse(pars[1]); hscale_Contrast.Value = (int)(NTSCPaletteGenerator.contrast * 1000); break; case "Gamma": NTSCPaletteGenerator.gamma = float.Parse(pars[1]); hscale_Gamma.Value = (int)(NTSCPaletteGenerator.gamma * 1000); break; case "Hue": NTSCPaletteGenerator.hue_tweak = float.Parse(pars[1]); hscale_Hue.Value = (int)(NTSCPaletteGenerator.hue_tweak * 1000); break; case "Saturation": NTSCPaletteGenerator.saturation = float.Parse(pars[1]); hscale_Saturation.Value = (int)(NTSCPaletteGenerator.saturation * 1000); break; } } label_Brightness.Text = NTSCPaletteGenerator.brightness.ToString("F3"); label_Contrast.Text = NTSCPaletteGenerator.contrast.ToString("F3"); label_Gamma.Text = NTSCPaletteGenerator.gamma.ToString("F3"); label_Hue.Text = NTSCPaletteGenerator.hue_tweak.ToString("F3"); label_Saturation.Text = NTSCPaletteGenerator.saturation.ToString("F3"); int[] palette = NTSCPaletteGenerator.GeneratePalette(); ShowPalette(palette); } else { for (int i = 0; i < lines.Length; i++) { string[] pars = lines[i].Split(new char[] { '=' }); switch (pars[0]) { case "Brightness": PALBPaletteGenerator.brightness = float.Parse(pars[1]); hscale_Brightness.Value = (int)(PALBPaletteGenerator.brightness * 1000); break; case "Contrast": PALBPaletteGenerator.contrast = float.Parse(pars[1]); hscale_Contrast.Value = (int)(PALBPaletteGenerator.contrast * 1000); break; case "Gamma": PALBPaletteGenerator.gamma = float.Parse(pars[1]); hscale_Gamma.Value = (int)(PALBPaletteGenerator.gamma * 1000); break; case "Hue": PALBPaletteGenerator.hue_tweak = float.Parse(pars[1]); hscale_Hue.Value = (int)(PALBPaletteGenerator.hue_tweak * 1000); break; case "Saturation": PALBPaletteGenerator.saturation = float.Parse(pars[1]); hscale_Saturation.Value = (int)(PALBPaletteGenerator.saturation * 1000); break; } } label_Brightness.Text = PALBPaletteGenerator.brightness.ToString("F3"); label_Contrast.Text = PALBPaletteGenerator.contrast.ToString("F3"); label_Gamma.Text = PALBPaletteGenerator.gamma.ToString("F3"); label_Hue.Text = PALBPaletteGenerator.hue_tweak.ToString("F3"); label_Saturation.Text = PALBPaletteGenerator.saturation.ToString("F3"); int[] palette = PALBPaletteGenerator.GeneratePalette(); ShowPalette(palette); } } openD.Destroy(); }
public AddSuperDomainWizard(Repository repository) { this.repository = repository; this.Title = Mono.Unix.Catalog.GetString("Add Super Domain Wizard"); this.Icon = Gdk.Pixbuf.LoadFromResource("Allors.R1.Development.GtkSharp.Icons.allors.ico"); this.WindowPosition = WindowPosition.CenterOnParent; this.DefaultWidth = 640; this.DefaultHeight = 1; var headerBox = new VBox { Spacing = 10, BorderWidth = 10 }; this.VBox.PackStart(headerBox, false, false, 0); headerBox.PackStart(new HtmlLabel("<span size=\"large\">Welcome to the Allors Add Super Domain Wizard</span>", 0.5f)); headerBox.PackStart(new HtmlLabel("This wizard makes this domain inherit from a new super domain.", 0.5f)); var form = new Form(); this.VBox.PackStart(form); this.fileChooserButton = new FileChooserButton(Mono.Unix.Catalog.GetString("Select a Domain"), 0); this.superDomainErrorMessage = new ErrorMessage(); this.ActionArea.Spacing = 10; this.ActionArea.BorderWidth = 5; this.ActionArea.LayoutStyle = ButtonBoxStyle.End; var buttonCancel = new Button { CanDefault = true, CanFocus = true, UseStock = true, UseUnderline = true, Label = "gtk-cancel" }; this.AddActionWidget(buttonCancel, -6); var buttonOk = new Button { CanDefault = true, CanFocus = true, UseStock = true, UseUnderline = true, Label = "gtk-ok" }; buttonOk.Clicked += this.OnButtonOkClicked; this.ActionArea.PackStart(buttonOk); // Layout form.Attach(this.fileChooserButton, 0, 1, 0, 1, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Fill, 0, 0); form.Attach(this.superDomainErrorMessage, 0, 1, 2, 3, AttachOptions.Fill, AttachOptions.Fill, 0, 0); this.ShowAll(); this.ResetErrorMessages(); var filter = new FileFilter { Name = "Allors repository (*.repository)" }; filter.AddPattern("*.repository"); this.fileChooserButton.AddFilter(filter); }
protected void OnButtonFinishClicked(object sender, EventArgs e) { string saveTo = null; progressFinal.Adjustment.Upper = 2; logger.Info("Пользователь выбирает файл..."); using (FileChooserDialog Chooser = new FileChooserDialog("Выберите куда сохранить изменения...", (Window)MainClass.MainWin.Toplevel, FileChooserAction.Save, "Отмена", ResponseType.Cancel, "Сохранить", ResponseType.Accept)) { Chooser.SetFilename(filePath); Chooser.DoOverwriteConfirmation = true; FileFilter Filter = new FileFilter(); Filter.AddPattern("*.xls"); Filter.AddPattern("*.xlsx"); Filter.Name = "Все поддерживаемые"; Chooser.AddFilter(Filter); Filter = new FileFilter(); Filter.AddPattern("*.xls"); Filter.Name = "Excel 2003"; Chooser.AddFilter(Filter); Filter = new FileFilter(); Filter.AddPattern("*.xlsx"); Filter.Name = "Excel 2007"; Chooser.AddFilter(Filter); if ((ResponseType)Chooser.Run() == ResponseType.Accept) { saveTo = Chooser.Filename; } Chooser.Destroy(); } if (String.IsNullOrEmpty(saveTo)) { return; } progressFinal.Adjustment.Value++; logger.Info("Обновляем таблицы..."); foreach (var row in xlsRows.Where(x => x.ChangePrice)) { var priceCell = row.XlsRow.GetCell(row.ColumnsMap[UpdatingXLSRow.ColumnType.Price]); priceCell.SetCellValue((double)row.NewPrice.Value); } progressFinal.Adjustment.Value++; logger.Info("Записываем фаил..."); try { using (FileStream file = new FileStream(saveTo, FileMode.Create, FileAccess.Write)) { wb.Write(file); } } catch (IOException ex) { if (ex.HResult == -2147024864) { MessageDialogWorks.RunErrorDialog("Указанный файл уже открыт в другом приложении. Оно заблокировало доступ к файлу."); return; } throw ex; } progressFinal.Adjustment.Value++; if (checkOpenAfterSave.Active) { logger.Info("Открываем во внешем приложении..."); System.Diagnostics.Process.Start(saveTo); } logger.Info("Ок"); OnCloseTab(false); }
// depends on gnuplot void OnCreateSVGFileActionActivated(object sender, System.EventArgs e) { if (data.RomLoaded == false) { return; } var table = CurrentTable; if (table == null) { return; } GnuPlot gnuPlot = GnuPlot.GetExistingGnuPlot(table); if (gnuPlot == null) { ErrorMsg("Error creating SVG export", "Need existing gnuplot window. Do a normal plot first."); return; } string filenameSuggested = string.IsNullOrEmpty(table.Title) ? "plot" : table.Title; filenameSuggested += ".svg"; if (svgDirectory == null && data.Rom.Path != null) { svgDirectory = System.IO.Path.GetDirectoryName(data.Rom.Path); } var fc = new Gtk.FileChooserDialog("Export plot as SVG file", this, FileChooserAction.Save, Gtk.Stock.Cancel, ResponseType.Cancel, Gtk.Stock.Save, ResponseType.Accept); try { FileFilter filter = new FileFilter(); filter.Name = "SVG files"; filter.AddPattern("*.svg"); fc.AddFilter(filter); filter = new FileFilter(); filter.Name = "All files"; filter.AddPattern("*"); fc.AddFilter(filter); fc.DoOverwriteConfirmation = true; fc.SetCurrentFolder(svgDirectory); fc.CurrentName = filenameSuggested; if (fc.Run() == (int)ResponseType.Accept) { GnuPlot.CreateSVG(table, fc.Filename); } // remember used dir svgDirectory = System.IO.Path.GetDirectoryName(fc.Filename); } catch (GnuPlotException ex) { ErrorMsg("Error creating SVG file", ex.Message); } catch (System.IO.IOException ex) { ErrorMsg("IO Exception", ex.Message); } catch (Exception ex) { // Access to path denied... ErrorMsg("Error", ex.Message); } finally { // Don't forget to call Destroy() or the FileChooserDialog window won't get closed. if (fc != null) { fc.Destroy(); } } }
private void HandlePintaCoreActionsLayersImportFromFileActivated(object sender, EventArgs e) { Document doc = PintaCore.Workspace.ActiveDocument; PintaCore.Tools.Commit(); using var fcd = new FileChooserNative( Translations.GetString("Open Image File"), PintaCore.Chrome.MainWindow, FileChooserAction.Open, Translations.GetString("Open"), Translations.GetString("Cancel")); fcd.SetCurrentFolder(PintaCore.System.GetDialogDirectory()); // Add image files filter var ff = new FileFilter(); foreach (var format in PintaCore.System.ImageFormats.Formats) { if (!format.IsWriteOnly()) { foreach (var ext in format.Extensions) { ff.AddPattern(string.Format("*.{0}", ext)); } } } ff.Name = Translations.GetString("Image files"); fcd.AddFilter(ff); var response = (ResponseType)fcd.Run(); if (response == ResponseType.Accept) { string file = fcd.Filename; string?directory = Path.GetDirectoryName(file); if (directory is not null) { PintaCore.System.LastDialogDirectory = directory; } // Open the image and add it to the layers UserLayer layer = doc.Layers.AddNewLayer(System.IO.Path.GetFileName(file)); using (var fs = new FileStream(file, FileMode.Open)) using (var bg = new Pixbuf(fs)) using (var g = new Cairo.Context(layer.Surface)) { Gdk.CairoHelper.SetSourcePixbuf(g, bg, 0, 0); g.Paint(); } doc.Layers.SetCurrentUserLayer(layer); AddLayerHistoryItem hist = new AddLayerHistoryItem(Resources.Icons.LayerImport, Translations.GetString("Import From File"), doc.Layers.IndexOf(layer)); doc.History.PushNewItem(hist); doc.Workspace.Invalidate(); } }
void OnExportTableAsCSVActionActivated(object sender, System.EventArgs e) { if (data.RomLoaded == false) { return; } Tables.Denso.Table table = CurrentTable; if (table == null) { return; } if (table is Tables.Denso.Table3D) { ErrorMsg("Error", "Creating CSV for 3D table not implemented yet."); return; } string filenameSuggested = string.IsNullOrEmpty(table.Title) ? "table" : table.Title; filenameSuggested += ".csv"; // TODO another var to remember export dir if (svgDirectory == null && data.Rom.Path != null) { svgDirectory = System.IO.Path.GetDirectoryName(data.Rom.Path); } var fc = new Gtk.FileChooserDialog("Export data as CSV file", this, FileChooserAction.Save, Gtk.Stock.Cancel, ResponseType.Cancel, Gtk.Stock.Save, ResponseType.Accept); try { FileFilter filter = new FileFilter(); filter.Name = "CSV files"; filter.AddPattern("*.csv"); fc.AddFilter(filter); filter = new FileFilter(); filter.Name = "All files"; filter.AddPattern("*"); fc.AddFilter(filter); fc.DoOverwriteConfirmation = true; fc.SetCurrentFolder(svgDirectory); fc.CurrentName = filenameSuggested; if (fc.Run() == (int)ResponseType.Accept) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fc.Filename, false, System.Text.Encoding.UTF8)) { ((Tables.Denso.Table2D)table).WriteCSV(sw); } } // remember used dir svgDirectory = System.IO.Path.GetDirectoryName(fc.Filename); } catch (GnuPlotException ex) { ErrorMsg("Error creating CSV file", ex.Message); } catch (System.IO.IOException ex) { ErrorMsg("IO Exception", ex.Message); } catch (Exception ex) { // Access to path denied... ErrorMsg("Error", ex.Message); } finally { // Don't forget to call Destroy() or the FileChooserDialog window won't get closed. if (fc != null) { fc.Destroy(); } } }
private void ImportProject() { Project project; bool isFake, exists; int res; string fileName; FileFilter filter; NewProjectDialog npd; FileChooserDialog fChooser; Log.Debug("Importing project"); /* Show a file chooser dialog to select the file to import */ fChooser = new FileChooserDialog(Catalog.GetString("Import Project"), mainWindow, FileChooserAction.Open, "gtk-cancel", ResponseType.Cancel, "gtk-open", ResponseType.Accept); fChooser.SetCurrentFolder(Config.HomeDir()); filter = new FileFilter(); filter.Name = Constants.PROJECT_NAME; filter.AddPattern("*.lpr"); fChooser.AddFilter(filter); res = fChooser.Run(); fileName = fChooser.Filename; fChooser.Destroy(); /* return if the user cancelled */ if (res != (int)ResponseType.Accept) { return; } /* try to import the project and show a message error is the file * is not a valid project */ try { project = Project.Import(fileName); } catch (Exception ex) { MessagePopup.PopupMessage(mainWindow, MessageType.Error, Catalog.GetString("Error importing project:") + "\n" + ex.Message); Log.Exception(ex); return; } isFake = (project.Description.File.FilePath == Constants.FAKE_PROJECT); /* If it's a fake live project prompt for a video file and * create a new PreviewMediaFile for this project */ if (isFake) { Log.Debug("Importing fake live project"); project.Description.File = null; npd = new NewProjectDialog(); npd.TransientFor = mainWindow; npd.Use = ProjectType.EditProject; npd.Project = project; int response = npd.Run(); while (true) { if (response != (int)ResponseType.Ok) { npd.Destroy(); return; } else if (npd.Project == null) { MessagePopup.PopupMessage(mainWindow, MessageType.Info, Catalog.GetString("Please, select a video file.")); response = npd.Run(); } else { project = npd.Project; npd.Destroy(); break; } } } /* If the project exists ask if we want to overwrite it */ if (Core.DB.Exists(project)) { MessageDialog md = new MessageDialog(mainWindow, DialogFlags.Modal, MessageType.Question, Gtk.ButtonsType.YesNo, Catalog.GetString("A project already exists for the file:") + project.Description.File.FilePath + "\n" + Catalog.GetString("Do you want to overwrite it?")); md.Icon = Gtk.IconTheme.Default.LoadIcon("longomatch", 48, 0); res = md.Run(); md.Destroy(); if (res != (int)ResponseType.Yes) { return; } exists = true; } else { exists = false; } if (isFake) { CreateThumbnails(project); } if (exists) { Core.DB.UpdateProject(project); } else { Core.DB.AddProject(project); } MessagePopup.PopupMessage(mainWindow, MessageType.Info, Catalog.GetString("Project successfully imported.")); }
public static bool Open(Widget parent) { var file = string.Empty; if (!IsUnix) { using (var openDialog = new OpenFileDialog()) { // check file exists openDialog.CheckFileExists = true; // If the previously browsed directory exists, then direct the user to it, otherwise direct to home directory. openDialog.InitialDirectory = Directory.Exists(Settings.Default.PreviousBrowseFolder) ? Settings.Default.PreviousBrowseFolder : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); // Set the filter to show only 'prf' files openDialog.Filter = "Projects file (*.prj)|*.prj|Lock file (*.prj.lk) |*.prj.lk|All Files (*.*)|*.*"; openDialog.FilterIndex = 1; //RestoreDirectory = true, openDialog.ShowReadOnly = false; openDialog.ShowDialog(); file = openDialog.FileName; openDialog.Reset(); } } else { using (var openDialog = new FileChooserDialog("Open File", parent as Window, FileChooserAction.Open)) { openDialog.AddButton("Open", ResponseType.Ok); openDialog.AddButton("Cancel", ResponseType.Close); SetCurrentFolder(Directory.Exists(Settings.Default.PreviousBrowseFolder) ? Settings.Default.PreviousBrowseFolder : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), openDialog.Handle); using (var openFilter = new FileFilter()) { openFilter.Name = "Projects File"; openFilter.AddMimeType("Projects File"); openFilter.AddPattern("*.prj"); openDialog.AddFilter(openFilter); } using (var openFilter = new FileFilter()) { openFilter.Name = "Projects Lock File"; openFilter.AddMimeType("Projects Lock File"); openFilter.AddPattern("*.prj.lk"); openDialog.AddFilter(openFilter); } using (var openFilter = new FileFilter()) { openFilter.Name = "All files"; openFilter.AddMimeType("All"); openFilter.AddPattern("*.*"); openDialog.AddFilter(openFilter); } if (openDialog.Run() == (int)ResponseType.Ok) { file = openDialog.File.ParsedName; } openDialog.Destroy(); } } // if no file has been provided / the file does not exist - do not continue if (string.IsNullOrEmpty(file) || !File.Exists(file)) { return(false); } //Console.WriteLine(Path.GetExtension(file)); // ensure that the correct file extension is being used if (Path.GetExtension(file) != ".prj") { using (var md = new MessageDialog(parent as Window, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "The selected file is not recognized by Projects.")) { md.Run(); md.Destroy(); } return(false); } // get the path from the selected file, by finding the last occurrence of a directory separator and save it into // the "PreviousBrowseFolder" Setting Settings.Default.PreviousBrowseFolder = file.Substring(0, file.LastIndexOf(Path.DirectorySeparatorChar)); // save settings Settings.Default.Save(); if (File.Exists(file + ".lk")) { using ( var dialog = new MessageDialog(parent as Window, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, $"The file is currently in use. If you're sure that this isn't the case, please delete the following file:\n {file}.lk") ) { dialog.Run(); dialog.Destroy(); } return(false); } var window = new ProjectWindow(file); window.Show(); parent.Destroy(); return(true); }
/// <summary> /// Ask the user for a file name. Used on OSs which are not Windows or MacOS. /// </summary> /// <param name="selectMultiple">Whether or not the user is allowed to select multiple files.</param> /// <returns>Array of files selected by the user.</returns> public string[] GenericFileDialog(bool selectMultiple) { string buttonText = string.Empty; FileChooserAction gtkActionType; if (Action == FileActionType.Open) { buttonText = "Open"; gtkActionType = FileChooserAction.Open; } else if (Action == FileActionType.Save) { buttonText = "Save"; gtkActionType = FileChooserAction.Save; } else if (Action == FileActionType.SelectFolder) { buttonText = "Select Folder"; gtkActionType = FileChooserAction.SelectFolder; } else { throw new Exception("This file chooser dialog has specified more than one action type."); } #if NETFRAMEWORK FileChooserDialog fileChooser = new FileChooserDialog(Prompt, null, gtkActionType, "Cancel", ResponseType.Cancel, buttonText, ResponseType.Accept); #else Window window = (Window)((ViewBase)ViewBase.MasterView).MainWidget; FileChooserNative fileChooser = new FileChooserNative(Prompt, window, gtkActionType, buttonText, "Cancel"); #endif fileChooser.SelectMultiple = selectMultiple; if (!string.IsNullOrEmpty(FileType)) { string[] specParts = FileType.Split(new Char[] { '|' }); for (int i = 0; i < specParts.Length; i += 2) { FileFilter fileFilter = new FileFilter(); fileFilter.Name = specParts[i]; fileFilter.AddPattern(specParts[i + 1]); fileChooser.AddFilter(fileFilter); } } FileFilter allFilter = new FileFilter(); allFilter.AddPattern("*"); allFilter.Name = "All files"; fileChooser.AddFilter(allFilter); fileChooser.SetCurrentFolder(InitialDirectory); string[] fileNames = new string[0]; if (fileChooser.Run() == (int)ResponseType.Accept) { fileNames = fileChooser.Filenames; } #if NETFRAMEWORK fileChooser.Cleanup(); #else fileChooser.Dispose(); #endif return(fileNames); }
protected override void OnActivated() { base.OnActivated(); if (String.IsNullOrEmpty(MainClass.Workspace.FilePath)) { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("workspace_not_exist"), MainClass.Languages.Translate("please_create_workspace"), Gtk.MessageType.Error); md.ShowDialog(); return; } Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog(MainClass.Languages.Translate("save_project_export"), MainClass.MainWindow, FileChooserAction.Save, "Cancel", ResponseType.Cancel, "Save", ResponseType.Accept); if (!String.IsNullOrEmpty(MainClass.Settings.LastOpenedExportDir)) { fc.SetCurrentFolder(MainClass.Settings.LastOpenedExportDir); } FileFilter filter = new FileFilter(); filter.Name = "zip files"; filter.AddMimeType("zip file"); filter.AddPattern("*.zip"); fc.AddFilter(filter); string appname = ""; int typ = -1; Gtk.TreeIter ti = new Gtk.TreeIter(); MainClass.MainWindow.WorkspaceTree.GetSelectedFile(out appname, out typ, out ti); if (String.IsNullOrEmpty(appname)) { return; } Project p = MainClass.Workspace.FindProject_byApp(appname, true); if (p == null) { return; } fc.CurrentName = p.ProjectName + "_" + p.AppFile.Version.Replace(".", "_"); //fc.SetFilename(p.ProjectName); if (fc.Run() != (int)ResponseType.Accept) { fc.Destroy(); return; } string name = fc.Filename; string ext = System.IO.Path.GetExtension(name); if (ext.ToLower() != ".zip") { name = name + ".zip"; } if (p != null) { p.Export(name, true); MainClass.Settings.LastOpenedExportDir = System.IO.Path.GetDirectoryName(fc.Filename); } fc.Destroy(); }
static List <string> MultiFileChooser(Widget parent, string title, string defaultName, string defaultFolder, string filterName, string[] extensions, FileChooserAction action, bool allowMultiple = true) { Window toplevel; FileChooserDialog fChooser; FileFilter filter; string button; List <string> path; if (action == FileChooserAction.Save) { button = "gtk-save"; } else { button = "gtk-open"; } if (parent != null) { toplevel = parent.Toplevel as Window; } else { toplevel = null; } fChooser = new FileChooserDialog(title, toplevel, action, "gtk-cancel", ResponseType.Cancel, button, ResponseType.Accept); fChooser.SelectMultiple = allowMultiple; if (defaultFolder != null) { fChooser.SetCurrentFolder(defaultFolder); } if (defaultName != null) { fChooser.CurrentName = defaultName; } if (filterName != null) { filter = new FileFilter(); filter.Name = filterName; if (extensions != null) { foreach (string p in extensions) { filter.AddPattern(p); } } fChooser.Filter = filter; } if (fChooser.Run() != (int)ResponseType.Accept) { path = new List <string>(); } else { path = new List <string>(fChooser.Filenames); } fChooser.Destroy(); return(path); }
void mnuFile_Open_Clicked(object o, EventArgs args) { FileChooserDialog chooser = new FileChooserDialog("Open", this, FileChooserAction.Open); chooser.LocalOnly = true; chooser.AddButton(Stock.Cancel, ResponseType.Cancel); chooser.AddButton(Stock.Open, ResponseType.Ok); FileFilter brnfilter = new FileFilter(); FileFilter allfilter = new FileFilter(); brnfilter.Name = "Barn files"; brnfilter.AddPattern("*.brn"); allfilter.Name = "All files"; allfilter.AddPattern("*.*"); chooser.AddFilter(brnfilter); chooser.AddFilter(allfilter); int response = chooser.Run(); if ((ResponseType)response == ResponseType.Ok) { try { BarnManager.OpenBarn(chooser.Uri.Replace("file://", "")); List <BarnFile> files = BarnManager.GetFiles(); Console.WriteLine("Starting..."); mainListStore.Clear(); foreach (BarnFile file in files) { mainListStore.AppendValues(file.Index, file.Name, file.InternalSize, BarnManager.MapExtensionToType(file.Extension), file.Barn, file.Compression.ToString()); } Console.WriteLine("There are " + files.Count + " files!"); } catch (System.IO.FileNotFoundException) { displayOkErrorMessageBox("Unable to open " + chooser.Uri + " because it could not be found."); } catch (System.IO.DirectoryNotFoundException) { displayOkErrorMessageBox("Unable to open " + chooser.Uri + " because part of the path could not be found."); } catch (BarnLib.BarnException) { displayOkErrorMessageBox("Unable to open " + chooser.Uri + " because it is not a valid Barn file."); } } chooser.Destroy(); }
public MainWindow2() : base(Gtk.WindowType.Toplevel) { this.Build(); m_app = new App(); m_app.Should += delegate(Act action) { switch (action) { case Act.AnalyzeHorizontal: return(IsHorizontalActive); case Act.AnalyzeVertical: return(IsVerticalActive); case Act.AnalyzeIslands: return(IsIslandsActive); case Act.Analyze: return(true); case Act.Clean: return(IsCleanActive); case Act.RemoveBackground: return(IsRemoveBackgroundActive); case Act.RefreshIslandsOutputAction: return(true); case Act.Process: return(true); } #if DEBUG throw new NotImplementedException(action.ToString()); #else return(false); #endif }; m_app.UpdateInterface += delegate(object sender, UIEventArgs e) { var app = m_app; switch (e.UI) { case UI.Output: textviewOutput.Buffer.Text = app.Output; return; case UI.ErrorMessage: ShowError(app.ErrorMessage); return; case UI.Filename: return; case UI.IslandEditor: islandeditor1.App = m_app; islandeditor1.QueueDraw(); return; case UI.CompletedTask: ShowCompleted(app.Task); return; } #if DEBUG throw new NotImplementedException(e.UI.ToString()); #endif }; comboboxMode.Active = 0; comboboxProcess.Active = 0; islandeditor1.App = m_app; var filter = new FileFilter(); filter.AddPattern("*.png"); filter.AddPattern("*.PNG"); filechooserbuttonOpen.AddFilter(filter); }
protected virtual void OnExporerTreeviewButtonPressEvent(object o, Gtk.ButtonPressEventArgs args) { TreePath path; exporerTreeview.GetPathAtPos((int)args.Event.X, (int)args.Event.Y, out path); if (path != null) { if (args.Event.Button == 3) { Gtk.MenuItem addNewMenuItem = null; if (path.Depth > 1) { int index = path.Indices [1]; if ((index == 2 || index == 1) && path.Depth == 2) { /*TODO 3tk - at the moment user added datafields are disabled * Gtk.Menu jBox = new Gtk.Menu (); * if (index == 1) { * addNewMenuItem = new MenuItem ("add field"); * * } else { * addNewMenuItem = new MenuItem ("add parameter"); * } * jBox.Add (addNewMenuItem); * * addNewMenuItem.Activated += delegate(object sender, EventArgs e) { * PropertyFieldEditor pfe = new PropertyFieldEditor (); * pfe.Response += delegate(object oo, ResponseArgs argss) { * if (argss.ResponseId == ResponseType.Ok) { * if (index == 1){ * //DesignService.Report.Fields.Add (new PropertyDataField (){ Name = pfe.PropertyName}); * updateTreeNode(dataFieldsNode,designService.Report.DataFields); * * }else { * //DesignService.Report.Parameters.Add (new PropertyDataField< (){ Name = pfe.PropertyName, DefaultValue = pfe.DefaultValue }); * updateTreeNode(parametersNode,designService.Report.Parameters); * } * * pfe.Destroy (); * * }else { * pfe.Destroy (); * } * }; * pfe.Show (); * }; * * jBox.ShowAll (); * jBox.Popup (); */ } else if (index == 4 && path.Depth == 2) { Gtk.Menu jBox = new Gtk.Menu(); addNewMenuItem = new MenuItem("add image"); jBox.Add(addNewMenuItem); addNewMenuItem.Activated += delegate(object sender, EventArgs e) { Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog("Choose the Monoreports file to open", null, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept); var fileFilter = new FileFilter { Name = "Images" }; fileFilter.AddPattern("*.jpg"); fileFilter.AddPattern("*.png"); fileFilter.AddPattern("*.gif"); fileFilter.AddPattern("*.JPG"); fileFilter.AddPattern("*.PNG"); fileFilter.AddPattern("*.GIF"); fc.AddFilter(fileFilter); if (fc.Run() == (int)ResponseType.Accept) { System.IO.FileStream file = System.IO.File.OpenRead(fc.Filename); byte[] bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); string fileName = System.IO.Path.GetFileName(fc.Filename); designService.Report.ResourceRepository.Add(fileName, bytes); designService.PixbufRepository.AddOrUpdatePixbufByName(fileName); file.Close(); } fc.Destroy(); updateTreeNode(imagesNode, designService.Report.ResourceRepository); }; jBox.ShowAll(); jBox.Popup(); } } } else if (args.Event.Button == 1) { if (path.Depth == 3) { int index = path.Indices [1]; if (index == 1) { Workspace.ShowInPropertyGrid(designService.Report.DataFields[path.Indices[2]]); } else if (index == 0) { Workspace.ShowInPropertyGrid(designService.Report.Parameters[path.Indices[2]]); } } } } }
public LoadBankTransferDocumentDlg() { this.Build(); _uow = UnitOfWorkFactory.CreateWithoutRoot(); TabName = "Загрузка из банк-клиента"; var txtFilter = new FileFilter(); txtFilter.AddPattern("*.txt"); txtFilter.Name = "Текстовые файлы (*.txt)"; var allFilter = new FileFilter(); allFilter.AddPattern("*"); allFilter.Name = "Все файлы"; filechooser.AddFilter(txtFilter); filechooser.AddFilter(allFilter); labelDescription1.Markup = String.Format("<span background=\"{0}\"> </span> - объект будет создан", NeedToAdd); foreach (var category in _categoryRepository.ExpenseCategories(_uow)) { expenseCategories.AppendValues(category.Name, category); } foreach (var category in _categoryRepository.IncomeCategories(_uow)) { incomeCategories.AppendValues(category.Name, category); } TreeViewColumn checkColumn = new TreeViewColumn(); checkColumn.Title = ""; CellRendererToggle checkCell = new CellRendererToggle(); checkCell.Activatable = true; checkCell.Toggled += CheckCell_Toggled; checkColumn.PackStart(checkCell, true); checkColumn.AddAttribute(checkCell, "active", (int)Columns.CheckCol); TreeViewColumn numberColumn = new TreeViewColumn(); numberColumn.Title = "№"; CellRendererText numberCell = new CellRendererText(); numberCell.Background = EvenRowColor; numberColumn.PackStart(numberCell, true); numberColumn.AddAttribute(numberCell, "text", (int)Columns.NumberCol); TreeViewColumn dateColumn = new TreeViewColumn(); dateColumn.Title = "Дата"; CellRendererText dateCell = new CellRendererText(); dateColumn.PackStart(dateCell, true); dateColumn.AddAttribute(dateCell, "text", (int)Columns.DateCol); TreeViewColumn totalColumn = new TreeViewColumn(); totalColumn.Title = "Сумма"; CellRendererText totalCell = new CellRendererText(); totalCell.Background = EvenRowColor; totalColumn.PackStart(totalCell, true); totalColumn.AddAttribute(totalCell, "text", (int)Columns.TotalCol); TreeViewColumn payerColumn = new TreeViewColumn(); payerColumn.Title = "Плательщик"; CellRendererText payerCell = new CellRendererText(); payerCell.WidthChars = 40; payerColumn.PackStart(payerCell, true); payerColumn.AddAttribute(payerCell, "text", (int)Columns.PayerNameCol); payerColumn.AddAttribute(payerCell, "background", (int)Columns.PayerNameColorCol); payerColumn.Resizable = true; TreeViewColumn payerAccountColumn = new TreeViewColumn(); payerAccountColumn.Title = "Счет плательщика"; CellRendererText payerAccountCell = new CellRendererText(); payerAccountColumn.PackStart(payerAccountCell, true); payerAccountColumn.AddAttribute(payerAccountCell, "text", (int)Columns.PayerAccountCol); payerAccountColumn.AddAttribute(payerAccountCell, "background", (int)Columns.PayerAccountColorCol); payerAccountColumn.Visible = false; TreeViewColumn payerBankColumn = new TreeViewColumn(); payerBankColumn.Title = "Банк плательщика"; CellRendererText payerBankCell = new CellRendererText(); payerBankCell.WidthChars = 40; payerBankColumn.PackStart(payerBankCell, true); payerBankColumn.AddAttribute(payerBankCell, "text", (int)Columns.PayerBankCol); payerBankColumn.AddAttribute(payerBankCell, "background", (int)Columns.PayerBankColorCol); payerBankColumn.Resizable = true; payerBankColumn.Visible = false; TreeViewColumn recipientColumn = new TreeViewColumn(); recipientColumn.Title = "Получатель"; CellRendererText recipientCell = new CellRendererText(); recipientCell.WidthChars = 40; recipientColumn.PackStart(recipientCell, true); recipientColumn.AddAttribute(recipientCell, "text", (int)Columns.RecipientNameCol); recipientColumn.AddAttribute(recipientCell, "background", (int)Columns.RecipientNameColorCol); recipientColumn.Resizable = true; TreeViewColumn recipientAccountColumn = new TreeViewColumn(); recipientAccountColumn.Title = "Счет получателя"; CellRendererText recipientAccountCell = new CellRendererText(); recipientAccountColumn.PackStart(recipientAccountCell, true); recipientAccountColumn.AddAttribute(recipientAccountCell, "text", (int)Columns.RecipientAccountCol); recipientAccountColumn.AddAttribute(recipientAccountCell, "background", (int)Columns.RecipientAccountColorCol); recipientAccountColumn.Visible = false; TreeViewColumn recipientBankColumn = new TreeViewColumn(); recipientBankColumn.Title = "Банк получателя"; CellRendererText recipientBankCell = new CellRendererText(); recipientBankCell.WidthChars = 40; recipientBankColumn.PackStart(recipientBankCell, true); recipientBankColumn.AddAttribute(recipientBankCell, "text", (int)Columns.RecipientBankCol); recipientBankColumn.AddAttribute(recipientBankCell, "background", (int)Columns.RecipientBankColorCol); recipientBankColumn.Resizable = true; recipientBankColumn.Visible = false; TreeViewColumn paymentReasonColumn = new TreeViewColumn(); paymentReasonColumn.Title = "Назначение платежа"; CellRendererText paymentReasonCell = new CellRendererText(); paymentReasonCell.WidthChars = 40; paymentReasonColumn.PackStart(paymentReasonCell, true); paymentReasonColumn.AddAttribute(paymentReasonCell, "text", (int)Columns.PaymentReasonCol); paymentReasonColumn.Resizable = true; TreeViewColumn categoryColumn = new TreeViewColumn(); categoryColumn.Title = "Категория дохода/расхода"; CellRendererCombo categoryCombo = new CellRendererCombo(); categoryCombo.TextColumn = 0; categoryCombo.Editable = true; categoryCombo.HasEntry = false; categoryCombo.Edited += CategoryCombo_Edited; categoryColumn.PackStart(categoryCombo, true); categoryColumn.AddAttribute(categoryCombo, "model", (int)Columns.CategoryComboModel); categoryColumn.AddAttribute(categoryCombo, "text", (int)Columns.CategoryName); treeDocuments.AppendColumn(checkColumn); treeDocuments.AppendColumn(numberColumn); treeDocuments.AppendColumn(dateColumn); treeDocuments.AppendColumn(totalColumn); treeDocuments.AppendColumn(categoryColumn); treeDocuments.AppendColumn(payerColumn); treeDocuments.AppendColumn(payerAccountColumn); treeDocuments.AppendColumn(payerBankColumn); treeDocuments.AppendColumn(recipientColumn); treeDocuments.AppendColumn(recipientAccountColumn); treeDocuments.AppendColumn(recipientBankColumn); treeDocuments.AppendColumn(paymentReasonColumn); treeDocuments.Model = documents; treeDocuments.TooltipColumn = (int)Columns.PaymentReasonCol; buttonUpload.Sensitive = buttonReadFile.Sensitive = false; checkButtonAll.Sensitive = false; }
protected void ReloadData(object sender, EventArgs e) { string result = null; Gtk.FileChooserDialog saveDialog = new Gtk.FileChooserDialog("Load File", null, Gtk.FileChooserAction.Open, "Cancel", Gtk.ResponseType.Cancel, "Load", Gtk.ResponseType.Accept); Gtk.FileFilter fileFilter = new FileFilter(); fileFilter.AddPattern("*.nirs"); fileFilter.Name = ".nirs"; saveDialog.AddFilter(fileFilter); Gtk.FileFilter fileFilter2 = new FileFilter(); fileFilter.AddPattern("*.snirf"); fileFilter.Name = ".snirf"; saveDialog.AddFilter(fileFilter2); if (saveDialog.Run() == (int)Gtk.ResponseType.Accept) { result = saveDialog.Filename; if (nirsdata == null) { nirsdata = new List <nirs.core.Data>(); } nirsdata.Clear(); if (result.Contains(".nirs")) { nirsdata.Add(nirs.io.readDOTnirs(result)); } else if (result.Contains(".snirf")) { nirs.core.Data[] datas = nirs.io.readSNIRF(result); nirsdata.Add(datas[0]); } for (int i = 0; i < nirsdata[0].probe.ChannelMap.Length; i++) { nirsdata[0].probe.ChannelMap[i].datasubtype = string.Format("raw {0}", nirsdata[0].probe.ChannelMap[i].datasubtype); } _handles.dataListStore.AppendValues(result, "Previously recorded file"); Gtk.ListStore ClearList = new Gtk.ListStore(typeof(string)); MainClass.win._handles.whichdata.Model = ClearList; List <string> datatypes = new List <string>(); for (int ii = 0; ii < nirsdata[0].probe.ChannelMap.Length; ii++) { datatypes.Add(nirsdata[0].probe.ChannelMap[ii].datasubtype); } datatypes = datatypes.Distinct().ToList(); foreach (string s in datatypes) { MainClass.win._handles.whichdata.AppendText(s); } MainClass.win._handles.whichdata.Active = 0; combobox_whichdata.Sensitive = true; combobox_selectview.Sensitive = true; checkbutton_autoscaleY.Sensitive = true; checkbutton_timeWindow.Sensitive = true; entry_timeWindow.Sensitive = true; checkbuttonYmax.Sensitive = true; checkbuttonYmin.Sensitive = true; entryYmax.Sensitive = true; entryYmin.Sensitive = true; } saveDialog.Destroy(); drawingarea_SDG.QueueDraw(); drawingarea_Data.QueueDraw(); drawingarea_SDG2.QueueDraw(); drawingarea_Data2.QueueDraw(); }
/// <summary> /// Ask the user for a file name. Used on OSs which are not Windows or MacOS. /// </summary> /// <param name="selectMultiple">Whether or not the user is allowed to select multiple files.</param> /// <returns>Array of files selected by the user.</returns> public string[] GenericFileDialog(bool selectMultiple) { string buttonText = string.Empty; FileChooserAction gtkActionType; if (Action == FileActionType.Open) { buttonText = "Open"; gtkActionType = FileChooserAction.Open; } else if (Action == FileActionType.Save) { buttonText = "Save"; gtkActionType = FileChooserAction.Save; } else if (Action == FileActionType.SelectFolder) { buttonText = "Select Folder"; gtkActionType = FileChooserAction.SelectFolder; } else { throw new Exception("This file chooser dialog has specified more than one action type."); } Window window = (Window)((ViewBase)ViewBase.MasterView).MainWidget; FileChooserNative fileChooser = new FileChooserNative(Prompt, window, gtkActionType, buttonText, "Cancel"); fileChooser.SelectMultiple = selectMultiple; string[] specParts = null; if (!string.IsNullOrEmpty(FileType)) { specParts = FileType.Split(new Char[] { '|' }); for (int i = 0; i < specParts.Length; i += 2) { FileFilter fileFilter = new FileFilter(); fileFilter.Name = specParts[i]; fileFilter.AddPattern(specParts[i + 1]); fileChooser.AddFilter(fileFilter); } } FileFilter allFilter = new FileFilter(); allFilter.AddPattern("*"); allFilter.Name = "All files"; fileChooser.AddFilter(allFilter); fileChooser.SetCurrentFolder(InitialDirectory); fileChooser.DoOverwriteConfirmation = true; bool tryAgain; string[] fileNames; do { fileNames = new string[0]; if (fileChooser.Run() == (int)ResponseType.Accept) { fileNames = fileChooser.Filenames; } // The Gtk FileChooser does NOT automatically append extensions based on the currently selected filter // We need to do this somewhat manually when saving files. // // Note that the following makes the assumption that specified filters have the form "*.ext". // // It is perhaps unclear whether, when the filename does not have the selected filter's extension, // an existing extension should be replaced, or added to. That is, if the selected filter // is "*.apsimx" and the user has provided the name "Wheat.json", should the returned name be // "Wheat.apsimx" or "Wheat.json.apsimx"? I have elected to append, rather than replace. // There is also the question of whether case differences should be considered or not. tryAgain = false; if (ProcessUtilities.CurrentOS.IsWindows && Action == FileActionType.Save && fileChooser.Filter != allFilter && specParts != null) { string filterName = fileChooser.Filter.Name; for (int i = 0; i < specParts.Length; i += 2) { if (filterName == specParts[i]) { string filterExt = Path.GetExtension(specParts[i + 1]); for (int j = 0; j < fileNames.Length; j++) { if (!Path.GetExtension(fileNames[j]).Equals(filterExt, StringComparison.CurrentCultureIgnoreCase)) { fileNames[j] = fileNames[j] + filterExt; if (File.Exists(fileNames[j])) { tryAgain = true; fileChooser.SetFilename(fileChooser.Filename + filterExt); } } } break; // We've applied one extension; let's not risk trying to apply another } } } } while (tryAgain); fileChooser.Dispose(); return(fileNames); }
private void AddButton_Clicked(object sender, EventArgs args) { FileChooserNative fileChooser = new FileChooserNative("Select DLC files", this, FileChooserAction.Open, "Add", "Cancel") { SelectMultiple = true }; FileFilter filter = new FileFilter() { Name = "Switch Game DLCs" }; filter.AddPattern("*.nsp"); fileChooser.AddFilter(filter); if (fileChooser.Run() == (int)ResponseType.Accept) { foreach (string containerPath in fileChooser.Filenames) { if (!File.Exists(containerPath)) { return; } using (FileStream containerFile = File.OpenRead(containerPath)) { PartitionFileSystem pfs = new PartitionFileSystem(containerFile.AsStorage()); bool containsDlc = false; _virtualFileSystem.ImportTickets(pfs); TreeIter?parentIter = null; foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); Nca nca = TryCreateNca(ncaFile.AsStorage(), containerPath); if (nca == null) { continue; } if (nca.Header.ContentType == NcaContentType.PublicData) { if ((nca.Header.TitleId & 0xFFFFFFFFFFFFE000).ToString("x16") != _titleId) { break; } parentIter ??= ((TreeStore)_dlcTreeView.Model).AppendValues(true, "", containerPath); ((TreeStore)_dlcTreeView.Model).AppendValues(parentIter.Value, true, nca.Header.TitleId.ToString("X16"), fileEntry.FullPath); containsDlc = true; } } if (!containsDlc) { GtkDialog.CreateErrorDialog("The specified file does not contain DLC for the selected title!"); } } } } fileChooser.Dispose(); }
public ExcelImportView(ExcelImportViewModel viewModel, IGtkViewResolver viewResolver) : base(viewModel) { Build(); #region Общее notebookSteps.ShowTabs = false; notebookSteps.Binding .AddBinding(viewModel, v => v.CurrentStep, w => w.CurrentPage) .InitializeFromSource(); treeviewRows.EnableGridLines = TreeViewGridLines.Both; treeviewRows.Binding.AddBinding(viewModel.ImportModel, v => v.DisplayRows, w => w.ItemsDataSource); treeviewRows.ButtonReleaseEvent += TreeviewRows_ButtonReleaseEvent; viewModel.ImportModel.PropertyChanged += IImportModel_PropertyChanged; #endregion #region Шаг 1 filechooser.Binding.AddBinding(viewModel, v => v.FileName, w => w.Filename); var Filter = new FileFilter(); Filter.AddPattern("*.xls"); Filter.AddPattern("*.xlsx"); Filter.Name = "Excel"; filechooser.AddFilter(Filter); comboSheets.SetRenderTextFunc <ImportedSheet>(x => x.Title); comboSheets.Binding.AddSource(viewModel) .AddBinding(v => v.Sheets, w => w.ItemsList) .AddBinding(v => v.SelectedSheet, w => w.SelectedItem); buttonLoad.Binding .AddBinding(viewModel, v => v.SensitiveSecondStepButton, w => w.Sensitive) .InitializeFromSource(); #endregion #region Шаг 2 spinTitleRow.Binding .AddBinding(ViewModel.ImportModel, v => v.HeaderRow, w => w.ValueAsInt) .AddBinding(ViewModel, v => v.RowsCount, w => w.Adjustment.Upper) .InitializeFromSource(); buttonReadEmployees.Binding .AddBinding(viewModel, v => v.SensitiveThirdStepButton, w => w.Sensitive) .InitializeFromSource(); labelColumnRecomendations.LabelProp = ViewModel.ImportModel.DataColumnsRecommendations; if (viewModel.ImportModel.MatchSettingsViewModel != null) { var settingsView = viewResolver.Resolve(viewModel.ImportModel.MatchSettingsViewModel); tableMatchSettings.Attach(settingsView, 0, 2, 1, 2); settingsView.Show(); } #endregion #region Шаг 3 var countersView = new CountersView(ViewModel.CountersViewModel); vboxCounters.PackStart(countersView, false, true, 2); countersView.Visible = true; eventboxLegendaNew.ModifyBg(StateType.Normal, ColorUtil.Create(ExcelImportViewModel.ColorOfNew)); eventboxLegendaChanged.ModifyBg(StateType.Normal, ColorUtil.Create(ExcelImportViewModel.ColorOfChanged)); eventboxLegendaNotFound.ModifyBg(StateType.Normal, ColorUtil.Create(ExcelImportViewModel.ColorOfNotFound)); eventboxLegendaError.ModifyBg(StateType.Normal, ColorUtil.Create(ExcelImportViewModel.ColorOfError)); eventboxLegendaSkipRows.ModifyBg(StateType.Normal, ColorUtil.Create(ExcelImportViewModel.ColorOfSkipped)); buttonSave.Binding .AddBinding(ViewModel, v => v.SensitiveSaveButton, w => w.Sensitive) .InitializeFromSource(); ViewModel.ProgressStep = progressTotal; #endregion }