Exemple #1
0
        public static void WPFShutdown()
        {
            try
            {
                foreach (var control in WidgetControlWPF.AllInstances.ToArray())
                {
                    if (control.InnerControl != null && !control.InnerControl.Destroyed)
                    {
                        control.InnerControl.AllowCreateRenderWindow = false;
                        control.InnerControl.DestroyRenderTarget();
                    }
                }
            }
            catch { }

            EngineApp.Shutdown();
            Log.DumpToFile("Program END\r\n");
            VirtualFileSystem.Shutdown();

            ////bug fix for ".NET-BroadcastEventWindow" error
            //Application.Exit();
        }
Exemple #2
0
        public static void TestVeryLargeNumberOfEmptyCommands(Logger logger)
        {
            string appPath = VirtualFileSystem.GetAbsolutePath("/data/TestVeryLargeNumberOfEmptyCommands");
            string dbPath  = appPath + "/TestVeryLargeNumberOfEmptyCommands";

            if (Directory.Exists(dbPath))
            {
                Directory.Delete(dbPath, true);
            }

            Directory.CreateDirectory(dbPath);
            VirtualFileSystem.MountFileSystem("/data/db", dbPath);
            logger.ActivateLog(LogMessageType.Debug);
            var       builder       = new Builder("TestBuilder", appPath, Builder.Mode.Build, logger);
            var       steps         = new List <BuildStep>();
            const int StepsPerLevel = 5;
            const int MaxLevel      = 5;

            BuildStepsRecursively(builder, steps, StepsPerLevel, MaxLevel);
            int stepCount = 0;

            for (var i = 0; i < MaxLevel; ++i)
            {
                stepCount += (int)Math.Pow(StepsPerLevel, i + 1);
            }
            Debug.Assert(steps.Count == stepCount);

            logger.Info(stepCount + " steps registered.");
            logger.Info("Starting builder (logger disabled)");
            logger.ActivateLog(LogMessageType.Fatal);
            builder.Run();
            logger.ActivateLog(LogMessageType.Debug);
            logger.Info("Build finished (logger re-enabled)");

            foreach (BuildStep step in steps)
            {
                Debug.Assert(step.Status == ResultStatus.Successful);
            }
        }
Exemple #3
0
        internal static void LoadIDE(bool IsPrimary, bool IsMaster)
        {
            var xIDE = new IDE(IsPrimary, IsMaster);

            bool Clean = true;

            if (xIDE.IsValid)
            {
                switch (xIDE.Device)
                {
                case Device.IDE_ATA:
                {
                    /*
                     * First we check If it has partitions,
                     *      If parition.count > 0
                     *          Add Individual Partitions
                     */
                    var xMBR = new MBR(xIDE);
                    if (xMBR.PartInfo.Count > 0)
                    {
                        for (int i = 0; i < xMBR.PartInfo.Count; i++)
                        {
                            /*
                             * Iterate over all FileSystem Drivers and check which is valid
                             */
                            var xFileSystem = new FatFileSystem(xMBR.PartInfo[i]);
                            if (xFileSystem.IsValid)
                            {
                                VirtualFileSystem.MountDevice(null, xFileSystem);
                                Clean = false;
                            }
                        }
                    }
                }
                break;
                }
            }
        }
Exemple #4
0
        private TitleUpdateWindow(Builder builder, string titleId, string titleName, VirtualFileSystem virtualFileSystem) : base(builder.GetObject("_titleUpdateWindow").Handle)
        {
            builder.Autoconnect(this);

            _titleId                     = titleId;
            _virtualFileSystem           = virtualFileSystem;
            _updateJsonPath              = System.IO.Path.Combine(AppDataManager.GamesDirPath, _titleId, "updates.json");
            _radioButtonToPathDictionary = new Dictionary <RadioButton, string>();

            try
            {
                _titleUpdateWindowData = JsonHelper.DeserializeFromFile <TitleUpdateMetadata>(_updateJsonPath);
            }
            catch
            {
                _titleUpdateWindowData = new TitleUpdateMetadata
                {
                    Selected = "",
                    Paths    = new List <string>()
                };
            }

            _baseTitleInfoLabel.Text = $"Updates Available for {titleName} [{titleId.ToUpper()}]";

            foreach (string path in _titleUpdateWindowData.Paths)
            {
                AddUpdate(path, false);
            }

            _noUpdateRadioButton.Active = true;
            foreach (KeyValuePair <RadioButton, string> keyValuePair in _radioButtonToPathDictionary)
            {
                if (keyValuePair.Value == _titleUpdateWindowData.Selected)
                {
                    keyValuePair.Key.Active = true;
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Maps FunctionMetadata to FunctionMetadataResponse.
        /// </summary>
        /// <param name="functionMetadata">FunctionMetadata to be mapped.</param>
        /// <param name="request">Current HttpRequest</param>
        /// <param name="hostOptions">The host options</param>
        /// <returns>Promise of a FunctionMetadataResponse</returns>
        public static async Task <FunctionMetadataResponse> ToFunctionMetadataResponse(this FunctionMetadata functionMetadata, HttpRequest request, ScriptJobHostOptions hostOptions, string routePrefix)
        {
            var functionPath             = Path.Combine(hostOptions.RootScriptPath, functionMetadata.Name);
            var functionMetadataFilePath = Path.Combine(functionPath, ScriptConstants.FunctionMetadataFileName);
            var baseUrl = request != null
                ? $"{request.Scheme}://{request.Host}"
                : "https://localhost/";

            var response = new FunctionMetadataResponse
            {
                Name               = functionMetadata.Name,
                ConfigHref         = VirtualFileSystem.FilePathToVfsUri(functionMetadataFilePath, baseUrl, hostOptions),
                ScriptRootPathHref = VirtualFileSystem.FilePathToVfsUri(functionPath, baseUrl, hostOptions, isDirectory: true),
                Href               = GetFunctionHref(functionMetadata.Name, baseUrl),
                Config             = await GetFunctionConfig(functionMetadataFilePath),

                // Properties below this comment are not present in the kudu version.
                IsDirect          = functionMetadata.IsDirect,
                IsDisabled        = functionMetadata.IsDisabled,
                IsProxy           = functionMetadata.IsProxy,
                Language          = functionMetadata.Language,
                InvokeUrlTemplate = GetFunctionInvokeUrlTemplate(baseUrl, functionMetadata, routePrefix)
            };

            if (!string.IsNullOrEmpty(hostOptions.TestDataPath))
            {
                var testDataFilePath = functionMetadata.GetTestDataFilePath(hostOptions);
                response.TestDataHref = VirtualFileSystem.FilePathToVfsUri(testDataFilePath, baseUrl, hostOptions);
                response.TestData     = await GetTestData(testDataFilePath, hostOptions);
            }

            if (!string.IsNullOrEmpty(functionMetadata.ScriptFile))
            {
                response.ScriptHref = VirtualFileSystem.FilePathToVfsUri(Path.Combine(hostOptions.RootScriptPath, functionMetadata.ScriptFile), baseUrl, hostOptions);
            }

            return(response);
        }
Exemple #6
0
    public static Stream open(string name, FileMode fileMode, FileAccess fileAccess)
    {
        if (VirtualFileSystem.IsVirtualFS(name))
        {
            return(VirtualFileSystem.Open(name, fileMode, fileAccess));
        }
        else if (fileMode == FileMode.Append)
        {
#if NETFRAMEWORK
            // this is the way to get atomic append behavior for all writes
            return(new FileStream(name, fileMode, FileSystemRights.AppendData, FileShare.ReadWrite, 1, FileOptions.None));
#else
            // the above constructor does not exist in .net core
            // since the buffer size is 1 byte, it's always atomic
            // if the buffer size needs to be bigger, find a way for the atomic append
            return(new FileStream(name, fileMode, fileAccess, FileShare.ReadWrite, 1, false));
#endif
        }
        else
        {
            return(new FileStream(name, fileMode, fileAccess, FileShare.ReadWrite, 1, false));
        }
    }
Exemple #7
0
        static void Main(string[] args)
        {
            Version = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;

            Console.Title = $"Ryujinx Console {Version} (Headless SDL2)";

            AppDataManager.Initialize(null);

            _virtualFileSystem      = VirtualFileSystem.CreateInstance();
            _contentManager         = new ContentManager(_virtualFileSystem);
            _accountManager         = new AccountManager(_virtualFileSystem);
            _userChannelPersistence = new UserChannelPersistence();

            _inputManager = new InputManager(new SDL2KeyboardDriver(), new SDL2GamepadDriver());

            GraphicsConfig.EnableShaderCache = true;

            Parser.Default.ParseArguments <Options>(args)
            .WithParsed(options => Load(options))
            .WithNotParsed(errors => errors.Output());

            _inputManager.Dispose();
        }
Exemple #8
0
        public void MakeSureWeirdBugWithFoldersAndFilesWithDuplicatedNamesIsGone()
        {
            Stream            stream;
            VirtualFileSystem fileSystem = TestCollaboratorsFactory.CreateFileSystem(out stream);

            Assert.AreEqual(0, fileSystem.GetAllFoldersFrom(VirtualFileSystem.Root).Count);

            fileSystem.CreateFile(@"\hip");
            fileSystem.CreateFolder(@"\hop");
            fileSystem.CreateFile(@"\chop");
            fileSystem.CreateFolder(@"\chop");

            fileSystem = TestCollaboratorsFactory.CreateFileSystemFromExistingStream(stream);

            fileSystem.CreateFile(@"\chopper");
            fileSystem.CreateFolder(@"\chopper");

            CollectionAssert.AreEquivalent(new[] { "hip", "chop", "chopper" }, fileSystem.GetNamesOfAllFilesFrom(VirtualFileSystem.Root));

            ReadOnlyCollection <FolderInfo> foldersUnderRoot = fileSystem.GetAllFoldersFrom(VirtualFileSystem.Root);

            CollectionAssert.AreEquivalent(new[] { "hop", "chop", "chopper" }, foldersUnderRoot.Select(folder => folder.Name).ToList());
        }
Exemple #9
0
        public static (Nca patch, Nca control) GetGameUpdateDataFromPartition(VirtualFileSystem fileSystem, PartitionFileSystem pfs, string titleId, int programIndex)
        {
            Nca patchNca   = null;
            Nca controlNca = null;

            fileSystem.ImportTickets(pfs);

            foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
            {
                using var ncaFile = new UniqueRef <IFile>();

                pfs.OpenFile(ref ncaFile.Ref(), fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                Nca nca = new Nca(fileSystem.KeySet, ncaFile.Release().AsStorage());

                int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);

                if (ncaProgramIndex != programIndex)
                {
                    continue;
                }

                if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != titleId)
Exemple #10
0
        public static VirtualFileSystem CreateFileSystemFromExistingStream(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            VirtualDisk disk = VirtualDisk.CreateFromStream(stream);

            var diskStructuresManager = new FileSystemNodeStorage(disk);

            FileSystemHeader header = diskStructuresManager.ReadFileSystemHeader(VirtualDiskFormatter.FileSystemHeaderBlockIndex);

            var nameValidator = FileSystemArtifactNamesValidator.Default;

            var pathValidator = PathValidator.Default;

            var pathBuilder = PathBuilder.Default;

            var nodeResolver = new NodeResolver(disk, diskStructuresManager, StringComparer.OrdinalIgnoreCase, header.RootBlockOffset, VirtualFileSystem.Root, VirtualFileSystem.DirectorySeparatorChar, pathValidator, pathBuilder);

            return(VirtualFileSystem.CreateFromDisk(disk, StringComparer.OrdinalIgnoreCase, nodeResolver, pathBuilder, nameValidator, pathValidator));
        }
Exemple #11
0
        public void CreateAHundredFilesUnderOneFolder()
        {
            VirtualFileSystem fileSystem = VirtualFileSystemFactory.CreateDefaultFileSystem();

            var namesOfFiles = new List <string>();

            ReadOnlyCollection <FileInfo> rootFolderFiles = fileSystem.GetAllFilesFrom(@"\");

            Assert.AreEqual(0, rootFolderFiles.Count);

            for (int i = 0; i < 100; i++)
            {
                string fileName = Guid.NewGuid().ToString("N");

                namesOfFiles.Add(fileName);

                fileSystem.CreateFile(@"\" + fileName);
            }

            var namesOfFilesUnderRoot = fileSystem.GetNamesOfAllFilesFrom(VirtualFileSystem.Root);

            CollectionAssert.AreEquivalent(namesOfFiles, namesOfFilesUnderRoot);
        }
Exemple #12
0
        public static void Save()
        {
            if (!ToolsLocalization.IsInitialized)
            {
                return;
            }
            string    realPathByVirtual = VirtualFileSystem.GetRealPathByVirtual(ToolsLocalization.EL);
            TextBlock textBlock         = new TextBlock();
            TextBlock textBlock2        = textBlock.AddChild("groups");

            foreach (ToolsLocalization.GroupItem current in ToolsLocalization.EM.Values)
            {
                TextBlock textBlock3 = textBlock2.AddChild("group", current.eM);
                foreach (KeyValuePair <string, string> current2 in current.em)
                {
                    textBlock3.SetAttribute(current2.Key, current2.Value);
                }
            }
            using (StreamWriter streamWriter = new StreamWriter(realPathByVirtual))
            {
                streamWriter.Write(textBlock.DumpToString());
            }
        }
Exemple #13
0
        /// <summary>
        /// Write the generated objects into the index map file.
        /// </summary>
        /// <param name="mergeWithCurrentIndexFile">Indicate if old values must be deleted or merged</param>
        public void WriteIndexFile(bool mergeWithCurrentIndexFile)
        {
            if (!mergeWithCurrentIndexFile)
            {
                VirtualFileSystem.FileDelete(IndexFileFullPath);
            }

            using (var indexFile = ContentIndexMap.NewTool(indexName))
            {
                // Filter database Location
                indexFile.AddValues(
                    Root.OutputObjects.Where(x => x.Key.Type == UrlType.Content)
                    .Select(x => new KeyValuePair <string, ObjectId>(x.Key.Path, x.Value.ObjectId)));

                foreach (var outputObject in Root.OutputObjects.Where(x => x.Key.Type == UrlType.Content).Select(x => x.Value))
                {
                    if (outputObject.Tags.Contains(DoNotCompressTag))
                    {
                        DisableCompressionIds.Add(outputObject.ObjectId);
                    }
                }
            }
        }
Exemple #14
0
        public UserProfileWindow(AccountManager accountManager, ContentManager contentManager,
                                 VirtualFileSystem virtualFileSystem)
        {
            AccountManager = accountManager;
            ContentManager = contentManager;
            ViewModel      = new UserProfileViewModel(this);

            DataContext = ViewModel;

            InitializeComponent();
#if DEBUG
            this.AttachDevTools();
#endif
            if (contentManager.GetCurrentFirmwareVersion() != null)
            {
                Task.Run(() =>
                {
                    AvatarProfileViewModel.PreloadAvatars(contentManager, virtualFileSystem);
                });
            }

            Title = $"Ryujinx {Program.Version} - " + LocaleManager.Instance["UserProfileWindowTitle"];
        }
Exemple #15
0
        private void OnResourceBeginEditMode(EventArgs eventArgs)
        {
            if (this.currentResourceObjectEditor == null)
            {
                string realPathByVirtual = VirtualFileSystem.GetRealPathByVirtual(this.currentResourcePath);
                Shell32Api.ShellExecuteEx(null, realPathByVirtual);
                return;
            }
            if (!this.currentResourceObjectEditor.AllowEditMode)
            {
                string realPathByVirtual2 = VirtualFileSystem.GetRealPathByVirtual(this.currentResourcePath);
                Shell32Api.ShellExecuteEx(null, realPathByVirtual2);
                return;
            }
            if (VirtualFile.IsInArchive(this.currentResourceObjectEditor.FileName))
            {
                Log.Warning(ToolsLocalization.Translate("Various", "This file is inside an archive. Unable to edit it."));
                return;
            }
            this.currentResourceObjectEditor.BeginEditMode();

            Log.Info("MainForm.Instance.EngineAppControl.Focus();");
        }
Exemple #16
0
        public ContentManager(VirtualFileSystem virtualFileSystem)
        {
            _contentDictionary = new SortedDictionary <(ulong, NcaContentType), string>();
            _locationEntries   = new Dictionary <StorageId, LinkedList <LocationEntry> >();

            _sharedFontTitleDictionary = new Dictionary <string, long>
            {
                { "FontStandard", 0x0100000000000811 },
                { "FontChineseSimplified", 0x0100000000000814 },
                { "FontExtendedChineseSimplified", 0x0100000000000814 },
                { "FontKorean", 0x0100000000000812 },
                { "FontChineseTraditional", 0x0100000000000813 },
                { "FontNintendoExtended", 0x0100000000000810 }
            };

            _systemTitlesNameDictionary = new Dictionary <long, string>()
            {
                { 0x010000000000080E, "TimeZoneBinary" },
                { 0x0100000000000810, "FontNintendoExtension" },
                { 0x0100000000000811, "FontStandard" },
                { 0x0100000000000812, "FontKorean" },
                { 0x0100000000000813, "FontChineseTraditional" },
                { 0x0100000000000814, "FontChineseSimple" },
            };

            _sharedFontFilenameDictionary = new Dictionary <string, string>
            {
                { "FontStandard", "nintendo_udsg-r_std_003.bfttf" },
                { "FontChineseSimplified", "nintendo_udsg-r_org_zh-cn_003.bfttf" },
                { "FontExtendedChineseSimplified", "nintendo_udsg-r_ext_zh-cn_003.bfttf" },
                { "FontKorean", "nintendo_udsg-r_ko_003.bfttf" },
                { "FontChineseTraditional", "nintendo_udjxh-db_zh-tw_003.bfttf" },
                { "FontNintendoExtended", "nintendo_ext_003.bfttf" }
            };

            _virtualFileSystem = virtualFileSystem;
        }
Exemple #17
0
        static void Main2()
        {
            if (!VirtualFileSystem.Init("user:Logs/Game.log", true, null, null, null))
            {
                return;
            }
            Log.DumpToFile(string.Format("Game {0}\r\n", EngineVersionInformation.Version));

            EngineApp.ConfigName = "user:Configs/Game.config";
            EngineApp.UseSystemMouseDeviceForRelativeMode = true;
            EngineApp.AllowJoysticksAndCustomInputDevices = true;
            EngineApp.AllowWriteEngineConfigFile          = true;
            EngineApp.AllowChangeVideoMode = true;

            EngineApp.Init(new GameEngineApp());
            EngineApp.Instance.WindowTitle = "Game";

            if (PlatformInfo.Platform == PlatformInfo.Platforms.Windows)
            {
                EngineApp.Instance.Icon = Game.Properties.Resources.Logo;
            }

            EngineConsole.Init();

            EngineApp.Instance.Config.RegisterClassParameters(typeof(GameEngineApp));

            if (EngineApp.Instance.Create())
            {
                EngineApp.Instance.Run();
            }

            EngineApp.Shutdown();

            Log.DumpToFile("Program END\r\n");

            VirtualFileSystem.Shutdown();
        }
Exemple #18
0
        public Stream OpenStream(ObjectId objectId, VirtualFileMode mode = VirtualFileMode.Open, VirtualFileAccess access = VirtualFileAccess.Read, VirtualFileShare share = VirtualFileShare.Read)
        {
            ObjectLocation objectLocation;

            lock (objects)
            {
                if (!objects.TryGetValue(objectId, out objectLocation))
                {
                    throw new FileNotFoundException();
                }
            }

            Stream stream;

            // Try to reuse same streams
            lock (bundleStreams)
            {
                // Available stream?
                if (bundleStreams.TryGetValue(objectLocation.BundleUrl, out stream))
                {
                    // Remove from available streams
                    bundleStreams.Remove(objectLocation.BundleUrl);
                }
                else
                {
                    stream = VirtualFileSystem.OpenStream(objectLocation.BundleUrl, VirtualFileMode.Open, VirtualFileAccess.Read);
                }
            }

            if (objectLocation.Info.IsCompressed)
            {
                stream.Position = objectLocation.Info.StartOffset;
                return(new PackageFileStreamLZ4(this, objectLocation.BundleUrl, stream, CompressionMode.Decompress, objectLocation.Info.SizeNotCompressed, objectLocation.Info.EndOffset - objectLocation.Info.StartOffset));
            }

            return(new PackageFileStream(this, objectLocation.BundleUrl, stream, objectLocation.Info.StartOffset, objectLocation.Info.EndOffset, false));
        }
Exemple #19
0
            public ObjectId ComputeInputHash(UrlType type, string filePath)
            {
                var hash = ObjectId.Empty;

                switch (type)
                {
                case UrlType.File:
                    hash = builderContext.InputHashes.ComputeFileHash(filePath);
                    break;

                case UrlType.ContentLink:
                case UrlType.Content:
                    if (!buildTransaction.TryGetValue(filePath, out hash))
                    {
                        Logger.Warning("Location " + filePath + " does not exist currently and is required to compute the current command hash. The build cache will not work for this command!");
                    }
                    break;

                case UrlType.Virtual:
                    var providerResult = VirtualFileSystem.ResolveProvider(filePath, true);
                    var dbProvider     = providerResult.Provider as DatabaseFileProvider;
                    var microProvider  = providerResult.Provider as MicroThreadFileProvider;
                    if (microProvider != null)
                    {
                        dbProvider = microProvider.ThreadLocal.Value as DatabaseFileProvider;
                    }

                    if (dbProvider != null)
                    {
                        dbProvider.ContentIndexMap.TryGetValue(providerResult.Path, out hash);
                    }
                    break;
                }

                return(hash);
            }
Exemple #20
0
        public void MakeSureMovingUnlistsFolderFromOldParentAndEnlistsItInNewOnePreservingChildren()
        {
            Stream            stream;
            VirtualFileSystem fileSystem = TestCollaboratorsFactory.CreateFileSystem(out stream);

            var folderA = fileSystem.CreateFolder(@"\A");
            var folderB = fileSystem.CreateFolder(@"\A\B");
            var folderC = fileSystem.CreateFolder(@"\A\B\C");
            var fileA   = fileSystem.CreateFile(fileSystem.PathBuilder.CombinePaths(folderB.FullPath, "AUnderB.txt"));
            var fileB   = fileSystem.CreateFile(fileSystem.PathBuilder.CombinePaths(folderB.FullPath, "BUnderB.txt"));
            var fileC   = fileSystem.CreateFile(fileSystem.PathBuilder.CombinePaths(folderC.FullPath, "C1.txt"));
            var fileD   = fileSystem.CreateFile(fileSystem.PathBuilder.CombinePaths(folderC.FullPath, "C2.txt"));

            var folderBMoved = fileSystem.MoveFolder(folderB.FullPath, VirtualFileSystem.Root);

            Assert.AreEqual(@"\B", folderBMoved.FullPath);

            CollectionAssert.AreEquivalent(new List <string>(), fileSystem.GetNamesOfAllFilesFrom(folderA.FullPath));
            CollectionAssert.AreEquivalent(new List <string>(), fileSystem.GetNamesOfAllFoldersFrom(folderA.FullPath));
            CollectionAssert.AreEquivalent(new[] { folderA.Name, folderB.Name }, fileSystem.GetNamesOfAllFoldersFrom(VirtualFileSystem.Root));
            CollectionAssert.AreEquivalent(new[] { fileA.Name, fileB.Name }, fileSystem.GetNamesOfAllFilesFrom(folderBMoved.FullPath));
            CollectionAssert.AreEquivalent(new[] { folderC.Name }, fileSystem.GetNamesOfAllFoldersFrom(folderBMoved.FullPath));
            CollectionAssert.AreEquivalent(new[] { fileC.Name, fileD.Name }, fileSystem.GetNamesOfAllFilesFrom(@"\B\c"));
        }
        public void TryWritingABigFileReadingItAfterSystemReload()
        {
            var testCollaborators = TestCollaboratorsFactory.CreateAllCollaborators(50000, false);

            byte[] interestingBytes = ByteBufferFactory.BuildSomeGuidsIntoByteArray(5000);

            int streamLength;

            const int numberOfGuidPortionsToReadAndWrite = 500;

            using (DataStreamReadableWritable stream = testCollaborators.VirtualFileSystem.CreateAndOpenFileForWriting(@"\hey"))
            {
                for (int i = 0; i < numberOfGuidPortionsToReadAndWrite; i++)
                {
                    stream.Write(interestingBytes, 0, interestingBytes.Length);
                }

                streamLength = stream.Length;
            }

            VirtualFileSystem fileSystemReloaded =
                TestCollaboratorsFactory.CreateFileSystemFromExistingStream(testCollaborators.Stream);

            using (DataStreamReadable stream = fileSystemReloaded.OpenFileForReading(@"\hey"))
            {
                Assert.AreEqual(streamLength, stream.Length);

                var bytesRead = new byte[interestingBytes.Length];

                for (int i = 0; i < numberOfGuidPortionsToReadAndWrite; i++)
                {
                    int numberOfBytesRead = stream.Read(bytesRead, 0, interestingBytes.Length);
                    CollectionAssert.AreEqual(interestingBytes, bytesRead);
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// </summary>
        public static void PollAutoUpdate()
        {
#if SHIPPING
            if (InternalUpdateDownload != null)
            {
                ManifestDownloadState Downloader = Program.ManifestDownloadManager.GetDownload(InternalUpdateDownload.ActiveManifestId);
                if (Downloader != null && Downloader.State == ManifestDownloadProgressState.Complete && Downloader.Manifest != null)
                {
                    int VersionNumber = StringUtils.ConvertSemanticVerisonNumber(VirtualFileSystem.GetNodeName(Downloader.Manifest.VirtualPath));

                    if (AppVersion.VersionNumber < VersionNumber)
                    {
                        //Logger.Log(LogLevel.Info, LogCategory.Main, "Installing new update: {0}", Downloader.Manifest.VirtualPath);
                        AutoUpdateAvailable = true;
                        //InstallAutoUpdate();
                    }
                }
                else
                {
                    AutoUpdateAvailable = false;
                }
            }
#endif
        }
Exemple #23
0
        public void Setup()
        {
            TestRoot = Path.Combine(GetFolderPath(SpecialFolder.MyDocuments), "Personal Cloud");
            Directory.CreateDirectory(TestRoot);
            TestRoot = Path.Combine(TestRoot, "Test Container");
            if (Directory.Exists(TestRoot))
            {
                Assert.Inconclusive("Previous test session may have failed. Please ensure \""
                                    + Path.GetDirectoryName(TestRoot)
                                    + "\" is empty before starting a new session.");
                return;
            }

            Directory.CreateDirectory(TestRoot);

            var logsDir = Path.Combine(TestRoot, "Logs");

            Directory.CreateDirectory(logsDir);

            Loggers = LoggerFactory.Create(builder => builder.//SetMinimumLevel(LogLevel.Trace).
                                           AddConsole(x => {
                x.TimestampFormat = "G";
            }));


            var dic = new Dictionary <string, IFileSystem>();

            dic["Files"] = new VirtualFileSystem(TestRoot);

            var RootFs = new FileSystemContainer(dic, Loggers.CreateLogger("FileContainerWebApiTest"));

            Server = new HttpProvider(10240, RootFs);
            Server.Start();

            Client = new TopFolderClient($"http://localhost:10240", new byte[32], "");
        }
Exemple #24
0
        public void TestUseBuildCacheOutput()
        {
            Utils.CleanContext();
            Utils.GenerateSourceFile("input1", "{32E4EDF4-E8AA-4D13-B111-9BD8AA2A8B07}");

            var builder1 = Utils.CreateBuilder();

            builder1.Root.Add(new InputOutputCommand {
                Delay = 100, Source = new ObjectUrl(UrlType.File, Utils.GetSourcePath("input1")), OutputUrl = "/db/url1"
            });
            builder1.Run(Builder.Mode.Build);

            VirtualFileSystem.FileDelete("/data/db/index");

            var builder2          = Utils.CreateBuilder();
            CommandBuildStep step = builder2.Root.Add(new InputOutputCommand {
                Delay = 100, Source = new ObjectUrl(UrlType.File, Utils.GetSourcePath("input1")), OutputUrl = "/db/url1"
            });

            builder2.Run(Builder.Mode.Build);
            builder2.WriteIndexFile(false);

            Assert.That(step.Status, Is.EqualTo(ResultStatus.NotTriggeredWasSuccessful));
            Assert.IsTrue(step.Result.OutputObjects.Keys.Contains(new ObjectUrl(UrlType.Internal, "/db/url1")));

            var indexMap = AssetIndexMap.Load();

            indexMap.UseTransaction = true;
            indexMap.LoadNewValues();

            ObjectId outputId;
            bool     objectIdFound = indexMap.TryGetValue("/db/url1", out outputId);

            Assert.IsTrue(objectIdFound);
            Assert.That(step.Result.OutputObjects[new ObjectUrl(UrlType.Internal, "/db/url1")], Is.EqualTo(outputId));
        }
Exemple #25
0
        private static unsafe int sys_open(sbyte *file, int flags, int mode)
        {
            var filename = new string(file);
            var stream   = VirtualFileSystem.GetFile(filename);

            Debug.Write("fopen: %s\n", filename);
            Heap.Free(filename);

            if (stream == null)
            {
                return(-1);
            }

            var Process = Scheduler.RunningProcess;
            var files   = Process.Files;
            int count   = files.Count;

            int fd = -1;

            for (int index = 0; index < count; index++)
            {
                if (files[index] == null)
                {
                    files[index] = stream;
                    fd           = index;
                }
            }

            if (fd == -1)
            {
                files.Add(stream);
                fd = count;
            }

            return(fd);
        }
Exemple #26
0
        public void MakeSureDeletingFilesAndFoldersFreesExactlyTheSpaceTheyOccupied()
        {
            VirtualFileSystem fileSystem = VirtualFileSystemFactory.CreateDefaultFileSystem();

            fileSystem.CreateFolder(@"\folder");

            int amountOfFreeSpaceBeforeStuffHasBeenCreated = fileSystem.FreeSpaceInBytes;

            var folderInfo = fileSystem.CreateFolder(@"\folder23");

            var fileInfo = fileSystem.CreateFile(@"\folder\testFile.txt");

            using (var stream = fileSystem.OpenFileForWriting(fileInfo.FullPath))
            {
                stream.SetLength((fileSystem.FreeSpaceInBytes / 4) * 3);
            }

            Assert.IsTrue(fileSystem.FreeSpaceInBytes < amountOfFreeSpaceBeforeStuffHasBeenCreated);

            fileSystem.DeleteFile(fileInfo.FullPath);
            fileSystem.DeleteFolder(folderInfo.FullPath);

            Assert.AreEqual(amountOfFreeSpaceBeforeStuffHasBeenCreated, fileSystem.FreeSpaceInBytes);
        }
Exemple #27
0
        public ImportingAddressableObjectVisitor(
            VirtualFileSystem targetFileSystem,
            string sourceFolderPath,
            string destinationFolder,
            IFileContentsBufferFactory fileContentsBufferFactory,
            IFileSystemCancellableTaskToken taskToken,
            int totalNumberOfFilesToVisit)
        {
            if (targetFileSystem == null)
            {
                throw new ArgumentNullException("targetFileSystem");
            }
            if (sourceFolderPath == null)
            {
                throw new ArgumentNullException("sourceFolderPath");
            }
            if (destinationFolder == null)
            {
                throw new ArgumentNullException("destinationFolder");
            }
            if (fileContentsBufferFactory == null)
            {
                throw new ArgumentNullException("fileContentsBufferFactory");
            }
            if (taskToken == null)
            {
                throw new ArgumentNullException("taskToken");
            }

            _targetFileSystem          = targetFileSystem;
            _sourceFolderPath          = sourceFolderPath;
            _destinationFolder         = destinationFolder;
            _fileContentsBufferFactory = fileContentsBufferFactory;
            _taskToken = taskToken;
            _totalNumberOfFilesToVisit = totalNumberOfFilesToVisit;
        }
        public void MakeSureEnumeratorDoesGiveOutAllFilesWhenSetAccordinglyDataSuite1()
        {
            VirtualFileSystem fileSystem = VirtualFileSystemFactory.CreateDefaultFileSystem();

            fileSystem.CreateFolder(@"\folder1");
            fileSystem.CreateFolder(@"\folder22");

            fileSystem.CreateFolder(@"\folder22\subfolder1");

            fileSystem.CreateFile(@"\folder22\file1");
            fileSystem.CreateFile(@"\folder22\file2");

            fileSystem.CreateFile(@"\folder1\file1");

            IEnumerator <FileInfo> fileEnumerator = fileSystem.EnumerateFilesUnderFolder(VirtualFileSystem.Root, "*");

            var allFiles = new List <string>();

            while (fileEnumerator.MoveNext())
            {
                allFiles.Add(fileEnumerator.Current.FullPath);
            }

            CollectionAssert.AreEquivalent(new[] { @"\folder22\file1", @"\folder22\file2", @"\folder1\file1" }, allFiles);

            allFiles.Clear();

            fileEnumerator = fileSystem.EnumerateFilesUnderFolder(@"\folder22", "file?");

            while (fileEnumerator.MoveNext())
            {
                allFiles.Add(fileEnumerator.Current.FullPath);
            }

            CollectionAssert.AreEquivalent(new[] { @"\folder22\file1", @"\folder22\file2" }, allFiles);
        }
        public DataStreamTestCollaboratorSet(IVirtualDisk disk, IFileSystemNodeStorage fileSystemNodeStorage, FileInfo fileInfo, VirtualFileSystem virtualFileSystem)
        {
            if (disk == null)
            {
                throw new ArgumentNullException("disk");
            }
            if (fileSystemNodeStorage == null)
            {
                throw new ArgumentNullException("fileSystemNodeStorage");
            }
            if (fileInfo == null)
            {
                throw new ArgumentNullException("fileInfo");
            }
            if (virtualFileSystem == null)
            {
                throw new ArgumentNullException("virtualFileSystem");
            }

            Disk = disk;
            FileSystemNodeStorage = fileSystemNodeStorage;
            FileInfo          = fileInfo;
            VirtualFileSystem = virtualFileSystem;
        }
Exemple #30
0
        public void DeleteBundles(Func <string, bool> bundleFileDeletePredicate)
        {
            var bundleFiles = VirtualFileSystem.ListFiles(vfsBundleDirectory, "*.bundle", VirtualSearchOption.TopDirectoryOnly).Result;

            // Obsolete: Android used to have .bundle.mp3 to avoid compression. Still here so that they get deleted on next build.
            // This can be removed later.
            bundleFiles = bundleFiles.Union(VirtualFileSystem.ListFiles(vfsBundleDirectory, "*.mp3", VirtualSearchOption.TopDirectoryOnly).Result).ToArray();

            foreach (var bundleFile in bundleFiles)
            {
                var bundleRealFile = VirtualFileSystem.GetAbsolutePath(bundleFile);

                // Remove ".mp3" (Android only)
                if (bundleRealFile.EndsWith(".mp3", StringComparison.CurrentCultureIgnoreCase))
                {
                    bundleRealFile = bundleRealFile.Substring(0, bundleRealFile.Length - 4);
                }

                if (bundleFileDeletePredicate(bundleRealFile))
                {
                    NativeFile.FileDelete(bundleRealFile);
                }
            }
        }
Exemple #31
0
 /**
  * Sets the VirtualFileSystem used by this Preprocessor.
  */
 public void setFileSystem(VirtualFileSystem filesystem)
 {
     this.filesystem = filesystem;
 }
 public void SetAttributes(string name, VirtualFileSystem.FileAttributes attributes)
 {
     System.IO.FileAttributes attrs = 0;
     if (attributes.HasFlag(VirtualFileSystem.FileAttributes.Normal)) attrs |= System.IO.FileAttributes.Normal;
     if (attributes.HasFlag(VirtualFileSystem.FileAttributes.ReadOnly)) attrs |= System.IO.FileAttributes.ReadOnly;
     if (attributes.HasFlag(VirtualFileSystem.FileAttributes.Hidden)) attrs |= System.IO.FileAttributes.Hidden;
     if (attributes.HasFlag(VirtualFileSystem.FileAttributes.Directory)) attrs |= System.IO.FileAttributes.Directory;
     if (attributes.HasFlag(VirtualFileSystem.FileAttributes.Archive)) attrs |= System.IO.FileAttributes.Archive;
     File.SetAttributes(name, attrs);
 }
Exemple #33
0
        public Preprocessor()
        {
            this.inputs = new List<Source>();

            this.macros = new Dictionary<String,Macro>();
            macros.Add(__LINE__.getName(), __LINE__);
            macros.Add(__FILE__.getName(), __FILE__);
            macros.Add(__COUNTER__.getName(), __COUNTER__);
            this.states = new Stack<State>();
            states.Push(new State());
            this.source = null;

            this.counter = 0;

            this.quoteincludepath = new List<String>();
            this.sysincludepath = new List<String>();
            this.frameworkspath = new List<String>();
            this.features = Feature.NONE;
            this.warnings = Warning.NONE;
            this.filesystem = new JavaFileSystem();
            this.listener = null;
        }
Exemple #34
0
		private static IUnityAnalyticsSession GetSingleton()
		{
			if (s_Implementation == null) {
				Logger.loggerInstance = new UnityLogger();
				IPlatformWrapper platformWrapper = PlatformWrapper.platform;
				#if NETFX_CORE
				IFileSystem fileSystem = new WindowsFileSystem();
				#elif UNITY_WEBPLAYER || UNITY_WEBGL
				IFileSystem fileSystem = new VirtualFileSystem();
				#else
				IFileSystem fileSystem = new FileSystem();
				#endif
				ICoroutineManager coroutineManager = new UnityCoroutineManager();
				s_Implementation = new SessionImpl(platformWrapper, coroutineManager, fileSystem);
				GameObserver.CreateComponent(platformWrapper, s_Implementation);
			}
			return s_Implementation;
		}
Exemple #35
0
 public static bool Create(string extension, out VirtualFileSystem fileSystem)
 {
     return SupportedFileSystems.TryGetValue(
         extension.Replace(".", "").ToUpper(),
         out fileSystem);
 }