示例#1
0
 public override void ExportStandaloneVm(
     Dictionary <string, FileOutput> output,
     TemplateStorage templates,
     IList <LibraryForExport> everyLibrary)
 {
     throw new NotImplementedException();
 }
 private void LoadResources(TemplateStorage templateStorage, ApplicationResource[] resources)
 {
     foreach (var resource in resources)
     {
         templateStorage.RegisterTemplate(resource.ResourceName, DeserializeTemplate(resource.Data));
     }
 }
示例#3
0
 public override void ExportProject(
     Dictionary <string, FileOutput> output,
     TemplateStorage templates,
     IList <LibraryForExport> libraries,
     ResourceDatabase resourceDatabase,
     Options options)
 {
     throw new NotImplementedException();
 }
示例#4
0
 public override void ExportProject(
     Dictionary <string, FileOutput> output,
     TemplateStorage templates,
     IList <LibraryForExport> libraries,
     ResourceDatabase resourceDatabase,
     Options options)
 {
     throw new InvalidOperationException("This platform does not support direct export.");
 }
示例#5
0
        private void ExportInterpreter(
            TemplateStorage templates,
            string baseDir,
            Dictionary <string, FileOutput> output)
        {
            foreach (string structKey in templates.GetTemplateKeysWithPrefix("vm:struct:"))
            {
                string structName = templates.GetName(structKey);
                output[baseDir + "Structs/" + structName + ".cs"] = new FileOutput()
                {
                    Type        = FileOutputType.Text,
                    TextContent = this.WrapStructCode(templates.GetCode(structKey)),
                };
            }

            string functionCode = templates.GetCode("vm:functions");

            output[baseDir + "Vm/CrayonWrapper.cs"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = string.Join("\r\n", new string[] {
                    "using System;",
                    "using System.Collections.Generic;",
                    "using System.Linq;",
                    "using Interpreter.Structs;",
                    "",
                    "namespace Interpreter.Vm",
                    "{",
                    "    public class CrayonWrapper",
                    "    {",
                    IndentCodeWithSpaces(functionCode, 8),
                    "    }",
                    "}",
                    ""
                }),
            };

            output[baseDir + "Vm/Globals.cs"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = string.Join("\r\n", new string[]
                {
                    "using System;",
                    "using System.Collections.Generic;",
                    "using Interpreter.Structs;",
                    "",
                    "namespace Interpreter.Vm",
                    "{",
                    templates.GetCode("vm:globals"),
                    "}",
                    ""
                }),
            };
        }
示例#6
0
 public override void ExportProject(
     Dictionary <string, FileOutput> output,
     TemplateStorage templates,
     IList <LibraryForExport> libraries,
     ResourceDatabase resourceDatabase,
     Options options)
 {
     this.ExportProjectImpl(
         output,
         templates,
         libraries,
         resourceDatabase,
         options);
 }
示例#7
0
        public override void ExportProject(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> libraries,
            ResourceDatabase resourceDatabase,
            Options options)
        {
            Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase);
            StringBuilder cCode = new StringBuilder();

            cCode.Append("#include <stdio.h>");
            cCode.Append(this.NL);
            cCode.Append("#include <stdlib.h>");
            cCode.Append(this.NL);
            cCode.Append("#include <string.h>");
            cCode.Append(this.NL);
            cCode.Append(this.NL);

            cCode.Append(this.LoadTextResource("Resources/List.txt", replacements));
            cCode.Append(this.LoadTextResource("Resources/String.txt", replacements));
            cCode.Append(this.LoadTextResource("Resources/Dictionary.txt", replacements));
            cCode.Append(this.LoadTextResource("Resources/TranslationHelper.txt", replacements));
            cCode.Append(this.NL);

            cCode.Append(templates.GetCode("vm:structsdecl"));
            cCode.Append(this.NL);

            foreach (string structKey in templates.GetTemplateKeysWithPrefix("vm:struct:"))
            {
                string structName = templates.GetName(structKey);
                cCode.Append(templates.GetCode(structKey));
            }
            cCode.Append(this.NL);

            cCode.Append(templates.GetCode("vm:stringtable"));
            cCode.Append(this.NL);
            cCode.Append(templates.GetCode("vm:functionsdecl"));
            cCode.Append(this.NL);
            cCode.Append(templates.GetCode("vm:functions"));
            cCode.Append(this.NL);

            cCode.Append(this.LoadTextResource("Resources/main.txt", replacements));

            output["main.c"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = cCode.ToString(),
            };
        }
示例#8
0
        public TemplateStorage GetStorage(TemplateDefinition definition)
        {
            var storage = new TemplateStorage();

            var list = new List <TemplateFile>();
            var pub  = new TemplateDirectory("public");

            foreach (var f in Directory.GetFiles(Path.Combine(WorkDir, "public"), "*.tt"))
            {
                pub.Files.Add(new TemplateFile(new FileInfo(f).Name, f, "C#"));
            }

            storage.Directories.Add(pub);
            storage.FromDefinition(definition);
            return(storage);
        }
        public ApplicationInstance CreateApp()
        {
            var codeSrc = new FileInfoCodeSource(_scripts.GetFileInfo("main.os"));

            _webEng.Environment.InjectObject(new WebGlobalContext(this, codeSrc, _webEng));

            var templateFactory = new DefaultTemplatesFactory();

            var storage = new TemplateStorage(templateFactory);

            _webEng.Environment.InjectObject(storage);
            _webEng.Engine.UpdateContexts();
            GlobalsManager.RegisterInstance(storage);

            return(ApplicationInstance.Create(codeSrc, _webEng));
        }
示例#10
0
        public override void ExportProject(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> libraries,
            ResourceDatabase resourceDatabase,
            Options options)
        {
            if (!options.GetBool(ExportOptionKey.HAS_ICON))
            {
                throw new InvalidOperationException("Cannot generate a Chrome Web App without an icon resource.");
            }

            string iconFilePath = options.GetString(ExportOptionKey.ICON_PATH);

            if (!FileUtil.FileExists(iconFilePath))
            {
                throw new InvalidOperationException("Icon resource path points to non-existent file.");
            }
            SystemBitmap iconFile  = new SystemBitmap(iconFilePath);
            SystemBitmap smallIcon = iconFile.CloneToNewSize(16, 16);
            SystemBitmap largeIcon = iconFile.CloneToNewSize(128, 128);

            JavaScriptApp.PlatformImpl      jsBasicPlatform = (JavaScriptApp.PlatformImpl) this.PlatformProvider.GetPlatform("javascript-app");
            Dictionary <string, FileOutput> proxyOutput     = new Dictionary <string, FileOutput>();

            jsBasicPlatform.ExportProjectImpl(proxyOutput, templates, libraries, resourceDatabase, options);
            Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase);

            replacements["JS_LIB_INCLUSIONS"] = JavaScriptApp.PlatformImpl.GenerateJsLibInclusionHtml(proxyOutput.Keys);
            this.CopyResourceAsText(proxyOutput, "background.js", "Resources/BackgroundJs.txt", replacements);
            this.CopyResourceAsText(proxyOutput, "index.html", "Resources/IndexHtml.txt", replacements); // overwrites GameHostHtml.txt from javascript-app
            this.CopyResourceAsText(proxyOutput, "chrome_web_app.js", "Resources/ChromeWebAppJs.txt", replacements);
            this.CopyResourceAsText(proxyOutput, "manifest.json", "Resources/ManifestJson.txt", Util.MakeReplacementStringsJsonSafe(replacements));
            proxyOutput["icon-16.png"] = new FileOutput()
            {
                Type   = FileOutputType.Image,
                Bitmap = smallIcon,
            };
            proxyOutput["icon-128.png"] = new FileOutput()
            {
                Type   = FileOutputType.Image,
                Bitmap = largeIcon,
            };

            output[replacements["PROJECT_ID"] + ".zip"] = ZipCreator.Create(proxyOutput, false);
        }
示例#11
0
        public TemplateStorage GetStorage(TemplateDefinition definition)
        {
            var storage = new TemplateStorage();

            var list = new List <TemplateFile>();
            var pub  = new TemplateDirectory("public");

            foreach (var f in Directory.GetFiles(Path.Combine(WorkDir, "public"), "*.vm"))
            {
                pub.Files.Add(new TemplateFile(new FileInfo(f).Name, f, "C#"));
            }

            storage.Directories.Add(pub);

            foreach (var p in definition.Partitions)
            {
                storage.Files.Add(new TemplateFile(string.Format("{1} ({0})", p.Name, p.FileName), p.FilePath, "C#"));
            }

            return(storage);
        }
示例#12
0
        public Process CreateProcess(Stream sourceStream, IHostApplication host)
        {
            var appDump         = DeserializeAppDump(sourceStream);
            var engine          = new HostedScriptEngine();
            var src             = new BinaryCodeSource();
            var templateStorage = new TemplateStorage(new StandaloneTemplateFactory());

            engine.SetGlobalEnvironment(host, src);
            engine.InitializationCallback = (e, env) =>
            {
                e.Environment.InjectObject(templateStorage);
                GlobalsManager.RegisterInstance(templateStorage);
            };
            engine.Initialize();

            LoadResources(templateStorage, appDump.Resources);
            LoadScripts(engine, appDump.Scripts);

            var process = engine.CreateProcess(host, appDump.Scripts[0].Image, src);

            return(process);
        }
示例#13
0
        public static void ExportJavaLibraries(
            AbstractPlatform platform,
            TemplateStorage templates,
            string srcPath,
            IList <LibraryForExport> libraries,
            Dictionary <string, FileOutput> output,
            string[] extraImports)
        {
            List <string> defaultImports = new List <string>()
            {
                "import java.util.ArrayList;",
                "import java.util.HashMap;",
                "import org.crayonlang.interpreter.FastList;",
                "import org.crayonlang.interpreter.Interpreter;",
                "import org.crayonlang.interpreter.LibraryFunctionPointer;",
                "import org.crayonlang.interpreter.TranslationHelper;",
                "import org.crayonlang.interpreter.VmGlobal;",
                "import org.crayonlang.interpreter.structs.*;",
            };

            defaultImports.AddRange(extraImports);
            defaultImports.Sort();

            foreach (LibraryForExport library in libraries)
            {
                if (library.HasPastelCode)
                {
                    TranspilerContext ctx         = library.PastelContext.GetTranspilerContext();
                    List <string>     libraryCode = new List <string>()
                    {
                        "package org.crayonlang.libraries." + library.Name.ToLower() + ";",
                        "",
                    };
                    libraryCode.AddRange(defaultImports);
                    libraryCode.AddRange(new string[]
                    {
                        "",
                        "public final class LibraryWrapper {",
                        "  private LibraryWrapper() {}",
                        "",
                    });

                    libraryCode.Add(templates.GetCode("library:" + library.Name + ":manifestfunc"));
                    libraryCode.Add(templates.GetCode("library:" + library.Name + ":functions"));

                    libraryCode.Add("}");
                    libraryCode.Add("");

                    string libraryPath = srcPath + "/org/crayonlang/libraries/" + library.Name.ToLower();

                    output[libraryPath + "/LibraryWrapper.java"] = new FileOutput()
                    {
                        Type        = FileOutputType.Text,
                        TextContent = string.Join(platform.NL, libraryCode),
                    };

                    foreach (string structKey in templates.GetTemplateKeysWithPrefix("library:" + library.Name + ":struct:"))
                    {
                        string structName = templates.GetName(structKey);
                        string structCode = templates.GetCode(structKey);

                        structCode = WrapStructCodeWithImports(platform.NL, structCode);

                        // This is kind of a hack.
                        // TODO: better.
                        structCode = structCode.Replace(
                            "package org.crayonlang.interpreter.structs;",
                            "package org.crayonlang.libraries." + library.Name.ToLower() + ";");

                        output[libraryPath + "/" + structName + ".java"] = new FileOutput()
                        {
                            Type        = FileOutputType.Text,
                            TextContent = structCode,
                        };
                    }

                    foreach (ExportEntity supFile in library.ExportEntities["COPY_CODE"])
                    {
                        string path = supFile.Values["target"].Replace("%LIBRARY_PATH%", libraryPath);
                        output[path] = supFile.FileOutput;
                    }
                }
            }
        }
示例#14
0
 public GenerateContractController(TemplateStorage templateStorage) => _templateStorage = templateStorage;
示例#15
0
        public override void ExportProject(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> libraries,
            ResourceDatabase resourceDatabase,
            Options options)
        {
            Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase);

            this.OutputAndroidBoilerplate(output, replacements, options);

            options.SetOption(ExportOptionKey.JS_FILE_PREFIX, null);
            options.SetOption(ExportOptionKey.JS_FULL_PAGE, false); // TODO: figure out if logic should be implemented in the web view for this.
            options.SetOption(ExportOptionKey.JS_HEAD_EXTRAS, string.Join(
                                  "\n",
                                  "<script type=\"text/javascript\" src=\"android.js\"></script>",
                                  "<style type=\"text/css\">",
                                  "  body { margin:0px; background-color:#000; }",
                                  "  #crayon_host {",
                                  "    background-color:#000;",
                                  "    text-align:left;",
                                  "    width:100%;",
                                  "    height:100%;",
                                  "  }",
                                  "</style>"
                                  ));

            Dictionary <string, FileOutput> files        = new Dictionary <string, FileOutput>();
            Dictionary <string, FileOutput> basicProject = new Dictionary <string, FileOutput>();

            this.ParentPlatform.ExportProject(
                basicProject,
                templates,
                libraries,
                resourceDatabase,
                options);

            // TODO: not good. The library inclusions should automatically be populated in LangJavaScript platforms.
            // This is also done identically in the ChromeApp PlatformImpl.
            replacements["JS_LIB_INCLUSIONS"] = JavaScriptApp.PlatformImpl.GenerateJsLibInclusionHtml(basicProject.Keys);

            foreach (string filePath in basicProject.Keys)
            {
                FileOutput file = basicProject[filePath];
                if (filePath.EndsWith("index.html"))
                {
                    file.TextContent = file.TextContent.Replace(
                        "<script type=\"text / javascript\" src=\"",
                        "<script type=\"text / javascript\" src=\"file:///android_asset/");
                }
                files["app/src/main/assets/" + filePath] = file;
            }

            // TODO: use orientations
            OrientationParser orientations = new OrientationParser(options);

            foreach (string filename in files.Keys)
            {
                output[this.ApplyReplacements(filename, replacements)] = files[filename];
            }
        }
示例#16
0
        public override void ExportProject(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> libraries,
            ResourceDatabase resourceDatabase,
            Options options)
        {
            options.SetOption(ExportOptionKey.JS_FILE_PREFIX, null);
            options.SetOption(ExportOptionKey.JS_FULL_PAGE, false); // iOS export has its own enforced fullscreen logic
            options.SetOption(ExportOptionKey.JS_HEAD_EXTRAS, string.Join(
                                  "\n",
                                  "<script type=\"text/javascript\" src=\"ios.js\"></script>",
                                  "<style type=\"text/css\">",
                                  "  body { margin:0px; background-color:#000; }",
                                  "  #crayon_host {",
                                  "    background-color:#000;",
                                  "    text-align:left;",
                                  "    width:100%;",
                                  "    height:100%;",
                                  "  }",
                                  "</style>"
                                  ));
            Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase);

            Dictionary <string, FileOutput> files        = new Dictionary <string, FileOutput>();
            Dictionary <string, FileOutput> basicProject = new Dictionary <string, FileOutput>();

            this.ParentPlatform.ExportProject(
                basicProject,
                templates,
                libraries,
                resourceDatabase,
                options);

            // TODO: not good. The library inclusions should automatically be populated in LangJavaScript platforms.
            // This is also done identically in the ChromeApp PlatformImpl.
            replacements["JS_LIB_INCLUSIONS"] = JavaScriptApp.PlatformImpl.GenerateJsLibInclusionHtml(basicProject.Keys);

            foreach (string filePath in basicProject.Keys)
            {
                files["%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/jsres/" + filePath] = basicProject[filePath];
            }

            // TODO: use this in the pbxproj file.
            string uuidSeed = options.GetStringOrNull(ExportOptionKey.GUID_SEED);


            OrientationParser orientations         = new OrientationParser(options);
            bool       useLandscapeForLaunchscreen = orientations.SupportsLandscapeLeft || orientations.SupportsLandscapeRight;
            FileOutput launchScreen;

            if (options.GetBool(ExportOptionKey.HAS_LAUNCHSCREEN))
            {
                launchScreen = new FileOutput()
                {
                    Type   = FileOutputType.Image,
                    Bitmap = new SystemBitmap(options.GetString(ExportOptionKey.LAUNCHSCREEN_PATH)),
                };
            }
            else
            {
                launchScreen = new FileOutput()
                {
                    Type   = FileOutputType.Image,
                    Bitmap = new SystemBitmap(typeof(JavaScriptAppIos.PlatformImpl).Assembly, "SwiftResources/" +
                                              (useLandscapeForLaunchscreen ? "launchhorizontal.png" : "launchvertical.png")),
                };
            }
            files["%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/Assets.xcassets/Launchscreen.imageset/launchscreen.png"] = launchScreen;
            replacements["LAUNCH_SCREEN_WIDTH"]  = launchScreen.Bitmap.Width.ToString();
            replacements["LAUNCH_SCREEN_HEIGHT"] = launchScreen.Bitmap.Height.ToString();

            IconSetGenerator icons = new IconSetGenerator();

            if (options.GetBool(ExportOptionKey.HAS_ICON))
            {
                string       iconPath = options.GetString(ExportOptionKey.ICON_PATH);
                SystemBitmap icon     = new SystemBitmap(iconPath);
                icons.AddInputImage(icon);
            }

            Dictionary <int, SystemBitmap> iconImagesBySize = icons
                                                              .AddOutputSize(20 * 1)
                                                              .AddOutputSize(20 * 2)
                                                              .AddOutputSize(20 * 3)
                                                              .AddOutputSize(29 * 1)
                                                              .AddOutputSize(29 * 2)
                                                              .AddOutputSize(29 * 3)
                                                              .AddOutputSize(40 * 1)
                                                              .AddOutputSize(40 * 2)
                                                              .AddOutputSize(40 * 3)
                                                              .AddOutputSize(60 * 2)
                                                              .AddOutputSize(60 * 3)
                                                              .AddOutputSize(76 * 1)
                                                              .AddOutputSize(76 * 2)
                                                              .AddOutputSize(167) // 83.5 * 2
                                                              .GenerateWithDefaultFallback();

            foreach (int size in iconImagesBySize.Keys)
            {
                files["%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/Assets.xcassets/AppIcon.appiconset/icon" + size + ".png"] = new FileOutput()
                {
                    Type   = FileOutputType.Image,
                    Bitmap = iconImagesBySize[size],
                };
            }

            foreach (string pair in new string[] {
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%.xcodeproj/project.pbxproj|SwiftResources/PbxProj.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/AppDelegate.swift|SwiftResources/AppDelegateSwift.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/Assets.xcassets/AppIcon.appiconset/Contents.json|SwiftResources/IconSetContentJson.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/Assets.xcassets/Launchscreen.imageset/Contents.json|SwiftResources/ImageSetContentJson.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/Base.lproj/LaunchScreen.storyboard|SwiftResources/LaunchScreenStoryboard.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/Base.lproj/Main.storyboard|SwiftResources/MainStoryboard.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/Info.plist|SwiftResources/InfoPlist.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/ViewController.swift|SwiftResources/ViewControllerSwift.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/jsres/ios.js|SwiftResources/iOSjs.txt",
                "%%%PROJECT_ID%%%/%%%PROJECT_ID%%%/jsres/index.html|SwiftResources/HostHtml.txt",
            })
            {
                string[] parts = pair.Split('|');
                files[parts[0]] = new FileOutput()
                {
                    TrimBomIfPresent = true,
                    Type             = FileOutputType.Text,
                    TextContent      = this.LoadTextResource(parts[1], replacements),
                };
            }

            foreach (string filename in files.Keys)
            {
                output[this.ApplyReplacements(filename, replacements)] = files[filename];
            }
        }
示例#17
0
        public int Run()
        {
            if (_sourceStream == null && CommandLineArguments != null && CommandLineArguments.Length > 1)
            {
                var firstArg = CommandLineArguments[0];
                if (firstArg == "-loadDump")
                {
                    var path = CommandLineArguments[1];
                    CommandLineArguments = CommandLineArguments.Skip(2).ToArray();
                    using (var dumpStream = new FileStream(path, FileMode.Open))
                    {
                        _sourceStream = GetCodeStream(dumpStream);
                    }

                    return(Run()); //ну да, говнокод и лапша, время жмет
                }
            }

            if (_sourceStream == null)
            {
                _sourceStream = LocateCode();
            }

            var engine = new HostedScriptEngine();
            var src    = new BinaryCodeSource();

            engine.SetGlobalEnvironment(this, src);

            try
            {
                var templateStorage = new TemplateStorage(new StandaloneTemplateFactory());
                engine.InitializationCallback = (e, env) =>
                {
                    e.Environment.InjectObject(templateStorage);
                    GlobalsManager.RegisterInstance(templateStorage);
                };

                engine.Initialize();

                var serializer = new BinaryFormatter();
                var appDump    = (ApplicationDump)serializer.Deserialize(_sourceStream);
                foreach (var resource in appDump.Resources)
                {
                    templateStorage.RegisterTemplate(resource.ResourceName, DeserializeTemplate(resource.Data));
                }
                var module = appDump.Scripts[0].Image;
                for (int i = 1; i < appDump.Scripts.Length; i++)
                {
                    engine.LoadUserScript(appDump.Scripts[i]);
                }

                var process = engine.CreateProcess(this, module, src);

                return(process.Start());
            }
            catch (ScriptInterruptionException e)
            {
                return(e.ExitCode);
            }
            catch (Exception e)
            {
                ShowExceptionInfo(e);
                return(1);
            }
        }
示例#18
0
        /// <summary>
        /// This is the method that is executed when the BackgroundWorker is activated.
        /// BackgroundWorkers make multi-threading simple and allow the user to do other
        /// things while exporting is occurring. It also provides an intuitive way to display
        /// the progress of the export to the user.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportBW_DoWork(object sender, DoWorkEventArgs e)
        {
            String[] selection = (String[])e.Argument;

            //Export everything to Word
            if (selection[0].Equals("All"))
            {
                String[] projects;

                string nextProjectSqlText = "SELECT projectName, projectID FROM Project;";
                string countProjectSql = "SELECT COUNT(projectID) FROM Project";

                DBCommand nextProjectSqlCmd = DBConnection.makeCommand(nextProjectSqlText);
                DBCommand countProjectSqlCmd = DBConnection.makeCommand(countProjectSql);

                SqlCeDataReader countProjectSqlReader = countProjectSqlCmd.Start();
                countProjectSqlReader.Read();
                projects = new String[countProjectSqlReader.GetInt32(0)]; //Initializes array
                countProjectSqlCmd.Stop(); //Stops command.

                SqlCeDataReader nextProjectSqlReader = nextProjectSqlCmd.Start();

                int i = 0;
                while (nextProjectSqlReader.Read())
                {
                    projects[i] = nextProjectSqlReader.GetString(0);
                    i++;
                }
                nextProjectSqlCmd.Stop(); //Stops command.

                for (int j = 0; j < projects.Length; j++)
                {
                    if (!exportProject("TMS_Export\\" + projects[j]))
                    {
                        e.Cancel = true;
                        break;
                    }

                    exportBW.ReportProgress((100 * (j + 1)) / projects.Length);

                    string getProjectIDText = "SELECT projectID FROM Project WHERE projectName='" + projects[j] + "';";
                    DBCommand getProjectIDCmd = DBConnection.makeCommand(getProjectIDText);
                    SqlCeDataReader getProjectIDReader = getProjectIDCmd.Start();
                    getProjectIDReader.Read();
                    int projectID = getProjectIDReader.GetInt32(0);

                    string getVersionSqlText = "SELECT versionNumber FROM Version WHERE project=" + projectID + ";";
                    DBCommand getVersionSqlCmd = DBConnection.makeCommand(getVersionSqlText);
                    SqlCeDataReader getVersionSqlReader = getVersionSqlCmd.Start();

                    while (getVersionSqlReader.Read())
                    {
                        double versionNum = (Double)getVersionSqlReader.GetSqlDouble(0);
                        exportVersion("TMS_Export\\" + projects[j], "Version " + versionNum);

                        string getVersionText = "SELECT versionID FROM Version WHERE versionNumber=" + versionNum + " AND project=" + projectID + ";";
                        DBCommand getVersionCmd = DBConnection.makeCommand(getVersionText);
                        SqlCeDataReader getVersionReader = getVersionCmd.Start();
                        getVersionReader.Read();
                        int versionID = getVersionReader.GetInt32(0);

                        string getFilesSqlText = "SELECT documentName FROM Document WHERE versionID=" + versionID + ";";
                        DBCommand getFilesSqlCmd = DBConnection.makeCommand(getFilesSqlText);
                        SqlCeDataReader getFilesSqlReader = getFilesSqlCmd.Start();
                        while (getFilesSqlReader.Read())
                        {
                            string documentName = getFilesSqlReader.GetString(0);

                            Serialization saveDocument = new Serialization();

                            string getTemplateTypeSqlText = "SELECT documentType FROM Document WHERE documentName='" + documentName + "' AND versionID=" + versionID + ";";
                            DBCommand getTemplateTypeSqlCmd = DBConnection.makeCommand(getTemplateTypeSqlText);
                            SqlCeDataReader getTemplateTypeSqlReader = getTemplateTypeSqlCmd.Start();
                            String templateType = "";
                            while (getTemplateTypeSqlReader.Read())
                            {
                                templateType += getTemplateTypeSqlReader.GetString(0);
                            }

                            string getTemplateSqlText = "SELECT templateData FROM Template WHERE templateName='" + templateType + "';";
                            DBCommand getTemplateSqlCmd = DBConnection.makeCommand(getTemplateSqlText);
                            SqlCeDataReader getTemplateSqlReader = getTemplateSqlCmd.Start();
                            String templateInput = "";
                            while (getTemplateSqlReader.Read())
                            {
                                templateInput += getTemplateSqlReader.GetString(0);
                            }

                            //Testing the deSerialize method.
                            TemplateStorage templateStorage = new TemplateStorage();
                            templateStorage = (TemplateStorage)saveDocument.deSerialize(templateStorage, templateInput);
                            List<string> genericList = new List<string>(templateStorage.Componentlist);
                            string getDocSqlText = "SELECT data FROM Document, Version WHERE documentName='" + documentName + "' AND Document.versionID=" + versionID + ";";
                            DBCommand getDocSqlCmd = DBConnection.makeCommand(getDocSqlText);
                            SqlCeDataReader getDocSqlReader = getDocSqlCmd.Start();
                            String documentData = "";

                            getDocSqlReader.Read();
                            documentData += getDocSqlReader.GetString(0);

                            while (getDocSqlReader.Read())
                            {

                            }
                            DocumentStorage documentStorage = new DocumentStorage();
                            documentStorage = (DocumentStorage)saveDocument.deSerialize(documentStorage, documentData);

                            string[] controlData = documentStorage.DocumentData;

                            exportFileWord(documentName, templateStorage.Componentlist, documentStorage.DocumentData, this.path + "\\TMS_Export\\" + projects[j] + "\\Version " + versionNum + "\\" + documentName);

                        }
                    }
                }
            }
            else
            {
                //Export specific project
                string nextProjectSqlText = "SELECT projectName, projectID FROM Project WHERE projectName='" + selection[0] + "';";
                DBCommand nextProjectSqlCmd = DBConnection.makeCommand(nextProjectSqlText);
                SqlCeDataReader nextProjectSqlReader = nextProjectSqlCmd.Start();
                nextProjectSqlReader.Read();
                String project = nextProjectSqlReader.GetString(0);
                int projectID = nextProjectSqlReader.GetInt32(1);

                bool directoryExists;

                if (selection[1].Equals("All"))
                {

                    directoryExists = exportProject(project);

                    if (!directoryExists)
                    {
                        e.Cancel = true;
                    }

                    string getVersionSqlText = "SELECT versionNumber FROM Version WHERE project=" + projectID + ";";
                    DBCommand getVersionSqlCmd = DBConnection.makeCommand(getVersionSqlText);
                    SqlCeDataReader getVersionSqlReader = getVersionSqlCmd.Start();

                    string getVersionSqlCountText = "SELECT COUNT(versionID) FROM Version WHERE project=" + projectID + ";";
                    DBCommand getVersionSqlCountCmd = DBConnection.makeCommand(getVersionSqlCountText);
                    SqlCeDataReader getVersionSqlCountReader = getVersionSqlCountCmd.Start();
                    getVersionSqlCountReader.Read();
                    int numberOfVersions = getVersionSqlCountReader.GetInt32(0);
                    int count = 0;

                    while (getVersionSqlReader.Read())
                    {
                        double versionNum = (Double)getVersionSqlReader.GetSqlDouble(0);

                        if (!exportVersion(project, "Version " + versionNum))
                        {
                            e.Cancel = true;
                            break;
                        }

                        exportBW.ReportProgress((100 * (count + 1)) / numberOfVersions);
                        count++;

                        string getVersionText = "SELECT versionID FROM Version WHERE versionNumber=" + versionNum + " AND project=" + projectID + ";";
                        DBCommand getVersionCmd = DBConnection.makeCommand(getVersionText);
                        SqlCeDataReader getVersionReader = getVersionCmd.Start();
                        getVersionReader.Read();
                        int versionID = getVersionReader.GetInt32(0);

                        string getFilesSqlText = "SELECT documentName FROM Document WHERE versionID=" + versionID + ";";
                        DBCommand getFilesSqlCmd = DBConnection.makeCommand(getFilesSqlText);
                        SqlCeDataReader getFilesSqlReader = getFilesSqlCmd.Start();
                        while (getFilesSqlReader.Read())
                        {
                            string documentName = getFilesSqlReader.GetString(0);

                            Serialization saveDocument = new Serialization();

                            string getTemplateTypeSqlText = "SELECT documentType FROM Document WHERE documentName='" + documentName + "' AND versionID=" + versionID + ";";
                            DBCommand getTemplateTypeSqlCmd = DBConnection.makeCommand(getTemplateTypeSqlText);
                            SqlCeDataReader getTemplateTypeSqlReader = getTemplateTypeSqlCmd.Start();
                            String templateType = "";
                            while (getTemplateTypeSqlReader.Read())
                            {
                                templateType += getTemplateTypeSqlReader.GetString(0);
                            }

                            string getTemplateSqlText = "SELECT templateData FROM Template WHERE templateName='" + templateType + "';";
                            DBCommand getTemplateSqlCmd = DBConnection.makeCommand(getTemplateSqlText);
                            SqlCeDataReader getTemplateSqlReader = getTemplateSqlCmd.Start();
                            String templateInput = "";
                            while (getTemplateSqlReader.Read())
                            {
                                templateInput += getTemplateSqlReader.GetString(0);
                            }

                            //Testing the deSerialize method.
                            TemplateStorage templateStorage = new TemplateStorage();
                            templateStorage = (TemplateStorage)saveDocument.deSerialize(templateStorage, templateInput);
                            List<string> genericList = new List<string>(templateStorage.Componentlist);
                            string getDocSqlText = "SELECT data FROM Document, Version WHERE documentName='" + documentName + "' AND Document.versionID=" + versionID + ";";
                            DBCommand getDocSqlCmd = DBConnection.makeCommand(getDocSqlText);
                            SqlCeDataReader getDocSqlReader = getDocSqlCmd.Start();
                            String documentData = "";

                            getDocSqlReader.Read();
                            documentData += getDocSqlReader.GetString(0);

                            while (getDocSqlReader.Read())
                            {

                            }
                            DocumentStorage documentStorage = new DocumentStorage();
                            documentStorage = (DocumentStorage)saveDocument.deSerialize(documentStorage, documentData);

                            string[] controlData = documentStorage.DocumentData;

                            exportFileWord(documentName, templateStorage.Componentlist, documentStorage.DocumentData, this.path + "\\" + project + "\\Version " + versionNum + "\\" + documentName);

                        }
                    }
                }
                else
                {
                    //Export specific version here
                    string getVersionSqlText = "SELECT versionNumber, versionID FROM Version WHERE project=" + projectID + " and versionNumber=" + selection[1].Substring(7) + ";";
                    DBCommand getVersionSqlCmd = DBConnection.makeCommand(getVersionSqlText);
                    SqlCeDataReader getVersionSqlReader = getVersionSqlCmd.Start();
                    getVersionSqlReader.Read();
                    Double versionNum = (Double)getVersionSqlReader.GetSqlDouble(0);
                    int versionID = getVersionSqlReader.GetInt32(1);

                    if (selection[2].Equals("All"))
                    {
                        directoryExists = exportVersion(project, "Version " + versionNum);

                        if (!directoryExists)
                        {
                            e.Cancel = true;
                        }

                        //Export all files for specific version here
                        string getFilesSqlText = "SELECT documentName FROM Document WHERE versionID=" + versionID + ";";
                        DBCommand getFilesSqlCmd = DBConnection.makeCommand(getFilesSqlText);
                        SqlCeDataReader getFilesSqlReader = getFilesSqlCmd.Start();

                        string getFileCountSqlText = "SELECT COUNT(documentID) FROM Document WHERE versionID=" + versionID + ";";
                        DBCommand getFileCountSqlCmd = DBConnection.makeCommand(getFileCountSqlText);
                        SqlCeDataReader getFileCountSqlReader = getFileCountSqlCmd.Start();
                        getFileCountSqlReader.Read();
                        int docCount = getFileCountSqlReader.GetInt32(0);
                        int count = 0;

                        while (getFilesSqlReader.Read())
                        {
                            exportBW.ReportProgress((100 * (count + 1)) / docCount);
                            count++;

                            string documentName = getFilesSqlReader.GetString(0);

                            Serialization saveDocument = new Serialization();

                            string getTemplateTypeSqlText = "SELECT documentType FROM Document WHERE documentName='" + documentName + "' AND versionID=" + versionID + ";";
                            DBCommand getTemplateTypeSqlCmd = DBConnection.makeCommand(getTemplateTypeSqlText);
                            SqlCeDataReader getTemplateTypeSqlReader = getTemplateTypeSqlCmd.Start();
                            String templateType = "";
                            while (getTemplateTypeSqlReader.Read())
                            {
                                templateType += getTemplateTypeSqlReader.GetString(0);
                            }

                            string getTemplateSqlText = "SELECT templateData FROM Template WHERE templateName='" + templateType + "';";
                            DBCommand getTemplateSqlCmd = DBConnection.makeCommand(getTemplateSqlText);
                            SqlCeDataReader getTemplateSqlReader = getTemplateSqlCmd.Start();
                            String templateInput = "";
                            while (getTemplateSqlReader.Read())
                            {
                                templateInput += getTemplateSqlReader.GetString(0);
                            }

                            //Testing the deSerialize method.
                            TemplateStorage templateStorage = new TemplateStorage();
                            templateStorage = (TemplateStorage)saveDocument.deSerialize(templateStorage, templateInput);
                            List<string> genericList = new List<string>(templateStorage.Componentlist);
                            string getDocSqlText = "SELECT data FROM Document, Version WHERE documentName='" + documentName + "' AND Document.versionID=" + versionID + ";";
                            DBCommand getDocSqlCmd = DBConnection.makeCommand(getDocSqlText);
                            SqlCeDataReader getDocSqlReader = getDocSqlCmd.Start();
                            String documentData = "";

                            getDocSqlReader.Read();
                            documentData += getDocSqlReader.GetString(0);

                            while (getDocSqlReader.Read())
                            {

                            }
                            DocumentStorage documentStorage = new DocumentStorage();
                            documentStorage = (DocumentStorage)saveDocument.deSerialize(documentStorage, documentData);

                            string[] controlData = documentStorage.DocumentData;

                            exportFileWord(documentName, templateStorage.Componentlist, documentStorage.DocumentData, this.path + "\\" + project + "\\Version " + versionNum + "\\" + documentName);

                        }
                    }
                    else
                    {
                        //Export specific file here
                        //Export all files for specific version here
                        string getFileSqlText = "SELECT documentName FROM Document WHERE versionID=" + versionID + " AND documentName='" + selection[2] + "';";
                        DBCommand getFileSqlCmd = DBConnection.makeCommand(getFileSqlText);
                        SqlCeDataReader getFileSqlReader = getFileSqlCmd.Start();

                        while (getFileSqlReader.Read())
                        {

                            string documentName = getFileSqlReader.GetString(0);

                            Serialization saveDocument = new Serialization();

                            string getTemplateTypeSqlText = "SELECT documentType FROM Document WHERE documentName='" + documentName + "' AND versionID=" + versionID + ";";
                            DBCommand getTemplateTypeSqlCmd = DBConnection.makeCommand(getTemplateTypeSqlText);
                            SqlCeDataReader getTemplateTypeSqlReader = getTemplateTypeSqlCmd.Start();
                            String templateType = "";
                            while (getTemplateTypeSqlReader.Read())
                            {
                                templateType += getTemplateTypeSqlReader.GetString(0);
                            }

                            string getTemplateSqlText = "SELECT templateData FROM Template WHERE templateName='" + templateType + "';";
                            DBCommand getTemplateSqlCmd = DBConnection.makeCommand(getTemplateSqlText);
                            SqlCeDataReader getTemplateSqlReader = getTemplateSqlCmd.Start();
                            String templateInput = "";
                            while (getTemplateSqlReader.Read())
                            {
                                templateInput += getTemplateSqlReader.GetString(0);
                            }

                            //Testing the deSerialize method.
                            TemplateStorage templateStorage = new TemplateStorage();
                            templateStorage = (TemplateStorage)saveDocument.deSerialize(templateStorage, templateInput);
                            List<string> genericList = new List<string>(templateStorage.Componentlist);
                            string getDocSqlText = "SELECT data FROM Document, Version WHERE documentName='" + documentName + "' AND Document.versionID=" + versionID + ";";
                            DBCommand getDocSqlCmd = DBConnection.makeCommand(getDocSqlText);
                            SqlCeDataReader getDocSqlReader = getDocSqlCmd.Start();
                            String documentData = "";

                            getDocSqlReader.Read();
                            documentData += getDocSqlReader.GetString(0);

                            while (getDocSqlReader.Read())
                            {

                            }
                            DocumentStorage documentStorage = new DocumentStorage();
                            documentStorage = (DocumentStorage)saveDocument.deSerialize(documentStorage, documentData);

                            string[] controlData = documentStorage.DocumentData;

                            exportFileWord(documentName, templateStorage.Componentlist, documentStorage.DocumentData, this.path + "\\" + documentName);

                            exportBW.ReportProgress(100);
                        }
                    }
                }
            }
        }
示例#19
0
        public override void ExportProject(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> libraries,
            ResourceDatabase resourceDatabase,
            Options options)
        {
            Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase);

            string srcPath        = "src";
            string srcPackagePath = srcPath + "/" + replacements["JAVA_PACKAGE"].Replace('.', '/') + "/";

            string[] imports = new string[]
            {
                "import org.crayonlang.interpreter.ResourceReader;",
                "import org.crayonlang.interpreter.AwtTranslationHelper;",
            };

            LangJava.PlatformImpl.ExportJavaLibraries(this, templates, srcPath, libraries, output, imports);

            foreach (string structKey in templates.GetTemplateKeysWithPrefix("vm:struct:"))
            {
                string structName = templates.GetName(structKey);
                string structCode = templates.GetCode(structKey);

                output["src/org/crayonlang/interpreter/structs/" + structName + ".java"] = new FileOutput()
                {
                    Type        = FileOutputType.Text,
                    TextContent = LangJava.PlatformImpl.WrapStructCodeWithImports(this.NL, structCode),
                };
            }

            StringBuilder sb = new StringBuilder();

            sb.Append(string.Join(this.NL, new string[] {
                "package org.crayonlang.interpreter;",
                "",
                "import java.util.ArrayList;",
                "import java.util.HashMap;",
                "import org.crayonlang.interpreter.structs.*;",
                "",
                "public final class Interpreter {",
                "  private Interpreter() {}",
                "",
            }));

            sb.Append(templates.GetCode("vm:functions"));
            sb.Append("}");
            sb.Append(this.NL);

            output["src/org/crayonlang/interpreter/Interpreter.java"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = sb.ToString(),
            };

            output["src/org/crayonlang/interpreter/VmGlobal.java"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = templates.GetCode("vm:globals"),
            };

            // common Java helper files
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/FastList.java", "Resources/FastList.txt", replacements);
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/LibraryFunctionPointer.java", "Resources/LibraryFunctionPointer.txt", replacements);
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/LibraryInstance.java", "Resources/LibraryInstance.txt", replacements);
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/TranslationHelper.java", "Resources/TranslationHelper.txt", replacements);
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/PlatformTranslationHelper.java", "Resources/PlatformTranslationHelper.txt", replacements);

            // java-app specific files
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/LibraryLoader.java", "Resources/LibraryLoader.txt", replacements);
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/ResourceReader.java", "Resources/ResourceReader.txt", replacements);
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/AwtTranslationHelper.java", "Resources/AwtTranslationHelper.txt", replacements);

            // need to move these to library supplemental files
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/GameWindow.java", "Resources/GameWindow.txt", replacements);
            this.CopyResourceAsText(output, "src/org/crayonlang/interpreter/RenderEngine.java", "Resources/RenderEngine.txt", replacements);

            this.CopyResourceAsText(output, srcPackagePath + "/Main.java", "Resources/Main.txt", replacements);
            this.CopyResourceAsText(output, "build.xml", "Resources/BuildXml.txt", replacements);

            output["resources/manifest.txt"] = resourceDatabase.ResourceManifestFile;
            output["resources/bytecode.txt"] = resourceDatabase.ByteCodeFile;
            if (resourceDatabase.ImageSheetManifestFile != null)
            {
                output["resources/imagesheetmanifest.txt"] = resourceDatabase.ImageSheetManifestFile;
            }

            foreach (string imageSheetFileName in resourceDatabase.ImageSheetFiles.Keys)
            {
                FileOutput imageSheetFile = resourceDatabase.ImageSheetFiles[imageSheetFileName];
                output["resources/images/" + imageSheetFileName] = imageSheetFile;
            }

            foreach (FileOutput audioResource in resourceDatabase.AudioResources)
            {
                output["resources/audio/" + audioResource.CanonicalFileName] = audioResource;
            }

            foreach (FileOutput textResource in resourceDatabase.TextResources)
            {
                output["resources/text/" + textResource.CanonicalFileName] = textResource;
            }

            foreach (FileOutput fontResource in resourceDatabase.FontResources)
            {
                output["resources/ttf/" + fontResource.CanonicalFileName] = fontResource;
            }

            IEnumerable <FileOutput> javaFiles = output.Keys
                                                 .Where(filename => filename.ToLower().EndsWith(".java"))
                                                 .Select(filename => output[filename]);

            foreach (FileOutput file in javaFiles)
            {
                file.TrimBomIfPresent = true;
            }
        }
示例#20
0
        public void ExportProjectImpl(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> libraries,
            ResourceDatabase resourceDatabase,
            Options options)
        {
            List <string> jsExtraHead = new List <string>()
            {
                options.GetStringOrEmpty(ExportOptionKey.JS_HEAD_EXTRAS)
            };
            bool fullPage = options.GetBool(ExportOptionKey.JS_FULL_PAGE);

            // There's a double-check here so that you can || them together and then have multiple options added here.
            if (fullPage)
            {
                jsExtraHead.Add(
                    "<script type=\"text/javascript\">"
                    + (fullPage ? "C$common$globalOptions['fullscreen'] = true;" : "")
                    + "</script>");
            }
            options.SetOption(ExportOptionKey.JS_HEAD_EXTRAS, string.Join("\n", jsExtraHead));

            Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase);

            output["vm.js"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = templates.GetCode("vm:globals") + this.NL + this.NL + templates.GetCode("vm:functions"),
            };

            List <LibraryForExport> librariesWithCode = new List <LibraryForExport>();

            foreach (LibraryForExport library in libraries)
            {
                if (library.HasPastelCode)
                {
                    string        libraryName = library.Name;
                    PastelContext libContext  = library.PastelContext;

                    List <string> libraryLines = new List <string>();
                    libraryLines.Add(templates.GetCode("library:" + libraryName + ":manifestfunc"));
                    libraryLines.Add("");
                    libraryLines.Add(templates.GetCode("library:" + libraryName + ":functions"));
                    libraryLines.Add("");
                    libraryLines.Add("C$common$scrapeLibFuncNames('" + libraryName.ToLower() + "');");
                    libraryLines.Add("");

                    // add helper functions after the scrape.

                    foreach (ExportEntity embedCode in library.ExportEntities["EMBED_CODE"])
                    {
                        libraryLines.Add(embedCode.StringValue);
                    }

                    output["libs/lib_" + libraryName.ToLower() + ".js"] = new FileOutput()
                    {
                        Type        = FileOutputType.Text,
                        TextContent = string.Join("\n", libraryLines),
                    };
                    librariesWithCode.Add(library);
                }
            }

            Dictionary <string, string> htmlReplacements = new Dictionary <string, string>(replacements);

            replacements["JS_LIB_INCLUSIONS"] = GenerateJsLibInclusionHtml(output.Keys);

            this.CopyResourceAsText(output, "index.html", "Resources/HostHtml.txt", replacements);

            this.CopyResourceAsText(output, "common.js", "Resources/Common.txt", replacements);

            TODO.JavaScriptDeGamification();
            output["lib_supplemental.js"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = this.LoadTextResource("Resources/ImageResource.txt", replacements),
            };

            StringBuilder resourcesJs = new StringBuilder();

            foreach (FileOutput textResource in resourceDatabase.TextResources)
            {
                resourcesJs.Append("C$common$addTextRes(");
                resourcesJs.Append(Util.ConvertStringValueToCode(textResource.CanonicalFileName));
                resourcesJs.Append(", ");
                resourcesJs.Append(Util.ConvertStringValueToCode(textResource.TextContent));
                resourcesJs.Append(");\n");
            }

            foreach (FileOutput fontResource in resourceDatabase.FontResources)
            {
                resourcesJs.Append("C$common$addBinaryRes(");
                resourcesJs.Append(Util.ConvertStringValueToCode(fontResource.CanonicalFileName));
                resourcesJs.Append(", '");
                resourcesJs.Append(Util.ConvertByteArrayToBase64(fontResource.GetFinalBinaryContent()));
                resourcesJs.Append("');\n");
            }

            FileOutput imageSheetManifest = resourceDatabase.ImageSheetManifestFile;

            resourcesJs.Append("C$common$addTextRes('image_sheets.txt', ");
            resourcesJs.Append(imageSheetManifest == null ? "''" : Util.ConvertStringValueToCode(imageSheetManifest.TextContent));
            resourcesJs.Append(");\n");

            resourcesJs.Append("C$common$resourceManifest = ");
            resourcesJs.Append(Util.ConvertStringValueToCode(resourceDatabase.ResourceManifestFile.TextContent));
            resourcesJs.Append(";\n");

            string filePrefix = options.GetStringOrNull(ExportOptionKey.JS_FILE_PREFIX);

            if (filePrefix != null)
            {
                resourcesJs.Append("C$common$jsFilePrefix = ");
                resourcesJs.Append(Util.ConvertStringValueToCode(filePrefix));
                resourcesJs.Append(";\n");
            }

            output["resources.js"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = resourcesJs.ToString(),
            };

            output["bytecode.js"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = "C$bytecode = " + Util.ConvertStringValueToCode(resourceDatabase.ByteCodeFile.TextContent) + ";",
            };

            foreach (string imageResourceFile in resourceDatabase.ImageSheetFiles.Keys)
            {
                FileOutput file = resourceDatabase.ImageSheetFiles[imageResourceFile];
                output["resources/images/" + imageResourceFile] = file;
            }

            foreach (FileOutput audioResourceFile in resourceDatabase.AudioResources)
            {
                output["resources/audio/" + audioResourceFile.CanonicalFileName] = audioResourceFile;
            }

            // TODO: minify JavaScript across all of output dictionary
        }
示例#21
0
        public override void ExportProject(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> libraries,
            ResourceDatabase resourceDatabase,
            Options options)
        {
            Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase);

            output["code/vm.py"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = string.Join(this.NL, new string[] {
                    this.LoadTextResource("Resources/header.txt", replacements),
                    this.LoadTextResource("Resources/TranslationHelper.txt", replacements),
                    templates.GetCode("vm:globals"),
                    this.LoadTextResource("Resources/LibraryRegistry.txt", replacements),
                    this.LoadTextResource("Resources/ResourceReader.txt", replacements),
                    templates.GetCode("vm:functions"),
                }),
            };

            foreach (LibraryForExport library in libraries)
            {
                TranspilerContext libCtx       = library.PastelContext.GetTranspilerContext();
                string            libraryName  = library.Name;
                List <string>     libraryLines = new List <string>();
                if (library.HasPastelCode)
                {
                    libraryLines.Add("import math");
                    libraryLines.Add("import os");
                    libraryLines.Add("import random");
                    libraryLines.Add("import sys");
                    libraryLines.Add("import time");
                    libraryLines.Add("import inspect");
                    libraryLines.Add("from code.vm import *");
                    libraryLines.Add("");
                    libraryLines.Add(templates.GetCode("library:" + libraryName + ":manifestfunc"));
                    libraryLines.Add(templates.GetCode("library:" + libraryName + ":functions"));
                    libraryLines.Add("");
                    libraryLines.Add("_moduleInfo = ('" + libraryName + "', dict(inspect.getmembers(sys.modules[__name__])))");
                    libraryLines.Add("");
                    libraryLines.AddRange(library.ExportEntities["EMBED_CODE"].Select(entity => entity.StringValue));

                    output["code/lib_" + libraryName.ToLower() + ".py"] = new FileOutput()
                    {
                        Type        = FileOutputType.Text,
                        TextContent = string.Join(this.NL, libraryLines),
                    };
                }
            }

            output["main.py"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = this.LoadTextResource("Resources/main.txt", replacements),
            };

            output["code/__init__.py"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = "",
            };

            output["res/bytecode.txt"]          = resourceDatabase.ByteCodeFile;
            output["res/resource_manifest.txt"] = resourceDatabase.ResourceManifestFile;
            if (resourceDatabase.ImageSheetManifestFile != null)
            {
                output["res/image_sheet_manifest.txt"] = resourceDatabase.ImageSheetManifestFile;
            }

            foreach (FileOutput image in resourceDatabase.ImageResources)
            {
                output["res/images/" + image.CanonicalFileName] = image;
            }

            foreach (string imageSheetFile in resourceDatabase.ImageSheetFiles.Keys)
            {
                output["res/images/" + imageSheetFile] = resourceDatabase.ImageSheetFiles[imageSheetFile];
            }

            foreach (FileOutput sound in resourceDatabase.AudioResources)
            {
                output["res/audio/" + sound.CanonicalFileName] = sound;
            }

            foreach (FileOutput textResource in resourceDatabase.TextResources)
            {
                output["res/text/" + textResource.CanonicalFileName] = textResource;
            }

            foreach (FileOutput fontResource in resourceDatabase.FontResources)
            {
                output["res/ttf/" + fontResource.CanonicalFileName] = fontResource;
            }
        }
示例#22
0
        // Returns true if any export is necessary i.e. bytecode-only libraries will return false.
        private bool GetLibraryCode(
            TemplateStorage templates,
            string baseDir,
            LibraryForExport library,
            List <LangCSharp.DllFile> dllsOut,
            Dictionary <string, FileOutput> filesOut)
        {
            string        libraryName  = library.Name;
            List <string> libraryLines = new List <string>();

            if (library.HasPastelCode)
            {
                string libraryDir      = baseDir + "Libraries/" + libraryName;
                string allFunctionCode = templates.GetCode("library:" + libraryName + ":functions");
                libraryLines.Add(allFunctionCode);

                foreach (string structKey in templates.GetTemplateKeysWithPrefix("library:" + libraryName + ":struct:"))
                {
                    string structName = templates.GetName(structKey);
                    filesOut[libraryDir + "/Structs/" + structName + ".cs"] = new FileOutput()
                    {
                        Type        = FileOutputType.Text,
                        TextContent = this.WrapStructCode(templates.GetCode(structKey)),
                    };
                }

                filesOut[libraryDir + "/LibraryWrapper.cs"] = new FileOutput()
                {
                    Type        = FileOutputType.Text,
                    TextContent = string.Join(this.NL,
                                              "using System;",
                                              "using System.Collections.Generic;",
                                              "using System.Linq;",
                                              "using Interpreter;",
                                              "using Interpreter.Structs;",
                                              "using Interpreter.Vm;",
                                              "",
                                              "namespace Interpreter.Libraries." + libraryName,
                                              "{",
                                              "    public static class LibraryWrapper",
                                              "    {",
                                              IndentCodeWithSpaces(string.Join(this.NL, libraryLines), 8),
                                              "    }",
                                              "}",
                                              ""),
                };

                foreach (ExportEntity codeFile in library.ExportEntities["COPY_CODE"])
                {
                    string targetPath = codeFile.Values["target"].Replace("%LIBRARY_PATH%", libraryDir);
                    filesOut[targetPath] = codeFile.FileOutput;
                }

                foreach (ExportEntity dllFile in library.ExportEntities["DOTNET_DLL"])
                {
                    dllsOut.Add(new LangCSharp.DllFile(dllFile));
                }

                return(true);
            }

            return(false);
        }
示例#23
0
        public override void ExportStandaloneVm(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> everyLibrary)
        {
            Dictionary <string, string> libraryProjectNameToGuid = new Dictionary <string, string>();

            string runtimeProjectGuid  = IdGenerator.GenerateCSharpGuid("runtime", "runtime-project");
            string runtimeAssemblyGuid = IdGenerator.GenerateCSharpGuid("runtime", "runtime-assembly");

            Dictionary <string, string> replacements = new Dictionary <string, string>()
            {
                { "PROJECT_ID", "CrayonRuntime" },
                { "PROJECT_GUID", runtimeProjectGuid },
                { "INTERPRETER_PROJECT_GUID", runtimeProjectGuid },
                { "ASSEMBLY_GUID", runtimeAssemblyGuid },
                { "PROJECT_TITLE", "Crayon Runtime" },
                { "COPYRIGHT", "©" },
                { "CURRENT_YEAR", DateTime.Now.Year.ToString() },
                { "DLL_REFERENCES", "" },
                { "CSHARP_APP_ICON", "<ApplicationIcon>icon.ico</ApplicationIcon>" },
                { "EMBEDDED_RESOURCES", "<EmbeddedResource Include=\"icon.ico\" />" },
                { "CSHARP_CONTENT_ICON", "" },
                { "DLLS_COPIED", "" },
            };
            string baseDir = "CrayonRuntime/";

            string dllReferencesOriginal = replacements["DLL_REFERENCES"];
            string dllsCopiedOriginal    = replacements["DLLS_COPIED"];
            string embeddedResources     = replacements["EMBEDDED_RESOURCES"];

            replacements["EMBEDDED_RESOURCES"] = "";
            foreach (LibraryForExport library in everyLibrary)
            {
                string libBaseDir = "Libs/" + library.Name + "/";
                List <LangCSharp.DllFile> dlls = new List <LangCSharp.DllFile>();
                if (this.GetLibraryCode(templates, libBaseDir, library, dlls, output))
                {
                    string name        = library.Name;
                    string projectGuid = IdGenerator.GenerateCSharpGuid(library.Name + "|" + library.Version, "library-project");
                    replacements["PROJECT_GUID"]  = projectGuid;
                    replacements["ASSEMBLY_GUID"] = IdGenerator.GenerateCSharpGuid(library.Name + "|" + library.Version, "library-assembly");
                    replacements["PROJECT_TITLE"] = library.Name;
                    replacements["LIBRARY_NAME"]  = library.Name;
                    LangCSharp.DllReferenceHelper.AddDllReferencesToProjectBasedReplacements(replacements, dlls, library.LibProjectNamesAndGuids);

                    libraryProjectNameToGuid[name] = projectGuid;

                    replacements["DOT_NET_LIBS"] = Util.JoinLines(
                        library.DotNetLibs.Select(
                            dotNetLib =>
                            "    <Reference Include=\"" + dotNetLib + "\" />")
                        .ToArray());

                    this.CopyResourceAsText(output, libBaseDir + library.Name + ".sln", "ResourcesLib/Solution.txt", replacements);
                    this.CopyResourceAsText(output, libBaseDir + library.Name + ".csproj", "ResourcesLib/ProjectFile.txt", replacements);
                    this.CopyResourceAsText(output, libBaseDir + "Properties/AssemblyInfo.cs", "ResourcesLib/AssemblyInfo.txt", replacements);

                    foreach (LangCSharp.DllFile dll in dlls)
                    {
                        output[libBaseDir + dll.HintPath] = dll.FileOutput;
                    }
                }
            }
            replacements["DLL_REFERENCES"]     = dllReferencesOriginal;
            replacements["DLLS_COPIED"]        = dllsCopiedOriginal;
            replacements["EMBEDDED_RESOURCES"] = embeddedResources;
            replacements["PROJECT_GUID"]       = runtimeProjectGuid;
            replacements["ASSEMBLY_GUID"]      = runtimeAssemblyGuid;

            this.CopyTemplatedFiles(baseDir, output, replacements, true);
            this.ExportInterpreter(templates, baseDir, output);
            this.ExportProjectFiles(baseDir, output, replacements, libraryProjectNameToGuid, true);
            this.CopyResourceAsBinary(output, baseDir + "icon.ico", "ResourcesVm/icon.ico");

            TODO.MoveCbxParserIntoTranslatedPastelCode();
            this.CopyResourceAsText(output, baseDir + "CbxDecoder.cs", "ResourcesVm/CbxDecoder.txt", replacements);
        }
示例#24
0
        public override void ExportProject(
            Dictionary <string, FileOutput> output,
            TemplateStorage templates,
            IList <LibraryForExport> libraries,
            ResourceDatabase resourceDatabase,
            Options options)
        {
            Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase);
            string projectId = options.GetString(ExportOptionKey.PROJECT_ID);
            string baseDir   = projectId + "/";

            this.CopyTemplatedFiles(baseDir, output, replacements, false);

            List <LangCSharp.DllFile> dlls = new List <LangCSharp.DllFile>();

            HashSet <string> dotNetLibs = new HashSet <string>();

            foreach (LibraryForExport library in libraries)
            {
                foreach (string dotNetLib in library.DotNetLibs)
                {
                    dotNetLibs.Add(dotNetLib);
                }
                this.GetLibraryCode(templates, baseDir, library, dlls, output);
            }

            LangCSharp.DllReferenceHelper.AddDllReferencesToProjectBasedReplacements(replacements, dlls, new Dictionary <string, string>());

            replacements["DLL_REFERENCES"] += Util.JoinLines(
                dotNetLibs
                .OrderBy(v => v.ToLower())
                .Select(
                    dotNetLib =>
                    "    <Reference Include=\"" + dotNetLib + "\" />")
                .ToArray());

            this.ExportInterpreter(templates, baseDir, output);

            output[baseDir + "Resources/ByteCode.txt"]         = resourceDatabase.ByteCodeFile;
            output[baseDir + "Resources/ResourceManifest.txt"] = resourceDatabase.ResourceManifestFile;
            if (resourceDatabase.ImageSheetManifestFile != null)
            {
                output[baseDir + "Resources/ImageSheetManifest.txt"] = resourceDatabase.ImageSheetManifestFile;
            }

            foreach (FileOutput imageFile in resourceDatabase.ImageResources.Where(img => img.CanonicalFileName != null))
            {
                output[baseDir + "Resources/" + imageFile.CanonicalFileName] = imageFile;
            }

            foreach (string imageSheetFileName in resourceDatabase.ImageSheetFiles.Keys)
            {
                output[baseDir + "Resources/" + imageSheetFileName] = resourceDatabase.ImageSheetFiles[imageSheetFileName];
            }

            foreach (FileOutput textFile in resourceDatabase.TextResources.Where(img => img.CanonicalFileName != null))
            {
                output[baseDir + "Resources/" + textFile.CanonicalFileName] = textFile;
            }

            foreach (FileOutput audioFile in resourceDatabase.AudioResources.Where(file => file.CanonicalFileName != null))
            {
                output[baseDir + "Resources/" + audioFile.CanonicalFileName] = audioFile;
            }

            foreach (FileOutput fontFile in resourceDatabase.FontResources.Where(file => file.CanonicalFileName != null))
            {
                output[baseDir + "Resources/" + fontFile.CanonicalFileName] = fontFile;
            }

            foreach (LangCSharp.DllFile dll in dlls)
            {
                output[baseDir + dll.HintPath] = dll.FileOutput;
            }

            if (options.GetBool(ExportOptionKey.HAS_ICON))
            {
                string        iconPath = options.GetString(ExportOptionKey.ICON_PATH);
                IconGenerator iconGen  = new IconGenerator();
                foreach (string path in iconPath.Split(','))
                {
                    iconGen.AddImage(new SystemBitmap(path.Trim()));
                }

                output[baseDir + "icon.ico"] = new FileOutput()
                {
                    Type          = FileOutputType.Binary,
                    BinaryContent = iconGen.GenerateIconFile(),
                };
            }

            this.ExportProjectFiles(baseDir, output, replacements, new Dictionary <string, string>(), false);
        }