Example #1
0
        /// <summary>
        /// Loads the bot token from disk.
        /// </summary>
        /// <exception cref="FileNotFoundException">Thrown if the bot token file can't be found.</exception>
        /// <exception cref="InvalidDataException">Thrown if no token exists in the file.</exception>
        /// <returns>A retrieval result which may or may not have succeeded.</returns>
        public async Task <RetrieveEntityResult <string> > GetBotTokenAsync()
        {
            var tokenPath = UPath.Combine(UPath.Root, "Discord", "bot.token");

            if (!this.FileSystem.FileExists(tokenPath))
            {
                return(RetrieveEntityResult <string> .FromError("The token file could not be found."));
            }

            var getTokenStream = OpenLocalStream(tokenPath);

            if (!getTokenStream.IsSuccess)
            {
                return(RetrieveEntityResult <string> .FromError("The token file could not be opened."));
            }

            await using var tokenStream = getTokenStream.Entity;
            var token = await AsyncIO.ReadAllTextAsync(tokenStream);

            if (string.IsNullOrEmpty(token))
            {
                return(RetrieveEntityResult <string> .FromError("The token file did not contain a valid token."));
            }

            return(RetrieveEntityResult <string> .FromSuccess(token));
        }
        public override bool Upgrade(PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage, IList <PackageLoadingAssetFile> assetFiles)
        {
            // Paradox 1.1 projects didn't have their dependency properly updated (they might have been marked as 1.0).
            // We know they are 1.1 only because there is a .props file.
            // This check shouldn't be necessary from 1.2.
            var packagePath   = dependentPackage.FullPath;
            var propsFilePath = UPath.Combine(packagePath.GetParent(), (UFile)(packagePath.GetFileName() + ".props"));

            if (!File.Exists(propsFilePath) && dependency.Version.MinVersion < new PackageVersion("1.1.0-beta"))
            {
                log.Error("Can't upgrade old projects from {0} 1.0 to 1.1", dependency.Name);
                return(false);
            }

            // Nothing to do for now, most of the work is already done by individual asset upgraders
            // We can later add logic here for package-wide upgrades (i.e. GameSettingsAsset)
            if (dependency.Version.MinVersion < new PackageVersion("1.2.0-beta"))
            {
                // UIImageGroups and SpriteGroups asset have been merged into a single SpriteSheet => rename the assets and modify the tag
                var uiImageGroups = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".pdxuiimage");
                var spritesGroups = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".pdxsprite");
                RenameAndChangeTag(assetFiles, uiImageGroups, "!UIImageGroup");
                RenameAndChangeTag(assetFiles, spritesGroups, "!SpriteGroup");
            }

            if (dependency.Version.MinVersion < new PackageVersion("1.3.0-alpha01"))
            {
                GameSettingsAsset.UpgraderVersion130.Upgrade(session, log, dependentPackage, dependency, dependencyPackage, assetFiles);
            }

            return(true);
        }
        /// <summary>
        /// Updates the location of the dossier data, matching it to the dossier's name.
        /// </summary>
        /// <param name="dossier">The dossier to update.</param>
        /// <param name="newTitle">The new dossier title.</param>
        /// <param name="ct">The cancellation token in use.</param>
        /// <returns>An entity modification result which may or may not have succeeded.</returns>
        public async Task <ModifyEntityResult> UpdateDossierDataLocationAsync
        (
            Dossier dossier,
            string newTitle,
            CancellationToken ct = default
        )
        {
            var originalDossierPath = GetDossierDataPath(dossier);

            var newDossierPath = UPath.Combine(this.BaseDossierPath, $"{newTitle}.pdf");

            if (!_content.FileSystem.FileExists(originalDossierPath) || originalDossierPath == newDossierPath)
            {
                return(ModifyEntityResult.FromSuccess());
            }

            try
            {
                _content.FileSystem.MoveFile(originalDossierPath, newDossierPath);
            }
            catch (Exception e)
            {
                return(ModifyEntityResult.FromError(e.Message));
            }

            await _database.SaveChangesAsync(ct);

            return(ModifyEntityResult.FromSuccess());
        }
Example #4
0
        /// <summary>
        /// Loads the sass from disk.
        /// </summary>
        private async Task <DetermineConditionResult> LoadSassAsync()
        {
            var sassPath     = UPath.Combine(UPath.Root, "Sass", "sass.txt");
            var sassNSFWPath = UPath.Combine(UPath.Root, "Sass", "sass-nsfw.txt");

            var getSassStream = _content.OpenLocalStream(sassPath);

            if (getSassStream.IsSuccess)
            {
                await using var sassStream = getSassStream.Entity;
                _sass = (await AsyncIO.ReadAllLinesAsync(sassStream)).ToList();
            }
            else
            {
                return(DetermineConditionResult.FromError(getSassStream));
            }

            var getNSFWSassStream = _content.OpenLocalStream(sassNSFWPath);

            if (getNSFWSassStream.IsSuccess)
            {
                await using var nsfwSassStream = getNSFWSassStream.Entity;
                _sassNSFW = (await AsyncIO.ReadAllLinesAsync(nsfwSassStream)).ToList();
            }
            else
            {
                return(DetermineConditionResult.FromError(getNSFWSassStream));
            }

            _isSassLoaded = true;
            return(DetermineConditionResult.FromSuccess());
        }
Example #5
0
        /// <summary>
        /// Loads the sass from disk.
        /// </summary>
        private async Task LoadSassAsync()
        {
            var sassPath     = UPath.Combine(UPath.Root, "Sass", "sass.txt");
            var sassNSFWPath = UPath.Combine(UPath.Root, "Sass", "sass-nsfw.txt");

            var getSassStream = OpenLocalStream(sassPath);

            if (getSassStream.IsSuccess)
            {
                using (var sassStream = getSassStream.Entity)
                {
                    _sass = (await AsyncIO.ReadAllLinesAsync(sassStream)).ToList();
                }
            }

            var getNSFWSassStream = OpenLocalStream(sassNSFWPath);

            if (getNSFWSassStream.IsSuccess)
            {
                using (var nsfwSassStream = getNSFWSassStream.Entity)
                {
                    _sassNSFW = (await AsyncIO.ReadAllLinesAsync(nsfwSassStream)).ToList();
                }
            }
        }
        public NewProjectTemplateCollectionViewModel(IViewModelServiceProvider serviceProvider, SessionViewModel session)
            : base(serviceProvider)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            Session = session;

            rootGroup = new TemplateDescriptionGroupViewModel(serviceProvider, "All templates");

            // Add a default General group
            var defaultGroup = new TemplateDescriptionGroupViewModel(rootGroup, "General");

            foreach (TemplateDescription template in session.FindTemplates(TemplateScope.Session))
            {
                if (!IsAssetsOnlyTemplate(template))
                {
                    continue;
                }

                var viewModel = new PackageTemplateViewModel(serviceProvider, template, session);
                var group     = ProcessGroup(rootGroup, template.Group) ?? defaultGroup;
                group.Templates.Add(viewModel);
            }

            Location = session.SolutionPath.GetFullDirectory() ?? InternalSettings.TemplatesWindowDialogLastNewSessionTemplateDirectory.GetValue();
            if (string.IsNullOrWhiteSpace(Location))
            {
                Location = UPath.Combine <UDirectory>(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Stride Projects");
            }

            SelectedGroup = rootGroup;
        }
Example #7
0
        /// <summary>
        /// Gets the filename to the specific package <paramref name="packageName"/> using the version <paramref name="versionRange"/> if not null, otherwise the <paramref name="constraintProvider"/> if specified.
        /// If no constraints are specified, the first entry if any are founds is used to get the filename.
        /// </summary>
        /// <param name="packageName">Name of the package.</param>
        /// <param name="versionRange">The version range.</param>
        /// <param name="constraintProvider">The package constraint provider.</param>
        /// <param name="allowPreleaseVersion">if set to <c>true</c> [allow prelease version].</param>
        /// <param name="allowUnlisted">if set to <c>true</c> [allow unlisted].</param>
        /// <returns>A location on the disk to the specified package or null if not found.</returns>
        /// <exception cref="System.ArgumentNullException">packageName</exception>
        public UFile GetPackageFileName(string packageName, PackageVersionRange versionRange = null, ConstraintProvider constraintProvider = null, bool allowPreleaseVersion = true, bool allowUnlisted = false)
        {
            if (packageName == null)
            {
                throw new ArgumentNullException(nameof(packageName));
            }

            var package = store.FindLocalPackage(packageName, versionRange, constraintProvider, allowPreleaseVersion, allowUnlisted);

            // If package was not found,
            if (package != null)
            {
                return(UPath.Combine(store.GetInstallPath(package), new UFile(packageName + Package.PackageFileExtension)));
            }

            // TODO: Check version for default package
            if (packageName == DefaultPackageName)
            {
                if (versionRange == null || versionRange.Contains(DefaultPackageVersion))
                {
                    return(UPath.Combine(UPath.Combine(UPath.Combine(InstallationPath, (UDirectory)store.RepositoryPath), defaultPackageDirectory), new UFile(packageName + Package.PackageFileExtension)));
                }
            }

            return(null);
        }
Example #8
0
        private static UFile GenerateLocation(string assetName, AssetTemplateGeneratorParameters parameters)
        {
            var location = assetName.StartsWith(parameters.TargetLocation) ? new UFile(assetName)
                                    : UPath.Combine(parameters.TargetLocation, new UFile(assetName));

            return(NamingHelper.ComputeNewName(location, x => parameters.Package.Assets.Find(x) != null, "{0}_{1}"));
        }
Example #9
0
        public virtual void PushFileOutput(UPath path, bool autoDispose = true)
        {
            if (path.IsNull || path.IsEmpty)
            {
                throw new ArgumentNullException(nameof(path));
            }

            var fileSystem = Options.FileSystem;

            if (fileSystem == null)
            {
                throw new InvalidOperationException($"The `{nameof(CodeWriterOptions)}.{nameof(CodeWriterOptions.FileSystem)}` is null but must be setup in order to use `{nameof(PushFileOutput)}`");
            }

            var filePath  = UPath.Combine(UPath.Root, path);
            var directory = filePath.GetDirectory();

            if (!directory.IsEmpty && !fileSystem.DirectoryExists(directory))
            {
                fileSystem.CreateDirectory(directory);
            }
            var finalWriter = new StreamWriter(new BufferedStream(fileSystem.CreateFile(filePath)));

            PushOutput(finalWriter, autoDispose);
        }
Example #10
0
        private static void PreLoadPackageDependencies(PackageSession session, ILogger log, Package package, PackageCollection loadedPackages, PackageLoadParameters loadParameters)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }
            if (loadParameters == null)
            {
                throw new ArgumentNullException("loadParameters");
            }

            // 1. Load store package
            foreach (var packageDependency in package.Meta.Dependencies)
            {
                var loadedPackage = session.Packages.Find(packageDependency);
                if (loadedPackage != null)
                {
                    continue;
                }

                var file = PackageStore.Instance.GetPackageFileName(packageDependency.Name, packageDependency.Version);

                if (file == null)
                {
                    // TODO: We need to support automatic download of packages. This is not supported yet when only Paradox
                    // package is supposed to be installed, but It will be required for full store
                    log.Error("Unable to find package {0} not installed", packageDependency);
                    continue;
                }

                // Recursive load of the system package
                PreLoadPackage(session, log, file, true, loadedPackages, loadParameters);
            }

            // 2. Load local packages
            foreach (var packageReference in package.LocalDependencies)
            {
                // Check that the package was not already loaded, otherwise return the same instance
                if (session.Packages.ContainsById(packageReference.Id))
                {
                    continue;
                }

                // Expand the string of the location
                var newLocation = (UFile)AssetRegistry.ExpandString(session, packageReference.Location);

                var subPackageFilePath = package.RootDirectory != null?UPath.Combine(package.RootDirectory, newLocation) : newLocation;

                // Recursive load
                PreLoadPackage(session, log, subPackageFilePath.FullPath, false, loadedPackages, loadParameters);
            }
        }
Example #11
0
        public ContentService(IFileSystem fileSystem)
        {
            FileSystem = fileSystem;

            _databaseCredentialsPath = UPath.Combine(UPath.Root, "Database", "database.credentials");
            _tokenPath = UPath.Combine(UPath.Root, "Discord", "bot.token");
        }
        public static void ApplyTreemaps()
        {
            var tiles = LandmasImporter.FindTerrainTilesInScene();

            foreach (var lodLevel in tiles)
            {
                var lod = Instance.ImportCfg.LodLevels[lodLevel.Key];

                foreach (var pair in lodLevel.Value)
                {
                    var region = pair.Key;

                    int    index       = (int)(region.X + (lod.GridSize - 1 - region.Z) * lod.GridSize);
                    string treemapName = string.Format("terrain_t_{0:00}.png", index);
                    var    treeMap     = AssetDatabase.LoadAssetAtPath(UPath.Combine(lod.FolderPath, treemapName), typeof(Texture2D)) as Texture2D;
                    if (treeMap == null)
                    {
                        Debug.LogError("Couldn't find treemap: " + treemapName);
                        continue;
                    }

                    LandmasImporter.ParseTreemapTexturesToTerrain(treeMap, pair.Value.Terrain.terrainData);
                }
            }
        }
Example #13
0
        /// <inheritdoc />
        public async Task <LoadResult> LoadFile(IStateInfo stateInfo, ArchiveFileInfo afi, Guid pluginId, LoadFileContext loadFileContext)
        {
            // If stateInfo is no archive state
            if (!(stateInfo.PluginState is IArchiveState archiveState))
            {
                throw new InvalidOperationException("The state represents no archive.");
            }

            // If file is already loaded
            var absoluteFilePath = UPath.Combine(stateInfo.AbsoluteDirectory, stateInfo.FilePath.ToRelative(), afi.FilePath.ToRelative());

            if (IsLoaded(absoluteFilePath))
            {
                return(new LoadResult(GetLoadedFile(absoluteFilePath)));
            }

            // 1. Create file system action
            var fileSystemAction = new Func <IStreamManager, IFileSystem>(streamManager =>
                                                                          FileSystemFactory.CreateAfiFileSystem(stateInfo, UPath.Root, streamManager));

            // 2. Load file
            // ArchiveFileInfos have stateInfo as their parent, if loaded like this
            var loadResult = await LoadFile(fileSystemAction, afi.FilePath, stateInfo, pluginId, loadFileContext);

            if (!loadResult.IsSuccessful)
            {
                return(loadResult);
            }

            // 3. Add archive child to parent
            // ArchiveChildren are only added, if a file is loaded like this
            stateInfo.ArchiveChildren.Add(loadResult.LoadedState);

            return(loadResult);
        }
        public async Task CreateJunctionPointWithJunctionFsForDeepPath()
        {
            IFileSystem fs = new JunctionFs(new MemoryFileSystem());

            UPath target = "/test1/sub1/sub2";
            UPath junctionPointVirtualPath = "/virtual";

            var junctionPoint = new JunctionPoint(junctionPointVirtualPath, target);

            fs.CreateDirectory(target);

            var entry = new DirectoryEntry(fs, target);

            var filePath = UPath.Combine(entry.Path, "test.txt");

            await using var testFile = fs.CreateFile(filePath);

            await testFile.WriteAsync(Encoding.UTF8.GetBytes("123"));

            fs.CreateJunctionPoint(junctionPoint, overwrite: true);

            var virtualFilePath = UPath.Combine(junctionPointVirtualPath, "test.txt");

            var virtualFile  = fs.GetFileEntry(virtualFilePath);
            var physicalFile = fs.GetFileEntry(filePath);

            Assert.True(virtualFile.Exists);
            Assert.True(physicalFile.Exists);

            bool junctionPointExists = fs.JunctionPointExists(virtualFilePath);

            Assert.True(junctionPointExists);
        }
Example #15
0
 /// <inheritdoc />
 public IStateInfo GetLoadedFile(UPath filePath)
 {
     lock (_loadedFilesLock)
     {
         return(_loadedFiles.FirstOrDefault(x => UPath.Combine(x.AbsoluteDirectory, x.FilePath.ToRelative()) == filePath));
     }
 }
Example #16
0
 /// <inheritdoc />
 public bool IsLoaded(UPath filePath)
 {
     lock (_loadedFilesLock)
     {
         return(_loadedFiles.Any(x => UPath.Combine(x.AbsoluteDirectory, x.FilePath.ToRelative()) == filePath));
     }
 }
Example #17
0
        private IEnumerable <IArchiveFileInfo> ReadTocTable(BinaryReaderX br, long tocOffset, long contentOffset)
        {
            // Read toc table
            _tocTable = CpkTable.Create(br.BaseStream, tocOffset);

            // Determine file offset
            var fileOffset = tocOffset;

            if (contentOffset >= 0)
            {
                fileOffset = tocOffset < 0 ? contentOffset : Math.Min(contentOffset, tocOffset);
            }

            // Populate files
            foreach (var row in _tocTable.Rows)
            {
                var dir        = row.Get <string>("DirName");
                var name       = row.Get <string>("FileName");
                var offset     = fileOffset + row.Get <long>("FileOffset");
                var compSize   = row.Get <int>("FileSize");
                var decompSize = row.Get <int>("ExtractSize");

                var subStream = new SubStream(br.BaseStream, offset, compSize);
                if (compSize == decompSize)
                {
                    yield return(new CpkArchiveFileInfo(subStream, UPath.Combine(dir, name).FullName, row));
                }
                else
                {
                    yield return(new CpkArchiveFileInfo(subStream, UPath.Combine(dir, name).FullName, row, Kompression.Implementations.Compressions.Crilayla, decompSize));
                }
            }
        }
Example #18
0
        private static CSharpClass CreateClassLib(CSharpConverter converter, UPath?subFilePathOverride = null)
        {
            var compilation = converter.CurrentCSharpCompilation;

            var path = converter.Options.DefaultOutputFilePath;

            if (subFilePathOverride != null)
            {
                path = UPath.Combine(converter.Options.DefaultOutputFilePath.GetDirectory(), subFilePathOverride.Value);
            }

            var csFile = new CSharpGeneratedFile(path);

            compilation.Members.Add(csFile);

            var csNamespace = new CSharpNamespace(converter.Options.DefaultNamespace);

            csFile.Members.Add(csNamespace);

            var csClassLib = new CSharpClass(converter.Options.DefaultClassLib);

            csClassLib.Modifiers |= CSharpModifiers.Partial | CSharpModifiers.Static;
            converter.ApplyDefaultVisibility(csClassLib, csNamespace);

            csNamespace.Members.Add(csClassLib);
            return(csClassLib);
        }
        /// <inheritdoc />
        protected override void CompileThumbnail(ThumbnailCompilerContext context, string thumbnailStorageUrl, AssetItem assetItem, Package originalPackage, AssetCompilerResult result)
        {
            var   thumbnailSize = context.ThumbnailResolution;
            UFile assetSource   = null;

            var sourceValid = !string.IsNullOrEmpty(Asset.Source);

            if (sourceValid)
            {
                // Get absolute path of asset source on disk
                var assetDirectory = assetItem.FullPath.GetParent();
                assetSource = UPath.Combine(assetDirectory, Asset.Source);
                sourceValid = File.Exists(assetSource);
            }

            if (sourceValid)
            {
                result.BuildSteps.Add(new ThumbnailBuildStep(new TextureThumbnailBuildCommand(context, thumbnailStorageUrl, assetItem, originalPackage, new TextureThumbnailParameters(Asset, assetSource, thumbnailStorageUrl, thumbnailSize))));
            }
            else
            {
                var gameSettings = context.GetGameSettingsAsset();
                result.Error($"Source is null or unreachable for Texture Asset [{Asset}]");
                result.BuildSteps.Add(new StaticThumbnailCommand <TextureAsset>(thumbnailStorageUrl, DefaultThumbnails.TextureNoSource, thumbnailSize, gameSettings.GetOrCreate <RenderingSettings>().ColorSpace == ColorSpace.Linear, assetItem.Package));
            }
        }
Example #20
0
        protected override void Compile(AssetCompilerContext context, string urlInStorage, UFile assetAbsolutePath, SpriteSheetAsset asset, AssetCompilerResult result)
        {
            result.BuildSteps = new AssetBuildStep(AssetItem);

            // create the registry containing the sprite assets texture index association
            var imageToTextureIndex = new Dictionary <SpriteInfo, int>();

            // create and add import texture commands
            if (asset.Sprites != null)
            {
                var gameSettingsAsset = context.GetGameSettingsAsset();

                // sort sprites by referenced texture.
                var spriteByTextures = asset.Sprites.GroupBy(x => x.Source).ToArray();
                for (int i = 0; i < spriteByTextures.Length; i++)
                {
                    // skip the texture if the file is not valid.
                    var textureFile = spriteByTextures[i].Key;
                    if (!TextureFileIsValid(textureFile))
                    {
                        continue;
                    }

                    var spriteAssetArray = spriteByTextures[i].ToArray();
                    foreach (var spriteAsset in spriteAssetArray)
                    {
                        imageToTextureIndex[spriteAsset] = i;
                    }

                    // create an texture asset.
                    var textureAsset = new TextureAsset
                    {
                        Id               = Guid.Empty, // CAUTION: It is important to use an empty GUID here, as we don't want the command to be rebuilt (by default, a new asset is creating a new guid)
                        Alpha            = asset.Alpha,
                        Format           = asset.Format,
                        GenerateMipmaps  = asset.GenerateMipmaps,
                        PremultiplyAlpha = asset.PremultiplyAlpha,
                        ColorKeyColor    = asset.ColorKeyColor,
                        ColorKeyEnabled  = asset.ColorKeyEnabled,
                    };

                    // Get absolute path of asset source on disk
                    var assetDirectory = assetAbsolutePath.GetParent();
                    var assetSource    = UPath.Combine(assetDirectory, spriteAssetArray[0].Source);

                    // add the texture build command.
                    result.BuildSteps.Add(
                        new TextureAssetCompiler.TextureConvertCommand(
                            SpriteSheetAsset.BuildTextureUrl(urlInStorage, i),
                            new TextureConvertParameters(assetSource, textureAsset, context.Platform, context.GetGraphicsPlatform(), gameSettingsAsset.DefaultGraphicsProfile, gameSettingsAsset.TextureQuality)));
                }

                result.BuildSteps.Add(new WaitBuildStep()); // wait the textures to be imported
            }

            if (!result.HasErrors)
            {
                result.BuildSteps.Add(new SpriteSheetCommand(urlInStorage, new SpriteSheetParameters(asset, context.Platform), imageToTextureIndex));
            }
        }
        /// <summary>
        /// Saves a .props file for the specified package, containing the xenko version (only Major.Minor)
        /// used to compile the package.
        /// </summary>
        /// <param name="package">The package.</param>
        public static void SaveProperties(Package package)
        {
            // Props file is in the same folder as the xkpkg file, just with a ".props" extension.
            var packagePath   = package.FullPath;
            var propsFilePath = UPath.Combine(packagePath.GetParent(), (UFile)(packagePath.GetFileNameWithoutExtension() + ".props"));

            var projectCollection   = new Microsoft.Build.Evaluation.ProjectCollection();
            var project             = new Microsoft.Build.Evaluation.Project(projectCollection);
            var commonPropertyGroup = project.Xml.AddPropertyGroup();

            var dependencies = package.FindDependencies(false, false, true);

            // Add Xenko version
            var xkVersion = dependencies.FirstOrDefault(d => d.Meta.Name == "Xenko");

            if (xkVersion != null)
            {
                var versionText = xkVersion.Meta.Version.Version.Major + "." + xkVersion.Meta.Version.Version.Minor;
                commonPropertyGroup.AddProperty("SiliconStudioPackageXenkoVersion", versionText);
            }

            if (File.Exists(propsFilePath))
            {
                File.Delete(propsFilePath);
            }
            project.Save(propsFilePath);
        }
        public NewOrOpenSessionTemplateCollectionViewModel(IViewModelServiceProvider serviceProvider, IModalDialog dialog)
            : base(serviceProvider)
        {
            this.dialog = dialog;
            rootGroup   = new TemplateDescriptionGroupViewModel(serviceProvider, "New project");

            // Add a default General group
            var defaultGroup = new TemplateDescriptionGroupViewModel(rootGroup, "General");

            foreach (TemplateDescription template in TemplateManager.FindTemplates(TemplateScope.Session))
            {
                var viewModel = new PackageTemplateViewModel(serviceProvider, template);
                var group     = ProcessGroup(rootGroup, template.Group) ?? defaultGroup;
                group.Templates.Add(viewModel);
            }

            recentGroup = new TemplateDescriptionGroupViewModel(serviceProvider, "Recent projects");
            var mru = EditorViewModel.Instance.MRU;

            foreach (var file in mru.MostRecentlyUsedFiles)
            {
                var viewModel = new ExistingProjectViewModel(ServiceProvider, file.FilePath);
                recentGroup.Templates.Add(viewModel);
            }

            Location = InternalSettings.TemplatesWindowDialogLastNewSessionTemplateDirectory.GetValue();
            if (string.IsNullOrWhiteSpace(Location))
            {
                Location = UPath.Combine <UDirectory>(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Xenko Projects");
            }

            BrowseForExistingProjectCommand = new AnonymousTaskCommand(serviceProvider, BrowseForExistingProject);
            SelectedGroup = rootGroup;
        }
Example #23
0
        /// <summary>
        /// Gets the filename to the specific package <paramref name="packageName"/> using the version <paramref name="versionRange"/> if not null, otherwise the <paramref name="constraintProvider"/> if specified.
        /// If no constraints are specified, the first entry if any are founds is used to get the filename.
        /// </summary>
        /// <param name="packageName">Name of the package.</param>
        /// <param name="versionRange">The version range.</param>
        /// <param name="constraintProvider">The package constraint provider.</param>
        /// <param name="allowPreleaseVersion">if set to <c>true</c> [allow prelease version].</param>
        /// <param name="allowUnlisted">if set to <c>true</c> [allow unlisted].</param>
        /// <returns>A location on the disk to the specified package or null if not found.</returns>
        /// <exception cref="System.ArgumentNullException">packageName</exception>
        public UFile GetPackageFileName(string packageName, PackageVersionRange versionRange = null, ConstraintProvider constraintProvider = null, bool allowPreleaseVersion = true, bool allowUnlisted = false)
        {
            if (packageName == null)
            {
                throw new ArgumentNullException(nameof(packageName));
            }

            var package = store.FindLocalPackage(packageName, versionRange, constraintProvider, allowPreleaseVersion, allowUnlisted);

            // If package was not found,
            if (package != null)
            {
                var packageRoot     = (UDirectory)store.GetRealPath(package);
                var packageFilename = new UFile(packageName + Package.PackageFileExtension);

                // First look for xkpkg at package root
                var packageFile = UPath.Combine(packageRoot, packageFilename);
                if (File.Exists(packageFile))
                {
                    return(packageFile);
                }

                // Then look for xkpkg inside xenko subfolder
                packageFile = UPath.Combine(UPath.Combine(packageRoot, (UDirectory)"xenko"), packageFilename);
                if (File.Exists(packageFile))
                {
                    return(packageFile);
                }
            }

            return(null);
        }
Example #24
0
        public sealed override bool Run(SessionTemplateGeneratorParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }
            parameters.Validate();

            var name            = parameters.Name;
            var outputDirectory = parameters.OutputDirectory;

            // Creates the package
            var package = NewPackage(name);

            // Setup the default namespace
            package.Meta.RootNamespace = parameters.Namespace;

            // Setup the path to save it
            package.FullPath = UPath.Combine(outputDirectory, new UFile(name + Package.PackageFileExtension));

            // Add it to the current session
            var session = parameters.Session;

            session.Packages.Add(package);

            // Load missing references
            session.LoadMissingReferences(parameters.Logger);
            return(true);
        }
Example #25
0
        protected override ResourceObject LoadFromDisk(string resourceName, string resourceVersion, DirectoryEntry directory)
        {
            // Imports the json properties into the runtime object
            var packageJson = new FileEntry(directory.FileSystem, directory.Path / "package.json");

            if (!packageJson.Exists)
            {
                Plugin.Site.Error($"The [{Name}] package doesn't contain the file `{packageJson}`");
                return(null);
            }

            var resource = new ResourceObject(this, resourceName, resourceVersion, directory);

            object result;

            Plugin.Site.Scripts.TryImportScriptFromFile(packageJson, resource, ScriptFlags.Expect, out result);
            if (result is ScriptObject)
            {
                var dynamicObject = (DynamicObject)resource;
                dynamicObject.Import(result);
                var main = dynamicObject.GetSafeValue <string>("main");
                if (main != null)
                {
                    var mainPath = UPath.Combine(resource.Path, main);
                    dynamicObject["main"] = mainPath;
                }
            }

            return(resource);
        }
        public UpdatePackageTemplateCollectionViewModel(SessionViewModel session)
            : base(session.SafeArgument(nameof(session)).ServiceProvider)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            this.session = session;

            var rootGroup = new TemplateDescriptionGroupViewModel(ServiceProvider, "All templates");

            foreach (TemplateDescription template in session.FindTemplates(TemplateScope.Package))
            {
                var viewModel = new PackageTemplateViewModel(ServiceProvider, template, session);
                rootGroup.Templates.Add(viewModel);
            }

            Location = session.SolutionPath?.GetFullDirectory() ?? InternalSettings.TemplatesWindowDialogLastNewSessionTemplateDirectory.GetValue();
            if (string.IsNullOrWhiteSpace(Location))
            {
                Location = UPath.Combine <UDirectory>(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Stride Projects");
            }

            SelectedGroup = rootGroup;
        }
Example #27
0
        // TODO: Properly untrack removed documents
        private async Task <bool> UpdateProject(TrackedAssembly trackedAssembly)
        {
            var location = trackedAssembly.LoadedAssembly.ProjectReference.Location;

            if (location.IsRelative)
            {
                location = UPath.Combine(trackedAssembly.Package.PackagePath.GetFullDirectory(), location);
            }
            var project = await OpenProject(location);

            if (project == null)
            {
                return(false);
            }

            trackedAssembly.Project = project;

            var packageDirectory = trackedAssembly.Package.PackagePath.GetFullDirectory();
            var projectDirectory = location.GetFullDirectory();

            foreach (var document in project.Documents)
            {
                // Limit ourselves to our package subfolders or project folders
                if (!packageDirectory.Contains(new UFile(document.FilePath)) &&
                    !projectDirectory.Contains(new UFile(document.FilePath)))
                {
                    continue;
                }

                directoryWatcher.Track(document.FilePath);
            }

            return(true);
        }
Example #28
0
        public override IEnumerable <ObjectUrl> GetInputFiles(AssetItem assetItem)
        {
            var modelAsset     = (ModelAsset)assetItem.Asset;
            var assetDirectory = assetItem.FullPath.GetParent();
            var assetSource    = UPath.Combine(assetDirectory, modelAsset.Source);

            yield return(new ObjectUrl(UrlType.File, assetSource));
        }
Example #29
0
        protected override Task <ResultStatus> DoCommandOverride(ICommandContext commandContext)
        {
            var compiler = GetOrCreateEffectCompiler(context);

            // Get main effect name (before the first dot)
            var isPdxfx = ShaderMixinManager.Contains(effectName);
            var source  = isPdxfx ? new ShaderMixinGeneratorSource(effectName) : (ShaderSource) new ShaderClassSource(effectName);

            int permutationCount;

            lock (PermutationCount)
            {
                PermutationCount.TryGetValue(effectName, out permutationCount);
                permutationCount++;
                PermutationCount[effectName] = permutationCount;
            }
            commandContext.Logger.Info("Trying permutation #{0} for effect [{1}]: \n{2}", permutationCount, effectName, compilerParameters.ToStringDetailed());

            var compilerResults = compiler.Compile(source, compilerParameters);

            // Copy logs and if there are errors, exit directlry
            compilerResults.CopyTo(commandContext.Logger);
            if (compilerResults.HasErrors)
            {
                return(Task.FromResult(ResultStatus.Failed));
            }

            // wait for result an check compilation status
            var completedTask = compilerResults.Bytecode.WaitForResult();

            completedTask.CompilationLog.CopyTo(commandContext.Logger);
            if (completedTask.CompilationLog.HasErrors)
            {
                return(Task.FromResult(ResultStatus.Failed));
            }

            // Register all dependencies
            var allSources = new HashSet <string>(completedTask.Bytecode.HashSources.Select(keyPair => keyPair.Key));

            foreach (var className in allSources)
            {
                commandContext.RegisterInputDependency(new ObjectUrl(UrlType.Internal, EffectCompilerBase.GetStoragePathFromShaderType(className)));
            }

            // Generate sourcecode if configured
            if (compilerParameters.ContainsKey(EffectSourceCodeKeys.Enable))
            {
                var outputDirectory     = UPath.Combine(context.Package.RootDirectory, baseUrl);
                var outputClassFile     = effectName + ".bytecode." + compilerParameters.Platform + "." + compilerParameters.Profile + ".cs";
                var fullOutputClassFile = Path.Combine(outputDirectory.ToWindowsPath(), outputClassFile);

                commandContext.Logger.Info("Writing shader bytecode to .cs source [{0}]", fullOutputClassFile);
                using (var stream = new FileStream(fullOutputClassFile, FileMode.Create, FileAccess.Write, FileShare.Write))
                    EffectByteCodeToSourceCodeWriter.Write(effectName, compilerParameters, compilerResults.Bytecode.WaitForResult().Bytecode, new StreamWriter(stream, System.Text.Encoding.UTF8));
            }

            return(Task.FromResult(ResultStatus.Successful));
        }
Example #30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PackageStore"/> class.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Unable to find a valid Xenko installation path</exception>
        private PackageStore(string installationPath = null, string defaultPackageName = "Xenko", string defaultPackageVersion = XenkoVersion.CurrentAsText)
        {
            // TODO: these are currently hardcoded to Xenko
            DefaultPackageName      = defaultPackageName;
            DefaultPackageVersion   = new PackageVersion(defaultPackageVersion);
            defaultPackageDirectory = DirectoryHelper.GetPackageDirectory(defaultPackageName);

            // 1. Try to use the specified installation path
            if (installationPath != null)
            {
                if (!DirectoryHelper.IsInstallationDirectory(installationPath))
                {
                    throw new ArgumentException("Invalid Xenko installation path [{0}]".ToFormat(installationPath), "installationPath");
                }

                globalInstallationPath = installationPath;
            }

            // 2. Try to resolve an installation path from the path of this assembly
            // We need to be able to use the package manager from an official Xenko install as well as from a developer folder
            if (globalInstallationPath == null)
            {
                globalInstallationPath = DirectoryHelper.GetInstallationDirectory(DefaultPackageName);
            }

            // If there is no root, this is an error
            if (globalInstallationPath == null)
            {
                throw new InvalidOperationException("Unable to find a valid Xenko installation or dev path");
            }

            // Preload default package
            var logger             = new LoggerResult();
            var defaultPackageFile = DirectoryHelper.GetPackageFile(defaultPackageDirectory, DefaultPackageName);

            defaultPackage = Package.Load(logger, defaultPackageFile, GetDefaultPackageLoadParameters());
            if (defaultPackage == null)
            {
                throw new InvalidOperationException("Error while loading default package from [{0}]: {1}".ToFormat(defaultPackageFile, logger.ToText()));
            }
            defaultPackage.IsSystem = true;

            // A flag variable just to know if it is a bare bone development directory
            isDev = defaultPackageDirectory != null && DirectoryHelper.IsRootDevDirectory(defaultPackageDirectory);

            // Check if we are in a root directory with store/packages facilities
            if (NugetStore.IsStoreDirectory(globalInstallationPath))
            {
                packagesDirectory = UPath.Combine(globalInstallationPath, (UDirectory)NugetStore.DefaultGamePackagesDirectory);
                store             = new NugetStore(globalInstallationPath);
            }
            else
            {
                // We should exit from here if NuGet is not configured.
                MessageBox.Show($"Unexpected installation. Cannot find a proper NuGet configuration for [{defaultPackageName}] in [{globalInstallationPath}]", "Installation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
        }