コード例 #1
0
        public async Task LoadCachableShouldStoreCollectedResults()
        {
            AggContext.StaticData = new FileSystemStaticData(TestContext.CurrentContext.ResolveProjectPath(5, "MatterControl", "StaticData"));
            MatterControlUtilities.OverrideAppDataLocation(TestContext.CurrentContext.ResolveProjectPath(5));

            string cacheScope = Path.Combine("Some", "Specific", "Scope");

            // Load cacheable content from collector, writing results to cache
            var versionInfo = await ApplicationController.LoadCacheableAsync <VersionInfo>(
                cacheKey : "HelloWorld-File1",
                cacheScope : cacheScope,
                collector : async() =>
            {
                return(JsonConvert.DeserializeObject <VersionInfo>("{\"BuildVersion\": \"HelloFromCollector\"}"));
            },
                staticDataFallbackPath : "BuildInfo.txt");

            Assert.IsTrue(versionInfo.BuildVersion == "HelloFromCollector", "LoadCacheable should use content from collector");

            string cachePath = ApplicationController.CacheablePath(cacheScope, "HelloWorld-File1");

            Assert.IsTrue(File.Exists(cachePath), "Collected results should be written to cache at expected path");

            Assert.IsTrue(File.ReadAllText(cachePath).Contains("HelloFromCollector"), "Cached content should equal collected content");
        }
コード例 #2
0
        private async Task DownloadMissingProfiles(IProgress <SyncReportType> syncReport)
        {
            SyncReportType reportValue = new SyncReportType();
            int            index       = 0;

            foreach (string oem in OemProfiles.Keys)
            {
                string cacheScope = Path.Combine("public-profiles", oem);

                index++;
                foreach (var model in OemProfiles[oem].Keys)
                {
                    var    publicDevice = OemProfiles[oem][model];
                    string cachePath    = ApplicationController.CacheablePath(cacheScope, publicDevice.CacheKey);
                    if (!File.Exists(cachePath))
                    {
                        await Task.Delay(20000);

                        await ProfileManager.LoadOemProfileAsync(publicDevice, oem, model);

                        if (syncReport != null)
                        {
                            reportValue.actionLabel  = string.Format("Downloading public profiles for {0}...", oem);
                            reportValue.percComplete = (double)index / OemProfiles.Count;
                            syncReport.Report(reportValue);
                        }
                    }
                }
            }
        }
コード例 #3
0
        public async static Task <PrinterSettings> LoadOemProfileAsync(PublicDevice publicDevice, string make, string model)
        {
            string cacheScope = Path.Combine("public-profiles", make);
            string cachePath  = ApplicationController.CacheablePath(cacheScope, publicDevice.CacheKey);

            return(await ApplicationController.LoadCacheableAsync <PrinterSettings>(
                       publicDevice.CacheKey,
                       cacheScope,
                       async() =>
            {
                // The collector specifically returns null to ensure LoadCacheable skips writing the
                // result to the cache. After this result is returned, it will attempt to load from
                // the local cache if the collector yielded no result
                if (File.Exists(cachePath) ||
                    ApplicationController.DownloadPublicProfileAsync == null)
                {
                    return null;
                }
                else
                {
                    // If the cache file for the current deviceToken does not exist, attempt to download it.
                    // An http 304 results in a null value and LoadCacheable will then load from the cache
                    return await ApplicationController.DownloadPublicProfileAsync(publicDevice.ProfileToken);
                }
            },
                       Path.Combine("Profiles", make, model + ProfileManager.ProfileExtension)));
        }
コード例 #4
0
ファイル: OemSettings.cs プロジェクト: visdauas/MatterControl
        private async Task DownloadMissingProfiles()
        {
            var reportValue = new ProgressStatus();
            int index       = 0;

            foreach (string oem in OemProfiles.Keys)
            {
                string cacheScope = Path.Combine("public-profiles", oem);

                index++;
                foreach (var model in OemProfiles[oem].Keys)
                {
                    var    publicDevice = OemProfiles[oem][model];
                    string cachePath    = ApplicationController.CacheablePath(cacheScope, publicDevice.CacheKey);
                    if (!File.Exists(cachePath))
                    {
                        await Task.Delay(20000);

                        await ProfileManager.LoadOemSettingsAsync(publicDevice, oem, model);

                        if (ApplicationController.Instance.ApplicationExiting)
                        {
                            return;
                        }
                    }
                }
            }
        }
コード例 #5
0
ファイル: OemSettings.cs プロジェクト: will8886/MatterControl
        private async Task DownloadMissingProfiles(IProgress <ProgressStatus> syncReport)
        {
            ProgressStatus reportValue = new ProgressStatus();
            int            index       = 0;

            foreach (string oem in OemProfiles.Keys)
            {
                string cacheScope = Path.Combine("public-profiles", oem);

                index++;
                foreach (var model in OemProfiles[oem].Keys)
                {
                    var    publicDevice = OemProfiles[oem][model];
                    string cachePath    = ApplicationController.CacheablePath(cacheScope, publicDevice.CacheKey);
                    if (!File.Exists(cachePath))
                    {
                        await Task.Delay(20000);

                        await ProfileManager.LoadOemSettingsAsync(publicDevice, oem, model);

                        if (ApplicationController.Instance.ApplicationExiting)
                        {
                            return;
                        }

                        if (syncReport != null)
                        {
                            reportValue.Status       = string.Format("Downloading public profiles for {0}...", oem);
                            reportValue.Progress0To1 = (double)index / OemProfiles.Count;
                            syncReport.Report(reportValue);
                        }
                    }
                }
            }
        }
コード例 #6
0
ファイル: OemSettings.cs プロジェクト: visdauas/MatterControl
        private OemProfileDictionary LoadOemProfiles()
        {
            string cachePath = ApplicationController.CacheablePath("public-profiles", "oemprofiles.json");

            // Load data from cache or fall back to stale StaticData content
            string json = File.Exists(cachePath) ? File.ReadAllText(cachePath) : null;

            if (string.IsNullOrWhiteSpace(json))
            {
                // If empty, purge the cache file and fall back to StaticData
                File.Delete(cachePath);

                json = StaticData.Instance.ReadAllText(Path.Combine("Profiles", "oemprofiles.json"));
            }

            try
            {
                return(JsonConvert.DeserializeObject <OemProfileDictionary>(json));
            }
            catch
            {
                // If json parse fails, purge the cache file and fall back to StaticData
                File.Delete(cachePath);

                json = StaticData.Instance.ReadAllText(Path.Combine("Profiles", "oemprofiles.json"));
                return(JsonConvert.DeserializeObject <OemProfileDictionary>(json));
            }
        }
コード例 #7
0
ファイル: OemSettings.cs プロジェクト: will8886/MatterControl
        private OemProfileDictionary LoadOemProfiles()
        {
            string cachePath = ApplicationController.CacheablePath("public-profiles", "oemprofiles.json");

            // Load data from cache or fall back to stale StaticData content
            string json = File.Exists(cachePath) ? File.ReadAllText(cachePath) : AggContext.StaticData.ReadAllText(Path.Combine("Profiles", "oemprofiles.json"));

            return(JsonConvert.DeserializeObject <OemProfileDictionary>(json));
        }
コード例 #8
0
ファイル: PathTests.cs プロジェクト: will8886/MatterControl
        public Task CacheablePathTest()
        {
            AggContext.StaticData = new FileSystemStaticData(TestContext.CurrentContext.ResolveProjectPath(4, "StaticData"));

            string path = ApplicationController.CacheablePath("scope", "key.file");

            Assert.AreEqual(
                path.Substring(path.IndexOf("MatterControl")),
                Path.Combine("MatterControl", "data", "temp", "cache", "scope", "key.file"),
                "Unexpected CacheablePath Value");

            return(Task.CompletedTask);
        }
コード例 #9
0
        public override void OnLoad(EventArgs args)
        {
            base.OnLoad(args);

            try
            {
                FeedData explorerFeed = null;

                var json = ApplicationController.LoadCachedFile("MatterHackers", staticFile);
                if (json != null)
                {
                    // Construct directly from cache
                    explorerFeed = JsonConvert.DeserializeObject <FeedData>(json);
                    // Add controls for content
                    AddControlsForContent(explorerFeed);
                }
                // Force layout to change to get it working
                var oldMargin = this.Margin;
                this.Margin = new BorderDouble(20);
                this.Margin = oldMargin;

                Task.Run(async() =>
                {
                    string cachePath = ApplicationController.CacheablePath("MatterHackers", staticFile);

                    // Construct directly from cache
                    explorerFeed = await LoadExploreFeed(json?.GetHashCode() ?? 0, cachePath);

                    if (explorerFeed != null)
                    {
                        UiThread.RunOnIdle(() =>
                        {
                            this.CloseAllChildren();

                            // Add controls for content
                            AddControlsForContent(explorerFeed);

                            // Force layout to change to get it working
                            this.Margin = new BorderDouble(20);
                            this.Margin = oldMargin;
                        });
                    }
                });
            }
            catch
            {
            }
        }
コード例 #10
0
ファイル: OemSettings.cs プロジェクト: will8886/MatterControl
        public ImageBuffer GetIcon(string oemName)
        {
            string cachePath = ApplicationController.CacheablePath("OemIcons", oemName + ".png");

            try
            {
                if (File.Exists(cachePath))
                {
                    return(AggContext.ImageIO.LoadImage(cachePath));
                }
                else
                {
                    var imageBuffer = new ImageBuffer(16, 16);

                    ApplicationController.Instance.LoadRemoteImage(
                        imageBuffer,
                        ApplicationController.Instance.GetFavIconUrl(oemName),
                        scaleToImageX: false).ContinueWith(t =>
                    {
                        try
                        {
                            AggContext.ImageIO.SaveImageData(cachePath, imageBuffer);
                        }
                        catch (Exception ex)
                        {
                            Console.Write(ex.Message);
                        }
                    });

                    return(imageBuffer);
                }
            }
            catch
            {
            }

            return(new ImageBuffer(16, 16));
        }
コード例 #11
0
        public static PrinterSettings RestoreFromOemProfile(PrinterInfo profile)
        {
            PrinterSettings oemProfile = null;

            try
            {
                var    publicDevice = OemSettings.Instance.OemProfiles[profile.Make][profile.Model];
                string cacheScope   = Path.Combine("public-profiles", profile.Make);

                string publicProfileToLoad = ApplicationController.CacheablePath(cacheScope, publicDevice.CacheKey);

                oemProfile    = JsonConvert.DeserializeObject <PrinterSettings>(File.ReadAllText(publicProfileToLoad));
                oemProfile.ID = profile.ID;
                oemProfile.SetValue(SettingsKey.printer_name, profile.Name);
                oemProfile.DocumentVersion = PrinterSettings.LatestVersion;

                oemProfile.Helpers.SetComPort(profile.ComPort);
                oemProfile.Save();
            }
            catch { }

            return(oemProfile);
        }
コード例 #12
0
        public async Task LoadCachableShouldFallbackToStaticData()
        {
            AggContext.StaticData = new FileSystemStaticData(TestContext.CurrentContext.ResolveProjectPath(5, "MatterControl", "StaticData"));
            MatterControlUtilities.OverrideAppDataLocation(TestContext.CurrentContext.ResolveProjectPath(5));

            string cacheScope = Path.Combine("Some", "Specific", "Scope");

            // Load cacheable content from StaticData when the collector returns null and no cached content exists
            var versionInfo = await ApplicationController.LoadCacheableAsync <VersionInfo>(
                cacheKey : "HelloWorld-File1",
                cacheScope : cacheScope,
                collector : async() =>
            {
                // Hypothetical http request with 304 indicating our results cached results have not expired
                return(null);
            },
                staticDataFallbackPath : "BuildInfo.txt");

            Assert.IsNotNull(versionInfo, "LoadCacheable should fall back to StaticData content if collection fails");

            string cachePath = ApplicationController.CacheablePath(cacheScope, "HelloWorld-File1");

            Assert.IsFalse(File.Exists(cachePath), "After fall back to StaticData content, cache should not contain fall back content");
        }
コード例 #13
0
        protected void SendRequest(ulong longHash)
        {
            string cacheFileName = ApplicationController.CacheablePath("Text", longHash.ToString() + ".txt");

            ResponseType cacheResponse = null;

            if (longHash != 0 &&
                ReloadRequest != null)
            {
                if (File.Exists(cacheFileName))
                {
                    try
                    {
                        string cacheText = null;
                        cacheText     = File.ReadAllText(cacheFileName);
                        cacheResponse = JsonConvert.DeserializeObject <ResponseType>(cacheText);

                        OnRequestSucceeded(cacheResponse);
                    }
                    catch
                    {
                    }
                }
            }

            RequestManager requestManager = new RequestManager();

            // Prevent constant exceptions on debug builds when stepping through code. In debug, let requests stay in limbo until resumed and prevent the timeout exceptions
#if !DEBUG
            requestManager.Timeout = this.Timeout;
#endif
            string jsonToSend = JsonConvert.SerializeObject(requestValues);

#if TRACEREQUESTS
            System.Diagnostics.Trace.Write(string.Format("ServiceRequest: {0}\r\n  {1}\r\n", uri, string.Join("\r\n\t", jsonToSend.Split(','))));
#endif

            requestManager.SendPOSTRequest(uri, jsonToSend, "", "", false);

            ResponseType           responseItem = null;
            JsonResponseDictionary errorResults = null;

            if (requestManager.LastResponse != null)
            {
                try
                {
                    responseItem = JsonConvert.DeserializeObject <ResponseType>(requestManager.LastResponse);
                }
                catch
                {
                    errorResults = JsonConvert.DeserializeObject <JsonResponseDictionary>(requestManager.LastResponse);
                }
            }

            if (responseItem != null)
            {
                if (ReloadRequest != null &&
                    longHash != 0)
                {
                    if (cacheResponse == null || !cacheResponse.Equals(responseItem))
                    {
                        lock (locker)
                        {
                            File.WriteAllText(cacheFileName, requestManager.LastResponse);
                        }

                        if (cacheResponse != null)
                        {
                            // we already sent back the succeeded response, send a cache miss
                            ReloadRequest(this, responseItem);
                        }
                        else
                        {
                            // send back the succeeded response
                            OnRequestSucceeded(responseItem);
                        }
                    }
                }
                else
                {
                    OnRequestSucceeded(responseItem);
                }
            }
            else
            {
                OnRequestFailed(errorResults);
            }

            OnRequestComplete();
        }
コード例 #14
0
        public ApplicationSettingsWidget(ThemeConfig theme)
            : base(FlowDirection.TopToBottom)
        {
            this.HAnchor         = HAnchor.Stretch;
            this.VAnchor         = VAnchor.Fit;
            this.BackgroundColor = theme.Colors.PrimaryBackgroundColor;
            this.theme           = theme;

            var configureIcon = AggContext.StaticData.LoadIcon("fa-cog_16.png", 16, 16, theme.InvertIcons);

#if __ANDROID__
            // Camera Monitoring
            bool hasCamera = true || ApplicationSettings.Instance.get(ApplicationSettingsKey.HardwareHasCamera) == "true";

            var previewButton = new IconButton(configureIcon, theme)
            {
                ToolTipText = "Configure Camera View".Localize()
            };
            previewButton.Click += (s, e) =>
            {
                AppContext.Platform.OpenCameraPreview();
            };

            this.AddSettingsRow(
                new SettingsItem(
                    "Camera Monitoring".Localize(),
                    theme,
                    new SettingsItem.ToggleSwitchConfig()
            {
                Checked      = ActiveSliceSettings.Instance.GetValue <bool>(SettingsKey.publish_bed_image),
                ToggleAction = (itemChecked) =>
                {
                    ActiveSliceSettings.Instance.SetValue(SettingsKey.publish_bed_image, itemChecked ? "1" : "0");
                }
            },
                    previewButton,
                    AggContext.StaticData.LoadIcon("camera-24x24.png", 24, 24))
                );
#endif

            // Print Notifications
            var configureNotificationsButton = new IconButton(configureIcon, theme)
            {
                Name        = "Configure Notification Settings Button",
                ToolTipText = "Configure Notifications".Localize(),
                Margin      = new BorderDouble(left: 6),
                VAnchor     = VAnchor.Center
            };
            configureNotificationsButton.Click += (s, e) =>
            {
                if (OpenPrintNotification != null)
                {
                    UiThread.RunOnIdle(OpenPrintNotification);
                }
            };

            AddMenuItem("Help".Localize(), () =>
            {
                UiThread.RunOnIdle(() =>
                {
                    DialogWindow.Show(new HelpPage("AllGuides"));
                });
            });

            this.AddSettingsRow(
                new SettingsItem(
                    "Notifications".Localize(),
                    theme,
                    new SettingsItem.ToggleSwitchConfig()
            {
                Checked      = UserSettings.Instance.get(UserSettingsKey.PrintNotificationsEnabled) == "true",
                ToggleAction = (itemChecked) =>
                {
                    UserSettings.Instance.set(UserSettingsKey.PrintNotificationsEnabled, itemChecked ? "true" : "false");
                }
            },
                    configureNotificationsButton,
                    AggContext.StaticData.LoadIcon("notify-24x24.png")));

            // Touch Screen Mode
            this.AddSettingsRow(
                new SettingsItem(
                    "Touch Screen Mode".Localize(),
                    theme,
                    new SettingsItem.ToggleSwitchConfig()
            {
                Checked      = UserSettings.Instance.get(UserSettingsKey.ApplicationDisplayMode) == "touchscreen",
                ToggleAction = (itemChecked) =>
                {
                    string displayMode = itemChecked ? "touchscreen" : "responsive";
                    if (displayMode != UserSettings.Instance.get(UserSettingsKey.ApplicationDisplayMode))
                    {
                        UserSettings.Instance.set(UserSettingsKey.ApplicationDisplayMode, displayMode);
                        ApplicationController.Instance.ReloadAll();
                    }
                }
            }));

            // LanguageControl
            var languageSelector = new LanguageSelector(theme);
            languageSelector.SelectionChanged += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    string languageCode = languageSelector.SelectedValue;
                    if (languageCode != UserSettings.Instance.get(UserSettingsKey.Language))
                    {
                        UserSettings.Instance.set(UserSettingsKey.Language, languageCode);

                        if (languageCode == "L10N")
                        {
                            GenerateLocalizationValidationFile();
                        }

                        ApplicationController.Instance.ResetTranslationMap();
                        ApplicationController.Instance.ReloadAll();
                    }
                });
            };

            this.AddSettingsRow(new SettingsItem("Language".Localize(), languageSelector, theme));

#if !__ANDROID__
            {
                // ThumbnailRendering
                var thumbnailsModeDropList = new DropDownList("", theme.Colors.PrimaryTextColor, maxHeight: 200, pointSize: theme.DefaultFontSize)
                {
                    BorderColor = theme.GetBorderColor(75)
                };
                thumbnailsModeDropList.AddItem("Flat".Localize(), "orthographic");
                thumbnailsModeDropList.AddItem("3D".Localize(), "raytraced");

                thumbnailsModeDropList.SelectedValue     = UserSettings.Instance.ThumbnailRenderingMode;
                thumbnailsModeDropList.SelectionChanged += (s, e) =>
                {
                    string thumbnailRenderingMode = thumbnailsModeDropList.SelectedValue;
                    if (thumbnailRenderingMode != UserSettings.Instance.ThumbnailRenderingMode)
                    {
                        UserSettings.Instance.ThumbnailRenderingMode = thumbnailRenderingMode;

                        UiThread.RunOnIdle(() =>
                        {
                            // Ask if the user they would like to rebuild their thumbnails
                            StyledMessageBox.ShowMessageBox(
                                (bool rebuildThumbnails) =>
                            {
                                if (rebuildThumbnails)
                                {
                                    string directoryToRemove = ApplicationController.CacheablePath("ItemThumbnails", "");
                                    try
                                    {
                                        if (Directory.Exists(directoryToRemove))
                                        {
                                            Directory.Delete(directoryToRemove, true);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        GuiWidget.BreakInDebugger();
                                    }

                                    Directory.CreateDirectory(directoryToRemove);

                                    ApplicationController.Instance.Library.NotifyContainerChanged();
                                }
                            },
                                "You are switching to a different thumbnail rendering mode. If you want, your current thumbnails can be removed and recreated in the new style. You can switch back and forth at any time. There will be some processing overhead while the new thumbnails are created.\n\nDo you want to rebuild your existing thumbnails now?".Localize(),
                                "Rebuild Thumbnails Now".Localize(),
                                StyledMessageBox.MessageType.YES_NO,
                                "Rebuild".Localize());
                        });
                    }
                };

                this.AddSettingsRow(
                    new SettingsItem(
                        "Thumbnails".Localize(),
                        thumbnailsModeDropList,
                        theme));

                // TextSize
                if (!double.TryParse(UserSettings.Instance.get(UserSettingsKey.ApplicationTextSize), out double currentTexSize))
                {
                    currentTexSize = 1.0;
                }

                double sliderThumbWidth = 10 * GuiWidget.DeviceScale;
                double sliderWidth      = 100 * GuiWidget.DeviceScale;
                var    textSizeSlider   = new SolidSlider(new Vector2(), sliderThumbWidth, .7, 1.4)
                {
                    Name               = "Text Size Slider",
                    Margin             = new BorderDouble(5, 0),
                    Value              = currentTexSize,
                    HAnchor            = HAnchor.Stretch,
                    VAnchor            = VAnchor.Center,
                    TotalWidthInPixels = sliderWidth,
                };

                var optionalContainer = new FlowLayoutWidget()
                {
                    VAnchor = VAnchor.Center | VAnchor.Fit,
                    HAnchor = HAnchor.Fit
                };

                TextWidget sectionLabel = null;

                var textSizeApplyButton = new TextButton("Apply".Localize(), theme)
                {
                    VAnchor         = VAnchor.Center,
                    BackgroundColor = theme.SlightShade,
                    Visible         = false,
                    Margin          = new BorderDouble(right: 6)
                };
                textSizeApplyButton.Click += (s, e) =>
                {
                    GuiWidget.DeviceScale = textSizeSlider.Value;
                    ApplicationController.Instance.ReloadAll();
                };
                optionalContainer.AddChild(textSizeApplyButton);

                textSizeSlider.ValueChanged += (s, e) =>
                {
                    double textSizeNew = textSizeSlider.Value;
                    UserSettings.Instance.set(UserSettingsKey.ApplicationTextSize, textSizeNew.ToString("0.0"));
                    sectionLabel.Text           = "Text Size".Localize() + $" : {textSizeNew:0.0}";
                    textSizeApplyButton.Visible = textSizeNew != currentTexSize;
                };

                var section = new SettingsItem(
                    "Text Size".Localize() + $" : {currentTexSize:0.0}",
                    textSizeSlider,
                    theme,
                    optionalContainer);

                sectionLabel = section.Children <TextWidget>().FirstOrDefault();

                this.AddSettingsRow(section);
            }
#endif

            AddMenuItem("Forums".Localize(), () => ApplicationController.Instance.LaunchBrowser("https://forums.matterhackers.com/category/20/mattercontrol"));
            AddMenuItem("Wiki".Localize(), () => ApplicationController.Instance.LaunchBrowser("http://wiki.mattercontrol.com"));
            AddMenuItem("Guides and Articles".Localize(), () => ApplicationController.Instance.LaunchBrowser("http://www.matterhackers.com/topic/mattercontrol"));
            AddMenuItem("Release Notes".Localize(), () => ApplicationController.Instance.LaunchBrowser("http://wiki.mattercontrol.com/Release_Notes"));
            AddMenuItem("Report a Bug".Localize(), () => ApplicationController.Instance.LaunchBrowser("https://github.com/MatterHackers/MatterControl/issues"));

            var updateMatterControl = new SettingsItem("Check For Update".Localize(), theme);
            updateMatterControl.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    UpdateControlData.Instance.CheckForUpdate();
                    DialogWindow.Show <CheckForUpdatesPage>();
                });
            };
            this.AddSettingsRow(updateMatterControl);

            this.AddChild(new SettingsItem("Theme".Localize(), new GuiWidget(), theme));
            this.AddChild(this.GetThemeControl(theme));

            var aboutMatterControl = new SettingsItem("About".Localize() + " " + ApplicationController.Instance.ProductName, theme);
            if (IntPtr.Size == 8)
            {
                // Push right
                aboutMatterControl.AddChild(new HorizontalSpacer());

                // Add x64 adornment
                var blueBox = new FlowLayoutWidget()
                {
                    Margin      = new BorderDouble(10, 0),
                    Padding     = new BorderDouble(2),
                    Border      = new BorderDouble(1),
                    BorderColor = theme.Colors.PrimaryAccentColor,
                    VAnchor     = VAnchor.Center | VAnchor.Fit,
                };
                blueBox.AddChild(new TextWidget("64", pointSize: 8, textColor: theme.Colors.PrimaryAccentColor));

                aboutMatterControl.AddChild(blueBox);
            }
            aboutMatterControl.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() => DialogWindow.Show <AboutPage>());
            };
            this.AddSettingsRow(aboutMatterControl);
        }
コード例 #15
0
        private void ParseJson(string jsonStr)
        {
            // parse result
            FileInfo[] dirContents = JsonConvert.DeserializeObject <FileInfo[]>(jsonStr);

            var childContainers = new SafeList <ILibraryContainerLink>();

            this.Items.Clear();

            // read in data
            foreach (FileInfo file in dirContents)
            {
                if (file.type == "dir")
                {
                    if (file.name == ".images")
                    {
                        ImageUrlCache = new List <(string name, string url)>();
                        // do the initial load
                        LoadFolderImageUrlCache().Wait();
                    }
                    else
                    {
                        childContainers.Add(new GitHubContainerLink(file.name,
                                                                    Account,
                                                                    Repository,
                                                                    RepoDirectory + "/" + file.name));
                    }
                }
                else if (file.type == "file")
                {
                    if (Path.GetExtension(file.name).ToLower() == ".library")
                    {
                        childContainers.Add(new GitHubLibraryLink(Path.GetFileNameWithoutExtension(file.name),
                                                                  Account,
                                                                  Repository,
                                                                  file.download_url));
                    }
                    else if (file.name == "index.md")
                    {
                        var uri = $"https://raw.githubusercontent.com/{Account}/{Repository}/main/{RepoDirectory}/index.md";
                        WebCache.RetrieveText(uri,
                                              (content) =>
                        {
                            HeaderMarkdown = content;
                            OnContentChanged();
                        },
                                              true,
                                              AddCromeHeaders);
                    }
                    else
                    {
                        this.Items.Add(new GitHubLibraryItem(file.name, file.download_url));
                    }
                }
            }

            Task.Run(async() =>
            {
                foreach (var item in this.Items)
                {
                    // check if we have any of the images cached
                    var thumbnail = await Task.Run(() => ApplicationController.Instance.Thumbnails.LoadCachedImage(item, 256, 256));

                    if (thumbnail != null &&
                        thumbnail.Width == 256)
                    {
                        // save so it is easy to create the upload data for GitHub folders
                        var filename = ApplicationController.CacheablePath(
                            Path.Combine("GitHubImages", this.Repository, this.RepoDirectory.Replace("/", "\\"), ".images"),
                            $"{Path.GetFileNameWithoutExtension(item.Name)}.png");
                        if (!File.Exists(filename))
                        {
                            ImageIO.SaveImageData(filename, thumbnail);
                        }
                    }
                }
            });

            this.ChildContainers = childContainers;

            OnContentChanged();
        }