コード例 #1
0
ファイル: ImageEditor.xaml.cs プロジェクト: sphayte/actools
        private async Task LoadImage(string filename, Rect?startRect)
        {
            _image = await BetterImage.LoadBitmapSourceAsync(filename);

            OriginalImage.SetCurrentValue(Image.SourceProperty, _image.ImageSource);
            CommandManager.InvalidateRequerySuggested();

            if (_image.IsBroken)
            {
                NonfatalError.Notify(AppStrings.Dialogs_ImageEditor_CantLoadImage);
                CloseWithResult(MessageBoxResult.Cancel);
            }
            else
            {
                _model.TotalWidth  = MainGrid.Width = _image.Width;
                _model.TotalHeight = MainGrid.Height = _image.Height;
                _model.CalculateMinAndMax();

                if (startRect.HasValue)
                {
                    var rect = startRect.Value;
                    _model.OffsetX     = rect.X;
                    _model.OffsetY     = rect.Y;
                    _model.ImageWidth  = rect.Width;
                    _model.ImageHeight = rect.Height;
                }
                else
                {
                    _model.CenterAndFit();
                }

                UpdateView();
            }
        }
コード例 #2
0
        private BetterImage MapCreateItem(string preferredFilename)
        {
            if (_mapItemPool.Count > 0)
            {
                var preferred = _mapItemPool.FindIndex(x => x.Filename == preferredFilename);
                if (preferred == -1)
                {
                    preferred = _mapItemPool.Count - 1;
                }

                var ret = _mapItemPool[preferred];
                _mapItemPool.RemoveAt(preferred);
                return(ret);
            }

            const double dotSize = 20d;
            var          created = new BetterImage {
                Width  = dotSize,
                Height = dotSize,
                Margin = new Thickness(-dotSize / 2, -dotSize / 2, 0, 0),
                Clip   = new EllipseGeometry {
                    RadiusX = dotSize / 2, RadiusY = dotSize / 2, Center = new Point(dotSize / 2, dotSize / 2)
                },
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top,
                RenderTransform     = new TranslateTransform(),
                ToolTip             = FindResource(@"DriverToolTip"),
                ContextMenu         = FindResource(@"DriverContextMenu") as ContextMenu
            };

            TrackMapItems.Children.Add(created);
            return(created);
        }
コード例 #3
0
        private byte[] PrepareTexture(string filename, string textureEffect)
        {
            var effect = GetEffect(textureEffect);

            if (effect == null)
            {
                return(File.ReadAllBytes(filename));
            }

            var image = BetterImage.LoadBitmapSource(filename);
            var size  = new Size(image.Width, image.Height);

            var result = new Image {
                Width  = image.Width,
                Height = image.Height,
                Source = image.ImageSource,
                Effect = effect,
            };

            result.Measure(size);
            result.Arrange(new Rect(size));
            result.ApplyTemplate();
            result.UpdateLayout();

            var bmp = new RenderTargetBitmap(image.Width, image.Height, 96, 96, PixelFormats.Pbgra32);

            bmp.Render(result);
            return(bmp.ToBytes(ImageFormat.Png));
        }
コード例 #4
0
        protected override void OnEnable()
        {
            BetterImage img = target as BetterImage;

            this.materialDrawer = new ImageAppearanceProviderEditorHelper(base.serializedObject, img);

            base.OnEnable();
            this.m_SpriteContent     = new GUIContent("Source Image");
            this.m_SpriteTypeContent = new GUIContent("Image Type");
            this.m_ClockwiseContent  = new GUIContent("Clockwise");
            this.m_Sprite            = base.serializedObject.FindProperty("m_Sprite");
            this.m_Type           = base.serializedObject.FindProperty("m_Type");
            this.m_FillCenter     = base.serializedObject.FindProperty("m_FillCenter");
            this.m_FillMethod     = base.serializedObject.FindProperty("m_FillMethod");
            this.m_FillOrigin     = base.serializedObject.FindProperty("m_FillOrigin");
            this.m_FillClockwise  = base.serializedObject.FindProperty("m_FillClockwise");
            this.m_FillAmount     = base.serializedObject.FindProperty("m_FillAmount");
            this.m_PreserveAspect = base.serializedObject.FindProperty("m_PreserveAspect");


            this.m_ShowType = new AnimBool(this.m_Sprite.objectReferenceValue != null);
            this.m_ShowType.valueChanged.AddListener(new UnityAction(this.Repaint));
            Image.Type mType = (Image.Type) this.m_Type.enumValueIndex;
            this.m_ShowSlicedOrTiled = new AnimBool((this.m_Type.hasMultipleDifferentValues ? false : mType == Image.Type.Sliced));
            this.m_ShowSliced        = new AnimBool((this.m_Type.hasMultipleDifferentValues ? false : mType == Image.Type.Sliced));
            this.m_ShowFilled        = new AnimBool((this.m_Type.hasMultipleDifferentValues ? false : mType == Image.Type.Filled));
            this.m_ShowSlicedOrTiled.valueChanged.AddListener(new UnityAction(this.Repaint));
            this.m_ShowSliced.valueChanged.AddListener(new UnityAction(this.Repaint));
            this.m_ShowFilled.valueChanged.AddListener(new UnityAction(this.Repaint));
            this.SetShowNativeSize(true);
        }
コード例 #5
0
        public override void OnInspectorGUI()
        {
            BetterImage img = target as BetterImage;


            base.serializedObject.Update();
            this.SpriteGUI();

            EditorGUILayout.Separator();
            if (img.type == Image.Type.Filled)
            {
                // coloring and materials not (yet) supported for filled images
                EditorGUILayout.PropertyField(this.m_Color);
                EditorGUILayout.PropertyField(this.m_Material);
            }
            else
            {
                // draw color and material
                materialDrawer.DrawInspectorGui(base.m_Material);
            }
            EditorGUILayout.Separator();


            base.RaycastControlsGUI();
            this.m_ShowType.target = this.m_Sprite.objectReferenceValue != null;
            if (EditorGUILayout.BeginFadeGroup(this.m_ShowType.faded))
            {
                this.TypeGUI();
            }
            EditorGUILayout.EndFadeGroup();
            this.SetShowNativeSize(false);
            if (EditorGUILayout.BeginFadeGroup(this.m_ShowNativeSize.faded))
            {
                EditorGUI.indentLevel = EditorGUI.indentLevel + 1;
                EditorGUILayout.PropertyField(this.m_PreserveAspect, new GUILayoutOption[0]);
                EditorGUI.indentLevel = EditorGUI.indentLevel - 1;
            }
            EditorGUILayout.EndFadeGroup();
            base.NativeSizeButtonGUI();
            base.serializedObject.ApplyModifiedProperties();



            if (img.type == UnityEngine.UI.Image.Type.Sliced)
            {
                var prop = serializedObject.FindProperty("keepBorderAspectRatio");
                EditorGUILayout.PropertyField(prop);
                serializedObject.ApplyModifiedProperties();
            }

            if (img.type == Image.Type.Sliced || img.type == Image.Type.Tiled)
            {
                var prop       = serializedObject.FindProperty("spriteBorderScaleFallback");
                var collection = serializedObject.FindProperty("customBorderScales");
                //EditorGUILayout.PropertyField(prop);

                ScreenConfigConnectionHelper.DrawSizerGui("Border Scale", collection, ref prop);
                serializedObject.ApplyModifiedProperties();
            }
        }
コード例 #6
0
        public static void MakeBetter(MenuCommand command)
        {
            Image img    = command.context as Image;
            var   newImg = Betterizer.MakeBetter <Image, BetterImage>(img);

            if (newImg != null)
            {
                newImg.SetAllDirty();

                BetterImage better = newImg as BetterImage;
                if (better != null)
                {
                    // set border scale both to height as default to make default scale uniform.
                    better.SpriteBorderScale.ModX.SizeModifiers[0].Mode = ImpactMode.PixelHeight;
                    better.SpriteBorderScale.ModY.SizeModifiers[0].Mode = ImpactMode.PixelHeight;

#if !UNITY_4 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2 && !UNITY_5_3 && !UNITY_5_4 && !UNITY_5_5  // from UNITY 5.6 on
                    // ensure shader channels in canvas
                    Canvas canvas = better.transform.GetComponentInParent <Canvas>();
                    canvas.additionalShaderChannels = canvas.additionalShaderChannels
                                                      | AdditionalCanvasShaderChannels.TexCoord1
                                                      | AdditionalCanvasShaderChannels.Tangent;
#endif
                }
            }
        }
コード例 #7
0
        private void CreateNewIcon()
        {
            if (Car == null)
            {
                return;
            }

            ValuesStorage.Set(_key, NewIconLabel.Text);
            // TODO: Save style?

            var size = new Size(CommonAcConsts.UpgradeIconWidth, CommonAcConsts.UpgradeIconHeight);

            NewIcon.Measure(size);
            NewIcon.Arrange(new Rect(size));
            NewIcon.ApplyTemplate();
            NewIcon.UpdateLayout();

            var bmp = new RenderTargetBitmap(CommonAcConsts.UpgradeIconWidth, CommonAcConsts.UpgradeIconHeight, 96, 96, PixelFormats.Pbgra32);

            bmp.Render(NewIcon);

            try {
                bmp.SaveTo(Car.UpgradeIcon);
                BetterImage.Refresh(Car.UpgradeIcon);
            } catch (IOException ex) {
                NonfatalError.Notify(AppStrings.UpgradeIcon_CannotChange, AppStrings.UpgradeIcon_CannotChange_Commentary, ex);
            } catch (Exception ex) {
                NonfatalError.Notify(AppStrings.UpgradeIcon_CannotChange, ex);
            }
        }
コード例 #8
0
        public override string GetInfoString()
        {
            BetterImage image = this.target as BetterImage;
            Rect        rect  = image.rectTransform.rect;
            object      num   = Mathf.RoundToInt(Mathf.Abs(rect.width));
            Rect        rect1 = image.rectTransform.rect;

            return(string.Format("Image Size: {0}x{1}", num, Mathf.RoundToInt(Mathf.Abs(rect1.height))));
        }
コード例 #9
0
        public override bool HasPreviewGUI()
        {
            BetterImage image = this.target as BetterImage;

            if (image == null)
            {
                return(false);
            }
            return(image.sprite != null);
        }
コード例 #10
0
ファイル: ImageViewer.xaml.cs プロジェクト: WildGenie/actools
            private async void UpdateCurrent()
            {
                var position = _currentPosition;
                var path     = _images[position] as string;

                if (path != null)
                {
                    _images[position] = BetterImage.LoadBitmapSource(path, double.IsPositiveInfinity(MaxImageWidth) ? -1 : (int)MaxImageWidth);
                }

                if (position < _images.Length - 1)
                {
                    var next     = position + 1;
                    var nextPath = _images[next] as string;
                    if (nextPath != null)
                    {
                        var loaded = await BetterImage.LoadBitmapSourceAsync(nextPath, double.IsPositiveInfinity(MaxImageWidth)? -1 : (int)MaxImageWidth);

                        var updated = _images[next];
                        if (updated as string != nextPath)
                        {
                            return;
                        }
                        _images[next] = loaded;
                    }
                }

                if (position > 1)
                {
                    var next     = position - 1;
                    var nextPath = _images[next] as string;
                    if (nextPath != null)
                    {
                        var loaded = await BetterImage.LoadBitmapSourceAsync(nextPath, double.IsPositiveInfinity(MaxImageWidth)? -1 : (int)MaxImageWidth);

                        var updated = _images[next];
                        if (updated as string != nextPath)
                        {
                            return;
                        }
                        _images[next] = loaded;
                    }
                }

                for (var i = 0; i < position - 2; i++)
                {
                    _images[i] = _originalImages[i];
                }

                for (var i = position + 3; i < _images.Length; i++)
                {
                    _images[i] = _originalImages[i];
                }
            }
コード例 #11
0
ファイル: FontObjectBitmap.cs プロジェクト: tankyx/actools
        public static async Task <FontObjectBitmap> CreateAsync(string bitmapFilename, string fontFilename)
        {
            try {
                var image = (await BetterImage.LoadBitmapSourceAsync(bitmapFilename)).ImageSource as BitmapSource;
                var data  = await FileUtils.ReadAllBytesAsync(fontFilename);

                return(new FontObjectBitmap(image, data));
            } catch (Exception e) {
                Logging.Warning(e);
                return(null);
            }
        }
コード例 #12
0
 private void OnImageMouseUp(object sender, MouseButtonEventArgs e)
 {
     if (_imageData == null)
     {
         return;
     }
     new ImageViewer(BetterImage.LoadBitmapSourceFromBytes(_imageData), x => _imageMessage)
     {
         MaxAreaWidth   = 1920,
         MaxAreaHeight  = 1080,
         MaxImageWidth  = 1920,
         MaxImageHeight = 1080
     }.ShowDialog();
 }
コード例 #13
0
        public override void Set(IniFile file)
        {
            ActionExtension.InvokeInMainThreadAsync(() => {
                var s = Stopwatch.StartNew();
                try {
                    var trackId         = file["RACE"].GetNonEmpty("TRACK");
                    var configurationId = file["RACE"].GetNonEmpty("CONFIG_TRACK");
                    var track           = TracksManager.Instance.GetLayoutById(trackId ?? string.Empty, configurationId);
                    if (track == null)
                    {
                        return;
                    }

                    var outline        = track.OutlineImage;
                    var outlineCropped = Path.Combine(Path.GetDirectoryName(track.OutlineImage) ?? "", "outline_cropped.png");
                    if (!File.Exists(outline) || File.Exists(outlineCropped))
                    {
                        return;
                    }

                    var image = BetterImage.LoadBitmapSource(outline);
                    var size  = new Size(256, 256);

                    var result = new BetterImage {
                        Width  = 256,
                        Height = 256,
                        Source = image.ImageSource,
                        CropTransparentAreas = true
                    };

                    result.Measure(size);
                    result.Arrange(new Rect(size));
                    result.ApplyTemplate();
                    result.UpdateLayout();

                    var bmp = new RenderTargetBitmap(256, 256, 96, 96, PixelFormats.Pbgra32);
                    bmp.Render(result);
                    File.WriteAllBytes(outlineCropped, bmp.ToBytes(ImageFormat.Png));
                } catch (Exception e) {
                    Logging.Error(e);
                } finally {
                    Logging.Write($"Time taken: {s.Elapsed.TotalMilliseconds:F2} ms");
                }
            });
        }
コード例 #14
0
            public bool Image(Table v)
            {
                var data = _data?.Get(GetText(v, "name") ?? "");

                if (data == null)
                {
                    Logging.Warning($"Image not found: {GetText(v, "name")}");
                    return(false);
                }

                ActionExtension.InvokeInMainThread(() => {
                    var image = new Image {
                        Source  = BetterImage.LoadBitmapSourceFromBytes(data).ImageSource,
                        Stretch = v[@"stretch"].As(Stretch.Uniform),
                        Effect  = GetEffect(v[@"effect"]?.ToString())
                    };
                    ApplyParams(v, image);
                    _canvas.Children.Add(image);
                });
                return(true);
            }
コード例 #15
0
        private void OnClosing(object sender, CancelEventArgs e)
        {
            if (!IsResultOk)
            {
                return;
            }

            foreach (var item in IconsList.FindVisualChildren <FrameworkElement>().Where(x => x.Name == @"NewIcon"))
            {
                if (!(item.DataContext is AppWindowItem data) || !data.IsInEditMode)
                {
                    continue;
                }

                item.DataContext = data;
                data.Save();
                var size   = new Size(CommonAcConsts.AppIconWidth, CommonAcConsts.AppIconHeight);
                var result = new ContentPresenter {
                    Width = size.Width, Height = size.Height, Content = item
                };

                SaveIcon();
                data.ShowEnabled = !data.ShowEnabled;
                SaveIcon();

                void SaveIcon()
                {
                    result.Measure(size);
                    result.Arrange(new Rect(size));
                    result.ApplyTemplate();
                    result.UpdateLayout();

                    var bmp = new RenderTargetBitmap(CommonAcConsts.AppIconWidth, CommonAcConsts.AppIconHeight, 96, 96, PixelFormats.Pbgra32);

                    bmp.Render(result);
                    bmp.SaveTo(data.IconOriginal);
                    BetterImage.Refresh(data.IconOriginal);
                }
            }
        }
コード例 #16
0
            public bool TrackMap(Table v)
            {
                var filename = _texturesContext.Track?.OutlineImage;

                if (filename == null || !File.Exists(filename))
                {
                    Logging.Warning("Outline image not available");
                    return(false);
                }

                ActionExtension.InvokeInMainThread(() => {
                    var image = new BetterImage {
                        Source = BetterImage.LoadBitmapSourceFromBytes(File.ReadAllBytes(filename)).ImageSource,
                        CropTransparentAreas = v[@"cropTransparent"].As(true),
                        Stretch = v[@"stretch"].As(Stretch.Uniform),
                        Effect  = GetEffect(v[@"effect"]?.ToString())
                    };
                    ApplyParams(v, image);
                    _canvas.Children.Add(image);
                });
                return(true);
            }
コード例 #17
0
            private void OnObjectPropertyChanged(object sender, PropertyChangedEventArgs e)
            {
                switch (e.PropertyName)
                {
                case nameof(CarObject.SpecsBhp):
                case nameof(CarObject.SpecsWeight):
                    if (RecalculatePwRatioAutomatically)
                    {
                        RecalculatePwRatioCommand.Execute();
                    }
                    break;

                case nameof(AcCommonObject.Year):
                    InnerFilterCommand?.RaiseCanExecuteChanged();
                    break;

                case nameof(CarObject.Brand):
                    if (SettingsHolder.Content.ChangeBrandIconAutomatically)
                    {
                        var entry = FilesStorage.Instance.GetContentFile(ContentCategory.BrandBadges, SelectedObject.Brand + @".png");
                        if (entry.Exists)
                        {
                            try {
                                FileUtils.Recycle(SelectedObject.BrandBadge);
                                File.Copy(entry.Filename, SelectedObject.BrandBadge);
                                BetterImage.Refresh(SelectedObject.BrandBadge);
                            } catch (Exception ex) {
                                Logging.Warning(ex);
                            }
                        }
                    }
                    break;

                case nameof(CarObject.SoundDonorId):
                    SelectedObject.GetSoundOrigin().Forget();
                    break;
                }
            }
コード例 #18
0
ファイル: ContentUtils.cs プロジェクト: windygu/actools
 private static FrameworkElement ToImage(string filename, int?decodeWidth)
 {
     return(ToImage(BetterImage.LoadBitmapSource(filename, decodeWidth ?? -1).ImageSource));
 }
コード例 #19
0
ファイル: FontObjectBitmap.cs プロジェクト: tankyx/actools
 public FontObjectBitmap(string bitmapFilename, string fontFilename) :
     this((BitmapSource)BetterImage.LoadBitmapSource(bitmapFilename).ImageSource, File.ReadAllBytes(fontFilename))
 {
 }
コード例 #20
0
        private App()
        {
            if (AppArguments.GetBool(AppFlag.IgnoreHttps))
            {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
            }

            AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation);
            AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation);
            AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize);

            AppArguments.Set(AppFlag.NoProxy, ref KunosApiProvider.OptionNoProxy);

            var proxy = AppArguments.Get(AppFlag.Proxy);

            if (!string.IsNullOrWhiteSpace(proxy))
            {
                try {
                    var s = proxy.Split(':');
                    WebRequest.DefaultWebProxy = new WebProxy(s[0], FlexibleParser.ParseInt(s.ArrayElementAtOrDefault(1), 1080));
                } catch (Exception e) {
                    Logging.Error(e);
                }
            }

            // TODO: AppArguments.Set(AppFlag.ScanPingTimeout, ref RecentManagerOld.OptionScanPingTimeout);
            AppArguments.Set(AppFlag.LanSocketTimeout, ref KunosApiProvider.OptionLanSocketTimeout);
            AppArguments.Set(AppFlag.LanPollTimeout, ref KunosApiProvider.OptionLanPollTimeout);
            AppArguments.Set(AppFlag.WebRequestTimeout, ref KunosApiProvider.OptionWebRequestTimeout);
            AppArguments.Set(AppFlag.DirectRequestTimeout, ref KunosApiProvider.OptionDirectRequestTimeout);
            AppArguments.Set(AppFlag.CommandTimeout, ref GameCommandExecutorBase.OptionCommandTimeout);

            AppArguments.Set(AppFlag.DisableAcRootChecking, ref AcPaths.OptionEaseAcRootCheck);
            AppArguments.Set(AppFlag.AcObjectsLoadingConcurrency, ref BaseAcManagerNew.OptionAcObjectsLoadingConcurrency);
            AppArguments.Set(AppFlag.SkinsLoadingConcurrency, ref CarObject.OptionSkinsLoadingConcurrency);
            AppArguments.Set(AppFlag.KunosCareerIgnoreSkippedEvents, ref KunosCareerEventsManager.OptionIgnoreSkippedEvents);
            AppArguments.Set(AppFlag.IgnoreMissingSkinsInKunosEvents, ref KunosEventObjectBase.OptionIgnoreMissingSkins);

            AppArguments.Set(AppFlag.CanPack, ref AcCommonObject.OptionCanBePackedFilter);
            AppArguments.Set(AppFlag.CanPackCars, ref CarObject.OptionCanBePackedFilter);

            AppArguments.Set(AppFlag.ForceToastFallbackMode, ref Toast.OptionFallbackMode);

            AppArguments.Set(AppFlag.SmartPresetsChangedHandling, ref UserPresetsControl.OptionSmartChangedHandling);
            AppArguments.Set(AppFlag.EnableRaceIniRestoration, ref Game.OptionEnableRaceIniRestoration);
            AppArguments.Set(AppFlag.EnableRaceIniTestMode, ref Game.OptionRaceIniTestMode);
            AppArguments.Set(AppFlag.RaceOutDebug, ref Game.OptionDebugMode);

            AppArguments.Set(AppFlag.NfsPorscheTribute, ref RaceGridViewModel.OptionNfsPorscheNames);
            AppArguments.Set(AppFlag.KeepIniComments, ref IniFile.OptionKeepComments);
            AppArguments.Set(AppFlag.AutoConnectPeriod, ref OnlineServer.OptionAutoConnectPeriod);
            AppArguments.Set(AppFlag.GenericModsLogging, ref GenericModsEnabler.OptionLoggingEnabled);
            AppArguments.Set(AppFlag.SidekickOptimalRangeThreshold, ref SidekickHelper.OptionRangeThreshold);
            AppArguments.Set(AppFlag.GoogleDriveLoaderDebugMode, ref GoogleDriveLoader.OptionDebugMode);
            AppArguments.Set(AppFlag.GoogleDriveLoaderManualRedirect, ref GoogleDriveLoader.OptionManualRedirect);
            AppArguments.Set(AppFlag.DebugPing, ref ServerEntry.OptionDebugPing);
            AppArguments.Set(AppFlag.DebugContentId, ref AcObjectNew.OptionDebugLoading);
            AppArguments.Set(AppFlag.JpegQuality, ref ImageUtilsOptions.JpegQuality);
            AppArguments.Set(AppFlag.FbxMultiMaterial, ref Kn5.OptionJoinToMultiMaterial);

            Acd.Factory       = new AcdFactory();
            Lazier.SyncAction = ActionExtension.InvokeInMainThreadAsync;
            KeyboardListenerFactory.Register <KeyboardListener>();

            LimitedSpace.Initialize();
            DataProvider.Initialize();
            SteamIdHelper.Initialize(AppArguments.Get(AppFlag.ForceSteamId));
            TestKey();

            AppDomain.CurrentDomain.ProcessExit += OnProcessExit;

            if (!AppArguments.GetBool(AppFlag.PreventDisableWebBrowserEmulationMode) && (
                    ValuesStorage.Get <int>(WebBrowserEmulationModeDisabledKey) < WebBrowserHelper.EmulationModeDisablingVersion ||
                    AppArguments.GetBool(AppFlag.ForceDisableWebBrowserEmulationMode)))
            {
                try {
                    WebBrowserHelper.DisableBrowserEmulationMode();
                    ValuesStorage.Set(WebBrowserEmulationModeDisabledKey, WebBrowserHelper.EmulationModeDisablingVersion);
                } catch (Exception e) {
                    Logging.Warning("Can’t disable emulation mode: " + e);
                }
            }

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
                Formatting           = Formatting.None,
                NullValueHandling    = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Include,
                Culture = CultureInfo.InvariantCulture
            };

            AcToolsLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (AcTools)", m, p, l);
            AcToolsLogging.NonFatalErrorHandler = (s, c, e, b) => {
                if (b)
                {
                    NonfatalError.NotifyBackground(s, c, e);
                }
                else
                {
                    NonfatalError.Notify(s, c, e);
                }
            };

            AppArguments.Set(AppFlag.ControlsDebugMode, ref ControlsSettings.OptionDebugControlles);
            AppArguments.Set(AppFlag.ControlsRescanPeriod, ref DirectInputScanner.OptionMinRescanPeriod);
            var ignoreControls = AppArguments.Get(AppFlag.IgnoreControls);

            if (!string.IsNullOrWhiteSpace(ignoreControls))
            {
                ControlsSettings.OptionIgnoreControlsFilter = Filter.Create(new StringTester(), ignoreControls);
            }

            var sseStart = AppArguments.Get(AppFlag.SseName);

            if (!string.IsNullOrWhiteSpace(sseStart))
            {
                SseStarter.OptionStartName = sseStart;
            }
            AppArguments.Set(AppFlag.SseLogging, ref SseStarter.OptionLogging);

            FancyBackgroundManager.Initialize();
            if (AppArguments.Has(AppFlag.UiScale))
            {
                AppearanceManager.Instance.AppScale = AppArguments.GetDouble(AppFlag.UiScale, 1d);
            }
            if (AppArguments.Has(AppFlag.WindowsLocationManagement))
            {
                AppearanceManager.Instance.ManageWindowsLocation = AppArguments.GetBool(AppFlag.WindowsLocationManagement, true);
            }

            if (!InternalUtils.IsAllRight)
            {
                AppAppearanceManager.OptionCustomThemes = false;
            }
            else
            {
                AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes);
            }

            AppArguments.Set(AppFlag.FancyHintsDebugMode, ref FancyHint.OptionDebugMode);
            AppArguments.Set(AppFlag.FancyHintsMinimumDelay, ref FancyHint.OptionMinimumDelay);
            AppArguments.Set(AppFlag.WindowsVerbose, ref DpiAwareWindow.OptionVerboseMode);
            AppArguments.Set(AppFlag.ShowroomUiVerbose, ref LiteShowroomFormWrapperWithTools.OptionAttachedToolsVerboseMode);
            AppArguments.Set(AppFlag.BenchmarkReplays, ref GameDialog.OptionBenchmarkReplays);

            // Shared memory, now as an app flag
            SettingsHolder.Drive.WatchForSharedMemory = !AppArguments.GetBool(AppFlag.DisableSharedMemory);

            /*AppAppearanceManager.OptionIdealFormattingModeDefaultValue = AppArguments.GetBool(AppFlag.IdealFormattingMode,
             *      !Equals(DpiAwareWindow.OptionScale, 1d));*/
            NonfatalErrorSolution.IconsDictionary = new Uri("/AcManager.Controls;component/Assets/IconData.xaml", UriKind.Relative);
            AppearanceManager.DefaultValuesSource = new Uri("/AcManager.Controls;component/Assets/ModernUI.Default.xaml", UriKind.Relative);
            AppAppearanceManager.Initialize(Pages.Windows.MainWindow.GetTitleLinksEntries());
            VisualExtension.RegisterInput <WebBlock>();

            ContentUtils.Register("AppStrings", AppStrings.ResourceManager);
            ContentUtils.Register("ControlsStrings", ControlsStrings.ResourceManager);
            ContentUtils.Register("ToolsStrings", ToolsStrings.ResourceManager);
            ContentUtils.Register("UiStrings", UiStrings.ResourceManager);

            AcObjectsUriManager.Register(new UriProvider());

            {
                var uiFactory = new GameWrapperUiFactory();
                GameWrapper.RegisterFactory(uiFactory);
                ServerEntry.RegisterFactory(uiFactory);
            }

            GameWrapper.RegisterFactory(new DefaultAssistsFactory());
            LapTimesManager.Instance.SetListener();
            RaceResultsStorage.Instance.SetListener();

            AcError.RegisterFixer(new AcErrorFixer());
            AcError.RegisterSolutionsFactory(new SolutionsFactory());

            InitializePresets();

            SharingHelper.Initialize();
            SharingUiHelper.Initialize(AppArguments.GetBool(AppFlag.ModernSharing) ? new Win10SharingUiHelper() : null);

            {
                var addonsDir  = FilesStorage.Instance.GetFilename("Addons");
                var pluginsDir = FilesStorage.Instance.GetFilename("Plugins");
                if (Directory.Exists(addonsDir) && !Directory.Exists(pluginsDir))
                {
                    Directory.Move(addonsDir, pluginsDir);
                }
                else
                {
                    pluginsDir = FilesStorage.Instance.GetDirectory("Plugins");
                }

                PluginsManager.Initialize(pluginsDir);
                PluginsWrappers.Initialize(
                    new AssemblyResolvingWrapper(KnownPlugins.Fmod, FmodResolverService.Resolver),
                    new AssemblyResolvingWrapper(KnownPlugins.Fann, FannResolverService.Resolver),
                    new AssemblyResolvingWrapper(KnownPlugins.Magick, ImageUtils.MagickResolver),
                    new AssemblyResolvingWrapper(KnownPlugins.CefSharp, CefSharpResolverService.Resolver));
            }

            {
                var onlineMainListFile   = FilesStorage.Instance.GetFilename("Online Servers", "Main List.txt");
                var onlineFavouritesFile = FilesStorage.Instance.GetFilename("Online Servers", "Favourites.txt");
                if (File.Exists(onlineMainListFile) && !File.Exists(onlineFavouritesFile))
                {
                    Directory.Move(onlineMainListFile, onlineFavouritesFile);
                }
            }

            CupClient.Initialize();
            Superintendent.Initialize();
            ModsWebBrowser.Initialize();

            AppArguments.Set(AppFlag.OfflineMode, ref AppKeyDialog.OptionOfflineMode);

            WebBlock.DefaultDownloadListener  = new WebDownloadListener();
            FlexibleLoader.CmRequestHandler   = new CmRequestHandler();
            ContextMenus.ContextMenusProvider = new ContextMenusProvider();
            PrepareUi();

            AppShortcut.Initialize("Content Manager", "Content Manager");

            // If shortcut exists, make sure it has a proper app ID set for notifications
            if (File.Exists(AppShortcut.ShortcutLocation))
            {
                AppShortcut.CreateShortcut();
            }

            AppIconService.Initialize(new AppIconProvider());

            Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ??
                                          Current.MainWindow as ModernWindow)?.BringToFront());
            BbCodeBlock.ImageClicked             += OnBbImageClick;
            BbCodeBlock.OptionEmojiProvider       = new EmojiProvider();
            BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images");
            BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji");

            BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/car"),
                                       new DelegateCommand <string>(
                                           id => {
                WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Car));
            }));

            BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/track"),
                                       new DelegateCommand <string>(
                                           id => {
                WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Track));
            }));

            BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/car"), new DelegateCommand <string>(id => {
                var s = id.Split('|');
                IndexDirectDownloader.DownloadCarAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget();
            }));

            BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/track"), new DelegateCommand <string>(id => {
                var s = id.Split('|');
                IndexDirectDownloader.DownloadTrackAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget();
            }));

            BbCodeBlock.AddLinkCommand(new Uri("cmd://createNeutralLut"),
                                       new DelegateCommand <string>(id => NeutralColorGradingLut.CreateNeutralLut(id.As(16))));

            BbCodeBlock.DefaultLinkNavigator.PreviewNavigate += (sender, args) => {
                if (args.Uri.IsAbsoluteUri && args.Uri.Scheme == "acmanager")
                {
                    ArgumentsHandler.ProcessArguments(new[] { args.Uri.ToString() }, true).Forget();
                    args.Cancel = true;
                }
            };

            AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize);
            AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached);
            BetterImage.RemoteUserAgent      = CmApiProvider.UserAgent;
            BetterImage.RemoteCacheDirectory = BbCodeBlock.OptionImageCacheDirectory;
            GameWrapper.Started += (sender, args) => {
                BetterImage.CleanUpCache();
                GCHelper.CleanUp();
            };

            AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc);
            Filter.OptionSimpleMatching = true;

            GameResultExtension.RegisterNameProvider(new GameSessionNameProvider());
            CarBlock.CustomShowroomWrapper   = new CustomShowroomWrapper();
            CarBlock.CarSetupsView           = new CarSetupsView();
            SettingsHolder.Content.OldLayout = AppArguments.GetBool(AppFlag.CarsOldLayout);

            var acRootIsFine = Superintendent.Instance.IsReady && !AcRootDirectorySelector.IsReviewNeeded();

            if (acRootIsFine && SteamStarter.Initialize(AcRootDirectory.Instance.Value))
            {
                if (SettingsHolder.Drive.SelectedStarterType != SettingsHolder.DriveSettings.SteamStarterType)
                {
                    SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.SteamStarterType;
                    Toast.Show("Starter changed to replacement", "Enjoy Steam being included into CM");
                }
            }
            else if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.SteamStarterType)
            {
                SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.DefaultStarterType;
                Toast.Show($"Starter changed to {SettingsHolder.Drive.SelectedStarterType.DisplayName}", "Steam Starter is unavailable", () => {
                    ModernDialog.ShowMessage(
                        "To use Steam Starter, please make sure CM is taken place of the official launcher and AC root directory is valid.",
                        "Steam Starter is unavailable", MessageBoxButton.OK);
                });
            }

            InitializeUpdatableStuff();
            BackgroundInitialization();
            ExtraProgressRings.Initialize();

            FatalErrorMessage.Register(new AppRestartHelper());
            ImageUtils.SafeMagickWrapper = fn => {
                try {
                    return(fn());
                } catch (OutOfMemoryException e) {
                    NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, ToolsStrings.MagickNet_CannotLoad_Commentary, e);
                } catch (Exception e) {
                    NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, e);
                }
                return(null);
            };

            DataFileBase.ErrorsCatcher = new DataSyntaxErrorCatcher();
            AppArguments.Set(AppFlag.SharedMemoryLiveReadingInterval, ref AcSharedMemory.OptionLiveReadingInterval);
            AcSharedMemory.Initialize();

            AppArguments.Set(AppFlag.RunRaceInformationWebserver, ref PlayerStatsManager.OptionRunStatsWebserver);
            AppArguments.Set(AppFlag.RaceInformationWebserverFile, ref PlayerStatsManager.OptionWebserverFilename);

            PlayerStatsManager.Instance.SetListener();
            RhmService.Instance.SetListener();

            WheelOptionsBase.SetStorage(new WheelAnglesStorage());

            _hibernator = new AppHibernator();
            _hibernator.SetListener();

            VisualCppTool.Initialize(FilesStorage.Instance.GetDirectory("Plugins", "NativeLibs"));

            try {
                SetRenderersOptions();
            } catch (Exception e) {
                VisualCppTool.OnException(e, null);
            }

            CommonFixes.Initialize();

            CmPreviewsTools.MissingShowroomHelper = new CarUpdatePreviewsDialog.MissingShowroomHelper();

            // Paint shop+livery generator?
            LiteShowroomTools.LiveryGenerator = new LiveryGenerator();

            // Discord
            if (AppArguments.Has(AppFlag.DiscordCmd))
            {
                // Do not show main window and wait for futher instructions?
            }

            if (SettingsHolder.Integrated.DiscordIntegration)
            {
                AppArguments.Set(AppFlag.DiscordVerbose, ref DiscordConnector.OptionVerboseMode);
                DiscordConnector.Initialize(AppArguments.Get(AppFlag.DiscordClientId) ?? InternalUtils.GetDiscordClientId(), new DiscordHandler());
                DiscordImage.OptionDefaultImage = @"track_ks_brands_hatch";
                GameWrapper.Started            += (sender, args) => args.StartProperties.SetAdditional(new GameDiscordPresence(args.StartProperties, args.Mode));
            }

            // Reshade?
            var loadReShade = AppArguments.GetBool(AppFlag.ForceReshade);

            if (!loadReShade && string.Equals(AppArguments.Get(AppFlag.ForceReshade), "kn5only", StringComparison.OrdinalIgnoreCase))
            {
                loadReShade = AppArguments.Values.Any(x => x.EndsWith(".kn5", StringComparison.OrdinalIgnoreCase));
            }

            if (loadReShade)
            {
                var reshade = Path.Combine(MainExecutingFile.Directory, "dxgi.dll");
                if (File.Exists(reshade))
                {
                    Kernel32.LoadLibrary(reshade);
                }
            }

            // Auto-show that thing
            InstallAdditionalContentDialog.Initialize();

            // Let’s roll
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
            new AppUi(this).Run();
        }
コード例 #21
0
ファイル: Emoji.cs プロジェクト: gro-ove/typo4
        private async Task <ImageSource> LoadImageSourceAsync()
        {
            var data = await _loader.LoadDataAsync(_id).ConfigureAwait(false);

            return(data == null ? null : await Task.Run(() => BetterImage.LoadBitmapSourceFromBytes(data).BitmapSource).ConfigureAwait(false));
        }
コード例 #22
0
ファイル: Emoji.cs プロジェクト: gro-ove/typo4
        private ImageSource LoadImageSource()
        {
            var data = _loader.LoadData(_id);

            return(data == null ? null : BetterImage.LoadBitmapSourceFromBytes(data).BitmapSource);
        }
コード例 #23
0
ファイル: FontObject.cs プロジェクト: Abishai2007/actools
 public FontObjectBitmap(byte[] bitmapData, byte[] fontData) :
     this((BitmapSource)BetterImage.LoadBitmapSourceFromBytes(bitmapData).BitmapSource, fontData)
 {
 }
コード例 #24
0
ファイル: ContentUtils.cs プロジェクト: windygu/actools
 private static FrameworkElement ToImage(byte[] bytes, int?decodeWidth)
 {
     return(ToImage(BetterImage.LoadBitmapSourceFromBytes(bytes, decodeWidth ?? -1).ImageSource));
 }
コード例 #25
0
 protected void OnImageChangedValue(string filename)
 {
     BetterImage.ReloadImage(filename);
 }
コード例 #26
0
 protected void OnImageChanged(string propertyName)
 {
     OnPropertyChanged(propertyName);
     BetterImage.ReloadImage((string)GetType().GetProperty(propertyName).GetValue(this, null));
 }