Ejemplo n.º 1
0
        protected override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            var exportInformation = new ExportInformation(Designation, Description);

            // Make sure we collect the garbage before opening the screenshot
            GC.Collect();
            GC.WaitForPendingFinalizers();

            var modified = surface.Modified;

            if (_editor != null)
            {
                try
                {
                    using (var image = surface.GetBitmapForExport())
                    {
                        _editor.Surface.AddImageContainer(image, 10, 10);
                    }
                    exportInformation.ExportMade = true;
                }
                catch (Exception e)
                {
                    Log.Error().WriteLine(e);
                    exportInformation.ErrorMessage = e.Message;
                }
            }
            else
            {
                _editorFactory.CreateOrReuse(surface, captureDetails);
                exportInformation.ExportMade = true;
            }

            ProcessExport(exportInformation, surface);
            // Workaround for the modified flag when using the editor.
            surface.Modified = modified;
            return(exportInformation);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Upload the capture to imgur
        /// </summary>
        /// <param name="captureDetails">ICaptureDetails</param>
        /// <param name="surfaceToUpload">ISurface</param>
        /// <returns>Uri</returns>
        private async Task <Uri> Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload)
        {
            var outputSettings = new SurfaceOutputSettings(_imgurConfiguration.UploadFormat, _imgurConfiguration.UploadJpegQuality, _imgurConfiguration.UploadReduceColors);

            try
            {
                string     filename = Path.GetFileName(FilenameHelper.GetFilenameFromPattern(_imgurConfiguration.FilenamePattern, _imgurConfiguration.UploadFormat, captureDetails));
                ImgurImage imgurImage;

                var cancellationTokenSource = new CancellationTokenSource();
                using (var pleaseWaitForm = new PleaseWaitForm("Imgur plug-in", _imgurLanguage.CommunicationWait, cancellationTokenSource))
                {
                    pleaseWaitForm.Show();
                    try
                    {
                        imgurImage = await ImgurUtils.UploadToImgurAsync(_oauth2Settings, surfaceToUpload, outputSettings, captureDetails.Title, filename, null, cancellationTokenSource.Token);

                        if (imgurImage != null)
                        {
                            // Create thumbnail
                            using (var tmpImage = surfaceToUpload.GetBitmapForExport())
                                using (var thumbnail = tmpImage.CreateThumbnail(90, 90))
                                {
                                    imgurImage.Image = thumbnail.ToBitmapSource();
                                }
                            if (_imgurConfiguration.AnonymousAccess && _imgurConfiguration.TrackHistory)
                            {
                                Log.Info().WriteLine("Storing imgur upload for hash {0} and delete hash {1}", imgurImage.Data.Id, imgurImage.Data.Deletehash);
                                _imgurConfiguration.ImgurUploadHistory.Add(imgurImage.Data.Id, imgurImage.Data.Deletehash);
                                _imgurConfiguration.RuntimeImgurHistory.Add(imgurImage.Data.Id, imgurImage);

                                // TODO: Update History - ViewModel!!!
                                // UpdateHistoryMenuItem();
                            }
                        }
                    }
                    finally
                    {
                        pleaseWaitForm.Close();
                    }
                }

                if (imgurImage != null)
                {
                    var uploadUrl = _imgurConfiguration.UsePageLink ? imgurImage.Data.LinkPage: imgurImage.Data.Link;
                    if (uploadUrl == null || !_imgurConfiguration.CopyLinkToClipboard)
                    {
                        return(uploadUrl);
                    }

                    try
                    {
                        ClipboardHelper.SetClipboardData(uploadUrl.AbsoluteUri);
                    }
                    catch (Exception ex)
                    {
                        Log.Error().WriteLine(ex, "Can't write to clipboard: ");
                        uploadUrl = null;
                    }
                    return(uploadUrl);
                }
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Error uploading.");
                MessageBox.Show(_imgurLanguage.UploadFailure + " " + e.Message);
            }
            return(null);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Upload the capture to imgur
        /// </summary>
        /// <param name="captureDetails">ICaptureDetails</param>
        /// <param name="surfaceToUpload">ISurface</param>
        /// <returns>Uri</returns>
        private async Task <Uri> Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload)
        {
            try
            {
                ImgurImage imgurImage;

                var cancellationTokenSource = new CancellationTokenSource();
                // TODO: Replace the form
                using (var ownedPleaseWaitForm = _pleaseWaitFormFactory(cancellationTokenSource))
                {
                    ownedPleaseWaitForm.Value.SetDetails("Imgur", _imgurLanguage.CommunicationWait);
                    ownedPleaseWaitForm.Value.Show();
                    try
                    {
                        imgurImage = await _imgurApi.UploadToImgurAsync(surfaceToUpload, captureDetails.Title, null, cancellationTokenSource.Token).ConfigureAwait(true);

                        if (imgurImage != null)
                        {
                            // Create thumbnail
                            using (var tmpImage = surfaceToUpload.GetBitmapForExport())
                                using (var thumbnail = tmpImage.CreateThumbnail(90, 90))
                                {
                                    imgurImage.Image = thumbnail.ToBitmapSource();
                                }
                            if (_imgurConfiguration.AnonymousAccess && _imgurConfiguration.TrackHistory)
                            {
                                Log.Debug().WriteLine("Storing imgur upload for hash {0} and delete hash {1}", imgurImage.Data.Id, imgurImage.Data.Deletehash);
                                _imgurConfiguration.ImgurUploadHistory.Add(imgurImage.Data.Id, imgurImage.Data.Deletehash);
                                _imgurConfiguration.RuntimeImgurHistory.Add(imgurImage.Data.Id, imgurImage);

                                // Update history
                                _imgurHistoryViewModel.ImgurHistory.Add(imgurImage);
                            }
                        }
                    }
                    finally
                    {
                        ownedPleaseWaitForm.Value.Close();
                    }
                }

                if (imgurImage != null)
                {
                    var uploadUrl = _imgurConfiguration.UsePageLink ? imgurImage.Data.LinkPage: imgurImage.Data.Link;
                    if (uploadUrl == null || !_imgurConfiguration.CopyLinkToClipboard)
                    {
                        return(uploadUrl);
                    }

                    try
                    {
                        using (var clipboardAccessToken = ClipboardNative.Access())
                        {
                            clipboardAccessToken.ClearContents();
                            clipboardAccessToken.SetAsUrl(uploadUrl.AbsoluteUri);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error().WriteLine(ex, "Can't write to clipboard: ");
                        uploadUrl = null;
                    }
                    return(uploadUrl);
                }
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Error uploading.");
                MessageBox.Show(_imgurLanguage.UploadFailure + " " + e.Message);
            }
            return(null);
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Create an image from a surface with the settings from the output settings applied
        /// </summary>
        /// <param name="surface"></param>
        /// <param name="outputSettings"></param>
        /// <param name="bitmapToSave"></param>
        /// <returns>true if the image must be disposed</returns>
        public static bool CreateBitmapFromSurface(ISurface surface, SurfaceOutputSettings outputSettings, out Bitmap bitmapToSave)
        {
            var disposeImage = false;

            if (outputSettings.Format == OutputFormats.greenshot || outputSettings.SaveBackgroundOnly)
            {
                // We save the image of the surface, this should not be disposed
                bitmapToSave = surface.Screenshot;
            }
            else
            {
                // We create the export image of the surface to save
                bitmapToSave = surface.GetBitmapForExport();
                disposeImage = true;
            }

            // The following block of modifications should be skipped when saving the greenshot format, no effects or otherwise!
            if (outputSettings.Format == OutputFormats.greenshot)
            {
                return(disposeImage);
            }
            Bitmap tmpBitmap;

            if (outputSettings.Effects != null && outputSettings.Effects.Count > 0)
            {
                // apply effects, if there are any
                using (var matrix = new Matrix())
                {
                    tmpBitmap = bitmapToSave.ApplyEffects(outputSettings.Effects, matrix);
                }
                if (tmpBitmap != null)
                {
                    if (disposeImage)
                    {
                        bitmapToSave.Dispose();
                    }
                    bitmapToSave = tmpBitmap;
                    disposeImage = true;
                }
            }

            // check for color reduction, forced or automatically, only when the DisableReduceColors is false
            if (outputSettings.DisableReduceColors || !CoreConfig.OutputFileAutoReduceColors && !outputSettings.ReduceColors)
            {
                return(disposeImage);
            }
            var isAlpha = Image.IsAlphaPixelFormat(bitmapToSave.PixelFormat);

            if (outputSettings.ReduceColors || !isAlpha && CoreConfig.OutputFileAutoReduceColors)
            {
                using (var quantizer = new WuQuantizer(bitmapToSave))
                {
                    var colorCount = quantizer.GetColorCount();
                    Log.Info().WriteLine("Image with format {0} has {1} colors", bitmapToSave.PixelFormat, colorCount);
                    if (!outputSettings.ReduceColors && colorCount >= 256)
                    {
                        return(disposeImage);
                    }
                    try
                    {
                        Log.Info().WriteLine("Reducing colors on bitmap to 256.");
                        tmpBitmap = quantizer.GetQuantizedImage(CoreConfig.OutputFileReduceColorsTo);
                        if (disposeImage)
                        {
                            bitmapToSave.Dispose();
                        }
                        bitmapToSave = tmpBitmap;
                        // Make sure the "new" image is disposed
                        disposeImage = true;
                    }
                    catch (Exception e)
                    {
                        Log.Warn().WriteLine(e, "Error occurred while Quantizing the image, ignoring and using original. Error: ");
                    }
                }
            }
            else if (isAlpha && !outputSettings.ReduceColors)
            {
                Log.Info().WriteLine("Skipping 'optional' color reduction as the image has alpha");
            }
            return(disposeImage);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Share the surface by using the Share-UI of Windows 10
        /// </summary>
        /// <param name="shareInfo">ShareInfo</param>
        /// <param name="handle">IntPtr with the handle for the hosting window</param>
        /// <param name="surface">ISurface with the bitmap to share</param>
        /// <param name="captureDetails">ICaptureDetails</param>
        /// <returns>Task with string, which describes the application which was used to share with</returns>
        private async Task Share(ShareInfo shareInfo, IntPtr handle, ISurface surface, ICaptureDetails captureDetails)
        {
            using (var imageStream = new MemoryRandomAccessStream())
                using (var logoStream = new MemoryRandomAccessStream())
                    using (var thumbnailStream = new MemoryRandomAccessStream())
                    {
                        var outputSettings = new SurfaceOutputSettings();
                        outputSettings.PreventGreenshotFormat();

                        // Create capture for export
                        ImageOutput.SaveToStream(surface, imageStream, outputSettings);
                        imageStream.Position = 0;
                        Log.Debug().WriteLine("Created RandomAccessStreamReference for the image");
                        var imageRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(imageStream);

                        // Create thumbnail
                        RandomAccessStreamReference thumbnailRandomAccessStreamReference;
                        using (var tmpImageForThumbnail = surface.GetBitmapForExport())
                            using (var thumbnail = tmpImageForThumbnail.CreateThumbnail(240, 160))
                            {
                                ImageOutput.SaveToStream(thumbnail, null, thumbnailStream, outputSettings);
                                thumbnailStream.Position             = 0;
                                thumbnailRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(thumbnailStream);
                                Log.Debug().WriteLine("Created RandomAccessStreamReference for the thumbnail");
                            }

                        // Create logo
                        RandomAccessStreamReference logoRandomAccessStreamReference;
                        using (var logo = GreenshotResources.GetGreenshotIcon().ToBitmap())
                            using (var logoThumbnail = logo.CreateThumbnail(30, 30))
                            {
                                ImageOutput.SaveToStream(logoThumbnail, null, logoStream, outputSettings);
                                logoStream.Position             = 0;
                                logoRandomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(logoStream);
                                Log.Info().WriteLine("Created RandomAccessStreamReference for the logo");
                            }

                        var dataTransferManagerHelper = new DataTransferManagerHelper(handle);
                        dataTransferManagerHelper.DataTransferManager.ShareProvidersRequested += (sender, args) =>
                        {
                            shareInfo.AreShareProvidersRequested = true;
                            Log.Debug().WriteLine("Share providers requested: {0}", string.Join(",", args.Providers.Select(p => p.Title)));
                        };
                        dataTransferManagerHelper.DataTransferManager.TargetApplicationChosen += (dtm, args) =>
                        {
                            shareInfo.ApplicationName = args.ApplicationName;
                            Log.Debug().WriteLine("TargetApplicationChosen: {0}", args.ApplicationName);
                        };
                        var filename    = FilenameHelper.GetFilename(OutputFormats.png, captureDetails);
                        var storageFile = await StorageFile.CreateStreamedFileAsync(filename, async streamedFileDataRequest =>
                        {
                            shareInfo.IsDeferredFileCreated = true;
                            // Information on the "how" was found here: https://socialeboladev.wordpress.com/2013/03/15/how-to-use-createstreamedfileasync/
                            Log.Debug().WriteLine("Creating deferred file {0}", filename);
                            try
                            {
                                using (var deferredStream = streamedFileDataRequest.AsStreamForWrite())
                                {
                                    await imageStream.CopyToAsync(deferredStream).ConfigureAwait(false);
                                    await imageStream.FlushAsync().ConfigureAwait(false);
                                }
                                // Signal that the stream is ready
                                streamedFileDataRequest.Dispose();
                            }
                            catch (Exception)
                            {
                                streamedFileDataRequest.FailAndClose(StreamedFileFailureMode.Incomplete);
                            }
                        }, imageRandomAccessStreamReference).AsTask().ConfigureAwait(false);

                        dataTransferManagerHelper.DataTransferManager.DataRequested += (dataTransferManager, dataRequestedEventArgs) =>
                        {
                            var deferral = dataRequestedEventArgs.Request.GetDeferral();
                            try
                            {
                                shareInfo.IsDataRequested = true;
                                Log.Debug().WriteLine("DataRequested with operation {0}", dataRequestedEventArgs.Request.Data.RequestedOperation);
                                var dataPackage = dataRequestedEventArgs.Request.Data;
                                dataPackage.OperationCompleted += (dp, eventArgs) =>
                                {
                                    Log.Debug().WriteLine("OperationCompleted: {0}, shared with", eventArgs.Operation);
                                    shareInfo.CompletedWithOperation = eventArgs.Operation;
                                    shareInfo.AcceptedFormat         = eventArgs.AcceptedFormatId;

                                    shareInfo.ShareTask.TrySetResult(true);
                                };
                                dataPackage.Destroyed += (dp, o) =>
                                {
                                    shareInfo.IsDestroyed = true;
                                    Log.Debug().WriteLine("Destroyed");
                                    shareInfo.ShareTask.TrySetResult(true);
                                };
                                dataPackage.ShareCompleted += (dp, shareCompletedEventArgs) =>
                                {
                                    shareInfo.IsShareCompleted = true;
                                    Log.Debug().WriteLine("ShareCompleted");
                                    shareInfo.ShareTask.TrySetResult(true);
                                };
                                dataPackage.Properties.Title               = captureDetails.Title;
                                dataPackage.Properties.ApplicationName     = "Greenshot";
                                dataPackage.Properties.Description         = "Share a screenshot";
                                dataPackage.Properties.Thumbnail           = thumbnailRandomAccessStreamReference;
                                dataPackage.Properties.Square30x30Logo     = logoRandomAccessStreamReference;
                                dataPackage.Properties.LogoBackgroundColor = Color.FromArgb(0xff, 0x3d, 0x3d, 0x3d);
                                dataPackage.SetStorageItems(new[] { storageFile });
                                dataPackage.SetBitmap(imageRandomAccessStreamReference);
                            }
                            finally
                            {
                                deferral.Complete();
                                Log.Debug().WriteLine("Called deferral.Complete()");
                            }
                        };
                        dataTransferManagerHelper.ShowShareUi();
                        Log.Debug().WriteLine("ShowShareUi finished.");
                        await shareInfo.ShareTask.Task.ConfigureAwait(false);
                    }
        }