Esempio n. 1
0
        /// <summary>
        /// Save design-time user data for the current room.
        /// </summary>
        public static void SaveToUserFile(Room room, RoomSettingsEditor editor, CompileMessages errors)
        {
            string fileName = room.UserFileName;

            StringWriter  sw     = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(sw);

            // Copy header style from Game.agf and Game.agf.user
            // TODO: unify all xml header read/write?
            writer.Formatting = Formatting.Indented;
            writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"" + Encoding.Default.WebName + "\"");
            writer.WriteComment("DO NOT EDIT THIS FILE. It is automatically generated by the AGS Editor, changing it manually could break your game");
            writer.WriteStartElement(XML_DATA_ROOT_NODE);
            writer.WriteAttributeString(AGSEditor.XML_ATTRIBUTE_VERSION_INDEX, CURRENT_DATA_VERSION_INDEX.ToString());
            writer.WriteAttributeString(AGSEditor.XML_ATTRIBUTE_EDITOR_VERSION, AGS.Types.Version.AGS_EDITOR_VERSION);

            SaveDataToXML(room, editor, writer);

            writer.WriteEndElement(); // Root node
            writer.Flush();           // Finish writing

            try
            {
                StreamWriter fileOutput = new StreamWriter(fileName, false, Encoding.Default);
                fileOutput.Write(sw.ToString());
                fileOutput.Close();
                writer.Close();
            }
            catch (Exception ex)
            {
                // TODO: had to break long message into two separate warnings, because Output panel is not suited for line breaks.
                errors.Add(new CompileWarning("Unable to write the room design-time preferences. Ensure that you have write access to the game folder, and that the file is not already open"));
                errors.Add(new CompileWarning(ex.Message, ex));
            }
        }
Esempio n. 2
0
        public override bool Build(CompileMessages errors, bool forceRebuild)
        {
            if (!base.Build(errors, forceRebuild))
            {
                return(false);
            }
            try
            {
                string             baseGameFileName = Factory.AGSEditor.BaseGameFileName;
                string             exeFileName      = baseGameFileName + ".exe";
                BuildTargetWindows targetWin        = BuildTargetsInfo.FindBuildTargetByName("Windows") as BuildTargetWindows;
                if (targetWin == null)
                {
                    errors.Add(new CompileError("Debug build depends on Windows build target being available! Your AGS installation may be corrupted!"));
                    return(false);
                }
                string compiledEXE = targetWin.GetCompiledPath(exeFileName);
                string compiledDat = targetWin.GetCompiledPath(baseGameFileName + ".ags");
                string sourceEXE   = Path.Combine(Factory.AGSEditor.EditorDirectory, AGSEditor.ENGINE_EXE_FILE_NAME);
                Utilities.DeleteFileIfExists(compiledEXE);
                Utilities.DeleteFileIfExists(compiledDat);
                File.Copy(sourceEXE, exeFileName, true);
                BusyDialog.Show("Please wait while we prepare to run the game...", new BusyDialog.ProcessingHandler(CreateDebugFiles), errors);
                if (errors.HasErrors)
                {
                    return(false);
                }
                Utilities.DeleteFileIfExists(GetDebugPath(exeFileName));
                File.Move(exeFileName, GetDebugPath(exeFileName));
                // copy configuration from Compiled folder to use with Debugging
                string cfgFilePath = targetWin.GetCompiledPath(AGSEditor.CONFIG_FILE_NAME);
                if (File.Exists(cfgFilePath))
                {
                    File.Copy(cfgFilePath, GetDebugPath(AGSEditor.CONFIG_FILE_NAME), true);
                }
                else
                {
                    cfgFilePath = Path.Combine(AGSEditor.OUTPUT_DIRECTORY, Path.Combine(AGSEditor.DATA_OUTPUT_DIRECTORY, AGSEditor.CONFIG_FILE_NAME));
                    if (File.Exists(cfgFilePath))
                    {
                        File.Copy(cfgFilePath, GetDebugPath(AGSEditor.CONFIG_FILE_NAME), true);
                    }
                }
                foreach (Plugin plugin in Factory.AGSEditor.CurrentGame.Plugins)
                {
                    File.Copy(Path.Combine(Factory.AGSEditor.EditorDirectory, plugin.FileName), GetDebugPath(plugin.FileName), true);
                }

                // Copy files from Compiled/Data to Compiled/Windows, because this is currently where game will be looking them up
                targetWin.CopyAuxiliaryGameFiles(Path.Combine(AGSEditor.OUTPUT_DIRECTORY, AGSEditor.DATA_OUTPUT_DIRECTORY), false);
            }
            catch (Exception ex)
            {
                errors.Add(new CompileError("Unexpected error: " + ex.Message));
                return(false);
            }
            return(true);
        }
Esempio n. 3
0
        private SpeechLipSyncLine CompilePamelaFile(string fileName, CompileMessages errors)
        {
            SpeechLipSyncLine syncDataForThisFile = new SpeechLipSyncLine();

            syncDataForThisFile.FileName = Path.GetFileNameWithoutExtension(fileName);

            string thisLine;
            bool   inMainSection = false;
            int    lineNumber    = 0;

            StreamReader sr = new StreamReader(fileName);

            while ((thisLine = sr.ReadLine()) != null)
            {
                lineNumber++;
                if (thisLine.ToLower().StartsWith("[speech]"))
                {
                    inMainSection = true;
                    continue;
                }
                if (inMainSection)
                {
                    if (thisLine.TrimStart().StartsWith("["))
                    {
                        // moved onto another section
                        break;
                    }
                    if (thisLine.IndexOf(':') > 0)
                    {
                        string[] parts = thisLine.Split(':');
                        int      part0;
                        // Convert from Pamela XPOS into milliseconds
                        if (!Int32.TryParse(parts[0], out part0))
                        {
                            string friendlyFileName = Path.GetFileName(fileName);
                            errors.Add(new CompileError("Non-numeric phoneme offset '" + parts[0] + "'", friendlyFileName, lineNumber));
                            continue;
                        }
                        int    milliSeconds = ((part0 / 15) * 1000) / 24;
                        string phonemeCode  = parts[1].Trim().ToUpper();
                        int    frameID      = FindFrameNumberForPhoneme(phonemeCode);
                        if (frameID < 0)
                        {
                            string friendlyFileName = Path.GetFileName(fileName);
                            errors.Add(new CompileError("No frame found to match phoneme code '" + phonemeCode + "'", friendlyFileName, lineNumber));
                        }
                        else
                        {
                            syncDataForThisFile.Phonemes.Add(new SpeechLipSyncPhoneme(milliSeconds, (short)frameID));
                        }
                    }
                }
            }
            sr.Close();
            AlignPhonemeOffsets(syncDataForThisFile);

            return(syncDataForThisFile);
        }
Esempio n. 4
0
        /// <summary>
        /// /// <summary>
        /// Creates a list of custom game resources as a list of tuples.
        /// </summary>
        /// <returns>
        /// - first tuple's element is resource's name,
        /// - second is real file path
        /// </returns>
        private Tuple <string, string>[] ConstructCustomFileListForDataFile(CompileMessages errors)
        {
            string userOpt = Factory.AGSEditor.CurrentGame.Settings.CustomDataDir;

            if (string.IsNullOrEmpty(userOpt))
            {
                return(Enumerable.Empty <Tuple <string, string> >().ToArray());
            }

            string curDir = Factory.AGSEditor.CurrentGame.DirectoryPath;

            string[] restrictedDirs = Factory.AGSEditor.RestrictedGameDirectories.
                                      Select(d => Path.Combine(curDir, d)).ToArray();

            List <string> userFiles = new List <string>();

            string[] user_dirs = userOpt.Split(',');
            Array.Sort(user_dirs);
            List <string> usedCustomDirs = new List <string>();

            foreach (var dir in user_dirs)
            {
                // don't allow absolute paths
                if (Path.IsPathRooted(dir))
                {
                    errors.Add(new CompileWarning(
                                   string.Format("Cannot use absolute path as a custom data source: {0}", dir)));
                    continue;
                }
                // don't allow paths with "." or ".." in them
                if (Utilities.DoesPathContainDotDirs(dir))
                {
                    errors.Add(new CompileWarning(
                                   string.Format("Cannot use path containing '.' or '..' as a custom data source: {0}", dir)));
                    continue;
                }
                // don't allow paths that match or inside restricted folders,
                // or folders that were already used to make a list of assets
                string testDir = Path.Combine(curDir, dir);
                if (Utilities.PathIsSameOrNestedAmong(testDir, restrictedDirs))
                {
                    errors.Add(new CompileWarning(
                                   string.Format("Cannot use restricted location as a custom data source: {0}", dir)));
                    continue;
                }
                if (Utilities.PathIsSameOrNestedAmong(testDir, usedCustomDirs))
                {
                    continue; // don't report, simply skip
                }
                Utilities.AddAllMatchingFiles(userFiles, dir, "*", true, SearchOption.AllDirectories);
                usedCustomDirs.Add(Path.Combine(curDir, dir));
            }

            // User files are registered under their relative paths
            return(userFiles.Select(f => new Tuple <string, string>(f, f)).ToArray());
        }
Esempio n. 5
0
        private void CompileTranslation(Translation translation, CompileMessages errors)
        {
            translation.LoadData();

            if (translation.TranslatedLines.Count < 1)
            {
                errors.Add(new CompileError("Translation " + translation.FileName + " appears to be empty. You must update the source before compiling.", translation.FileName, 1));
                return;
            }

            string compiledFile = Path.Combine(AGSEditor.OUTPUT_DIRECTORY,
                                               Path.Combine(AGSEditor.DATA_OUTPUT_DIRECTORY, translation.CompiledFileName));
            bool foundTranslatedLine = false;

            using (BinaryWriter bw = new BinaryWriter(new FileStream(compiledFile, FileMode.Create, FileAccess.Write)))
            {
                bw.Write(Encoding.ASCII.GetBytes(COMPILED_TRANSLATION_FILE_SIGNATURE));
                bw.Write(TRANSLATION_BLOCK_GAME_ID);
                byte[] gameName = Factory.NativeProxy.TransformStringToBytes(_agsEditor.CurrentGame.Settings.GameName);
                bw.Write(gameName.Length + 4);
                bw.Write(_agsEditor.CurrentGame.Settings.UniqueID);
                bw.Write(gameName);
                bw.Write(TRANSLATION_BLOCK_TRANSLATION_DATA);
                long offsetOfBlockSize = bw.BaseStream.Position;
                bw.Write((int)0);
                foreach (string line in translation.TranslatedLines.Keys)
                {
                    if (translation.TranslatedLines[line].Length > 0)
                    {
                        foundTranslatedLine = true;
                        bw.Write(Factory.NativeProxy.TransformStringToBytes(ConvertEscapedCharacters(line)));
                        bw.Write(Factory.NativeProxy.TransformStringToBytes(ConvertEscapedCharacters(translation.TranslatedLines[line])));
                    }
                }
                bw.Write(Factory.NativeProxy.TransformStringToBytes(string.Empty));
                bw.Write(Factory.NativeProxy.TransformStringToBytes(string.Empty));
                long mainBlockSize = (bw.BaseStream.Position - offsetOfBlockSize) - 4;
                bw.Write(TRANSLATION_BLOCK_OPTIONS);
                bw.Write((int)12);
                bw.Write(translation.NormalFont ?? -1);
                bw.Write(translation.SpeechFont ?? -1);
                bw.Write((translation.RightToLeftText == true) ? 2 : ((translation.RightToLeftText == false) ? 1 : -1));
                bw.Write(TRANSLATION_BLOCK_END_OF_FILE);
                bw.Write((int)0);
                bw.Seek((int)offsetOfBlockSize, SeekOrigin.Begin);
                bw.Write((int)mainBlockSize);
                bw.Close();
            }

            if (!foundTranslatedLine)
            {
                errors.Add(new CompileError("Translation " + translation.FileName + " did not appear to have any translated lines. Make sure you translate some text before compiling the translation.", translation.FileName, 1));
                File.Delete(compiledFile);
            }
        }
Esempio n. 6
0
        private SpeechLipSyncLine CompilePapagayoFile(string fileName, CompileMessages errors)
        {
            SpeechLipSyncLine syncDataForThisFile = new SpeechLipSyncLine();

            syncDataForThisFile.FileName = Path.GetFileNameWithoutExtension(fileName);

            string thisLine;
            int    lineNumber = 0;

            StreamReader sr = new StreamReader(fileName);

            if ((thisLine = sr.ReadLine()) != null) // Skip over the first line (always a heading)
            {
                while ((thisLine = sr.ReadLine()) != null)
                {
                    lineNumber++;
                    if (thisLine.IndexOf(' ') > 0)
                    {
                        string[] parts = thisLine.Split(' ');
                        int      part0;
                        if (!Int32.TryParse(parts[0], out part0))
                        {
                            string friendlyFileName = Path.GetFileName(fileName);
                            errors.Add(new CompileError("Non-numeric phoneme offset '" + parts[0] + "'", friendlyFileName, lineNumber));
                            continue;
                        }
                        int xpos = part0;
                        if (xpos < 0) // Clamp negative XPOS to 0
                        {
                            xpos = 0;
                        }
                        int    milliSeconds = (part0 * 1000) / 24;
                        string phonemeCode  = parts[1].Trim().ToUpper();
                        int    frameID      = FindFrameNumberForPhoneme(phonemeCode);
                        if (frameID < 0)
                        {
                            string friendlyFileName = Path.GetFileName(fileName);
                            errors.Add(new CompileError("No frame found to match phoneme code '" + phonemeCode + "'", friendlyFileName, lineNumber));
                        }
                        else
                        {
                            syncDataForThisFile.Phonemes.Add(new SpeechLipSyncPhoneme(milliSeconds, (short)frameID));
                        }
                    }
                }
            }
            sr.Close();
            AlignPhonemeOffsets(syncDataForThisFile);

            return(syncDataForThisFile);
        }
Esempio n. 7
0
        private string ProcessScript(string script)
        {
            int index = 0;

            while (index < script.Length)
            {
                index = SkipComments(script, index);

                if ((index < script.Length) &&
                    ((script[index] == '"') || (script[index] == '\'')))
                {
                    char stringTerminator = script[index];
                    int  stringStartIndex = index;
                    index++;
                    while (index < script.Length)
                    {
                        if (DoesStringTerminateHere(script, index, stringTerminator))
                        {
                            break;
                        }
                        index++;
                    }
                    if (index >= script.Length)
                    {
                        _errors.Add(new CompileError("Unterminated string in script: " + script.Substring(stringStartIndex)));
                        return(script);
                    }

                    if (stringTerminator == '"')
                    {
                        int    stringEndIndex   = index;
                        string previousFuncCall = GetPreviousCharacters(script, stringStartIndex - 1);
                        int    charID           = ParseFunctionCallAndFindCharacterID(previousFuncCall);
                        if (charID >= 0)
                        {
                            string scriptBeforeString = script.Substring(0, stringStartIndex + 1);
                            string scriptAfterString  = script.Substring(stringEndIndex);
                            string mainString         = script.Substring(stringStartIndex + 1, (stringEndIndex - stringStartIndex) - 1);
                            string modifiedString     = CreateSpeechLine(charID, mainString);
                            script = scriptBeforeString + modifiedString + scriptAfterString;
                            index  = stringStartIndex + modifiedString.Length + 1;
                        }
                    }
                }
                index++;
            }
            return(script);
        }
Esempio n. 8
0
        public override bool Build(CompileMessages errors, bool forceRebuild)
        {
            if (!base.Build(errors, forceRebuild))
            {
                return(false);
            }
            string compiledDataDir  = Path.Combine(AGSEditor.OUTPUT_DIRECTORY, AGSEditor.DATA_OUTPUT_DIRECTORY);
            string baseGameFileName = Factory.AGSEditor.BaseGameFileName;
            string newExeName       = GetCompiledPath(baseGameFileName + ".exe");
            string sourceEXE        = Path.Combine(Factory.AGSEditor.EditorDirectory, AGSEditor.ENGINE_EXE_FILE_NAME);

            File.Copy(sourceEXE, newExeName, true);
            UpdateWindowsEXE(newExeName, errors);
            CreateCompiledSetupProgram();
            Environment.CurrentDirectory = Factory.AGSEditor.CurrentGame.DirectoryPath;
            string mainGameData = Path.Combine(compiledDataDir, baseGameFileName + ".ags");

            if (File.Exists(mainGameData))
            {
                AttachDataToEXE(mainGameData, newExeName);
            }
            else
            {
                errors.Add(new CompileError(String.Format("Unable to locate main game data file at '{0}'", mainGameData)));
            }
            CopyAuxiliaryGameFiles(compiledDataDir, true);
            // Update config file with current game parameters
            Factory.AGSEditor.WriteConfigFile(GetCompiledPath());
            // Copy Windows plugins
            CopyPlugins(errors);
            return(true);
        }
Esempio n. 9
0
        public void ConvertDialogScriptToRealScript(Dialog dialog, Game game, CompileMessages errors)
        {
            string thisLine;
            _currentlyInsideCodeArea = false;
            _hadFirstEntryPoint = false;
            _game = game;
            _currentDialog = dialog;
            _existingEntryPoints.Clear();
            _currentLineNumber = 0;

            StringReader sr = new StringReader(dialog.Script);
            StringWriter sw = new StringWriter();
            sw.Write(string.Format("function _run_dialog{0}(int entryPoint) {1} ", dialog.ID, "{"));
            while ((thisLine = sr.ReadLine()) != null)
            {
                _currentLineNumber++;
                try
                {
                    ConvertDialogScriptLine(thisLine, sw, errors);
                }
                catch (CompileMessage ex)
                {
                    errors.Add(ex);
                }
            }
            if (_currentlyInsideCodeArea)
            {
                sw.WriteLine("}");
            }
            sw.WriteLine("return RUN_DIALOG_RETURN; }"); // end the function
            dialog.CachedConvertedScript = sw.ToString();
            sw.Close();
            sr.Close();
        }
Esempio n. 10
0
        public CompileMessages NumberSpeechLines(Game game, bool includeNarrator, bool combineIdenticalLines, bool removeNumbering, int? characterID)
        {
            _speechableFunctionCalls = GetFunctionCallsToProcessForSpeech(includeNarrator);

            _errors = new CompileMessages();
            _game = game;
            _includeNarrator = includeNarrator;
            _combineIdenticalLines = combineIdenticalLines;
            _removeNumbering = removeNumbering;
            _characterID = characterID;

            if (Factory.AGSEditor.AttemptToGetWriteAccess(SPEECH_REFERENCE_FILE_NAME))
            {
                using (_referenceFile = new StreamWriter(SPEECH_REFERENCE_FILE_NAME, false))
                {
                    _referenceFile.WriteLine("// AGS auto-numbered speech lines output. This file was automatically generated.");
                    PerformNumbering(game);
                }
            }
            else
            {
                _errors.Add(new CompileError("unable to create file " + SPEECH_REFERENCE_FILE_NAME));
            }

            return _errors;
        }
Esempio n. 11
0
        public CompileMessages NumberSpeechLines(Game game, bool includeNarrator, bool combineIdenticalLines, bool removeNumbering, int?characterID)
        {
            _speechableFunctionCalls = GetFunctionCallsToProcessForSpeech(includeNarrator);

            _errors                = new CompileMessages();
            _game                  = game;
            _includeNarrator       = includeNarrator;
            _combineIdenticalLines = combineIdenticalLines;
            _removeNumbering       = removeNumbering;
            _characterID           = characterID;

            if (Factory.AGSEditor.AttemptToGetWriteAccess(SPEECH_REFERENCE_FILE_NAME))
            {
                using (_referenceFile = new StreamWriter(SPEECH_REFERENCE_FILE_NAME, false))
                {
                    _referenceFile.WriteLine("// AGS auto-numbered speech lines output. This file was automatically generated.");
                    PerformNumbering(game);
                }
            }
            else
            {
                _errors.Add(new CompileError("unable to create file " + SPEECH_REFERENCE_FILE_NAME));
            }

            return(_errors);
        }
Esempio n. 12
0
        public override bool Build(CompileMessages errors, bool forceRebuild)
        {
            if (!base.Build(errors, forceRebuild))
            {
                return(false);
            }
            Factory.AGSEditor.SetMODMusicFlag();
            DeleteAnyExistingSplitResourceFiles();
            if (!DataFileWriter.SaveThisGameToFile(AGSEditor.COMPILED_DTA_FILE_NAME, Factory.AGSEditor.CurrentGame, errors))
            {
                return(false);
            }
            string errorMsg = DataFileWriter.MakeDataFile(ConstructFileListForDataFile(errors),
                                                          Factory.AGSEditor.CurrentGame.Settings.SplitResources * 1000000,
                                                          Factory.AGSEditor.BaseGameFileName, true);

            if (errorMsg != null)
            {
                errors.Add(new CompileError(errorMsg));
            }
            File.Delete(AGSEditor.COMPILED_DTA_FILE_NAME);
            CreateAudioVOXFile(forceRebuild);
            // Update config file with current game parameters
            Factory.AGSEditor.WriteConfigFile(GetCompiledPath());
            return(true);
        }
Esempio n. 13
0
        private bool IsProjectSane(CompileMessages errors)
        {
            foreach (string error in AndroidUtilities.GetPreferencesErrors())
            {
                errors.Add(new CompileError("Android Build: " + error));
            }

            return(errors.Count == 0);
        }
Esempio n. 14
0
 public virtual bool Build(CompileMessages errors, bool forceRebuild)
 {
     if (!IsAvailable)
     {
         errors.Add(new CompileError("Could not build target platform " + Name + ", because the file '" +
                                     missingFile + "' is unavailable."));
         return(false);
     }
     EnsureStandardSubfoldersExist();
     return(true);
 }
 /// <summary>
 /// Displays the wizard to collect metadata needed to build for Android.
 /// </summary>
 private bool CollectMetadata(CompileMessages errors)
 {
     AndroidBuilderPane.Instance.CheckForErrors();
     if (AndroidBuilderPane.Errors.Count == 0)
     {
         return(true);
     }
     foreach (string error in AndroidBuilderPane.Errors)
     {
         errors.Add(new CompileError("Android build error: " + error));
     }
     AndroidBuilderPlugin.AGSEditor.GUIController.AddOrShowPane(AndroidBuilderPlugin.Pane);
     return(false);
 }
Esempio n. 16
0
 public override bool Build(CompileMessages errors, bool forceRebuild)
 {
     if (!base.Build(errors, forceRebuild)) return false;
     try
     {
         string baseGameFileName = Factory.AGSEditor.BaseGameFileName;
         string exeFileName = baseGameFileName + ".exe";
         IBuildTarget targetWin = BuildTargetsInfo.FindBuildTargetByName("Windows");
         if (targetWin == null)
         {
             errors.Add(new CompileError("Debug build depends on Windows build target being available! Your AGS installation may be corrupted!"));
             return false;
         }
         string compiledEXE = targetWin.GetCompiledPath(exeFileName);
         string sourceEXE = Path.Combine(Factory.AGSEditor.EditorDirectory, AGSEditor.ENGINE_EXE_FILE_NAME);
         Utilities.DeleteFileIfExists(compiledEXE);
         File.Copy(sourceEXE, exeFileName, true);
         BusyDialog.Show("Please wait while we prepare to run the game...", new BusyDialog.ProcessingHandler(CreateDebugFiles), errors);
         if (errors.HasErrors)
         {
             return false;
         }
         Utilities.DeleteFileIfExists(GetDebugPath(exeFileName));
         File.Move(exeFileName, GetDebugPath(exeFileName));
         // copy configuration from Compiled folder to use with Debugging
         string cfgFilePath = targetWin.GetCompiledPath(AGSEditor.CONFIG_FILE_NAME);
         if (File.Exists(cfgFilePath))
         {
             File.Copy(cfgFilePath, GetDebugPath(AGSEditor.CONFIG_FILE_NAME), true);
         }
         else
         {
             cfgFilePath = Path.Combine(AGSEditor.OUTPUT_DIRECTORY, Path.Combine(AGSEditor.DATA_OUTPUT_DIRECTORY, AGSEditor.CONFIG_FILE_NAME));
             if (File.Exists(cfgFilePath))
             {
                 File.Copy(cfgFilePath, GetDebugPath(AGSEditor.CONFIG_FILE_NAME), true);
             }
         }
         foreach (Plugin plugin in Factory.AGSEditor.CurrentGame.Plugins)
         {
             File.Copy(Path.Combine(Factory.AGSEditor.EditorDirectory, plugin.FileName), GetDebugPath(plugin.FileName), true);
         }
     }
     catch (Exception ex)
     {
         errors.Add(new CompileError("Unexpected error: " + ex.Message));
         return false;
     }
     return true;
 }
Esempio n. 17
0
 public void CopyPlugins(CompileMessages errors)
 {
     try
     {
         string outputDir = GetCompiledPath();
         foreach (Plugin plugin in Factory.AGSEditor.CurrentGame.Plugins)
         {
             File.Copy(Path.Combine(Factory.AGSEditor.EditorDirectory, plugin.FileName), Path.Combine(outputDir, plugin.FileName), true);
         }
     }
     catch (Exception ex)
     {
         errors.Add(new CompileError("Unexpected error: " + ex.Message));
     }
 }
        /// <summary>
        /// Deploy the APK to RELEASE_DIR.
        /// </summary>
        private bool DeployApk(CompileMessages errors)
        {
            string apk = GetCompiledPath(STUDIO_PROJECT_DIR, "app", "build", "outputs", "apk", "app-release.apk");

            if (File.Exists(apk))
            {
                File.Copy(apk, GetCompiledPath(RELEASE_DIR, AndroidMetadata.APKName), true);
                return(true);
            }
            else
            {
                errors.Add(new CompileError("APK not found in expected location! Do not move or delete files during building!"));
                return(false);
            }
        }
Esempio n. 19
0
 public override bool Build(CompileMessages errors, bool forceRebuild)
 {
     if (!base.Build(errors, forceRebuild))
     {
         return(false);
     }
     try
     {
         string baseGameFileName = Factory.AGSEditor.BaseGameFileName;
         string exeFileName      = baseGameFileName + ".exe";
         string compiledEXE      = Path.Combine(Path.Combine(AGSEditor.OUTPUT_DIRECTORY,
                                                             BuildTargetWindows.WINDOWS_DIRECTORY), exeFileName);
         string sourceEXE = Path.Combine(Factory.AGSEditor.EditorDirectory, AGSEditor.ENGINE_EXE_FILE_NAME);
         Utilities.DeleteFileIfExists(compiledEXE);
         File.Copy(sourceEXE, exeFileName, true);
         BusyDialog.Show("Please wait while we prepare to run the game...", new BusyDialog.ProcessingHandler(CreateDebugFiles), errors);
         if (errors.HasErrors)
         {
             return(false);
         }
         Utilities.DeleteFileIfExists(GetDebugPath(exeFileName));
         File.Move(exeFileName, GetDebugPath(exeFileName));
         // copy configuration from Compiled folder to use with Debugging
         string cfgFilePath = Path.Combine(AGSEditor.OUTPUT_DIRECTORY, AGSEditor.CONFIG_FILE_NAME);
         if (!Factory.AGSEditor.Preferences.UseLegacyCompiler)
         {
             IBuildTarget targetWin = BuildTargetsInfo.FindBuildTargetByName("Windows");
             if (targetWin != null)
             {
                 cfgFilePath = targetWin.GetCompiledPath(AGSEditor.OUTPUT_DIRECTORY, AGSEditor.CONFIG_FILE_NAME);
             }
         }
         if (File.Exists(cfgFilePath))
         {
             File.Copy(cfgFilePath, GetDebugPath(AGSEditor.CONFIG_FILE_NAME), true);
         }
         foreach (Plugin plugin in Factory.AGSEditor.CurrentGame.Plugins)
         {
             File.Copy(Path.Combine(Factory.AGSEditor.EditorDirectory, plugin.FileName), GetDebugPath(plugin.FileName), true);
         }
     }
     catch (Exception ex)
     {
         errors.Add(new CompileError("Unexpected error: " + ex.Message));
         return(false);
     }
     return(true);
 }
Esempio n. 20
0
        private void UpdateAllTranslationsWithNewDefaultText(Dictionary <string, string> textChanges, CompileMessages errors)
        {
            foreach (Translation otherTranslation in _agsEditor.CurrentGame.Translations)
            {
                otherTranslation.LoadData();
                Dictionary <string, string> newTranslation = new Dictionary <string, string>();

                foreach (string sourceLine in otherTranslation.TranslatedLines.Keys)
                {
                    string otherTranslationOfThisLine = otherTranslation.TranslatedLines[sourceLine];
                    string newKeyName = null;
                    if ((textChanges.ContainsKey(sourceLine)) && (textChanges[sourceLine].Length > 0))
                    {
                        newKeyName = textChanges[sourceLine];

                        if (newTranslation.ContainsKey(newKeyName))
                        {
                            if (!string.IsNullOrEmpty(otherTranslationOfThisLine))
                            {
                                errors.Add(new CompileWarning("Text '" + newKeyName + "' already has a translation; '" + sourceLine + "' translation will be lost"));
                            }
                            newKeyName = null;
                        }
                    }
                    else if (!newTranslation.ContainsKey(sourceLine))
                    {
                        newKeyName = sourceLine;
                    }

                    if (newKeyName != null)
                    {
                        if (newKeyName == otherTranslationOfThisLine)
                        {
                            newTranslation.Add(newKeyName, string.Empty);
                        }
                        else
                        {
                            newTranslation.Add(newKeyName, otherTranslationOfThisLine);
                        }
                    }
                }

                otherTranslation.TranslatedLines = newTranslation;
                otherTranslation.Modified        = true;
                otherTranslation.SaveData();
            }
        }
Esempio n. 21
0
        public void ConvertDialogScriptToRealScript(Dialog dialog, Game game, CompileMessages errors)
        {
            string thisLine;

            _currentlyInsideCodeArea = false;
            _hadFirstEntryPoint      = false;
            _game      = game;
            _sayFnName = game.Settings.DialogScriptSayFunction;
            if (string.IsNullOrWhiteSpace(_sayFnName))
            {
                _sayFnName = "Say";
            }
            _narrateFnName = game.Settings.DialogScriptNarrateFunction;
            if (string.IsNullOrWhiteSpace(_narrateFnName))
            {
                _narrateFnName = "Display";
            }
            _currentDialog = dialog;
            _existingEntryPoints.Clear();
            _currentLineNumber = 0;

            StringReader sr = new StringReader(dialog.Script);
            StringWriter sw = new StringWriter();

            sw.Write(string.Format("function _run_dialog{0}(int entryPoint) {1} ", dialog.ID, "{"));
            while ((thisLine = sr.ReadLine()) != null)
            {
                _currentLineNumber++;
                try
                {
                    ConvertDialogScriptLine(thisLine, sw, errors);
                }
                catch (CompileMessage ex)
                {
                    errors.Add(ex);
                }
            }
            if (_currentlyInsideCodeArea)
            {
                sw.WriteLine("}");
            }
            sw.WriteLine("return RUN_DIALOG_RETURN; }"); // end the function
            dialog.CachedConvertedScript = sw.ToString();
            sw.Close();
            sr.Close();
        }
Esempio n. 22
0
 public override bool Build(CompileMessages errors, bool forceRebuild)
 {
     if (!base.Build(errors, forceRebuild))
     {
         return(false);
     }
     Factory.AGSEditor.SetMODMusicFlag();
     DeleteAnyExistingSplitResourceFiles();
     if (Factory.AGSEditor.Preferences.UseLegacyCompiler)
     {
         Factory.NativeProxy.CompileGameToDTAFile(Factory.AGSEditor.CurrentGame, AGSEditor.COMPILED_DTA_FILE_NAME);
         // if using the legacy compiler, make sure engine EXE is copied before calling CreateGameEXE
         string newExeName = GetCompiledPath(Factory.AGSEditor.BaseGameFileName + ".exe");
         string sourceEXE  = Path.Combine(Factory.AGSEditor.EditorDirectory, AGSEditor.ENGINE_EXE_FILE_NAME);
         File.Copy(sourceEXE, newExeName, true);
         BuildTargetWindows targetWindows = (BuildTargetsInfo.FindBuildTargetByName("Windows") as BuildTargetWindows);
         // updating the Vista game explorer resources after the EXE is fully created is deleting the data file,
         // corrupting the game resources
         targetWindows.UpdateWindowsEXE(newExeName, errors);
         // the above all needs to be done here anyway, so finish up by creating the setup EXE and copying plugins
         targetWindows.CreateCompiledSetupProgram();
         targetWindows.CopyPlugins(errors);
         Factory.NativeProxy.CreateGameEXE(ConstructFileListForDataFile(), Factory.AGSEditor.CurrentGame, Factory.AGSEditor.BaseGameFileName);
     }
     else
     {
         if (!DataFileWriter.SaveThisGameToFile(AGSEditor.COMPILED_DTA_FILE_NAME, Factory.AGSEditor.CurrentGame, errors))
         {
             return(false);
         }
         string errorMsg = DataFileWriter.MakeDataFile(ConstructFileListForDataFile(), Factory.AGSEditor.CurrentGame.Settings.SplitResources * 1000000,
                                                       Factory.AGSEditor.BaseGameFileName, true);
         if (errorMsg != null)
         {
             errors.Add(new CompileError(errorMsg));
         }
     }
     File.Delete(AGSEditor.COMPILED_DTA_FILE_NAME);
     CreateAudioVOXFile(forceRebuild);
     // Update config file with current game parameters
     Factory.AGSEditor.WriteConfigFile(AGSEditor.OUTPUT_DIRECTORY);
     return(true);
 }
        /// <summary>
        /// Extract launcher icons from zip to disk.
        /// </summary>
        private bool ExtractLauncherIcons(CompileMessages errors)
        {
            if (string.IsNullOrEmpty(AndroidMetadata.LauncherIconsZip))
            {
                errors.Add(new CompileError("Launcher icons must be provided to build for Android. Consider using the Android Asset Studio if you need to generate launcher icons."));
                return(false);
            }
            string rootDir = GetCompiledPath(STUDIO_PROJECT_DIR, "app", "src", "main");

            using (ZipStorer zip = ZipStorer.Open(AndroidMetadata.LauncherIconsZip, FileAccess.Read))
            {
                List <ZipStorer.ZipFileEntry> files = zip.ReadCentralDir();
                foreach (ZipStorer.ZipFileEntry entry in files)
                {
                    zip.ExtractFile(entry, Path.Combine(rootDir, entry.FilenameInZip));
                }
            }
            return(true);
        }
 private bool CopyLibrariesToAndroidStudioProject(CompileMessages errors)
 {
     foreach (KeyValuePair <string, string> kvPair in GetRequiredLibraryPaths())
     {
         string library = kvPair.Value.EndsWith(kvPair.Key) ? kvPair.Value : Path.Combine(kvPair.Value, kvPair.Key);
         try
         {
             string destPath = GetCompiledPath(STUDIO_PROJECT_DIR, LIBS_DIR, kvPair.Key);
             Directory.CreateDirectory(Path.GetDirectoryName(destPath));
             File.Copy(library, destPath, true);
         }
         catch (System.Exception e)
         {
             errors.Add(new CompileError("Error copying Android library file '" + kvPair.Key + "':" + System.Environment.NewLine + e.Message));
             return(false);
         }
     }
     return(true);
 }
Esempio n. 25
0
 public override bool Build(CompileMessages errors, bool forceRebuild)
 {
     if (!base.Build(errors, forceRebuild)) return false;
     Factory.AGSEditor.SetMODMusicFlag();
     DeleteAnyExistingSplitResourceFiles();
     if (!DataFileWriter.SaveThisGameToFile(AGSEditor.COMPILED_DTA_FILE_NAME, Factory.AGSEditor.CurrentGame, errors))
     {
         return false;
     }
     string errorMsg = DataFileWriter.MakeDataFile(ConstructFileListForDataFile(), Factory.AGSEditor.CurrentGame.Settings.SplitResources * 1000000,
         Factory.AGSEditor.BaseGameFileName, true);
     if (errorMsg != null)
     {
         errors.Add(new CompileError(errorMsg));
     }
     File.Delete(AGSEditor.COMPILED_DTA_FILE_NAME);
     CreateAudioVOXFile(forceRebuild);
     // Update config file with current game parameters
     Factory.AGSEditor.WriteConfigFile(GetCompiledPath());
     return true;
 }
Esempio n. 26
0
        public CompileMessages CompileGame(bool forceRebuild, bool createMiniExeForDebug)
        {
            Factory.GUIController.ClearOutputPanel();
            CompileMessages errors = new CompileMessages();

            Utilities.EnsureStandardSubFoldersExist();

            if (PreCompileGame != null)
            {
                PreCompileGameEventArgs evArgs = new PreCompileGameEventArgs(forceRebuild);
                evArgs.Errors = errors;

                PreCompileGame(evArgs);

                if (!evArgs.AllowCompilation)
                {
                    Factory.GUIController.ShowOutputPanel(errors);
                    ReportErrorsIfAppropriate(errors);
                    return errors;
                }
            }

            RunPreCompilationChecks(errors);

            if (!errors.HasErrors)
            {
                CompileMessage result = (CompileMessage)BusyDialog.Show("Patientez durant la compilation du script...", new BusyDialog.ProcessingHandler(CompileScripts), new CompileScriptsParameters(errors, forceRebuild));
                if (result != null)
                {
                    errors.Add(result);
                }
                else if (!errors.HasErrors)
                {
                    string sourceEXE = Path.Combine(this.EditorDirectory, ENGINE_EXE_FILE_NAME);
                    if (!File.Exists(sourceEXE))
                    {
                        errors.Add(new CompileError("Fichier '" + sourceEXE + "' introuvable. La compilation du jeu requiert la présence de ce fichier."));
                    }
                    else if (createMiniExeForDebug)
                    {
                        CreateMiniEXEForDebugging(sourceEXE, errors);
                    }
                    else
                    {
                        CreateCompiledFiles(sourceEXE, errors, forceRebuild);
                    }
                }
            }

            Factory.GUIController.ShowOutputPanel(errors);

            ReportErrorsIfAppropriate(errors);

            return errors;
        }
Esempio n. 27
0
        public CompileMessages CompileGame(bool forceRebuild, bool createMiniExeForDebug)
        {
            Factory.GUIController.ClearOutputPanel();
            CompileMessages errors = new CompileMessages();

            Utilities.EnsureStandardSubFoldersExist();

            if (PreCompileGame != null)
            {
                PreCompileGameEventArgs evArgs = new PreCompileGameEventArgs(forceRebuild);
                evArgs.Errors = errors;

                PreCompileGame(evArgs);

                if (!evArgs.AllowCompilation)
                {
                    Factory.GUIController.ShowOutputPanel(errors);
                    ReportErrorsIfAppropriate(errors);
                    return errors;
                }
            }

            RunPreCompilationChecks(errors);

            if (!errors.HasErrors)
            {
                CompileMessage result = (CompileMessage)BusyDialog.Show("Please wait while your scripts are compiled...", new BusyDialog.ProcessingHandler(CompileScripts), new CompileScriptsParameters(errors, forceRebuild));
                if (result != null)
                {
                    errors.Add(result);
                }
                else if (!errors.HasErrors)
                {
                    if (createMiniExeForDebug)
                    {
                        CreateMiniEXEForDebugging(errors);
                    }
                    else
                    {
                        CreateCompiledFiles(errors, forceRebuild);
                    }
                }
            }

            Factory.GUIController.ShowOutputPanel(errors);

            ReportErrorsIfAppropriate(errors);

            return errors;
        }
Esempio n. 28
0
 private void CreateCompiledFiles(CompileMessages errors, bool forceRebuild)
 {
     try
     {
         BusyDialog.Show("Please wait while your game is created...", new BusyDialog.ProcessingHandler(CreateCompiledFiles), new CompileScriptsParameters(errors, forceRebuild));
     }
     catch (Exception ex)
     {
         errors.Add(new CompileError("Unexpected error: " + ex.Message));
     }
 }
Esempio n. 29
0
        private void UpdateAllTranslationsWithNewDefaultText(Dictionary<string, string> textChanges, CompileMessages errors)
        {
            foreach (Translation otherTranslation in _agsEditor.CurrentGame.Translations)
            {
                otherTranslation.LoadData();
                Dictionary<string, string> newTranslation = new Dictionary<string, string>();

                foreach (string sourceLine in otherTranslation.TranslatedLines.Keys)
                {
                    string otherTranslationOfThisLine = otherTranslation.TranslatedLines[sourceLine];
                    string newKeyName = null;
                    if ((textChanges.ContainsKey(sourceLine)) && (textChanges[sourceLine].Length > 0))
                    {
                        newKeyName = textChanges[sourceLine];

                        if (newTranslation.ContainsKey(newKeyName))
                        {
                            if (!string.IsNullOrEmpty(otherTranslationOfThisLine))
                            {
                                errors.Add(new CompileWarning("Text '" + newKeyName + "' already has a translation; '" + sourceLine + "' translation will be lost"));
                            }
                            newKeyName = null;
                        }
                    }
                    else if (!newTranslation.ContainsKey(sourceLine))
                    {
                        newKeyName = sourceLine;
                    }

                    if (newKeyName != null)
                    {
                        if (newKeyName == otherTranslationOfThisLine)
                        {
                            newTranslation.Add(newKeyName, string.Empty);
                        }
                        else
                        {
                            newTranslation.Add(newKeyName, otherTranslationOfThisLine);
                        }
                    }
                }

                otherTranslation.TranslatedLines = newTranslation;
                otherTranslation.Modified = true;
                otherTranslation.SaveData();
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Creates a mini-exe that only contains the GAME.DTA file,
        /// in order to improve compile speed.
        /// All other files will be sourced from the game folder.
        /// </summary>
        private void CreateMiniEXEForDebugging(string sourceEXE, CompileMessages errors)
        {
            try
            {
                if (!Directory.Exists(DEBUG_OUTPUT_DIRECTORY))
                {
                    Directory.CreateDirectory(DEBUG_OUTPUT_DIRECTORY);
                }
                Utilities.DeleteFileIfExists(this.CompiledEXEFileName);
                File.Copy(sourceEXE, this.BaseGameFileName + ".exe", true);

                BusyDialog.Show("Please wait while we prepare to run the game...", new BusyDialog.ProcessingHandler(CreateDebugFiles), null);

                Utilities.DeleteFileIfExists(this.DebugEXEFileName);
                File.Move(this.BaseGameFileName + ".exe", this.DebugEXEFileName);

                // copy configuration from Compiled folder to use with Debugging
                string cfgFilePath = Path.Combine(OUTPUT_DIRECTORY, CONFIG_FILE_NAME);
                if (File.Exists(cfgFilePath))
                {
                    File.Copy(cfgFilePath, Path.Combine(DEBUG_OUTPUT_DIRECTORY, CONFIG_FILE_NAME), true);
                }

                foreach (Plugin plugin in _game.Plugins)
                {
                    File.Copy(Path.Combine(this.EditorDirectory, plugin.FileName), DEBUG_OUTPUT_DIRECTORY + "\\" + plugin.FileName, true);
                }
            }
            catch (Exception ex)
            {
                errors.Add(new CompileError("Unexpected error: " + ex.Message));
            }
        }
Esempio n. 31
0
 private void RaiseDialogScriptCompileWarning(string errorMsg, CompileMessages errors)
 {
     errors.Add(new CompileWarning(errorMsg, "Dialog " + _currentDialog.ID, _currentLineNumber));
 }
Esempio n. 32
0
        public override bool Build(CompileMessages errors, bool forceRebuild)
        {
            if (!base.Build(errors, forceRebuild))
            {
                return(false);
            }
            if (!CheckPluginsHaveSharedLibraries())
            {
                errors.Add(new CompileError("Could not build for Linux due to missing plugins."));
                return(false);
            }
            foreach (string fileName in Directory.GetFiles(Path.Combine(AGSEditor.OUTPUT_DIRECTORY, AGSEditor.DATA_OUTPUT_DIRECTORY)))
            {
                if ((File.GetAttributes(fileName) & (FileAttributes.Hidden | FileAttributes.System | FileAttributes.Temporary)) != 0)
                {
                    continue;
                }
                if ((!fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) &&
                    (!Path.GetFileName(fileName).Equals("winsetup.exe", StringComparison.OrdinalIgnoreCase)) &&
                    (!Path.GetFileName(fileName).Equals(AGSEditor.CONFIG_FILE_NAME, StringComparison.OrdinalIgnoreCase)))
                {
                    Utilities.HardlinkOrCopy(GetCompiledPath(LINUX_DATA_DIR, Path.GetFileName(fileName)), fileName, true);
                }
            }
            // Update config file with current game parameters
            Factory.AGSEditor.WriteConfigFile(GetCompiledPath(LINUX_DATA_DIR));

            foreach (KeyValuePair <string, string> pair in GetRequiredLibraryPaths())
            {
                string fileName = pair.Value;
                if (!fileName.EndsWith(pair.Key))
                {
                    fileName = Path.Combine(fileName, pair.Key);
                }
                string folderName = null;
                if ((!fileName.EndsWith("ags32")) && (!fileName.EndsWith("ags64")))
                {
                    // the engine files belong in the LINUX_DATA_DIR, but the other libs
                    // should have lib32 or lib64 subdirectories as part of their name
                    folderName = Path.GetFileName(Path.GetDirectoryName(fileName).TrimEnd(Path.DirectorySeparatorChar));
                }
                Utilities.HardlinkOrCopy(GetCompiledPath(LINUX_DATA_DIR, folderName, Path.GetFileName(fileName)),
                                         fileName, true);
            }
            string linuxDataLib32Dir   = GetCompiledPath(LINUX_DATA_DIR, LINUX_LIB32_DIR);
            string linuxDataLib64Dir   = GetCompiledPath(LINUX_DATA_DIR, LINUX_LIB64_DIR);
            string editorLinuxDir      = Path.Combine(Factory.AGSEditor.EditorDirectory, LINUX_DIR);
            string editorLinuxLib32Dir = Path.Combine(editorLinuxDir, LINUX_LIB32_DIR);
            string editorLinuxLib64Dir = Path.Combine(editorLinuxDir, LINUX_LIB64_DIR);

            foreach (string soName in _plugins)
            {
                Utilities.HardlinkOrCopy(Path.Combine(linuxDataLib32Dir, soName),
                                         Path.Combine(editorLinuxLib32Dir, soName), true);
                Utilities.HardlinkOrCopy(Path.Combine(linuxDataLib64Dir, soName),
                                         Path.Combine(editorLinuxLib64Dir, soName), true);
            }
            string scriptFileName = GetCompiledPath(Factory.AGSEditor.BaseGameFileName.Replace(" ", "")); // strip whitespace from script name
            string scriptText     =
                @"#!/bin/sh
scriptpath=$(readlink -f ""$0"")
scriptdir=$(dirname ""$scriptpath"")

for arg; do
    if [ ""$arg"" = ""--help"" ]; then
        echo ""Usage: $(basename ""$scriptpath"") [<ags options>]\n""
        break
    fi
done

## Old versions of Mesa can hang when using DRI3
## https://bugs.freedesktop.org/show_bug.cgi?id=106404
export LIBGL_DRI3_DISABLE=true

if [ ""$(uname -m)"" = ""x86_64"" ]; then" + GetSymLinkScriptForEachPlugin(true) +
                @"
else" + GetSymLinkScriptForEachPlugin(false) +
                @"
fi
";

            scriptText = scriptText.Replace("\r\n", "\n"); // make sure script has UNIX line endings
            FileStream stream = File.Create(scriptFileName);

            byte[] bytes = Encoding.UTF8.GetBytes(scriptText);
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();
            return(true);
        }
Esempio n. 33
0
        private static void ImportRoomList(Game game, BinaryReader reader, string fullPathToGameFiles, CompileMessages importErrors)
        {
            Dictionary<int, UnloadedRoom> rooms = new Dictionary<int, UnloadedRoom>();
            foreach (string roomFileFullPath in Utilities.GetDirectoryFileList(Path.GetDirectoryName(fullPathToGameFiles), "room*.crm"))
            {
                int roomNumber = GetRoomNumberFromFileName(Path.GetFileName(roomFileFullPath));

                if (roomNumber >= 0)
                {
                    try
                    {
                        string roomScript = Factory.NativeProxy.LoadRoomScript(roomFileFullPath);
                        if (roomScript != null)
                        {
                            StreamWriter sw = new StreamWriter(roomFileFullPath.Substring(0, roomFileFullPath.Length - 4) + ".asc", false, Encoding.Default);
                            sw.Write(roomScript);
                            sw.Close();
                        }
                    }
                    catch (AGSEditorException ex)
                    {
                        importErrors.Add(new CompileError("There was an error saving the script for room " + roomNumber + ": " + ex.Message));
                    }

                    UnloadedRoom newUnloadedRoom = new UnloadedRoom(roomNumber);
                    rooms.Add(roomNumber, newUnloadedRoom);
                    game.Rooms.Add(newUnloadedRoom);
                }
                else
                {
                    importErrors.Add(new CompileWarning("The room file '" + roomFileFullPath + "' does not have a recognised name and will not be part of the game."));
                }
            }

            ((List<IRoom>)game.Rooms).Sort();

            int roomCount = reader.ReadInt32();
            for (int i = 0; i < roomCount; i++)
            {
                string roomDescription = ReadNullTerminatedString(reader);
                if (rooms.ContainsKey(i))
                {
                    rooms[i].Description = roomDescription;
                }
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Preprocesses and then compiles the script using the supplied headers.
        /// </summary>
        public void CompileScript(Script script, List<Script> headers, CompileMessages errors, bool isRoomScript)
        {
            IPreprocessor preprocessor = CompilerFactory.CreatePreprocessor(AGS.Types.Version.AGS_EDITOR_VERSION);
            DefineMacrosAccordingToGameSettings(preprocessor);

            List<string> preProcessedCode = new List<string>();
            foreach (Script header in headers)
            {
                preProcessedCode.Add(preprocessor.Preprocess(header.Text, header.FileName));
            }

            preProcessedCode.Add(preprocessor.Preprocess(script.Text, script.FileName));

            #if DEBUG
            // TODO: REMOVE BEFORE DISTRIBUTION
            /*			if (true)
            {
                string wholeScript = string.Join("\n", preProcessedCode.ToArray());
                IScriptCompiler compiler = CompilerFactory.CreateScriptCompiler();
                CompileResults output = compiler.CompileScript(wholeScript);
                preprocessor.Results.AddRange(output);
            }*/
            #endif

            if (preprocessor.Results.Count > 0)
            {
                foreach (AGS.CScript.Compiler.Error error in preprocessor.Results)
                {
                    CompileError newError = new CompileError(error.Message, error.ScriptName, error.LineNumber);
                    if (errors == null)
                    {
                        throw newError;
                    }
                    errors.Add(newError);
                }
            }
            else
            {
                Factory.NativeProxy.CompileScript(script, preProcessedCode.ToArray(), _game, isRoomScript);
            }
        }
Esempio n. 35
0
        private void RunPreCompilationChecks(CompileMessages errors)
        {
            if ((_game.LipSync.Type == LipSyncType.PamelaVoiceFiles) &&
                (_game.Settings.SpeechStyle == SpeechStyle.Lucasarts))
            {
                errors.Add(new CompileError("Voice lip-sync cannot be used with Lucasarts-style speech"));
            }

            if ((_game.Settings.EnhancedSaveGames) &&
                (_game.Settings.SaveGameFileExtension == string.Empty))
            {
                errors.Add(new CompileError("Enhanced Save Games are enabled but no file extension is specified"));
            }

            if (_game.PlayerCharacter == null)
            {
                errors.Add(new CompileError("No character has been set as the player character"));
            }
            else if (_game.FindRoomByID(_game.PlayerCharacter.StartingRoom) == null)
            {
                errors.Add(new CompileError("The game is set to start in room " + _game.PlayerCharacter.StartingRoom + " which does not exist"));
            }

            if ((_game.Settings.GraphicsDriver == GraphicsDriver.D3D9) &&
                (_game.Settings.ColorDepth == GameColorDepth.Palette))
            {
                errors.Add(new CompileError("Direct3D graphics driver does not support 256-colour games"));
            }

            if ((_game.Settings.ColorDepth == GameColorDepth.Palette) &&
                (_game.Settings.RoomTransition == RoomTransitionStyle.CrossFade))
            {
                errors.Add(new CompileError("You cannot use the CrossFade room transition with 256-colour games"));
            }

            if ((_game.Settings.DialogOptionsGUI < 0) ||
                (_game.Settings.DialogOptionsGUI >= _game.GUIs.Count))
            {
                if (_game.Settings.DialogOptionsGUI != 0)
                {
                    errors.Add(new CompileError("Invalid GUI number set for Dialog Options GUI"));
                }
            }

            foreach (Character character in _game.Characters)
            {
                AGS.Types.View view = _game.FindViewByID(character.NormalView);
                if (view == null)
                {
                    errors.Add(new CompileError("Character " + character.ID + " (" + character.RealName + ") has invalid normal view."));
                }
                else
                {
                    EnsureViewHasAtLeast4LoopsAndAFrameInLeftRightLoops(view);
                }
            }

            foreach (GUI gui in _game.GUIs)
            {
                if (gui is NormalGUI)
                {
                    if ((((NormalGUI)gui).Width > _game.MinRoomWidth) ||
                        (((NormalGUI)gui).Height > _game.MinRoomHeight))
                    {
                        errors.Add(new CompileWarning("GUI " + gui.Name + " is larger than the screen size and may cause errors in the game."));
                    }
                }
            }

            Dictionary<string, AGS.Types.View> viewNames = new Dictionary<string, AGS.Types.View>();
            EnsureViewNamesAreUnique(_game.RootViewFolder, viewNames, errors);

            foreach (AudioClip clip in _game.RootAudioClipFolder.GetAllAudioClipsFromAllSubFolders())
            {
                if (!File.Exists(clip.CacheFileName))
                {
                    errors.Add(new CompileError("Audio file missing for " + clip.ScriptName + ": " + clip.CacheFileName));
                }
            }

            if (!IsEnoughSpaceFreeOnDisk(MINIMUM_BYTES_FREE_TO_COMPILE))
            {
                errors.Add(new CompileError("There is not enough space on the disk."));
            }
        }
Esempio n. 36
0
        public override bool Build(CompileMessages errors, bool forceRebuild)
        {
            if (!base.Build(errors, forceRebuild)) return false;
            if (!CheckPluginsHaveSharedLibraries())
            {
                errors.Add(new CompileError("Could not build for Linux due to missing plugins."));
                return false;
            }
            foreach (string fileName in Directory.GetFiles(Path.Combine(AGSEditor.OUTPUT_DIRECTORY, AGSEditor.DATA_OUTPUT_DIRECTORY)))
            {
                if ((!fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) &&
                    (!Path.GetFileName(fileName).Equals("winsetup.exe", StringComparison.OrdinalIgnoreCase)) &&
                    (!Path.GetFileName(fileName).Equals(AGSEditor.CONFIG_FILE_NAME, StringComparison.OrdinalIgnoreCase)))
                {
                    Utilities.CreateHardLink(GetCompiledPath(LINUX_DATA_DIR, Path.GetFileName(fileName)), fileName, true);
                }
            }
            // Update config file with current game parameters
            Factory.AGSEditor.WriteConfigFile(GetCompiledPath(LINUX_DATA_DIR));

            foreach (KeyValuePair<string, string> pair in GetRequiredLibraryPaths())
            {
                string fileName = pair.Value;
                if (!fileName.EndsWith(pair.Key)) fileName = Path.Combine(fileName, pair.Key);
                string folderName = null;
                if ((!fileName.EndsWith("ags32")) && (!fileName.EndsWith("ags64")))
                {
                    // the engine files belong in the LINUX_DATA_DIR, but the other libs
                    // should have lib32 or lib64 subdirectories as part of their name
                    folderName = Path.GetFileName(Path.GetDirectoryName(fileName).TrimEnd(Path.DirectorySeparatorChar));
                }
                Utilities.CreateHardLink(GetCompiledPath(LINUX_DATA_DIR, folderName, Path.GetFileName(fileName)),
                    fileName, true);
            }
            string linuxDataLib32Dir = GetCompiledPath(LINUX_DATA_DIR, LINUX_LIB32_DIR);
            string linuxDataLib64Dir = GetCompiledPath(LINUX_DATA_DIR, LINUX_LIB64_DIR);
            string editorLinuxDir = Path.Combine(Factory.AGSEditor.EditorDirectory, LINUX_DIR);
            string editorLinuxLib32Dir = Path.Combine(editorLinuxDir, LINUX_LIB32_DIR);
            string editorLinuxLib64Dir = Path.Combine(editorLinuxDir, LINUX_LIB64_DIR);
            foreach (string soName in _plugins)
            {
                Utilities.CreateHardLink(Path.Combine(linuxDataLib32Dir, soName),
                    Path.Combine(editorLinuxLib32Dir, soName), true);
                Utilities.CreateHardLink(Path.Combine(linuxDataLib64Dir, soName),
                    Path.Combine(editorLinuxLib64Dir, soName), true);
            }
            string scriptFileName = GetCompiledPath(Factory.AGSEditor.BaseGameFileName.Replace(" ", "")); // strip whitespace from script name
            string scriptText =
            @"#!/bin/sh
            SCRIPTPATH=""$(dirname ""$(readlink -f $0)"")""

            if test ""x$@"" = ""x-h"" -o ""x$@"" = ""x--help""
              then
            echo ""Usage:"" ""$(basename ""$(readlink -f $0)"")"" ""[<ags options>]""
            echo """"
            fi

            if test $(uname -m) = x86_64
              then" + GetSymLinkScriptForEachPlugin(true) +
            @"
              else" + GetSymLinkScriptForEachPlugin(false) +
            @"
            fi
            ";
            scriptText = scriptText.Replace("\r\n", "\n"); // make sure script has UNIX line endings
            FileStream stream = File.Create(scriptFileName);
            byte[] bytes = Encoding.UTF8.GetBytes(scriptText);
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();
            return true;
        }
Esempio n. 37
0
 private void RaiseDialogScriptCompileWarning(string errorMsg, CompileMessages errors)
 {
     errors.Add(new CompileWarning(errorMsg, "Dialog " + _currentDialog.ID, _currentLineNumber));
 }
Esempio n. 38
0
        private void RunPreCompilationChecks(CompileMessages errors)
        {
            if ((_game.LipSync.Type == LipSyncType.PamelaVoiceFiles) &&
                (_game.Settings.SpeechStyle == SpeechStyle.Lucasarts))
            {
                errors.Add(new CompileError("La synchronisation labiale ne peut pas être utilisée avec le style Lucasarts"));
            }

            if ((_game.Settings.EnhancedSaveGames) &&
                (_game.Settings.SaveGameFileExtension == string.Empty))
            {
                errors.Add(new CompileError("Les sauvegardes enrichies sont activées mais aucune extension de fichier n'est spécifiée"));
            }

            if (_game.PlayerCharacter == null)
            {
                errors.Add(new CompileError("Aucun personnage n'a été défini comme personnage joueur"));
            }
            else if (_game.FindRoomByID(_game.PlayerCharacter.StartingRoom) == null)
            {
                errors.Add(new CompileError("Le jeu doit commencer dans la pièce " + _game.PlayerCharacter.StartingRoom + " qui n'existe pas"));
            }

            if ((_game.Settings.GraphicsDriver == GraphicsDriver.D3D9) &&
                (_game.Settings.ColorDepth == GameColorDepth.Palette))
            {
                errors.Add(new CompileError("Le pilote graphique Direct3D ne supporte pas les jeux en 256 couleurs"));
            }

            if ((_game.Settings.ColorDepth == GameColorDepth.Palette) &&
                (_game.Settings.RoomTransition == RoomTransitionStyle.CrossFade))
            {
                errors.Add(new CompileError("Vous ne pouvez pas utiliser la transition de fondu enchaîné pour les jeux en 256 couleurs"));
            }

            if ((_game.Settings.DialogOptionsGUI < 0) ||
                (_game.Settings.DialogOptionsGUI >= _game.RootGUIFolder.GetAllItemsCount()))
            {
                if (_game.Settings.DialogOptionsGUI != 0)
                {
                    errors.Add(new CompileError("Le numéro d'interface entré comme Interface des Options de Dialogues est invalide"));
                }
            }

            foreach (Character character in _game.RootCharacterFolder.AllItemsFlat)
            {
                AGS.Types.View view = _game.FindViewByID(character.NormalView);
                if (view == null)
                {
                    errors.Add(new CompileError("La vue normale du personnage " + character.ID + " (" + character.RealName + ") est invalide."));
                }
                else
                {
                    EnsureViewHasAtLeast4LoopsAndAFrameInLeftRightLoops(view);
                }
            }

            foreach (GUI gui in _game.RootGUIFolder.AllItemsFlat)
            {
                NormalGUI normalGui = gui as NormalGUI;
                if (normalGui != null)
                {
                    if ((normalGui.Width > _game.MinRoomWidth) ||
                        (normalGui.Height > _game.MinRoomHeight))
                    {
                        errors.Add(new CompileWarning("L'interface " + gui.Name + " est plus large que l'écran et peut causer des erreurs dans le jeu."));
                    }
                }
            }

            Dictionary<string, AGS.Types.View> viewNames = new Dictionary<string, AGS.Types.View>();
            EnsureViewNamesAreUnique(_game.RootViewFolder, viewNames, errors);

            foreach (AudioClip clip in _game.RootAudioClipFolder.GetAllAudioClipsFromAllSubFolders())
            {
                if (!File.Exists(clip.CacheFileName))
                {
                    errors.Add(new CompileError("Le fichier audio pour " + clip.ScriptName + " est manquant : " + clip.CacheFileName));
                }
            }

            if (!IsEnoughSpaceFreeOnDisk(MINIMUM_BYTES_FREE_TO_COMPILE))
            {
                errors.Add(new CompileError("Espace disque insuffisant."));
            }
        }
Esempio n. 39
0
        private void AGSEditor_ProcessAllGameTexts(IGameTextProcessor processor, CompileMessages errors)
        {
            if (processor.MakesChanges)
            {
                if (!CheckOutAllRoomsAndScripts())
                {
                    errors.Add(new CompileError("Failed to open room files for writing"));
                    return;
                }
            }

            foreach (UnloadedRoom unloadedRoom in _agsEditor.CurrentGame.Rooms)
            {
                UnloadCurrentRoom();
                Room room = LoadNewRoomIntoMemory(unloadedRoom, errors);

                room.Script.Text = processor.ProcessText(room.Script.Text, GameTextType.Script);
                if (processor.MakesChanges)
                {
                    room.Script.SaveToDisk();
                }

                foreach (RoomMessage message in room.Messages)
                {
                    int charId = message.CharacterID;
                    if (!message.ShowAsSpeech)
                    {
                        charId = Character.NARRATOR_CHARACTER_ID;
                    }
                    message.Text = processor.ProcessText(message.Text, GameTextType.Message, charId);
                }

                foreach (RoomHotspot hotspot in room.Hotspots)
                {
                    hotspot.Description = processor.ProcessText(hotspot.Description, GameTextType.ItemDescription);
                }

                foreach (RoomObject obj in room.Objects)
                {
                    obj.Description = processor.ProcessText(obj.Description, GameTextType.ItemDescription);
                }

                if (processor.MakesChanges)
                {
                    CompileMessages roomErrors = new CompileMessages();
                    SaveRoomButDoNotShowAnyErrors(room, roomErrors, "Saving updates to room " + room.Number + "...");

                    if (roomErrors.Count > 0)
                    {
                        errors.Add(new CompileError("Failed to save room " + room.FileName + "; details below"));
                        errors.Add(roomErrors[0]);
                    }
                }
            }
        }
Esempio n. 40
0
        private void EnsureViewNamesAreUnique(ViewFolder folder, Dictionary<string, AGS.Types.View> viewNames, CompileMessages errors)
        {
            foreach (ViewFolder subFolder in folder.SubFolders)
            {
                EnsureViewNamesAreUnique(subFolder, viewNames, errors);
            }

            foreach (AGS.Types.View view in folder.Views)
            {
                if (!string.IsNullOrEmpty(view.Name))
                {
                    if (viewNames.ContainsKey(view.Name.ToLower()))
                    {
                        errors.Add(new CompileError("Il y a au moins deux vues qui partagent le même nom '" + view.Name + "'"));
                    }
                    else
                    {
                        viewNames.Add(view.Name.ToLower(), view);
                    }
                }
            }
        }
Esempio n. 41
0
 private void EnsureScriptNamesAreUnique(Room room, CompileMessages errors)
 {
     foreach (RoomHotspot hotspot in room.Hotspots)
     {
         if (_agsEditor.CurrentGame.IsScriptNameAlreadyUsed(hotspot.Name, hotspot))
         {
             errors.Add(new CompileError("Hotspot '" + hotspot.Name + "' script name conflicts with other game item"));
         }
     }
     foreach (RoomObject obj in room.Objects)
     {
         if (_agsEditor.CurrentGame.IsScriptNameAlreadyUsed(obj.Name, obj))
         {
             errors.Add(new CompileError("Object '" + obj.Name + "' script name conflicts with other game item"));
         }
     }
 }
Esempio n. 42
0
        private SpeechLipSyncLine CompilePAMFile(string fileName, CompileMessages errors)
        {
            SpeechLipSyncLine syncDataForThisFile = new SpeechLipSyncLine();

            syncDataForThisFile.FileName = Path.GetFileNameWithoutExtension(fileName);

            string thisLine;
            bool   inMainSection = false;
            int    lineNumber    = 0;

            StreamReader sr = new StreamReader(fileName);

            while ((thisLine = sr.ReadLine()) != null)
            {
                lineNumber++;
                if (thisLine.ToLower().StartsWith("[speech]"))
                {
                    inMainSection = true;
                    continue;
                }
                if (inMainSection)
                {
                    if (thisLine.TrimStart().StartsWith("["))
                    {
                        // moved onto another section
                        break;
                    }
                    if (thisLine.IndexOf(':') > 0)
                    {
                        string[] parts = thisLine.Split(':');
                        // Convert from Pamela XPOS into milliseconds
                        int    milliSeconds = ((Convert.ToInt32(parts[0]) / 15) * 1000) / 24;
                        string phenomeCode  = parts[1].Trim().ToUpper();
                        int    frameID      = FindFrameNumberForPhenome(phenomeCode);
                        if (frameID < 0)
                        {
                            string friendlyFileName = Path.GetFileName(fileName);
                            errors.Add(new CompileError("No frame found to match phenome code '" + phenomeCode + "'", friendlyFileName, lineNumber));
                        }
                        else
                        {
                            syncDataForThisFile.Phenomes.Add(new SpeechLipSyncPhenome(milliSeconds, (short)frameID));
                        }
                    }
                }
            }
            sr.Close();
            syncDataForThisFile.Phenomes.Sort();

            // The PAM file contains start times: Convert to end times
            for (int i = 0; i < syncDataForThisFile.Phenomes.Count - 1; i++)
            {
                syncDataForThisFile.Phenomes[i].EndTimeOffset = syncDataForThisFile.Phenomes[i + 1].EndTimeOffset;
            }

            if (syncDataForThisFile.Phenomes.Count > 1)
            {
                syncDataForThisFile.Phenomes[syncDataForThisFile.Phenomes.Count - 1].EndTimeOffset = syncDataForThisFile.Phenomes[syncDataForThisFile.Phenomes.Count - 2].EndTimeOffset + 1000;
            }

            return(syncDataForThisFile);
        }
Esempio n. 43
0
 public void CopyPlugins(CompileMessages errors)
 {
     try
     {
         string outputDir = GetCompiledPath();
         foreach (Plugin plugin in Factory.AGSEditor.CurrentGame.Plugins)
         {
             File.Copy(Path.Combine(Factory.AGSEditor.EditorDirectory, plugin.FileName), Path.Combine(outputDir, plugin.FileName), true);
         }
     }
     catch (Exception ex)
     {
         errors.Add(new CompileError("Unexpected error: " + ex.Message));
     }
 }
Esempio n. 44
0
        private void CreateCompiledFiles(string sourceEXE, CompileMessages errors, bool forceRebuild)
        {
            try
            {
                string newExeName = this.CompiledEXEFileName;
                File.Copy(sourceEXE, newExeName, true);

                if (File.Exists(CUSTOM_ICON_FILE_NAME))
                {
                    try
                    {
                        Factory.NativeProxy.UpdateFileIcon(newExeName, CUSTOM_ICON_FILE_NAME);
                    }
                    catch (AGSEditorException ex)
                    {
                        Factory.GUIController.ShowMessage("An problem occurred setting your custom icon onto the EXE file. The error was: " + ex.Message, MessageBoxIcon.Warning);
                    }
                }

                try
                {
                    UpdateVistaGameExplorerResources(newExeName);
                }
                catch (Exception ex)
                {
                    errors.Add(new CompileError("Unable to register for Vista Game Explorer: " + ex.Message));
                }

                try
                {
                    Factory.NativeProxy.UpdateFileVersionInfo(newExeName, _game.Settings.DeveloperName, _game.Settings.GameName);
                }
                catch (Exception ex)
                {
                    errors.Add(new CompileError("Unable to set EXE name/description: " + ex.Message));
                }

                BusyDialog.Show("Please wait while your game is created...", new BusyDialog.ProcessingHandler(CreateCompiledFiles), forceRebuild);

                foreach (Plugin plugin in _game.Plugins)
                {
                    File.Copy(Path.Combine(this.EditorDirectory, plugin.FileName), OUTPUT_DIRECTORY + "\\" + plugin.FileName, true);
                }
            }
            catch (Exception ex)
            {
                errors.Add(new CompileError("Unexpected error: " + ex.Message));
            }
        }
Esempio n. 45
0
        public override bool Build(CompileMessages errors, bool forceRebuild)
        {
            if (!base.Build(errors, forceRebuild))
            {
                return(false);
            }

            UseGradleDaemon = Factory.AGSEditor.Settings.AndroidBuildGradleDaemon;
            string andProjDir = GetAndroidProjectInCompiledDir();

            if (!IsProjectSane(errors))
            {
                return(false);
            }

            InstallSdkToolsIfNeeded();

            AndroidBuildFormat buildFormat = Factory.AGSEditor.CurrentGame.Settings.AndroidBuildFormat;
            string             appName     = GetFinalAppName();

            string assetsDir = GetAssetsDir();

            if (!Directory.Exists(assetsDir))
            {
                Directory.CreateDirectory(assetsDir);
            }
            ClearInvalidAssetDirIfNeeded();

            foreach (string fileName in Directory.GetFiles(Path.Combine(AGSEditor.OUTPUT_DIRECTORY, AGSEditor.DATA_OUTPUT_DIRECTORY)))
            {
                if ((File.GetAttributes(fileName) & (FileAttributes.Hidden | FileAttributes.System | FileAttributes.Temporary)) != 0)
                {
                    continue;
                }
                if ((!fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) &&
                    (!Path.GetFileName(fileName).Equals("winsetup.exe", StringComparison.OrdinalIgnoreCase)) &&
                    (!Path.GetFileName(fileName).Equals(AGSEditor.CONFIG_FILE_NAME, StringComparison.OrdinalIgnoreCase)))
                {
                    string dest_filename = Path.Combine(assetsDir, Path.GetFileName(fileName));
                    Utilities.HardlinkOrCopy(dest_filename, fileName, true);
                }
            }

            // Update config file with current game parameters
            Factory.AGSEditor.WriteConfigFile(assetsDir);
            WriteAndroidCfg(assetsDir);

            foreach (KeyValuePair <string, string> pair in GetRequiredLibraryPaths())
            {
                string fileName  = pair.Key;
                string originDir = pair.Value;

                string dest = GetCompiledPath(ANDROID_DIR, Path.GetDirectoryName(fileName));

                if (!Directory.Exists(dest))
                {
                    // doesn't exist, let's create it
                    Directory.CreateDirectory(dest);
                }

                string destFile       = GetCompiledPath(ANDROID_DIR, fileName);
                string originFile     = Path.Combine(originDir, fileName);
                string destFileName   = Utilities.ResolveSourcePath(destFile);
                string sourceFileName = Utilities.ResolveSourcePath(originFile);

                if (fileName.EndsWith(".so"))
                {
                    Utilities.HardlinkOrCopy(destFile, originFile, true);
                }
                else
                {
                    File.Copy(sourceFileName, destFileName, true);
                }
            }

            string destDir = GetCompiledPath(ANDROID_DIR, "mygame");

            WriteProjectProperties(destDir);
            WriteLocalStaticProperties(destDir);
            WriteProjectXml(destDir);
            IconAssetType iconType = GetGameIconType();

            if (iconType != IconAssetType.NoIconFiles)
            {
                SetGameIcons(iconType, destDir);
            }

            GradleTasks gradleTask = GradleTasks.bundleRelease;

            if (buildFormat == AndroidBuildFormat.ApkEmbedded)
            {
                gradleTask = GradleTasks.assembleRelease;
            }

            if (!AndroidUtilities.RunGradlewTask(gradleTask, andProjDir, use_daemon: UseGradleDaemon))
            {
                errors.Add(new CompileError("There was an error running gradle to build the Android App."));
                return(false);
            }

            string appFinalFile     = GetFinalAppName();
            string appSrcDir        = GetOutputDir();
            string generatedAppFile = Path.Combine(appSrcDir, appFinalFile);

            if (File.Exists(generatedAppFile))
            {
                try
                {
                    Utilities.HardlinkOrCopy(GetCompiledPath(ANDROID_DIR, appFinalFile), generatedAppFile, true);
                }
                catch { }

                return(true);
            }

            errors.Add(new CompileError("Failed to generate Android App."));

            return(false);
        }
Esempio n. 46
0
        private void EnsureViewNamesAreUnique(ViewFolder folder, Dictionary<string, AGS.Types.View> viewNames, CompileMessages errors)
        {
            foreach (ViewFolder subFolder in folder.SubFolders)
            {
                EnsureViewNamesAreUnique(subFolder, viewNames, errors);
            }

            foreach (AGS.Types.View view in folder.Views)
            {
                if (!string.IsNullOrEmpty(view.Name))
                {
                    if (viewNames.ContainsKey(view.Name.ToLower()))
                    {
                        errors.Add(new CompileError("There are two or more views with the same name '" + view.Name + "'"));
                    }
                    else
                    {
                        viewNames.Add(view.Name.ToLower(), view);
                    }
                }
            }
        }
Esempio n. 47
0
        private void CompileTranslation(Translation translation, CompileMessages errors)
        {
            translation.LoadData();

            if (translation.TranslatedLines.Count < 1)
            {
                errors.Add(new CompileError("Translation " + translation.FileName + " appears to be empty. You must update the source before compiling.", translation.FileName, 1));
                return;
            }

            string compiledFile = Path.Combine(AGSEditor.OUTPUT_DIRECTORY, translation.CompiledFileName);
            bool foundTranslatedLine = false;

            using (BinaryWriter bw = new BinaryWriter(new FileStream(compiledFile, FileMode.Create, FileAccess.Write)))
            {
                bw.Write(Encoding.ASCII.GetBytes(COMPILED_TRANSLATION_FILE_SIGNATURE));
                bw.Write(TRANSLATION_BLOCK_GAME_ID);
                byte[] gameName = Factory.NativeProxy.TransformStringToBytes(_agsEditor.CurrentGame.Settings.GameName);
                bw.Write(gameName.Length + 4);
                bw.Write(_agsEditor.CurrentGame.Settings.UniqueID);
                bw.Write(gameName);
                bw.Write(TRANSLATION_BLOCK_TRANSLATION_DATA);
                long offsetOfBlockSize = bw.BaseStream.Position;
                bw.Write((int)0);
                foreach (string line in translation.TranslatedLines.Keys)
                {
                    if (translation.TranslatedLines[line].Length > 0)
                    {
                        foundTranslatedLine = true;
                        bw.Write(Factory.NativeProxy.TransformStringToBytes(ConvertEscapedCharacters(line)));
                        bw.Write(Factory.NativeProxy.TransformStringToBytes(ConvertEscapedCharacters(translation.TranslatedLines[line])));
                    }
                }
                bw.Write(Factory.NativeProxy.TransformStringToBytes(string.Empty));
                bw.Write(Factory.NativeProxy.TransformStringToBytes(string.Empty));
                long mainBlockSize = (bw.BaseStream.Position - offsetOfBlockSize) - 4;
                bw.Write(TRANSLATION_BLOCK_OPTIONS);
                bw.Write((int)12);
                bw.Write(translation.NormalFont ?? -1);
                bw.Write(translation.SpeechFont ?? -1);
                bw.Write((translation.RightToLeftText == true) ? 2 : ((translation.RightToLeftText == false) ? 1 : -1));
                bw.Write(TRANSLATION_BLOCK_END_OF_FILE);
                bw.Write((int)0);
                bw.Seek((int)offsetOfBlockSize, SeekOrigin.Begin);
                bw.Write((int)mainBlockSize);
                bw.Close();
            }

            if (!foundTranslatedLine)
            {
                errors.Add(new CompileError("Translation " + translation.FileName + " did not appear to have any translated lines. Make sure you translate some text before compiling the translation.", translation.FileName, 1));
                File.Delete(compiledFile);
            }
        }
Esempio n. 48
0
        public CompileMessages CompileGame(bool forceRebuild, bool createMiniExeForDebug)
        {
            Factory.GUIController.ClearOutputPanel();
            CompileMessages errors = new CompileMessages();

            Utilities.EnsureStandardSubFoldersExist();

            if (PreCompileGame != null)
            {
                PreCompileGameEventArgs evArgs = new PreCompileGameEventArgs(forceRebuild);
                evArgs.Errors = errors;

                PreCompileGame(evArgs);

                if (!evArgs.AllowCompilation)
                {
                    Factory.GUIController.ShowOutputPanel(errors);
                    ReportErrorsIfAppropriate(errors);
                    return errors;
                }
            }

            RunPreCompilationChecks(errors);

            if (!errors.HasErrors)
            {
                CompileMessage result = (CompileMessage)BusyDialog.Show("Please wait while your scripts are compiled...", new BusyDialog.ProcessingHandler(CompileScripts), new CompileScriptsParameters(errors, forceRebuild));
                if (result != null)
                {
                    errors.Add(result);
                }
                else if (!errors.HasErrors)
                {
                    string sourceEXE = Path.Combine(this.EditorDirectory, ENGINE_EXE_FILE_NAME);
                    if (!File.Exists(sourceEXE))
                    {
                        errors.Add(new CompileError("Cannot find the file '" + sourceEXE + "'. This file is required in order to compile your game."));
                    }
                    else if (createMiniExeForDebug)
                    {
                        CreateMiniEXEForDebugging(sourceEXE, errors);
                    }
                    else
                    {
                        CreateCompiledFiles(sourceEXE, errors, forceRebuild);
                    }
                }
            }

            Factory.GUIController.ShowOutputPanel(errors);

            ReportErrorsIfAppropriate(errors);

            return errors;
        }
Esempio n. 49
0
        private bool RecompileAnyRoomsWhereTheScriptHasChanged(CompileMessages errors, bool rebuildAll)
        {
            List<UnloadedRoom> roomsToRebuild = new List<UnloadedRoom>();
            List<string> roomFileNamesToRebuild = new List<string>();
            bool success = true;
            foreach (UnloadedRoom unloadedRoom in _agsEditor.CurrentGame.Rooms)
            {
                if (!File.Exists(unloadedRoom.ScriptFileName))
                {
                    errors.Add(new CompileError("File not found: " + unloadedRoom.ScriptFileName + "; If you deleted this file, use the Exclude From Game option to remove it from the game."));
                    success = false;
                }
                else if (!File.Exists(unloadedRoom.FileName))
                {
                    errors.Add(new CompileError("File not found: " + unloadedRoom.FileName + "; If you deleted this file, use the Exclude From Game option to remove it from the game."));
                    success = false;
                }
                else if ((rebuildAll) ||
                    (Utilities.DoesFileNeedRecompile(unloadedRoom.ScriptFileName, unloadedRoom.FileName)) ||
                    (HaveScriptHeadersBeenUpdatedSinceRoomWasCompiled(unloadedRoom.FileName)))
                {
                    roomsToRebuild.Add(unloadedRoom);
                    roomFileNamesToRebuild.Add(unloadedRoom.FileName);
                }
            }

            if (!_agsEditor.AttemptToGetWriteAccess(roomFileNamesToRebuild))
            {
                errors.Add(new CompileError("Failed to open files for writing"));
                return false;
            }

            foreach (UnloadedRoom unloadedRoom in roomsToRebuild)
            {
                Room room;
                if ((_loadedRoom == null) || (_loadedRoom.Number != unloadedRoom.Number))
                {
                    UnloadCurrentRoom();
                    room = LoadNewRoomIntoMemory(unloadedRoom, errors);
                }
                else
                {
                    room = _loadedRoom;
                }
                // Ensure that the script is saved (in case this is a 2.72
                // room and LoadNewRoom has just jibbled the script)
                room.Script.SaveToDisk();

                CompileMessages roomErrors = new CompileMessages();
                SaveRoomButDoNotShowAnyErrors(room, roomErrors, "Rebuilding room " + room.Number + " because a script has changed...");

                if (roomErrors.Count > 0)
                {
                    errors.Add(new CompileError("Failed to save room " + room.FileName + "; details below"));
                    errors.Add(roomErrors[0]);
                    success = false;
                    break;
                }
            }

            return success;
        }
Esempio n. 50
0
        private static bool CreateScriptsForInteraction(string itemName, Script script, Interactions interactions, CompileMessages errors)
        {
            bool convertedSome = false;

            for (int i = 0; i < interactions.ImportedScripts.Length; i++)
            {
                if ((interactions.ImportedScripts[i] != null) &&
                    (interactions.ImportedScripts[i].Length > 0))
                {
                    if (interactions.ImportedScripts[i].IndexOf(SINGLE_RUN_SCRIPT_TAG) >= 0)
                    {
                        // just a single Run Script -- don't wrap it in an outer
                        // function since there's no need to
                        interactions.ScriptFunctionNames[i] = interactions.ImportedScripts[i].Replace(SINGLE_RUN_SCRIPT_TAG, string.Empty).Replace("();", string.Empty).Trim();
                        convertedSome = true;
                    }
                    else
                    {
                        string funcName = itemName + "_" + interactions.FunctionSuffixes[i];
                        string funcScriptLine = "function " + funcName + "()";
                        interactions.ScriptFunctionNames[i] = funcName;
                        if (script.Text.IndexOf(funcScriptLine) >= 0)
                        {
                            errors.Add(new CompileWarning("Function " + funcName + " already exists in script and could not be created"));
                        }
                        else
                        {
                            script.Text += Environment.NewLine + funcScriptLine + Environment.NewLine;
                            script.Text += "{" + Environment.NewLine + interactions.ImportedScripts[i] + "}" + Environment.NewLine;
                            convertedSome = true;
                        }
                    }
                    interactions.ImportedScripts[i] = null;
                }
            }

            return convertedSome;
        }
Esempio n. 51
0
        private void SaveRoomButDoNotShowAnyErrors(Room room, CompileMessages errors, string pleaseWaitText)
        {
            lock (_roomLoadingOrSavingLock)
            {
                if (room != _loadedRoom)
                {
                    errors.Add(new CompileError("Attempted to save room " + room.Number + " which is not loaded"));
                    return;
                }

                PerformPreSaveChecks(room);

                if (!_agsEditor.AttemptToGetWriteAccess(room.FileName))
                {
                    errors.Add(new CompileError("Unable to open file " + room.FileName + " for writing"));
                    return;
                }

                if (PreSaveRoom != null)
                {
                    PreSaveRoom(room, errors);
                }

                EnsureScriptNamesAreUnique(room, errors);
                try
                {
                    if (!errors.HasErrors)
                    {
                        BusyDialog.Show(pleaseWaitText, new BusyDialog.ProcessingHandler(SaveRoomOnThread), room);
                    }
                }
                catch (CompileMessage ex)
                {
                    errors.Add(ex);
                }
                catch (AGSEditorException ex)
                {
                    errors.Add(new CompileError(ex.Message, ex));
                }
            }
        }
Esempio n. 52
0
 private static SpriteFolder ImportSpriteFolders(BinaryReader reader, Dictionary<int,Sprite> spriteList, CompileMessages importErrors)
 {
     const string DUMMY_FOLDER_NAME = "$$TEMPNAME";
     Dictionary<int, SpriteFolder> spriteFolders = new Dictionary<int, SpriteFolder>();
     int spriteFolderCount = reader.ReadInt32();
     // First, create an object for all of them (since folder 2
     // might have folder 15 as its parent, all objects need
     // to be there from the start).
     for (int i = 0; i < spriteFolderCount; i++)
     {
         spriteFolders.Add(i, new SpriteFolder(DUMMY_FOLDER_NAME));
     }
     for (int i = 0; i < spriteFolderCount; i++)
     {
         int numItems = reader.ReadInt32();
         for (int j = 0; j < 240; j++)
         {
             int spriteNum = reader.ReadInt16();
             if ((j < numItems) && (spriteNum >= 0))
             {
                 if (spriteList.ContainsKey(spriteNum))
                 {
                     spriteFolders[i].Sprites.Add(spriteList[spriteNum]);
                     spriteList.Remove(spriteNum);
                 }
                 else
                 {
                     importErrors.Add(new CompileWarning("Sprite " + spriteNum + " not found whilst importing the sprite folder list"));
                 }
             }
         }
         int parentFolder = reader.ReadInt16();
         if (parentFolder >= 0)
         {
             if (!spriteFolders.ContainsKey(parentFolder))
             {
                 throw new AGS.Types.InvalidDataException("Invalid sprite folder structure found: folder " + i + " has parent " + parentFolder);
             }
             spriteFolders[parentFolder].SubFolders.Add(spriteFolders[i]);
         }
         string folderName = ReadNullTerminatedString(reader, 30);
         if (folderName.Contains("\0"))
         {
             folderName = folderName.TrimEnd('\0');
         }
         spriteFolders[i].Name = folderName;
     }
     return spriteFolders[0];
 }
Esempio n. 53
0
        private bool AddPlayMusicCommandToPlayerEntersRoomScript(Room room, CompileMessages errors)
        {
            bool scriptModified = false;

            if (room.PlayMusicOnRoomLoad > 0)
            {
                AudioClip clip = _agsEditor.CurrentGame.FindAudioClipForOldMusicNumber(null, room.PlayMusicOnRoomLoad);
                if (clip == null)
                {
                    errors.Add(new CompileWarning("Room " + room.Number + ": Unable to find aMusic" + room.PlayMusicOnRoomLoad + " which was set as this room's start music"));
                    return scriptModified;
                }

                string scriptName = room.Interactions.GetScriptFunctionNameForInteractionSuffix(Room.EVENT_SUFFIX_ROOM_LOAD);
                if (string.IsNullOrEmpty(scriptName))
                {
                    scriptName = "Room_" + Room.EVENT_SUFFIX_ROOM_LOAD;
                    room.Interactions.SetScriptFunctionNameForInteractionSuffix(Room.EVENT_SUFFIX_ROOM_LOAD, scriptName);
                    room.Script.Text += Environment.NewLine + "function " + scriptName + "()" +
                        Environment.NewLine + "{" + Environment.NewLine +
                        "}" + Environment.NewLine;
                    scriptModified = true;
                }
                int functionOffset = room.Script.Text.IndexOf(scriptName);
                if (functionOffset < 0)
                {
                    errors.Add(new CompileWarning("Room " + room.Number + ": Unable to find definition for " + scriptName + " to add Room Load music " + room.PlayMusicOnRoomLoad));
                }
                else
                {
                    functionOffset = room.Script.Text.IndexOf('{', functionOffset);
                    functionOffset = room.Script.Text.IndexOf('\n', functionOffset) + 1;
                    string newScript = room.Script.Text.Substring(0, functionOffset);
                    newScript += "  " + clip.ScriptName + ".Play();" + Environment.NewLine;
                    newScript += room.Script.Text.Substring(functionOffset);
                    room.Script.Text = newScript;
                    room.PlayMusicOnRoomLoad = 0;
                    scriptModified = true;
                }
            }

            return scriptModified;
        }
Esempio n. 54
0
        private static void ImportRoomList(Game game, BinaryReader reader, string fullPathToGameFiles, CompileMessages importErrors)
        {
            Dictionary<int, UnloadedRoom> rooms = new Dictionary<int, UnloadedRoom>();
            foreach (string roomFileFullPath in Utilities.GetDirectoryFileList(Path.GetDirectoryName(fullPathToGameFiles), "room*.crm"))
            {
                int roomNumber = GetRoomNumberFromFileName(Path.GetFileName(roomFileFullPath));

                if (roomNumber >= 0)
                {
                    try
                    {
                        string roomScript = Factory.NativeProxy.LoadRoomScript(roomFileFullPath);
                        if (roomScript != null)
                        {
                            StreamWriter sw = new StreamWriter(roomFileFullPath.Substring(0, roomFileFullPath.Length - 4) + ".asc", false, Encoding.Default);
                            sw.Write(roomScript);
                            sw.Close();
                        }
                    }
                    catch (AGSEditorException ex)
                    {
                        importErrors.Add(new CompileError("Erreur lors de la sauvegarde du script de la pièce " + roomNumber + " : " + ex.Message));
                    }

                    UnloadedRoom newUnloadedRoom = new UnloadedRoom(roomNumber);
                    rooms.Add(roomNumber, newUnloadedRoom);
                    game.RootRoomFolder.Items.Add(newUnloadedRoom);
                }
                else
                {
                    importErrors.Add(new CompileWarning("Le fichier de pièce '" + roomFileFullPath + "' possède un nom non-reconnu et ne sera pas intégré au jeu."));
                }
            }

            game.RootRoomFolder.Sort(false);

            int roomCount = reader.ReadInt32();
            for (int i = 0; i < roomCount; i++)
            {
                string roomDescription = ReadNullTerminatedString(reader);
                if (rooms.ContainsKey(i))
                {
                    rooms[i].Description = roomDescription;
                }
            }
        }
Esempio n. 55
0
        public override bool Build(CompileMessages errors, bool forceRebuild)
        {
            if (!base.Build(errors, forceRebuild))
            {
                return(false);
            }
            if (!CheckPluginsHaveSharedLibraries())
            {
                errors.Add(new CompileError("Could not build for Linux due to missing plugins."));
                return(false);
            }
            foreach (string fileName in Directory.GetFiles(AGSEditor.OUTPUT_DIRECTORY))
            {
                if ((!fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) &&
                    (!Path.GetFileName(fileName).Equals("winsetup.exe", StringComparison.OrdinalIgnoreCase)) &&
                    (!Path.GetFileName(fileName).Equals(AGSEditor.CONFIG_FILE_NAME, StringComparison.OrdinalIgnoreCase)))
                {
                    Utilities.CreateHardLink(GetCompiledPath(LINUX_DATA_DIR, Path.GetFileName(fileName)), fileName, true);
                }
            }
            // Update config file with current game parameters
            Factory.AGSEditor.WriteConfigFile(GetCompiledPath(LINUX_DATA_DIR));

            foreach (KeyValuePair <string, string> pair in GetRequiredLibraryPaths())
            {
                string fileName = pair.Value;
                if (!fileName.EndsWith(pair.Key))
                {
                    fileName = Path.Combine(fileName, pair.Key);
                }
                string folderName = null;
                if ((!fileName.EndsWith("ags32")) && (!fileName.EndsWith("ags64")))
                {
                    // the engine files belong in the LINUX_DATA_DIR, but the other libs
                    // should have lib32 or lib64 subdirectories as part of their name
                    folderName = Path.GetFileName(Path.GetDirectoryName(fileName).TrimEnd(Path.DirectorySeparatorChar));
                }
                Utilities.CreateHardLink(GetCompiledPath(LINUX_DATA_DIR, folderName, Path.GetFileName(fileName)),
                                         fileName, true);
            }
            string linuxDataLib32Dir   = GetCompiledPath(LINUX_DATA_DIR, LINUX_LIB32_DIR);
            string linuxDataLib64Dir   = GetCompiledPath(LINUX_DATA_DIR, LINUX_LIB64_DIR);
            string editorLinuxDir      = Path.Combine(Factory.AGSEditor.EditorDirectory, LINUX_DIR);
            string editorLinuxLib32Dir = Path.Combine(editorLinuxDir, LINUX_LIB32_DIR);
            string editorLinuxLib64Dir = Path.Combine(editorLinuxDir, LINUX_LIB64_DIR);

            foreach (string soName in _plugins)
            {
                Utilities.CreateHardLink(Path.Combine(linuxDataLib32Dir, soName),
                                         Path.Combine(editorLinuxLib32Dir, soName), true);
                Utilities.CreateHardLink(Path.Combine(linuxDataLib64Dir, soName),
                                         Path.Combine(editorLinuxLib64Dir, soName), true);
            }
            string scriptFileName = GetCompiledPath(Factory.AGSEditor.BaseGameFileName.Replace(" ", "")); // strip whitespace from script name
            string scriptText     =
                @"#!/bin/sh
SCRIPTPATH=""$(dirname ""$(readlink -f $0)"")""

if test ""x$@"" = ""x-h"" -o ""x$@"" = ""x--help""
  then
    echo ""Usage:"" ""$(basename ""$(readlink -f $0)"")"" ""[<ags options>]""
    echo """"
fi

if test $(uname -m) = x86_64
  then" + GetSymLinkScriptForEachPlugin(true) +
                @"
  else" + GetSymLinkScriptForEachPlugin(false) +
                @"
fi
";

            scriptText = scriptText.Replace("\r\n", "\n"); // make sure script has UNIX line endings
            FileStream stream = File.Create(scriptFileName);

            byte[] bytes = Encoding.UTF8.GetBytes(scriptText);
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();
            return(true);
        }
Esempio n. 56
0
        private SpeechLipSyncLine CompilePAMFile(string fileName, CompileMessages errors)
        {
            SpeechLipSyncLine syncDataForThisFile = new SpeechLipSyncLine();
            syncDataForThisFile.FileName = Path.GetFileNameWithoutExtension(fileName);

            string thisLine;
            bool inMainSection = false;
            int lineNumber = 0;

            StreamReader sr = new StreamReader(fileName);
            while ((thisLine = sr.ReadLine()) != null)
            {
                lineNumber++;
                if (thisLine.ToLower().StartsWith("[speech]"))
                {
                    inMainSection = true;
                    continue;
                }
                if (inMainSection)
                {
                    if (thisLine.TrimStart().StartsWith("["))
                    {
                        // moved onto another section
                        break;
                    }
                    if (thisLine.IndexOf(':') > 0)
                    {
                        string[] parts = thisLine.Split(':');
                        // Convert from Pamela XPOS into milliseconds
                        int milliSeconds = ((Convert.ToInt32(parts[0]) / 15) * 1000) / 24;
                        string phenomeCode = parts[1].Trim().ToUpper();
                        int frameID = FindFrameNumberForPhenome(phenomeCode);
                        if (frameID < 0)
                        {
                            string friendlyFileName = Path.GetFileName(fileName);
                            errors.Add(new CompileError("No frame found to match phenome code '" + phenomeCode + "'", friendlyFileName, lineNumber));
                        }
                        else
                        {
                            syncDataForThisFile.Phenomes.Add(new SpeechLipSyncPhenome(milliSeconds, (short)frameID));
                        }
                    }
                }
            }
            sr.Close();
            syncDataForThisFile.Phenomes.Sort();

            // The PAM file contains start times: Convert to end times
            for (int i = 0; i < syncDataForThisFile.Phenomes.Count - 1; i++)
            {
                syncDataForThisFile.Phenomes[i].EndTimeOffset = syncDataForThisFile.Phenomes[i + 1].EndTimeOffset;
            }

            if (syncDataForThisFile.Phenomes.Count > 1)
            {
                syncDataForThisFile.Phenomes[syncDataForThisFile.Phenomes.Count - 1].EndTimeOffset = syncDataForThisFile.Phenomes[syncDataForThisFile.Phenomes.Count - 2].EndTimeOffset + 1000;
            }

            return syncDataForThisFile;
        }
Esempio n. 57
0
        public override void CommandClick(string controlID)
        {
            if (controlID == COMMAND_NEW_ITEM)
            {
                IList <Translation> items   = _agsEditor.CurrentGame.Translations;
                Translation         newItem = new Translation(GetFreeNameForTranslation());
                newItem.Name = newItem.Name;
                items.Add(newItem);

                // Create a dummy placeholder file
                StreamWriter sw = new StreamWriter(newItem.FileName);
                sw.Close();
                newItem.LoadData();

                string newNodeID = "Trl" + (items.Count - 1);
                _guiController.ProjectTree.StartFromNode(this, TOP_LEVEL_COMMAND_ID);
                AddTreeLeafForTranslation(newNodeID, newItem);
                _guiController.ProjectTree.SelectNode(this, newNodeID);
                _agsEditor.CurrentGame.FilesAddedOrRemoved = true;

                StartRename(newItem, newNodeID);
            }
            else if (controlID == COMMAND_RENAME_ITEM)
            {
                StartRename(_itemRightClicked, _commandIDRightClicked);
            }
            else if (controlID == COMMAND_MAKE_DEFAULT)
            {
                if (_guiController.ShowQuestion("This command will replace all the text in your game with the translations in this file. This means that your current default language will be lost in the process.\n\nAdditionally, all your translations will be updated to contain this translation as the source text.\n\nAre you really sure you want to continue?", MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    ReplaceGameTextWithTranslation(_itemRightClicked);
                }
            }
            else if (controlID == COMMAND_UPDATE_SOURCE)
            {
                List <Translation> translations = new List <Translation>();
                translations.Add(_itemRightClicked);
                UpdateTranslations(translations);
            }
            else if (controlID == COMMAND_UPDATE_ALL)
            {
                UpdateTranslations(_agsEditor.CurrentGame.Translations);
            }
            else if (controlID == COMMAND_COMPILE)
            {
                CompileMessages errors = new CompileMessages();
                try
                {
                    CompileTranslation(_itemRightClicked, errors);
                }
                catch (Exception e)
                {
                    errors.Add(new CompileError(e.Message));
                }
                if (errors.Count > 0)
                {
                    _guiController.ShowMessage(string.Format("Translation compiled with errors: \n\n{0}",
                                                             errors[0].Message), MessageBoxIcon.Warning);
                }
                else
                {
                    _guiController.ShowMessage("Translation compiled successfully.", MessageBoxIcon.Information);
                }
            }
            else if (controlID == COMMAND_DELETE_ITEM)
            {
                if (_guiController.ShowQuestion("Are you sure you want to delete this translation?") == DialogResult.Yes)
                {
                    string removing = _itemRightClicked.FileName;

                    /*                    if (_documents.ContainsKey(_itemRightClicked))
                     *                  {
                     *                      _guiController.RemovePaneIfExists(_documents[_itemRightClicked]);
                     *                      _documents.Remove(_itemRightClicked);
                     *                  }*/
                    _agsEditor.CurrentGame.Translations.Remove(_itemRightClicked);
                    _agsEditor.CurrentGame.FilesAddedOrRemoved = true;

                    if (File.Exists(_itemRightClicked.FileName))
                    {
                        _agsEditor.DeleteFileOnDiskAndSourceControl(_itemRightClicked.FileName);
                    }
                    RePopulateTreeView();
                    TranslationListTypeConverter.SetTranslationsList(_agsEditor.CurrentGame.Translations);
                }
            }
            else
            {
                if (controlID != TOP_LEVEL_COMMAND_ID)
                {
                    Translation translation = _agsEditor.CurrentGame.Translations[Convert.ToInt32(controlID.Substring(3))];
                    _guiController.ShowMessage("Currently you cannot edit translations within the editor. Load the file " + translation.FileName + " into your favourite text editor to do your translation work.", MessageBoxIcon.Information);

                    /*                    if (!_documents.ContainsKey(chosenFont))
                     *                  {
                     *                      Dictionary<string, object> list = new Dictionary<string, object>();
                     *                      list.Add(chosenFont.Name + " (Font " + chosenFont.ID + ")", chosenFont);
                     *
                     *                      _documents.Add(chosenFont, new ContentDocument(new FontEditor(chosenFont), chosenFont.WindowTitle, this, list));
                     *                      _documents[chosenFont].SelectedPropertyGridObject = chosenFont;
                     *                  }
                     *                  _guiController.AddOrShowPane(_documents[chosenFont]);*/
                }
            }
        }