private void OnBrowseClicked(object o, EventArgs args)
        {
            FileChooserDialog chooser = new FileChooserDialog(
                Catalog.GetString("Open Location"),
                null,
                FileChooserAction.Open
            );

            chooser.SetCurrentFolder(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
            chooser.AddButton(Stock.Cancel, ResponseType.Cancel);
            chooser.AddButton(Stock.Open, ResponseType.Ok);
            chooser.DefaultResponse = ResponseType.Ok;
            chooser.LocalOnly = false;

            if(chooser.Run() == (int)ResponseType.Ok) {
                address_entry.Entry.Text = chooser.Uri;
            }

            chooser.Destroy();
        }
Esempio n. 2
0
 public void OpenDialog(bool multipleFiles, params FileTypes[] fileTypes)
 {
     fcd = new FileChooserDialog("Choose Files", null, FileChooserAction.Open, ButtonsType.Ok);
     fcd.AddButton("Open", ResponseType.Ok);
     fcd.AddFilter(Utils.FileTypesToGtkFilter(fileTypes));
     fcd.SelectMultiple = true;
     fcd.Run();
 }
        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);
                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.PurchasePrice).Digits(2).WidthChars(10)
                                                   .XAlign(1)
                                                   .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.EquipmentTypeName)
                                                   .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();
                });
            };
        }
Esempio n. 4
0
 public void OpenDialog(params FileTypes[] fileTypes)
 {
     fcd = new FileChooserDialog("Choose Path", null, FileChooserAction.Save, ButtonsType.Ok);
     fcd.AddButton("Save", ResponseType.Ok);
     FileFilter filter = new FileFilter();
     fcd.AddFilter(Utils.FileTypesToGtkFilter(fileTypes));
     fcd.Run();
 }
Esempio n. 5
0
        void ButtonOpenClicked(object sender, EventArgs args)
        {
            FileChooserDialog dialog = new FileChooserDialog("Open", this, FileChooserAction.Open, new object[] { "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept });

            dialog.SetCurrentFolder(Environment.GetFolderPath(Environment.SpecialFolder.Personal));

            if (dialog.Run() == (int)ResponseType.Accept)
            {
                _pipelineOK = false;

                if (_playbin != null)
                {
                    _playbin.SetState(Gst.State.Null);
                }
                else
                {
                    _playbin = ElementFactory.Make("playbin", "playbin");
                }

                _scale.Value = 0;

                if (_playbin == null)
                {
                    Console.WriteLine("Unable to create element 'playbin'");
                }

                _playbin.Bus.EnableSyncMessageEmission();
                _playbin.Bus.AddSignalWatch();

                _playbin.Bus.SyncMessage += delegate(object bus, SyncMessageArgs sargs) {
                    Gst.Message msg = sargs.Message;

                    if (!Gst.Video.Global.IsVideoOverlayPrepareWindowHandleMessage(msg))
                    {
                        return;
                    }

                    Element src = msg.Src as Element;
                    if (src == null)
                    {
                        return;
                    }

                    try {
                        src["force-aspect-ratio"] = true;
                    }
                    catch (PropertyNotFoundException) {}
                    Element overlay = null;
                    if (src is Gst.Bin)
                    {
                        overlay = ((Gst.Bin)src).GetByInterface(VideoOverlayAdapter.GType);
                    }

                    VideoOverlayAdapter adapter = new VideoOverlayAdapter(overlay.Handle);
                    adapter.WindowHandle = _xWindowId;
                    adapter.HandleEvents(true);
                };

                _playbin.Bus.Message += delegate(object bus, MessageArgs margs) {
                    Message message = margs.Message;

                    switch (message.Type)
                    {
                    case Gst.MessageType.Error:
                        GLib.GException err;
                        string          msg;

                        message.ParseError(out err, out msg);
                        Console.WriteLine(String.Format("Error message: {0}", msg));
                        _pipelineOK = false;
                        break;

                    case Gst.MessageType.Eos:
                        Console.WriteLine("EOS");
                        break;
                    }
                };

                switch (System.Environment.OSVersion.Platform)
                {
                case PlatformID.Unix:
                    _playbin["uri"] = "file://" + dialog.Filename;
                    break;

                case PlatformID.Win32NT:
                case PlatformID.Win32S:
                case PlatformID.Win32Windows:
                case PlatformID.WinCE:
                    _playbin["uri"] = "file:///" + dialog.Filename.Replace("\\", "/");
                    break;
                }

                StateChangeReturn sret = _playbin.SetState(Gst.State.Playing);

                if (sret == StateChangeReturn.Async)
                {
                    State state, pending;
                    sret = _playbin.GetState(out state, out pending, Gst.Constants.SECOND * 5L);
                }

                if (sret == StateChangeReturn.Success)
                {
                    Console.WriteLine("State change successful");
                    _pipelineOK = true;
                }
                else
                {
                    Console.WriteLine("State change failed for {0} ({1})\n", dialog.Filename, sret);
                }
            }

            dialog.Destroy();
        }
Esempio n. 6
0
        protected void OnOpenButtonClicked(object sender, EventArgs e)
        {
            // Open a file chooser window
            FileChooserDialog fcd = new FileChooserDialog(
                "Sélection du fichier à dupliquer",
                null, fileChooserAction,
                "Annuler", ResponseType.Cancel,
                "Ouvrir", ResponseType.Accept)
            {
                DefaultResponse = ResponseType.Ok,
                SelectMultiple  = false
            };

            if (fcd.Run() == (int)ResponseType.Accept)
            {
                // If the user want to duplicate a repository...
                if (fileChooserAction.Equals(FileChooserAction.SelectFolder))
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(fcd.Filename);

                    // Set folder values
                    fileFingerprint = "";
                    fullFileName    = directoryInfo.FullName + "/";
                    shortFileName   = directoryInfo.Name;
                    fileSize        = GetRepositorySize(directoryInfo);

                    // Set UI folder information
                    filenameLabel.Text             = SetItalic(shortFileName + "/");
                    filenameInfoLabel.Text         = SetItalic(directoryInfo.FullName + "/");
                    sizeInfoLabel.Text             = SetItalic(GetRepositorySize(directoryInfo) + " octets");
                    parentRepositoryInfoLabel.Text = SetItalic(directoryInfo.Parent + "/");
                    lastAccessDateInfoLabel.Text   = SetItalic(directoryInfo.LastAccessTime.ToString());
                    lastWriteDateInfoLabel.Text    = SetItalic(directoryInfo.LastWriteTime.ToString());
                    fingerprintInfoLabel.Text      = SetItalic("Empreinte MD5 indisponible");
                }
                // ... or a file
                else
                {
                    FileInfo fileInfo = new FileInfo(fcd.Filename);

                    // Set file values
                    fileFingerprint = GetFileFingerprint(fileInfo.FullName);
                    fullFileName    = fileInfo.FullName;
                    shortFileName   = GetFileName(fullFileName);
                    fileSize        = fileInfo.Length;

                    // Set UI file information
                    filenameLabel.Text             = SetItalic(shortFileName);
                    filenameInfoLabel.Text         = SetItalic(fileInfo.FullName);
                    sizeInfoLabel.Text             = SetItalic(fileInfo.Length.ToString() + " octets");
                    parentRepositoryInfoLabel.Text = SetItalic(fileInfo.DirectoryName + "/");
                    lastAccessDateInfoLabel.Text   = SetItalic(fileInfo.LastAccessTime.ToString());
                    lastWriteDateInfoLabel.Text    = SetItalic(fileInfo.LastWriteTime.ToString());
                    fingerprintInfoLabel.Text      = SetItalic(fileFingerprint);
                }

                // Apply tags
                filenameLabel.UseMarkup             = true;
                filenameInfoLabel.UseMarkup         = true;
                sizeInfoLabel.UseMarkup             = true;
                parentRepositoryInfoLabel.UseMarkup = true;
                lastAccessDateInfoLabel.UseMarkup   = true;
                lastWriteDateInfoLabel.UseMarkup    = true;
                fingerprintInfoLabel.UseMarkup      = true;

                // Unsensitive the other frames
                filenameLabel.Sensitive    = true;
                fileFrame.Sensitive        = true;
                duplicationFrame.Sensitive = true;
            }
            fcd.Destroy();
        }
Esempio n. 7
0
        private void HandleInstallerDialog(FileChooserDialog fileChooser)
        {
            if (fileChooser.Run() == (int)ResponseType.Accept)
            {
                MessageDialog dialog = null;

                try
                {
                    string filename = fileChooser.Filename;

                    fileChooser.Dispose();

                    SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);

                    if (firmwareVersion == null)
                    {
                        dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                        dialog.Text = "Firmware not found.";

                        dialog.SecondaryText = $"A valid system firmware was not found in {filename}.";

                        Logger.Error?.Print(LogClass.Application, $"A valid system firmware was not found in {filename}.");

                        dialog.Run();
                        dialog.Hide();
                        dialog.Dispose();

                        return;
                    }

                    SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();

                    string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";

                    if (currentVersion != null)
                    {
                        dialogMessage += $"This will replace the current system version {currentVersion.VersionString}. ";
                    }

                    dialogMessage += "Do you want to continue?";

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, false, "");

                    dialog.Text          = $"Install Firmware {firmwareVersion.VersionString}";
                    dialog.SecondaryText = dialogMessage;

                    int response = dialog.Run();

                    dialog.Dispose();

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, false, "");

                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";

                    dialog.SecondaryText = "Installing firmware...";

                    if (response == (int)ResponseType.Yes)
                    {
                        Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");

                        Thread thread = new Thread(() =>
                        {
                            GLib.Idle.Add(new GLib.IdleHandler(() =>
                            {
                                dialog.Run();
                                return(false);
                            }));

                            try
                            {
                                _contentManager.InstallFirmware(filename);

                                GLib.Idle.Add(new GLib.IdleHandler(() =>
                                {
                                    dialog.Dispose();

                                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";

                                    dialog.SecondaryText = $"System version {firmwareVersion.VersionString} successfully installed.";

                                    Logger.Info?.Print(LogClass.Application, $"System version {firmwareVersion.VersionString} successfully installed.");

                                    dialog.Run();
                                    dialog.Dispose();

                                    return(false);
                                }));
                            }
                            catch (Exception ex)
                            {
                                GLib.Idle.Add(new GLib.IdleHandler(() =>
                                {
                                    dialog.Dispose();

                                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString} Failed.";

                                    dialog.SecondaryText = $"An error occured while installing system version {firmwareVersion.VersionString}." +
                                                           " Please check logs for more info.";

                                    Logger.Error?.Print(LogClass.Application, ex.Message);

                                    dialog.Run();
                                    dialog.Dispose();

                                    return(false);
                                }));
                            }
                            finally
                            {
                                RefreshFirmwareLabel();
                            }
                        });

                        thread.Name = "GUI.FirmwareInstallerThread";
                        thread.Start();
                    }
                    else
                    {
                        dialog.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    if (dialog != null)
                    {
                        dialog.Dispose();
                    }

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                    dialog.Text = "Parsing Firmware Failed.";

                    dialog.SecondaryText = "An error occured while parsing firmware. Please check the logs for more info.";

                    Logger.Error?.Print(LogClass.Application, ex.Message);

                    dialog.Run();
                    dialog.Dispose();
                }
            }
            else
            {
                fileChooser.Dispose();
            }
        }
Esempio n. 8
0
        // This is actually both for "Save As" and saving a file that never
        // been saved before.  Either way, we need to prompt for a filename.
        private bool SaveFileAs(Document document)
        {
            var fcd = new FileChooserDialog(Mono.Unix.Catalog.GetString("Save Image File"),
                                            PintaCore.Chrome.MainWindow,
                                            FileChooserAction.Save,
                                            Gtk.Stock.Cancel,
                                            Gtk.ResponseType.Cancel,
                                            Gtk.Stock.Save, Gtk.ResponseType.Ok);

            fcd.DoOverwriteConfirmation = true;
            fcd.SetCurrentFolder(PintaCore.System.GetDialogDirectory());
            fcd.AlternativeButtonOrder = new int[] { (int)ResponseType.Ok, (int)ResponseType.Cancel };

            bool hasFile = document.HasFile;

            if (hasFile)
            {
                fcd.SetFilename(document.PathAndFileName);
            }

            Dictionary <FileFilter, FormatDescriptor> filetypes = new Dictionary <FileFilter, FormatDescriptor> ();

            // Add all the formats we support to the save dialog
            foreach (var format in PintaCore.System.ImageFormats.Formats)
            {
                if (!format.IsReadOnly())
                {
                    fcd.AddFilter(format.Filter);
                    filetypes.Add(format.Filter, format);

                    // Set the filter to anything we found
                    // We want to ensure that *something* is selected in the filetype
                    fcd.Filter = format.Filter;
                }
            }

            // If we already have a format, set it to the default.
            // If not, default to jpeg
            FormatDescriptor format_desc = null;

            if (hasFile)
            {
                format_desc = PintaCore.System.ImageFormats.GetFormatByFile(document.Filename);
            }

            if (format_desc == null)
            {
                format_desc = PintaCore.System.ImageFormats.GetDefaultSaveFormat();

                // Gtk doesn't like it if we set the file name to an extension that we don't have
                // a filter for, so we change the extension to our default extension.
                if (hasFile)
                {
                    fcd.SetFilename(Path.ChangeExtension(document.PathAndFileName, format_desc.Extensions[0]));
                }
            }

            fcd.Filter = format_desc.Filter;

            fcd.AddNotification("filter", this.OnFilterChanged);

            // Replace GTK's ConfirmOverwrite with our own, for UI consistency
            fcd.ConfirmOverwrite += (eventSender, eventArgs) => {
                if (this.ConfirmOverwrite(fcd, fcd.Filename))
                {
                    eventArgs.RetVal = FileChooserConfirmation.AcceptFilename;
                }
                else
                {
                    eventArgs.RetVal = FileChooserConfirmation.SelectAgain;
                }
            };

            while (fcd.Run() == (int)Gtk.ResponseType.Ok)
            {
                FormatDescriptor format = filetypes[fcd.Filter];
                string           file   = fcd.Filename;

                if (string.IsNullOrEmpty(Path.GetExtension(file)))
                {
                    // No extension; add one from the format descriptor.
                    file            = string.Format("{0}.{1}", file, format.Extensions[0]);
                    fcd.CurrentName = Path.GetFileName(file);

                    // We also need to display an overwrite confirmation message manually,
                    // because MessageDialog won't do this for us in this case.
                    if (File.Exists(file) && !ConfirmOverwrite(fcd, file))
                    {
                        continue;
                    }
                }

                // Always follow the extension rather than the file type drop down
                // ie: if the user chooses to save a "jpeg" as "foo.png", we are going
                // to assume they just didn't update the dropdown and really want png
                var format_type = PintaCore.System.ImageFormats.GetFormatByFile(file);

                if (format_type != null)
                {
                    format = format_type;
                }

                PintaCore.System.LastDialogDirectory = fcd.CurrentFolder;

                // If saving the file failed or was cancelled, let the user select
                // a different file type.
                if (!SaveFile(document, file, format, fcd))
                {
                    continue;
                }

                //The user is saving the Document to a new file, so technically it
                //hasn't been saved to its associated file in this session.
                document.HasBeenSavedInSession = false;

                RecentManager.Default.AddFull(fcd.Uri, PintaCore.System.RecentData);
                PintaCore.System.ImageFormats.SetDefaultFormat(Path.GetExtension(file));

                document.HasFile         = true;
                document.PathAndFileName = file;

                fcd.Destroy();
                return(true);
            }

            fcd.Destroy();
            return(false);
        }
Esempio n. 9
0
    protected void SaveImageFile(Pixbuf src, bool input = true, bool recon = false)
    {
        ImageSaver.Title = input ? "Save target pattern" : (recon ? "Save reconstruction" : "Save phase pattern");

        string directory;

        // Add most recent directory
        if (!string.IsNullOrEmpty(ImageSaver.Filename))
        {
            directory = GetDirectory(ImageSaver.Filename);

            if (Directory.Exists(directory))
            {
                ImageSaver.SetCurrentFolder(directory);
            }
        }

        if (ImageSaver.Run() == (int)ResponseType.Accept)
        {
            if (!string.IsNullOrEmpty(ImageSaver.Filename))
            {
                FileName = ImageSaver.Filename;

                directory = GetDirectory(FileName);

                var ext = ImageSaver.Filter.Name;

                var fmt = ext;

                switch (ext)
                {
                case "jpg":

                    if (!FileName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && !FileName.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase))
                    {
                        FileName = String.Format("{0}.jpg", GetFileName(FileName));
                    }

                    fmt = "jpeg";

                    break;

                case "tif":

                    if (!FileName.EndsWith(".tif", StringComparison.OrdinalIgnoreCase) && !FileName.EndsWith(".tiff", StringComparison.OrdinalIgnoreCase))
                    {
                        FileName = String.Format("{0}.tif", GetFileName(FileName));
                    }

                    fmt = "tiff";

                    break;

                default:

                    FileName = String.Format("{0}.{1}", GetFileName(FileName), ext);

                    break;
                }

                if (src != null)
                {
                    FileName = GetName(FileName);

                    var fullpath = String.Format("{0}/{1}", directory, FileName);

                    try
                    {
                        src.Save(fullpath, fmt);

                        FileName = fullpath;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error saving {0}: {1}", FileName, ex.Message);
                    }
                }
            }
        }

        ImageSaver.Hide();
    }