private bool getGMEConsole()
        {
            if (GMEConsole == null || GMEConsole.gme == null)
            {
                GMEConsole = GMEConsole.CreateFromProject(this.project);
            }

            return(GMEConsole != null && GMEConsole.gme != null);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Called when an FCO or folder changes
 /// </summary>
 /// <param name="subject">the object the event(s) happened to</param>
 /// <param name="eventMask">objectevent_enum values ORed together</param>
 /// <param name="param">extra information provided for cetertain event types</param>
 public void ObjectEvent(MgaObject subject, uint eventMask, object param)
 {
     // TODO: Handle object events (OR eventMask with the members of objectevent_enum)
     // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask
     if (GMEConsole == null)
     {
         GMEConsole = GMEConsole.CreateFromProject(project);
     }
     TriggerQudtRefreshIfNeeded();
 }
Ejemplo n.º 3
0
        public void CallCyPhy2CADWithTransaction(MgaProject project, MgaFCO toplevelAssembly, int param)
        {
            if (GMEConsole == null)
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
            }
            Dictionary <MgaFCO, MgaFCO> objectMap = new Dictionary <MgaFCO, MgaFCO>();

            try
            {
                project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED);
                handleEvents = false;
                GenerateCADAssemblyXml(project, toplevelAssembly, param);

                try
                {
                    HighlightInTree(toplevelAssembly, 1);
                }
                catch (Exception e)
                {
                    GMEConsole.Error.Write("Error during processing the model: " + e.Message);
                    // Don't do anything, there won't be highlight
                }
            }
            finally
            {
                project.AbortTransaction();
                handleEvents = true;
            }
        }
Ejemplo n.º 4
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);

                MgaGateway.BeginTransaction(transactiontype_enum.TRANSACTION_NON_NESTED);
                try
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                }
                finally
                {
                    MgaGateway.AbortTransaction();
                }
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Ejemplo n.º 5
0
        public void MainInTransaction(InterpreterMainParameters parameters)
        {
            this.mainParameters = (InterpreterMainParameters)parameters;
            if (GMEConsole == null)
            {
                GMEConsole = GMEConsole.CreateFromProject(mainParameters.Project);
            }

            var    currentObject          = mainParameters.CurrentFCO;
            var    currentOutputDirectory = mainParameters.OutputDirectory;
            string artifactName           = string.Empty;
            string metaBaseName           = currentObject.MetaBase.Name;

            if (metaBaseName == typeof(CyPhyClasses.DesignContainer).Name)
            {
                artifactName = ExportToFile(CyPhyClasses.DesignContainer.Cast(currentObject), currentOutputDirectory);
            }
            else if (metaBaseName == typeof(CyPhyClasses.ComponentAssembly).Name)
            {
                artifactName = ExportToFile(CyPhyClasses.ComponentAssembly.Cast(currentObject), currentOutputDirectory);
            }
            else if (IsTestBenchType(metaBaseName))
            {
                artifactName = ExportToFile(CyPhyClasses.TestBenchType.Cast(currentObject), currentOutputDirectory);
            }

            if (!string.IsNullOrWhiteSpace(artifactName))
            {
                var manifest = AVM.DDP.MetaTBManifest.OpenForUpdate(currentOutputDirectory);
                manifest.AddArtifact(Path.GetFileName(artifactName), "Design Model");
                manifest.Serialize(currentOutputDirectory);
            }
        }
Ejemplo n.º 6
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                });
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Ejemplo n.º 7
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Ejemplo n.º 8
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            GMEConsole = GMEConsole.CreateFromProject(project);
            GMEConsole.Out.WriteLine("Running the AddConnector interpreter...");

            Boolean ownLogger = false;

            if (Logger == null)
            {
                ownLogger = true;
                Logger    = new CyPhyGUIs.GMELogger(project, "AddConnector");
            }

            GMEConsole.Out.WriteLine("\n======================================================================================================================================\n");

            using (Logger)  // Ensure Logger is disposed if there is an unexpected exception. MOT-84
            {
                Logger.WriteInfo("Starting AddConnector.");

                AddConnector(currentobj, selectedobjs);

                Logger.WriteInfo("The AddConnector interpreter has finished.");
            }

            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
Ejemplo n.º 9
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                }, abort: false);
            }
            finally
            {
                MgaGateway      = null;
                project         = null;
                currentobj      = null;
                this.currentobj = null;
                this.sut        = null;
                selectedobjs    = null;
                GMEConsole      = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// This function is called for each interpreter invocation before Main.
        /// Don't perform MGA operations here unless you open a tansaction.
        /// </summary>
        /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
        public void Initialize(MgaProject project)
        {
            // TODO: Add your initialization code here...
            Contract.Requires(project != null);

            GMEConsole = GMEConsole.CreateFromProject(project);
            MgaGateway = new MgaGateway(project);
        }
Ejemplo n.º 11
0
 private void ConnectionClosed(Exception e)
 {
     SyncControl.BeginInvoke((System.Action) delegate
     {
         if (addon != null)
         {
             GMEConsole console = GMEConsole.CreateFromProject(addon.Project);
             console.Error.WriteLine("Connection to MetaLink lost.");
             //componentEditMessages.Clear();
             interests.Clear();
             AssemblyID = null;
             CloseMetaLinkBridge();
             if (console.gme != null)
             {
                 // Marshal.FinalReleaseComObject(console.gme); is this needed?
             }
             Enable(false);
             if (syncedComponents.Count > 0)
             {
                 bool inTx = ((addon.Project.ProjectStatus & 8) != 0);
                 if (inTx == false)
                 {
                     addon.Project.BeginTransactionInNewTerr();
                 }
                 try
                 {
                     foreach (string id in syncedComponents.Keys)
                     {
                         ISIS.GME.Common.Interfaces.Base model = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, id);
                         if (model == null)
                         {
                             model = CyphyMetaLinkUtils.GetComponentByAvmId(addon.Project, id);
                         }
                         if (model != null)
                         {
                             HighlightInTree(model, 0);
                         }
                     }
                 }
                 finally
                 {
                     if (inTx == false)
                     {
                         addon.Project.AbortTransaction();
                     }
                 }
                 syncedComponents.Clear();
                 designIdToCadAssemblyXml.Clear();
             }
         }
     });
 }
Ejemplo n.º 12
0
        void DragNDropHandler(string filename)
        {
            Tuple <Type, MethodInfo> method;

            if (dictofCATDnDMethods.TryGetValue(Path.GetExtension(filename), out method))
            {
                CATModule newinst = CreateCATModuleLogged(method.Item1);

                method.Item2.Invoke(newinst, new object[] { filename });

                GMEConsole console = GMEConsole.CreateFromProject(this.StashProject);
                console.Info.WriteLine("Processed " + filename);
                Marshal.ReleaseComObject(console.gme);
            }
        }
Ejemplo n.º 13
0
        public static string ExportToFile(CyPhy.Component c, String s_outFilePath)
        {
            try
            {
                avm.Component avmComponent = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(c);
                SerializeAvmComponent(avmComponent, s_outFilePath);

                return(s_outFilePath);
            }
            catch (Exception ex)
            {
                var console = GMEConsole.CreateFromProject(c.Impl.Project);
                console.Error.WriteLine("Exception Parsing {0}: {1}", Safeify(c.Name), ex.Message);
                return(null);
            }
        }
Ejemplo n.º 14
0
        public static String ExportToFile(CyPhy.Component c, String s_outFolder)
        {
            try
            {
                avm.Component avmComponent  = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(c);
                String        s_outFilePath = String.Format("{0}\\{1}.component.acm", s_outFolder, System.IO.Path.GetRandomFileName());
                SerializeAvmComponent(avmComponent, s_outFilePath);

                return(s_outFilePath);
            }
            catch (Exception ex)
            {
                var console = GMEConsole.CreateFromProject(c.Impl.Project);
                console.Error.WriteLine("Exception Parsing {0}: {1}", Safeify(c.Name), ex.Message);
                return(null);
            }
        }
Ejemplo n.º 15
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                if (currentobj == null)
                {
                    // TODO: Add Ballistic TB here once supported.
                    this.GMEConsole.Error.Write("CyPhyMultiJobRun must be called from either a BlastTestBench, CFDTestBench, or BallisticTestBench.");
                    return;
                }

                MgaGateway = new MgaGateway(project);
                string kindName = null;
                MgaGateway.PerformInTransaction(delegate
                {
                    kindName = currentobj.MetaBase.Name;
                });

                if (kindName == "CFDTestBench" || kindName == "BlastTestBench" || kindName == "BallisticTestBench")
                {
                }
                else
                {
                    this.GMEConsole.Error.Write("CyPhyMultiJobRun must be called from either a BlastTestBench or CFDTestBench, not '{0}'", kindName);
                    return;
                }

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Ejemplo n.º 16
0
        public FlexConsole(ConsoleType consoleType, MgaProject mgaProject = null)
        {
            switch (consoleType)
            {
            case ConsoleType.NONE:
                _info = _warning = _error = _out = new NullTextWriter();
                break;

            case ConsoleType.CONSOLE:
                _info = _warning = _error = Console.Error;
                _out  = Console.Out;
                break;

            case ConsoleType.GMECONSOLE:
                _gmeConsole = GMEConsole.CreateFromProject(mgaProject);
                _info       = _gmeConsole.Info;
                _warning    = _gmeConsole.Warning;
                _error      = _gmeConsole.Error;
                _out        = _gmeConsole.Out;
                break;
            }
        }
Ejemplo n.º 17
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                },
                                                transactiontype_enum.TRANSACTION_NON_NESTED);
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                //ISIS.GME.Common.Utils.ObjectCache.Clear();


                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }
Ejemplo n.º 18
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                this.project = project;
                GMEConsole   = GMEConsole.CreateFromProject(project);
                MgaGateway   = new MgaGateway(project);

                project.CreateAddOn(this, out addon);
                // addOn->put_EventMask(OBJEVENT_ATTR | OBJEVENT_CONNECTED));

                MgaGateway.PerformInTransaction(delegate
                {
                    component = Main(project, currentobj, selectedobjs, Convert(param));
                });

                if (GMEConsole.gme != null && component != null)
                {
                    GMEConsole.gme.ShowFCO(component, false);
                }
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                // GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Ejemplo n.º 19
0
        public GMELogger(MgaProject project, string interpreterName = null)
        {
            this.m_project = project;
            this.GMEConsoleLoggingLevel = MessageType_enum.Success;

            var gme_console = GMEConsole.CreateFromProject(project);

            this.AddWriter(gme_console.Out);

            if (string.IsNullOrWhiteSpace(interpreterName) == false)
            {
                var logFilePath = Path.Combine(MgaExtensions.MgaExtensions.GetProjectDirectoryPath(project), "log");

                Directory.CreateDirectory(logFilePath);

                string logFileName = string.Format("{0}.{1}.log",
                                                   interpreterName,
                                                   System.Diagnostics.Process.GetCurrentProcess().Id);

                this.AddWriter(Path.Combine(logFilePath, logFileName));

                // TODO: would be nice to log as html file too.
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Called when an FCO or folder changes
        /// </summary>
        /// <param name="subject">the object the event(s) happened to</param>
        /// <param name="eventMask">objectevent_enum values ORed together</param>
        /// <param name="param">extra information provided for cetertain event types</param>
        public void ObjectEvent(MgaObject subject, uint eventMask, object param)
        {
            if (!componentEnabled || !handleEvents)
            {
                return;
            }
            if (GMEConsole == null)
            {
                GMEConsole = GMEConsole.CreateFromProject(subject.Project);
            }

            // TODO: Handle object events (OR eventMask with the members of objectevent_enum)
            // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask

            // If the event is OBJEVENT_DESTROYED, most operations on subject will fail
            //   Safe operations: getting Project, ObjType, ID, MetaRole, Meta, MetaBase, Name, AbsPath
            //   Operations that will fail: all others, including attribute access and graph navigation
            //     Try handling OBJEVENT_PRE_DESTROYED if these operations are necessary

            // Be careful not to modify Library objects (check subject.IsLibObject)

            // MessageBox.Show(eventMask.ToString());
            // GMEConsole.Out.WriteLine(subject.Name);
        }
Ejemplo n.º 21
0
        public Checker(MgaFCO model, MgaProject project, IMgaTraceability traceability = null, CyPhyGUIs.GMELogger logger = null)
        {
            Model   = model;
            Project = project;
            if (logger != null)
            {
                this.Logger = logger;
            }
            else
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
            }

            registeredRules = new ConcurrentDictionary <string, List <RuleDescriptor> >();

            if (traceability == null)
            {
                this.Traceability = new META.MgaTraceability();
            }
            else
            {
                this.Traceability = traceability;
            }
        }
Ejemplo n.º 22
0
        // 8/16/13
        private void TraverseComponentAssemblyForComponentExport(ComponentIndex compindex, CyPhy.ComponentAssembly componentasm, string OutputDirectory, string ProjectDirectory)
        {
            foreach (CyPhy.ComponentRef cref in componentasm.Children.ComponentRefCollection)
            {
                throw new Exception("Model not fully elaborated, contains ComponentRef [" + cref.Path + "]");
            }

            foreach (CyPhy.ComponentAssembly cainst in componentasm.Children.ComponentAssemblyCollection)
            {
                TraverseComponentAssemblyForComponentExport(compindex, cainst, OutputDirectory, ProjectDirectory);
            }


            foreach (CyPhy.Component cint in componentasm.Children.ComponentCollection)
            {
                var    console       = GMEConsole.CreateFromProject(cint.Impl.Project);
                string comp_inst_loc = cint.Attributes.InstanceGUID; //Component Instance
                char[] charsToTrim   = { '{', '}' };

                string ACMDir = Path.Combine(OutputDirectory, "ComponentACMs");  //create folder for component acm's
                if (!Directory.Exists(ACMDir))
                {
                    Directory.CreateDirectory(ACMDir);
                }

                string avmid = cint.Attributes.AVMID;

                string newACMComponentFileLocation;
                char[] charsToTrim1    = { '{', '}' };
                string RandACMFileName = System.IO.Path.GetRandomFileName() + ".component.acm";
                newACMComponentFileLocation = Path.Combine(ACMDir, RandACMFileName);
                String classification = "";
                try
                {
                    // First, try to copy the original ACM file, if found.
                    // If not, then export a new one. CAD model must be present.
                    string originalACMFilePath = "";
                    if (META.ComponentLibraryManager.TryGetOriginalACMFilePath(cint, out originalACMFilePath, META.ComponentLibraryManager.PathConvention.ABSOLUTE, ProjectDirectory: ProjectDirectory))
                    {
                        File.Copy(originalACMFilePath, newACMComponentFileLocation);
                        classification = cint.Attributes.Classifications.Split('\n').FirstOrDefault();
                    }
                    else
                    {
                        const string   cadFormat = "Creo";
                        CyPhy.CADModel cadmodel  = cint.Children.CADModelCollection.FirstOrDefault(x => x.Attributes.FileFormat.ToString() == cadFormat);
                        if (cadmodel == null || cadmodel.Attributes.FileFormat.ToString() != cadFormat)
                        {
                            console.Warning.WriteLine("Skipping component export for {0}. No original ACM file found and no CAD model present in component.", Safeify(cint.Name));
                            continue;
                        }
                        else
                        {
                            var avmComponentModel = CyPhyML2AVM.AVMComponentBuilder.CyPhyML2AVM(cint);
                            SerializeAvmComponent(avmComponentModel, newACMComponentFileLocation);
                            classification = avmComponentModel.Classifications.FirstOrDefault();
                        }
                    }
                }
                catch (Exception ex)
                {
                    //var console = GMEConsole.CreateFromProject(cint.Impl.Project);
                    console.Warning.WriteLine("Unable to find original ACM file or export a new one for {0}. Reason: {1} Moving to next component.", Safeify(cint.Name), Safeify(ex.Message));
                    continue;
                }

                System.Uri acm           = new Uri(newACMComponentFileLocation);
                System.Uri acm_folder    = new Uri(ACMDir);
                string     relative_path = Uri.UnescapeDataString(acm_folder.MakeRelativeUri(acm).ToString());

                compindex.AddMember(cint.Name, cint.Attributes.AVMID, cint.Attributes.InstanceGUID, relative_path, classification);  //add component to index
                compindex.Serialize();
                compindex.SerializeToFile(Path.Combine(OutputDirectory, "component_index.json"));
            }
        }
Ejemplo n.º 23
0
        public void InvokeEx(MgaProject project,
                             MgaFCO currentobj,
                             MgaFCOs selectedobjs,
                             int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole  = GMEConsole.CreateFromProject(project);
                MgaGateway  = new MgaGateway(project);
                this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);

                if (currentobj == null)
                {
                    this.Logger.WriteError("Invalid context. This interpreter can only be run if open in the correct context (E.g., test bench).");
                    return;
                }

                GMEConsole.Out.WriteLine(DateTime.Now.ToString() + " running CyPhyPrepIFab Interpreter");

                //InitLogger();

                // [1] CyPhy2CAD
                // [2] Export DDP, Manufacture XML, Manufacture Manifest
                // [3] Generate AppendArtifact.py - script to append artifacts to testbench_manifest.json files
                // [4] Generate DesignModel1BOM.py - script to generate .bom.json from ddp file
                // [5] Generate main run bat file

                //CallCAD(project, currentobj, selectedobjs, param);                              // CyPhy2CAD
                MgaGateway.PerformInTransaction(delegate
                {
                    string kindName = string.Empty;
                    if (currentobj != null)
                    {
                        kindName = currentobj.MetaBase.Name;
                    }

                    if (string.IsNullOrEmpty(kindName) == false && kindName != typeof(CyPhyClasses.TestBench).Name)
                    {
                        Logger.WriteFailed("CyPhyPrepIFAB must be called from a TestBench.");
                        return;
                    }

                    ElaborateModel(project, currentobj, selectedobjs, param);                       // elaborate model
                    CallCAD(project, currentobj, selectedobjs, param);                              // CyPhy2CAD
                    ManufacturingGeneration(currentobj);                                            // DDP, Manufacture XML, Manufacture Manifest
                },
                                                transactiontype_enum.TRANSACTION_NON_NESTED);


                GenerateAppendArtifactScript();                                                     // AppendArtifact.py
                GenerateBOMGenScript();                                                             // DesignModel1BOM.py
                GenerateRunBatFile();                                                               // main run bat file

                GMEConsole.Out.WriteLine("CyPhyPrepIFab Interpreter Finished!");
            }
            catch (Exception)
            {
                Logger.WriteError("{0} has finished with critical errors. Please see above.", this.ComponentName);
            }

            finally
            {
                //Trace.Close();
                MgaGateway = null;
                if (Logger != null)
                {
                    Logger.Dispose();
                }
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Called when an FCO or folder changes
        /// </summary>
        /// <param name="subject">the object the event(s) happened to</param>
        /// <param name="eventMask">objectevent_enum values ORed together</param>
        /// <param name="param">extra information provided for cetertain event types</param>
        public void ObjectEvent(MgaObject subject, uint eventMask, object param)
        {
            if (!componentEnabled)
            {
                return;
            }

            if (subject.HasReadOnlyAccess())
            {
                return;
            }

            if (GMEConsole == null)
            {
                GMEConsole = GMEConsole.CreateFromProject(subject.Project);
            }

            // TODO: Handle object events (OR eventMask with the members of objectevent_enum)
            // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask
            uint uOBJEVENT_ATTR      = 0;
            uint uOBJEVENT_CREATED   = 0;
            uint uOBJEVENT_NEWCHILD  = 0;
            uint uOBJEVENT_LOSTCHILD = 0;
            uint uOBJEVENT_OPENMODEL = 0;

            unchecked { uOBJEVENT_ATTR = (uint)objectevent_enum.OBJEVENT_ATTR; }
            unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; }
            unchecked { uOBJEVENT_NEWCHILD = (uint)objectevent_enum.OBJEVENT_NEWCHILD; }
            unchecked { uOBJEVENT_LOSTCHILD = (uint)objectevent_enum.OBJEVENT_LOSTCHILD; }
            unchecked { uOBJEVENT_OPENMODEL = (uint)objectevent_enum.OBJEVENT_OPENMODEL; }

            if ((eventMask & uOBJEVENT_CREATED) != 0)
            {
                if (subject.IsLibObject || subject.IsWritable == false)
                {
                    return;
                }
                if (subject.MetaBase.Name == "TestBenchRef")
                {
                    if (subject as MgaReference != null)
                    {
                        UpdateColor((subject as MgaReference).Referred);
                    }
                }
                else if (subject.MetaBase.Name == "Optimizer")
                {
                    (subject as MgaFCO).RegistryValue["portLabelLength"] = "0";
                }
                else if (subject.MetaBase.Name == "VariableSweep")
                {
                    (subject as MgaFCO).RegistryValue["dstStyle"] = "arrow";
                    (subject as MgaFCO).RegistryValue["color"]    = "0xff80c0";
                }
                else if (subject.MetaBase.Name == "ObjectiveMapping")
                {
                    (subject as MgaFCO).RegistryValue["dstStyle"] = "arrow";
                    (subject as MgaFCO).RegistryValue["color"]    = "0x7cadde";
                }
            }
            else if ((eventMask & uOBJEVENT_ATTR) != 0)
            {
                this.DisplayPCCIterations(subject, true);

                if (subject.MetaBase.Name == "ValueFlow")
                {
                    // set the src custom formula's name to the specified name
                    // in the ValueFlow attribute field
                    MgaSimpleConnection ValueFlow = subject as MgaSimpleConnection;
                    var src = ValueFlow.Src;
                    if (src.Meta.Name == "CustomFormula")
                    {
                        foreach (MgaAttribute attr in ValueFlow.Attributes)
                        {
                            if (attr.Meta.Name == "FormulaVariableName")
                            {
                                if (string.IsNullOrEmpty(attr.StringValue) == false)
                                {
                                    src.Name = attr.StringValue;
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (subject.MetaBase.Name == "TestBench")
                {
                    // Excel import helper
                    MgaModel testBench = subject as MgaModel;

                    // call color helper
                    UpdateColor(testBench as MgaFCO);
                }
            }
            else if ((eventMask & uOBJEVENT_NEWCHILD) != 0 || (eventMask & uOBJEVENT_LOSTCHILD) != 0)
            {
                this.DisplayPCCIterations(subject, false);
            }
            else if ((eventMask & uOBJEVENT_OPENMODEL) != 0)
            {
            }
            //MessageBox.Show(eventMask.ToString());
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Given a component, ensures that the component has a backend folder
        /// for storing resources. Ensures that the Component has an AVMID unique
        /// to the project.  Creates a folder if necessary.
        /// </summary>
        /// <param name="component"></param>
        /// <param name="ProjectDirectory">Directory in which the /components/ folder resides. Defaults to project directory of <paramref name="component"/></param>
        /// <returns>The path of the Component folder, relative to the project root</returns>
        public static String EnsureComponentFolder(CyPhy.Component component, string ProjectDirectory = null)
        {
            Boolean bIsArchetype = (component.ParentContainer.Kind == "Components");

            String path = "";

            EnsureAVMID(component);

            var    mp_MgaProject = component.Impl.Project;
            String p_ProjectRoot = ProjectDirectory ?? mp_MgaProject.GetRootDirectoryPath();

            // META-2640 use full path instead of relative project path
            if (p_ProjectRoot == "")
            {
                p_ProjectRoot = ".";
            }
            p_ProjectRoot = Path.GetFullPath(p_ProjectRoot);
            var lastChar = p_ProjectRoot.Last();

            if (lastChar != '\\' && lastChar != '/')
            {
                p_ProjectRoot += '\\';
            }

            // Try to get a path from the CyPhy model.
            // If that fails, check the manifest.
            Boolean bHasFolderSpecified = false;

            if (!String.IsNullOrWhiteSpace(component.Attributes.Path))
            {
                bHasFolderSpecified = true;
                path = component.Attributes.Path;

                // Strip filename if necessary
                if (path.EndsWith(".acm"))
                {
                    path = Path.GetDirectoryName(path);
                }
                else if (path.EndsWith("ComponentData.xml"))
                {
                    path = Path.GetDirectoryName(path);
                }
            }
            else
            {
                // If a project file already exists, this will load it.
                MetaAvmProject proj = MetaAvmProject.Create(p_ProjectRoot, component.Impl.Project, null, GMEConsole.CreateFromProject(mp_MgaProject));

                // Check to see if this component has a folder already.
                var c_CompEntryInProjectFile = proj.Project.Components.Find(x => x.avmid == component.Attributes.AVMID);
                if (c_CompEntryInProjectFile != null)
                {
                    bHasFolderSpecified = true;
                    path = Path.GetDirectoryName(c_CompEntryInProjectFile.modelpath);
                }
            }

            bHasFolderSpecified = bHasFolderSpecified &&
                                  !PathContainsIllegalChar(path);

            if (bHasFolderSpecified && !Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            // Only create new folders for archetypes
            else if (!bHasFolderSpecified && bIsArchetype)
            {
                var absPath = CreateComponentFolder(mp_MgaProject);
                path = MakeRelativePath(p_ProjectRoot, absPath);
                path = path.Replace('\\', '/') + '/';
            }

            // Strip any leading path character
            if (path.Length >= 2 && (path.Substring(0, 2) == "./" || path.Substring(0, 2) == ".\\"))
            {
                path = path.Remove(0, 2);
            }

            // Store the path in the component's attribute for faster retrieval next time.
            component.Attributes.Path = path;

            return(path);
        }
Ejemplo n.º 26
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }
            if (currentobj == null)
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                GMEConsole.Warning.WriteLine("Please run in the context of a TestBench");
                return;
            }

            // Make sure running within the context of a testbench
            bool inTBContext = false;

            MgaGateway.PerformInTransaction(delegate
            {
                if (currentobj.Meta.Name == "TestBench")
                {
                    inTBContext = true;
                }
            });
            if (!inTBContext)
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                GMEConsole.Warning.WriteLine("Please run in the context of a TestBench");
                return;
            }

            // Need to get an output path from the user.
            using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog())
            {
                fbd.Description = "Choose a path for the generated files.";
                //fbd.ShowNewFolderButton = true;
                DialogResult dr = fbd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    OutputDirectory = fbd.SelectedPath;
                }
                else
                {
                    GMEConsole = GMEConsole.CreateFromProject(project);
                    GMEConsole.Out.WriteLine("CyPhyComplexity: Operation cancelled");
                    return;
                }
            }

            try
            {
                CallElaboratorAndMain(project, currentobj, selectedobjs, param);
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Ejemplo n.º 27
0
 /// <summary>
 /// This function is called for each interpreter invocation before Main.
 /// Don't perform MGA operations here unless you open a transaction.
 /// </summary>
 /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
 public void Initialize(MgaProject project)
 {
     GMEConsole = GMEConsole.CreateFromProject(project);
     MgaGateway = new MgaGateway(project);
 }
Ejemplo n.º 28
0
        public void DesignPackageImport()
        {
            // Clean the test directory
            var pathTest = Path.Combine(META.VersionInfo.MetaPath,
                                        "test",
                                        "InterchangeTest",
                                        "DesignInterchangeTest",
                                        "ImportTestUnits",
                                        "Package");

            foreach (var path in Directory.EnumerateDirectories(pathTest))
            {
                Directory.Delete(path, true);
            }
            foreach (var path in Directory.EnumerateFiles(pathTest, "*.*"))
            {
                if (!path.Contains("NestedFolders.adp"))
                {
                    File.Delete(path);
                }
            }

            // Create a test project
            var proj = new MgaProject();

            proj.Create("MGA=" + Path.Combine(pathTest, "testmodel.mga"), "CyPhyML");

            try
            {
                String pathCA = null;
                proj.PerformInTransaction(() =>
                {
                    // Instantiate the importer and import the package
                    var importer = new AVMDesignImporter(GMEConsole.CreateFromProject(proj), proj);

                    var mdlCA = importer.ImportFile(Path.Combine(pathTest, "NestedFolders.adp"), AVMDesignImporter.DesignImportMode.CREATE_CAS);
                    var ca    = CyPhyClasses.ComponentAssembly.Cast(mdlCA.Impl);
                    pathCA    = ca.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
                });

                // Check the design's backend folder for all files except for the ADM.
                var filesExpected = new List <String>
                {
                    "testObject.txt",
                    "dir1/testObject.txt",
                    "dir1/dir1a/testObject.txt",
                    "dir2/testObject.txt"
                };
                var filesInDir = Directory.GetFiles(pathCA, "*.*", SearchOption.AllDirectories);

                Assert.Equal(filesExpected.Count(), filesInDir.Count());
                foreach (var file in filesExpected)
                {
                    String fullPath = Path.Combine(pathCA, file);
                    Assert.True(File.Exists(fullPath));
                }
            }
            finally
            {
                proj.Save();
                proj.Close();
            }
        }
Ejemplo n.º 29
0
        private void RenameComponentDirectory(CyPhy.Component component, string oldPath)
        {
            if (string.IsNullOrEmpty(oldPath) || Path.GetFullPath(oldPath) == Path.GetFullPath(component.Attributes.Path))
            {
                return;
            }
            // CPMDecorator may hold handle to icon. Try to free it. (Doesn't work if still open in the model editor)
            CoFreeUnusedLibraries();

            // Check to see if this "changed" path is the same one we saw last time we were in this function, post-normalization.
            // If so, then don't consider this a rename, and return.
            var    componentGuid = component.Guid.ToString();
            String lastPath;

            if (lastObservedPaths.TryGetValue(componentGuid, out lastPath) && lastPath.Equals(component.Attributes.Path))
            {
                return;
            }

            var project     = component.Impl.Project;
            var projectRoot = Path.GetFullPath(project.GetRootDirectoryPath());

            if (Directory.Exists(Path.Combine(projectRoot, component.Attributes.Path)))
            {
                var console = GMEConsole.CreateFromProject(project);
                if (console.gme != null)
                {
                    console.Error.WriteLine(String.Format("Cannot move component directory to {0}: this directory already exists.", component.Attributes.Path));
                    Marshal.FinalReleaseComObject(console.gme);
                }
                Marshal.ThrowExceptionForHR(-2023391233); // E_MGA_CONSTRAINT_VIOLATION	= 0x87657fff
            }

            if (Directory.Exists(Path.Combine(projectRoot, oldPath)))
            {
                // Normalize path syntax
                if (component.Attributes.Path.Contains("\\"))
                {
                    component.Attributes.Path = component.Attributes.Path.Replace("\\", "/");
                }
                if (component.Attributes.Path.EndsWith("/") == false)
                {
                    component.Attributes.Path = component.Attributes.Path + "/";
                }
                var pathWithoutTrailingSlash = Path.GetDirectoryName(component.Attributes.Path);

                // Directory.CreateDirectory(Path.Combine(projectRoot, Path.GetDirectoryName(pathWithoutTrailingSlash)));
                try
                {
                    Directory.Move(Path.Combine(projectRoot, oldPath), Path.Combine(projectRoot, pathWithoutTrailingSlash));
                }
                catch (IOException e)
                {
                    var console = GMEConsole.CreateFromProject(project);
                    if (console.gme != null)
                    {
                        string    msg = String.Format("Cannot move component directory {0}.", oldPath);
                        const int E_SHARING_VIOLATION = unchecked ((int)0x80070020);
                        const int E_ACCESS_DENIED     = unchecked ((int)0x80070005);
                        if (Marshal.GetHRForException(e) == E_SHARING_VIOLATION || Marshal.GetHRForException(e) == E_ACCESS_DENIED)
                        {
                            msg = msg + " Check that the folder and files it contains are not open in another program.";
                        }
                        console.Info.WriteLine(msg);
                        //Marshal.FinalReleaseComObject(console.gme);
                    }

                    throw;
                }
                var iconPath = (component.Impl as GME.MGA.IMgaFCO).get_RegistryValue("icon");
                if (String.IsNullOrWhiteSpace(iconPath) == false)
                {
                    iconPath = iconPath.Replace(oldPath, component.Attributes.Path);
                    (component.Impl as GME.MGA.IMgaFCO).set_RegistryValue("icon", iconPath);
                }
                {
                    var console = GMEConsole.CreateFromProject(project);
                    if (console.gme != null)
                    {
                        console.Info.WriteLine(String.Format("Moved component directory from {0} to {1}", oldPath, component.Attributes.Path));
                        //Marshal.FinalReleaseComObject(console.gme);
                    }
                }
            }

            lastObservedPaths[componentGuid] = component.Attributes.Path;
        }
Ejemplo n.º 30
0
        public static string previousExportPath = null; // MOT-387

        /// <summary>
        /// This function is called for each interpreter invocation before Main.
        /// Don't perform MGA operations here unless you open a tansaction.
        /// </summary>
        /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
        public void Initialize(MgaProject project)
        {
            // TODO: Add your initialization code here...
            GMEConsole = GMEConsole.CreateFromProject(project);
        }