Ejemplo n.º 1
0
        async Task EADesktopScanAddLibrary()
        {
            try
            {
                //Open the Windows registry
                using (RegistryKey registryKeyLocalMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
                {
                    using (RegistryKey registryKeyUninstall = registryKeyLocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"))
                    {
                        if (registryKeyUninstall != null)
                        {
                            foreach (string uninstallApp in registryKeyUninstall.GetSubKeyNames())
                            {
                                try
                                {
                                    using (RegistryKey installDetails = registryKeyUninstall.OpenSubKey(uninstallApp))
                                    {
                                        string uninstallString = installDetails.GetValue("UninstallString")?.ToString();
                                        if (uninstallString.Contains("EAInstaller"))
                                        {
                                            string appName    = installDetails.GetValue("DisplayName")?.ToString();
                                            string appIcon    = installDetails.GetValue("DisplayIcon")?.ToString().Replace("\"", string.Empty);
                                            string installDir = installDetails.GetValue("InstallLocation")?.ToString().Replace("\"", string.Empty);
                                            await EADesktopAddApplication(appName, appIcon, installDir);
                                        }
                                    }
                                }
                                catch { }
                            }
                        }
                    }
                }
            }
            catch
            {
                Debug.WriteLine("Failed adding EA Desktop library.");
            }

            string EADesktopGetContentID(string installDir)
            {
                try
                {
                    //Open installer data xml file
                    string xmlDataPath = Path.Combine(installDir, @"__Installer\InstallerData.xml");
                    //Debug.WriteLine("EA install xml path: " + xmlDataPath);

                    //Get content ids from data
                    string      contentIds  = string.Empty;
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(xmlDataPath);

                    XmlNodeList nodeIdsList = xmlDocument.GetElementsByTagName("contentIDs");
                    foreach (XmlNode nodeIds in nodeIdsList)
                    {
                        XmlNodeList nodeIdList = nodeIds.SelectNodes("contentID");
                        foreach (XmlNode nodeId in nodeIdList)
                        {
                            contentIds += nodeId.InnerText + ",";
                            contentIds += nodeId.InnerText + "_pc,";
                        }
                    }

                    return(AVFunctions.StringRemoveEnd(contentIds, ","));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Failed to get EA contentID: " + ex.Message);
                    return(string.Empty);
                }
            }

            async Task EADesktopAddApplication(string appName, string appIcon, string installDir)
            {
                try
                {
                    //Get contentIds
                    string contentIds = EADesktopGetContentID(installDir);
                    if (string.IsNullOrWhiteSpace(contentIds))
                    {
                        Debug.WriteLine("No EA contentId found for: " + appName);
                        return;
                    }

                    //Set run command
                    string runCommand = "origin://LaunchGame/" + contentIds;
                    vLauncherAppAvailableCheck.Add(runCommand);

                    //Check if application is already added
                    DataBindApp launcherExistCheck = List_Launchers.Where(x => x.PathExe.ToLower() == runCommand.ToLower()).FirstOrDefault();
                    if (launcherExistCheck != null)
                    {
                        //Debug.WriteLine("EA Desktop app already in list: " + appIds);
                        return;
                    }

                    //Get application name
                    string appNameLower = appName.ToLower();

                    //Check if application name is ignored
                    if (vCtrlIgnoreLauncherName.Any(x => x.String1.ToLower() == appNameLower))
                    {
                        //Debug.WriteLine("Launcher is on the blacklist skipping: " + appName);
                        await ListBoxRemoveAll(lb_Launchers, List_Launchers, x => x.Name.ToLower() == appNameLower);

                        return;
                    }

                    //Get application image
                    BitmapImage iconBitmapImage = FileToBitmapImage(new string[] { appName, appIcon, "EA Desktop" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, 90, 0);

                    //Add the application to the list
                    DataBindApp dataBindApp = new DataBindApp()
                    {
                        Category       = AppCategory.Launcher,
                        Launcher       = AppLauncher.EADesktop,
                        Name           = appName,
                        ImageBitmap    = iconBitmapImage,
                        PathExe        = runCommand,
                        StatusLauncher = vImagePreloadEADesktop
                    };

                    await ListBoxAddItem(lb_Launchers, List_Launchers, dataBindApp, false, false);

                    //Debug.WriteLine("Added EA Desktop app: " + appIds + "/" + appName);
                }
                catch
                {
                    Debug.WriteLine("Failed adding EA Desktop app: " + appName);
                }
            }
        }
Ejemplo n.º 2
0
        //Update the memory information
        void UpdateMemoryInformation(IHardware hardwareItem)
        {
            try
            {
                //Check if the information is visible
                bool showPercentage = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "MemShowPercentage"));
                bool showUsed       = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "MemShowUsed"));
                bool showFree       = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "MemShowFree"));
                bool showTotal      = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "MemShowTotal"));
                if (!showPercentage && !showUsed && !showFree && !showTotal)
                {
                    AVActions.ActionDispatcherInvoke(delegate
                    {
                        stackpanel_CurrentMem.Visibility = Visibility.Collapsed;
                    });
                    return;
                }

                if (hardwareItem.HardwareType == HardwareType.Memory)
                {
                    hardwareItem.Update();
                    string MemoryPercentage = string.Empty;
                    string MemoryBytes      = string.Empty;
                    float  RawMemoryUsed    = 0;
                    float  RawMemoryFree    = 0;

                    foreach (ISensor sensor in hardwareItem.Sensors)
                    {
                        try
                        {
                            if (showPercentage && sensor.SensorType == SensorType.Load)
                            {
                                //Debug.WriteLine("Mem Load Perc: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                MemoryPercentage = " " + Convert.ToInt32(sensor.Value) + "%";
                            }
                            else if (sensor.SensorType == SensorType.Data)
                            {
                                //Debug.WriteLine("Mem Load Data: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Identifier.ToString().EndsWith("data/0"))
                                {
                                    RawMemoryUsed = (float)sensor.Value;
                                }
                                else if (sensor.Identifier.ToString().EndsWith("data/1"))
                                {
                                    RawMemoryFree = (float)sensor.Value;
                                }
                            }
                        }
                        catch { }
                    }

                    if (showUsed)
                    {
                        MemoryBytes += " " + RawMemoryUsed.ToString("0.0") + "GB";
                    }
                    if (showFree)
                    {
                        MemoryBytes += " " + RawMemoryFree.ToString("0.0") + "GB";
                    }
                    if (showTotal)
                    {
                        MemoryBytes += " " + Convert.ToInt32(RawMemoryUsed + RawMemoryFree) + "GB";
                    }

                    if (!string.IsNullOrWhiteSpace(MemoryPercentage) || !string.IsNullOrWhiteSpace(MemoryBytes))
                    {
                        string stringDisplay = AVFunctions.StringRemoveStart(vTitleMEM + MemoryPercentage + MemoryBytes, " ");
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            textblock_CurrentMem.Text        = stringDisplay;
                            stackpanel_CurrentMem.Visibility = Visibility.Visible;
                        });
                    }
                    else
                    {
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            stackpanel_CurrentMem.Visibility = Visibility.Collapsed;
                        });
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 3
0
        //Update the cpu information
        void UpdateCpuInformation(IHardware hardwareItem, float fanSpeedFloat)
        {
            try
            {
                //Check if the information is visible
                bool showName          = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "CpuShowName"));
                bool showPercentage    = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "CpuShowPercentage"));
                bool showTemperature   = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "CpuShowTemperature"));
                bool showCoreFrequency = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "CpuShowCoreFrequency"));
                bool showPowerWatt     = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "CpuShowPowerWatt"));
                bool showPowerVolt     = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "CpuShowPowerVolt"));
                bool showFanSpeed      = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "CpuShowFanSpeed"));
                if (!showName && !showPercentage && !showTemperature && !showCoreFrequency && !showPowerWatt && !showPowerVolt && !showFanSpeed)
                {
                    AVActions.ActionDispatcherInvoke(delegate
                    {
                        stackpanel_CurrentCpu.Visibility = Visibility.Collapsed;
                    });
                    return;
                }

                if (hardwareItem.HardwareType == HardwareType.Cpu)
                {
                    hardwareItem.Update();
                    string CpuName         = string.Empty;
                    string CpuPercentage   = string.Empty;
                    string CpuTemperature  = string.Empty;
                    string CpuFrequency    = string.Empty;
                    string CpuPowerWattage = string.Empty;
                    string CpuPowerVoltage = string.Empty;
                    string CpuFanSpeed     = string.Empty;

                    //Set the cpu name
                    if (showName)
                    {
                        CpuName = hardwareItem.Name;
                    }

                    //Set the cpu fan speed
                    if (showFanSpeed)
                    {
                        CpuFanSpeed = " " + Convert.ToInt32(fanSpeedFloat) + "RPM";
                    }

                    foreach (ISensor sensor in hardwareItem.Sensors)
                    {
                        try
                        {
                            if (showPercentage && sensor.SensorType == SensorType.Load)
                            {
                                //Debug.WriteLine("CPU Load: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Identifier.ToString().EndsWith("load/0"))
                                {
                                    CpuPercentage = " " + Convert.ToInt32(sensor.Value) + "%";
                                }
                            }
                            else if (showTemperature && sensor.SensorType == SensorType.Temperature)
                            {
                                //Debug.WriteLine("CPU Temp: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Name == "CPU Package" || sensor.Name == "CPU Cores")
                                {
                                    float RawCpuTemperature = (float)sensor.Value;
                                    CpuTemperature = " " + RawCpuTemperature.ToString("0") + "°";
                                }
                            }
                            else if (showCoreFrequency && sensor.SensorType == SensorType.Clock)
                            {
                                //Debug.WriteLine("CPU Frequency: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Name == "CPU Core #1")
                                {
                                    float RawCpuFrequency = (float)sensor.Value;
                                    if (RawCpuFrequency < 1000)
                                    {
                                        CpuFrequency = " " + RawCpuFrequency.ToString("0") + "MHz";
                                    }
                                    else
                                    {
                                        CpuFrequency = " " + (RawCpuFrequency / 1000).ToString("0.00") + "GHz";
                                    }
                                }
                            }
                            else if (showPowerWatt && sensor.SensorType == SensorType.Power)
                            {
                                //Debug.WriteLine("CPU Wattage: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Identifier.ToString().EndsWith("power/0"))
                                {
                                    CpuPowerWattage = " " + Convert.ToInt32(sensor.Value) + "W";
                                }
                            }
                            else if (showPowerVolt && sensor.SensorType == SensorType.Voltage)
                            {
                                //Debug.WriteLine("CPU Voltage: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                float RawPowerVoltage = (float)sensor.Value;
                                if (RawPowerVoltage <= 0)
                                {
                                    CpuPowerVoltage = " 0V";
                                }
                                else
                                {
                                    CpuPowerVoltage = " " + RawPowerVoltage.ToString("0.000") + "V";
                                }
                            }
                        }
                        catch { }
                    }

                    bool cpuNameNullOrWhiteSpace = string.IsNullOrWhiteSpace(CpuName);
                    if (!cpuNameNullOrWhiteSpace || !string.IsNullOrWhiteSpace(CpuPercentage) || !string.IsNullOrWhiteSpace(CpuTemperature) || !string.IsNullOrWhiteSpace(CpuFrequency) || !string.IsNullOrWhiteSpace(CpuPowerWattage) || !string.IsNullOrWhiteSpace(CpuPowerVoltage) || !string.IsNullOrWhiteSpace(CpuFanSpeed))
                    {
                        string stringDisplay = string.Empty;
                        string stringStats   = AVFunctions.StringRemoveStart(vTitleCPU + CpuPercentage + CpuTemperature + CpuFrequency + CpuFanSpeed + CpuPowerWattage + CpuPowerVoltage, " ");
                        if (string.IsNullOrWhiteSpace(stringStats))
                        {
                            stringDisplay = CpuName;
                        }
                        else
                        {
                            if (cpuNameNullOrWhiteSpace)
                            {
                                stringDisplay = stringStats;
                            }
                            else
                            {
                                stringDisplay = CpuName + "\n" + stringStats;
                            }
                        }

                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            textblock_CurrentCpu.Text        = stringDisplay;
                            stackpanel_CurrentCpu.Visibility = Visibility.Visible;
                        });
                    }
                    else
                    {
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            stackpanel_CurrentCpu.Visibility = Visibility.Collapsed;
                        });
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 4
0
        //Load item into the viewer
        private async Task LoadItem(string CustomItemContent)
        {
            try
            {
                //Load the full item
                TableItems LoadTable = await SQLConnection.Table <TableItems>().Where(x => x.item_id == vCurrentWebSource.item_id).FirstOrDefaultAsync();

                if (LoadTable != null)
                {
                    //Check if media needs to load
                    AppVariables.LoadMedia = true;
                    if (!NetworkInterface.GetIsNetworkAvailable() && !(bool)AppVariables.ApplicationSettings["DisplayImagesOffline"])
                    {
                        AppVariables.LoadMedia = false;
                    }

                    //Set the date time string
                    DateTime convertedDate    = DateTime.SpecifyKind(LoadTable.item_datetime, DateTimeKind.Utc).ToLocalTime();
                    string   DateAuthorString = convertedDate.ToString(AppVariables.CultureInfoFormat.LongDatePattern, AppVariables.CultureInfoFormat) + ", " + convertedDate.ToString(AppVariables.CultureInfoFormat.ShortTimePattern, AppVariables.CultureInfoFormat);

                    //Add the author to date time
                    if (!string.IsNullOrWhiteSpace(LoadTable.item_author))
                    {
                        DateAuthorString += " by " + LoadTable.item_author;
                    }
                    tb_ItemDateString.Text = DateAuthorString;

                    //Load the item content
                    bool SetHtmlToRichTextBlock = false;
                    if (!string.IsNullOrWhiteSpace(CustomItemContent))
                    {
                        await HtmlToXaml(rtb_ItemContent, CustomItemContent, string.Empty);

                        SetHtmlToRichTextBlock = true;
                    }
                    else if (!string.IsNullOrWhiteSpace(LoadTable.item_content_full))
                    {
                        SetHtmlToRichTextBlock = await HtmlToXaml(rtb_ItemContent, LoadTable.item_content_full, string.Empty);
                    }

                    //Check if html to xaml has failed
                    if (!SetHtmlToRichTextBlock || !rtb_ItemContent.Children.Any())
                    {
                        //Load summary text
                        TextBlock textLabel = new TextBlock();
                        textLabel.Text = AVFunctions.StringCut(LoadTable.item_content, AppVariables.MaximumItemTextLength, "...");

                        //Add paragraph to rich text block
                        rtb_ItemContent.Children.Clear();
                        rtb_ItemContent.Children.Add(textLabel);
                    }

                    //Check if item content contains preview image
                    await CheckItemContentContainsPreviewImage(LoadTable);

                    //Adjust the itemviewer size
                    await AdjustItemViewerSize();
                }
            }
            catch { }
        }
Ejemplo n.º 5
0
        static public async Task <bool> ItemsRead(ObservableCollection <Items> UpdateList, bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Downloading read status...", true);
                }
                System.Diagnostics.Debug.WriteLine("Downloading read status...");

                //Get all stored items from the database
                List <TableItems> CurrentItems = await SQLConnection.Table <TableItems>().ToListAsync();

                if (CurrentItems.Any())
                {
                    //Get last stored item date minus starred items
                    TableItems LastStoredItem = CurrentItems.Where(x => x.item_star_status == false).OrderByDescending(x => x.item_datetime).LastOrDefault();
                    if (LastStoredItem != null)
                    {
                        //Date time calculations
                        DateTime RemoveItemsRange = LastStoredItem.item_datetime.AddHours(-1);
                        //System.Diagnostics.Debug.WriteLine("Downloading read items till: " + LastStoredItem.item_title + "/" + RemoveItemsRange);
                        long UnixTimeTicks = (RemoveItemsRange.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10000000; //Second

                        string[][] RequestHeader  = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                        Uri        DownloadUri    = new Uri(ApiConnectionUrl + "stream/items/ids?output=json&s=user/-/state/com.google/read&n=" + AppVariables.ItemsMaximumLoad + "&ot=" + UnixTimeTicks);
                        string     DownloadString = await AVDownloader.DownloadStringAsync(10000, "News Scroll", RequestHeader, DownloadUri);

                        if (!string.IsNullOrWhiteSpace(DownloadString))
                        {
                            JObject WebJObject = JObject.Parse(DownloadString);
                            if (WebJObject["itemRefs"] != null && WebJObject["itemRefs"].HasValues)
                            {
                                if (!Silent)
                                {
                                    await EventProgressDisableUI("Updating " + WebJObject["itemRefs"].Count() + " read status...", true);
                                }
                                System.Diagnostics.Debug.WriteLine("Updating " + WebJObject["itemRefs"].Count() + " read status...");

                                //Check and set the received read item ids
                                string        ReadUpdateString = string.Empty;
                                List <string> ReadItemsList    = new List <string>();
                                foreach (JToken JTokenRoot in WebJObject["itemRefs"])
                                {
                                    string FoundItemId = JTokenRoot["id"].ToString().Replace(" ", string.Empty).Replace("tag:google.com,2005:reader/item/", string.Empty);
                                    ReadUpdateString += "'" + FoundItemId + "',";
                                    ReadItemsList.Add(FoundItemId);
                                }

                                //Update the read status in database
                                if (ReadItemsList.Any())
                                {
                                    ReadUpdateString = AVFunctions.StringRemoveEnd(ReadUpdateString, ",");
                                    int UpdatedItems = await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_id IN (" + ReadUpdateString + ") AND item_read_status = ('0')");

                                    System.Diagnostics.Debug.WriteLine("Updated read items: " + UpdatedItems);
                                }

                                //Update the read status in list
                                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    try
                                    {
                                        List <Items> ReadItemsIDList = UpdateList.Where(x => x.item_read_status == Visibility.Collapsed && ReadItemsList.Any(y => y == x.item_id)).ToList();
                                        foreach (Items ReadItem in ReadItemsIDList)
                                        {
                                            ReadItem.item_read_status = Visibility.Visible;
                                        }
                                    }
                                    catch { }
                                });

                                //Update the unread status in database
                                string        UnreadUpdateString = string.Empty;
                                List <string> UnreadItemsList    = (await SQLConnection.Table <TableItems>().ToListAsync()).Where(x => x.item_read_status == true && x.item_datetime > RemoveItemsRange).Select(x => x.item_id).Except(ReadItemsList).ToList();
                                foreach (string UnreadItem in UnreadItemsList)
                                {
                                    UnreadUpdateString += "'" + UnreadItem + "',";
                                }
                                if (UnreadItemsList.Any())
                                {
                                    UnreadUpdateString = AVFunctions.StringRemoveEnd(UnreadUpdateString, ",");
                                    int UpdatedItems = await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('0') WHERE item_id IN (" + UnreadUpdateString + ") AND item_read_status = ('1')");

                                    System.Diagnostics.Debug.WriteLine("Updated unread items: " + UpdatedItems);
                                }

                                //Update the unread status in list
                                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    try
                                    {
                                        List <Items> UnreadItemsIDList = UpdateList.Where(x => x.item_read_status == Visibility.Visible && UnreadItemsList.Any(y => y == x.item_id)).ToList();
                                        foreach (Items UnreadItem in UnreadItemsIDList)
                                        {
                                            UnreadItem.item_read_status = Visibility.Collapsed;
                                        }
                                    }
                                    catch { }
                                });
                            }
                        }
                    }
                }

                if (EnableUI)
                {
                    await EventProgressEnableUI();
                }
                return(true);
            }
            catch
            {
                await EventProgressEnableUI();

                return(false);
            }
        }
Ejemplo n.º 6
0
        public async Task AdjustItemsScrollingDirection(Int32 Direction)
        {
            try
            {
                if (!AdjustingItemsScrollingDirection)
                {
                    if (Direction == 0)
                    {
                        Style TargetStyle = (Style)Application.Current.Resources["ListViewVertical"];
                        if (ListView_Items.Style != TargetStyle)
                        {
                            AdjustingItemsScrollingDirection = true;
                            Double[] CurrentOffset = EventsScrollViewer.GetCurrentOffset(ListView_Items);

                            ScrollViewer virtualScrollViewer = AVFunctions.FindVisualChild <ScrollViewer>(ListView_Items);
                            if (virtualScrollViewer != null)
                            {
                                ListView_Items.Style              = TargetStyle;
                                ListView_Items.ItemTemplate       = (DataTemplate)Application.Current.Resources["ListViewItemsVertical" + Convert.ToInt32(AppVariables.ApplicationSettings["ListViewStyle"])];
                                ListView_Items.ItemContainerStyle = (Style)Application.Current.Resources["ListViewItemStretchedVertical"];

                                await Task.Delay(10);

                                virtualScrollViewer.ChangeView(CurrentOffset[1], (CurrentOffset[0] + 2), null);
                                //Debug.WriteLine("Scrolling to vertical:" + (CurrentOffset[0] + 2));
                            }

                            //Adjust Status Current Item margin
                            button_StatusCurrentItem.Margin = new Thickness(6, 0, 0, 6);

                            AdjustingItemsScrollingDirection = false;
                        }
                    }
                    else if (Direction == 1)
                    {
                        Style TargetStyle = (Style)Application.Current.Resources["ListViewHorizontal"];
                        if (ListView_Items.Style != TargetStyle)
                        {
                            AdjustingItemsScrollingDirection = true;
                            Double[] CurrentOffset = EventsScrollViewer.GetCurrentOffset(ListView_Items);

                            ScrollViewer virtualScrollViewer = AVFunctions.FindVisualChild <ScrollViewer>(ListView_Items);
                            if (virtualScrollViewer != null)
                            {
                                ListView_Items.Style              = TargetStyle;
                                ListView_Items.ItemTemplate       = (DataTemplate)Application.Current.Resources["ListViewItemsHorizontal" + Convert.ToInt32(AppVariables.ApplicationSettings["ListViewStyle"])];
                                ListView_Items.ItemContainerStyle = (Style)Application.Current.Resources["ListViewItemStretchedHorizontal"];

                                await Task.Delay(10);

                                virtualScrollViewer.ChangeView((CurrentOffset[1] + 2), CurrentOffset[0], null);
                                //Debug.WriteLine("Scrolling to horizontal:" + (CurrentOffset[1] + 2));
                            }

                            //Adjust Status Current Item margin
                            if (AVFunctions.DevMobile())
                            {
                                button_StatusCurrentItem.Margin = new Thickness(6, 0, 0, 6);
                            }
                            else
                            {
                                button_StatusCurrentItem.Margin = new Thickness(16, 0, 0, 16);
                            }

                            AdjustingItemsScrollingDirection = false;
                        }
                    }
                    else if (Direction == 2)
                    {
                        Rect ScreenSize = AVFunctions.AppWindowResolution();
                        if (ScreenSize.Width > ScreenSize.Height)
                        {
                            await AdjustItemsScrollingDirection(1);
                        }
                        else
                        {
                            await AdjustItemsScrollingDirection(0);
                        }
                    }
                }
            }
            catch { AdjustingItemsScrollingDirection = false; }
        }
Ejemplo n.º 7
0
        private async Task GenerateImage(Span addSpan, HtmlNode htmlNode)
        {
            try
            {
                //Decode the image source link
                string sourceUri = string.Empty;
                if (htmlNode.Attributes["src"] != null)
                {
                    sourceUri = WebUtility.HtmlDecode(htmlNode.Attributes["src"].Value);
                    sourceUri = WebUtility.UrlDecode(sourceUri);
                }
                else if (htmlNode.Attributes["srcset"] != null)
                {
                    sourceUri = WebUtility.HtmlDecode(htmlNode.Attributes["srcset"].Value);
                    sourceUri = WebUtility.UrlDecode(sourceUri);
                }

                //Split an image srcset link
                Regex RegexSourceset = new Regex(@"(?:\s+\d+[wx])(?:,\s+)?");
                IEnumerable <string> ImageSources = RegexSourceset.Split(sourceUri).Where(x => x != string.Empty);
                if (ImageSources.Any())
                {
                    sourceUri = ImageSources.LastOrDefault();
                }

                //Split http(s):// tags from uri
                if (sourceUri.Contains("https://") && sourceUri.LastIndexOf("https://") <= 20)
                {
                    sourceUri = sourceUri.Substring(sourceUri.LastIndexOf("https://"));
                }
                if (sourceUri.Contains("http://") && sourceUri.LastIndexOf("http://") <= 20)
                {
                    sourceUri = sourceUri.Substring(sourceUri.LastIndexOf("http://"));
                }

                //Check if image needs to be blocked
                if (string.IsNullOrWhiteSpace(sourceUri) || AppVariables.BlockedListUrl.Any(sourceUri.ToLower().Contains))
                {
                    Debug.WriteLine("Blocked image: " + sourceUri);
                    return;
                }

                //Check if device is low on memory
                if (AVFunctions.DevMemoryAvailableMB() < 100)
                {
                    grid_item_image img = new grid_item_image();
                    img.item_status.Text = "Image not loaded,\ndevice is low on memory.";
                    img.IsHitTestVisible = false;

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = img;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Check if media is a gif(v) file
                bool ImageIsGif = sourceUri.ToLower().Contains(".gif");
                bool ImageIsSvg = sourceUri.ToLower().Contains(".svg");

                //Check if low bandwidth mode is enabled
                if (ImageIsGif && (bool)AppVariables.ApplicationSettings["LowBandwidthMode"])
                {
                    grid_item_image img = new grid_item_image();
                    img.item_status.Text = "Gif not loaded,\nlow bandwidth mode.";
                    img.IsHitTestVisible = false;

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = img;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Create item image
                Debug.WriteLine("Adding image: " + sourceUri);
                SvgImageSource SvgImage    = null;
                BitmapImage    BitmapImage = null;
                if (ImageIsSvg)
                {
                    SvgImage = await AVImage.LoadSvgImage(sourceUri);
                }
                else
                {
                    BitmapImage = await AVImage.LoadBitmapImage(sourceUri, true);
                }

                if (SvgImage != null || BitmapImage != null)
                {
                    grid_item_image img = new grid_item_image();
                    img.MaxHeight = AppVariables.MaximumItemImageHeight;

                    if (SvgImage != null)
                    {
                        img.item_source.Source = SvgImage;
                    }

                    if (BitmapImage != null)
                    {
                        img.value_item_image = BitmapImage;
                    }

                    //Get and set alt from the image
                    if (vImageShowAlt && htmlNode.Attributes["alt"] != null)
                    {
                        string AltText = Process.ProcessItemTextSummary(htmlNode.Attributes["alt"].Value, false, false);
                        if (!string.IsNullOrWhiteSpace(AltText))
                        {
                            img.item_description.Text       = AltText;
                            img.item_description.Visibility = Visibility.Visible;

                            //Enable or disable text selection
                            if ((bool)AppVariables.ApplicationSettings["ItemTextSelection"])
                            {
                                img.item_description.IsTextSelectionEnabled = true;
                            }
                            else
                            {
                                img.item_description.IsTextSelectionEnabled = false;
                            }
                        }
                    }

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = img;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                }
                else
                {
                    grid_item_image img = new grid_item_image();
                    img.item_status.Text = "Image is not available,\nopen item in browser to view it.";
                    img.IsHitTestVisible = false;

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = img;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }
            }
            catch { }
        }
Ejemplo n.º 8
0
        //Download weather and forecast
        async Task DownloadWeather()
        {
            try
            {
                Debug.WriteLine("Downloading Weather update.");

                //Check for internet connection
                if (!DownloadInternetCheck())
                {
                    BackgroundStatusUpdateSettings("Never", null, null, null, "NoWifiEthernet");
                    return;
                }

                //Check if location is available
                if (String.IsNullOrEmpty(DownloadWeatherLocation))
                {
                    BackgroundStatusUpdateSettings("Never", null, null, null, "NoWeatherLocation");
                    return;
                }

                //Download and save weather summary
                string WeatherSummaryResult = await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://service.weather.microsoft.com/" + DownloadWeatherLanguage + "/weather/summary/" + DownloadWeatherLocation + DownloadWeatherUnits));

                if (!String.IsNullOrEmpty(WeatherSummaryResult))
                {
                    //Update weather summary status
                    UpdateWeatherSummaryStatus(WeatherSummaryResult);

                    //Notification - Current Weather
                    ShowNotiWeatherCurrent();

                    //Save weather summary data
                    await AVFile.SaveText("TimeMeWeatherSummary.js", WeatherSummaryResult);
                }
                else
                {
                    Debug.WriteLine("Failed no weather summary found.");
                    BackgroundStatusUpdateSettings("Failed", null, null, null, "NoWeatherSummary");
                    return;
                }

                //Download and save weather forecast
                string WeatherForecastResult = await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://service.weather.microsoft.com/" + DownloadWeatherLanguage + "/weather/forecast/daily/" + DownloadWeatherLocation + DownloadWeatherUnits));

                if (!String.IsNullOrEmpty(WeatherForecastResult))
                {
                    //Save weather forecast data
                    await AVFile.SaveText("TimeMeWeatherForecast.js", WeatherForecastResult);
                }
                else
                {
                    Debug.WriteLine("Failed no weather forecast found.");
                    BackgroundStatusUpdateSettings("Failed", null, null, null, "NoWeatherForecast");
                    return;
                }

                //Save Weather status
                BgStatusDownloadWeather = DateTimeNow.ToString(vCultureInfoEng);
                vApplicationSettings["BgStatusDownloadWeather"] = BgStatusDownloadWeather;
                BgStatusDownloadWeatherTime = BgStatusDownloadWeather;
                vApplicationSettings["BgStatusDownloadWeatherTime"] = BgStatusDownloadWeather;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed updating the weather info.");
                BackgroundStatusUpdateSettings("Failed", null, null, null, "CatchDownloadWeather" + ex.Message);
            }

            //Update weather summary status
            void UpdateWeatherSummaryStatus(string WeatherSummaryResult)
            {
                try
                {
                    //Check if there is summary data available
                    JObject SummaryJObject = JObject.Parse(WeatherSummaryResult);
                    if (SummaryJObject["responses"][0]["weather"] != null)
                    {
                        //Set Weather Provider Information
                        JToken HttpJTokenProvider = SummaryJObject["responses"][0]["weather"][0]["provider"];
                        if (HttpJTokenProvider["name"] != null)
                        {
                            string Provider = HttpJTokenProvider["name"].ToString();
                            if (!String.IsNullOrEmpty(Provider))
                            {
                                BgStatusWeatherProvider = Provider; vApplicationSettings["BgStatusWeatherProvider"] = BgStatusWeatherProvider;
                            }
                            else
                            {
                                BgStatusWeatherProvider = "N/A"; vApplicationSettings["BgStatusWeatherProvider"] = BgStatusWeatherProvider;
                            }
                        }

                        //Set Weather Current Conditions
                        string Icon               = "";
                        string Condition          = "";
                        string Temperature        = "";
                        string WindSpeedDirection = "";
                        JToken UnitsJToken        = SummaryJObject["units"];
                        JToken HttpJTokenCurrent  = SummaryJObject["responses"][0]["weather"][0]["current"];
                        if (HttpJTokenCurrent["icon"] != null)
                        {
                            Icon = HttpJTokenCurrent["icon"].ToString();
                        }
                        if (HttpJTokenCurrent["cap"] != null)
                        {
                            Condition = HttpJTokenCurrent["cap"].ToString();
                        }
                        if (HttpJTokenCurrent["temp"] != null)
                        {
                            Temperature = HttpJTokenCurrent["temp"].ToString() + "°";
                        }
                        if (HttpJTokenCurrent["windSpd"] != null && HttpJTokenCurrent["windDir"] != null)
                        {
                            WindSpeedDirection = HttpJTokenCurrent["windSpd"].ToString() + " " + UnitsJToken["speed"].ToString() + " " + AVFunctions.DegreesToCardinal(Convert.ToDouble((HttpJTokenCurrent["windDir"].ToString())));
                        }

                        //Set Weather Forecast Conditions
                        string RainChance         = "";
                        string TemperatureLow     = "";
                        string TemperatureHigh    = "";
                        JToken HttpJTokenForecast = SummaryJObject["responses"][0]["weather"][0]["forecast"]["days"][0];
                        if (HttpJTokenForecast["precip"] != null)
                        {
                            RainChance = HttpJTokenForecast["precip"].ToString() + "%";
                        }
                        if (HttpJTokenForecast["tempLo"] != null)
                        {
                            TemperatureLow = HttpJTokenForecast["tempLo"].ToString() + "°";
                        }
                        if (HttpJTokenForecast["tempHi"] != null)
                        {
                            TemperatureHigh = HttpJTokenForecast["tempHi"].ToString() + "°";
                        }

                        //Set Weather Icon
                        if (!String.IsNullOrEmpty(Icon))
                        {
                            BgStatusWeatherCurrentIcon = Icon;
                            vApplicationSettings["BgStatusWeatherCurrentIcon"] = BgStatusWeatherCurrentIcon;
                        }
                        else
                        {
                            BgStatusWeatherCurrentIcon = "0";
                            vApplicationSettings["BgStatusWeatherCurrentIcon"] = BgStatusWeatherCurrentIcon;
                        }

                        //Set Weather Temperature and Condition
                        if (!String.IsNullOrEmpty(Temperature) && !String.IsNullOrEmpty(Condition))
                        {
                            BgStatusWeatherCurrent = AVFunctions.ToTitleCase(Condition) + ", " + Temperature;
                            vApplicationSettings["BgStatusWeatherCurrent"] = BgStatusWeatherCurrent;
                        }
                        else
                        {
                            BgStatusWeatherCurrent = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrent"] = BgStatusWeatherCurrent;
                        }

                        //Set Weather Temperature
                        if (!String.IsNullOrEmpty(Temperature))
                        {
                            BgStatusWeatherCurrentTemp = Temperature;
                            vApplicationSettings["BgStatusWeatherCurrentTemp"] = BgStatusWeatherCurrentTemp;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTemp = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTemp"] = BgStatusWeatherCurrentTemp;
                        }

                        //Set Weather Condition
                        if (!String.IsNullOrEmpty(Condition))
                        {
                            BgStatusWeatherCurrentText = AVFunctions.ToTitleCase(Condition);
                            vApplicationSettings["BgStatusWeatherCurrentText"] = BgStatusWeatherCurrentText;
                        }
                        else
                        {
                            BgStatusWeatherCurrentText = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentText"] = BgStatusWeatherCurrentText;
                        }

                        //Set Weather Wind Speed and Direction
                        if (!String.IsNullOrEmpty(WindSpeedDirection))
                        {
                            BgStatusWeatherCurrentWindSpeed = WindSpeedDirection;
                            vApplicationSettings["BgStatusWeatherCurrentWindSpeed"] = BgStatusWeatherCurrentWindSpeed;
                        }
                        else
                        {
                            BgStatusWeatherCurrentWindSpeed = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentWindSpeed"] = BgStatusWeatherCurrentWindSpeed;
                        }

                        //Set Weather Rain Chance
                        if (!String.IsNullOrEmpty(RainChance))
                        {
                            BgStatusWeatherCurrentRainChance = RainChance;
                            vApplicationSettings["BgStatusWeatherCurrentRainChance"] = BgStatusWeatherCurrentRainChance;
                        }
                        else
                        {
                            BgStatusWeatherCurrentRainChance = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentRainChance"] = BgStatusWeatherCurrentRainChance;
                        }

                        //Set Weather Temp Low
                        if (!String.IsNullOrEmpty(TemperatureLow))
                        {
                            BgStatusWeatherCurrentTempLow = TemperatureLow;
                            vApplicationSettings["BgStatusWeatherCurrentTempLow"] = BgStatusWeatherCurrentTempLow;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTempLow = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTempLow"] = BgStatusWeatherCurrentTempLow;
                        }

                        //Set Weather Temp High
                        if (!String.IsNullOrEmpty(TemperatureHigh))
                        {
                            BgStatusWeatherCurrentTempHigh = TemperatureHigh;
                            vApplicationSettings["BgStatusWeatherCurrentTempHigh"] = BgStatusWeatherCurrentTempHigh;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTempHigh = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTempHigh"] = BgStatusWeatherCurrentTempHigh;
                        }
                    }
                }
                catch { }
            }
        }
Ejemplo n.º 9
0
        //Add feed to the api
        private async Task AddFeedToApi()
        {
            try
            {
                //Check if user is logged in
                if (!CheckLogin())
                {
                    await AVMessageBox.Popup("Not logged in", "Adding a feed can only be done when you are logged in.", "Ok", "", "", "", "", false);

                    return;
                }

                //Check for internet connection
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    await AVMessageBox.Popup("No internet connection", "Adding a feed can only be done when there is an internet connection available.", "Ok", "", "", "", "", false);

                    return;
                }

                //Remove ending / characters from the url
                txtbox_AddFeed.Text = AVFunctions.StringRemoveEnd(txtbox_AddFeed.Text, "/");

                //Check if there is an url entered
                if (String.IsNullOrWhiteSpace(txtbox_AddFeed.Text))
                {
                    //Focus on the text box to open keyboard
                    txtbox_AddFeed.IsEnabled = false;
                    txtbox_AddFeed.IsEnabled = true;
                    txtbox_AddFeed.Focus(FocusState.Programmatic);
                    return;
                }

                //Validate the url entered
                if (!Regex.IsMatch(txtbox_AddFeed.Text, @"^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$"))
                {
                    await AVMessageBox.Popup("Invalid feed link", "The entered feed link is invalid or does not contain a feed, please check your link and try again.", "Ok", "", "", "", "", false);

                    //Focus on the text box to open keyboard
                    txtbox_AddFeed.IsEnabled = false;
                    txtbox_AddFeed.IsEnabled = true;
                    txtbox_AddFeed.Focus(FocusState.Programmatic);
                    return;
                }

                await ProgressDisableUI("Adding feed: " + txtbox_AddFeed.Text, true);

                if (await AddFeed(txtbox_AddFeed.Text))
                {
                    //Reset the online status
                    OnlineUpdateFeeds   = true;
                    OnlineUpdateNews    = true;
                    OnlineUpdateStarred = true;
                    ApiMessageError     = String.Empty;

                    //Reset the last update setting
                    AppVariables.ApplicationSettings["LastItemsUpdate"] = "Never";

                    //Reset the textbox entry
                    txtbox_AddFeed.Text = String.Empty;

                    //Load all the feeds
                    await LoadFeeds();
                }
                else
                {
                    //Focus on the text box to open keyboard
                    txtbox_AddFeed.IsEnabled = false;
                    txtbox_AddFeed.IsEnabled = true;
                    txtbox_AddFeed.Focus(FocusState.Programmatic);
                }

                await ProgressEnableUI();
            }
            catch { }
        }
Ejemplo n.º 10
0
        public static async Task ApplicationStart()
        {
            try
            {
                //Check application settings
                SettingsPage.SettingsCheck();

                //Adjust the title bar color
                await AppAdjust.AdjustTitleBarColor(null, true, true);

                //Adjust the color theme
                AppAdjust.AdjustColorTheme();

                //Adjust the font sizes
                AppAdjust.AdjustFontSizes();

                //Adjust application user agent
                //AppAdjust.AdjustUserAgent();

                //Set Landscape Display
                if ((bool)AppVariables.ApplicationSettings["DisableLandscapeDisplay"])
                {
                    DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;
                }
                else
                {
                    DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait | DisplayOrientations.Landscape;
                }

                //Calculate the maximum preload items
                Size ScreenResolution = AVFunctions.DevScreenResolution();
                if (ScreenResolution.Width > ScreenResolution.Height)
                {
                    AppVariables.ContentToScrollLoad = Convert.ToInt32(ScreenResolution.Width / 280) + 4;
                }
                else
                {
                    AppVariables.ContentToScrollLoad = Convert.ToInt32(ScreenResolution.Height / 280) + 4;
                }
                Debug.WriteLine("Preload items has been set to: " + AppVariables.ContentToScrollLoad);

                //Connect to the database
                if (!DatabaseConnect())
                {
                    MessageDialog MessageDialog = new MessageDialog("Your database will be cleared, please restart the application to continue.", "Failed to connect to the database");
                    await MessageDialog.ShowAsync();

                    await DatabaseReset();

                    Application.Current.Exit();
                    return;
                }

                //Create the database tables
                await DatabaseCreate();

                //Register application timers
                AppTimers.TimersRegister();

                //Register application events
                Events.Events.EventsRegister();

                //Check if all items need to load
                if ((bool)AppVariables.ApplicationSettings["LoadAllItems"])
                {
                    AppVariables.ItemsToScrollLoad = 100000;
                }

                //Prevent application lock screen
                try { AppVariables.DisplayRequest.RequestActive(); } catch { }
            }
            catch { }
        }
Ejemplo n.º 11
0
        //Get and list all files and folders
        async Task PickerLoadFilesFolders(string targetPath, int targetIndex)
        {
            try
            {
                //Clean the target path string
                targetPath = Path.GetFullPath(targetPath);

                //Add the Go up directory to the list
                if (Path.GetPathRoot(targetPath) != targetPath)
                {
                    BitmapImage  imageBack        = FileToBitmapImage(new string[] { "Assets/Default/Icons/Up.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0);
                    DataBindFile dataBindFileGoUp = new DataBindFile()
                    {
                        FileType = FileType.GoUpPre, Name = "Go up", Description = "Go up to the previous folder.", ImageBitmap = imageBack, PathFile = Path.GetDirectoryName(targetPath)
                    };
                    await ListBoxAddItem(lb_FilePicker, List_FilePicker, dataBindFileGoUp, false, false);
                }
                else
                {
                    BitmapImage  imageBack        = FileToBitmapImage(new string[] { "Assets/Default/Icons/Up.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0);
                    DataBindFile dataBindFileGoUp = new DataBindFile()
                    {
                        FileType = FileType.GoUpPre, Name = "Go up", Description = "Go up to the previous folder.", ImageBitmap = imageBack, PathFile = "PC"
                    };
                    await ListBoxAddItem(lb_FilePicker, List_FilePicker, dataBindFileGoUp, false, false);
                }

                AVActions.ActionDispatcherInvoke(delegate
                {
                    //Enable or disable the copy paste status
                    if (vClipboardFiles.Any())
                    {
                        grid_Popup_FilePicker_textblock_ClipboardStatus.Visibility = Visibility.Visible;
                    }

                    //Enable or disable the current path
                    grid_Popup_FilePicker_textblock_CurrentPath.Text       = "Current path: " + targetPath;
                    grid_Popup_FilePicker_textblock_CurrentPath.Visibility = Visibility.Visible;
                });

                //Add launch emulator options
                if (vFilePickerShowRoms)
                {
                    string       fileDescription        = "Launch the emulator without a rom loaded";
                    BitmapImage  fileImage              = FileToBitmapImage(new string[] { "Assets/Default/Icons/Emulator.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0);
                    DataBindFile dataBindFileWithoutRom = new DataBindFile()
                    {
                        FileType = FileType.FilePre, Name = fileDescription, Description = fileDescription + ".", ImageBitmap = fileImage, PathFile = string.Empty
                    };
                    await ListBoxAddItem(lb_FilePicker, List_FilePicker, dataBindFileWithoutRom, false, false);

                    string       romDescription        = "Launch the emulator with this folder as rom";
                    BitmapImage  romImage              = FileToBitmapImage(new string[] { "Assets/Default/Icons/Emulator.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0);
                    DataBindFile dataBindFileFolderRom = new DataBindFile()
                    {
                        FileType = FileType.FilePre, Name = romDescription, Description = romDescription + ".", ImageBitmap = romImage, PathFile = targetPath
                    };
                    await ListBoxAddItem(lb_FilePicker, List_FilePicker, dataBindFileFolderRom, false, false);
                }

                //Enable or disable the side navigate buttons
                AVActions.ActionDispatcherInvoke(delegate
                {
                    grid_Popup_FilePicker_button_ControllerLeft.Visibility  = Visibility.Visible;
                    grid_Popup_FilePicker_button_ControllerUp.Visibility    = Visibility.Visible;
                    grid_Popup_FilePicker_button_ControllerStart.Visibility = Visibility.Visible;
                });

                //Get all the top files and folders
                DirectoryInfo   directoryInfo    = new DirectoryInfo(targetPath);
                DirectoryInfo[] directoryFolders = null;
                FileInfo[]      directoryFiles   = null;
                if (vFilePickerSortType == SortingType.Name)
                {
                    directoryFolders = directoryInfo.GetDirectories("*", SearchOption.TopDirectoryOnly).OrderBy(x => x.Name).ToArray();
                    directoryFiles   = directoryInfo.GetFiles("*", SearchOption.TopDirectoryOnly).OrderBy(x => x.Name).ToArray();
                }
                else
                {
                    directoryFolders = directoryInfo.GetDirectories("*", SearchOption.TopDirectoryOnly).OrderByDescending(x => x.LastWriteTime).ToArray();
                    directoryFiles   = directoryInfo.GetFiles("*", SearchOption.TopDirectoryOnly).OrderByDescending(x => x.LastWriteTime).ToArray();
                }

                //Get all rom images and descriptions
                FileInfo[] directoryRomImages       = new FileInfo[] { };
                FileInfo[] directoryRomDescriptions = new FileInfo[] { };
                if (vFilePickerShowRoms)
                {
                    string[] imageFilter       = { "jpg", "png" };
                    string[] descriptionFilter = { "json" };

                    DirectoryInfo          directoryInfoRomsUser     = new DirectoryInfo("Assets/User/Games");
                    FileInfo[]             directoryPathsRomsUser    = directoryInfoRomsUser.GetFiles("*", SearchOption.AllDirectories);
                    DirectoryInfo          directoryInfoRomsDefault  = new DirectoryInfo("Assets/Default/Games");
                    FileInfo[]             directoryPathsRomsDefault = directoryInfoRomsDefault.GetFiles("*", SearchOption.AllDirectories);
                    IEnumerable <FileInfo> directoryPathsRoms        = directoryPathsRomsUser.Concat(directoryPathsRomsDefault);

                    FileInfo[] romsImages  = directoryPathsRoms.Where(file => imageFilter.Any(filter => file.Name.EndsWith(filter, StringComparison.InvariantCultureIgnoreCase))).ToArray();
                    FileInfo[] filesImages = directoryFiles.Where(file => imageFilter.Any(filter => file.Name.EndsWith(filter, StringComparison.InvariantCultureIgnoreCase))).ToArray();
                    directoryRomImages = filesImages.Concat(romsImages).OrderByDescending(x => x.Name.Length).ToArray();

                    FileInfo[] romsDescriptions  = directoryPathsRoms.Where(file => descriptionFilter.Any(filter => file.Name.EndsWith(filter, StringComparison.InvariantCultureIgnoreCase))).ToArray();
                    FileInfo[] filesDescriptions = directoryFiles.Where(file => descriptionFilter.Any(filter => file.Name.EndsWith(filter, StringComparison.InvariantCultureIgnoreCase))).ToArray();
                    directoryRomDescriptions = filesDescriptions.Concat(romsDescriptions).OrderByDescending(x => x.Name.Length).ToArray();
                }

                //Get all the directories from target directory
                if (vFilePickerShowDirectories)
                {
                    try
                    {
                        //Fill the file picker listbox with folders
                        foreach (DirectoryInfo listFolder in directoryFolders)
                        {
                            try
                            {
                                //Cancel loading
                                if (vFilePickerLoadCancel)
                                {
                                    Debug.WriteLine("File picker folder load cancelled.");
                                    vFilePickerLoadCancel = false;
                                    vFilePickerLoadBusy   = false;
                                    return;
                                }

                                BitmapImage listImage       = null;
                                string      listDescription = string.Empty;

                                //Load image files for the list
                                if (vFilePickerShowRoms)
                                {
                                    GetRomDetails(listFolder.Name, listFolder.FullName, directoryRomImages, directoryRomDescriptions, ref listImage, ref listDescription);
                                }
                                else
                                {
                                    listImage = FileToBitmapImage(new string[] { "Assets/Default/Icons/Folder.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0);
                                }

                                //Get the folder size
                                //string folderSize = AVFunctions.ConvertBytesSizeToString(GetDirectorySize(listDirectory));

                                //Get the folder date
                                string folderDate = listFolder.LastWriteTime.ToShortDateString().Replace("-", "/");

                                //Set the detailed text
                                string folderDetailed = folderDate;

                                //Check the copy cut type
                                ClipboardType clipboardType = ClipboardType.None;
                                DataBindFile  clipboardFile = vClipboardFiles.Where(x => x.PathFile == listFolder.FullName).FirstOrDefault();
                                if (clipboardFile != null)
                                {
                                    clipboardType = clipboardFile.ClipboardType;
                                }

                                //Add folder to the list
                                bool systemFileFolder = listFolder.Attributes.HasFlag(FileAttributes.System);
                                bool hiddenFileFolder = listFolder.Attributes.HasFlag(FileAttributes.Hidden);
                                if (!systemFileFolder && (!hiddenFileFolder || Convert.ToBoolean(Setting_Load(vConfigurationCtrlUI, "ShowHiddenFilesFolders"))))
                                {
                                    DataBindFile dataBindFileFolder = new DataBindFile()
                                    {
                                        FileType = FileType.Folder, ClipboardType = clipboardType, Name = listFolder.Name, NameDetail = folderDetailed, Description = listDescription, DateModified = listFolder.LastWriteTime, ImageBitmap = listImage, PathFile = listFolder.FullName
                                    };
                                    await ListBoxAddItem(lb_FilePicker, List_FilePicker, dataBindFileFolder, false, false);
                                }
                            }
                            catch { }
                        }
                    }
                    catch { }
                }

                //Get all the files from target directory
                if (vFilePickerShowFiles)
                {
                    try
                    {
                        //Enable or disable selection button in the list
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            grid_Popup_FilePicker_button_SelectFolder.Visibility = Visibility.Collapsed;
                        });

                        //Filter files in and out
                        if (vFilePickerFilterIn.Any())
                        {
                            directoryFiles = directoryFiles.Where(file => vFilePickerFilterIn.Any(filter => file.Name.EndsWith(filter, StringComparison.InvariantCultureIgnoreCase))).ToArray();
                        }
                        if (vFilePickerFilterOut.Any())
                        {
                            directoryFiles = directoryFiles.Where(file => !vFilePickerFilterOut.Any(filter => file.Name.EndsWith(filter, StringComparison.InvariantCultureIgnoreCase))).ToArray();
                        }

                        //Fill the file picker listbox with files
                        foreach (FileInfo listFile in directoryFiles)
                        {
                            try
                            {
                                //Cancel loading
                                if (vFilePickerLoadCancel)
                                {
                                    Debug.WriteLine("File picker file load cancelled.");
                                    vFilePickerLoadCancel = false;
                                    vFilePickerLoadBusy   = false;
                                    return;
                                }

                                BitmapImage listImage       = null;
                                string      listDescription = string.Empty;

                                //Load image files for the list
                                if (vFilePickerShowRoms)
                                {
                                    GetRomDetails(listFile.Name, string.Empty, directoryRomImages, directoryRomDescriptions, ref listImage, ref listDescription);
                                }
                                else
                                {
                                    string listFileFullNameLower  = listFile.FullName.ToLower();
                                    string listFileExtensionLower = listFile.Extension.ToLower().Replace(".", string.Empty);
                                    if (listFileFullNameLower.EndsWith(".jpg") || listFileFullNameLower.EndsWith(".png") || listFileFullNameLower.EndsWith(".gif"))
                                    {
                                        listImage = FileToBitmapImage(new string[] { listFile.FullName }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, 50, 0);
                                    }
                                    else
                                    {
                                        listImage = FileToBitmapImage(new string[] { "Assets/Default/Extensions/" + listFileExtensionLower + ".png", "Assets/Default/Icons/File.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, 50, 0);
                                    }
                                }

                                //Get the file size
                                string fileSize = AVFunctions.ConvertBytesSizeToString(listFile.Length);

                                //Get the file date
                                string fileDate = listFile.LastWriteTime.ToShortDateString().Replace("-", "/");

                                //Set the detailed text
                                string fileDetailed = fileSize + " (" + fileDate + ")";

                                //Check the copy cut type
                                ClipboardType clipboardType = ClipboardType.None;
                                DataBindFile  clipboardFile = vClipboardFiles.Where(x => x.PathFile == listFile.FullName).FirstOrDefault();
                                if (clipboardFile != null)
                                {
                                    clipboardType = clipboardFile.ClipboardType;
                                }

                                //Add file to the list
                                bool systemFileFolder = listFile.Attributes.HasFlag(FileAttributes.System);
                                bool hiddenFileFolder = listFile.Attributes.HasFlag(FileAttributes.Hidden);
                                if (!systemFileFolder && (!hiddenFileFolder || Convert.ToBoolean(Setting_Load(vConfigurationCtrlUI, "ShowHiddenFilesFolders"))))
                                {
                                    FileType fileType      = FileType.File;
                                    string   fileExtension = Path.GetExtension(listFile.Name);
                                    if (fileExtension == ".url" || fileExtension == ".lnk")
                                    {
                                        fileType = FileType.Link;
                                    }
                                    DataBindFile dataBindFileFile = new DataBindFile()
                                    {
                                        FileType = fileType, ClipboardType = clipboardType, Name = listFile.Name, NameDetail = fileDetailed, Description = listDescription, DateModified = listFile.LastWriteTime, ImageBitmap = listImage, PathFile = listFile.FullName
                                    };
                                    await ListBoxAddItem(lb_FilePicker, List_FilePicker, dataBindFileFile, false, false);
                                }
                            }
                            catch { }
                        }
                    }
                    catch { }
                }
                else
                {
                    //Enable or disable selection button in the list
                    AVActions.ActionDispatcherInvoke(delegate
                    {
                        grid_Popup_FilePicker_button_SelectFolder.Visibility = Visibility.Visible;
                    });
                }

                //Check if there are files or folders
                FilePicker_CheckFilesAndFoldersCount();
            }
            catch { }
        }
Ejemplo n.º 12
0
        //Load item into the viewer
        private async Task LoadItem(string CustomItemContent)
        {
            try
            {
                //Set item bindings
                Binding binding_item_title = new Binding();
                binding_item_title.Source = vCurrentItem;
                binding_item_title.Path   = new PropertyPath("item_title");
                tb_ItemTitle.SetBinding(TextBlock.TextProperty, binding_item_title);

                Binding binding_item_datestring = new Binding();
                binding_item_datestring.Source = vCurrentItem;
                binding_item_datestring.Path   = new PropertyPath("item_datestring");
                tb_ItemDateString.SetBinding(TextBlock.TextProperty, binding_item_datestring);

                Binding binding_item_read_status = new Binding();
                binding_item_read_status.Source = vCurrentItem;
                binding_item_read_status.Path   = new PropertyPath("item_read_status");
                image_item_read_status.SetBinding(Image.VisibilityProperty, binding_item_read_status);

                Binding binding_item_star_status = new Binding();
                binding_item_star_status.Source = vCurrentItem;
                binding_item_star_status.Path   = new PropertyPath("item_star_status");
                image_item_star_status.SetBinding(Image.VisibilityProperty, binding_item_star_status);

                Binding binding_feed_icon = new Binding();
                binding_feed_icon.Source = vCurrentItem;
                binding_feed_icon.Path   = new PropertyPath("feed_icon");
                image_feed_icon.SetBinding(Image.SourceProperty, binding_feed_icon);

                Binding binding_feed_title = new Binding();
                binding_feed_title.Source = vCurrentItem;
                binding_feed_title.Path   = new PropertyPath("feed_title");

                ToolTip header_tooltip = new ToolTip();
                header_tooltip.SetBinding(ToolTip.ContentProperty, binding_feed_title);
                ToolTipService.SetToolTip(stackpanel_HeaderItem, header_tooltip);

                //Load the full item
                TableItems LoadTable = await SQLConnection.Table <TableItems>().Where(x => x.item_id == vCurrentItem.item_id).FirstOrDefaultAsync();

                if (LoadTable != null)
                {
                    //Load the item content
                    bool SetHtmlToRichTextBlock = false;
                    if (!string.IsNullOrWhiteSpace(CustomItemContent))
                    {
                        await HtmlToXaml(popup_ItemContent, CustomItemContent, string.Empty);

                        SetHtmlToRichTextBlock = true;
                    }
                    else if (!string.IsNullOrWhiteSpace(LoadTable.item_content_full))
                    {
                        SetHtmlToRichTextBlock = await HtmlToXaml(popup_ItemContent, LoadTable.item_content_full, string.Empty);
                    }

                    //Check if html to xaml has failed
                    if (!SetHtmlToRichTextBlock || !popup_ItemContent.Children.Any())
                    {
                        //Load summary text
                        TextBlock textLabel = new TextBlock();
                        textLabel.Text = AVFunctions.StringCut(LoadTable.item_content, AppVariables.MaximumItemTextLength, "...");

                        //Add paragraph to rich text block
                        popup_ItemContent.Children.Clear();
                        popup_ItemContent.Children.Add(textLabel);
                    }

                    //Check if item content contains preview image
                    CheckItemContentContainsPreviewImage(LoadTable);
                }
            }
            catch { }
        }
Ejemplo n.º 13
0
        //Download game information
        public async Task <DownloadInfoGame> DownloadInfoGame(string nameRom, int imageWidth, bool saveOriginalName)
        {
            try
            {
                //Filter the game name
                string nameRomSaveOriginal = FilterNameFile(nameRom);
                string nameRomSaveFilter   = FilterNameRom(nameRom, true, false, true, 0);

                //Show the text input popup
                string nameRomDownload = await Popup_ShowHide_TextInput("Game search", nameRomSaveFilter, "Search information for the game", true);

                if (string.IsNullOrWhiteSpace(nameRomDownload))
                {
                    Debug.WriteLine("No search term entered.");
                    return(null);
                }
                nameRomDownload = nameRomDownload.ToLower();

                await Notification_Send_Status("Download", "Downloading information");

                Debug.WriteLine("Downloading information for: " + nameRom);

                //Download available games
                IEnumerable <ApiIGDBGames> iGDBGames = await ApiIGDB_DownloadGames(nameRomDownload);

                if (iGDBGames == null || !iGDBGames.Any())
                {
                    Debug.WriteLine("No games found");
                    await Notification_Send_Status("Close", "No games found");

                    return(null);
                }

                //Ask user which game to download
                List <DataBindString> Answers     = new List <DataBindString>();
                BitmapImage           imageAnswer = FileToBitmapImage(new string[] { "Assets/Default/Icons/Game.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0);
                foreach (ApiIGDBGames infoGames in iGDBGames)
                {
                    //Check if information is available
                    if (infoGames.cover == 0 && string.IsNullOrWhiteSpace(infoGames.summary))
                    {
                        continue;
                    }

                    //Release date
                    string gameReleaseDate = string.Empty;
                    string gameReleaseYear = string.Empty;
                    ApiIGDB_ReleaseDateToString(infoGames, out gameReleaseDate, out gameReleaseYear);

                    //Game platforms
                    string gamePlatforms = string.Empty;
                    if (infoGames.platforms != null)
                    {
                        foreach (int platformId in infoGames.platforms)
                        {
                            ApiIGDBPlatforms apiIGDBPlatforms = vApiIGDBPlatforms.Where(x => x.id == platformId).FirstOrDefault();
                            gamePlatforms = AVFunctions.StringAdd(gamePlatforms, apiIGDBPlatforms.name, ",");
                        }
                    }

                    DataBindString answerDownload = new DataBindString();
                    answerDownload.ImageBitmap = imageAnswer;
                    answerDownload.Name        = infoGames.name;
                    answerDownload.NameSub     = gamePlatforms;
                    answerDownload.NameDetail  = gameReleaseYear;
                    answerDownload.Data1       = infoGames;
                    Answers.Add(answerDownload);
                }

                //Get selected result
                DataBindString messageResult = await Popup_Show_MessageBox("Select a found game (" + Answers.Count() + ")", "* Information will be saved in the \"Assets\\User\\Games\\Downloaded\" folder as:\n" + nameRomSaveFilter, "Download image and description for the game:", Answers);

                if (messageResult == null)
                {
                    Debug.WriteLine("No game selected");
                    return(null);
                }

                //Create downloaded directory
                AVFiles.Directory_Create("Assets/User/Games/Downloaded", false);

                //Convert result back to json
                ApiIGDBGames selectedGame = (ApiIGDBGames)messageResult.Data1;

                await Notification_Send_Status("Download", "Downloading image");

                Debug.WriteLine("Downloading image for: " + nameRom);

                //Get the image url
                BitmapImage downloadedBitmapImage = null;
                string      downloadImageId       = selectedGame.cover.ToString();
                if (downloadImageId != "0")
                {
                    ApiIGDBImage[] iGDBImages = await ApiIGDB_DownloadImage(downloadImageId, "covers");

                    if (iGDBImages == null || !iGDBImages.Any())
                    {
                        Debug.WriteLine("No images found");
                        await Notification_Send_Status("Close", "No images found");

                        return(null);
                    }

                    //Download and save image
                    ApiIGDBImage infoImages = iGDBImages.FirstOrDefault();
                    Uri          imageUri   = new Uri("https://images.igdb.com/igdb/image/upload/t_720p/" + infoImages.image_id + ".png");
                    byte[]       imageBytes = await AVDownloader.DownloadByteAsync(5000, "CtrlUI", null, imageUri);

                    if (imageBytes != null && imageBytes.Length > 256)
                    {
                        try
                        {
                            //Convert bytes to a BitmapImage
                            downloadedBitmapImage = BytesToBitmapImage(imageBytes, imageWidth);

                            //Save bytes to image file
                            if (saveOriginalName)
                            {
                                File.WriteAllBytes("Assets/User/Games/Downloaded/" + nameRomSaveOriginal + ".png", imageBytes);
                            }
                            else
                            {
                                File.WriteAllBytes("Assets/User/Games/Downloaded/" + nameRomSaveFilter + ".png", imageBytes);
                            }

                            Debug.WriteLine("Saved image: " + imageBytes.Length + "bytes/" + imageUri);
                        }
                        catch { }
                    }
                }

                //Json settings
                JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
                jsonSettings.NullValueHandling = NullValueHandling.Ignore;

                //Json serialize
                string serializedObject = JsonConvert.SerializeObject(selectedGame, jsonSettings);

                //Save json information
                if (saveOriginalName)
                {
                    File.WriteAllText("Assets/User/Games/Downloaded/" + nameRomSaveOriginal + ".json", serializedObject);
                }
                else
                {
                    File.WriteAllText("Assets/User/Games/Downloaded/" + nameRomSaveFilter + ".json", serializedObject);
                }

                await Notification_Send_Status("Download", "Downloaded information");

                Debug.WriteLine("Downloaded and saved information for: " + nameRom);

                //Return the information
                DownloadInfoGame downloadInfo = new DownloadInfoGame();
                downloadInfo.ImageBitmap = downloadedBitmapImage;
                downloadInfo.Details     = selectedGame;
                return(downloadInfo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed downloading game information: " + ex.Message);
                await Notification_Send_Status("Close", "Failed downloading");

                return(null);
            }
        }
Ejemplo n.º 14
0
        public static async Task Application_LaunchCheck(string applicationName, ProcessPriorityClass priorityLevel, bool skipFileCheck, bool focusActiveProcess)
        {
            try
            {
                Debug.WriteLine("Checking application status.");
                Process   currentProcess  = Process.GetCurrentProcess();
                string    processName     = currentProcess.ProcessName;
                Process[] activeProcesses = Process.GetProcessesByName(processName);

                //Check - If application is already running
                if (activeProcesses.Length > 1)
                {
                    Debug.WriteLine("Application is already running.");

                    //Show the active process
                    if (focusActiveProcess)
                    {
                        foreach (Process activeProcess in activeProcesses)
                        {
                            try
                            {
                                if (currentProcess.Id != activeProcess.Id)
                                {
                                    Debug.WriteLine("Showing active process: " + activeProcess.Id);
                                    await FocusProcessWindow(applicationName, activeProcess.Id, activeProcess.MainWindowHandle, 0, false, false);
                                }
                            }
                            catch { }
                        }
                    }

                    //Close the current process
                    Debug.WriteLine("Closing the process.");
                    Environment.Exit(0);
                    return;
                }

                //Set the working directory to executable directory
                try
                {
                    Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
                }
                catch { }

                //Set the application priority level
                try
                {
                    currentProcess.PriorityClass = priorityLevel;
                }
                catch { }

                //Check - Windows version check
                if (AVFunctions.DevOsVersion() < 10)
                {
                    MessageBox.Show(applicationName + " only supports Windows 10 or newer.", applicationName);
                    Environment.Exit(0);
                    return;
                }

                //Check for missing application files
                if (!skipFileCheck)
                {
                    ApplicationFiles = ApplicationFiles.Concat(ProfileFiles).Concat(ResourcesFiles).Concat(AssetsDefaultFiles).ToArray();
                    foreach (string checkFile in ApplicationFiles)
                    {
                        try
                        {
                            if (!File.Exists(checkFile))
                            {
                                MessageBox.Show("File: " + checkFile + " could not be found, please check your installation.", applicationName);
                                Environment.Exit(0);
                                return;
                            }
                        }
                        catch { }
                    }
                }

                //Check for missing user folders
                AVFiles.Directory_Create(@"Assets\User\Apps", false);
                AVFiles.Directory_Create(@"Assets\User\Clocks", false);
                AVFiles.Directory_Create(@"Assets\User\Fonts", false);
                AVFiles.Directory_Create(@"Assets\User\Games", false);
                AVFiles.Directory_Create(@"Assets\User\Sounds", false);
            }
            catch { }
        }
Ejemplo n.º 15
0
        //Adjust the news items scrolling direction
        public async Task AdjustItemsScrollingDirection(int Direction)
        {
            try
            {
                if (Direction == 0)
                {
                    Style TargetStyle = (Style)Application.Current.Resources["ListViewVertical"];
                    if (ListView_Items.Style != TargetStyle)
                    {
                        ScrollViewer virtualScrollViewer = AVFunctions.FindVisualChild <ScrollViewer>(ListView_Items);
                        if (virtualScrollViewer != null)
                        {
                            object CurrentOffset = EventsScrollViewer.GetCurrentOffsetItem(ListView_Items);
                            ListView_Items.Style              = TargetStyle;
                            ListView_Items.ItemTemplate       = (DataTemplate)Application.Current.Resources["ListViewItemsVertical" + Convert.ToInt32(AppVariables.ApplicationSettings["ListViewStyle"])];
                            ListView_Items.ItemContainerStyle = (Style)Application.Current.Resources["ListViewItemStretchedVertical"];

                            await Task.Delay(100);

                            ListView_Items.ScrollIntoView(CurrentOffset);
                            System.Diagnostics.Debug.WriteLine("Changed listview to vertical style.");
                        }

                        //Adjust Status Current Item margin
                        button_StatusCurrentItem.Margin = new Thickness(6, 0, 0, 6);
                    }
                }
                else if (Direction == 1)
                {
                    Style TargetStyle = (Style)Application.Current.Resources["ListViewHorizontal"];
                    if (ListView_Items.Style != TargetStyle)
                    {
                        ScrollViewer virtualScrollViewer = AVFunctions.FindVisualChild <ScrollViewer>(ListView_Items);
                        if (virtualScrollViewer != null)
                        {
                            object CurrentOffset = EventsScrollViewer.GetCurrentOffsetItem(ListView_Items);
                            ListView_Items.Style              = TargetStyle;
                            ListView_Items.ItemTemplate       = (DataTemplate)Application.Current.Resources["ListViewItemsHorizontal" + Convert.ToInt32(AppVariables.ApplicationSettings["ListViewStyle"])];
                            ListView_Items.ItemContainerStyle = (Style)Application.Current.Resources["ListViewItemStretchedHorizontal"];

                            await Task.Delay(100);

                            ListView_Items.ScrollIntoView(CurrentOffset);
                            System.Diagnostics.Debug.WriteLine("Changed listview to horizontal style.");
                        }

                        //Adjust Status Current Item margin
                        if (AVFunctions.DevMobile())
                        {
                            button_StatusCurrentItem.Margin = new Thickness(6, 0, 0, 6);
                        }
                        else
                        {
                            button_StatusCurrentItem.Margin = new Thickness(16, 0, 0, 16);
                        }
                    }
                }
                else if (Direction == 2)
                {
                    Rect ScreenSize = AVFunctions.AppWindowResolution();
                    if (ScreenSize.Width > ScreenSize.Height)
                    {
                        await AdjustItemsScrollingDirection(1);
                    }
                    else
                    {
                        await AdjustItemsScrollingDirection(0);
                    }
                }
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine("Failed to adjust item scrolling direction.");
            }
        }
Ejemplo n.º 16
0
        private async Task HideShowHeader(bool ForceClose)
        {
            try
            {
                Int32 HeaderTargetSize  = Convert.ToInt32(stackpanel_Header.Tag);
                Int32 HeaderCurrentSize = Convert.ToInt32(stackpanel_Header.Height);
                if (ForceClose || HeaderCurrentSize == HeaderTargetSize)
                {
                    //Check if there are any search results
                    if (!List_SearchItems.Any())
                    {
                        Debug.WriteLine("There are no search results, not closing the header...");
                        return;
                    }

                    AVAnimations.Ani_Height(stackpanel_Header, 0, false, 0.075);
                    await HideShowMenu(true);

                    if (!AVFunctions.DevMobile())
                    {
                        iconMenu.Margin = new Thickness(0, 0, 16, 0);
                    }

                    image_iconMenu.Source = await AVImage.LoadBitmapImage("ms-appx:///Assets/iconMenu-Dark.png", false);

                    image_iconMenu.Opacity = 0.60;

                    grid_StatusApplication.Margin     = new Thickness(0, 0, 0, 0);
                    grid_StatusApplication.Background = new SolidColorBrush(Color.FromArgb(255, 88, 88, 88))
                    {
                        Opacity = 0.60
                    };
                    border_StatusCurrentItem.Background = new SolidColorBrush(Color.FromArgb(255, 88, 88, 88))
                    {
                        Opacity = 0.50
                    };

                    //Update the current item status text
                    if (AppVariables.CurrentTotalItemsCount == 0)
                    {
                        textblock_StatusCurrentItem.Text = textblock_StatusCurrentItem.Tag.ToString();
                    }
                    else
                    {
                        textblock_StatusCurrentItem.Text = textblock_StatusCurrentItem.Tag.ToString() + "/" + AppVariables.CurrentTotalItemsCount;
                    }

                    //Adjust the title bar color
                    await AppAdjust.AdjustTitleBarColor(this.RequestedTheme, false, false);

                    AppVariables.HeaderHidden = true;
                }
                else
                {
                    AVAnimations.Ani_Height(stackpanel_Header, HeaderTargetSize, true, 0.075);

                    iconMenu.Margin = new Thickness(0, 0, 0, 0);

                    image_iconMenu.Source = await AVImage.LoadBitmapImage("ms-appx:///Assets/iconMenu.png", false);

                    image_iconMenu.Opacity = 1;

                    grid_StatusApplication.Margin     = new Thickness(0, 65, 0, 0);
                    grid_StatusApplication.Background = new SolidColorBrush((Color)Resources["SystemAccentColor"])
                    {
                        Opacity = 0.60
                    };
                    border_StatusCurrentItem.Background = new SolidColorBrush((Color)Resources["SystemAccentColor"])
                    {
                        Opacity = 0.50
                    };

                    //Update the current item status text
                    textblock_StatusCurrentItem.Text = textblock_StatusCurrentItem.Tag.ToString();

                    //Adjust the title bar color
                    await AppAdjust.AdjustTitleBarColor(this.RequestedTheme, true, false);

                    AppVariables.HeaderHidden = false;
                }
            }
            catch { }
        }
Ejemplo n.º 17
0
        private async Task HideShowHeader(bool ForceClose)
        {
            try
            {
                Int32 HeaderTargetSize  = Convert.ToInt32(stackpanel_Header.Tag);
                Int32 HeaderCurrentSize = Convert.ToInt32(stackpanel_Header.Height);
                if (ForceClose || HeaderCurrentSize == HeaderTargetSize)
                {
                    AVAnimations.Ani_Height(stackpanel_Header, 0, false, 0.075);
                    await HideShowMenu(true);

                    if (!AVFunctions.DevMobile())
                    {
                        iconMenu.Margin = new Thickness(0, 0, 16, 0);
                    }

                    image_iconMenu.Source = await AVImage.LoadBitmapImage("ms-appx:///Assets/iconMenu-Dark.png", false);

                    image_iconMenu.Opacity = 0.60;

                    image_iconBack.Source = await AVImage.LoadBitmapImage("ms-appx:///Assets/iconBack-Dark.png", false);

                    image_iconBack.Opacity = 0.60;

                    grid_StatusApplication.Margin     = new Thickness(0, 0, 0, 0);
                    grid_StatusApplication.Background = new SolidColorBrush(Color.FromArgb(255, 88, 88, 88))
                    {
                        Opacity = 0.60
                    };
                    border_StatusCurrentItem.Background = new SolidColorBrush(Color.FromArgb(255, 88, 88, 88))
                    {
                        Opacity = 0.50
                    };

                    //Adjust the title bar color
                    await AppAdjust.AdjustTitleBarColor(this.RequestedTheme, false, false);

                    AppVariables.HeaderHidden = true;
                }
                else
                {
                    AVAnimations.Ani_Height(stackpanel_Header, HeaderTargetSize, true, 0.075);

                    iconMenu.Margin = new Thickness(0, 0, 0, 0);

                    image_iconMenu.Source = await AVImage.LoadBitmapImage("ms-appx:///Assets/iconMenu.png", false);

                    image_iconMenu.Opacity = 1;

                    image_iconBack.Source = await AVImage.LoadBitmapImage("ms-appx:///Assets/iconBack.png", false);

                    image_iconBack.Opacity = 1;

                    grid_StatusApplication.Margin     = new Thickness(0, 65, 0, 0);
                    grid_StatusApplication.Background = new SolidColorBrush((Color)Resources["SystemAccentColor"])
                    {
                        Opacity = 0.60
                    };
                    border_StatusCurrentItem.Background = new SolidColorBrush((Color)Resources["SystemAccentColor"])
                    {
                        Opacity = 0.50
                    };

                    //Adjust the title bar color
                    await AppAdjust.AdjustTitleBarColor(this.RequestedTheme, true, false);

                    AppVariables.HeaderHidden = false;
                }
            }
            catch { }
        }
Ejemplo n.º 18
0
        private async Task HideShowHeader(bool ForceClose)
        {
            try
            {
                if (ForceClose || stackpanel_Header.Visibility == Visibility.Visible)
                {
                    //Check if there are any search results
                    if (!List_SearchItems.Any())
                    {
                        System.Diagnostics.Debug.WriteLine("There are no search results, not closing the header...");
                        return;
                    }

                    stackpanel_Header.Visibility = Visibility.Collapsed;
                    await HideShowMenu(true);

                    if (!AVFunctions.DevMobile())
                    {
                        iconMenu.Margin = new Thickness(0, 0, 16, 0);
                    }

                    image_iconMenu.Source = await AVImage.LoadBitmapImage("ms-appx:///Assets/iconMenu-Dark.png", false);

                    image_iconMenu.Opacity = 0.60;

                    grid_StatusApplication.Margin     = new Thickness(0, 0, 0, 0);
                    grid_StatusApplication.Background = new SolidColorBrush(Color.FromArgb(255, 88, 88, 88))
                    {
                        Opacity = 0.60
                    };
                    border_StatusCurrentItem.Background = new SolidColorBrush(Color.FromArgb(255, 88, 88, 88))
                    {
                        Opacity = 0.50
                    };

                    //Update the current item status text
                    if (AppVariables.CurrentTotalItemsCount == 0)
                    {
                        textblock_StatusCurrentItem.Text = AppVariables.CurrentShownItemCount.ToString();
                    }
                    else
                    {
                        textblock_StatusCurrentItem.Text = AppVariables.CurrentShownItemCount + "/" + AppVariables.CurrentTotalItemsCount;
                    }

                    AppVariables.HeaderHidden = true;
                }
                else
                {
                    stackpanel_Header.Visibility = Visibility.Visible;

                    iconMenu.Margin = new Thickness(0, 0, 0, 0);

                    image_iconMenu.Source = await AVImage.LoadBitmapImage("ms-appx:///Assets/iconMenu.png", false);

                    image_iconMenu.Opacity = 1;

                    grid_StatusApplication.Margin     = new Thickness(0, 65, 0, 0);
                    grid_StatusApplication.Background = new SolidColorBrush((Color)Application.Current.Resources["ApplicationAccentLightColor"])
                    {
                        Opacity = 0.60
                    };
                    border_StatusCurrentItem.Background = new SolidColorBrush((Color)Application.Current.Resources["ApplicationAccentLightColor"])
                    {
                        Opacity = 0.50
                    };

                    //Update the current item status text
                    textblock_StatusCurrentItem.Text = AppVariables.CurrentShownItemCount.ToString();

                    AppVariables.HeaderHidden = false;
                }
            }
            catch { }
        }
Ejemplo n.º 19
0
        private void GenerateVideo(Span addSpan, HtmlNode htmlNode)
        {
            try
            {
                //Check if media loading is allowed
                if (!AppVariables.LoadMedia)
                {
                    grid_item_video video = new grid_item_video();
                    video.item_status.Text = "Video not loaded,\nnetwork is not available.";

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = video;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Check if device is low on memory
                if (AVFunctions.DevMemoryAvailableMB() < 200)
                {
                    grid_item_video video = new grid_item_video();
                    video.item_status.Text = "Video not loaded,\ndevice is low on memory.";

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = video;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Check if low bandwidth mode is enabled
                if ((bool)AppVariables.ApplicationSettings["LowBandwidthMode"])
                {
                    grid_item_image img = new grid_item_image();
                    img.item_status.Text = "Video not loaded,\nlow bandwidth mode.";
                    img.IsHitTestVisible = false;

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = img;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Create item video
                string VideoString = htmlNode.Attributes["src"].Value;
                if (!string.IsNullOrWhiteSpace(VideoString))
                {
                    Debug.WriteLine("Opening video: " + VideoString);

                    grid_item_video video = new grid_item_video();
                    video.item_source.Source = new Uri(VideoString);

                    //Check if media is a gif(v) file
                    if (VideoString.ToLower().Contains(".gif"))
                    {
                        video.item_source.AutoPlay    = true;
                        video.item_source.MediaEnded += delegate
                        {
                            video.item_source.Position = new TimeSpan();
                            video.item_source.Play();
                        };
                    }
                    else
                    {
                        video.item_source.AutoPlay = false;
                    }

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = video;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                }
            }
            catch { }
        }
Ejemplo n.º 20
0
        public static void SettingsCheck()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("Checking application settings...");

                //Check allowed memory usage
                uint AllowedMemory = 999999999; //Fix(MemoryManager.AppMemoryUsageLimit / 1024 / 1024);
                System.Diagnostics.Debug.WriteLine("Current memory limit: " + AllowedMemory);

                //Account
                if (!AppVariables.ApplicationSettings.ContainsKey("ApiAccount"))
                {
                    AppVariables.ApplicationSettings["ApiAccount"] = string.Empty;
                }

                //Password
                if (!AppVariables.ApplicationSettings.ContainsKey("ApiPassword"))
                {
                    AppVariables.ApplicationSettings["ApiPassword"] = string.Empty;
                }

                //Update Items on Startup
                if (!AppVariables.ApplicationSettings.ContainsKey("UpdateItemsStartup"))
                {
                    AppVariables.ApplicationSettings["UpdateItemsStartup"] = true;
                }

                //Display items author
                if (!AppVariables.ApplicationSettings.ContainsKey("DisplayItemsAuthor"))
                {
                    AppVariables.ApplicationSettings["DisplayItemsAuthor"] = true;
                }

                //Display images offline
                if (!AppVariables.ApplicationSettings.ContainsKey("DisplayImagesOffline"))
                {
                    AppVariables.ApplicationSettings["DisplayImagesOffline"] = false;
                }

                //Display Read Marked items
                if (!AppVariables.ApplicationSettings.ContainsKey("DisplayReadMarkedItems"))
                {
                    AppVariables.ApplicationSettings["DisplayReadMarkedItems"] = false;
                }

                //Hide Read Marked item
                if (!AppVariables.ApplicationSettings.ContainsKey("HideReadMarkedItem"))
                {
                    AppVariables.ApplicationSettings["HideReadMarkedItem"] = false;
                }

                //News item content cutting
                if (!AppVariables.ApplicationSettings.ContainsKey("ContentCutting"))
                {
                    AppVariables.ApplicationSettings["ContentCutting"] = true;
                }

                //News item content cutting length
                if (!AppVariables.ApplicationSettings.ContainsKey("ContentCuttingLength"))
                {
                    AppVariables.ApplicationSettings["ContentCuttingLength"] = 200;
                }

                //Disable Landscape Display
                if (!AppVariables.ApplicationSettings.ContainsKey("DisableLandscapeDisplay"))
                {
                    AppVariables.ApplicationSettings["DisableLandscapeDisplay"] = false;
                }

                //Low bandwidth mode
                if (!AppVariables.ApplicationSettings.ContainsKey("LowBandwidthMode"))
                {
                    AppVariables.ApplicationSettings["LowBandwidthMode"] = false;
                }

                //Disable Swipe Action
                if (!AppVariables.ApplicationSettings.ContainsKey("DisableSwipeActions"))
                {
                    AppVariables.ApplicationSettings["DisableSwipeActions"] = false;
                }

                //Swipe direction
                if (!AppVariables.ApplicationSettings.ContainsKey("SwipeDirection"))
                {
                    AppVariables.ApplicationSettings["SwipeDirection"] = "0";
                }

                //Default item open method
                if (!AppVariables.ApplicationSettings.ContainsKey("ItemOpenMethod"))
                {
                    AppVariables.ApplicationSettings["ItemOpenMethod"] = "0";
                    //if (AllowedMemory <= 420) { AppVariables.ApplicationSettings["ItemOpenMethod"] = "0"; }
                    //else { AppVariables.ApplicationSettings["ItemOpenMethod"] = "1"; }
                }

                //Item list view style
                if (!AppVariables.ApplicationSettings.ContainsKey("ListViewStyle"))
                {
                    AppVariables.ApplicationSettings["ListViewStyle"] = "0";
                }

                //Remove Items Range
                if (!AppVariables.ApplicationSettings.ContainsKey("RemoveItemsRange"))
                {
                    AppVariables.ApplicationSettings["RemoveItemsRange"] = "4";
                }

                //Color Theme
                if (!AppVariables.ApplicationSettings.ContainsKey("ColorTheme"))
                {
                    AppVariables.ApplicationSettings["ColorTheme"] = "2";
                }

                //Item Scroll Direction
                if (!AppVariables.ApplicationSettings.ContainsKey("ItemScrollDirection"))
                {
                    if (AVFunctions.DevMobile())
                    {
                        AppVariables.ApplicationSettings["ItemScrollDirection"] = "0";
                    }
                    else
                    {
                        AppVariables.ApplicationSettings["ItemScrollDirection"] = "2";
                    }
                }

                ////Maximum Update Items
                //if (!AppVariables.ApplicationSettings.ContainsKey("MaxUpdateItems"))
                //{
                //    AppVariables.ApplicationSettings["MaxUpdateItems"] = "1000";
                //}

                //Adjust font size
                if (!AppVariables.ApplicationSettings.ContainsKey("AdjustFontSize"))
                {
                    AppVariables.ApplicationSettings["AdjustFontSize"] = 0;
                }

                //Last Api Login Auth
                if (!AppVariables.ApplicationSettings.ContainsKey("ConnectApiAuth"))
                {
                    AppVariables.ApplicationSettings["ConnectApiAuth"] = string.Empty;
                }

                //Last items update time
                if (!AppVariables.ApplicationSettings.ContainsKey("LastItemsUpdate"))
                {
                    AppVariables.ApplicationSettings["LastItemsUpdate"] = "Never";
                }
            }
            catch { }
        }
Ejemplo n.º 21
0
        private void GenerateWebview(Span addSpan, HtmlNode htmlNode)
        {
            try
            {
                //Check if webview limit reached
                if (vWebViewAdded == vWebViewLimit)
                {
                    grid_item_webview webView = new grid_item_webview();
                    webView.item_status.Text = "Webview not loaded,\nlimit has been reached.";

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = webView;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Check if media loading is allowed
                if (!AppVariables.LoadMedia)
                {
                    grid_item_webview webView = new grid_item_webview();
                    webView.item_status.Text = "Webview not loaded,\nnetwork is not available.";

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = webView;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Check if device is low on memory
                if (AVFunctions.DevMemoryAvailableMB() < 200)
                {
                    grid_item_webview webView = new grid_item_webview();
                    webView.item_status.Text = "Webview not loaded,\ndevice is low on memory.";

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = webView;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Check if low bandwidth mode is enabled
                if ((bool)AppVariables.ApplicationSettings["LowBandwidthMode"])
                {
                    grid_item_image img = new grid_item_image();
                    img.item_status.Text = "Webview not loaded,\nlow bandwidth mode.";
                    img.IsHitTestVisible = false;

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = img;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());
                    return;
                }

                //Create item webview
                string WebLink = htmlNode.Attributes["src"].Value;
                if (!string.IsNullOrWhiteSpace(WebLink))
                {
                    Debug.WriteLine("Opening webview: " + WebLink);

                    grid_item_webview webView = new grid_item_webview();
                    webView.item_source.Source = new Uri(WebLink);
                    webView.item_source.ContainsFullScreenElementChanged += webview_Full_ContainsFullScreenElementChanged;
                    webView.item_source.NewWindowRequested += webview_Full_NewWindowRequested;

                    InlineUIContainer iui = new InlineUIContainer();
                    iui.Child = webView;

                    addSpan.Inlines.Add(iui);
                    //addSpan.Inlines.Add(new LineBreak());

                    //Update the webview count
                    vWebViewAdded++;
                }
            }
            catch { }
        }
Ejemplo n.º 22
0
        //Update the network information
        void UpdateNetworkInformation(IHardware hardwareItem, ref float networkUpFloat, ref float networkDownFloat)
        {
            try
            {
                //Check if the information is visible
                bool showCurrentUsage = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "NetShowCurrentUsage"));
                if (!showCurrentUsage)
                {
                    AVActions.ActionDispatcherInvoke(delegate
                    {
                        stackpanel_CurrentNet.Visibility = Visibility.Collapsed;
                    });
                    return;
                }

                if (hardwareItem.HardwareType == HardwareType.Network)
                {
                    hardwareItem.Update();
                    string networkUsage = string.Empty;

                    foreach (ISensor sensor in hardwareItem.Sensors)
                    {
                        try
                        {
                            if (sensor.SensorType == SensorType.Throughput)
                            {
                                //Debug.WriteLine("Network Data: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Identifier.ToString().EndsWith("throughput/7"))
                                {
                                    networkUpFloat += (float)sensor.Value;
                                }
                                else if (sensor.Identifier.ToString().EndsWith("throughput/8"))
                                {
                                    networkDownFloat += (float)sensor.Value;
                                }
                            }
                        }
                        catch { }
                    }

                    string networkDownString = AVFunctions.ConvertBytesSizeToString(networkDownFloat) + " DL ";
                    string networkUpString   = AVFunctions.ConvertBytesSizeToString(networkUpFloat) + " UP";
                    networkUsage += " " + networkDownString + networkUpString;

                    if (!string.IsNullOrWhiteSpace(networkUsage))
                    {
                        string stringDisplay = AVFunctions.StringRemoveStart(vTitleNET + networkUsage, " ");
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            textblock_CurrentNet.Text        = stringDisplay;
                            stackpanel_CurrentNet.Visibility = Visibility.Visible;
                        });
                    }
                    else
                    {
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            stackpanel_CurrentNet.Visibility = Visibility.Collapsed;
                        });
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 23
0
        //Open item in browser
        private async Task OpenBrowser(Uri TargetUri, bool closePopup)
        {
            try
            {
                int MsgBoxResult = 0;

                //Check internet connection
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    await new MessagePopup().Popup("No internet connection", "You currently don't have an internet connection available to open this item or link in the webviewer or your webbrowser.", "Ok", "", "", "", "", false);
                    return;
                }

                //Check webbrowser only links
                if (TargetUri != null)
                {
                    string TargetString = TargetUri.ToString();
                    if (!TargetString.StartsWith("http"))
                    {
                        MsgBoxResult = 2;
                    }
                }

                if (MsgBoxResult != 2)
                {
                    string LowMemoryWarning = string.Empty;
                    if (AVFunctions.DevMemoryAvailableMB() < 200)
                    {
                        LowMemoryWarning = "\n\n* Your device is currently low on available memory and may cause issues when you open this link or item in the webviewer.";
                    }
                    MsgBoxResult = await new MessagePopup().Popup("Open this item or link", "Do you want to open this item or link in the webviewer or your webbrowser?" + LowMemoryWarning, "Webviewer (In-app)", "Webbrowser (Device)", "", "", "", true);
                }

                if (MsgBoxResult == 1)
                {
                    if (closePopup)
                    {
                        ClosePopup();
                    }
                    //Open item in webviewer
                    WebViewer webViewer = new WebViewer();
                    await webViewer.OpenPopup(TargetUri, vCurrentWebSource);
                }
                else if (MsgBoxResult == 2)
                {
                    if (closePopup)
                    {
                        ClosePopup();
                    }
                    //Open item in webbrowser
                    if (TargetUri != null)
                    {
                        await Launcher.LaunchUriAsync(TargetUri);
                    }
                    else
                    {
                        await Launcher.LaunchUriAsync(new Uri(vCurrentWebSource.item_link, UriKind.RelativeOrAbsolute));
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 24
0
        public static async Task <bool> ProcessTableItemsToList(ObservableCollection <Items> AddList, List <TableItems> LoadTableItems, bool AddFromTop, bool HideReadStatus, bool HideStarStatus)
        {
            try
            {
                List <TableFeeds> FeedList = await SQLConnection.Table <TableFeeds>().ToListAsync();

                foreach (TableItems LoadTable in LoadTableItems)
                {
                    //Load and check item id
                    string ItemId = LoadTable.item_id;
                    if (AddList.Any(x => x.item_id == ItemId))
                    {
                        continue;
                    }

                    //Load feed id and title
                    string FeedId    = LoadTable.item_feed_id;
                    string FeedTitle = "Unknown feed";

                    TableFeeds TableResult = FeedList.Where(x => x.feed_id == FeedId).FirstOrDefault();
                    if (TableResult == null)
                    {
                        //System.Diagnostics.Debug.WriteLine("Feed not found: " + FeedId);
                        if (LoadTable.item_feed_title != null && !string.IsNullOrWhiteSpace(LoadTable.item_feed_title))
                        {
                            System.Diagnostics.Debug.WriteLine("Backup feed title: " + LoadTable.item_feed_title);
                            FeedTitle = LoadTable.item_feed_title;
                        }
                        else if (FeedId.StartsWith("user/"))
                        {
                            System.Diagnostics.Debug.WriteLine("Detected an user feed.");
                            FeedTitle = "User feed";
                        }
                    }
                    else
                    {
                        //Set the feed item title
                        FeedTitle = TableResult.feed_title;
                    }

                    //Load item image
                    Visibility ItemImageVisibility = Visibility.Collapsed;
                    string     ItemImageLink       = LoadTable.item_image;
                    if (!string.IsNullOrWhiteSpace(ItemImageLink))
                    {
                        ItemImageVisibility = Visibility.Visible;
                    }

                    //Set the date time string
                    DateTime convertedDate    = DateTime.SpecifyKind(LoadTable.item_datetime, DateTimeKind.Utc).ToLocalTime();
                    string   DateAuthorString = convertedDate.ToString(AppVariables.CultureInfoFormat.LongDatePattern, AppVariables.CultureInfoFormat) + ", " + convertedDate.ToString(AppVariables.CultureInfoFormat.ShortTimePattern, AppVariables.CultureInfoFormat);

                    //Add the author to date time
                    if ((bool)AppVariables.ApplicationSettings["DisplayItemsAuthor"] && !string.IsNullOrWhiteSpace(LoadTable.item_author))
                    {
                        DateAuthorString += " by " + LoadTable.item_author;
                    }

                    //Check item read or star status
                    Visibility ReadVisibility = Visibility.Collapsed;
                    if (!HideReadStatus)
                    {
                        ReadVisibility = LoadTable.item_read_status ? Visibility.Visible : Visibility.Collapsed;
                    }
                    Visibility StarredVisibility = Visibility.Collapsed;
                    if (!HideStarStatus)
                    {
                        StarredVisibility = LoadTable.item_star_status ? Visibility.Visible : Visibility.Collapsed;
                    }

                    //Load item content
                    string item_content = string.Empty;
                    if ((bool)AppVariables.ApplicationSettings["ContentCutting"])
                    {
                        item_content = AVFunctions.StringCut(LoadTable.item_content, Convert.ToInt32(AppVariables.ApplicationSettings["ContentCuttingLength"]), "...");
                    }
                    else
                    {
                        item_content = AVFunctions.StringCut(LoadTable.item_content, AppVariables.MaximumItemTextLength, "...");
                    }

                    //Add item to list
                    Items NewItem = new Items()
                    {
                        feed_id = FeedId, feed_title = FeedTitle, item_id = ItemId, item_read_status = ReadVisibility, item_star_status = StarredVisibility, item_title = LoadTable.item_title, item_image_visibility = ItemImageVisibility, item_image_link = ItemImageLink, item_content = item_content, item_link = LoadTable.item_link, item_datestring = DateAuthorString, item_datetime = LoadTable.item_datetime
                    };
                    if (AddFromTop)
                    {
                        AddList.Insert(0, NewItem);
                    }
                    else
                    {
                        AddList.Add(NewItem);
                    }

                    //Update the added item count
                    AppVariables.CurrentItemsLoaded++;

                    //Request information update
                    if (AppVariables.CurrentItemsLoaded == 1)
                    {
                        await EventHideProgressionStatus();
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Failed processing multiple items from database: " + ex.Message);
                return(false);
            }
        }
Ejemplo n.º 25
0
        //Update the battery information
        void UpdateBatteryInformation(IHardware hardwareItem)
        {
            try
            {
                //Check if the information is visible
                bool showPercentage = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "BatShowPercentage"));
                if (!showPercentage)
                {
                    AVActions.ActionDispatcherInvoke(delegate
                    {
                        stackpanel_CurrentBat.Visibility = Visibility.Collapsed;
                    });
                    return;
                }

                if (hardwareItem.HardwareType == HardwareType.Battery)
                {
                    hardwareItem.Update();
                    string BatteryPercentage = string.Empty;
                    string BatteryStatus     = string.Empty;

                    foreach (ISensor sensor in hardwareItem.Sensors)
                    {
                        try
                        {
                            if (sensor.SensorType == SensorType.Level)
                            {
                                if (sensor.Name == "Charge Level")
                                {
                                    //Debug.WriteLine("Bat Level: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                    BatteryPercentage = " " + Convert.ToInt32(sensor.Value) + "%";
                                }
                            }
                            else if (sensor.SensorType == SensorType.Power)
                            {
                                if (sensor.Name == "Charge Rate")
                                {
                                    //Debug.WriteLine("Bat Charge Rate: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                    BatteryStatus = " (Charging)";
                                }
                            }
                            else if (sensor.SensorType == SensorType.TimeSpan)
                            {
                                //Debug.WriteLine("Bat Estimated Time: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                BatteryStatus = " (" + AVFunctions.SecondsToHms(Convert.ToInt32(sensor.Value), true) + ")";
                            }
                        }
                        catch { }
                    }

                    if (!string.IsNullOrWhiteSpace(BatteryPercentage) || !string.IsNullOrWhiteSpace(BatteryStatus))
                    {
                        string stringDisplay = AVFunctions.StringRemoveStart(vTitleBAT + BatteryPercentage + BatteryStatus, " ");
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            textblock_CurrentBat.Text        = stringDisplay;
                            stackpanel_CurrentBat.Visibility = Visibility.Visible;
                        });
                    }
                    else
                    {
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            stackpanel_CurrentBat.Visibility = Visibility.Collapsed;
                        });
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 26
0
        //Update current weather tile data
        async Task <bool> LoadTileDataWeather()
        {
            try
            {
                Debug.WriteLine("Loading the weather tile data.");

                //Check if weather background updates are enabled
                if (!setBackgroundDownload || !setDownloadWeather || !await AVFunctions.LocalFileExists("TimeMeWeatherSummary.js") || !await AVFunctions.LocalFileExists("TimeMeWeatherForecast.js"))
                {
                    return(false);
                }

                //Load last weather update time
                if (setDisplayWeatherTileUpdateTime)
                {
                    //Set the weather update time text
                    if (BgStatusDownloadWeatherTime != "Never")
                    {
                        DateTime WeatherTime = DateTime.Parse(BgStatusDownloadWeatherTime, vCultureInfoEng);
                        if (setDisplay24hClock)
                        {
                            if (!String.IsNullOrEmpty(TextTimeSplit))
                            {
                                WeatherLastUpdate = WeatherTime.ToString("HH" + TextTimeSplit + "mm");
                            }
                            else
                            {
                                WeatherLastUpdate = WeatherTime.ToString("HH:mm");
                            }
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(TextTimeSplit))
                            {
                                WeatherLastUpdate = WeatherTime.ToString("h" + TextTimeSplit + "mm tt", vCultureInfoEng);
                            }
                            else
                            {
                                WeatherLastUpdate = WeatherTime.ToString("h:mm tt", vCultureInfoEng);
                            }
                        }
                    }
                    else
                    {
                        WeatherLastUpdate = "Unknown";
                    }
                }
                else
                {
                    WeatherLastUpdate = "";
                }

                //Load weather detailed information
                if (setDisplayWeatherTileLocation)
                {
                    WeatherDetailed = BgStatusWeatherCurrentLocation;
                }
                else if (setDisplayWeatherTileProvider)
                {
                    WeatherDetailed = BgStatusWeatherProvider;
                }
                else
                {
                    WeatherDetailed = "";
                }

                //Load weather tile background photo or color
                if (setDisplayBackgroundPhotoWeather)
                {
                    if (await AVFunctions.LocalFileExists("TimeMeTilePhoto.png"))
                    {
                        TileContentId = WebUtility.HtmlEncode(BgStatusPhotoName);
                        TileWeather_BackgroundPhotoXml = "<image src=\"ms-appdata:///local/TimeMeTilePhoto.png\" placement=\"background\" hint-overlay=\"" + setDisplayBackgroundBrightnessInt + "\"/>";
                    }
                    else
                    {
                        TileWeather_BackgroundPhotoXml = "<image src=\"ms-appx:///Assets/Tiles/TimeMeTilePhoto.png\" placement=\"background\" hint-overlay=\"" + setDisplayBackgroundBrightnessInt + "\"/>";
                    }
                }
                else if (setDisplayBackgroundColorWeather)
                {
                    if (await AVFunctions.LocalFileExists("TimeMeTileColor.png"))
                    {
                        TileContentId = WebUtility.HtmlEncode(setLiveTileColorBackground);
                        TileWeather_BackgroundPhotoXml = "<image src=\"ms-appdata:///local/TimeMeTileColor.png\" placement=\"background\" hint-overlay=\"0\"/>";
                    }
                    else
                    {
                        TileWeather_BackgroundPhotoXml = "<image src=\"ms-appx:///Assets/Tiles/TimeMeTileColor.png\" placement=\"background\" hint-overlay=\"0\"/>";
                    }
                }

                //Load weather forecast tile data
                if (setWeatherTileSizeName == "WeatherForecast" || setWeatherTileSizeName == "WeatherCombo")
                {
                    //Set not available Weather Forecast styles
                    if (setWeatherTileSizeName == "WeatherForecast")
                    {
                        WeatherTile1 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">N/A</text><image src=\"ms-appx:///Assets/WeatherSquare" + WeatherIconStyle + "/0.png\" hint-removeMargin=\"true\"/><text hint-align=\"center\">N/A</text></subgroup>";
                        WeatherTile2 = WeatherTile1; WeatherTile3 = WeatherTile1; WeatherTile4 = WeatherTile1; WeatherTile5 = WeatherTile1;
                    }
                    else
                    {
                        WeatherTile1 = "<subgroup hint-textStacking=\"center\" hint-weight=\"45\"><image src=\"ms-appx:///Assets/Weather" + WeatherIconStyle + "/0.png\" hint-removeMargin=\"true\"/></subgroup><subgroup hint-textStacking=\"center\" hint-weight=\"50\"><text hint-align=\"left\">N/A</text><text hint-align=\"left\" hint-style=\"captionSubtle\">N/A</text></subgroup>";
                        WeatherTile2 = WeatherTile1; WeatherTile3 = WeatherTile1; WeatherTile4 = WeatherTile1; WeatherTile5 = WeatherTile1;
                    }

                    //Load weather forecast for tile
                    JObject ForecastJObject;
                    using (Stream OpenStreamForReadAsync = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("TimeMeWeatherForecast.js"))
                    {
                        using (StreamReader StreamReader = new StreamReader(OpenStreamForReadAsync))
                        {
                            ForecastJObject = JObject.Parse(await StreamReader.ReadToEndAsync());
                            OpenStreamForReadAsync.Dispose();
                        }
                    }
                    //Check if there is weather forecast available
                    if (ForecastJObject["responses"][0]["weather"] == null || ForecastJObject["responses"][0]["weather"][0]["days"].Count() <= 1)
                    {
                        return(false);
                    }
                    else
                    {
                        int    ForecastCount  = 1;
                        JToken ForecastJToken = ForecastJObject["responses"][0]["weather"][0]["days"];
                        foreach (JToken DayJToken in ForecastJToken)
                        {
                            //Set Weather Date
                            string WeatherDate = "";
                            if (DayJToken["daily"]["valid"] != null)
                            {
                                WeatherDate = DayJToken["daily"]["valid"].ToString();
                                if (!String.IsNullOrEmpty(WeatherDate))
                                {
                                    DateTime WeatherDateTime = DateTime.Parse(WeatherDate);

                                    //Check if the day has already passed
                                    if (WeatherDateTime.AddDays(1) < DateTimeNow)
                                    {
                                        continue;
                                    }
                                    //if (WeatherDateTime.Day == Tile_DateTimeMin.Day) { WeatherDate = "Tod"; }
                                    //else
                                    //{
                                    if (setDisplayRegionLanguage)
                                    {
                                        WeatherDate = AVFunctions.ToTitleCase(WeatherDateTime.ToString("ddd", vCultureInfoReg));
                                    }
                                    else
                                    {
                                        WeatherDate = WeatherDateTime.ToString("ddd", vCultureInfoEng);
                                    }
                                    //}
                                }
                                else
                                {
                                    WeatherDate = "N/A";
                                }
                            }
                            else
                            {
                                WeatherDate = "N/A";
                            }

                            //Set Weather Icon
                            string WeatherIcon       = "";
                            string WeatherIconFormat = "WeatherSquare" + WeatherIconStyle;
                            if (setWeatherTileSizeName == "WeatherCombo")
                            {
                                WeatherIconFormat = "Weather" + WeatherIconStyle;
                            }
                            if (DayJToken["daily"]["icon"] != null)
                            {
                                WeatherIcon = DayJToken["daily"]["icon"].ToString();
                                if (!String.IsNullOrEmpty(WeatherIcon))
                                {
                                    if (await AVFunctions.AppFileExists("Assets/" + WeatherIconFormat + "/" + WeatherIcon + ".png"))
                                    {
                                        WeatherIcon = "/Assets/" + WeatherIconFormat + "/" + WeatherIcon + ".png";
                                    }
                                    else
                                    {
                                        WeatherIcon = "/Assets/" + WeatherIconFormat + "/0.png";
                                    }
                                }
                                else
                                {
                                    WeatherIcon = "/Assets/" + WeatherIconFormat + "/0.png";
                                }
                            }
                            else
                            {
                                WeatherIcon = "/Assets/" + WeatherIconFormat + "/0.png";
                            }

                            //Set Weather Highest Temperature
                            string WeatherTempHigh = "";
                            if (DayJToken["daily"]["tempHi"] != null)
                            {
                                WeatherTempHigh = DayJToken["daily"]["tempHi"].ToString();
                                if (!String.IsNullOrEmpty(WeatherTempHigh))
                                {
                                    WeatherTempHigh = WeatherTempHigh + "°";
                                }
                                else
                                {
                                    WeatherTempHigh = "N/A";
                                }
                            }
                            else
                            {
                                WeatherTempHigh = "N/A";
                            }

                            //Set Weather Lowest Temperature
                            string WeatherTempLow = "";
                            if (DayJToken["daily"]["tempLo"] != null)
                            {
                                WeatherTempLow = DayJToken["daily"]["tempLo"].ToString();
                                if (!String.IsNullOrEmpty(WeatherTempLow))
                                {
                                    WeatherTempLow = WeatherTempLow + "°";
                                }
                                else
                                {
                                    WeatherTempLow = "N/A";
                                }
                            }
                            else
                            {
                                WeatherTempLow = "N/A";
                            }

                            //Set Weather Forecast to XML
                            if (setWeatherTileSizeName == "WeatherForecast")
                            {
                                if (setShowMoreTiles && (setDisplayWeatherTileLocation || setDisplayWeatherTileProvider || setDisplayWeatherTileUpdateTime))
                                {
                                    switch (ForecastCount)
                                    {
                                    case 1: { WeatherTile1 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text></subgroup>"; break; }

                                    case 2: { WeatherTile2 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text></subgroup>"; break; }

                                    case 3: { WeatherTile3 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text></subgroup>"; break; }

                                    case 4: { WeatherTile4 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text></subgroup>"; break; }

                                    case 5: { WeatherTile5 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text></subgroup>"; break; }
                                    }
                                }
                                else
                                {
                                    switch (ForecastCount)
                                    {
                                    case 1: { WeatherTile1 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text><text hint-align=\"center\" hint-style=\"captionsubtle\">" + WeatherTempLow + "</text></subgroup>"; break; }

                                    case 2: { WeatherTile2 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text><text hint-align=\"center\" hint-style=\"captionsubtle\">" + WeatherTempLow + "</text></subgroup>"; break; }

                                    case 3: { WeatherTile3 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text><text hint-align=\"center\" hint-style=\"captionsubtle\">" + WeatherTempLow + "</text></subgroup>"; break; }

                                    case 4: { WeatherTile4 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text><text hint-align=\"center\" hint-style=\"captionsubtle\">" + WeatherTempLow + "</text></subgroup>"; break; }

                                    case 5: { WeatherTile5 = "<subgroup hint-weight=\"1\"><text hint-align=\"center\">" + WeatherDate + "</text><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/><text hint-align=\"center\">" + WeatherTempHigh + "</text><text hint-align=\"center\" hint-style=\"captionsubtle\">" + WeatherTempLow + "</text></subgroup>"; break; }
                                    }
                                }
                            }
                            else
                            {
                                switch (ForecastCount)
                                {
                                case 1: { WeatherTile1 = "<subgroup hint-textStacking=\"center\" hint-weight=\"45\"><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/></subgroup><subgroup hint-textStacking=\"center\" hint-weight=\"50\"><text hint-align=\"left\">" + WeatherDate + "</text><text hint-align=\"left\" hint-style=\"captionSubtle\">" + WeatherTempHigh + "</text></subgroup>"; break; }

                                case 2: { WeatherTile2 = "<subgroup hint-textStacking=\"center\" hint-weight=\"45\"><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/></subgroup><subgroup hint-textStacking=\"center\" hint-weight=\"50\"><text hint-align=\"left\">" + WeatherDate + "</text><text hint-align=\"left\" hint-style=\"captionSubtle\">" + WeatherTempHigh + "</text></subgroup>"; break; }

                                case 3: { WeatherTile3 = "<subgroup hint-textStacking=\"center\" hint-weight=\"45\"><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/></subgroup><subgroup hint-textStacking=\"center\" hint-weight=\"50\"><text hint-align=\"left\">" + WeatherDate + "</text><text hint-align=\"left\" hint-style=\"captionSubtle\">" + WeatherTempHigh + "</text></subgroup>"; break; }

                                case 4: { WeatherTile4 = "<subgroup hint-textStacking=\"center\" hint-weight=\"45\"><image src=\"ms-appx://" + WeatherIcon + "\" hint-removeMargin=\"true\"/></subgroup><subgroup hint-textStacking=\"center\" hint-weight=\"50\"><text hint-align=\"left\">" + WeatherDate + "</text><text hint-align=\"left\" hint-style=\"captionSubtle\">" + WeatherTempHigh + "</text></subgroup>"; break; }
                                }
                            }
                            ForecastCount++;
                        }
                    }
                }

                //Load weather words tile data
                else if (setWeatherTileSizeName == "WeatherWords")
                {
                    //Set Weather Condition
                    if (BgStatusWeatherCurrentText.Length >= 12)
                    {
                        WeatherTile1 = BgStatusWeatherCurrentText.Replace("!", "") + " and " + BgStatusWeatherCurrentTemp + " outside";
                    }
                    else
                    {
                        WeatherTile1 = "Now " + BgStatusWeatherCurrentText.Replace("!", "") + " and " + BgStatusWeatherCurrentTemp + " outside";
                    }

                    //Load weather summary for tile
                    JObject ForecastJObject;
                    using (Stream OpenStreamForReadAsync = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("TimeMeWeatherForecast.js"))
                    {
                        using (StreamReader StreamReader = new StreamReader(OpenStreamForReadAsync))
                        {
                            ForecastJObject = JObject.Parse(await StreamReader.ReadToEndAsync());
                            OpenStreamForReadAsync.Dispose();
                        }
                    }
                    //Check if there is weather forecast available
                    if (ForecastJObject["responses"][0]["weather"] == null || ForecastJObject["responses"][0]["weather"][0]["days"].Count() <= 1)
                    {
                        return(false);
                    }
                    else
                    {
                        JToken ForecastJToken = ForecastJObject["responses"][0]["weather"][0]["days"][0]["daily"]["day"];

                        //Set Weather Summary
                        if (ForecastJToken["summary"] != null)
                        {
                            string Summary = ForecastJToken["summary"].ToString();
                            if (!String.IsNullOrEmpty(Summary))
                            {
                                WeatherTile2 = Summary;
                            }
                            else
                            {
                                WeatherTile2 = "Weather summary is not available.";
                            }
                        }
                        else
                        {
                            WeatherTile2 = "Weather summary is not available.";
                        }
                    }
                }

                return(true);
            }
            catch { return(false); }
        }
Ejemplo n.º 27
0
        //Update the gpu information
        void UpdateGpuInformation(IHardware hardwareItem)
        {
            try
            {
                //Check if the information is visible
                bool showName          = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "GpuShowName"));
                bool showPercentage    = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "GpuShowPercentage"));
                bool showTemperature   = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "GpuShowTemperature"));
                bool showMemoryUsed    = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "GpuShowMemoryUsed"));
                bool showCoreFrequency = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "GpuShowCoreFrequency"));
                bool showFanSpeed      = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "GpuShowFanSpeed"));
                bool showPowerWatt     = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "GpuShowPowerWatt"));
                bool showPowerVolt     = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "GpuShowPowerVolt"));
                if (!showName && !showPercentage && !showTemperature && !showMemoryUsed && !showCoreFrequency && !showFanSpeed && !showPowerWatt && !showPowerVolt)
                {
                    AVActions.ActionDispatcherInvoke(delegate
                    {
                        stackpanel_CurrentGpu.Visibility = Visibility.Collapsed;
                    });
                    return;
                }

                if (hardwareItem.HardwareType == HardwareType.GpuNvidia || hardwareItem.HardwareType == HardwareType.GpuAmd)
                {
                    hardwareItem.Update();
                    string GpuName         = string.Empty;
                    string GpuPercentage   = string.Empty;
                    string GpuTemperature  = string.Empty;
                    string GpuMemory       = string.Empty;
                    string GpuFrequency    = string.Empty;
                    string GpuFanSpeed     = string.Empty;
                    string GpuPowerWattage = string.Empty;
                    string GpuPowerVoltage = string.Empty;

                    //Set the gpu name
                    if (showName)
                    {
                        GpuName = hardwareItem.Name;
                    }

                    foreach (ISensor sensor in hardwareItem.Sensors)
                    {
                        try
                        {
                            if (showPercentage && sensor.SensorType == SensorType.Load)
                            {
                                //Debug.WriteLine("GPU Load: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Identifier.ToString().EndsWith("load/0"))
                                {
                                    GpuPercentage = " " + Convert.ToInt32(sensor.Value) + "%";
                                }
                            }
                            else if (showTemperature && sensor.SensorType == SensorType.Temperature)
                            {
                                //Debug.WriteLine("GPU Temp: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Identifier.ToString().EndsWith("temperature/0"))
                                {
                                    GpuTemperature = " " + sensor.Value.ToString() + "°";
                                }
                            }
                            else if (showMemoryUsed && sensor.SensorType == SensorType.SmallData)
                            {
                                //Debug.WriteLine("GPU Mem: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Name == "GPU Memory Used")
                                {
                                    float RawMemoryUsage = (float)sensor.Value;
                                    if (RawMemoryUsage < 1024)
                                    {
                                        GpuMemory = " " + RawMemoryUsage.ToString("0") + "MB";
                                    }
                                    else
                                    {
                                        GpuMemory = " " + (RawMemoryUsage / 1024).ToString("0.0") + "GB";
                                    }
                                }
                            }
                            else if (showCoreFrequency && sensor.SensorType == SensorType.Clock)
                            {
                                //Debug.WriteLine("GPU Frequency: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (sensor.Name == "GPU Core")
                                {
                                    GpuFrequency = " " + ((float)sensor.Value).ToString("0") + "MHz";
                                }
                            }
                            else if (showFanSpeed && (sensor.SensorType == SensorType.Fan || sensor.SensorType == SensorType.Control))
                            {
                                //Debug.WriteLine("GPU Fan: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                if (string.IsNullOrWhiteSpace(GpuFanSpeed))
                                {
                                    if (sensor.Identifier.ToString().EndsWith("fan/0"))
                                    {
                                        GpuFanSpeed = " " + sensor.Value.ToString() + "RPM";
                                    }
                                    else if (sensor.Name == "GPU Fan")
                                    {
                                        GpuFanSpeed = " " + sensor.Value.ToString() + "%";
                                    }
                                }
                            }
                            else if (showPowerWatt && sensor.SensorType == SensorType.Power)
                            {
                                //Debug.WriteLine("GPU Wattage: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                GpuPowerWattage = " " + Convert.ToInt32(sensor.Value) + "W";
                            }
                            else if (showPowerVolt && sensor.SensorType == SensorType.Voltage)
                            {
                                //Debug.WriteLine("GPU Voltage: " + sensor.Name + "/" + sensor.Identifier + "/" + sensor.Value.ToString());
                                float RawPowerVoltage = (float)sensor.Value;
                                if (RawPowerVoltage <= 0)
                                {
                                    GpuPowerVoltage = " 0V";
                                }
                                else
                                {
                                    GpuPowerVoltage = " " + RawPowerVoltage.ToString("0.000") + "V";
                                }
                            }
                        }
                        catch { }
                    }

                    bool gpuNameNullOrWhiteSpace = string.IsNullOrWhiteSpace(GpuName);
                    if (!gpuNameNullOrWhiteSpace || !string.IsNullOrWhiteSpace(GpuPercentage) || !string.IsNullOrWhiteSpace(GpuTemperature) || !string.IsNullOrWhiteSpace(GpuFrequency) || !string.IsNullOrWhiteSpace(GpuMemory) || !string.IsNullOrWhiteSpace(GpuFanSpeed) || !string.IsNullOrWhiteSpace(GpuPowerWattage) || !string.IsNullOrWhiteSpace(GpuPowerVoltage))
                    {
                        string stringDisplay = string.Empty;
                        string stringStats   = AVFunctions.StringRemoveStart(vTitleGPU + GpuPercentage + GpuTemperature + GpuFrequency + GpuMemory + GpuFanSpeed + GpuPowerWattage + GpuPowerVoltage, " ");
                        if (string.IsNullOrWhiteSpace(stringStats))
                        {
                            stringDisplay = GpuName;
                        }
                        else
                        {
                            if (gpuNameNullOrWhiteSpace)
                            {
                                stringDisplay = stringStats;
                            }
                            else
                            {
                                stringDisplay = GpuName + "\n" + stringStats;
                            }
                        }

                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            textblock_CurrentGpu.Text        = stringDisplay;
                            stackpanel_CurrentGpu.Visibility = Visibility.Visible;
                        });
                    }
                    else
                    {
                        AVActions.ActionDispatcherInvoke(delegate
                        {
                            stackpanel_CurrentGpu.Visibility = Visibility.Collapsed;
                        });
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 28
0
        async Task BattleNetAddApplication(ProductInstall productInstall, string launcherExePath)
        {
            try
            {
                //Get application details
                //Improve find way to load proper uid
                string appUid     = productInstall.uid;
                string installDir = productInstall.settings.installPath;

                //Check if application id is in blacklist
                if (vBattleNetUidBlacklist.Contains(appUid))
                {
                    Debug.WriteLine("BattleNet uid is blacklisted: " + appUid);
                    return;
                }

                //Check if application is installed
                if (!Directory.Exists(installDir))
                {
                    Debug.WriteLine("BattleNet game is not installed: " + appUid);
                    return;
                }

                //Set application launch argument
                string launchArgument = "--exec=\"launch_uid " + appUid + "\"";
                vLauncherAppAvailableCheck.Add(launcherExePath);

                //Check if application is already added
                DataBindApp launcherExistCheck = List_Launchers.Where(x => !string.IsNullOrWhiteSpace(x.Argument) && x.Argument.ToLower() == launchArgument.ToLower()).FirstOrDefault();
                if (launcherExistCheck != null)
                {
                    //Debug.WriteLine("BattleNet app already in list: " + appUid);
                    return;
                }

                //Get application branch
                string appBranch = productInstall.settings.branch;
                appBranch = appBranch.Replace("_", string.Empty);
                foreach (string branchReplace in vBattleNetBranchReplace)
                {
                    appBranch = appBranch.Replace(branchReplace, string.Empty);
                }
                appBranch = AVFunctions.ToTitleCase(appBranch);

                //Get application name
                string appName = Path.GetFileName(installDir);
                if (!string.IsNullOrWhiteSpace(appBranch))
                {
                    appName += " (" + appBranch + ")";
                }

                //Check if application name is ignored
                string appNameLower = appName.ToLower();
                if (vCtrlIgnoreLauncherName.Any(x => x.String1.ToLower() == appNameLower))
                {
                    //Debug.WriteLine("Launcher is on the blacklist skipping: " + appName);
                    await ListBoxRemoveAll(lb_Launchers, List_Launchers, x => x.Name.ToLower() == appNameLower);

                    return;
                }

                //Get application image
                BitmapImage iconBitmapImage = FileToBitmapImage(new string[] { appName, "Battle.Net" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, 90, 0);

                //Add the application to the list
                DataBindApp dataBindApp = new DataBindApp()
                {
                    Category       = AppCategory.Launcher,
                    Launcher       = AppLauncher.BattleNet,
                    Name           = appName,
                    ImageBitmap    = iconBitmapImage,
                    PathExe        = launcherExePath,
                    Argument       = launchArgument,
                    StatusLauncher = vImagePreloadBattleNet,
                    LaunchKeyboard = true
                };

                await ListBoxAddItem(lb_Launchers, List_Launchers, dataBindApp, false, false);

                //Debug.WriteLine("Added BattleNet app: " + appName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed adding BattleNet app: " + ex.Message);
            }
        }
Ejemplo n.º 29
0
        //Update the monitor information
        void UpdateMonitorInformation()
        {
            try
            {
                //Check if the information is visible
                bool showResolution    = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "MonShowResolution"));
                bool showDpiResolution = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "MonShowDpiResolution"));
                bool showColorBitDepth = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "MonShowColorBitDepth"));
                bool showRefreshRate   = Convert.ToBoolean(Setting_Load(vConfigurationFpsOverlayer, "MonShowRefreshRate"));
                if (!showResolution && !showColorBitDepth && !showRefreshRate)
                {
                    AVActions.ActionDispatcherInvoke(delegate
                    {
                        stackpanel_CurrentMon.Visibility = Visibility.Collapsed;
                    });
                    return;
                }

                //Get the current active screen
                int monitorNumber = Convert.ToInt32(Setting_Load(vConfigurationCtrlUI, "DisplayMonitor"));

                //Get the screen resolution
                DisplayMonitor displayMonitorSettings = GetSingleMonitorEnumDisplay(monitorNumber);
                string         screenResolutionString = string.Empty;
                if (showResolution)
                {
                    if (showDpiResolution)
                    {
                        screenResolutionString = " " + displayMonitorSettings.WidthDpi + "x" + displayMonitorSettings.HeightDpi;
                    }
                    else
                    {
                        screenResolutionString = " " + displayMonitorSettings.WidthNative + "x" + displayMonitorSettings.HeightNative;
                    }
                }

                //Get the screen color bit depth
                string screenColorBitDepthString = string.Empty;
                if (showColorBitDepth)
                {
                    screenColorBitDepthString = " " + displayMonitorSettings.BitDepth + "Bits";
                }

                //Get the screen refresh rate
                string screenRefreshRateString = string.Empty;
                if (showRefreshRate)
                {
                    int screenRefreshRateInt = displayMonitorSettings.RefreshRate;
                    if (screenRefreshRateInt > 0)
                    {
                        if (showResolution || showColorBitDepth)
                        {
                            screenRefreshRateString = " @ " + screenRefreshRateInt + "Hz";
                        }
                        else
                        {
                            screenRefreshRateString = " " + screenRefreshRateInt + "Hz";
                        }
                    }
                }

                //Update the screen resolution
                string stringDisplay = AVFunctions.StringRemoveStart(vTitleMON + screenResolutionString + screenColorBitDepthString + screenRefreshRateString, " ");
                AVActions.ActionDispatcherInvoke(delegate
                {
                    textblock_CurrentMon.Text        = stringDisplay;
                    stackpanel_CurrentMon.Visibility = Visibility.Visible;
                });
            }
            catch { }
        }
Ejemplo n.º 30
0
        //Get screen shot colors and set it to byte array
        private static unsafe void ScreenColors(LedSideTypes SideType, int DirectionLedCount, byte[] SerialBytes, byte *BitmapData, ref int CurrentSerialByte)
        {
            try
            {
                //Check the led side
                if (DirectionLedCount == 0 || SideType == LedSideTypes.None)
                {
                    return;
                }

                //Calculate led color direction and bottom gap
                int CaptureZoneHor  = 0;
                int CaptureZoneVer  = 0;
                int CaptureZoneSize = 0;
                int CaptureDiffMax  = 0;
                int CaptureDiffMin  = 0;
                int BottomGapMax    = 0;
                int BottomGapMin    = 0;
                if (SideType == LedSideTypes.TopLeftToRight)
                {
                    CaptureZoneHor  = 0;
                    CaptureZoneVer  = vScreenOutputHeight - vMarginTop;
                    CaptureZoneSize = vScreenOutputWidth / DirectionLedCount;
                    CaptureDiffMax  = (vScreenOutputWidth - (CaptureZoneSize * DirectionLedCount)) / 2;
                    CaptureDiffMin  = DirectionLedCount - CaptureDiffMax;
                }
                else if (SideType == LedSideTypes.TopRightToLeft)
                {
                    CaptureZoneHor  = vScreenOutputWidth - 1;
                    CaptureZoneVer  = vScreenOutputHeight - vMarginTop;
                    CaptureZoneSize = vScreenOutputWidth / DirectionLedCount;
                    CaptureDiffMax  = (vScreenOutputWidth - (CaptureZoneSize * DirectionLedCount)) / 2;
                    CaptureDiffMin  = DirectionLedCount - CaptureDiffMax;
                }
                else if (SideType == LedSideTypes.BottomLeftToRight)
                {
                    DirectionLedCount += setLedBottomGap;
                    CaptureZoneHor     = 0;
                    CaptureZoneVer     = vMarginBottom;
                    CaptureZoneSize    = vScreenOutputWidth / DirectionLedCount;
                    CaptureDiffMax     = (vScreenOutputWidth - (CaptureZoneSize * DirectionLedCount)) / 2;
                    CaptureDiffMin     = DirectionLedCount - CaptureDiffMax;
                    int BottomGapDiff   = setLedBottomGap / 2;
                    int BottomGapTarget = DirectionLedCount / 2;
                    BottomGapMax = BottomGapTarget + BottomGapDiff;
                    BottomGapMin = BottomGapTarget - BottomGapDiff - 1;
                }
                else if (SideType == LedSideTypes.BottomRightToLeft)
                {
                    DirectionLedCount += setLedBottomGap;
                    CaptureZoneHor     = vScreenOutputWidth - 1;
                    CaptureZoneVer     = vMarginBottom;
                    CaptureZoneSize    = vScreenOutputWidth / DirectionLedCount;
                    CaptureDiffMax     = (vScreenOutputWidth - (CaptureZoneSize * DirectionLedCount)) / 2;
                    CaptureDiffMin     = DirectionLedCount - CaptureDiffMax;
                    int BottomGapDiff   = setLedBottomGap / 2;
                    int BottomGapTarget = DirectionLedCount / 2;
                    BottomGapMax = BottomGapTarget + BottomGapDiff;
                    BottomGapMin = BottomGapTarget - BottomGapDiff - 1;
                }
                else if (SideType == LedSideTypes.LeftBottomToTop)
                {
                    CaptureZoneHor  = vMarginLeft;
                    CaptureZoneVer  = 1;
                    CaptureZoneSize = vScreenOutputHeight / DirectionLedCount;
                    CaptureDiffMax  = (vScreenOutputHeight - (CaptureZoneSize * DirectionLedCount)) / 2;
                    CaptureDiffMin  = DirectionLedCount - CaptureDiffMax;
                }
                else if (SideType == LedSideTypes.LeftTopToBottom)
                {
                    CaptureZoneHor  = vMarginLeft;
                    CaptureZoneVer  = vScreenOutputHeight;
                    CaptureZoneSize = vScreenOutputHeight / DirectionLedCount;
                    CaptureDiffMax  = (vScreenOutputHeight - (CaptureZoneSize * DirectionLedCount)) / 2;
                    CaptureDiffMin  = DirectionLedCount - CaptureDiffMax;
                }
                else if (SideType == LedSideTypes.RightBottomToTop)
                {
                    CaptureZoneHor  = vScreenOutputWidth - vMarginRight;
                    CaptureZoneVer  = 1;
                    CaptureZoneSize = vScreenOutputHeight / DirectionLedCount;
                    CaptureDiffMax  = (vScreenOutputHeight - (CaptureZoneSize * DirectionLedCount)) / 2;
                    CaptureDiffMin  = DirectionLedCount - CaptureDiffMax;
                }
                else if (SideType == LedSideTypes.RightTopToBottom)
                {
                    CaptureZoneHor  = vScreenOutputWidth - vMarginRight;
                    CaptureZoneVer  = vScreenOutputHeight;
                    CaptureZoneSize = vScreenOutputHeight / DirectionLedCount;
                    CaptureDiffMax  = (vScreenOutputHeight - (CaptureZoneSize * DirectionLedCount)) / 2;
                    CaptureDiffMin  = DirectionLedCount - CaptureDiffMax;
                }
                //Debug.WriteLine("Zone range: " + vCaptureZoneRange + " / Zone size: " + CaptureZoneSize + " / Zone difference: " + CaptureZoneDiff + " / Leds: " + DirectionLedCount);

                //Get colors from the bitmap
                for (int currentLed = 0; currentLed < DirectionLedCount; currentLed++)
                {
                    //Set led off color byte array
                    if (SideType == LedSideTypes.LedsOff)
                    {
                        SerialBytes[CurrentSerialByte] = 0;
                        CurrentSerialByte++;

                        SerialBytes[CurrentSerialByte] = 0;
                        CurrentSerialByte++;

                        SerialBytes[CurrentSerialByte] = 0;
                        CurrentSerialByte++;
                        continue;
                    }

                    //Skip bottom gap leds
                    bool skipCapture = false;
                    if (BottomGapMax != 0 && AVFunctions.BetweenNumbers(currentLed, BottomGapMin, BottomGapMax, false))
                    {
                        //Debug.WriteLine("Led: " + currentLed + " / GapMin: " + BottomGapMin + " / GapMax: " + BottomGapMax + " / GapLeds: " + setLedBottomGap);
                        skipCapture = true;
                    }

                    if (!skipCapture)
                    {
                        //Capture the colors
                        int CapturedColors = 0;
                        int AverageRed     = 0;
                        int AverageGreen   = 0;
                        int AverageBlue    = 0;
                        CaptureColorAlgorithm(BitmapData, ref CapturedColors, ref AverageRed, ref AverageGreen, ref AverageBlue, CaptureZoneHor, CaptureZoneVer, CaptureZoneSize, SideType);

                        //Calculate average color from the bitmap screen capture
                        //Debug.WriteLine("Captured " + UsedColors + " pixel colors from the bitmap data.");
                        if (CapturedColors > 0)
                        {
                            ColorRGBA CurrentColor = new ColorRGBA()
                            {
                                R = (byte)(AverageRed / CapturedColors), G = (byte)(AverageGreen / CapturedColors), B = (byte)(AverageBlue / CapturedColors)
                            };
                            AdjustLedColors(ref CurrentColor);

                            //Set the color to color byte array
                            SerialBytes[CurrentSerialByte] = CurrentColor.R;
                            CurrentSerialByte++;

                            SerialBytes[CurrentSerialByte] = CurrentColor.G;
                            CurrentSerialByte++;

                            SerialBytes[CurrentSerialByte] = CurrentColor.B;
                            CurrentSerialByte++;
                        }
                        else
                        {
                            //Set the color to color byte array
                            SerialBytes[CurrentSerialByte] = 0;
                            CurrentSerialByte++;

                            SerialBytes[CurrentSerialByte] = 0;
                            CurrentSerialByte++;

                            SerialBytes[CurrentSerialByte] = 0;
                            CurrentSerialByte++;
                        }
                    }

                    //Zone difference correction
                    if (CaptureDiffMax != 0 && AVFunctions.BetweenNumbersOr(currentLed, CaptureDiffMin, CaptureDiffMax, true))
                    {
                        if (SideType == LedSideTypes.TopLeftToRight)
                        {
                            CaptureZoneHor++;
                        }
                        else if (SideType == LedSideTypes.TopRightToLeft)
                        {
                            CaptureZoneHor--;
                        }
                        else if (SideType == LedSideTypes.BottomLeftToRight)
                        {
                            CaptureZoneHor++;
                        }
                        else if (SideType == LedSideTypes.BottomRightToLeft)
                        {
                            CaptureZoneHor--;
                        }
                        else if (SideType == LedSideTypes.LeftBottomToTop)
                        {
                            CaptureZoneVer++;
                        }
                        else if (SideType == LedSideTypes.LeftTopToBottom)
                        {
                            CaptureZoneVer--;
                        }
                        else if (SideType == LedSideTypes.RightBottomToTop)
                        {
                            CaptureZoneVer++;
                        }
                        else if (SideType == LedSideTypes.RightTopToBottom)
                        {
                            CaptureZoneVer--;
                        }
                    }

                    //Skip to the next capture zone
                    if (SideType == LedSideTypes.TopLeftToRight)
                    {
                        CaptureZoneHor += CaptureZoneSize;
                    }
                    else if (SideType == LedSideTypes.TopRightToLeft)
                    {
                        CaptureZoneHor -= CaptureZoneSize;
                    }
                    else if (SideType == LedSideTypes.BottomLeftToRight)
                    {
                        CaptureZoneHor += CaptureZoneSize;
                    }
                    else if (SideType == LedSideTypes.BottomRightToLeft)
                    {
                        CaptureZoneHor -= CaptureZoneSize;
                    }
                    else if (SideType == LedSideTypes.LeftBottomToTop)
                    {
                        CaptureZoneVer += CaptureZoneSize;
                    }
                    else if (SideType == LedSideTypes.LeftTopToBottom)
                    {
                        CaptureZoneVer -= CaptureZoneSize;
                    }
                    else if (SideType == LedSideTypes.RightBottomToTop)
                    {
                        CaptureZoneVer += CaptureZoneSize;
                    }
                    else if (SideType == LedSideTypes.RightTopToBottom)
                    {
                        CaptureZoneVer -= CaptureZoneSize;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to get colors for leds: " + ex.Message);
            }
        }