Exemplo n.º 1
0
        /// <summary>
        /// 提供图片转码
        /// </summary>
        /// <param name="SourceFile">源文件</param>
        /// <param name="DestinationFile">目标文件</param>
        /// <param name="IsEnableScale">是否启用缩放</param>
        /// <param name="ScaleWidth">缩放宽度</param>
        /// <param name="ScaleHeight">缩放高度</param>
        /// <param name="InterpolationMode">插值模式</param>
        /// <returns></returns>
        public static Task TranscodeFromImageAsync(StorageFile SourceFile, StorageFile DestinationFile, bool IsEnableScale = false, uint ScaleWidth = default, uint ScaleHeight = default, BitmapInterpolationMode InterpolationMode = default)
        {
            return Task.Run(() =>
            {
                IsAnyTransformTaskRunning = true;

                using (IRandomAccessStream OriginStream = SourceFile.OpenAsync(FileAccessMode.Read).AsTask().Result)
                {
                    BitmapDecoder Decoder = BitmapDecoder.CreateAsync(OriginStream).AsTask().Result;
                    using (IRandomAccessStream TargetStream = DestinationFile.OpenAsync(FileAccessMode.ReadWrite).AsTask().Result)
                    using (SoftwareBitmap TranscodeImage = Decoder.GetSoftwareBitmapAsync().AsTask().Result)
                    {
                        BitmapEncoder Encoder = DestinationFile.FileType switch
                        {
                            ".png" => BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, TargetStream).AsTask().Result,
                            ".jpg" => BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, TargetStream).AsTask().Result,
                            ".bmp" => BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, TargetStream).AsTask().Result,
                            ".heic" => BitmapEncoder.CreateAsync(BitmapEncoder.HeifEncoderId, TargetStream).AsTask().Result,
                            ".tiff" => BitmapEncoder.CreateAsync(BitmapEncoder.TiffEncoderId, TargetStream).AsTask().Result,
                            _ => throw new InvalidOperationException("Unsupport image format"),
                        };

                        if (IsEnableScale)
                        {
                            Encoder.BitmapTransform.ScaledWidth = ScaleWidth;
                            Encoder.BitmapTransform.ScaledHeight = ScaleHeight;
                            Encoder.BitmapTransform.InterpolationMode = InterpolationMode;
                        }

                        Encoder.SetSoftwareBitmap(TranscodeImage);
                        Encoder.IsThumbnailGenerated = true;
                        try
                        {
                            Encoder.FlushAsync().AsTask().Wait();
                        }
                        catch (Exception err)
                        {
                            if (err.HResult == unchecked((int)0x88982F81))
                            {
                                Encoder.IsThumbnailGenerated = false;
                                Encoder.FlushAsync().AsTask().Wait();
                            }
                            else
                            {
                                try
                                {
                                    DestinationFile.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                                }
                                catch
                                {

                                }

                                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                {
                                    QueueContentDialog dialog = new QueueContentDialog
                                    {
                                        Title = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                        Content = Globalization.GetString("EnDecode_Dialog_Content"),
                                        CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                    };
                                    _ = await dialog.ShowAsync().ConfigureAwait(true);
                                }).AsTask().Wait();
                            }
                        }
                    }
                }

                IsAnyTransformTaskRunning = false;
            });
        }
Exemplo n.º 2
0
        public static async Task SetCommandBarFlyoutWithExtraContextMenuItems(this ListViewBase ListControl, CommandBarFlyout Flyout, Point ShowAt)
        {
            if (Flyout == null)
            {
                throw new ArgumentNullException(nameof(Flyout), "Argument could not be null");
            }

            if (Interlocked.Exchange(ref ContextMenuLockResource, 1) == 0)
            {
                try
                {
                    if (ApplicationData.Current.LocalSettings.Values["ContextMenuExtSwitch"] is bool IsExt && !IsExt)
                    {
                        foreach (AppBarButton ExtraButton in Flyout.SecondaryCommands.OfType <AppBarButton>().Where((Btn) => Btn.Name == "ExtraButton").ToArray())
                        {
                            Flyout.SecondaryCommands.Remove(ExtraButton);
                        }

                        foreach (AppBarSeparator Separator in Flyout.SecondaryCommands.OfType <AppBarSeparator>().Where((Sep) => Sep.Name == "CustomSep").ToArray())
                        {
                            Flyout.SecondaryCommands.Remove(Separator);
                        }
                    }
                    else
                    {
                        string[] SelectedPathArray = null;

                        if (ListControl.SelectedItems.Count <= 1)
                        {
                            if (ListControl.SelectedItem is FileSystemStorageItemBase Selected)
                            {
                                SelectedPathArray = new string[] { Selected.Path };
                            }
                            else if (ListControl.FindParentOfType <FileControl>() is FileControl Control && !string.IsNullOrEmpty(Control.CurrentPresenter.CurrentFolder?.Path))
                            {
                                SelectedPathArray = new string[] { Control.CurrentPresenter.CurrentFolder.Path };
                            }
                        }
                        else
                        {
                            SelectedPathArray = ListControl.SelectedItems.OfType <FileSystemStorageItemBase>().Select((Item) => Item.Path).ToArray();
                        }

                        if (SelectedPathArray != null)
                        {
                            using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
                            {
                                List <ContextMenuItem> ExtraMenuItems = await Exclusive.Controller.GetContextMenuItemsAsync(SelectedPathArray, Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down)).ConfigureAwait(true);

                                foreach (AppBarButton ExtraButton in Flyout.SecondaryCommands.OfType <AppBarButton>().Where((Btn) => Btn.Name == "ExtraButton").ToArray())
                                {
                                    Flyout.SecondaryCommands.Remove(ExtraButton);
                                }

                                foreach (AppBarSeparator Separator in Flyout.SecondaryCommands.OfType <AppBarSeparator>().Where((Sep) => Sep.Name == "CustomSep").ToArray())
                                {
                                    Flyout.SecondaryCommands.Remove(Separator);
                                }

                                if (ExtraMenuItems.Count > 0)
                                {
                                    async void ClickHandler(object sender, RoutedEventArgs args)
                                    {
                                        if (sender is FrameworkElement Btn)
                                        {
                                            if (Btn.Tag is ContextMenuItem MenuItem)
                                            {
                                                Flyout.Hide();

                                                if (!await MenuItem.InvokeAsync().ConfigureAwait(true))
                                                {
                                                    QueueContentDialog Dialog = new QueueContentDialog
                                                    {
                                                        Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                                        Content         = Globalization.GetString("QueueDialog_InvokeContextMenuError_Content"),
                                                        CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                                    };

                                                    await Dialog.ShowAsync().ConfigureAwait(true);
                                                }
                                            }
                                        }
                                    }

                                    short ShowExtNum = Convert.ToInt16(Math.Max(9 - Flyout.SecondaryCommands.Count((Item) => Item is AppBarButton), 0));

                                    int Index = Flyout.SecondaryCommands.IndexOf(Flyout.SecondaryCommands.OfType <AppBarSeparator>().FirstOrDefault()) + 1;

                                    if (ExtraMenuItems.Count > ShowExtNum + 1)
                                    {
                                        Flyout.SecondaryCommands.Insert(Index, new AppBarSeparator {
                                            Name = "CustomSep"
                                        });

                                        foreach (ContextMenuItem AddItem in ExtraMenuItems.Take(ShowExtNum))
                                        {
                                            Flyout.SecondaryCommands.Insert(Index, await AddItem.GenerateUIButtonAsync(ClickHandler).ConfigureAwait(true));
                                        }

                                        AppBarButton MoreItem = new AppBarButton
                                        {
                                            Label    = Globalization.GetString("CommandBarFlyout_More_Item"),
                                            Icon     = new SymbolIcon(Symbol.More),
                                            Name     = "ExtraButton",
                                            MinWidth = 250
                                        };

                                        MenuFlyout MoreFlyout = new MenuFlyout();

                                        await ContextMenuItem.GenerateSubMenuItemsAsync(MoreFlyout.Items, ExtraMenuItems.Skip(ShowExtNum).ToArray(), ClickHandler).ConfigureAwait(true);

                                        MoreItem.Flyout = MoreFlyout;

                                        Flyout.SecondaryCommands.Insert(Index + ShowExtNum, MoreItem);
                                    }
                                    else
                                    {
                                        foreach (ContextMenuItem AddItem in ExtraMenuItems)
                                        {
                                            Flyout.SecondaryCommands.Insert(Index, await AddItem.GenerateUIButtonAsync(ClickHandler).ConfigureAwait(true));
                                        }

                                        Flyout.SecondaryCommands.Insert(Index + ExtraMenuItems.Count, new AppBarSeparator {
                                            Name = "CustomSep"
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
Exemplo n.º 3
0
        /// <summary>
        /// 更新支持或反对的信息
        /// </summary>
        /// <param name="Type">更新类型</param>
        private async void UpdateSupportInfo(FeedBackUpdateType Type)
        {
            switch (Type)
            {
            case FeedBackUpdateType.AddLike:
            {
                if (UserVoteAction == "-")
                {
                    DislikeNum = (Convert.ToInt16(DislikeNum) - 1).ToString();
                }

                LikeNum        = (Convert.ToInt16(LikeNum) + 1).ToString();
                UserVoteAction = "+";
                break;
            }

            case FeedBackUpdateType.DelLike:
            {
                LikeNum        = (Convert.ToInt16(LikeNum) - 1).ToString();
                UserVoteAction = "=";
                break;
            }

            case FeedBackUpdateType.AddDislike:
            {
                if (UserVoteAction == "+")
                {
                    LikeNum = (Convert.ToInt16(LikeNum) - 1).ToString();
                }

                DislikeNum     = (Convert.ToInt16(DislikeNum) + 1).ToString();
                UserVoteAction = "-";
                break;
            }

            case FeedBackUpdateType.DelDislike:
            {
                DislikeNum     = (Convert.ToInt16(DislikeNum) - 1).ToString();
                UserVoteAction = "=";
                break;
            }
            }

            SupportDescription = $"({LikeNum} {Globalization.GetString("FeedBackItem_SupportDescription_Positive")} , {DislikeNum} {Globalization.GetString("FeedBackItem_SupportDescription_Negative")})";

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SupportDescription)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsLike)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsDislike)));

            await Task.Run(() =>
            {
                Locker.WaitOne();
            }).ConfigureAwait(true);

            try
            {
                if (!await MySQL.Current.UpdateFeedBackVoteAsync(this).ConfigureAwait(true))
                {
                    QueueContentDialog dialog = new QueueContentDialog
                    {
                        Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                        Content         = Globalization.GetString("Network_Error_Dialog_Content"),
                        CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                    };
                    _ = await dialog.ShowAsync().ConfigureAwait(true);
                }
            }
            finally
            {
                Locker.Set();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 提供图片转码
        /// </summary>
        /// <param name="SourceFile">源文件</param>
        /// <param name="DestinationFile">目标文件</param>
        /// <param name="IsEnableScale">是否启用缩放</param>
        /// <param name="ScaleWidth">缩放宽度</param>
        /// <param name="ScaleHeight">缩放高度</param>
        /// <param name="InterpolationMode">插值模式</param>
        /// <returns></returns>
        public static async Task TranscodeFromImageAsync(FileSystemStorageFile SourceFile, FileSystemStorageFile DestinationFile, bool IsEnableScale = false, uint ScaleWidth = default, uint ScaleHeight = default, BitmapInterpolationMode InterpolationMode = default)
        {
            try
            {
                IsAnyTransformTaskRunning = true;

                using (ExtendedExecutionController ExtExecution = await ExtendedExecutionController.TryCreateExtendedExecution())
                    using (IRandomAccessStream OriginStream = await SourceFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read).ConfigureAwait(false))
                    {
                        try
                        {
                            BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(OriginStream);

                            using (SoftwareBitmap TranscodeImage = await Decoder.GetSoftwareBitmapAsync())
                                using (IRandomAccessStream TargetStream = await DestinationFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.ReadWrite).ConfigureAwait(false))
                                {
                                    BitmapEncoder Encoder = DestinationFile.Type.ToLower() switch
                                    {
                                        ".png" => await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, TargetStream),
                                        ".jpg" => await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, TargetStream),
                                        ".bmp" => await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, TargetStream),
                                        ".heic" => await BitmapEncoder.CreateAsync(BitmapEncoder.HeifEncoderId, TargetStream),
                                        ".tiff" => await BitmapEncoder.CreateAsync(BitmapEncoder.TiffEncoderId, TargetStream),
                                        _ => throw new InvalidOperationException("Unsupport image format"),
                                    };

                                    if (IsEnableScale)
                                    {
                                        Encoder.BitmapTransform.ScaledWidth       = ScaleWidth;
                                        Encoder.BitmapTransform.ScaledHeight      = ScaleHeight;
                                        Encoder.BitmapTransform.InterpolationMode = InterpolationMode;
                                    }

                                    Encoder.SetSoftwareBitmap(TranscodeImage);

                                    await Encoder.FlushAsync();
                                }
                        }
                        catch (Exception)
                        {
                            await DestinationFile.DeleteAsync(true);

                            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                            {
                                QueueContentDialog dialog = new QueueContentDialog
                                {
                                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                    Content         = Globalization.GetString("EnDecode_Dialog_Content"),
                                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                };

                                _ = await dialog.ShowAsync();
                            });
                        }
                    }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex);
            }
            finally
            {
                IsAnyTransformTaskRunning = false;
            }
        }
        public async Task MoveAsync(IEnumerable <string> Source, string DestinationPath, ProgressChangedEventHandler ProgressHandler = null, bool IsUndoOperation = false)
        {
            if (Source == null)
            {
                throw new ArgumentNullException(nameof(Source), "Parameter could not be null");
            }

            try
            {
                IsNowHasAnyActionExcuting = true;

                if (await TryConnectToFullTrustExutor().ConfigureAwait(true))
                {
                    List <KeyValuePair <string, string> > MessageList = new List <KeyValuePair <string, string> >();

                    foreach (string SourcePath in Source)
                    {
                        try
                        {
                            _ = await StorageFile.GetFileFromPathAsync(SourcePath);

                            MessageList.Add(new KeyValuePair <string, string>(SourcePath, string.Empty));
                        }
                        catch
                        {
                            try
                            {
                                StorageFolder TargetFolder = await StorageFolder.GetFolderFromPathAsync(DestinationPath);

                                if (await TargetFolder.TryGetItemAsync(Path.GetFileName(SourcePath)) is StorageFolder ExistFolder)
                                {
                                    QueueContentDialog Dialog = new QueueContentDialog
                                    {
                                        Title             = Globalization.GetString("Common_Dialog_WarningTitle"),
                                        Content           = $"{Globalization.GetString("QueueDialog_FolderRepeat_Content")} {ExistFolder.Name}",
                                        PrimaryButtonText = Globalization.GetString("QueueDialog_FolderRepeat_PrimaryButton"),
                                        CloseButtonText   = Globalization.GetString("QueueDialog_FolderRepeat_CloseButton")
                                    };

                                    if (await Dialog.ShowAsync().ConfigureAwait(false) != ContentDialogResult.Primary)
                                    {
                                        StorageFolder NewFolder = await TargetFolder.CreateFolderAsync(Path.GetFileName(SourcePath), CreationCollisionOption.GenerateUniqueName);

                                        MessageList.Add(new KeyValuePair <string, string>(SourcePath, NewFolder.Name));
                                    }
                                    else
                                    {
                                        MessageList.Add(new KeyValuePair <string, string>(SourcePath, string.Empty));
                                    }
                                }
                                else
                                {
                                    MessageList.Add(new KeyValuePair <string, string>(SourcePath, string.Empty));
                                }
                            }
                            catch
                            {
                                throw new FileNotFoundException();
                            }
                        }
                    }

                    Task ProgressTask;

                    if (await PipeLineController.Current.CreateNewNamedPipe().ConfigureAwait(true))
                    {
                        ProgressTask = PipeLineController.Current.ListenPipeMessage(ProgressHandler);
                    }
                    else
                    {
                        ProgressTask = Task.CompletedTask;
                    }

                    ValueSet Value = new ValueSet
                    {
                        { "ExcuteType", ExcuteType_Move },
                        { "SourcePath", JsonConvert.SerializeObject(MessageList) },
                        { "DestinationPath", DestinationPath },
                        { "Guid", PipeLineController.Current.GUID.ToString() },
                        { "Undo", IsUndoOperation }
                    };

                    Task <AppServiceResponse> MessageTask = Connection.SendMessageAsync(Value).AsTask();

                    await Task.WhenAll(MessageTask, ProgressTask).ConfigureAwait(true);

                    if (MessageTask.Result.Status == AppServiceResponseStatus.Success)
                    {
                        if (MessageTask.Result.Message.ContainsKey("Success"))
                        {
                            if (MessageTask.Result.Message.TryGetValue("OperationRecord", out object value))
                            {
                                OperationRecorder.Current.Value.Push(JsonConvert.DeserializeObject <List <string> >(Convert.ToString(value)));
                            }
                        }
                        else if (MessageTask.Result.Message.ContainsKey("Error_NotFound"))
                        {
                            throw new FileNotFoundException();
                        }
                        else if (MessageTask.Result.Message.ContainsKey("Error_Failure"))
                        {
                            throw new InvalidOperationException("Fail to move item");
                        }
                        else if (MessageTask.Result.Message.ContainsKey("Error_Capture"))
                        {
                            throw new FileCaputureException();
                        }
                        else
                        {
                            throw new Exception("Unknown reason");
                        }
                    }
                    else
                    {
                        throw new NoResponseException();
                    }
                }
                else
                {
                    throw new NoResponseException();
                }
            }
            finally
            {
                IsNowHasAnyActionExcuting = false;
            }
        }