Ejemplo n.º 1
0
        private LayoutFile AddLayout(string name)
        {
            var dataPath   = Path.Combine(this._BasePath, name);
            var layoutPath = Path.Combine(dataPath, "layout.toc");

            if (File.Exists(layoutPath) == false)
            {
                Logger.Debug("Could not load superbundle layout for '{0}'.", name);
                return(null);
            }

            var layout = LayoutFile.Read(layoutPath);

            // superbundles listed in the layout, but not associated with any install chunk?

            /*
             * var badSuperbundles = layout.Superbundles
             *                          .Select(sbi => sbi.Name)
             *                          .Except(layout.InstallManifest.InstallChunks
             *                                        .Where(ic => ic.Superbundles != null)
             *                                        .SelectMany(ic => ic.Superbundles))
             *                          .ToArray();
             */

            var index = this._Sources.FindLastIndex(s => s.Layout.Head > layout.Head);

            this._Sources.Insert(index < 0 ? 0 : (index + 1), new DataSource(layout, dataPath));
            return(layout);
        }
 public DynamicRenderDocument(DocumentFile document, LayoutFile layout, Site site)
     : base(document.SourceRelativePath)
 {
     _document = document;
     _layout = layout;
     _site = site;
 }
Ejemplo n.º 3
0
 public DynamicLayoutFile(DocumentFile activeDocument, LayoutFile layout, Site site)
     : base(layout.SourceRelativePath)
 {
     this.ActiveDocument = activeDocument;
     this.Layout = layout;
     this.Site = site;
 }
Ejemplo n.º 4
0
        protected void RenderIndex(LayoutFile layout, IEnumerable <Document> posts, string basePath)
        {
            int skip = 0;
            IEnumerable <Document> page;

            while ((page = posts.Skip(skip).Take(PageSize)).Any())
            {
                var outputPath = Path.Combine(basePath, skip == 0 ? "index.html" : string.Format("index{0}.html", skip));
                Render(layout, page, outputPath);
                skip += PageSize;
            }
        }
Ejemplo n.º 5
0
        public DataSource(LayoutFile layout, string path)
        {
            if (layout == null)
            {
                throw new ArgumentNullException("layout");
            }

            if (string.IsNullOrEmpty(path) == true)
            {
                throw new ArgumentNullException("path");
            }

            this.Layout = layout;
            this.Path   = path;
        }
Ejemplo n.º 6
0
        public string StartExport(string layoutName, LayoutFile layout, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets, bool exportUnsupportedTags)
        {
            //https://anno1800.fandom.com/wiki/Template:Production_layout
            //https://anno1800.fandom.com/wiki/Template:Production_layout/doc
            //https://anno1800.fandom.com/wiki/Category:Template_documentation

            //https://anno1800.fandom.com/wiki/Testing_page

            //TODO warn user when layout contains more than 15 building types because template only supports 1-15
            //template only supports 1-8 for "Production x Type" and "Production x per minute"
            //TODO warn user (or exit) when layout contains buildings other than Anno 1800

            var calculatedStatistics = _statisticsCalculationHelper.CalculateStatistics(layout.Objects);

            var exportString = new StringBuilder(900);//best guess on minimal layout

            exportString.Append(TEMPLATE_START)
            .AppendLine(HEADER_PRODUCTION_LAYOUT)
            .Append(TEMPLATE_LINE_START).Append(HEADER_ICON).AppendLine(TEMPLATE_ENTRY_DELIMITER)
            .Append(TEMPLATE_LINE_START).Append(HEADER_LAYOUT_NAME).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(layoutName)
            .Append(TEMPLATE_LINE_START).Append(HEADER_LAYOUT_IMAGE).AppendLine(TEMPLATE_ENTRY_DELIMITER);

            //add buildings
            exportString = addBuildingInfo(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets);

            exportString.Append(TEMPLATE_LINE_START).Append(HEADER_LAYOUT_DESCRIPTION).AppendLine(TEMPLATE_ENTRY_DELIMITER)
            .Append(TEMPLATE_LINE_START).Append(HEADER_SIZE).Append(TEMPLATE_ENTRY_DELIMITER).Append(calculatedStatistics.UsedAreaWidth.ToString()).Append(TEMPLATE_SIZE_ENTRY_DELIMITER).AppendLine(calculatedStatistics.UsedAreaHeight.ToString())
            .Append(TEMPLATE_LINE_START).Append(HEADER_TILES).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(calculatedStatistics.UsedTiles.ToString())
            .Append(TEMPLATE_LINE_START).Append(HEADER_AUTHOR).AppendLine(TEMPLATE_ENTRY_DELIMITER)
            .Append(TEMPLATE_LINE_START).Append(HEADER_SOURCE).AppendLine(TEMPLATE_ENTRY_DELIMITER);

            exportString = addProductionInfo(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets);
            exportString = addConstructionInfo(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets);
            exportString = addBalance(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets);
            exportString = addWorkforceInfo(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets);
            exportString = addInfluence(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets);
            exportString = addAttractiveness(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets);

            if (exportUnsupportedTags)
            {
                exportString = addUnsupportedEntries(exportString);
            }

            exportString.Append(TEMPLATE_END);

            return(exportString.ToString());
        }
Ejemplo n.º 7
0
        private void AddUpdates(LayoutFile layout, string name)
        {
            var updatesPath = Path.Combine(this._BasePath, name);

            foreach (var updatePath in Directory.GetDirectories(updatesPath))
            {
                var manifestPath = Path.Combine(updatePath, "package.mft");
                if (File.Exists(manifestPath) == false)
                {
                    continue;
                }

                var dataPath = Path.Combine(updatePath, "Data");
                var index    = this._Sources.FindLastIndex(s => s.Layout.Head > layout.Head);
                this._Sources.Insert(index < 0 ? 0 : (index + 1), new DataSource(layout, dataPath));
            }
        }
Ejemplo n.º 8
0
        private static List <Layout.InstallChunk> GetSuperbundleInstallChunks(LayoutFile layout, string name)
        {
            var rootChunk = layout.InstallManifest.InstallChunks.FirstOrDefault(
                ici => ici.Superbundles.Select(n => n.ToLowerInvariant()).Contains(name) == true);

            if (rootChunk == null)
            {
                return(null);
            }

            var chunks = new Dictionary <Guid, Layout.InstallChunk>();

            chunks.Add(rootChunk.Id, rootChunk);

            var queue = new Queue <Guid>();

            foreach (var id in rootChunk.RequiredChunks)
            {
                queue.Enqueue(id);
            }

            while (queue.Count > 0)
            {
                var id = queue.Dequeue();

                if (chunks.ContainsKey(id) == true)
                {
                    continue;
                }

                var chunk = layout.InstallManifest.InstallChunks.SingleOrDefault(ici => ici.Id == id);
                if (chunk == default(Layout.InstallChunk))
                {
                    throw new InvalidOperationException();
                }

                chunks.Add(id, chunk);

                foreach (var childId in chunk.RequiredChunks)
                {
                    queue.Enqueue(childId);
                }
            }

            return(chunks.Values.ToList());
        }
Ejemplo n.º 9
0
        public ChunkLookup(LayoutFile layout, string dataPath)
        {
            if (layout == null)
            {
                throw new ArgumentNullException("layout");
            }

            if (dataPath == null)
            {
                throw new ArgumentNullException("dataPath");
            }

            this._Lock             = new object();
            this._Layout           = layout;
            this._DataPath         = dataPath;
            this._Superbundles     = new Dictionary <string, SuperbundleFile>();
            this._TableOfContents  = new Dictionary <string, TableOfContentsFile>();
            this._InstallChunkInfo = new Dictionary <Guid, InstallChunkInfo>();
            this._ChunkInfo        = new Dictionary <string, List <ChunkVariantInfo> >();
        }
Ejemplo n.º 10
0
        public void SaveFile_LayoutVersionChangedByUser_ShouldUseLayoutVersion()
        {
            // Arrange
            LayoutFile layoutFileUsedToSave = null;
            var        versionToSave        = new Version(42, 42, 42, 42);

            var mockedLayoutLoader = new Mock <ILayoutLoader>();

            _ = mockedLayoutLoader.Setup(x => x.SaveLayout(It.IsAny <LayoutFile>(), It.IsAny <string>()))
                .Callback <LayoutFile, string>((layout, filePath) => layoutFileUsedToSave = layout);

            var viewModel = GetViewModel(layoutLoaderToUse: mockedLayoutLoader.Object);

            viewModel.LayoutSettingsViewModel.LayoutVersion = versionToSave;

            // Act
            viewModel.SaveFile("dummy");

            // Assert
            mockedLayoutLoader.Verify(x => x.SaveLayout(It.IsAny <LayoutFile>(), It.IsAny <string>()), Times.Once());
            Assert.Equal(versionToSave, layoutFileUsedToSave.LayoutVersion);
        }
Ejemplo n.º 11
0
        private string RenderContentForExtension(string path, string content, string extension, DocumentFile document, string documentContent, LayoutFile layout)
        {
            var data = new CaseInsensitiveExpando();

            data["Site"]     = this.Site.GetAsDynamic();
            data["Document"] = document.GetAsDynamic(documentContent);
            data["Layout"]   = layout == null ? null : layout.GetAsDynamic();
            data["Books"]    = this.Site.Books == null ? null : this.Site.Books.Select(b => b.GetAsDynamic(document)).ToList();

            var engine = this.Engines[extension];

            return(engine.Render(path, content, data));
        }
Ejemplo n.º 12
0
        public static void Main(string[] args)
        {
            bool verbose  = false;
            bool showHelp = false;

            var options = new OptionSet()
            {
                { "v|verbose", "be verbose", v => verbose = v != null },
                { "h|help", "show this message and exit", v => showHelp = v != null },
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 || extras.Count > 2 || showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ input_[sb|toc] [output_dir]", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            Paths paths;

            if (Paths.Discover(extras[0], extras.Count > 1 ? extras[1] : null, out paths) == false)
            {
                Console.WriteLine("Failed to discover data paths.");
                return;
            }

            var superbundleName = Path.ChangeExtension(paths.Superbundle.Substring(paths.Data.Length + 1), null);

            superbundleName = Helpers.FilterName(superbundleName).ToLowerInvariant();

            var layout = LayoutFile.Read(Path.Combine(paths.Data, "layout.toc"));

            var chunkLookup = new ChunkLookup(layout, paths.Data);
            var chunkLoader = new ChunkLoader(chunkLookup);

            var superbundle = chunkLookup.AddBundle(superbundleName);

            // add common chunk bundles (chunks*.toc/sb)
            foreach (var superbundleInfo in layout.Superbundles.Where(
                         sbi => ChunkLookup.IsChunkBundle(sbi.Name) == true))
            {
                if (chunkLookup.AddBundle(superbundleInfo.Name.ToLowerInvariant()) == null)
                {
                    Console.WriteLine("Failed to load catalog for '{0}'.", superbundleInfo.Name);
                }
            }

            foreach (var bundleInfo in superbundle.Bundles)
            {
                if (bundleInfo.Ebx == null)
                {
                    continue;
                }

                foreach (var ebxInfo in bundleInfo.Ebx)
                {
                    using (var data = new MemoryStream())
                    {
                        try
                        {
                            chunkLoader.Load(ebxInfo, data);
                            data.Position = 0;
                        }
                        catch (ChunkCryptoKeyMissingException e)
                        {
                            Console.WriteLine("Cannot decrypt '{0}' without crypto key '{1}'.", ebxInfo.Name, e.KeyId);
                            continue;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Exception while loading '{0}':", ebxInfo.Name);
                            Console.WriteLine(e);
                            continue;
                        }

                        var outputName       = Helpers.FilterPath(ebxInfo.Name);
                        var outputPath       = Path.Combine(paths.Output, outputName + ".dummy");
                        var outputParentPath = Path.GetDirectoryName(outputPath);
                        if (string.IsNullOrEmpty(outputParentPath) == false)
                        {
                            Directory.CreateDirectory(outputParentPath);
                        }

                        if (verbose == true)
                        {
                            Console.WriteLine("{0}", resourceInfo.Name);
                        }

                        bool wasConverted = false;
                        outputPath   = Path.Combine(paths.Output, outputName + ".entity");
                        wasConverted = ConvertEntity(data, outputPath, chunkLookup, chunkLoader);

                        if (wasConverted == false)
                        {
                            outputPath = Path.Combine(paths.Output, outputName + ".ebx");
                            using (var output = File.Create(outputPath))
                            {
                                output.WriteFromStream(data, data.Length);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Saves the given objects to the given file and includes the current file version number.
 /// </summary>
 /// <param name="objects">objects to save</param>
 /// <param name="pathToLayoutFile">filepath to save to</param>
 public void SaveLayout(LayoutFile layout, string pathToLayoutFile)
 {
     SerializationHelper.SaveToFile(layout, pathToLayoutFile);
 }
Ejemplo n.º 14
0
 public FileLoadedEventArgs(string filePathToUse, LayoutFile layoutToUse = null)
 {
     FilePath = filePathToUse;
     Layout   = layoutToUse;
 }
Ejemplo n.º 15
0
        private async Task GenerateTemplate(object param)
        {
            try
            {
                IsBusy        = true;
                StatusMessage = string.Empty;

                var buildingPresetsTask = Task.Run(() =>
                {
                    //load building presets
                    BuildingPresets localBuildingPresets = null;
                    try
                    {
                        var loader           = new BuildingPresetsLoader();
                        localBuildingPresets = loader.Load(PresetsVM.SelectedFile);
                        if (localBuildingPresets == null || localBuildingPresets.Buildings == null)
                        {
                            throw new ArgumentException();
                        }
                    }
                    catch (Exception ex)
                    {
                        var message = $"Error parsing {nameof(BuildingPresets)}.";
                        logger.Error(ex, message);
                        MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                        StatusMessage = $"{message} -> Maybe wrong selected file?";
                        return(null);
                    }

                    PresetsVersion = localBuildingPresets.Version;

                    return(localBuildingPresets);
                });

                var wikiBuildingInfoPresetsTask = Task.Run(() =>
                {
                    //load wiki buildng info
                    WikiBuildingInfoPresets localWikiBuildingInfoPresets = null;
                    try
                    {
                        var loader = new WikiBuildingInfoPresetsLoader();
                        localWikiBuildingInfoPresets = loader.Load(WikiBuildingsInfoVM.SelectedFile);
                    }
                    catch (Exception ex)
                    {
                        var message = $"Error parsing {nameof(WikiBuildingInfoPresets)}.";
                        logger.Error(ex, message);
                        MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                        StatusMessage = $"{message} -> Maybe wrong selected file?";
                        return(null);
                    }

                    WikiBuildingInfoPresetsVersion = localWikiBuildingInfoPresets.Version.ToString();

                    return(localWikiBuildingInfoPresets);
                });

                var layoutTask = Task.Run(() =>
                {
                    //load layout
                    LayoutFile localLayout = null;
                    try
                    {
                        ILayoutLoader loader = new LayoutLoader();
                        localLayout          = loader.LoadLayout(LayoutVM.SelectedFile);
                    }
                    catch (Exception ex)
                    {
                        var message = "Error parsing layout file.";
                        logger.Error(ex, message);
                        MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                        StatusMessage = $"{message} -> Maybe wrong selected file?";
                        return(null);
                    }

                    LayoutName = Path.GetFileName(LayoutVM.SelectedFile);

                    return(localLayout);
                });

                await Task.WhenAll(buildingPresetsTask, wikiBuildingInfoPresetsTask, layoutTask);

                var buildingPresets         = buildingPresetsTask.Result;
                var wikiBuildingInfoPresets = wikiBuildingInfoPresetsTask.Result;
                var layout = layoutTask.Result;

                if (buildingPresets == null || wikiBuildingInfoPresets == null || layout == null)
                {
                    return;
                }

                var layoutNameForTemplate = Path.GetFileNameWithoutExtension(LayoutVM.SelectedFile).Replace("_", " ");

                await Task.Run(() =>
                {
                    var exporter = new FandomExporter();
                    Template     = exporter.StartExport(layoutNameForTemplate, layout, buildingPresets, wikiBuildingInfoPresets, true);
                });

                StatusMessage = "Template successfully generated.";
            }
            catch (Exception ex)
            {
                var message = "Error generating template.";
                logger.Error(ex, message);
                MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                StatusMessage = $"{message} -> Details in log file.";
            }
            finally
            {
                IsBusy = false;
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Saves the given objects to the given stream and includes the current file version number.
 /// </summary>
 /// <param name="objects">objects to save</param>
 /// <param name="streamWithLayout">stream to save to</param>
 public void SaveLayout(LayoutFile layout, Stream streamWithLayout)
 {
     SerializationHelper.SaveToStream(layout, streamWithLayout);
 }
Ejemplo n.º 17
0
        private string RenderDocumentContentUsingLayout(DocumentFile document, string documentContent, LayoutFile layout)
        {
            var content = this.RenderContentForExtension(layout.SourcePath, layout.SourceContent, layout.Extension, document, documentContent, layout);

            string parentLayoutName;

            if (layout.Metadata.TryGet <string>("layout", out parentLayoutName))
            {
                var parentLayout = this.Site.Layouts[parentLayoutName];

                content = this.RenderDocumentContentUsingLayout(document, content, parentLayout);
            }

            return(content);
        }
Ejemplo n.º 18
0
        public static void Main(string[] args)
        {
            bool convertTextures = false;
            bool showHelp        = false;

            var options = new OptionSet()
            {
                { "convert-textures", "convert textures", v => convertTextures = v != null },
                { "h|help", "show this message and exit", v => showHelp = v != null },
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 || extras.Count > 2 || showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ input_[sb|toc] [output_dir]", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            string bundlePath, superbundlePath, layoutPath, outputBasePath;

            if (Path.GetExtension(extras[0]) == ".sb")
            {
                superbundlePath = Path.GetFullPath(extras[0]);
                bundlePath      = Path.ChangeExtension(superbundlePath, ".toc");
                layoutPath      = Helpers.FindLayoutPath(superbundlePath);
                outputBasePath  = extras.Count > 1 ? extras[1] : Path.ChangeExtension(superbundlePath, null) + "_unpack";
            }
            else
            {
                bundlePath      = Path.GetFullPath(extras[0]);
                superbundlePath = Path.ChangeExtension(bundlePath, ".sb");
                layoutPath      = Helpers.FindLayoutPath(bundlePath);
                outputBasePath  = extras.Count > 1 ? extras[1] : Path.ChangeExtension(bundlePath, null) + "_unpack";
            }

            if (string.IsNullOrEmpty(layoutPath) == true)
            {
                Console.WriteLine("Could not find layout file.");
                return;
            }

            var dataPath = Path.GetDirectoryName(layoutPath) ?? "";

            var bundle      = TableOfContentsFile.Read(bundlePath);
            var superbundle = SuperbundleFile.Read(superbundlePath);

            var extensionsById = ResourceTypes.GetExtensions();

            if (bundle.IsCas == false)
            {
                throw new NotImplementedException();
            }
            else
            {
                var commonBundlePaths = Directory.GetFiles(dataPath, "chunks*.toc", SearchOption.AllDirectories);
                var commonBundles     = new List <TableOfContentsFile>();
                foreach (var commonBundlePath in commonBundlePaths)
                {
                    var commonBundle = TableOfContentsFile.Read(commonBundlePath);
                    commonBundles.Add(commonBundle);
                }

                var superbundleName = Path.ChangeExtension(superbundlePath.Substring(dataPath.Length + 1), null);
                superbundleName = Helpers.FilterName(superbundleName).ToLowerInvariant();

                var layout        = LayoutFile.Read(layoutPath);
                var installChunks = GetSuperbundleInstallChunks(layout, superbundleName);
                var catalogLookup = new CatalogLookup(dataPath);

                foreach (var installChunk in installChunks)
                {
                    if (catalogLookup.Add(installChunk.InstallBundle) == false)
                    {
                        Console.WriteLine("Failed to load catalog for '{0}'.", installChunk.Name);
                    }
                }

                foreach (var bundleInfo in superbundle.Bundles)
                {
                    if (bundleInfo.Resources == null)
                    {
                        continue;
                    }

                    foreach (var resourceInfo in bundleInfo.Resources)
                    {
                        var entry = catalogLookup.GetEntry(resourceInfo);
                        if (entry == null)
                        {
                            Console.WriteLine("Could not find catalog entry for '{0}'.", resourceInfo.Name);
                            continue;
                        }

                        if (entry.CompressedSize != resourceInfo.Size)
                        {
                            throw new FormatException();
                        }

                        var outputName       = Helpers.FilterPath(resourceInfo.Name);
                        var outputPath       = Path.Combine(outputBasePath, outputName + ".dummy");
                        var outputParentPath = Path.GetDirectoryName(outputPath);
                        if (string.IsNullOrEmpty(outputParentPath) == false)
                        {
                            Directory.CreateDirectory(outputParentPath);
                        }

                        Console.WriteLine("{0}", resourceInfo.Name);

                        bool wasConverted = false;
                        if (convertTextures == true && resourceInfo.ResourceType == ResourceTypes.Texture)
                        {
                            wasConverted = ConvertTexture(bundleInfo,
                                                          resourceInfo,
                                                          entry,
                                                          outputPath,
                                                          catalogLookup,
                                                          commonBundles);
                        }

                        if (wasConverted == false)
                        {
                            string extension;
                            if (extensionsById.TryGetValue(resourceInfo.ResourceType, out extension) == true)
                            {
                                extension = "." + extension;
                            }
                            else
                            {
                                extension = ".#" + resourceInfo.ResourceType.ToString("X8");
                            }

                            outputPath = Path.Combine(outputBasePath, outputName + extension);
                            using (var output = File.Create(outputPath))
                            {
                                Extraction.Extract(resourceInfo, entry, output);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
 static RoadSearchHelperTests()
 {
     defaultObjectList = new LayoutLoader().LoadLayout(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestData", "RoadSearchHelper", "BreadthFirstSearch_FindBuildingInfluenceRange.ad"), true);
 }