Exemple #1
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            #region Validation

            if (Global.UpdateAvailable == null)
            {
                WhatsNewParagraph.Inlines.Add("Something wrong happened. No update was found.");
                return;
            }

            #endregion

            try
            {
                //Detect if this is portable or installed. Download the proper file.
                IsChocolatey = AppDomain.CurrentDomain.BaseDirectory.EndsWith(@"Chocolatey\lib\screentogif\content\");
                IsInstaller  = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory).Any(x => x.ToLowerInvariant().EndsWith("screentogif.visualelementsmanifest.xml"));

                VersionRun.Text = $"{LocalizationHelper.Get("S.Updater.Version")} {Global.UpdateAvailable.Version}";
                SizeRun.Text    = !UserSettings.All.PortableUpdate ? (Global.UpdateAvailable.InstallerSize > 0 ? Humanizer.BytesToString(Global.UpdateAvailable.InstallerSize) : "") :
                                  (Global.UpdateAvailable.PortableSize > 0 ? Humanizer.BytesToString(Global.UpdateAvailable.PortableSize) : "");
                TypeRun.Text = IsInstaller ? LocalizationHelper.Get("S.Updater.Installer") : LocalizationHelper.Get("S.Updater.Portable");

                //Details.
                if (Global.UpdateAvailable.IsFromGithub)
                {
                    //From Github, the description is available.
                    var splited = Global.UpdateAvailable.Description.Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

                    WhatsNewParagraph.Inlines.Add(splited[0].Replace(" What's new?\r\n\r\n", ""));
                    FixesParagraph.Inlines.Add(splited.Length > 1 ? splited[1].Replace(" Bug fixes:\r\n\r\n", "").Replace(" Fixed:\r\n\r\n", "") : "Aparently nothing.");
                }
                else
                {
                    //If the release detail was obtained by querying Fosshub, no release note is available.
                    MainFlowDocument.Blocks.Remove(WhatsNewParagraphTitle);
                    MainFlowDocument.Blocks.Remove(FixesParagraphTitle);
                    MainFlowDocument.Blocks.Remove(FixesParagraph);

                    var run = new Run();
                    run.SetResourceReference(Run.TextProperty, "S.Updater.Info.NewVersionAvailable");
                    WhatsNewParagraph.Inlines.Add(run);
                }

                DocumentViewer.UpdateLayout();

                //If set to force the download the portable version of the app, check if it was downloaded.
                if (UserSettings.All.PortableUpdate)
                {
                    //If the update was already downloaded.
                    if (File.Exists(Global.UpdateAvailable.PortablePath))
                    {
                        //If it's still downloading, wait for it to finish before displaying "Open".
                        if (Global.UpdateAvailable.IsDownloading)
                        {
                            Global.UpdateAvailable.TaskCompletionSource = new TaskCompletionSource <bool>();
                            await Global.UpdateAvailable.TaskCompletionSource.Task;

                            if (!IsLoaded)
                            {
                                return;
                            }
                        }

                        DownloadButton.SetResourceReference(ExtendedButton.TextProperty, "S.Updater.InstallManually");
                    }

                    return;
                }

                //If set to download automatically, check if the installer was downloaded.
                if (UserSettings.All.InstallUpdates)
                {
                    //If the update was already downloaded.
                    if (File.Exists(Global.UpdateAvailable.InstallerPath))
                    {
                        //If it's still downloading, wait for it to finish before displaying "Install".
                        if (Global.UpdateAvailable.IsDownloading)
                        {
                            Global.UpdateAvailable.TaskCompletionSource = new TaskCompletionSource <bool>();
                            await Global.UpdateAvailable.TaskCompletionSource.Task;

                            if (!IsLoaded)
                            {
                                return;
                            }
                        }

                        DownloadButton.SetResourceReference(ExtendedButton.TextProperty, "S.Updater.Install");

                        //When the update was prompted manually, the user can set the installer to run the app afterwards.
                        if (WasPromptedManually)
                        {
                            RunAfterwardsCheckBox.Visibility = Visibility.Visible;
                            RunAfterwardsCheckBox.IsChecked  = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to load the download details");
                StatusBand.Error(LocalizationHelper.Get("S.Updater.Warning.Show"));
            }
            finally
            {
                Height        = ActualHeight;
                SizeToContent = SizeToContent.Width;
                Width         = ActualWidth;
                SizeToContent = SizeToContent.Manual;

                MaxHeight = double.PositiveInfinity;
                MaxWidth  = double.PositiveInfinity;

                CenterOnScreen();
            }
        }
        private async void Add_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                AddExtension    = true,
                CheckFileExists = true,
                Title           = "Open a Resource Dictionary",
                Filter          = "Resource Dictionay (*.xaml)|*.xaml;"
            };

            var result = ofd.ShowDialog();

            if (!result.HasValue || !result.Value)
            {
                return;
            }

            StatusBand.Info("Validating resource name...");

            #region Validation

            if (!ofd.FileName.Contains("StringResources"))
            {
                Dialog.Ok("Action Denied", "The name of file does not follow a valid pattern.",
                          "Try renaming like (without the []): StringResources.[Language Code].xaml");

                StatusBand.Hide();
                return;
            }

            var subs = ofd.FileName.Substring(ofd.FileName.IndexOf("StringResources"));

            if (Application.Current.Resources.MergedDictionaries.Any(x => x.Source != null && x.Source.OriginalString.Contains(subs)))
            {
                Dialog.Ok("Action Denied", "You can't add a resource with the same name.",
                          "Try renaming like: StringResources.[Language Code].xaml");

                StatusBand.Hide();
                return;
            }

            var pieces = subs.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

            if (pieces.Length != 3)
            {
                Dialog.Ok("Action Denied", "Filename with wrong format.",
                          "Try renaming like: StringResources.[Language Code].xaml");

                StatusBand.Hide();
                return;
            }
            var cultureName = pieces[1];

            string properCulture;
            try
            {
                properCulture = await Task.Factory.StartNew(() => CheckSupportedCulture(cultureName));
            }
            catch (CultureNotFoundException)
            {
                Dialog.Ok("Action Denied", "Unknown Language.",
                          $"The \"{cultureName}\" and its family were not recognized as a valid language codes.");

                StatusBand.Hide();
                return;
            }
            catch (Exception ex)
            {
                Dialog.Ok("Action Denied", "Error checking culture.", ex.Message);

                StatusBand.Hide();
                return;
            }

            if (properCulture != cultureName)
            {
                Dialog.Ok("Action Denied", "Redundant Language Code.",
                          $"The \"{cultureName}\" code is redundant. Try using \'{properCulture}\" instead");

                StatusBand.Hide();
                return;
            }

            #endregion

            StatusBand.Info("Importing resource...");

            var fileName = ofd.FileName;

            try
            {
                await Task.Factory.StartNew(() => LocalizationHelper.ImportStringResource(fileName));
            }
            catch (Exception ex)
            {
                Dialog.Ok("Localization", "Localization - Importing Xaml Resource", ex.Message);

                StatusBand.Hide();
                await Task.Factory.StartNew(() => GC.Collect());

                return;
            }

            var resourceDictionary = Application.Current.Resources.MergedDictionaries.LastOrDefault();

            var imageItem = new ImageListBoxItem
            {
                Tag     = resourceDictionary?.Source.OriginalString ?? "Unknown",
                Content = resourceDictionary?.Source.OriginalString ?? "Unknown",
                Image   = FindResource("Vector.Translate") as Canvas,
                Author  = "Recognized as " + pieces[1]
            };

            StatusBand.Hide();

            ResourceListBox.Items.Add(imageItem);
            ResourceListBox.ScrollIntoView(imageItem);

            CommandManager.InvalidateRequerySuggested();
        }
        private void GetMultipleScreencaps()
        {
            var start  = TimeSpan.FromMilliseconds(SelectionSlider.LowerValue);
            var end    = TimeSpan.FromMilliseconds(SelectionSlider.UpperValue);
            var fps    = FpsIntegerUpDown.Value;
            var count  = CountFrames();
            var folder = Path.Combine(RootFolder, "Import");
            var path   = Path.Combine(folder, $"%0{count.ToString().Length + 1}d.png");

            try
            {
                //Create temporary folder.
                if (Directory.Exists(folder))
                {
                    Directory.Delete(folder, true);
                }

                Directory.CreateDirectory(folder);

                CaptureProgressBar.Maximum = count;
                CaptureProgressBar.Value   = 0;

                var info = new ProcessStartInfo(UserSettings.All.FfmpegLocation)
                {
                    Arguments              = $" -i \"{VideoPath}\" -vsync 2 -progress pipe:1 -vf scale={VideoWidth}:{VideoHeight} -ss {start:hh\\:mm\\:ss\\.fff} -to {end:hh\\:mm\\:ss\\.fff} -hide_banner -c:v png -r {fps} -vframes {count} \"{path}\"",
                    CreateNoWindow         = true,
                    ErrorDialog            = false,
                    UseShellExecute        = false,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true
                };

                _process = new Process();
                _process.OutputDataReceived += (sender, e) =>
                {
                    if (string.IsNullOrEmpty(e.Data))
                    {
                        return;
                    }

                    var parsed = e.Data.Split('=');

                    switch (parsed[0])
                    {
                    case "frame":
                        Dispatcher?.InvokeAsync(() => { CaptureProgressBar.Value = Convert.ToDouble(parsed[1]); });
                        break;

                    case "progress":
                        if (parsed[1] == "end")
                        {
                            GetFiles(folder);
                        }

                        break;
                    }
                };

                _process.ErrorDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        throw new Exception("Error while capturing frames with FFmpeg.")
                              {
                                  HelpLink = $"Command:\n\r{info.Arguments}\n\rResult:\n\r{e.Data}"
                              }
                    }
                    ;
                };

                _process.StartInfo = info;
                _process.Start();
                _process.BeginOutputReadLine();
            }
            catch (Exception e)
            {
                LogWriter.Log(e, "Error importing frames with FFmpeg");
                ClearImportFolder(folder);

                StatusBand.Error(LocalizationHelper.Get("S.ImportVideo.Error") + Environment.NewLine + e.Message + Environment.NewLine + e.HelpLink);
            }
        }
Exemple #4
0
        private async void DownloadButton_Click(object sender, RoutedEventArgs e)
        {
            StatusBand.Hide();

            if (EncodingManager.Encodings.Any(a => a.Status == Status.Processing))
            {
                StatusBand.Warning(LocalizationHelper.Get("S.Updater.Warning.Encoding"));
                return;
            }

            DownloadButton.IsEnabled = false;
            StatusBand.Info(LocalizationHelper.Get("S.Updater.Downloading"));

            //If it's still downloading, wait for it to finish.
            if (Global.UpdateAvailable.IsDownloading)
            {
                Global.UpdateAvailable.TaskCompletionSource = new TaskCompletionSource <bool>();
                await Global.UpdateAvailable.TaskCompletionSource.Task;

                if (!IsLoaded)
                {
                    return;
                }
            }

            //If update already downloaded, simply close this window. The installation will happen afterwards.
            if (File.Exists(Global.UpdateAvailable.ActivePath))
            {
                GC.Collect();
                DialogResult = true;
                return;
            }

            //When the update was not queried from Github, the download must be done by browser.
            if (!Global.UpdateAvailable.IsFromGithub)
            {
                try
                {
                    Process.Start(Global.UpdateAvailable.ActiveDownloadUrl);
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Impossible to open the browser to download the update.", Global.UpdateAvailable?.ActiveDownloadUrl);
                }

                GC.Collect();
                DialogResult = true;
                return;
            }

            DownloadProgressBar.Visibility   = Visibility.Visible;
            RunAfterwardsCheckBox.Visibility = Visibility.Collapsed;

            var result = await Task.Run(async() => await App.MainViewModel.DownloadUpdate());

            //If cancelled.
            if (!IsLoaded)
            {
                return;
            }

            if (!result)
            {
                DownloadButton.IsEnabled       = true;
                DownloadProgressBar.Visibility = Visibility.Hidden;
                StatusBand.Error(LocalizationHelper.Get("S.Updater.Warning.Download"));
                return;
            }

            //If the update was downloaded successfully, close this window to run.
            if (File.Exists(Global.UpdateAvailable.ActivePath))
            {
                GC.Collect();
                StatusBand.Hide();
                DialogResult = true;
                return;
            }

            StatusBand.Error(LocalizationHelper.Get("S.Updater.Warning.Download"));
        }
        private async Task LoadPreview()
        {
            StatusBand.Hide();

            //Disable the UI when loading.
            Cursor = Cursors.AppStarting;
            ImporterComboBox.IsEnabled = false;
            DetailsGrid.IsEnabled      = false;
            SelectionSlider.IsEnabled  = false;
            OkButton.IsEnabled         = false;
            PreviewerGrid.Opacity      = 0;
            LoadingLabel.Visibility    = Visibility.Visible;
            DetailsGrid.Visibility     = Visibility.Collapsed;

            LowerSelectionImage.Source = null;
            UpperSelectionImage.Source = null;
            VideoWidth      = 0;
            VideoHeight     = 0;
            Duration        = TimeSpan.Zero;
            _previewerReady = 0;

            //If trying to use FFmpeg, check if it's possible.
            if (UserSettings.All.VideoImporter == 1)
            {
                if (!Util.Other.IsFfmpegPresent())
                {
                    StatusBand.Warning(LocalizationHelper.Get("Editor.Warning.Ffmpeg"), null, () => App.MainViewModel.OpenOptions.Execute(Options.ExtrasIndex));
                    FaultLoading();
                    return;
                }
            }

            var log = "";

            try
            {
                if (UserSettings.All.VideoImporter == 0)
                {
                    log += "Video path: " + VideoPath;

                    //Unregister all events.
                    _upperPlayer.MediaOpened -= MediaPlayer_MediaOpened;
                    _upperPlayer.MediaFailed -= MediaPlayer_MediaFailed;
                    _lowerPlayer.MediaOpened -= MediaPlayer_MediaOpened;
                    _lowerPlayer.MediaFailed -= MediaPlayer_MediaFailed;

                    if (_wasPreviewChangedRegistered)
                    {
                        _lowerPlayer.Changed        -= LowerPlayer_Changed;
                        _upperPlayer.Changed        -= UpperPlayer_Changed;
                        _wasPreviewChangedRegistered = false;
                    }

                    if (_wasCaptureChangedRegistered)
                    {
                        _lowerPlayer.Changed        -= CapturePlayer_Changed;
                        _wasCaptureChangedRegistered = false;
                    }

                    var previous = _upperPlayer.Source?.AbsoluteUri;

                    _upperPlayer.MediaOpened += MediaPlayer_MediaOpened;
                    _upperPlayer.MediaFailed += MediaPlayer_MediaFailed;
                    _lowerPlayer.MediaOpened += MediaPlayer_MediaOpened;
                    _lowerPlayer.MediaFailed += MediaPlayer_MediaFailed;

                    if (!string.IsNullOrWhiteSpace(previous) && previous == new Uri(VideoPath).AbsoluteUri)
                    {
                        //Same video as before.
                        _previewerReady = 2;
                        await WhenBothLoaded();
                    }
                    else
                    {
                        //Open the same video file in both players.
                        _upperPlayer.Open(new Uri(VideoPath));
                        _upperPlayer.Pause();
                        _lowerPlayer.Open(new Uri(VideoPath));
                        _lowerPlayer.Pause();
                    }
                }
                else
                {
                    await GetVideoDetails();
                    await SucessLoading();
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to load the previewers", log);

                FaultLoading(ex);
            }
        }
        private async Task RenderPreview(bool lower = true)
        {
            try
            {
                StatusBand.Hide();

                var drawingVisual = new DrawingVisual();

                if (lower)
                {
                    using (var dc = drawingVisual.RenderOpen())
                    {
                        if (UserSettings.All.VideoImporter == 0)
                        {
                            dc.DrawVideo(_lowerPlayer, new Rect(0, 0, _lowerPlayer.NaturalVideoWidth, _lowerPlayer.NaturalVideoHeight));
                        }
                        else
                        {
                            //Capture image from FFmpeg.
                            var image = await GetScreencap();

                            //Render image in target.
                            if (image != null)
                            {
                                dc.DrawImage(image, new Rect(0, 0, VideoWidth, VideoHeight));
                            }
                        }
                    }

                    lock (_lock)
                        _lowerRenderTargetBitmap.Render(drawingVisual);
                    return;
                }

                using (var dc = drawingVisual.RenderOpen())
                {
                    if (UserSettings.All.VideoImporter == 0)
                    {
                        dc.DrawVideo(_upperPlayer, new Rect(0, 0, _upperPlayer.NaturalVideoWidth, _upperPlayer.NaturalVideoHeight));
                    }
                    else
                    {
                        //Capture image from FFmpeg.
                        var image = await GetScreencap(false);

                        //Render image in target.
                        if (image != null)
                        {
                            dc.DrawImage(image, new Rect(0, 0, VideoWidth, VideoHeight));
                        }
                    }
                }

                lock (_lock)
                    _upperRenderTargetBitmap.Render(drawingVisual);
            }
            catch (TimeoutException t)
            {
                LogWriter.Log(t, "Impossible to get the preview of the video.");
                StatusBand.Warning(LocalizationHelper.Get("S.ImportVideo.Timeout"));
            }
            catch (Exception e)
            {
                LogWriter.Log(e, "Impossible to get the preview of the video.");
                StatusBand.Error(LocalizationHelper.Get("S.ImportVideo.Error"));
            }
        }
        private void SendButton_Click(object sender, RoutedEventArgs e)
        {
            StatusBand.Hide();

            #region Validation

            if (TitleTextBox.Text.Length == 0)
            {
                StatusBand.Warning(FindResource("S.Feedback.Warning.Title") as string);
                TitleTextBox.Focus();
                return;
            }

            if (MessageTextBox.Text.Length == 0)
            {
                StatusBand.Warning(FindResource("S.Feedback.Warning.Message") as string);
                MessageTextBox.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(Secret.Password))
            {
                Dialog.Ok("Feedback", "You are probably running from the source code", "Please, don't try to log into the account of the e-mail sender. " +
                          "Everytime someone does that, the e-mail gets locked and this feature (the feedback) stops working.", Dialog.Icons.Warning);
                return;
            }

            #endregion

            #region UI

            StatusBand.Info(FindResource("S.Feedback.Sending").ToString());

            Cursor             = Cursors.AppStarting;
            MainGrid.IsEnabled = false;
            MainGrid.UpdateLayout();

            #endregion

            //Please, don't try to log with this e-mail and password. :/
            //Everytime someone does this, I have to change the password and the Feedback feature stops working until I update the app.
            var passList = Secret.Password.Split('|');

            var smtp = new SmtpClient
            {
                Timeout               = 5 * 60 * 1000, //Minutes, seconds, miliseconds
                Port                  = Secret.Port,
                Host                  = Secret.Host,
                EnableSsl             = true,
                UseDefaultCredentials = true,
                Credentials           = new NetworkCredential(Secret.Email, passList[_current])
            };

            //Please, don't try to log with this e-mail and password. :/
            //Everytime someone does this, I have to change the password and the Feedback feature stops working until I update the app.
            var mail = new MailMessage
            {
                From       = new MailAddress("*****@*****.**"),
                Subject    = "ScreenToGif - Feedback",
                IsBodyHtml = true
            };

            mail.To.Add("*****@*****.**");

            #region Text

            var sb = new StringBuilder();
            sb.Append("<html xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\">");
            sb.Append("<head><meta content=\"en-us\" http-equiv=\"Content-Language\" />" +
                      "<meta content=\"text/html; charset=utf-16\" http-equiv=\"Content-Type\" />" +
                      "<title>Screen To Gif - Feedback</title>" +
                      "</head>");

            sb.AppendFormat("<style>{0}</style>", Util.Other.GetTextResource("ScreenToGif.Resources.Style.css"));

            sb.Append("<body>");
            sb.AppendFormat("<h1>{0}</h1>", TitleTextBox.Text);
            sb.Append("<div id=\"content\"><div>");
            sb.Append("<h2>Overview</h2>");
            sb.Append("<div id=\"overview\"><table><tr>");
            sb.Append("<th _locid=\"UserTableHeader\">User</th>");

            if (MailTextBox.Text.Length > 0)
            {
                sb.Append("<th _locid=\"FromTableHeader\">Mail</th>");
            }

            sb.Append("<th _locid=\"VersionTableHeader\">Version</th>");
            sb.Append("<th _locid=\"WindowsTableHeader\">Windows</th>");
            sb.Append("<th _locid=\"BitsTableHeader\">Instruction Size</th>");
            sb.Append("<th _locid=\"MemoryTableHeader\">Working Memory</th>");
            sb.Append("<th _locid=\"IssueTableHeader\">Issue?</th>");
            sb.Append("<th _locid=\"SuggestionTableHeader\">Suggestion?</th></tr>");
            sb.AppendFormat("<tr><td class=\"textcentered\">{0}</td>", Environment.UserName);

            if (MailTextBox.Text.Length > 0)
            {
                sb.AppendFormat("<td class=\"textcentered\">{0}</td>", MailTextBox.Text);
            }

            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Assembly.GetExecutingAssembly().GetName().Version.ToString(4));
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Environment.OSVersion.Version);
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Environment.Is64BitOperatingSystem ? "64 bits" : "32 Bits");
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Humanizer.BytesToString(Environment.WorkingSet));
            sb.AppendFormat("<td class=\"textcentered\">{0}</td>", IssueCheckBox.IsChecked.Value ? "Yes" : "No");
            sb.AppendFormat("<td class=\"textcentered\">{0}</td></tr></table></div></div>", SuggestionCheckBox.IsChecked.Value ? "Yes" : "No");

            sb.Append("<h2>Details</h2><div><div><table>");
            sb.Append("<tr id=\"ProjectNameHeaderRow\"><th class=\"messageCell\" _locid=\"MessageTableHeader\">Message</th></tr>");
            sb.Append("<tr name=\"MessageRowClassProjectName\">");
            sb.AppendFormat("<td class=\"messageCell\">{0}</td></tr></table>", MessageTextBox.Text);
            sb.Append("</div></div></div></body></html>");

            #endregion

            mail.Body = sb.ToString();

            foreach (AttachmentListBoxItem attachment in AttachmentListBox.Items)
            {
                mail.Attachments.Add(new Attachment(attachment.Attachment));
            }

            smtp.SendCompleted += Smtp_OnSendCompleted;
            smtp.SendMailAsync(mail);
        }
Exemple #8
0
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        #region Adjust to file type

        switch (Current.Type)
        {
        case ExportFormats.Gif:
            EncoderScreenToGifItem.IsEnabled = true;
            EncoderFfmpegItem.IsEnabled      = true;
            EncoderGifskiItem.IsEnabled      = Environment.Is64BitProcess;
            EncoderSystemItem.IsEnabled      = true;
            break;

        case ExportFormats.Apng:
            EncoderScreenToGifItem.IsEnabled = true;
            EncoderFfmpegItem.IsEnabled      = true;
            EncoderGifskiItem.IsEnabled      = false;
            EncoderSystemItem.IsEnabled      = false;
            break;

        case ExportFormats.Webp:
        case ExportFormats.Bpg:
        case ExportFormats.Avi:
        case ExportFormats.Mkv:
        case ExportFormats.Mov:
        case ExportFormats.Mp4:
        case ExportFormats.Webm:
            EncoderScreenToGifItem.IsEnabled = false;
            EncoderFfmpegItem.IsEnabled      = true;
            EncoderGifskiItem.IsEnabled      = false;
            EncoderSystemItem.IsEnabled      = false;
            break;

        case ExportFormats.Jpeg:
        case ExportFormats.Png:
        case ExportFormats.Bmp:
        case ExportFormats.Stg:
        case ExportFormats.Psd:
            EncoderScreenToGifItem.IsEnabled = true;
            EncoderFfmpegItem.IsEnabled      = false;
            EncoderGifskiItem.IsEnabled      = false;
            EncoderSystemItem.IsEnabled      = false;
            break;
        }

        #endregion

        TitleTextBox.Focus();
        ExtensionTextBlock.Text       = Current.Type.ToString();
        EncoderComboBox.SelectedValue = Current.Encoder;

        if (IsNew)
        {
            AutoSaveCheckBox.IsChecked = true;
            return;
        }

        //Edit.
        IconBorder.Background      = TryFindResource("Vector.Pen") as Brush;
        ModeTextBlock.Text         = LocalizationHelper.Get("S.Edit");
        EncoderComboBox.IsEnabled  = false;
        TitleTextBox.Text          = Current.Title ?? "";
        DescriptionTextBox.Text    = Current.Description ?? "";
        AutoSaveCheckBox.IsChecked = Current.HasAutoSave;
        SaveInfoTextBlock.SetResourceReference(TextBlock.TextProperty, "S.Preset.Info." + (AutoSaveCheckBox.IsChecked == true ? "Automatic" : "Manual"));

        //If it's a default preset, just let the user edit the "auto save" feature.
        if (string.IsNullOrWhiteSpace(Current.TitleKey))
        {
            return;
        }

        TitleTextBox.IsEnabled       = false;
        DescriptionTextBox.IsEnabled = false;
        AutoSaveCheckBox.Focus();

        StatusBand.Info(LocalizationHelper.Get("S.Preset.Warning.Readonly"));
    }
Exemple #9
0
    private void Ok_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
    {
        #region Validation

        if (TitleTextBox.IsNullOrWhiteSpace())
        {
            StatusBand.Warning(LocalizationHelper.Get("S.Preset.Warning.Name"));
            return;
        }

        var list = UserSettings.All.ExportPresets.OfType <ExportPreset>().ToList();

        //Don't let two preset of the same type to have the same name.
        if (list.Any(a => a.Type == Current.Type && a.Title != Current.Title && a.Title == TitleTextBox.Text.Trim()))
        {
            StatusBand.Warning(LocalizationHelper.Get("S.Preset.Warning.SameName"));
            return;
        }

        #endregion

        #region Build preset

        var encoder = EncoderComboBox.SelectedValue as EncoderTypes?;

        if (IsNew)
        {
            switch (Current.Type)
            {
            case ExportFormats.Gif:
            {
                switch (encoder)
                {
                case EncoderTypes.ScreenToGif:
                    var embeddedGifPreset = new EmbeddedGifPreset();

                    Current.CopyPropertiesTo(embeddedGifPreset);
                    embeddedGifPreset.Encoder = EncoderTypes.ScreenToGif;
                    embeddedGifPreset.ImageId = "Vector.Logo";
                    Current = embeddedGifPreset;
                    break;

                case EncoderTypes.FFmpeg:
                    var ffmpegGifPreset = new FfmpegGifPreset();

                    Current.CopyPropertiesTo(ffmpegGifPreset);
                    ffmpegGifPreset.Encoder = EncoderTypes.FFmpeg;
                    ffmpegGifPreset.ImageId = "Vector.Ffmpeg";
                    Current = ffmpegGifPreset;
                    break;

                case EncoderTypes.Gifski:
                    var gifskiGifPreset = new GifskiGifPreset();

                    Current.CopyPropertiesTo(gifskiGifPreset);
                    gifskiGifPreset.Encoder = EncoderTypes.Gifski;
                    gifskiGifPreset.ImageId = "Vector.Gifski";
                    Current = gifskiGifPreset;
                    break;

                case EncoderTypes.System:
                    var systemGifPreset = new SystemGifPreset();

                    Current.CopyPropertiesTo(systemGifPreset);
                    systemGifPreset.Encoder = EncoderTypes.System;
                    systemGifPreset.ImageId = "Vector.Net";
                    Current = systemGifPreset;
                    break;
                }

                break;
            }

            case ExportFormats.Apng:
            {
                switch (encoder)
                {
                case EncoderTypes.ScreenToGif:
                {
                    var embeddedApngPreset = new EmbeddedApngPreset();

                    Current.CopyPropertiesTo(embeddedApngPreset);
                    embeddedApngPreset.Encoder = EncoderTypes.ScreenToGif;
                    embeddedApngPreset.ImageId = "Vector.Logo";
                    Current = embeddedApngPreset;
                    break;
                }

                case EncoderTypes.FFmpeg:
                {
                    var ffmpegApngPreset = new FfmpegApngPreset();

                    Current.CopyPropertiesTo(ffmpegApngPreset);
                    ffmpegApngPreset.Encoder = EncoderTypes.FFmpeg;
                    ffmpegApngPreset.ImageId = "Vector.Ffmpeg";
                    Current = ffmpegApngPreset;
                    break;
                }
                }

                break;
            }

            case ExportFormats.Webp:
            {
                var ffmpegWebpPreset = new FfmpegWebpPreset();

                Current.CopyPropertiesTo(ffmpegWebpPreset);
                Current = ffmpegWebpPreset;
                break;
            }

            case ExportFormats.Avi:
            {
                var ffmpegAviPreset = new FfmpegAviPreset();

                Current.CopyPropertiesTo(ffmpegAviPreset);
                Current = ffmpegAviPreset;
                break;
            }

            case ExportFormats.Mkv:
            {
                var ffmpegMkvPreset = new FfmpegMkvPreset();

                Current.CopyPropertiesTo(ffmpegMkvPreset);
                Current = ffmpegMkvPreset;
                break;
            }

            case ExportFormats.Mov:
            {
                var ffmpegMovPreset = new FfmpegMovPreset();

                Current.CopyPropertiesTo(ffmpegMovPreset);
                Current = ffmpegMovPreset;
                break;
            }

            case ExportFormats.Mp4:
            {
                var ffmpegMp4Preset = new FfmpegMp4Preset();

                Current.CopyPropertiesTo(ffmpegMp4Preset);
                Current = ffmpegMp4Preset;
                break;
            }

            case ExportFormats.Webm:
            {
                var ffmpegWebmPreset = new FfmpegWebmPreset();

                Current.CopyPropertiesTo(ffmpegWebmPreset);
                Current = ffmpegWebmPreset;
                break;
            }

            case ExportFormats.Jpeg:
            {
                var jpegPreset = new JpegPreset();

                Current.CopyPropertiesTo(jpegPreset);
                Current = jpegPreset;
                break;
            }

            case ExportFormats.Png:
            {
                var pngPreset = new PngPreset();

                Current.CopyPropertiesTo(pngPreset);
                Current = pngPreset;
                break;
            }

            case ExportFormats.Bmp:
            {
                var bmpPreset = new BmpPreset();

                Current.CopyPropertiesTo(bmpPreset);
                Current = bmpPreset;
                break;
            }

            case ExportFormats.Stg:
            {
                var projectPreset = new StgPreset();

                Current.CopyPropertiesTo(projectPreset);
                Current = projectPreset;
                break;
            }

            case ExportFormats.Psd:
            {
                var psdPreset = new PsdPreset();

                Current.CopyPropertiesTo(psdPreset);
                Current = psdPreset;
                break;
            }
            }
        }

        Current.IsDefault      = false;
        Current.Title          = TitleTextBox.Text;
        Current.TitleKey       = null;
        Current.Description    = DescriptionTextBox.Text;
        Current.DescriptionKey = null;
        Current.HasAutoSave    = AutoSaveCheckBox.IsChecked == true;
        Current.CreationDate   = IsNew ? DateTime.UtcNow : Current.CreationDate;

        #endregion

        #region Update on list

        if (IsNew)
        {
            list.Add(Current);
        }

        //Persist the changes to the settings.
        UserSettings.All.ExportPresets = new ArrayList(list.ToArray());

        #endregion

        DialogResult = true;
    }
Exemple #10
0
        private async void DownloadButton_Click(object sender, RoutedEventArgs e)
        {
            #region Save as

            var save = new Microsoft.Win32.SaveFileDialog
            {
                FileName   = "ScreenToGif", // + Element.XPathSelectElement("tag_name").Value,
                DefaultExt = ".exe",
                Filter     = "ScreenToGif executable (.exe)|*.exe"
            };

            var result = save.ShowDialog();

            if (!result.HasValue || !result.Value)
            {
                return;
            }

            #endregion

            DownloadButton.IsEnabled = false;
            StatusBand.Info("Downloading...");
            DownloadProgressBar.Visibility = Visibility.Visible;

            var tempFilename = save.FileName.Replace(".exe", DateTime.Now.ToString(" hh-mm-ss fff") + ".zip");

            #region Download

            try
            {
                using (var webClient = new WebClient())
                {
                    webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                    await webClient.DownloadFileTaskAsync(new Uri(Element.XPathSelectElement("assets").FirstNode.XPathSelectElement("browser_download_url").Value), tempFilename);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Download updates");

                DownloadButton.IsEnabled       = true;
                DownloadProgressBar.Visibility = Visibility.Hidden;

                Dialog.Ok("Update", "Error while downloading", ex.Message);
                return;
            }

            #endregion

            //If cancelled.
            if (!IsLoaded)
            {
                return;
            }

            #region Unzip

            try
            {
                //Deletes if already exists.
                if (File.Exists(save.FileName))
                {
                    File.Delete(save.FileName);
                }

                //Unzips the only file.
                using (var zipArchive = ZipFile.Open(tempFilename, ZipArchiveMode.Read))
                {
                    zipArchive.Entries.First(x => x.Name.EndsWith(".exe")).ExtractToFile(save.FileName);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Unziping update");

                DownloadButton.IsEnabled       = true;
                DownloadProgressBar.Visibility = Visibility.Hidden;

                Dialog.Ok("Update", "Error while unzipping", ex.Message);
                return;
            }

            #endregion

            //If cancelled.
            if (!IsLoaded)
            {
                return;
            }

            #region Delete temporary zip and run

            try
            {
                File.Delete(tempFilename);

                Process.Start(save.FileName);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Finishing update");

                DownloadButton.IsEnabled       = true;
                DownloadProgressBar.Visibility = Visibility.Hidden;

                Dialog.Ok("Update", "Error while finishing the update", ex.Message);
                return;
            }

            #endregion

            DialogResult = true;
        }
Exemple #11
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            #region Size check

            var left  = NewList[0].Path.SourceFrom();
            var right = CurrentList[0].Path.SourceFrom();

            //Left: New, Right: Current
            LeftImage.Source  = left;
            RightImage.Source = right;

            //The image should be displayed based on the scale of the screen.
            var scaleLeft  = Math.Round(left.DpiX / 96d, 2);
            var scaleRight = Math.Round(right.DpiX / 96d, 2);
            var scale      = this.Scale();

            var scaleDiffLeft  = Math.Round(scale / scaleLeft, 2);
            var scaleDiffRight = Math.Round(scale / scaleRight, 2);

            LeftImage.Width  = _leftWidth = left.Width / scaleDiffLeft;
            LeftImage.Height = _leftHeight = left.Height / scaleDiffLeft;

            RightImage.Width  = _rightWidth = right.Width / scaleDiffRight;
            RightImage.Height = _rightHeight = right.Height / scaleDiffRight;

            #endregion

            #region Initial sizing

            LeftImage.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            LeftImage.Arrange(new Rect(new Point(0, 0), LeftImage.DesiredSize));
            RightImage.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            RightImage.Arrange(new Rect(new Point(0, 0), RightImage.DesiredSize));

            if (Math.Abs(LeftImage.ActualWidth - RightImage.ActualWidth) > 0.01 || Math.Abs(LeftImage.ActualHeight - RightImage.ActualHeight) > 0.01)
            {
                StatusBand.Warning(LocalizationHelper.Get("S.InsertFrames.DifferentSizes"));
            }

            LeftCanvas.Width  = LeftImage.ActualWidth;
            LeftCanvas.Height = LeftImage.ActualHeight;

            RightCanvas.Width  = RightImage.ActualWidth;
            RightCanvas.Height = RightImage.ActualHeight;

            EqualizeSizes();

            #endregion

            MouseLeftButtonDown += Unselect_MouseLeftButtonDown;

            LeftImage.MouseLeftButtonDown  += Select_PreviewMouseLeftButtonDown;
            LeftCanvas.MouseLeftButtonDown += Select_PreviewMouseLeftButtonDown;

            RightImage.MouseLeftButtonDown  += Select_PreviewMouseLeftButtonDown;
            RightCanvas.MouseLeftButtonDown += Select_PreviewMouseLeftButtonDown;

            LeftCanvas.SizeChanged  += Canvas_SizeChanged;
            RightCanvas.SizeChanged += Canvas_SizeChanged;

            UpdateLayout();
        }