Example #1
0
        private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            _requestData = e.Request.Data;

            _requestData.Properties.Title = _title;
            _requestData.Properties.Description = _description;
            _requestData.SetWebLink(new Uri(_imageUrl));
        }
		partial void HandleShareRequested(string shareLink)
		{
			var dataPackage = new DataPackage();
			dataPackage.SetText(shareLink);
            dataPackage.SetWebLink(new Uri(shareLink));
			Clipboard.SetContent(dataPackage);

			var notificationService = SimpleIoc.Default.GetInstance<NotificationService>();
			notificationService.ShowToast("File shared", "A link has been copied to the clipboard", "Assets/Logo.scale-100.png");

			this.Complete();
		}
        private async Task CopyLink(File file)
        {
            this.IsLoading = true;
            try
            {
                var link = await this.client.GetPublicFileLinkAsync(file.FileId, null);
                var dataPackage = new DataPackage();
                dataPackage.SetText(link);
                dataPackage.SetWebLink(new Uri(link));
                Clipboard.SetContent(dataPackage);

                var notificationService = SimpleIoc.Default.GetInstance<NotificationService>();
                notificationService.ShowToast("File(s) shared", "A link has been copied to the clipboard", "Assets/Logo.scale-100.png");
            }
            finally
            {
                this.IsLoading = false;
            }
        }
Example #4
0
 async   void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
    {
        DataRequest request = args.Request;
        //We are going to use an async API to talk to the webview, so get a deferral for the results
        DataRequestDeferral deferral = args.Request.GetDeferral();
        DataPackage dp = await homewebview.CaptureSelectedContentToDataPackageAsync();
        if (dp != null && dp.GetView().AvailableFormats.Count >0)
        { // Webview has a selection, so we'll share its data package
            dp.Properties.Title = "来自多彩浏览器的分享";
            request.Data = dp;
        }
        else { 
            // No selection, so we'll share the url of the webview
            DataPackage myData = new DataPackage();
            myData.SetWebLink(homewebview.Source);
            myData.Properties.Title = "来自多彩浏览器的分享";
            myData.Properties.Description = homewebview.Source.ToString();
            request.Data = myData; }
        deferral.Complete();
    }
        /// <summary>
        /// Sets the current web link content that is stored in the clipboard.
        /// </summary>
        /// <param name="content">The web link content that is stored in the clipboard.</param>
        public virtual void SetWebLink(Uri content)
        {
            var package = new DataPackage();

            package.SetWebLink(content);

            Clipboard.SetContent(package);
        }
        /// <summary>
        /// Raised when the user initiates a Share operation.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        async void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            DataRequest request = args.Request;
            // We are going to use an async API to talk to the webview, so get a deferral to give
            // us time to generate the results.
            DataRequestDeferral deferral = request.GetDeferral();
            DataPackage dp = await WebViewControl.CaptureSelectedContentToDataPackageAsync();

            // Determine whether there was any selected content.
            bool hasSelection = false;
            try
            {
                hasSelection = (dp != null) && (dp.GetView().AvailableFormats.Count > 0);
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                    case unchecked((int)0x80070490):
                        // Mobile does not generate a data package with AvailableFormats
                        // and results in an exception. Sorry. Handle the case by acting as
                        // if we had no selected content.
                        hasSelection = false;
                        break;

                    default:
                        // All other exceptions are unexpected. Let them propagate.
                        throw;
                }
            }

            if (hasSelection)
            {
                // Webview has a selection, so we'll share its data package.
                dp.Properties.Title = "WebView sample selected content";
            }
            else
            {
                // No selection, so we'll share the url of the webview.
                dp = new DataPackage();
                dp.SetWebLink(WebViewControl.Source);
                dp.Properties.Title = "WebView sample page";
            }
            dp.Properties.Description = WebViewControl.Source.ToString();
            request.Data = dp;

            deferral.Complete();
        }
Example #7
0
        private static DataPackageView GetFromNative(NSPasteboard pasteboard)
        {
            if (pasteboard is null)
            {
                throw new ArgumentException(nameof(pasteboard));
            }

            var dataPackage = new DataPackage();

            // Extract all the standard data format information from the pasteboard items.
            // Each format can only be used once; therefore, generally the last occurrence of the format will be the one used.
            foreach (NSPasteboardItem item in pasteboard.PasteboardItems)
            {
                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeTIFF) ||
                    item.Types.Contains(NSPasteboard.NSPasteboardTypePNG))
                {
                    // Images may be very large, we never want to load them until they are needed.
                    // Therefore, create a data provider used to asynchronously fetch the image.
                    dataPackage.SetDataProvider(
                        StandardDataFormats.Bitmap,
                        async cancellationToken =>
                    {
                        NSImage?image = null;

                        /* Some apps, including Photos, don't appear to put image data in the pasteboard.
                         * Instead, the image URL is provided although the type indicates it is an image.
                         *
                         * To get around this an image is read as follows:
                         *   (1) If the pasteboard contains an image type then:
                         *   (2) Attempt to read the image as an object (NSImage).
                         *       This may fail as some tested apps provide a URL although declare an image (Photos).
                         *       With other apps (such as web browsers) an image will be read correctly here.
                         *   (3) If reading as an NSImage object fails, attempt to read the image from a file URL (local images)
                         *   (4) If reading from a file URL fails, attempt to read the image from a URL (remote images)
                         *
                         * Reading as an NSImage object follows the docs here:
                         *   https://docs.microsoft.com/en-us/xamarin/mac/app-fundamentals/copy-paste#add-an-nsdocument
                         */

                        var classArray = new Class[] { new Class("NSImage") };
                        if (pasteboard.CanReadObjectForClasses(classArray, null))
                        {
                            NSObject[] objects = pasteboard.ReadObjectsForClasses(classArray, null);

                            if (objects.Length > 0)
                            {
                                // Only use the first image found
                                image = objects[0] as NSImage;
                            }
                        }

                        // In order to get here the pasteboard must have declared it had image types.
                        // However, if image is null, no objects were found and the image is likely a URL instead.
                        if (image == null &&
                            item.Types.Contains(NSPasteboard.NSPasteboardTypeFileUrl))
                        {
                            var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeFileUrl);
                            image   = new NSImage(new NSUrl(url));
                        }

                        if (image == null &&
                            item.Types.Contains(NSPasteboard.NSPasteboardTypeUrl))
                        {
                            var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeUrl);
                            image   = new NSImage(new NSUrl(url));
                        }

                        if (image != null)
                        {
                            // Thanks to: https://stackoverflow.com/questions/13305028/monomac-best-way-to-convert-bitmap-to-nsimage/13355747
                            using (var imageData = image.AsTiff())
                            {
                                var imgRep = NSBitmapImageRep.ImageRepFromData(imageData !) as NSBitmapImageRep;
                                var data   = imgRep !.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, null);

                                return(new RandomAccessStreamReference(async ct =>
                                {
                                    return data.AsStream().AsRandomAccessStream().TrySetContentType("image/png");
                                }));
                            }
                        }
                        else
                        {
                            // Return an empty image
                            return(new RandomAccessStreamReference(async ct =>
                            {
                                var stream = new MemoryStream();
                                stream.Position = 0;

                                return stream.AsRandomAccessStream().TrySetContentType("image/png");
                            }));
                        }
                    });
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeHTML))
                {
                    var html = item.GetStringForType(NSPasteboard.NSPasteboardTypeHTML);
                    if (html != null)
                    {
                        dataPackage.SetHtmlFormat(html);
                    }
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeRTF))
                {
                    var rtf = item.GetStringForType(NSPasteboard.NSPasteboardTypeRTF);
                    if (rtf != null)
                    {
                        dataPackage.SetRtf(rtf);
                    }
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeFileUrl))
                {
                    // Drag and drop will use temporary URLs similar to: file:///.file/id=1234567.1234567
                    var tempFileUrl = item.GetStringForType(NSPasteboard.NSPasteboardTypeFileUrl);

                    // Files may be very large, we never want to load them until they are needed.
                    // Therefore, create a data provider used to asynchronously fetch the file.
                    dataPackage.SetDataProvider(
                        StandardDataFormats.StorageItems,
                        async cancellationToken =>
                    {
                        // Convert from a temp Url (see above example) into an absolute file path
                        var fileUrl = new NSUrl(tempFileUrl);
                        var file    = await StorageFile.GetFileFromPathAsync(fileUrl.FilePathUrl.AbsoluteString);

                        var storageItems = new List <IStorageItem>();
                        storageItems.Add(file);

                        return(storageItems.AsReadOnly());
                    });
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeString))
                {
                    var text = item.GetStringForType(NSPasteboard.NSPasteboardTypeString);
                    if (text != null)
                    {
                        dataPackage.SetText(text);
                    }
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeUrl))
                {
                    var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeUrl);
                    if (url != null)
                    {
                        DataPackage.SeparateUri(
                            url,
                            out string?webLink,
                            out string?applicationLink);

                        if (webLink != null)
                        {
                            dataPackage.SetWebLink(new Uri(webLink));
                        }

                        if (applicationLink != null)
                        {
                            dataPackage.SetApplicationLink(new Uri(applicationLink));
                        }

                        // Deprecated but still added for compatibility
                        dataPackage.SetUri(new Uri(url));
                    }
                }
            }

            return(dataPackage.GetView());
        }
		private static void FillPackage(StorageFile[] files, DataPackage package, object subShareItem)
		{
			if (subShareItem != null)
			{
				switch (subShareItem.GetType().Name)
				{
					case nameof(TextShareItem):
						{
							package.SetText((subShareItem as TextShareItem).Text);
						}
						break;
					case nameof(ApplicationLinkShareItem):
						{
							var sitm = subShareItem as ApplicationLinkShareItem;
							package.SetApplicationLink(sitm.ApplicationLink);
						}
						break;

					case nameof(DelayRenderedImageShareItem):
						{
							var sitm = subShareItem as DelayRenderedImageShareItem;
							package.SetBitmap(RandomAccessStreamReference.CreateFromStream(sitm.SelectedImage.GetRandowmAccessStream()));
						}
						break;

					case nameof(FilesShareItem):
						{
							StorageFile[] resultArray = files;
							package.SetStorageItems(resultArray);
						}
						break;
					case nameof(HtmlShareItem):
						{
							var sitm = subShareItem as HtmlShareItem;

							var fmt = HtmlFormatHelper.CreateHtmlFormat(sitm.HtmlFragment);
							package.SetHtmlFormat(fmt);
							package.SetText(sitm.HtmlFragment);

						}
						break;
					case nameof(WebLinkShareItem):
						{
							var sitm = subShareItem as WebLinkShareItem;
							package.SetWebLink(sitm.WebLink);
							package.SetText(sitm.WebLink?.ToString());

						}
						break;

					default:
						break;
				}

			}
		}
Example #9
0
        public static DataPackageView GetContent()
        {
            var dataPackage = new DataPackage();

            var manager = ContextHelper.Current.GetSystemService(Context.ClipboardService) as ClipboardManager;

            if (manager is null)
            {
                return(dataPackage.GetView());
            }

            var clipData = manager.PrimaryClip;

            Uri /* ? */    clipApplicationLink = null;
            string /* ? */ clipHtml            = null;
            string /* ? */ clipText            = null;
            Uri /* ? */    clipUri             = null;
            Uri /* ? */    clipWebLink         = null;

            // Extract all the standard data format information from the clipboard.
            // Each format can only be used once; therefore, the last occurrence of the format will be the one used.
            if (clipData != null)
            {
                for (int itemIndex = 0; itemIndex < clipData.ItemCount; itemIndex++)
                {
                    var item = clipData.GetItemAt(itemIndex);

                    if (item != null)
                    {
                        var itemText = item.Text;
                        if (itemText != null)
                        {
                            clipText = itemText;
                        }

                        // An Android Uri must be specially mapped for UWP as the UWP's direct equivalent
                        // standard data format 'Uri' is deprecated.
                        //
                        // 1. WebLink is used if the URI has a scheme of http or https
                        // 2. ApplicationLink is used if not #1
                        //
                        // For full compatibility, Uri is still populated regardless of #1 or #2.
                        var itemUri    = item.Uri;
                        var itemUriStr = itemUri?.ToString();
                        if (itemUriStr != null)
                        {
                            if (itemUriStr.StartsWith("http", StringComparison.InvariantCultureIgnoreCase) ||
                                itemUriStr.StartsWith("https", StringComparison.InvariantCultureIgnoreCase))
                            {
                                clipWebLink = new Uri(itemUriStr);
                            }
                            else
                            {
                                clipApplicationLink = new Uri(itemUriStr);
                            }

                            // Deprecated but added for compatibility
                            clipUri = new Uri(itemUriStr);
                        }

                        var itemHtml = item.HtmlText;
                        if (itemText != null)
                        {
                            clipHtml = itemHtml;
                        }
                    }
                }
            }

            // Add standard data formats to the data package.
            // This can be done synchronously on Android since the data is already available from above.
            if (clipApplicationLink != null)
            {
                dataPackage.SetApplicationLink(clipApplicationLink);
            }

            if (clipHtml != null)
            {
                dataPackage.SetHtmlFormat(clipHtml);
            }

            if (clipText != null)
            {
                dataPackage.SetText(clipText);
            }

            if (clipUri != null)
            {
                dataPackage.SetUri(clipUri);
            }

            if (clipWebLink != null)
            {
                dataPackage.SetWebLink(clipWebLink);
            }

            return(dataPackage.GetView());
        }
 /// <summary>
 /// Копировать ссылку в клипборд.
 /// </summary>
 public async void CopyLink()
 {
     try
     {
         var webLink = link.GetWebLink();
         if (webLink != null)
         {
             var dp = new DataPackage();
             dp.SetText(webLink.ToString());
             dp.SetWebLink(webLink);
             Clipboard.SetContent(dp);
             Clipboard.Flush();
         }
     }
     catch (Exception ex)
     {
         await AppHelpers.ShowError(ex);
     }
 }
Example #11
0
        public static DataPackageView GetContent()
        {
            var dataPackage = new DataPackage();

            var manager = ContextHelper.Current.GetSystemService(Context.ClipboardService) as ClipboardManager;

            if (manager is null)
            {
                return(dataPackage.GetView());
            }

            var clipData = manager.PrimaryClip;

            Uri /* ? */    clipApplicationLink = null;
            string /* ? */ clipHtml            = null;
            string /* ? */ clipText            = null;
            Uri /* ? */    clipUri             = null;
            Uri /* ? */    clipWebLink         = null;

            // Extract all the standard data format information from the clipboard.
            // Each format can only be used once; therefore, the last occurrence of the format will be the one used.
            if (clipData != null)
            {
                for (int itemIndex = 0; itemIndex < clipData.ItemCount; itemIndex++)
                {
                    var item = clipData.GetItemAt(itemIndex);

                    if (item != null)
                    {
                        var itemText = item.Text;
                        if (itemText != null)
                        {
                            clipText = itemText;
                        }

                        var itemUriStr = item.Uri?.ToString();
                        if (itemUriStr != null)
                        {
                            DataPackage.SeparateUri(
                                itemUriStr,
                                out string webLink,
                                out string applicationLink);

                            clipWebLink         = webLink != null ? new Uri(webLink) : null;
                            clipApplicationLink = applicationLink != null ? new Uri(applicationLink) : null;
                            clipUri             = new Uri(itemUriStr);                             // Deprecated but still added for compatibility
                        }

                        var itemHtml = item.HtmlText;
                        if (itemHtml != null)
                        {
                            clipHtml = itemHtml;
                        }
                    }
                }
            }

            // Add standard data formats to the data package.
            // This can be done synchronously on Android since the data is already available from above.
            if (clipApplicationLink != null)
            {
                dataPackage.SetApplicationLink(clipApplicationLink);
            }

            if (clipHtml != null)
            {
                dataPackage.SetHtmlFormat(clipHtml);
            }

            if (clipText != null)
            {
                dataPackage.SetText(clipText);
            }

            if (clipUri != null)
            {
                dataPackage.SetUri(clipUri);
            }

            if (clipWebLink != null)
            {
                dataPackage.SetWebLink(clipWebLink);
            }

            return(dataPackage.GetView());
        }
Example #12
0
 private async void CopyMediaLinkFlyoutItem_OnClick(object sender, RoutedEventArgs e)
 {
     try
     {
         var f = sender as FrameworkElement;
         var t = f?.Tag as IPostMediaFileViewModel;
         if (t?.WebLink != null)
         {
             var dp = new DataPackage();
             dp.SetText(t.WebLink);
             dp.SetWebLink(new Uri(t.WebLink, UriKind.Absolute));
             Clipboard.SetContent(dp);
             Clipboard.Flush();
         }
     }
     catch (Exception ex)
     {
         await AppHelpers.ShowError(ex);
     }
 }
 private async void CopyLinkFlyoutItem_OnClick(object sender, RoutedEventArgs e)
 {
     try
     {
         var f = sender as FrameworkElement;
         var t = f?.Tag as IPostViewModel;
         if (t?.Link != null)
         {
             var uri = t.Link.GetWebLink();
             if (uri != null)
             {
                 var dp = new DataPackage();
                 dp.SetText(uri.ToString());
                 dp.SetWebLink(uri);
                 Clipboard.SetContent(dp);
                 Clipboard.Flush();
             }
         }
     }
     catch (Exception ex)
     {
         await AppHelpers.ShowError(ex);
     }
 }