Exemple #1
0
        public async Task TestClipboardMonitor_Text()
        {
            const string testString    = "Dapplo.Windows.Tests.ClipboardTests";
            bool         hasNewContent = false;
            var          subscription  = ClipboardNative.OnUpdate.Where(clipboard => clipboard.Formats.Contains("TEST_FORMAT")).Subscribe(clipboard =>
            {
                Log.Debug().WriteLine("Detected change {0}", string.Join(",", clipboard.Formats));
                Log.Debug().WriteLine("Owner {0}", clipboard.OwnerHandle);
                Log.Debug().WriteLine("Sequence {0}", clipboard.Id);

                hasNewContent = true;
            });

            using (var clipboardAccessToken = ClipboardNative.Access())
            {
                clipboardAccessToken.ClearContents();
                clipboardAccessToken.SetAsUnicodeString(testString, "TEST_FORMAT");
            }
            await Task.Delay(100);

            subscription.Dispose();

            // Doesn't work on AppVeyor!!
            Assert.True(hasNewContent);
        }
Exemple #2
0
        /// <summary>
        ///     Test monitoring the clipboard
        /// </summary>
        /// <returns></returns>
        public async Task TestClipboardMonitor_WaitForCopy()
        {
            var tcs          = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
            var subscription = ClipboardNative.OnUpdate.Skip(1).Subscribe(clipboardUpdateInformation =>
            {
                Log.Debug().WriteLine("Formats {0}", string.Join(",", clipboardUpdateInformation.Formats));
                Log.Debug().WriteLine("Owner {0}", clipboardUpdateInformation.OwnerHandle);
                Log.Debug().WriteLine("Sequence {0}", clipboardUpdateInformation.Id);

                if (clipboardUpdateInformation.Formats.Contains("PNG"))
                {
                    using (var clipboard = ClipboardNative.Access())
                    {
                        using (var stream = clipboard.GetAsStream("PNG"))
                        {
                            using (var fileStream = File.Create(@"c:\projects\test.png"))
                            {
                                stream.CopyTo(fileStream);
                            }
                        }
                    }
                }

                tcs.TrySetResult(true);
            });

            await tcs.Task;

            subscription.Dispose();
        }
Exemple #3
0
 /// <inheritdoc />
 public string GetClipboardString()
 {
     using (var clipboardAccessToken = ClipboardNative.Access())
     {
         return(clipboardAccessToken.GetAsUnicodeString());
     }
 }
Exemple #4
0
 /// <inheritdoc />
 public void CopyToClipboard(string origin, string text)
 {
     using (var clipboardAccessToken = ClipboardNative.Access())
     {
         clipboardAccessToken.SetAsUnicodeString(text);
     }
 }
        /// <summary>
        /// Place the clip back onto the clipboard
        /// </summary>
        /// <param name="clip">Clip</param>
        /// <param name="fromExisting">bool</param>
        public static void PlaceOnClipboard(this Clip clip, bool fromExisting = false)
        {
            var handle = WinProcHandler.Instance.Handle;

            if (InteropWindowFactory.CreateFor(clip.OriginalWindowHandle).Exists())
            {
                handle = clip.OriginalWindowHandle;
            }
            // TODO: Prevent detecting the restore, especially if Dopy doesn't "paste" with it's Window handle
            using var clipboardAccessToken = ClipboardNative.Access(handle);
            clipboardAccessToken.ClearContents();
            // Make the clipboard as modified by DOPY
            if (fromExisting || clip.IsModifiedByDopy)
            {
                clipboardAccessToken.SetAsUnicodeString($"On {DateTime.Now:O}", ClipboardFormats.Dopy);
            }
            foreach (var key in clip.Contents.Keys)
            {
                clipboardAccessToken.SetAsStream(key, clip.Contents[key]);
            }
            if (!string.IsNullOrEmpty(clip.ClipboardText))
            {
                clipboardAccessToken.SetAsUnicodeString(clip.ClipboardText);
            }
        }
Exemple #6
0
        public async Task TestClipboardStore_MemoryStream()
        {
            const string testString = "Dapplo.Windows.Tests.ClipboardTests";
            var          testStream = new MemoryStream();
            var          bytes      = Encoding.Unicode.GetBytes(testString + "\0");

            Assert.Equal(testString, Encoding.Unicode.GetString(bytes).TrimEnd('\0'));
            testStream.Write(bytes, 0, bytes.Length);

            testStream.Seek(0, SeekOrigin.Begin);
            Assert.Equal(testString, Encoding.Unicode.GetString(testStream.GetBuffer(), 0, (int)testStream.Length).TrimEnd('\0'));

            using (var clipboardAccessToken = ClipboardNative.Access())
            {
                clipboardAccessToken.ClearContents();
                clipboardAccessToken.SetAsStream(StandardClipboardFormats.UnicodeText, testStream);
            }
            await Task.Delay(100);

            using (var clipboardAccessToken = ClipboardNative.Access())
            {
                Assert.Equal(testString, clipboardAccessToken.GetAsUnicodeString());
                var unicodeBytes = clipboardAccessToken.GetAsBytes(StandardClipboardFormats.UnicodeText);
                Assert.Equal(testString, Encoding.Unicode.GetString(unicodeBytes, 0, unicodeBytes.Length).TrimEnd('\0'));

                var unicodeStream = clipboardAccessToken.GetAsStream(StandardClipboardFormats.UnicodeText);
                using (var memoryStream = new MemoryStream())
                {
                    unicodeStream.CopyTo(memoryStream);
                    Assert.Equal(testString, Encoding.Unicode.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length).TrimEnd('\0'));
                }
            }
        }
 /// <summary>
 /// Used from the View
 /// </summary>
 public void CopyToClipboard()
 {
     using (var clipboardAccessToken = ClipboardNative.Access())
     {
         clipboardAccessToken.ClearContents();
         clipboardAccessToken.SetAsUrl(SelectedImgur.Data.Link?.AbsoluteUri);
     }
 }
Exemple #8
0
 /// <summary>
 ///     Test if the clipboard contains files
 /// </summary>
 /// <returns></returns>
 //[WpfFact]
 public void TestClipboard_Filenames()
 {
     using (var clipboardAccessToken = ClipboardNative.Access())
     {
         var filenames = clipboardAccessToken.GetFilenames();
         Assert.True(filenames.Any());
     }
 }
Exemple #9
0
 public void CopyToClipboard()
 {
     // TODO: Build url
     using (var clipboardAccessToken = ClipboardNative.Access())
     {
         clipboardAccessToken.ClearContents();
         clipboardAccessToken.SetAsUrl(SelectedLutim.LutimInfo.Short);
     }
 }
Exemple #10
0
        protected override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            var exportInformation = new ExportInformation(Designation, Description);

            try
            {
                using (var clipboardAccessToken = ClipboardNative.Access())
                {
                    clipboardAccessToken.ClearContents();
                    // TODO: Test if this works
                    if (!string.IsNullOrEmpty(surface.LastSaveFullPath))
                    {
                        clipboardAccessToken.SetAsUnicodeString(surface.LastSaveFullPath);
                    }

                    foreach (var clipboardFormat in CoreConfiguration.ClipboardFormats)
                    {
                        switch (clipboardFormat)
                        {
                        case ClipboardFormats.DIB:
                            clipboardAccessToken.SetAsDeviceIndependendBitmap(surface);
                            break;

                        case ClipboardFormats.DIBV5:
                            clipboardAccessToken.SetAsFormat17(surface);
                            break;

                        case ClipboardFormats.PNG:
                            clipboardAccessToken.SetAsBitmap(surface, new SurfaceOutputSettings(OutputFormats.png));
                            break;

                        case ClipboardFormats.BITMAP:
                            clipboardAccessToken.SetAsBitmap(surface, new SurfaceOutputSettings(OutputFormats.bmp));
                            break;

                        case ClipboardFormats.HTML:
                            clipboardAccessToken.SetAsHtml(surface);
                            break;

                        case ClipboardFormats.HTMLDATAURL:
                            clipboardAccessToken.SetAsEmbeddedHtml(surface);
                            break;
                        }
                    }
                }
                exportInformation.ExportMade = true;
            }
            catch (Exception)
            {
                // TODO: Change to general logic in ProcessExport
                surface.SendMessageEvent(this, SurfaceMessageTyp.Error, "Error");                 //GreenshotLanguage.editorclipboardfailed);
            }
            ProcessExport(exportInformation, surface);
            return(exportInformation);
        }
 /// <summary>
 ///
 /// </summary>
 public FormatsViewModel(
     IDopyTranslations dopyTranslations,
     IDopyConfiguration dopyConfiguration)
 {
     DopyTranslations  = dopyTranslations;
     DopyConfiguration = dopyConfiguration;
     dopyTranslations.CreateDisplayNameBinding(this, nameof(IDopyTranslations.FormatsConfigTitle));
     Id = "F_Formats";
     SelectedFormats = new ObservableCollection <string>(DopyConfiguration.IncludeFormats);
     using var clipboardAccessToken = ClipboardNative.Access();
     AvailableFormats = new ObservableCollection <string>(clipboardAccessToken.AvailableFormats());
 }
        /// <summary>
        /// Upload the capture to OneDrive
        /// </summary>
        /// <param name="captureDetails">ICaptureDetails</param>
        /// <param name="surfaceToUpload">ISurface</param>
        /// <returns>Uri</returns>
        private async Task <Uri> Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload)
        {
            try
            {
                Uri response;

                var cancellationTokenSource = new CancellationTokenSource();
                using (var ownedPleaseWaitForm = _pleaseWaitFormFactory(cancellationTokenSource))
                {
                    ownedPleaseWaitForm.Value.SetDetails("OneDrive", _oneDriveLanguage.CommunicationWait);
                    ownedPleaseWaitForm.Value.Show();
                    try
                    {
                        var oneDriveResponse = await UploadToOneDriveAsync(_oauth2Settings, surfaceToUpload, null, cancellationTokenSource.Token);

                        Log.Info().WriteLine($"id: {oneDriveResponse.Id}");

                        if (_oneDriveConfiguration.LinkType == OneDriveLinkType.@private)
                        {
                            response = new Uri(oneDriveResponse.WebUrl);
                        }
                        else
                        {
                            var sharableLink = await CreateSharableLinkAync(_oauth2Settings, oneDriveResponse.Id, _oneDriveConfiguration.LinkType);

                            response = new Uri(sharableLink.Link.WebUrl);
                        }
                    }
                    finally
                    {
                        ownedPleaseWaitForm.Value.Close();
                    }
                }

                if (_oneDriveConfiguration.AfterUploadLinkToClipBoard)
                {
                    using (var clipboardAccessToken = ClipboardNative.Access())
                    {
                        clipboardAccessToken.ClearContents();
                        clipboardAccessToken.SetAsUrl(response.AbsoluteUri);
                    }
                }

                return(response);
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Error uploading.");
                MessageBox.Show(_oneDriveLanguage.UploadFailure + " " + e.Message);
            }

            return(null);
        }
Exemple #13
0
        private void ContextMenuOpening(object sender, CancelEventArgs e)
        {
            using (var clipboardAccessToken = ClipboardNative.Access())
            {
                contextmenu_captureclipboard.Enabled = clipboardAccessToken.HasImage();
            }
            contextmenu_capturelastregion.Enabled = _coreConfiguration.LastCapturedRegion != NativeRect.Empty;

            // IE context menu code
            try
            {
                if (_coreConfiguration.IECapture && IeCaptureHelper.IsIeRunning())
                {
                    contextmenu_captureie.Enabled         = true;
                    contextmenu_captureiefromlist.Enabled = true;
                }
                else
                {
                    contextmenu_captureie.Enabled         = false;
                    contextmenu_captureiefromlist.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                Log.Warn().WriteLine("Problem accessing IE information: {0}", ex.Message);
            }

            // Multi-Screen captures
            contextmenu_capturefullscreen.Click           -= CaptureFullScreenToolStripMenuItemClick;
            contextmenu_capturefullscreen.DropDownOpening -= MultiScreenDropDownOpening;
            contextmenu_capturefullscreen.DropDownClosed  -= MultiScreenDropDownClosing;
            if (Screen.AllScreens.Length > 1)
            {
                contextmenu_capturefullscreen.DropDownOpening += MultiScreenDropDownOpening;
                contextmenu_capturefullscreen.DropDownClosed  += MultiScreenDropDownClosing;
            }
            else
            {
                contextmenu_capturefullscreen.Click += CaptureFullScreenToolStripMenuItemClick;
            }

            var now = DateTime.Now;

            if (now.Month == 12 && now.Day > 19 && now.Day < 27 || // christmas
                now.Month == 3 && now.Day > 13 && now.Day < 21)
            {
                // birthday
                var resources = new ComponentResourceManager(typeof(MainForm));
                contextmenu_donate.Image = (Image)resources.GetObject("contextmenu_present.Image");
            }
        }
Exemple #14
0
        public async Task TestClipboardStore_String()
        {
            const string testString = "Dapplo.Windows.Tests.ClipboardTests";

            using (var clipboardAccessToken = ClipboardNative.Access())
            {
                clipboardAccessToken.ClearContents();
                clipboardAccessToken.SetAsUnicodeString(testString);
            }
            await Task.Delay(100);

            using (var clipboardAccessToken = ClipboardNative.Access())
            {
                Assert.Equal(testString, clipboardAccessToken.GetAsUnicodeString());
            }
        }
Exemple #15
0
        public void TestClipboard_RegisterFormat()
        {
            string format = "DAPPLO.DOPY" + ClipboardNative.SequenceNumber;

            // Register the format
            var id1 = ClipboardFormatExtensions.RegisterFormat(format);
            // Register the format again
            var id2 = ClipboardFormatExtensions.RegisterFormat(format);

            Assert.Equal(id1, id2);

            // Make sure it works
            using (var clipboard = ClipboardNative.Access())
            {
                clipboard.ClearContents();
                clipboard.SetAsUnicodeString("Blub", format);
            }
        }
        /// <summary>
        /// Run the Windows 10 OCR engine to process the text on the captured image
        /// </summary>
        /// <param name="manuallyInitiated"></param>
        /// <param name="surface"></param>
        /// <param name="captureDetails"></param>
        /// <returns>ExportInformation</returns>
        public override async Task <ExportInformation> ExportCaptureAsync(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            var exportInformation = new ExportInformation(Designation, Description);

            try
            {
                string text;
                var    ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
                using (var imageStream = new MemoryStream())
                {
                    ImageOutput.SaveToStream(surface, imageStream, new SurfaceOutputSettings());
                    imageStream.Position = 0;

                    var decoder = await BitmapDecoder.CreateAsync(imageStream.AsRandomAccessStream());

                    var softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                    var ocrResult = await ocrEngine.RecognizeAsync(softwareBitmap);

                    text = ocrResult.Text;
                }


                // Check if we found text
                if (!string.IsNullOrWhiteSpace(text))
                {
                    // Place the OCR text on the clipboard
                    using (var clipboardAccessToken = ClipboardNative.Access())
                    {
                        clipboardAccessToken.ClearContents();
                        clipboardAccessToken.SetAsUnicodeString(text);
                    }
                }
                exportInformation.ExportMade = true;
            }
            catch (Exception ex)
            {
                exportInformation.ExportMade   = false;
                exportInformation.ErrorMessage = ex.Message;
            }

            ProcessExport(exportInformation, surface);
            return(exportInformation);
        }
Exemple #17
0
        /// <summary>
        /// Upload the capture to Tfs
        /// </summary>
        /// <param name="workItem">WorkItem</param>
        /// <param name="surfaceToUpload">ISurface</param>
        /// <returns>Uri</returns>
        private async Task <Uri> Upload(WorkItem workItem, ISurface surfaceToUpload)
        {
            try
            {
                Uri response;

                var cancellationTokenSource = new CancellationTokenSource();
                using (var ownedPleaseWaitForm = _pleaseWaitFormFactory(cancellationTokenSource))
                {
                    ownedPleaseWaitForm.Value.SetDetails("TFS plug-in", _tfsLanguage.CommunicationWait);
                    ownedPleaseWaitForm.Value.Show();
                    try
                    {
                        var result = await _tfsClient.CreateAttachment(surfaceToUpload);

                        await _tfsClient.LinkAttachment(workItem, result);

                        response = result.Url;
                    }
                    finally
                    {
                        ownedPleaseWaitForm.Value.Close();
                    }
                }

                if (_tfsConfiguration.AfterUploadLinkToClipBoard)
                {
                    using (var clipboardAccessToken = ClipboardNative.Access())
                    {
                        clipboardAccessToken.ClearContents();
                        clipboardAccessToken.SetAsUrl(response.AbsoluteUri);
                    }
                }

                return(response);
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Error uploading.");
                MessageBox.Show(_tfsLanguage.UploadFailure + " " + e.Message);
            }

            return(null);
        }
Exemple #18
0
        public async Task <string> Upload(ICaptureDetails captureDetails, ISurface surface)
        {
            string uploadUrl = null;

            try
            {
                var cancellationTokenSource = new CancellationTokenSource();
                using (var ownedPleaseWaitForm = _pleaseWaitFormFactory(cancellationTokenSource))
                {
                    ownedPleaseWaitForm.Value.SetDetails("Flickr", _flickrLanguage.CommunicationWait);
                    ownedPleaseWaitForm.Value.Show();
                    try
                    {
                        uploadUrl = await UploadToFlickrAsync(surface, captureDetails.Title, cancellationTokenSource.Token);
                    }
                    finally
                    {
                        ownedPleaseWaitForm.Value.Close();
                    }
                }


                if (uploadUrl == null)
                {
                    return(null);
                }
                if (_flickrConfiguration.AfterUploadLinkToClipBoard)
                {
                    using (var clipboardAccessToken = ClipboardNative.Access())
                    {
                        clipboardAccessToken.ClearContents();
                        clipboardAccessToken.SetAsUrl(uploadUrl);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Error uploading.");
                MessageBox.Show(_flickrLanguage.UploadFailure + @" " + e.Message);
            }
            return(uploadUrl);
        }
Exemple #19
0
        public override async Task <ExportInformation> ExportCaptureAsync(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            var exportInformation = new ExportInformation(Designation, Description);
            var uploadUrl         = await UploadAsync(surface).ConfigureAwait(true);

            if (uploadUrl != null)
            {
                exportInformation.Uri        = uploadUrl;
                exportInformation.ExportMade = true;
                if (_dropboxPluginConfiguration.AfterUploadLinkToClipBoard)
                {
                    using (var clipboardAccessToken = ClipboardNative.Access())
                    {
                        clipboardAccessToken.ClearContents();
                        clipboardAccessToken.SetAsUrl(uploadUrl);
                    }
                }
            }
            ProcessExport(exportInformation, surface);
            return(exportInformation);
        }
Exemple #20
0
        /// <summary>
        ///     Saves image to specific path with specified quality
        /// </summary>
        public static void Save(ISurface surface, string fullPath, bool allowOverwrite, SurfaceOutputSettings outputSettings, bool copyPathToClipboard)
        {
            fullPath = FilenameHelper.MakeFqFilenameSafe(fullPath);
            var path = Path.GetDirectoryName(fullPath);

            // check whether path exists - if not create it
            if (path != null)
            {
                var di = new DirectoryInfo(path);
                if (!di.Exists)
                {
                    Directory.CreateDirectory(di.FullName);
                }
            }

            if (!allowOverwrite && File.Exists(fullPath))
            {
                var throwingException = new ArgumentException("File '" + fullPath + "' already exists.");
                throwingException.Data.Add("fullPath", fullPath);
                throw throwingException;
            }
            Log.Debug().WriteLine("Saving surface to {0}", fullPath);
            // Create the stream and call SaveToStream
            using (var stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
            {
                SaveToStream(surface, stream, outputSettings);
            }

            // TODO: This should not be done here, remove this!!
            if (copyPathToClipboard)
            {
                using (var clipboardAccessToken = ClipboardNative.Access())
                {
                    clipboardAccessToken.ClearContents();
                    // TODO: File??
                    clipboardAccessToken.SetAsUnicodeString(fullPath);
                }
            }
        }
        /// <inheritdoc />
        public override async Task <ExportInformation> ExportCaptureAsync(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            var exportInformation = new ExportInformation(Designation, Description);

            var fullPath = captureDetails.Filename ?? surface.SaveNamedTmpFile(CoreConfiguration, _externalCommandConfiguration);

            using (var cli = new Cli(_externalCommandDefinition.Command))
            {
                var arguments = string.Format(_externalCommandDefinition.Arguments, fullPath);
                // Execute
                var output = await cli.ExecuteAsync(arguments).ConfigureAwait(true);

                if (_externalCommandDefinition.CommandBehavior.HasFlag(CommandBehaviors.ParseOutputForUris))
                {
                    var uriMatches = UriRegexp.Matches(output.StandardOutput);
                    if (uriMatches.Count > 0)
                    {
                        exportInformation.Uri = uriMatches[0].Groups[1].Value;

                        using (var clipboardAccessToken = ClipboardNative.Access())
                        {
                            clipboardAccessToken.ClearContents();
                            clipboardAccessToken.SetAsUrl(exportInformation.Uri);
                        }
                    }
                }

                if (_externalCommandDefinition.CommandBehavior.HasFlag(CommandBehaviors.DeleteOnExit))
                {
                    File.Delete(fullPath);
                }
            }

            ProcessExport(exportInformation, surface);
            return(exportInformation);
        }
        /// <summary>
        /// Create the full-blown Clip object
        /// </summary>
        /// <param name="clipboardUpdateInformation">ClipboardContents</param>
        /// <returns>Clip</returns>
        private Clip CreateClip(ClipboardUpdateInformation clipboardUpdateInformation)
        {
            if (clipboardUpdateInformation.OwnerHandle == IntPtr.Zero)
            {
                // TODO: Handle "0" here!!!
                Log.Warn().WriteLine("Clipboard content is owned by process 0");
            }
            var interopWindow = InteropWindowFactory.CreateFor(clipboardUpdateInformation.OwnerHandle);

            // Make sure we use the parent window (top level) for the title.
            IInteropWindow toplevelWindow = interopWindow;
            var            parent         = toplevelWindow.GetParent();

            while (true)
            {
                if (parent == IntPtr.Zero)
                {
                    break;
                }
                toplevelWindow = toplevelWindow?.GetParentWindow();
                parent         = toplevelWindow.GetParent();
            }
            var  caption = toplevelWindow.GetCaption();
            Clip clip;

            using (var process = Process.GetProcessById(interopWindow.GetProcessId()))
            {
                // Make sure we got something, when the caption is emtry up to now
                if (string.IsNullOrEmpty(caption))
                {
                    caption = process.MainWindowTitle;
                }

                // Try to create the product name
                string productName = process.ProcessName;

                try
                {
                    var versionInfo = FileVersionInfo.GetVersionInfo(process.MainModule.FileName);
                    productName = versionInfo.ProductName;
                }
                catch (Win32Exception ex)
                {
                    // This happens with elevated processes
                    Log.Warn().WriteLine(ex, "Problem retrieving process information for a process with ID {0} and name {1}", process.Id, process.ProcessName);
                }

                clip = new Clip
                {
                    WindowTitle          = caption,
                    OwnerIcon            = interopWindow.GetIcon <BitmapSource>(true) ?? toplevelWindow.GetIcon <BitmapSource>(true),
                    SessionId            = _currentSession.Id,
                    ProcessName          = process.ProcessName,
                    ProductName          = productName,
                    OriginalWindowHandle = clipboardUpdateInformation.OwnerHandle,
                    SequenceNumber       = clipboardUpdateInformation.Id,
                    OriginalFormats      = clipboardUpdateInformation.Formats.ToList()
                };
            }

            using (var clipboardAccessToken = ClipboardNative.Access())
            {
                clip.Filenames = clipboardAccessToken.GetFilenames().ToList();
                if (clip.OriginalFormats.Contains("CF_UNICODETEXT"))
                {
                    clip.ClipboardText = clipboardAccessToken.GetAsUnicodeString();
                }

                foreach (var format in clipboardUpdateInformation.Formats)
                {
                    if (!_dopyConfiguration.IncludeFormats.Contains(format))
                    {
                        continue;
                    }
                    clip.Formats.Add(format);
                    using var clipboardStream = clipboardAccessToken.GetAsStream(format);
                    var memoryStream = new MemoryStream((int)clipboardStream.Length);
                    clipboardStream.CopyTo(memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    clip.Contents[format] = memoryStream;
                }
            }
            return(clip);
        }
        /// <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);
        }
Exemple #24
0
        /// <summary>
        /// Upload the capture to lutim
        /// </summary>
        /// <param name="surfaceToUpload">ISurface</param>
        /// <returns>true if the upload succeeded</returns>
        private async Task <string> Upload(ISurface surfaceToUpload)
        {
            string uploadUrl;

            try
            {
                LutimInfo lutimInfo;

                var cancellationTokenSource = new CancellationTokenSource();
                using (var ownedPleaseWaitForm = _pleaseWaitFormFactory(cancellationTokenSource))
                {
                    ownedPleaseWaitForm.Value.SetDetails("Lutim", _lutimLanguage.CommunicationWait);
                    ownedPleaseWaitForm.Value.Show();
                    try
                    {
                        lutimInfo = await _lutimApi.UploadToLutim(surfaceToUpload).ConfigureAwait(true);

                        if (lutimInfo != null)
                        {
                            Log.Info().WriteLine("Storing lutim upload for hash {0} and delete hash {1}",
                                                 lutimInfo.Short, lutimInfo.Token);
                            // TODO: Write somewhere
                            // _lutimConfiguration.LutimUploadHistory.Add(lutimInfo.Short, lutimInfo.ToIniString());
                            _lutimConfiguration.RuntimeLutimHistory.Add(lutimInfo.Short, lutimInfo);
                            // TODO: Update
                            // UpdateHistoryMenuItem();
                        }
                    }
                    finally
                    {
                        ownedPleaseWaitForm.Value.Close();
                    }
                }


                if (lutimInfo != null)
                {
                    uploadUrl = lutimInfo.Short;
                    if (string.IsNullOrEmpty(uploadUrl) || !_lutimConfiguration.CopyLinkToClipboard)
                    {
                        return(uploadUrl);
                    }
                    try
                    {
                        using (var clipboardAccessToken = ClipboardNative.Access())
                        {
                            clipboardAccessToken.ClearContents();
                            clipboardAccessToken.SetAsUrl(uploadUrl);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error().WriteLine(ex, "Can't write to clipboard: ");
                        return(null);
                    }
                    return(uploadUrl);
                }
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Error uploading.");
                MessageBox.Show(_lutimLanguage.UploadFailure + " " + e.Message);
            }
            return(null);
        }