예제 #1
0
        public static bool CreatePackage(string dataRootPath, List <string> inputPaths, string outputPath, List <string> ignoredFiles)
        {
            try
            {
                if (!dataRootPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    dataRootPath += Path.DirectorySeparatorChar;
                }

                var package = new Package();

                foreach (var f in inputPaths)
                {
                    AddFilesToPackage(package, f, dataRootPath, outputPath, ignoredFiles);
                }

                DivinityApp.Log($"Writing package '{outputPath}'.");
                using (var writer = new PackageWriter(package, outputPath))
                {
                    WritePackage(writer, package, outputPath);
                }
                return(true);
            }
            catch (Exception ex)
            {
                DivinityApp.Log($"Error creating package: {ex}");
                return(false);
            }
        }
        public void OnError(Exception value)
        {
            var message = $"(OnError) Exception encountered:\nType: {value.GetType().ToString()}\tMessage: {value.Message}\nSource: {value.Source}\nStackTrace: {value.StackTrace}";

            DivinityApp.Log(message);
            //MessageBoxResult result = Xceed.Wpf.Toolkit.MessageBox.Show(view, message, "Error Encountered", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, view.MainWindowMessageBox_OK.Style);
        }
예제 #3
0
        /// <summary>
        /// Caches original ImageSource, creates and caches grayscale ImageSource and grayscale opacity mask
        /// </summary>
        private void SetSources()
        {
            // If grayscale image cannot be created set grayscale source to original Source first
            _sourceGray = _sourceColor = Source;

            // Create Opacity Mask for grayscale image as FormatConvertedBitmap does not keep transparency info
            _opacityMaskGray         = new ImageBrush(_sourceColor);
            _opacityMaskGray.Opacity = 0.6;
            Uri uri = null;

            try
            {
                // Get the string Uri for the original image source first
                string stringUri = TypeDescriptor.GetConverter(Source).ConvertTo(Source, typeof(string)) as string;

                // Try to resolve it as an absolute Uri
                if (!Uri.TryCreate(stringUri, UriKind.Absolute, out uri))
                {
                    // Uri is relative => requested image is in the same assembly as this object
                    stringUri = "pack://application:,,,/" + stringUri.TrimStart(new char[2] {
                        Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar
                    });
                    uri = new Uri(stringUri);
                }

                // create and cache grayscale ImageSource
                _sourceGray = new FormatConvertedBitmap(new BitmapImage(uri), PixelFormats.Gray8, null, 0);
            }
            catch (Exception e)
            {
                //Debug.Fail("The Image used cannot be grayed out.", "Use BitmapImage or URI as a Source in order to allow gray scaling. Make sure the absolute Uri is used as relative Uri may sometimes resolve incorrectly.\n\nException: " + e.Message);
                DivinityApp.Log($"Error greying out image '{uri}'({Source}).\n\nException: {e.Message}");
            }
        }
예제 #4
0
        public static bool ExtractPackages(IEnumerable <string> pakPaths, string outputDirectory)
        {
            int success = 0;
            int count   = pakPaths.Count();

            foreach (var path in pakPaths)
            {
                try
                {
                    //Put each pak into its own folder
                    string destination = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(path));

                    //Unless the foldername == the pak name and we're only extracting one pak
                    if (count == 1 && Path.GetDirectoryName(outputDirectory).Equals(Path.GetFileNameWithoutExtension(path)))
                    {
                        destination = outputDirectory;
                    }
                    var packager = new Packager();
                    packager.UncompressPackage(path, destination, null);
                    success++;
                }
                catch (Exception ex)
                {
                    DivinityApp.Log($"Error extracting package: {ex.ToString()}");
                }
            }
            return(success >= count);
        }
        static void OnGridViewSizeChanged(object sender, RoutedEventArgs e)
        {
            if (sender is ListView listView)
            {
                if (listView.View is GridView gridView)
                {
                    if (gridView.Columns.Count >= 2)
                    {
                        // take into account vertical scrollbar
                        var actualWidth = listView.ActualWidth - SystemParameters.VerticalScrollBarWidth;
                        DivinityApp.Log($"GridView actual width: {actualWidth}");

                        for (Int32 i = 2; i < gridView.Columns.Count; i++)
                        {
                            DivinityApp.Log($"** GridView.Columns[{i}] actual width: {gridView.Columns[i].ActualWidth}");
                            actualWidth = actualWidth - gridView.Columns[i].ActualWidth;
                        }

                        DivinityApp.Log($"GridView.Columns[1] next actual width: {actualWidth}");

                        if (actualWidth > 0 && gridView.Columns.Count >= 2)
                        {
                            gridView.Columns[1].Width = actualWidth;
                        }
                    }
                }
            }
        }
예제 #6
0
        private static void PrintDebugNode(Node node, string indent = "", int index = -1)
        {
            if (index > -1)
            {
                DivinityApp.Log($"{indent} [{index}] Node: Name({node.Name}) Children{node.ChildCount}");
            }
            else
            {
                DivinityApp.Log($"{indent} Node: Name({node.Name}) Children{node.ChildCount}");
            }

            DivinityApp.Log($"{indent}Attributes ({node.Attributes.Count})");
            if (node.Attributes.Count > 0)
            {
                foreach (var entry in node.Attributes)
                {
                    DivinityApp.Log($"{indent}  Attribute: Name({entry.Key}) Value({entry.Value.Value}) Type({entry.Value.Type})");
                }
            }

            DivinityApp.Log($"{indent}Children ({node.ChildCount})");
            if (node.ChildCount > 0)
            {
                foreach (var entry in node.Children)
                {
                    DivinityApp.Log($"{indent}  Child List({entry.Key})");
                    int i = 0;
                    foreach (var node2 in entry.Value)
                    {
                        PrintDebugNode(node2, indent + " ", i);
                        i++;
                    }
                }
            }
        }
예제 #7
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool reverse = false;

            if (parameter != null)
            {
                if (parameter is int reverseInt)
                {
                    reverse = reverseInt > 0;
                }
                else if (parameter is bool r)
                {
                    reverse = r;
                }
                DivinityApp.Log($"BoolToVisibilityConverter param: {parameter} | {parameter.GetType()}");
            }

            if (value is bool b)
            {
                if (!reverse)
                {
                    return(b ? Visibility.Visible : Visibility.Collapsed);
                }
                else
                {
                    return(!b ? Visibility.Visible : Visibility.Collapsed);
                }
            }
            return(Visibility.Visible);
        }
 private bool FocusSelectedItem(ListView lv)
 {
     try
     {
         var listBoxItem = (ListBoxItem)lv.ItemContainerGenerator.ContainerFromItem(lv.SelectedItem);
         if (listBoxItem == null)
         {
             var firstItem = lv.Items.GetItemAt(0);
             if (firstItem != null)
             {
                 listBoxItem = (ListBoxItem)lv.ItemContainerGenerator.ContainerFromItem(firstItem);
             }
         }
         if (listBoxItem != null)
         {
             listBoxItem.Focus();
             Keyboard.Focus(listBoxItem);
             return(true);
         }
     }
     catch (Exception ex)
     {
         DivinityApp.Log($"{ex}");
     }
     return(false);
 }
 public static string GetTruePath(string path)
 {
     try
     {
         var driveType = DivinityFileUtils.GetPathDriveType(path);
         if (driveType == System.IO.DriveType.Fixed)
         {
             if (JunctionPoint.Exists(path))
             {
                 string realPath = JunctionPoint.GetTarget(path);
                 if (!String.IsNullOrEmpty(realPath))
                 {
                     return(realPath);
                 }
             }
         }
         else
         {
             DivinityApp.Log($"Skipping junction check for path '{path}'. Drive type is '{driveType}'.");
         }
     }
     catch (Exception ex)
     {
         DivinityApp.Log($"Error checking junction point '{path}': {ex}");
     }
     return(path);
 }
        public static void EmptyWastebasket(bool show_progress,
                                            bool play_sound, bool confirm)
        {
            RecycleFlags options = 0;

            if (!show_progress)
            {
                options =
                    options | RecycleFlags.SHERB_NOPROGRESSUI;
            }
            if (!play_sound)
            {
                options =
                    options | RecycleFlags.SHERB_NOSOUND;
            }
            if (!confirm)
            {
                options =
                    options | RecycleFlags.SHERB_NOCONFIRMATION;
            }

            try
            {
                SHEmptyRecycleBin(IntPtr.Zero, null, (uint)options);
            }
            catch (Exception ex)
            {
                DivinityApp.Log("Error emptying wastebasket.\n" + ex.ToString());
            }
        }
        // Delete a file or move it to the recycle bin.
        public static void DeleteFile(string filename, bool confirm,
                                      bool delete_permanently)
        {
            UIOption ui_option = UIOption.OnlyErrorDialogs;

            if (confirm)
            {
                ui_option = UIOption.AllDialogs;
            }

            RecycleOption recycle_option =
                recycle_option = RecycleOption.SendToRecycleBin;

            if (delete_permanently)
            {
                recycle_option = RecycleOption.DeletePermanently;
            }
            try
            {
                Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(filename, ui_option, recycle_option);
            }
            catch (Exception ex)
            {
                DivinityApp.Log("Error deleting file.\n" + ex.ToString());
            }
        }
 private void TraceBackground(Control c)
 {
     DivinityApp.Log($"{c} Background({c.Background})");
     foreach (var c2 in c.FindVisualChildren <Control>())
     {
         if (c2.Background != null && !c2.Background.Equals(Brushes.Transparent))
         {
             TraceBackground(c2);
         }
     }
 }
        public void OnNext(Exception value)
        {
            //if (Debugger.IsAttached) Debugger.Break();

            var message = $"(OnNext) Exception encountered:\nType: {value.GetType().ToString()}\tMessage: {value.Message}\nSource: {value.Source}\nStackTrace: {value.StackTrace}";

            DivinityApp.Log(message);
            MessageBox.Show(message, "Error Encountered", MessageBoxButton.OK, MessageBoxImage.Error);
            //MessageBoxResult result = Xceed.Wpf.Toolkit.MessageBox.Show(view, message, "Error Encountered", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, view.MainWindowMessageBox_OK.Style);
            //RxApp.MainThreadScheduler.Schedule(() => { throw value; });
        }
 override public bool HasNullChildElement()
 {
     foreach (var c in _listView.Items)
     {
         if (c == null)
         {
             DivinityApp.Log("Found a null entry in ModListViewAutomationPeer");
             return(true);
         }
     }
     return(false);
 }
 public static string GetSteamWorkshopPath()
 {
     if (LastSteamInstallPath != "")
     {
         string workshopFolder = Path.Combine(LastSteamInstallPath, PATH_Steam_WorkshopFolder);
         DivinityApp.Log($"Looking for workshop folder at '{workshopFolder}'.");
         if (Directory.Exists(workshopFolder))
         {
             return(workshopFolder);
         }
     }
     return("");
 }
 public bool ValueContains(string val, bool separateWhitespace = false)
 {
     if (separateWhitespace && val.IndexOf(" ") > 1)
     {
         var vals     = val.Split(separators, StringSplitOptions.RemoveEmptyEntries);
         var findVals = FilterValue.Split(separators, StringSplitOptions.RemoveEmptyEntries);
         DivinityApp.Log($"Searching for '{String.Join("; ", findVals)}' in ({String.Join("; ", vals)}");
         return(vals.Any(x => findVals.Any(x2 => CultureInfo.CurrentCulture.CompareInfo.IndexOf(x, x2, CompareOptions.IgnoreCase) >= 0)));
     }
     else
     {
         return(CultureInfo.CurrentCulture.CompareInfo.IndexOf(val, FilterValue, CompareOptions.IgnoreCase) >= 0);
     }
 }
예제 #17
0
 public static bool ExtractPackage(string pakPath, string outputDirectory)
 {
     try
     {
         var packager = new Packager();
         packager.UncompressPackage(pakPath, outputDirectory, null);
         return(true);
     }
     catch (Exception ex)
     {
         DivinityApp.Log($"Error extracting package: {ex.ToString()}");
         return(false);
     }
 }
예제 #18
0
        public static async Task <bool> CreatePackageAsync(string dataRootPath, List <string> inputPaths, string outputPath, List <string> ignoredFiles, CancellationToken?token = null)
        {
            try
            {
                if (token == null)
                {
                    token = CancellationToken.None;
                }

                if (token.Value.IsCancellationRequested)
                {
                    return(false);
                }

                if (!dataRootPath.EndsWith(Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar.ToString()))
                {
                    dataRootPath += Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar;
                }

                var package = new Package();

                foreach (var f in inputPaths)
                {
                    if (token.Value.IsCancellationRequested)
                    {
                        throw new TaskCanceledException("Cancelled package creation.");
                    }
                    await AddFilesToPackageAsync(package, f, dataRootPath, outputPath, ignoredFiles, token.Value);
                }

                DivinityApp.Log($"Writing package '{outputPath}'.");
                using (var writer = new PackageWriter(package, outputPath))
                {
                    await WritePackageAsync(writer, package, outputPath, token.Value);
                }
                return(true);
            }
            catch (Exception ex)
            {
                if (!token.Value.IsCancellationRequested)
                {
                    DivinityApp.Log($"Error creating package: {ex.ToString()}");
                }
                else
                {
                    DivinityApp.Log($"Cancelled creating package: {ex.ToString()}");
                }
                return(false);
            }
        }
예제 #19
0
 public static string DownloadUrlAsString(string downloadUrl)
 {
     using (System.Net.WebClient webClient = new System.Net.WebClient())
     {
         try
         {
             return(webClient.DownloadString(downloadUrl));
         }
         catch (Exception ex)
         {
             DivinityApp.Log($"Error downloading '{downloadUrl}' as string:\n{ex}");
         }
         return("");
     }
 }
 private static object GetKey(RegistryKey reg, string subKey, string keyValue)
 {
     try
     {
         RegistryKey key = reg.OpenSubKey(subKey);
         if (key != null)
         {
             return(key.GetValue(keyValue));
         }
     }
     catch (Exception e)
     {
         DivinityApp.Log($"Error reading registry subKey ({subKey}): {e.ToString()}");
     }
     return(null);
 }
예제 #21
0
 public static void PrintDebug(this Resource resource)
 {
     foreach (var kvpRegion in resource.Regions)
     {
         DivinityApp.Log($"Region: Key({kvpRegion.Key}) Name({kvpRegion.Value.Name}) RegionName({kvpRegion.Value.RegionName})");
         foreach (var nodeList in kvpRegion.Value.Children)
         {
             DivinityApp.Log($" Children: Key({nodeList.Key})");
             for (var i = 0; i < nodeList.Value.Count; i++)
             {
                 var node = nodeList.Value[i];
                 PrintDebugNode(node, "  ", i);
             }
         }
     }
 }
예제 #22
0
 public static async Task <bool> WriteFileAsync(string path, string content)
 {
     try
     {
         using (System.IO.StreamWriter outputFile = new System.IO.StreamWriter(path))
         {
             await outputFile.WriteAsync(content);
         }
         return(true);
     }
     catch (Exception ex)
     {
         DivinityApp.Log($"Error writing file: {ex.ToString()}");
         return(false);
     }
 }
        public void OnError(Exception error)
        {
            DivinityApp.Log($"Error: ({error.GetType().ToString()}: {error.Message}\n{error.StackTrace}");
            if (Debugger.IsAttached)
            {
                Debugger.Break();
            }

            RxApp.MainThreadScheduler.Schedule(() => {
                if (_viewModel.MainProgressIsActive)
                {
                    _viewModel.MainProgressIsActive = false;
                }
                _viewModel.View.AlertBar.SetDangerAlert(error.Message);
                //throw error;
            });
        }
 public static string GetWorkshopPath(string appid)
 {
     if (LastSteamInstallPath != "")
     {
         string steamWorkshopPath = GetSteamWorkshopPath();
         if (!String.IsNullOrEmpty(steamWorkshopPath))
         {
             string workshopFolder = Path.Combine(steamWorkshopPath, "content", appid);
             DivinityApp.Log($"Looking for game workshop folder at '{workshopFolder}'.");
             if (Directory.Exists(workshopFolder))
             {
                 return(workshopFolder);
             }
         }
     }
     return("");
 }
        private static Size MeasureText(string text,
                                        FontFamily fontFamily,
                                        FontStyle fontStyle,
                                        FontWeight fontWeight,
                                        FontStretch fontStretch, double fontSize)
        {
            Typeface      typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
            GlyphTypeface glyphTypeface;

            if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
            {
                return(MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize));
            }

            double totalWidth = 0;
            double height     = 0;

            for (int n = 0; n < text.Length; n++)
            {
                try
                {
                    ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]];

                    double width = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize;

                    double glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex] * fontSize;

                    if (glyphHeight > height)
                    {
                        height = glyphHeight;
                    }

                    totalWidth += width;
                }
                catch (Exception ex)
                {
                    DivinityApp.Log($"Error measuring text:\n{ex}");
                }
            }

            return(new Size(totalWidth, height));
        }
예제 #26
0
 public static T SafeDeserializeFromPath <T>(string path)
 {
     try
     {
         if (File.Exists(path))
         {
             string contents = File.ReadAllText(path);
             return(SafeDeserialize <T>(contents));
         }
         else
         {
             DivinityApp.Log($"Error deserializing json: File '{path}' does not exist.");
         }
     }
     catch (Exception ex)
     {
         DivinityApp.Log("Error deserializing json:\n" + ex.ToString());
     }
     return(default(T));
 }
예제 #27
0
        public void SaveDefaultKeybindings()
        {
            string filePath = @"Data\keybindings-default.json";

            try
            {
                Directory.CreateDirectory("Data");
                var keyMapDict = new Dictionary <string, Hotkey>();
                foreach (var key in All)
                {
                    keyMapDict.Add(key.ID, key);
                }
                string contents = JsonConvert.SerializeObject(keyMapDict, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(filePath, contents);
            }
            catch (Exception ex)
            {
                DivinityApp.Log($"Error saving default keybindings at '{filePath}': {ex}");
            }
        }
        private void Sort(string sortBy, ListSortDirection direction, object sender)
        {
            if (sortBy == "Version")
            {
                sortBy = "Version.Version";
            }
            if (sortBy == "#")
            {
                sortBy = "Index";
            }
            if (sortBy == "Name")
            {
                sortBy = "DisplayName";
            }
            if (sortBy == "Modes")
            {
                sortBy = "Targets";
            }
            if (sortBy == "Last Updated")
            {
                sortBy = "LastUpdated";
            }

            try
            {
                ListView        lv       = sender as ListView;
                ICollectionView dataView =
                    CollectionViewSource.GetDefaultView(lv.ItemsSource);

                dataView.SortDescriptions.Clear();
                SortDescription sd = new SortDescription(sortBy, direction);
                dataView.SortDescriptions.Add(sd);
                dataView.Refresh();
            }
            catch (Exception ex)
            {
                DivinityApp.Log("Error sorting mods:");
                DivinityApp.Log(ex.ToString());
            }
        }
예제 #29
0
        private static void AddFilesToPackage(Package package, string path, string dataRootPath, string outputPath, List <string> ignoredFiles)
        {
            if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                path += Path.DirectorySeparatorChar;
            }

            var files = Directory.EnumerateFiles(path, DirectoryEnumerationOptions.Recursive | DirectoryEnumerationOptions.LargeCache, new DirectoryEnumerationFilters()
            {
                InclusionFilter = (f) =>
                {
                    return(!ignoredFiles.Any(x => IgnoreFile(f.FullPath, x)));
                }
            }).ToDictionary(k => k.Replace(dataRootPath, String.Empty), v => v);

            foreach (KeyValuePair <string, string> file in files)
            {
                DivinityApp.Log("Creating FilesystemFileInfo ");
                FilesystemFileInfo fileInfo = FilesystemFileInfo.CreateFromEntry(file.Value, file.Key);
                package.Files.Add(fileInfo);
            }
        }
        private void Sort(string sortBy, ListSortDirection direction, object sender, bool modUpdatesGrid = false)
        {
            if (sortBy == "Version" || sortBy == "Current")
            {
                sortBy = "Version.Version";
            }
            if (sortBy == "New")
            {
                sortBy = "WorkshopMod.Version.Version";
            }
            if (sortBy == "#")
            {
                sortBy = "Index";
            }

            if (modUpdatesGrid && sortBy != "IsSelected" && sortBy != "WorkshopMod.Version.Version")
            {
                sortBy = "LocalMod." + sortBy;
            }

            if (sortBy != "")
            {
                try
                {
                    ListView        lv       = sender as ListView;
                    ICollectionView dataView =
                        CollectionViewSource.GetDefaultView(lv.ItemsSource);

                    dataView.SortDescriptions.Clear();
                    SortDescription sd = new SortDescription(sortBy, direction);
                    dataView.SortDescriptions.Add(sd);
                    dataView.Refresh();
                }
                catch (Exception ex)
                {
                    DivinityApp.Log("Error sorting grid: " + ex.ToString());
                }
            }
        }