コード例 #1
0
        public static ProjectBase CreatePlatformSpecificProject(Project coreVisualStudioProject, string fileName)
        {
            ProjectBase toReturn = null;

            if (FileManager.GetExtension(fileName) == "contentproj")
            {
                toReturn = new XnaContentProject(coreVisualStudioProject);
            }

            string errorMessage = null;

            if (toReturn == null)
            {
                toReturn = TryGetProjectTypeFromDefineConstants(coreVisualStudioProject, out errorMessage);
            }


            if (toReturn == null)
            {
                // If we got here that means that the preprocessor defines don't match what
                // Glue expects.  This is probably bad - Glue generated code will likely not
                // compile, so let's warn the user
                GlueGui.ShowMessageBox(errorMessage);
            }

            return(toReturn);
        }
コード例 #2
0
        public static void Initialize()
        {
            try
            {
                InitializeTypesNotSupported();


                mPositionedObjectMembers = new List <MemberWithType>();

                Type type = typeof(PositionedObject);

                var listToFill = mPositionedObjectMembers;

                FillListWithAvailableVariablesInType(type, listToFill);


                RemoveUnwantedVariables();

                ReorganizeVariables();
            }
            catch (Exception e)
            {
#if GLUE
                GlueGui.ShowMessageBox("Error in ExposedVariableManager " + e.ToString(), "Error");
#else
                MessageBox.Show("Error in ExposedVariableManager " + e.ToString(), "Error");
#endif
                throw new Exception("Error in ExposedVariableManager.Initialize", e);
            }
        }
コード例 #3
0
        private void AddProjectClick(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new System.Windows.Forms.OpenFileDialog();

            openFileDialog.Filter = "C# Project files (*.csproj)|*.csproj|VS Project files (*.vcproj)|*.vcproj|Android Project (*.project)|*.project";

            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var newProject = ProjectManager.AddSyncedProject(openFileDialog.FileName);

                // If newProject is null, then no project was added
                if (newProject != null)
                {
                    ViewModel.Refresh();
                }
                else
                {
                    GlueGui.ShowMessageBox("The selected project is already a synced project.");
                }

                GluxCommands.Self.SaveGlux();

                ProjectManager.SaveProjects();
            }
        }
コード例 #4
0
        public NamedObjectSave ShowAddNewObjectDialog(AddObjectViewModel addObjectViewModel = null)
        {
            NamedObjectSave newNamedObject = null;

            // add named object, add object, addnamedobject, add new object, addnewobject, createobject, addobject

            addObjectViewModel = CreateAndShowAddNamedObjectWindow(addObjectViewModel);

            if (addObjectViewModel.DialogResult == DialogResult.OK)
            {
                string whyItIsntValid = null;
                bool   isValid        = NameVerifier.IsNamedObjectNameValid(addObjectViewModel.ObjectName, out whyItIsntValid);

                if (isValid)
                {
                    if (addObjectViewModel.SourceType == SourceType.Entity && !RecursionManager.Self.CanContainInstanceOf(GlueState.Self.CurrentElement, addObjectViewModel.SourceClassType))
                    {
                        isValid        = false;
                        whyItIsntValid = "This type would result in infinite recursion";
                    }
                }

                if (isValid)
                {
                    newNamedObject = GlueCommands.Self.GluxCommands.AddNewNamedObjectToSelectedElement(addObjectViewModel);
                    GlueState.Self.CurrentNamedObjectSave = newNamedObject;
                }
                else
                {
                    GlueGui.ShowMessageBox(whyItIsntValid);
                }
            }

            return(newNamedObject);
        }
コード例 #5
0
ファイル: CameraMainPlugin.cs プロジェクト: Kr3m/FlatRedBall
        public void ShowCameraUi()
        {
            var glueProject = ProjectManager.GlueProjectSave;

            if (glueProject != null)
            {
                bool shouldShowNewUi = glueProject.DisplaySettings != null;

                if (shouldShowNewUi)
                {
                    if (control == null)
                    {
                        control = new CameraSettingsControl();
                        base.AddToTab(PluginManager.LeftTab, control, "Display Settings");
                    }
                    else
                    {
                        base.AddTab();
                    }

                    respondToViewModelChanges = false;
                    {
                        viewModel.SetFrom(glueProject.DisplaySettings);

                        bool showSupportedOrientationLink =
                            GetIfSupportsOrientation(GlueState.Self.CurrentMainProject) ||
                            GlueState.Self.SyncedProjects.Any(item => GetIfSupportsOrientation(item));

                        if (showSupportedOrientationLink)
                        {
                            viewModel.SupportedOrientationsLinkVisibility = System.Windows.Visibility.Visible;
                        }
                        else
                        {
                            viewModel.SupportedOrientationsLinkVisibility = System.Windows.Visibility.Collapsed;
                        }

                        control.DataContext = viewModel;
                    }
                    respondToViewModelChanges = true;
                }

                else
                {
                    CameraSettingsWindow cameraSettingsWindow = new CameraSettingsWindow();
                    cameraSettingsWindow.ShowDialog();
                }
            }
            else
            {
                GlueGui.ShowMessageBox("You must load or create a project first to set the camera settings.");
            }
        }
コード例 #6
0
ファイル: DropboxPlugin.cs プロジェクト: Riva3000/FlatRedBall
        private void HandleGluxLoad()
        {
            string folder            = ProjectManager.ProjectRootDirectory;
            bool   isInDropboxFolder = GetIfIsInDropBoxFolder(folder);

            if (isInDropboxFolder)
            {
                GlueGui.ShowMessageBox("This project appears to be in a Dropbox folder.  " +
                                       "Working with projects while they are in Dropbox folders may cause problems.\n\n" +
                                       "Consider moving the project out of a Dropbox folder or pausing syncing while working.");
            }
        }
コード例 #7
0
        private bool ResolveDuplicateProjectEntry(bool wasChanged, ProjectItem buildItem)
        {
#if GLUE
            MultiButtonMessageBox mbmb = new MultiButtonMessageBox();

            mbmb.MessageText = "The item " + buildItem.UnevaluatedInclude + " is part of " +
                               "the project twice.  Glue does not support double-entries in a project.  What would you like to do?";

            mbmb.AddButton("Remove the duplicate entry and continue", System.Windows.Forms.DialogResult.OK);
            mbmb.AddButton("Remove the duplicate, but show me a list of all contained objects before removal", System.Windows.Forms.DialogResult.No);
            mbmb.AddButton("Cancel loading the project - this will throw an exception", System.Windows.Forms.DialogResult.Cancel);

            DialogResult result;

            if (GlueGui.TryShowDialog(mbmb, out result))
            {
                switch (result)
                {
                case DialogResult.OK:
                    mProject.RemoveItem(buildItem);
                    mProject.ReevaluateIfNecessary();
                    break;

                case DialogResult.No:
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (var item in mProject.AllEvaluatedItems)
                    {
                        stringBuilder.AppendLine(item.ItemType + " " + item.UnevaluatedInclude);
                    }
                    string whereToSave = FileManager.UserApplicationDataForThisApplication + "ProjectFileOutput.txt";
                    FileManager.SaveText(stringBuilder.ToString(), whereToSave);
                    Process.Start(whereToSave);


                    mProject.RemoveItem(buildItem);
                    mProject.ReevaluateIfNecessary();
                    break;

                case DialogResult.Cancel:
                    throw new Exception("Duplicate entries found: " + buildItem.ItemType + " " + buildItem.UnevaluatedInclude);
                }
            }
            else
#endif
            {
                //mProject.EvaluatedItems.RemoveItemAt(i);
                mProject.RemoveItem(buildItem);
                mProject.ReevaluateIfNecessary();
            }
            wasChanged = true;
            return(wasChanged);
        }
コード例 #8
0
        private static void DeserializeToRcr(AvailableDelimiters delimiter, string fileName, out RuntimeCsvRepresentation rcr, out bool succeeded)
        {
            rcr = null;

            succeeded = true;

            try
            {
                // Let's load this bad boy and get info about the class we need to make
                rcr = CsvFileManager.CsvDeserializeToRuntime(fileName);
            }
            catch (Exception e)
            {
                GlueGui.ShowMessageBox("Error parsing CSV\n\n" + fileName + "\nAttempted to use " + delimiter + " as the delimiter.  If this is not the delimiter of the file, try changing the delimiter in Glue after the file is added");

                FlatRedBall.Glue.Plugins.PluginManager.ReceiveError(e.ToString());

                succeeded = false;
            }
        }
コード例 #9
0
        private void HandleGluxLoad()
        {
            string folder = GlueState.Self.CurrentGlueProjectDirectory;

            // This happened once, not sure why
            if (string.IsNullOrEmpty(folder))
            {
                int m = 3;
            }
            else
            {
                bool isInDropboxFolder = GetIfIsInDropBoxFolder(folder);

                if (isInDropboxFolder)
                {
                    GlueGui.ShowMessageBox("This project appears to be in a Dropbox folder.  " +
                                           "Working with projects while they are in Dropbox folders may cause problems.\n\n" +
                                           "Consider moving the project out of a Dropbox folder or pausing syncing while working.");
                }
            }
        }
コード例 #10
0
        public void GenerateAndAddToProjectIfNecessary()
        {
            string codeContents = GetCode();

            string absoluteFileName = ProjectSpecificFullFileName;

            const int numberOfTimesToTry = 5;

            int  numberOfFailures = 0;
            bool succeeded        = false;

            while (numberOfFailures < numberOfTimesToTry)
            {
                try
                {
                    FileManager.SaveText(codeContents, absoluteFileName);

                    succeeded = true;
                    break;
                }
                catch
                {
                    numberOfFailures++;
                }
            }

            if (!succeeded)
            {
                GlueGui.ShowMessageBox("Failed to generate factory at file:\n\n" +
                                       absoluteFileName + "\n\nIs the file being locked by something?\n" +
                                       "This is not a fatal error - you can manually re-generate this " +
                                       "object or make a change to it to force a regeneration.");
            }


            if (ProjectManager.ProjectBase != null && IsPartOfProject == false)
            {
                AddSelfToProject();
            }
        }
コード例 #11
0
        public void ShowCameraUi()
        {
            var glueProject = ProjectManager.GlueProjectSave;

            if (glueProject != null)
            {
                bool shouldShowNewUi = glueProject.DisplaySettings != null;

                if (shouldShowNewUi)
                {
                    if (control == null)
                    {
                        control = new CameraSettingsControl();
                        base.AddToTab(PluginManager.LeftTab, control, "Display Settings");
                    }
                    else
                    {
                        base.AddTab();
                    }

                    respondToViewModelChanges = false;
                    {
                        viewModel.SetFrom(glueProject.DisplaySettings);

                        control.DataContext = viewModel;
                    }
                    respondToViewModelChanges = true;
                }

                else
                {
                    CameraSettingsWindow cameraSettingsWindow = new CameraSettingsWindow();
                    cameraSettingsWindow.ShowDialog();
                }
            }
            else
            {
                GlueGui.ShowMessageBox("You must load or create a project first to set the camera settings.");
            }
        }
コード例 #12
0
        public static void UpdateLoadGlobalContentCode()
        {
            var classContent = GetLoadGlobalContentCode();



            string absoluteFileName = FileManager.RelativeDirectory + "GlobalContent.Generated.cs";

            bool failedSaving = false;

            try
            {
                FileWatchManager.IgnoreNextChangeOnFile(absoluteFileName);
                FileManager.SaveText(classContent.ToString(), absoluteFileName);
            }
            catch
            {
                failedSaving = true;
            }


            if (failedSaving)
            {
                System.Windows.Forms.MessageBox.Show("Could not save the file\n\n" + absoluteFileName);
            }

            if (ProjectManager.ProjectBase.GetItem(absoluteFileName) == null)
            {
                ProjectManager.ProjectBase.AddCodeBuildItem(absoluteFileName);
            }

            try
            {
                CodeWriter.InitializeStaticData(ProjectManager.GameClassFileName, true);
            }
            catch (CodeParseException exception)
            {
                GlueGui.ShowMessageBox("Could not add GlobalContent.Initialize to your Game class because of an error:\n\n" + exception.Message);
            }
        }
コード例 #13
0
        private static void RemoveCodeForCsv(ReferencedFileSave rfs, string alternativeName = null, bool saveProject = true)
        {
            if (alternativeName == null)
            {
                alternativeName = rfs.Name;
            }
            string className = rfs.GetTypeForCsvFile(alternativeName);

            // the class name will be fully qualified, but we don't want that, we want just the end:
            if (className.Contains("."))
            {
                // provides the name after the dot:
                className = FileManager.GetExtension(className);
            }

            string whatToRemove = "DataTypes/" + className + ".Generated.cs";


            if (ProjectManager.ProjectBase.RemoveItem(whatToRemove) && saveProject)
            {
                ProjectManager.SaveProjects();
            }
            string fileToDelete = whatToRemove;

            fileToDelete = ProjectManager.MakeAbsolute(fileToDelete);
            if (System.IO.File.Exists(fileToDelete))
            {
                try
                {
                    FileHelper.DeleteFile(fileToDelete);
                }
                catch (Exception e)
                {
                    GlueGui.ShowMessageBox("Could not delete the file " + fileToDelete + "\n\nThe file is no longer referneced by the project so it is not necessary to delete this file manually.");
                }
            }
        }
コード例 #14
0
        /// <summary>
        /// Injects the insideOfMethod into an event for the argument
        /// </summary>
        /// <param name="currentElement">The IElement containing the EventResponseSave.</param>
        /// <param name="eventResponseSave">The EventResponseSave which should have its contents set or replaced.</param>
        /// <param name="insideOfMethod">The inside of the methods to assign.</param>
        /// <returns>The full file name which contains the method contents.</returns>
        public static string InjectTextForEventAndSaveCustomFile(IElement currentElement, EventResponseSave eventResponseSave, string insideOfMethod)
        {
            // In case the user passes null we don't want to have null reference exceptions:
            if (insideOfMethod == null)
            {
                insideOfMethod = "";
            }

            ParsedMethod parsedMethod =
                eventResponseSave.GetParsedMethodFromAssociatedFile();


            string fullFileName = eventResponseSave.GetSharedCodeFullFileName();

            bool forceRegenerate = false;

            string fileContents = null;

            if (File.Exists(fullFileName))
            {
                fileContents    = FileManager.FromFileText(fullFileName);
                forceRegenerate = fileContents.Contains("public partial class") == false && fileContents.Contains("{") == false;

                if (forceRegenerate)
                {
                    GlueGui.ShowMessageBox("Forcing a regneration of " + fullFileName + " because it appears to be empty.");
                }
            }

            CreateEmptyCodeIfNecessary(currentElement, fullFileName, forceRegenerate);

            fileContents = FileManager.FromFileText(fullFileName);

            int indexToAddAt = 0;

            if (parsedMethod != null)
            {
                int startIndex;
                int endIndex;
                GetStartAndEndIndexForMethod(parsedMethod, fileContents, out startIndex, out endIndex);
                // We want to include the \r\n at the end, so add 2
                endIndex += 2;
                string whatToRemove = fileContents.Substring(startIndex, endIndex - startIndex);

                fileContents = fileContents.Replace(whatToRemove, null);

                indexToAddAt = startIndex;
                // remove the method to re-add it
            }
            else
            {
                indexToAddAt = EventManager.GetLastLocationInClass(fileContents, startOfLine: true);
            }
            ICodeBlock codeBlock = new CodeDocument(2);

            codeBlock.TabCharacter = "    ";

            insideOfMethod = "" + insideOfMethod.Replace("\r\n", "\r\n            ");
            codeBlock      = EventCodeGenerator.FillWithCustomEventCode(codeBlock, eventResponseSave, insideOfMethod, currentElement);

            string methodContents = codeBlock.ToString();


            fileContents = fileContents.Insert(indexToAddAt, codeBlock.ToString());

            eventResponseSave.Contents = null;
            try
            {
                FlatRedBall.Glue.IO.FileWatchManager.IgnoreNextChangeOnFile(fullFileName);
                FileManager.SaveText(fileContents, fullFileName);
            }
            catch (Exception e)
            {
                PluginManager.ReceiveError("Could not save file to " + fullFileName);
            }
            return(fullFileName);
        }
コード例 #15
0
        private bool DeserializeGluxXmlInternal(string projectFileName, string glueProjectFile)
        {
            bool succeeded = true;

            try
            {
                ProjectManager.GlueProjectSave = GlueProjectSaveExtensions.Load(glueProjectFile);

                string errors;
                ProjectManager.GlueProjectSave.PostLoadInitialize(out errors);

                if (errors != null)
                {
                    GlueGui.ShowMessageBox(errors);
                }
            }
            catch (Exception e)
            {
                MultiButtonMessageBox mbmb = new MultiButtonMessageBox();
                mbmb.MessageText = "There was an error loading the .glux file.  What would you like to do?";

                mbmb.AddButton("Nothing - Glue will abort loading the project.", DialogResult.None);
                mbmb.AddButton("See the Exception", DialogResult.OK);
                mbmb.AddButton("Try loading again", DialogResult.Retry);
                mbmb.AddButton("Test for conflicts", DialogResult.Yes);

                DialogResult result = mbmb.ShowDialog(MainGlueWindow.Self);
                mCurrentInitWindow.Close();

                switch (result)
                {
                case DialogResult.None:
                    // Do nothing;

                    break;

                case DialogResult.OK:
                    MessageBox.Show(e.ToString());
                    break;

                case DialogResult.Retry:
                    LoadProject(projectFileName);
                    break;

                case DialogResult.Yes:
                    string text = FileManager.FromFileText(glueProjectFile);

                    if (text.Contains("<<<"))
                    {
                        MessageBox.Show("There are conflicts in your GLUX file.  You will need to use a merging " +
                                        "tool or text editor to resolve these conflicts.");
                    }
                    else
                    {
                        MessageBox.Show("No Subversion conflicts found in your GLUX.");
                    }
                    break;
                }
                succeeded = false;
            }
            return(succeeded);
        }
コード例 #16
0
        public static void GenerateEventGeneratedFile(IElement element)
        {
            //string fileName = EventManager.GetEventFileNameForElement(element);
            //string fullCustomFileName = ProjectManager.ProjectBase.Directory + fileName;

            ////////////////// Early Out //////////////////////

            ///////////////// End Early Out////////////////////

            string projectDirectory = ProjectManager.ProjectBase.Directory;


            string fullGeneratedFileName = projectDirectory + EventManager.GetGeneratedEventFileNameForElement(element);

            ////////////////EARLY OUT///////////////
            if (element.Events.Count == 0)
            {
                // The file may exist.  If it does, we want to make sure it's empty:
                if (File.Exists(fullGeneratedFileName))
                {
                    FileWatchManager.IgnoreNextChangeOnFile(fullGeneratedFileName);
                    FileManager.SaveText("", fullGeneratedFileName);
                }


                return;
            }
            ///////////////END EARLY OUT///////////

            if (!File.Exists(fullGeneratedFileName))
            {
                CodeWriter.AddEventGeneratedCodeFileForElement(element);
            }
            else
            {
                // Make sure the file is part of the project
                GlueCommands.Self.ProjectCommands.UpdateFileMembershipInProject(ProjectManager.ProjectBase, fullGeneratedFileName, false, false);
            }

            ICodeBlock codeBlock = GenerateEventGeneratedCodeFile(element);

            // Let's try this a few times:
            int  numberOfFailures = 0;
            bool succeeded        = false;

            FileWatchManager.IgnoreNextChangeOnFile(fullGeneratedFileName);

            while (numberOfFailures < 3)
            {
                try
                {
                    FileManager.SaveText(codeBlock.ToString(), fullGeneratedFileName);
                    succeeded = true;
                    break;
                }
                catch
                {
                    numberOfFailures++;
                    System.Threading.Thread.Sleep(30);
                }
            }

            if (!succeeded)
            {
                GlueGui.ShowMessageBox("Could not save " + fullGeneratedFileName);
            }
        }
コード例 #17
0
        private static bool DetermineIfShouldLoad(string projectFileName)
        {
            bool shouldLoad = true;

            // see if this project references any plugins that aren't installed:
            var glueFileName = FileManager.RemoveExtension(projectFileName) + ".glux";

            if (System.IO.File.Exists(glueFileName))
            {
                try
                {
                    var tempGlux = GlueProjectSaveExtensions.Load(glueFileName);

                    var requiredPlugins = tempGlux.PluginData.RequiredPlugins;

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

                    foreach (var requiredPlugin in requiredPlugins)
                    {
                        var matchingPlugin = PluginManager.AllPluginContainers.FirstOrDefault(item => item.Name == requiredPlugin.Name);

                        if (matchingPlugin == null)
                        {
                            individualPluginMessages.Add(requiredPlugin.Name);
                        }
                        else
                        {
                            switch (requiredPlugin.VersionRequirement)
                            {
                            case VersionRequirement.EqualToOrNewerThan:
                                bool isNewerOrEqual = matchingPlugin.Plugin.Version >= new Version(requiredPlugin.Version);
                                if (!isNewerOrEqual)
                                {
                                    individualPluginMessages.Add($"{requiredPlugin.Name} must be updated\n\t{requiredPlugin.Version} required\n\t{matchingPlugin.Plugin.Version} installed");
                                }
                                break;

                            default:     // eventually fill in the rest
                                throw new NotImplementedException();
                                //break;
                            }
                        }
                    }

                    string missingPluginMessage = null;
                    if (individualPluginMessages.Count != 0)
                    {
                        missingPluginMessage = $"The project {glueFileName} requires the following plugins:\n";

                        foreach (var item in individualPluginMessages)
                        {
                            missingPluginMessage += "\n" + item;
                        }

                        missingPluginMessage += "\n\nWould you like to load the project anyway? It may not run, or may run incorrectly until all plugins are installed/updated.";
                    }

                    if (!string.IsNullOrEmpty(missingPluginMessage))
                    {
                        var result = MessageBox.Show(missingPluginMessage, "Missing Plugins", MessageBoxButtons.YesNo);

                        shouldLoad = result == DialogResult.Yes;
                    }
                }
                catch (Exception e)
                {
                    GlueGui.ShowMessageBox($"Could not load .glux file {glueFileName}. Error:\n\n{e.ToString()}");
                    shouldLoad = false;
                }
            }

            return(shouldLoad);
        }
コード例 #18
0
        public void LoadProject(string projectFileName, InitializationWindow initializationWindow = null)
        {
            TimeManager.Initialize();
            var topSection = Section.GetAndStartContextAndTime("All");

            ////////////////// EARLY OUT!!!!!!!!!
            if (!File.Exists(projectFileName))
            {
                GlueGui.ShowException("Could not find the project " + projectFileName + "\n\nOpening Glue without a project.", "Error Loading Project", null);
                return;
            }
            //////////////////// End EARLY OUT////////////////////////////////

            FileWatchManager.PerformFlushing = false;

            bool closeInitWindow = PrepareInitializationWindow(initializationWindow);

            // close the project before turning off task processing...
            ClosePreviousProject(projectFileName);

            TaskManager.Self.WaitForAllTasksFinished(pumpEvents: true);

            // turn off task processing while this is loading, so that no background tasks are running while plugins are starting up.
            // Do this *after* closing previous project, because closing previous project waits for all tasks to finish.
            TaskManager.Self.IsTaskProcessingEnabled = false;

            SetInitWindowText("Loading code project");

            var result = ProjectCreator.CreateProject(projectFileName);

            ProjectManager.ProjectBase = result.Project;

            bool shouldLoad = result.Project != null;

            if (shouldLoad && result.ShouldTryToLoadProject)
            {
                shouldLoad = DetermineIfShouldLoad(projectFileName);
            }

            if (shouldLoad)
            {
                ProjectManager.ProjectBase.Load(projectFileName);

                var sln = GlueState.Self.CurrentSlnFileName;

                if (sln == null)
                {
                    GlueCommands.Self.PrintError("Could not find .sln file for project - this may cause file reference errors, and may need to be manually fixed");
                }


                SetInitWindowText("Finding Game class");


                FileWatchManager.UpdateToProjectDirectory();
                FileManager.RelativeDirectory = FileManager.GetDirectory(projectFileName);
                // this will make other threads work properly:
                FileManager.DefaultRelativeDirectory = FileManager.RelativeDirectory;

                ElementViewWindow.AddDirectoryNodes();

                #region Load the GlueProjectSave file if one exists

                string glueProjectFile = ProjectManager.GlueProjectFileName;
                bool   shouldSaveGlux  = false;

                if (!FileManager.FileExists(glueProjectFile))
                {
                    ProjectManager.GlueProjectSave = new GlueProjectSave();

                    // temporary - eventually this will just be done in the .glux itself, or by the plugin
                    // but for now we do it here because we only want to do it on new projects
                    Plugins.EmbeddedPlugins.CameraPlugin.CameraMainPlugin.CreateGlueProjectSettingsFor(ProjectManager.GlueProjectSave);


                    ProjectManager.FindGameClass();
                    GluxCommands.Self.SaveGlux();

                    // no need to do this - will do it in PerformLoadGlux:
                    //PluginManager.ReactToLoadedGlux(ProjectManager.GlueProjectSave, glueProjectFile);
                    //shouldSaveGlux = true;

                    //// There's not a lot of code to generate so we can do it on the main thread
                    //// so we get the save to occur after
                    //GlueCommands.Self.GenerateCodeCommands.GenerateAllCodeSync();
                    //ProjectManager.SaveProjects();
                }
                PerformGluxLoad(projectFileName, glueProjectFile);

                #endregion

                SetInitWindowText("Cleaning extra Screens and Entities");


                foreach (ScreenTreeNode screenNode in ElementViewWindow.AllScreens)
                {
                    if (screenNode.SaveObject == null)
                    {
                        ScreenSave screenSave = new ScreenSave();
                        screenSave.Name = screenNode.Text;

                        ProjectManager.GlueProjectSave.Screens.Add(screenSave);
                        screenNode.SaveObject = screenSave;
                    }
                }

                foreach (EntityTreeNode entityNode in ElementViewWindow.AllEntities)
                {
                    if (entityNode.EntitySave == null)
                    {
                        EntitySave entitySave = new EntitySave();
                        entitySave.Name = entityNode.Text;
                        entitySave.Tags.Add("GLUE");
                        entitySave.Source = "GLUE";

                        ProjectManager.GlueProjectSave.Entities.Add(entitySave);
                        entityNode.EntitySave = entitySave;
                    }
                }


                UnreferencedFilesManager.Self.RefreshUnreferencedFiles(true);

                MainGlueWindow.Self.Text = "FlatRedBall Glue - " + projectFileName;

                if (shouldSaveGlux)
                {
                    GluxCommands.Self.SaveGlux();
                }

                TaskManager.Self.AddSync(() =>
                {
                    // Someone may have unloaded the project while it was starting up
                    if (GlueState.Self.CurrentGlueProject != null)
                    {
                        GlueCommands.Self.ProjectCommands.SaveProjects();
                    }
                }, "Save all projects after initial load");

                FileWatchManager.PerformFlushing = true;
                FileWatchManager.FlushAndClearIgnores();
            }
            if (closeInitWindow)
            {
                mCurrentInitWindow.Close();
            }


            Section.EndContextAndTime();

            TaskManager.Self.IsTaskProcessingEnabled = true;

            // If we ever want to make things go faster, turn this back on and let's see what's going on.
            //topSection.Save("Sections.xml");
        }
コード例 #19
0
 public void ShowMessageBox(string message)
 {
     GlueGui.ShowMessageBox(message);
 }
コード例 #20
0
ファイル: ProjectLoader.cs プロジェクト: Riva3000/FlatRedBall
        public void LoadProject(string projectFileName, InitializationWindow initializationWindow)
        {
            TimeManager.Initialize();
            var topSection = Section.GetAndStartContextAndTime("All");

            ////////////////// EARLY OUT!!!!!!!!!
            if (!File.Exists(projectFileName))
            {
                GlueGui.ShowException("Could not find the project " + projectFileName + "\n\nOpening Glue without a project.", "Error Loading Project", null);
                return;
            }
            //////////////////// End EARLY OUT////////////////////////////////

            FileWatchManager.PerformFlushing = false;

            bool closeInitWindow = PrepareInitializationWindow(initializationWindow);

            ClosePreviousProject(projectFileName);


            SetInitWindowText("Loading code project");


            ProjectManager.ProjectBase = ProjectCreator.CreateProject(projectFileName);

            bool shouldLoad = true;

            if (ProjectManager.ProjectBase == null)
            {
                DialogResult result = MessageBox.Show(
                    "The project\n\n" + projectFileName + "\n\nis an unknown project type.  Would you like more " +
                    "info on how to fix this problem?", "Unknown Project Type", MessageBoxButtons.YesNo);

                if (result == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start("http://www.flatredball.com/frb/docs/index.php?title=Glue:Reference:Projects:csproj_File");
                }
                shouldLoad = false;
            }

            // see if this project references any plugins that aren't installed:
            var glueFileName = FileManager.RemoveExtension(projectFileName) + ".glux";

            if (System.IO.File.Exists(glueFileName))
            {
                try
                {
                    var tempGlux = GlueProjectSaveExtensions.Load(glueFileName);

                    var requiredPlugins = tempGlux.PluginData.RequiredPlugins;

                    List <string> missingPlugins = new List <string>();
                    foreach (var requiredPlugin in requiredPlugins)
                    {
                        if (PluginManager.AllPluginContainers.Any(item => item.Name == requiredPlugin) == false)
                        {
                            missingPlugins.Add(requiredPlugin);
                        }
                    }

                    if (missingPlugins.Count != 0)
                    {
                        var message = $"The project {glueFileName} requires the following plugins:";

                        foreach (var item in missingPlugins)
                        {
                            message += "\n" + item;
                        }

                        message += "\nWould you like to load the project anyway? It may not run, or may run incorrectly until all plugins are installed.";

                        var result = MessageBox.Show(message, "Missing Plugins", MessageBoxButtons.YesNo);

                        shouldLoad = result == DialogResult.Yes;
                    }
                }
                catch (Exception e)
                {
                    GlueGui.ShowMessageBox($"Could not load .glux file {glueFileName}. Error:\n\n{e.ToString()}");
                    shouldLoad = false;
                }
            }

            if (shouldLoad)
            {
                ProjectManager.ProjectBase.Load(projectFileName);


                SetInitWindowText("Finding Game class");


                FileWatchManager.UpdateToProjectDirectory();
                FileManager.RelativeDirectory = FileManager.GetDirectory(projectFileName);
                // this will make other threads work properly:
                FileManager.DefaultRelativeDirectory = FileManager.RelativeDirectory;

                ElementViewWindow.AddDirectoryNodes();

                #region Load the GlueProjectSave file if one exists

                string glueProjectFile = ProjectManager.GlueProjectFileName;
                bool   shouldSaveGlux  = false;

                if (!FileManager.FileExists(glueProjectFile))
                {
                    ProjectManager.GlueProjectSave = new GlueProjectSave();

                    // temporary - eventually this will just be done in the .glux itself
                    Plugins.EmbeddedPlugins.CameraPlugin.CameraMainPlugin.CreateGlueProjectSettingsFor(ProjectManager.GlueProjectSave);


                    ProjectManager.FindGameClass();
                    GluxCommands.Self.SaveGlux();

                    // no need to do this - will do it in PerformLoadGlux:
                    //PluginManager.ReactToLoadedGlux(ProjectManager.GlueProjectSave, glueProjectFile);
                    //shouldSaveGlux = true;

                    //// There's not a lot of code to generate so we can do it on the main thread
                    //// so we get the save to occur after
                    //GlueCommands.Self.GenerateCodeCommands.GenerateAllCodeSync();
                    //ProjectManager.SaveProjects();
                }
                PerformGluxLoad(projectFileName, glueProjectFile);

                #endregion

                SetInitWindowText("Cleaning extra Screens and Entities");


                foreach (ScreenTreeNode screenNode in ElementViewWindow.AllScreens)
                {
                    if (screenNode.ScreenSave == null)
                    {
                        ScreenSave screenSave = new ScreenSave();
                        screenSave.Name = screenNode.Text;

                        ProjectManager.GlueProjectSave.Screens.Add(screenSave);
                        screenNode.ScreenSave = screenSave;
                    }
                }

                foreach (EntityTreeNode entityNode in ElementViewWindow.AllEntities)
                {
                    if (entityNode.EntitySave == null)
                    {
                        EntitySave entitySave = new EntitySave();
                        entitySave.Name = entityNode.Text;
                        entitySave.Tags.Add("GLUE");
                        entitySave.Source = "GLUE";

                        ProjectManager.GlueProjectSave.Entities.Add(entitySave);
                        entityNode.EntitySave = entitySave;
                    }
                }


                UnreferencedFilesManager.Self.RefreshUnreferencedFiles(true);

                MainGlueWindow.Self.Text = "FlatRedBall Glue - " + projectFileName;
                MainGlueWindow.Self.SaveRecentProject(projectFileName);

                if (shouldSaveGlux)
                {
                    GluxCommands.Self.SaveGlux();
                }

                TaskManager.Self.AddSync(GlueCommands.Self.ProjectCommands.SaveProjects, "Save all projects");

                FileWatchManager.PerformFlushing = true;
                FileWatchManager.FlushAndClearIgnores();
            }
            if (closeInitWindow)
            {
                mCurrentInitWindow.Close();
            }


            Section.EndContextAndTime();
            // If we ever want to make things go faster, turn this back on and let's see what's going on.
            //topSection.Save("Sections.xml");
        }
コード例 #21
0
        private void ReactToNamedObjectChangedInstanceName(NamedObjectSave namedObjectSave, object oldValueAsObject)
        {
            string oldValue = (string)oldValueAsObject;

            #region Fail checks

            string whyItIsntValid;

            NameVerifier.IsNamedObjectNameValid(namedObjectSave.InstanceName, out whyItIsntValid);

            if (!string.IsNullOrEmpty(whyItIsntValid))
            {
                GlueGui.ShowMessageBox(whyItIsntValid);
                namedObjectSave.InstanceName = oldValue;
            }
            #endregion

            else
            {
                IElement currentElement = EditorLogic.CurrentElement;

                string baseObject = ((IElement)EditorLogic.CurrentElement).BaseObject;
                // See if the entity has a base and if the base contains this name
                if (!string.IsNullOrEmpty(baseObject))
                {
                    INamedObjectContainer baseNamedObjectContainer = ObjectFinder.Self.GetNamedObjectContainer(baseObject);

                    NamedObjectSave baseNamedObject = baseNamedObjectContainer.GetNamedObjectRecursively(namedObjectSave.InstanceName);

                    if (baseNamedObject != null)
                    {
                        if (baseNamedObject.SetByDerived)
                        {
                            // There is a base element that has an object with the same
                            // name as the derived element.  The derived doesn't have a same-named
                            // object already, and the base is SetByDerived, so let's setup the derived
                            // to use the base and notify the user.
                            namedObjectSave.DefinedByBase = true;
                            MessageBox.Show("This object has the same name as\n\n" + baseNamedObject.ToString() + "\n\nIt is SetByDerived, " +
                                            "so Glue will use this as the base object for the object " + namedObjectSave.InstanceName);
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show("A base object already has an object with this name");
                            namedObjectSave.InstanceName = oldValue;
                        }
                    }
                }

                if (currentElement != null)
                {
                    // See if any named objects in this instance use this for tunneling

                    foreach (CustomVariable customVariable in currentElement.CustomVariables)
                    {
                        if (!string.IsNullOrEmpty(customVariable.SourceObject) && customVariable.SourceObject == oldValue)
                        {
                            MessageBox.Show("Changing the variable " + customVariable.Name + " so it uses " + namedObjectSave.InstanceName + " instead of " + (string)oldValue);

                            customVariable.SourceObject = namedObjectSave.InstanceName;
                        }
                    }

                    // See if any events tunnel to this NOS
                    foreach (EventResponseSave eventResponseSave in currentElement.Events)
                    {
                        if (!string.IsNullOrEmpty(eventResponseSave.SourceObject) && eventResponseSave.SourceObject == oldValue)
                        {
                            MessageBox.Show("Chaing the Event " + eventResponseSave.EventName + " so it uses " + namedObjectSave.InstanceName + " instead of " + oldValue);

                            eventResponseSave.SourceObject = namedObjectSave.InstanceName;
                        }
                    }
                }

                // If this is a layer, see if any other NOS's use this as their Layer
                if (namedObjectSave.IsLayer)
                {
                    List <NamedObjectSave> namedObjectList = EditorLogic.CurrentElement.NamedObjects;

                    string oldLayerName = (string)oldValue;

                    foreach (NamedObjectSave nos in namedObjectList)
                    {
                        nos.ReplaceLayerRecursively(oldLayerName, namedObjectSave.InstanceName);
                    }
                }
            }
        }
コード例 #22
0
        private static bool CreateConstsForCsvEntries(ReferencedFileSave initialRfs, List <TypedMemberBase> members, Dictionary <string, string> untypedMembers, ICodeBlock codeBlock)
        {
            bool succeeded = true;

            bool addToOrderedLists = true;


            CustomClassSave customClass = GetCustomClassForCsv(initialRfs.Name);

            bool usesCustomClass = customClass != null;
            List <ReferencedFileSave> rfsesForClass = new List <ReferencedFileSave>();

            if (usesCustomClass)
            {
                foreach (string name in customClass.CsvFilesUsingThis)
                {
                    ReferencedFileSave foundRfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(name);

                    // A dupe was added one during a Glue crash, so let's protect against that:
                    if (foundRfs != null && rfsesForClass.Contains(foundRfs) == false)
                    {
                        rfsesForClass.Add(foundRfs);
                    }
                }
            }
            else
            {
                rfsesForClass.Add(initialRfs);
            }


            Dictionary <ReferencedFileSave, RuntimeCsvRepresentation> representations = new Dictionary <ReferencedFileSave, RuntimeCsvRepresentation>();


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

            foreach (ReferencedFileSave rfs in rfsesForClass)
            {
                if (rfs.CreatesDictionary)
                {
                    string fileName = rfs.Name;
                    fileName = ProjectManager.MakeAbsolute(fileName);

                    var rcr = CsvFileManager.CsvDeserializeToRuntime(fileName);

                    representations.Add(rfs, rcr);
                    rcr.RemoveHeaderWhitespaceAndDetermineIfRequired();
                    int requiredIndex = rcr.GetRequiredIndex();
                    if (requiredIndex == -1)
                    {
                        succeeded = false;
                        GlueGui.ShowMessageBox("The file " + rfs.Name + " is marked as a dictionary but has no column marked as required");
                    }
                    else
                    {
                        var requiredValues = RequiredColumnValues(rcr);
                        allKeys.AddRange(requiredValues);
                    }
                }
            }

            if (allKeys.Any())
            {
                var distinct = allKeys.Distinct();

                var firstRcr      = representations.First().Value;
                int requiredIndex = firstRcr.GetRequiredIndex();

                string type = GetRequiredKeyType(firstRcr, members, untypedMembers, requiredIndex);


                FillCodeBlockWithKeys(codeBlock, type, firstRcr, allKeys.Distinct().ToArray());
                // the first rcr defines the ordered keys. Others won't add themselves to this list
                FillOrderedListWithKeys(codeBlock, type, firstRcr);
            }

            return(succeeded);
        }
コード例 #23
0
        public void RefreshUnreferencedFilesInternal()
        {
            // This may be called sync and async at the same time
            // and this can cause weird results.  let's make sure that
            // this never happens...
            lock (mLastAddedUnreferencedFiles)
            {
                mLastAddedUnreferencedFiles.Clear();
                if (ProjectManager.ContentProject != null && !mHasHadFailure)
                {
                    // return after;

                    mListBeforeAddition.Clear();

                    // Gotta to-lower it
                    // so we can do =='s checks later.
                    for (int i = 0; i < mUnreferencedFiles.Count; i++)
                    {
                        mListBeforeAddition.Add(mUnreferencedFiles[i].FilePath.ToLower());
                    }

                    mUnreferencedFiles.Clear();

                    string contentDirectory = ProjectManager.ContentProject.GetAbsoluteContentFolder();

                    List <FilePath> referencedFiles = null;

                    try
                    {
                        referencedFiles = GlueCommands.Self.FileCommands.GetAllReferencedFilePaths()
                                          .Distinct()
                                          .OrderBy(item => item.FullPath)
                                          .ToList();
                    }
                    catch
                    {
                        if (!alreadyShowedMessage)
                        {
                            alreadyShowedMessage = true;

                            string message = "Glue was unable to track references to some files.  This means that Glue will be unable to automatically add files " +
                                             "to your project, and also will be unable to remove files if necessary.  It is recommended that you fix the file reference errors and restart.";

                            GlueGui.ShowMessageBox(message);

                            mHasHadFailure = true;
                        }
                    }


                    if (referencedFiles != null)
                    {
                        var project = ProjectManager.ProjectBase;

                        // Added this here to make it easier to debug. This isn't necessary for function, as
                        // internally it does a IsContent check
                        var contentItems = project.ContentProject.EvaluatedItems
                                           .Where(item => ProjectManager.IsContent(item.UnevaluatedInclude.ToLower().Replace(@"\", @"/")))
                                           .ToList();

                        foreach (var evaluatedItem in contentItems)
                        {
                            AddIfUnreferenced(evaluatedItem, project, referencedFiles, mUnreferencedFiles);
                        }

                        Application.DoEvents();

                        // copy the list to make it not lock
                        List <ProjectBase> syncedProjectCopy = new List <ProjectBase>();

                        lock (ProjectManager.SyncedProjects)
                        {
                            syncedProjectCopy.AddRange(ProjectManager.SyncedProjects);
                        }

                        foreach (var syncedProject in syncedProjectCopy)
                        {
                            var cloned = syncedProject.ContentProject.EvaluatedItems;
                            foreach (var evaluatedItem in cloned)
                            {
                                AddIfUnreferenced(evaluatedItem, syncedProject, referencedFiles, mUnreferencedFiles);
                                // Since we're in a lock, maybe we shouldn't
                                // Allow the application to do its thing
                                //Application.DoEvents();
                            }
                        }
                    }

                    mUnreferencedFiles = mUnreferencedFiles.OrderBy(item => item.FilePath.ToLowerInvariant()).ToList();
                }
            }
        }
コード例 #24
0
        public static EntityTreeNode AddEntity(EntitySave entitySave, bool generateCode = true)
        {
            Section.GetAndStartContextAndTime("Constructor");
            EntityTreeNode treeNode = new EntityTreeNode(FileManager.RemovePath(entitySave.Name));

            Section.EndContextAndTime();
            Section.GetAndStartContextAndTime("Code file");

            treeNode.CodeFile = entitySave.Name + ".cs";

            Section.EndContextAndTime();
            Section.GetAndStartContextAndTime("Add node");

            TreeNode treeNodeToAddTo = null;
            bool     succeeded       = true;

            if (entitySave.Name.StartsWith("Entities/") == false &&
                entitySave.Name.StartsWith("Entities\\") == false)
            {
                GlueGui.ShowMessageBox(
                    "The Entity named " + entitySave.Name + " must have a name that starts with \"Entities/\"");
                succeeded = false;
            }
            if (succeeded)
            {
                string containingDirectory = FileManager.MakeRelative(FileManager.GetDirectory(entitySave.Name));

                if (containingDirectory == "Entities/")
                {
                    treeNodeToAddTo = mEntityNode;
                }
                else
                {
                    string directory = containingDirectory.Substring("Entities/".Length);

                    treeNodeToAddTo = GlueState.Self.Find.TreeNodeForDirectoryOrEntityNode(
                        directory, mEntityNode);
                    if (treeNodeToAddTo == null && !string.IsNullOrEmpty(directory))
                    {
                        // If it's null that may mean the directory doesn't exist.  We should make it
                        string absoluteDirectory = ProjectManager.MakeAbsolute(containingDirectory);
                        if (!Directory.Exists(absoluteDirectory))
                        {
                            Directory.CreateDirectory(absoluteDirectory);
                        }
                        AddDirectoryNodes(FileManager.RelativeDirectory + "Entities/", mEntityNode);

                        // now try again
                        treeNodeToAddTo = GlueState.Self.Find.TreeNodeForDirectoryOrEntityNode(
                            directory, mEntityNode);
                    }
                }

                // Someone in the chat room got a crash on the Add call.  Not sure why
                // so adding these to help find out what's up.
                if (treeNodeToAddTo == null)
                {
                    throw new NullReferenceException("treeNodeToAddTo is null.  This is bad");
                }
                if (treeNode == null)
                {
                    throw new NullReferenceException("treeNode is null.  This is bad");
                }


                treeNodeToAddTo.Nodes.Add(treeNode);
                treeNodeToAddTo.Nodes.SortByTextConsideringDirectories();

                Section.EndContextAndTime();
                Section.GetAndStartContextAndTime("Set generated");
                string generatedFile = entitySave.Name + ".Generated.cs";

                if (FileManager.FileExists(generatedFile))
                {
                    treeNode.GeneratedCodeFile = generatedFile;
                }

                Section.EndContextAndTime();
                Section.GetAndStartContextAndTime("Sort");
                SortEntities();

                Section.EndContextAndTime();

                treeNode.EntitySave = entitySave;
            }
            return(treeNode);
        }
コード例 #25
0
        private static bool CreateConstsForCsvEntries(ReferencedFileSave initialRfs, List <TypedMemberBase> members, Dictionary <string, string> untypedMembers, ICodeBlock codeBlock)
        {
            bool succeeded = true;

            bool addToOrderedLists = true;


            CustomClassSave customClass = GetCustomClassForCsv(initialRfs.Name);

            bool usesCustomClass = customClass != null;
            List <ReferencedFileSave> rfsesForClass = new List <ReferencedFileSave>();

            if (usesCustomClass)
            {
                foreach (string name in customClass.CsvFilesUsingThis)
                {
                    ReferencedFileSave foundRfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(name);

                    if (foundRfs != null)
                    {
                        rfsesForClass.Add(foundRfs);
                    }
                }
            }
            else
            {
                rfsesForClass.Add(initialRfs);
            }



            foreach (ReferencedFileSave rfs in rfsesForClass)
            {
                if (rfs.CreatesDictionary)
                {
                    string fileName = rfs.Name;
                    fileName = ProjectManager.MakeAbsolute(fileName);

                    var rcr = CsvFileManager.CsvDeserializeToRuntime(fileName);
                    rcr.RemoveHeaderWhitespaceAndDetermineIfRequired();
                    int requiredIndex = rcr.GetRequiredIndex();
                    if (requiredIndex == -1)
                    {
                        succeeded = false;
                        GlueGui.ShowMessageBox("The file " + rfs.Name + " is marked as a dictionary but has no column marked as required");
                    }
                    else
                    {
                        string type = GetRequiredKeyType(rcr, members, untypedMembers, requiredIndex);

                        FillCodeBlockWithKeys(codeBlock, type, rcr);
                        // The first entry will be the "primary" one?
                        if (addToOrderedLists)
                        {
                            FillOrderedListWithKeys(codeBlock, type, rcr);
                            addToOrderedLists = false;
                        }
                    }
                }
            }

            return(succeeded);
        }
コード例 #26
0
        public static void GenerateAndSaveDataClass(ReferencedFileSave rfs, AvailableDelimiters delimiter)
        {
            string fileName = rfs.Name;

            fileName = ProjectManager.MakeAbsolute(fileName);

            #region See if the CSV file doesn't exist and warn the user if not
            if (!System.IO.File.Exists(fileName))
            {
                MessageBox.Show("Could not find the CSV file " + fileName +
                                " when trying to generate a data file");
            }
            #endregion

            else // CSV exists
            {
                #region Save off the old delimiter and switch to using the new one - we need the old one so we can switch back after this function finishes

                char oldDelimiter = CsvFileManager.Delimiter;
                CsvFileManager.Delimiter = delimiter.ToChar();
                #endregion

                if (!string.IsNullOrEmpty(rfs.UniformRowType))
                {
                    // This simply
                    // checks to make
                    // sure the CSV is
                    // set up right - it
                    // doesn't actually generate
                    // any code because the CSV will
                    // deserialize to an array of primitives.
                    CheckUniformTypeValidity(rfs, fileName, oldDelimiter);
                }
                else
                {
                    RuntimeCsvRepresentation rcr;
                    bool succeeded;
                    DeserializeToRcr(delimiter, fileName, out rcr, out succeeded);

                    if (succeeded)
                    {
                        CsvFileManager.Delimiter = oldDelimiter;


                        string whyIsCsvWrong = GetWhyCsvIsWrong(rcr, rfs.CreatesDictionary, fileName);

                        if (!string.IsNullOrEmpty(whyIsCsvWrong))
                        {
                            GlueGui.ShowMessageBox(whyIsCsvWrong);
                            succeeded = false;
                        }
                        else
                        {
                            string className;
                            List <TypedMemberBase>      members;
                            Dictionary <string, string> untypedMembers;

                            CustomClassSave customClass = GetCustomClassForCsv(rfs.Name);

                            if (customClass == null || customClass.GenerateCode)
                            {
                                fileName = GetClassInfoFromCsvs(rfs, fileName, rcr, out className, out members, out untypedMembers);


                                succeeded = GenerateClassFromMembers(rfs, succeeded, className, members, untypedMembers);
                            }
                        }
                    }
                }
            }
        }
コード例 #27
0
        public static void ExportGroup(IEnumerable <IElement> elementGroup)
        {
            string directoryToExportTo = FileManager.UserApplicationDataForThisApplication + "ExportTemp\\";
            bool   succeeded           = true;

            if (Directory.Exists(directoryToExportTo))
            {
                try
                {
                    FileManager.DeleteDirectory(directoryToExportTo);
                }
                catch (Exception e)
                {
                    GlueGui.ShowMessageBox("Failed to delete the target export directory: \n" + e.ToString());
                    succeeded = false;
                }
            }

            Directory.CreateDirectory(directoryToExportTo);

            // If a single Entity is exported it must be self-contained
            // to be exported (it can't reference files outside of its relative
            // directory.  If a group of Entities are exported they may share files.
            // Therefore, we will populate the filesReferencedByElements List to suppress
            // warnings about files not referenced when they are part of the group.
            List <string> filesReferencedByElements = new List <string>();

            foreach (IElement element in elementGroup)
            {
                // We don't want to do this recursively - only the elements that
                // have been selected for export.
                foreach (ReferencedFileSave rfs in element.ReferencedFiles)
                {
                    string absoluteFile = ProjectManager.MakeAbsolute(rfs.Name, true);

                    absoluteFile = FileManager.Standardize(absoluteFile, null, false).ToLower();

                    filesReferencedByElements.Add(absoluteFile);
                }
            }

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

            foreach (IElement element in elementGroup)
            {
                if (!succeeded)
                {
                    break;
                }
                const bool openDirectory = false;

                string directoryForElement = directoryToExportTo + FileManager.GetDirectory(element.Name, RelativeType.Relative);
                Directory.CreateDirectory(directoryForElement);
                string outputFile = ExportElementToDirectory(element, directoryForElement, openDirectory, filesReferencedByElements, true);
                succeeded = !string.IsNullOrEmpty(outputFile);
                if (succeeded)
                {
                    filesToEmbed.Add(outputFile);
                }
            }

            if (succeeded)
            {
                // Create a zip that contains all the .entz and .scrz files
                SaveFileDialog fileDialog = new SaveFileDialog();
                fileDialog.Filter = "Glue Group (*.ggpz)|*.ggpz";
                DialogResult result = fileDialog.ShowDialog();

                if (result != DialogResult.Cancel)
                {
                    string whereToSaveFile = null;

                    whereToSaveFile = fileDialog.FileName;
                    using (ZipFile zip = new ZipFile())
                    {
                        foreach (string file in filesToEmbed)
                        {
                            string directoryInZip = FileManager.GetDirectory(FileManager.MakeRelative(file, directoryToExportTo), RelativeType.Relative);
                            zip.AddFile(file, directoryInZip);
                        }

                        zip.Save(whereToSaveFile);
                    }


                    string locationToShow = "\"" + whereToSaveFile + "\"";
                    locationToShow = locationToShow.Replace("/", "\\");
                    Process.Start("explorer.exe", "/select," + locationToShow);
                }
            }
        }