Esempio n. 1
0
 public PropertyGenerator(GeneratorData data, Translator translator, Documentation documentation)
 {
     this.data = data;
     this.translator = translator;
     this.documentation = documentation;
     this.PropertyMethods = new List<IntPtr>();
 }
        protected override void Begin()
        {
            Dictionary<string, Documentation> docs = new Dictionary<string, Documentation>();

            XPathNavigator nav = this.XPathDocument.CreateNavigator();

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);
            nsmgr.AddNamespace("xs", XmlSchema.Namespace);

            foreach(XPathNavigator node in nav.Select(XPathExpression, nsmgr)) {
                Documentation doc = new Documentation();
                string[] lines = node.Value.Split(new char[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
                for(int i = 0; i < lines.Length; i++) {
                    lines[i] = lines[i].TrimStart(' ','\t');
                }
                doc.Text = String.Join("\r\n", lines);

                while(node.MoveToParent()) {
                    if (node.LocalName == "attribute" ||
                        node.LocalName == "complexType" ||
                        node.LocalName == "element")
                    {
                        string name = node.GetAttribute("name", String.Empty);
                        if (name == String.Empty) {
                            name = node.GetAttribute("ref", String.Empty);
                        }

                        doc.FullName = name + FirstUpper(doc.FullName);
                    }
                }
                docs[doc.FullName] = doc;
            }

            foreach (CodeTypeDeclaration type in this.Code.Types) {
                Comment(docs, type.Name, type.Comments);
                foreach(CodeTypeMember member in type.Members) {
                    Comment(docs, type.Name + FirstUpper(member.Name), member.Comments);
                }
            }

            //			System.Diagnostics.Debug.WriteLine("Unused comments:");
            //			foreach(KeyValuePair<string, Documentation> kvp in docs) {
            //				if (!kvp.Value.Used) {
            //					System.Diagnostics.Debug.WriteLine(kvp.Value.ToString());
            //				}
            //			}
        }
        public static Documentation Get()
        {
            if (docs == null)
            {
                var xDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/bin/Brisk4GameSDK.xml"));
                var tmpDocs = new Documentation(xDoc);
                foreach (var item in tmpDocs.Members.Where(t=>t.Type == "T"))
                {
                    var related = tmpDocs.Members.Where(t => t.Type != "T" && t.Name.StartsWith(item.Name + "."));
                    item.Children = related.ToArray();
                }
                tmpDocs.Members = tmpDocs.Members.Where(t => t.Type == "T").OrderBy(t=>t.Name).ToArray();
                docs = tmpDocs;
            }

            return docs;
        }
Esempio n. 4
0
        protected internal virtual void Read(XmlSchemaObject obj)
        {
            var annotated = (XmlSchemaAnnotated)obj;

            if (annotated != null && annotated.Annotation != null)
            {
                foreach (var xmlDoc in annotated.Annotation.Items.OfType <XmlSchemaDocumentation>())
                {
                    var doc = new SDataSchemaDocumentation {
                        Language = xmlDoc.Language
                    };

                    if (xmlDoc.Markup != null)
                    {
                        doc.Text = string.Concat(xmlDoc.Markup.Select(text => text.Value).ToArray());
                    }

                    Documentation.Add(doc);
                }
            }

            ReadSmeAttributes(obj);
        }
Esempio n. 5
0
        /// <summary>
        /// Loads the given XML documentation.
        /// </summary>
        /// <param name="unit">The <see cref="Unit"/> target of the loading.</param>
        /// <param name="xmlRoot">The XElement root of the info.</param>
        /// <param name="rootEntities">The classes in the <see cref="Unit"/>.</param>
        /// <param name="allEntities">All entities in the <see cref="Unit"/>.</param>
        public void LoadXmlElementsFrom(Unit unit,
                                        XElement xmlRoot,
                                        ISet <Entity> rootEntities,
                                        IDictionary <Id, Entity> allEntities)
        {
            IEnumerable <XElement> members =
                xmlRoot.Element("members").Elements("member");

            // Load entities with their associated documentation
            foreach (XElement member in members)
            {
                string name = (string)member.Attribute("name");

                // Load the documentation from the (flat) XML
                var xmlDoc = Documentation.Create(name, member);

                // Create the associated entity and store it
                var entity = new Entity(unit)
                {
                    Docs = xmlDoc
                };

                try {
                    allEntities.Add(entity.Id, entity);
                } catch (System.ArgumentException) {
                    string errorMsg = "Entity: " + entity
                                      + "\n\n\tis duplicated in the docs:\n"
                                      + "\n\t" + allEntities[entity.Id];
                    throw new System.ArgumentException(errorMsg);
                }
            }

            // Organize entities in the unit's structure
            this.FindRootClasses(unit, rootEntities, allEntities);
            this.Matrioska(allEntities);
        }
Esempio n. 6
0
 /// <summary>
 /// Initializes a new instance of the Command class.
 /// </summary>
 /// <param name="name">name property</param>
 /// <param name="fromSourceSystem">fromSourceSystem property</param>
 /// <param name="containerId">containerId property</param>
 /// <param name="descriptions">Description property, used to describe
 /// assets</param>
 /// <param name="experts">The data steward of the asset</param>
 /// <param name="tags">Taging the asset</param>
 /// <param name="termTags">Taging the asset using glossary terms, this
 /// is a feature only for standard SKU</param>
 /// <param name="columnDescriptions">Descriptions of a column</param>
 /// <param name="columnTags">Tagging a column</param>
 /// <param name="columnTermTags">Tagging a column with glossary terms,
 /// this is a feature only for standard SKU </param>
 /// <param name="parameterDescriptions">Parameter descriptions</param>
 /// <param name="parameterTags">Tagging a parameter</param>
 /// <param name="parameterTermTags">Tagging a parameter with glossary
 /// terms, this is a feature only for standard SKU</param>
 public Command(string name, Dsl dsl, DataSource dataSource, LastRegisteredBy lastRegisteredBy, bool fromSourceSystem, System.Collections.Generic.IList <RolesItem> roles = default(System.Collections.Generic.IList <RolesItem>), double?containerId = default(double?), System.Collections.Generic.IList <Description> descriptions = default(System.Collections.Generic.IList <Description>), System.Collections.Generic.IList <Expert> experts = default(System.Collections.Generic.IList <Expert>), AccessInstruction accessInstructions = default(AccessInstruction), Documentation documentation = default(Documentation), FriendlyName friendlyName = default(FriendlyName), System.Collections.Generic.IList <Tag> tags = default(System.Collections.Generic.IList <Tag>), System.Collections.Generic.IList <TermTag> termTags = default(System.Collections.Generic.IList <TermTag>), CommandSchema schema = default(CommandSchema), System.Collections.Generic.IList <ColumnDescription> columnDescriptions = default(System.Collections.Generic.IList <ColumnDescription>), System.Collections.Generic.IList <ColumnTag> columnTags = default(System.Collections.Generic.IList <ColumnTag>), System.Collections.Generic.IList <ColumnTermTag> columnTermTags = default(System.Collections.Generic.IList <ColumnTermTag>), System.Collections.Generic.IList <ParameterDescription> parameterDescriptions = default(System.Collections.Generic.IList <ParameterDescription>), System.Collections.Generic.IList <ParameterTag> parameterTags = default(System.Collections.Generic.IList <ParameterTag>), System.Collections.Generic.IList <ParameterTermTag> parameterTermTags = default(System.Collections.Generic.IList <ParameterTermTag>))
 {
     Roles                 = roles;
     Name                  = name;
     Dsl                   = dsl;
     DataSource            = dataSource;
     LastRegisteredBy      = lastRegisteredBy;
     FromSourceSystem      = fromSourceSystem;
     ContainerId           = containerId;
     Descriptions          = descriptions;
     Experts               = experts;
     AccessInstructions    = accessInstructions;
     Documentation         = documentation;
     FriendlyName          = friendlyName;
     Tags                  = tags;
     TermTags              = termTags;
     Schema                = schema;
     ColumnDescriptions    = columnDescriptions;
     ColumnTags            = columnTags;
     ColumnTermTags        = columnTermTags;
     ParameterDescriptions = parameterDescriptions;
     ParameterTags         = parameterTags;
     ParameterTermTags     = parameterTermTags;
 }
Esempio n. 7
0
        /// <summary>
        /// Получить данные отчета
        /// </summary>
        private List <ReportData> GetReportData(DocumentationStimulReportParams parameters)
        {
            documentation     = DataStore.Get <Documentation>(parameters.DocumentationId);
            PurchasingRequest = documentation.PurchasingRequestCopy;
            BuildDataSources();

            var list = new List <ReportData>
            {
                // условные переменные, скрывающие некоторые части отчёта
                GetShowVariablesData(),
                // Основной объект
                GetMainReportBusinessObject(),
                // Информация о лотах
                GetLotInfo(),
                // ТРУ
                GetLotSpecData(),
                // преимущества участников
                GetParticipantBenefitsData(),
                // требования к участникам
                GetParticipantRequirementsData(),
            };

            return(list);
        }
        void FillClientMembers(Documentation doc, string typeFullName)
        {
            var actAssembly = typeof(ToolkitResourceManager).Assembly;
            var type        = actAssembly.GetType(typeFullName, true);

            if (type.IsSubclassOf(typeof(ExtenderControlBase))
                ||
                type.IsSubclassOf(typeof(ScriptControlBase))
                ||
                type == typeof(ComboBox))
            {
                var clientScriptName = type
                                       .CustomAttributes
                                       .First(a => a.AttributeType.Name == "ClientScriptResourceAttribute")
                                       .ConstructorArguments[1];
                var jsFileName = clientScriptName.Value + ".js";

                var jsLines       = System.IO.File.ReadAllLines(Server.MapPath("~/bin/Scripts/" + jsFileName));
                var commentParser = new CommentParser();
                var clientMembers = commentParser.ParseFile(jsLines, typeFullName);

                doc.Add(clientMembers, ContentType.Text);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Get the license expiration date
        /// </summary>
        /// <param name="licenseInfo"></param>
        /// <returns></returns>
        internal static DateTime getLicenseExp(string licenseInfo)
        {
            string   expDate = "";
            DateTime DT      = DateTime.Now;

            try
            {
                //Days
                int a = licenseInfo.IndexOf("Time remaining") + 14;
                int b = licenseInfo.IndexOf("days");
                expDate = licenseInfo.Substring(a, b - a).Trim();
                DT      = DT.AddDays(Int32.Parse(expDate));
                string days = expDate;
                //Hours
                a       = licenseInfo.IndexOf("days,") + 5;
                b       = licenseInfo.IndexOf("hours");
                expDate = licenseInfo.Substring(a, b - a).Trim();
                DT      = DT.AddHours(Int32.Parse(expDate));
                //Minutes
                a       = licenseInfo.IndexOf("hours,") + 6;
                b       = licenseInfo.IndexOf("min");
                expDate = licenseInfo.Substring(a, b - a).Trim();
                DT      = DT.AddMinutes(Int32.Parse(expDate));
                //Seconds
                a       = licenseInfo.IndexOf("min,") + 4;
                b       = licenseInfo.IndexOf("sec");
                expDate = licenseInfo.Substring(a, b - a).Trim();
                DT      = DT.AddSeconds(Int32.Parse(expDate));
            }catch
            {
                //Something failed. subtracta year and return that
                DT = DateTime.Now.AddYears(-1);
            }

            return(DT);
        }
        internal static string Render(Documentation doc, int tabLevel)
        {
            StringWriter sw = new StringWriter();

            if (doc == null)
            {
                return("");
            }

            #region Description

            if (RimbaCsRenderer.SuppressDoc)
            {
                return(string.Empty);
            }

            string tabPrefix = new String('\t', tabLevel);

            if (doc.Definition != null || doc.Description != null)
            {
                sw.WriteLine(tabPrefix + "/// <summary>");

                if (!RimbaCsRenderer.SuppressDoc)
                {
                    List <String> defn = new List <string>();
                    defn.AddRange(doc.Definition ?? new List <String>());
                    defn.AddRange(doc.Description ?? new List <String>());
                    foreach (String s in defn)
                    {
                        sw.WriteLine(tabPrefix + "/// ");
                        foreach (String line in s.Split('\n'))
                        {
                            sw.WriteLine(tabPrefix + "/// {0}", line.Replace("\r", "").Replace("&", "&amp;"));
                        }
                        sw.WriteLine(tabPrefix + "/// ");
                    }
                }
                sw.WriteLine(tabPrefix + "/// </summary>");
            }
            #endregion

            #region Walkthrough = Example

            if (doc.Walkthrough != null || doc.Usage != null)
            {
                if (!RimbaCsRenderer.SuppressDoc)
                {
                    sw.WriteLine(tabPrefix + "/// <example>");
                    sw.WriteLine(tabPrefix + "/// <para><b>Walkthrough</b></para>");
                    foreach (string s in doc.Walkthrough ?? new List <String>())
                    {
                        foreach (String line in s.Split('\n'))
                        {
                            sw.WriteLine(tabPrefix + "/// {0}", line.Replace("\r", "").Replace("&", "&amp;"));
                        }
                    }
                    sw.WriteLine(tabPrefix + "/// <para><b>Usage Notes</b></para>");
                    foreach (string s in doc.Usage ?? new List <String>())
                    {
                        foreach (String line in s.Split('\n'))
                        {
                            sw.WriteLine(tabPrefix + "/// {0}", line.Replace("\r", "").Replace("&", "&amp;"));
                        }
                    }
                    sw.WriteLine(tabPrefix + "/// </example>");
                }
            }

            #endregion

            #region Remarks
            if (doc.Rationale != null)
            {
                if (!RimbaCsRenderer.SuppressDoc)
                {
                    sw.WriteLine(tabPrefix + "/// <remarks>");
                    foreach (String s in doc.Rationale)
                    {
                        foreach (String line in s.Split('\n'))
                        {
                            sw.WriteLine(tabPrefix + "/// {0}", line.Replace("\r", "").Replace("&", "&amp;"));
                        }
                    }
                    sw.WriteLine(tabPrefix + "/// {0}", doc.Copyright);
                    sw.WriteLine(tabPrefix + "/// </remarks>");
                }
            }
            #endregion

            return(sw.ToString());
        }
Esempio n. 11
0
        internal static void DefineGlobals()
        {
            var g = Module.Global;

            Documentation.SectionIntroduction("control flow",
                                              "Tasks that run or otherwise control the execution of other tasks.");

            Documentation.SectionIntroduction("control flow//calling tasks",
                                              "Tasks that call another task once.");

            Documentation.SectionIntroduction("control flow//looping",
                                              "Tasks that repeatedly call other tasks.");

            Documentation.SectionIntroduction("control flow//looping//all solutions predicates",
                                              "Tasks that collect together all the solutions to a given call.");

            Documentation.SectionIntroduction("higher-order predicates",
                                              "Predicates that run other predicates.");

            g[nameof(Call)] = new GeneralPrimitive(nameof(Call), Call)
                              .Arguments("call", "extra_arguments", "...")
                              .Documentation("control flow//calling tasks", "Runs the call to the task represented in the tuple 'call'. If extra_arguments are included, they will be added to the end of the call tuple.");
            g[nameof(IgnoreOutput)] = new GeneralPrimitive(nameof(IgnoreOutput), IgnoreOutput)
                                      .Arguments("calls", "...")
                                      .Documentation("control flow//calling tasks", "Runs each of the calls, in order, but throws away their output text.");
            g[nameof(Begin)] = new GeneralPrimitive(nameof(And), Begin)
                               .Arguments("task", "...")
                               .Documentation("control flow", "Runs each of the tasks, in order.");
            g[nameof(And)] = new GeneralPrimitive(nameof(And), And)
                             .Arguments("calls", "...")
                             .Documentation("control flow", "Runs each of the calls, in order.");
            g[nameof(Or)] = new GeneralPrimitive(nameof(And), Or)
                            .Arguments("calls", "...")
                            .Documentation("control flow", "Runs each of the calls, in order until one works.");
            g[nameof(Not)] = new GeneralPrimitive(nameof(Not), Not)
                             .Arguments("call")
                             .Documentation("higher-order predicates", "Runs call.  If the call succeeds, it Not, fails, undoing any effects of the call.  If the call fails, then Not succeeds.  This requires the call to be ground (not contain any uninstantiated variables), since [Not [P ?x]] means \"not [P ?x] for any ?x\".  Use NotAny if you mean to have unbound variables in the goal.");
            g[nameof(NotAny)] = new GeneralPrimitive(nameof(NotAny), NotAny)
                                .Arguments("call")
                                .Documentation("higher-order predicates", "Runs call.  If the call succeeds, it Not, fails, undoing any effects of the call.  If the call fails, then Not succeeds.");
            g[nameof(FindAll)] = new GeneralPrimitive(nameof(FindAll), FindAll)
                                 .Arguments("?result", "call", "?all_results")
                                 .Documentation("control flow//looping//all solutions predicates", "Runs call, backtracking to find every possible solution to it.  For each solution, FindAll records the value of ?result, and returns a list of all ?results in order, in ?all_results.  If backtracking produces duplicate ?results, there will be multiple copies of them in ?all_results; to eliminate duplicate solutions, use FindUnique.  If call never fails, this will run forever.");
            g[nameof(FindUnique)] = new GeneralPrimitive(nameof(FindUnique), FindUnique)
                                    .Arguments("?result", "call", "?all_results")
                                    .Documentation("control flow//looping//all solutions predicates", "Runs call, backtracking to find every possible solution to it.  For each solution, FindAll records the value of ?result, and returns a list of all ?results in order, in ?all_results, eliminating duplicate solutions.  If call never fails, this will run forever.");
            g[nameof(DoAll)] = new DeterministicTextGeneratorMetaTask(nameof(DoAll), DoAll)
                               .Arguments("generator_call", "other_calls", "...")
                               .Documentation("control flow//looping", "Runs generator_call, finding all its solutions by backtracking.  For each solution, runs the other tasks, collecting all their text output.  Since the results are backtracked, any variable bindings or set commands are undone.");;
            g[nameof(ForEach)] = new GeneralPrimitive(nameof(ForEach), ForEach)
                                 .Arguments("generator_call", "other_calls", "...")
                                 .Documentation("control flow//looping", "Runs generator_call, finding all its solutions by backtracking.  For each solution, runs the other tasks, collecting all their text output.  Since the results are backtracked, any variable bindings are undone.  However, all text generated and set commands performed are preserved.");
            g[nameof(Implies)] = new GeneralPrimitive(nameof(Implies), Implies)
                                 .Arguments("higher-order predicates", "other_calls", "...")
                                 .Documentation("higher-order predicates", "True if for every solution to generator_call, other_calls succeeds.  So this is essentially like ForEach, but whereas ForEach always succeeds, Implies fails if other_calls ever fails.  Text output and sets of global variables are preserved, as with ForEach.");
            g[nameof(Once)] = new GeneralPrimitive(nameof(Once), Once)
                              .Arguments("code", "...")
                              .Documentation("control flow//controlling backtracking", "Runs code normally, however, if any subsequent code backtracks, once will not rerun the code, but will fail to whatever code preceded it.");
            g[nameof(ExactlyOnce)] = new GeneralPrimitive(nameof(ExactlyOnce), ExactlyOnce)
                                     .Arguments("code", "...")
                                     .Documentation("control flow//controlling backtracking", "Runs code normally.  If the code fails, ExactlyOnce throws an exception.  If it succeeds, ExactlyOnce succeeds.  However, if any subsequent code backtracks, once will not rerun the code, but will fail to whatever code preceded it.");
            g[nameof(Max)] = new GeneralPrimitive(nameof(Max), Max)
                             .Arguments("?scoreVariable", "code", "...")
                             .Documentation("control flow//looping//all solutions predicates", "Runs code, backtracking to find all solutions, keeping the state (text output and variable bindings) of the solution with the largest value of ?scoreVariable");
            g[nameof(Min)] = new GeneralPrimitive(nameof(Min), Min)
                             .Arguments("?scoreVariable", "code", "...")
                             .Documentation("control flow//looping//all solutions predicates", "Runs code, backtracking to find all solutions, keeping the state (text output and variable bindings) of the solution with the smallest value of ?scoreVariable");
            g[nameof(SaveText)] = new GeneralPrimitive(nameof(SaveText), SaveText)
                                  .Arguments("call", "?variable")
                                  .Documentation("control flow//calling tasks", "Runs call, but places its output in ?variable rather than the output buffer.");
            g[nameof(PreviousCall)] = new GeneralPrimitive(nameof(PreviousCall), PreviousCall)
                                      .Arguments("?call_pattern")
                                      .Documentation("reflection//dynamic analysis", "Unifies ?call_pattern with the most recent successful call that matches it.  Backtracking will match against previous calls.");
            g[nameof(UniqueCall)] = new GeneralPrimitive(nameof(UniqueCall), UniqueCall)
                                    .Arguments("?call_pattern")
                                    .Documentation("reflection//dynamic analysis", "Calls ?call_pattern, finding successive solutions until one is found that can't be unified with a previous successful call.");
            g[nameof(Parse)] = new GeneralPrimitive(nameof(Parse), Parse)
                               .Arguments("call", "text")
                               .Documentation("control flow//calling tasks", "True if call can generate text as its output.  This is done by running call and backtracking whenever its output diverges from text.  Used to determine if a grammar can generate a given string.");
        }
Esempio n. 12
0
        // Strips MathML tags from the source and replaces the equations with the content
        // found in the <!-- eqn: :--> comments in the docs.
        // Todo: Some simple MathML tags do not include comments, find a solution.
        // Todo: Some files include more than 1 function - find a way to map these extra functions.
        Documentation ProcessFile(string file, EnumProcessor processor)
        {
            string text;

            if (LastFile == file)
            {
                return(Cached);
            }

            LastFile = file;
            text     = File.ReadAllText(file);

            text = text
                   .Replace("&epsi;", "epsilon")   // Fix unrecognized &epsi; entities
                   .Replace("xml:", String.Empty); // Remove namespaces
            text = remove_doctype.Replace(text, String.Empty);
            text = remove_xmlns.Replace(text, string.Empty);

            Match m = remove_mathml.Match(text);

            while (m.Length > 0)
            {
                string removed = text.Substring(m.Index, m.Length);
                text = text.Remove(m.Index, m.Length);
                int equation = removed.IndexOf("eqn");
                if (equation > 0)
                {
                    // Find the start and end of the equation string
                    int eqn_start = equation + 4;
                    int eqn_end   = removed.IndexOf(":-->") - equation - 4;
                    if (eqn_end < 0)
                    {
                        // Note: a few docs from man4 delimit eqn end with ": -->"
                        eqn_end = removed.IndexOf(": -->") - equation - 4;
                    }
                    if (eqn_end < 0)
                    {
                        Console.WriteLine("[Warning] Failed to find equation for mml.");
                        goto next;
                    }

                    string eqn_substring = removed.Substring(eqn_start, eqn_end);
                    text = text.Insert(m.Index, "<![CDATA[" + eqn_substring + "]]>");
                }

next:
                m = remove_mathml.Match(text);
            }

            XDocument doc = null;

            try
            {
                doc    = XDocument.Parse(text);
                Cached = ToInlineDocs(doc, processor);
                return(Cached);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine(doc.ToString());
                return(null);
            }
        }
Esempio n. 13
0
 private Documentation(Documentation toClone)
 {
     title       = toClone.title;
     description = toClone.description;
 }
Esempio n. 14
0
        void RegisterGlobalCommands()
        {
            UI.Inspector.Inspector.RegisterGlobalCommands();
            UI.Timeline.CommandBindings.Bind();
            UI.SceneView.SceneView.RegisterGlobalCommands();

            var h = CommandHandlerList.Global;

            h.Connect(GenericCommands.NewProject, new ProjectNew());
            h.Connect(GenericCommands.NewTan, new FileNew());
            h.Connect(GenericCommands.Open, new FileOpen());
            h.Connect(GenericCommands.OpenProject, new FileOpenProject());
            h.Connect(GenericCommands.Save, new FileSave());
            h.Connect(GenericCommands.CloseProject, new FileCloseProject());
            h.Connect(GenericCommands.SaveAs, new FileSaveAs());
            h.Connect(GenericCommands.SaveAll, new FileSaveAll());
            h.Connect(GenericCommands.Revert, new FileRevert());
            h.Connect(GenericCommands.Close, new FileClose());
            h.Connect(GenericCommands.CloseAll, new FileCloseAll());
            h.Connect(GenericCommands.CloseAllButCurrent, new FileCloseAllButCurrent());
            h.Connect(GenericCommands.Quit, Application.Exit);
            h.Connect(GenericCommands.PreferencesDialog, () => new PreferencesDialog());
            h.Connect(GenericCommands.Group, new GroupNodes());
            h.Connect(GenericCommands.Ungroup, new UngroupNodes());
            h.Connect(GenericCommands.InsertTimelineColumn, new InsertTimelineColumn());
            h.Connect(GenericCommands.RemoveTimelineColumn, new RemoveTimelineColumn());
            h.Connect(GenericCommands.NextDocument, new SetNextDocument());
            h.Connect(GenericCommands.PreviousDocument, new SetPreviousDocument());
            h.Connect(GenericCommands.DefaultLayout, new ViewDefaultLayout());
            h.Connect(GenericCommands.SaveLayout, new SaveLayout());
            h.Connect(GenericCommands.LoadLayout, new LoadLayout());
            h.Connect(GenericCommands.GroupContentsToMorphableMeshes, new GroupContentsToMorphableMeshes());
            h.Connect(GenericCommands.ExportScene, new ExportScene());
            h.Connect(GenericCommands.InlineExternalScene, new InlineExternalScene());
            h.Connect(GenericCommands.UpsampleAnimationTwice, new UpsampleAnimationTwice());
            h.Connect(GenericCommands.ViewHelp, () => Documentation.ShowHelp(Documentation.StartPageName));
            h.Connect(GenericCommands.HelpMode, () => Documentation.IsHelpModeOn = !Documentation.IsHelpModeOn);
            h.Connect(GenericCommands.ViewChangelog, () => Documentation.ShowHelp(Documentation.ChangelogPageName));
            h.Connect(GenericCommands.ConvertToButton, new ConvertToButton());
            h.Connect(Tools.AlignLeft, new AlignLeft());
            h.Connect(Tools.AlignRight, new AlignRight());
            h.Connect(Tools.AlignTop, new AlignTop());
            h.Connect(Tools.AlignBottom, new AlignBottom());
            h.Connect(Tools.CenterHorizontally, new CenterHorizontally());
            h.Connect(Tools.CenterVertically, new CenterVertically());
            h.Connect(Tools.DistributeLeft, new DistributeLeft());
            h.Connect(Tools.DistributeHorizontally, new DistributeCenterHorizontally());
            h.Connect(Tools.DistributeRight, new DistributeRight());
            h.Connect(Tools.DistributeTop, new DistributeTop());
            h.Connect(Tools.DistributeVertically, new DistributeCenterVertically());
            h.Connect(Tools.DistributeBottom, new DistributeBottom());
            h.Connect(Tools.CenterVertically, new DistributeCenterVertically());
            h.Connect(Tools.AlignCentersHorizontally, new AlignCentersHorizontally());
            h.Connect(Tools.AlignCentersVertically, new AlignCentersVertically());
            h.Connect(Tools.AlignTo, new AlignAndDistributeToHandler(Tools.AlignTo));
            h.Connect(Tools.CenterAlignTo, new CenterToHandler(Tools.CenterAlignTo));
            h.Connect(Tools.RestoreOriginalSize, new RestoreOriginalSize());
            h.Connect(Tools.ResetScale, new ResetScale());
            h.Connect(Tools.ResetRotation, new ResetRotation());
            h.Connect(Tools.FitToContainer, new FitToContainer());
            h.Connect(Tools.FitToContent, new FitToContent());
            h.Connect(Tools.FlipX, new FlipX());
            h.Connect(Tools.FlipY, new FlipY());
            h.Connect(Tools.CenterView, new CenterView());
            h.Connect(Command.Copy, Core.Operations.Copy.CopyToClipboard, IsCopyPasteAllowedForSelection);
            h.Connect(Command.Cut, new DocumentDelegateCommandHandler(Core.Operations.Cut.Perform, IsCopyPasteAllowedForSelection));
            h.Connect(Command.Paste, new DocumentDelegateCommandHandler(() => Paste(), Document.HasCurrent));
            h.Connect(Command.Delete, new DocumentDelegateCommandHandler(Core.Operations.Delete.Perform, IsCopyPasteAllowedForSelection));
            h.Connect(Command.SelectAll, new DocumentDelegateCommandHandler(() => {
                foreach (var row in Document.Current.Rows)
                {
                    Core.Operations.SelectRow.Perform(row, true);
                }
            }, () => Document.Current?.Rows.Count > 0));
            h.Connect(Command.Undo, () => Document.Current.History.Undo(), () => Document.Current?.History.CanUndo() ?? false);
            h.Connect(Command.Redo, () => Document.Current.History.Redo(), () => Document.Current?.History.CanRedo() ?? false);
            h.Connect(SceneViewCommands.PasteAtOldPosition, new DocumentDelegateCommandHandler(() => Paste(pasteAtMouse: false), Document.HasCurrent));
            h.Connect(SceneViewCommands.SnapWidgetBorderToRuler, new SnapWidgetBorderCommandHandler());
            h.Connect(SceneViewCommands.SnapWidgetPivotToRuler, new SnapWidgetPivotCommandHandler());
            h.Connect(SceneViewCommands.SnapRulerLinesToWidgets, new SnapRulerLinesToWidgetCommandHandler());
            h.Connect(SceneViewCommands.ClearActiveRuler, new DocumentDelegateCommandHandler(ClearActiveRuler));
            h.Connect(SceneViewCommands.ManageRulers, new ManageRulers());
            h.Connect(SceneViewCommands.GeneratePreview, new GeneratePreview());
            h.Connect(TimelineCommands.CutKeyframes, UI.Timeline.Operations.CutKeyframes.Perform);
            h.Connect(TimelineCommands.CopyKeyframes, UI.Timeline.Operations.CopyKeyframes.Perform);
            h.Connect(TimelineCommands.PasteKeyframes, UI.Timeline.Operations.PasteKeyframes.Perform);
            h.Connect(TimelineCommands.ReverseKeyframes, UI.Timeline.Operations.ReverseKeyframes.Perform);
            h.Connect(TimelineCommands.CreatePositionKeyframe, UI.Timeline.Operations.TogglePositionKeyframe.Perform);
            h.Connect(TimelineCommands.CreateRotationKeyframe, UI.Timeline.Operations.ToggleRotationKeyframe.Perform);
            h.Connect(TimelineCommands.CreateScaleKeyframe, UI.Timeline.Operations.ToggleScaleKeyframe.Perform);
            h.Connect(TimelineCommands.CenterTimelineOnCurrentColumn, new DocumentDelegateCommandHandler(UI.Timeline.Operations.CenterTimelineOnCurrentColumn.Perform));
            h.Connect(SceneViewCommands.ToggleDisplayRuler, new DisplayRuler());
            h.Connect(SceneViewCommands.SaveCurrentRuler, new SaveRuler());
            h.Connect(TimelineCommands.NumericMove, () => new NumericMoveDialog());
            h.Connect(TimelineCommands.NumericScale, () => new NumericScaleDialog());
            h.Connect(ToolsCommands.RenderToPngSequence, new RenderToPngSequence());
            h.Connect(GitCommands.ForceUpdate, new ForceUpdate());
            h.Connect(GitCommands.Update, new Update());
            h.Connect(GenericCommands.ClearCache, new ClearCache());
            h.Connect(GenericCommands.ResetGlobalSettings, new ResetGlobalSettings());
            h.Connect(GenericCommands.PurgeBackups, new PurgeBackUps());
        }
Esempio n. 15
0
 public void SetDocumentation(Documentation documentation)
 {
     Documentation = documentation;
 }
Esempio n. 16
0
 public void PostDocumentation(Documentation documentation)
 {
     _service.addDocumentation(documentation);
 }
        public override Element Build()
        {
            var @class = new Class(SourceType.Name.SanitizeTypeName())
            {
                Modifiers = { Modifier.Export }
            };

            WriteLine(ConsoleColor.Green, "class", @class.Name);

            if (Inherits != null)
            {
                @class.Extends = Inherits.TypescriptName();
            }

            var classDocumentation = Documentation?.ForClass(SourceType);

            if (classDocumentation != null)
            {
                @class.Comment = classDocumentation.Summary;
            }

            if (SourceType.IsAbstract)
            {
                @class.Modifiers.Add(Modifier.Abstract);
            }

            foreach (var @interface in _interfaces)
            {
                @class.Implements.Add(@interface.TypescriptName());
            }

            foreach (var typeArgument in _typeArguments)
            {
                @class.TypeArguments.Add(typeArgument.TypescriptName());
            }

            if (!SourceType.IsAbstract)
            {
                foreach (var attribute in _attributes)
                {
                    var name      = attribute.GetType().ClassDecoratorName();
                    var arguments = new ObjectLiteral(attribute);
                    @class.Decorators.Add(new Decorator(name, new[] { arguments }));
                }
            }

            foreach (var source in _properties)
            {
                var getMethod  = source.GetMethod;
                var target     = new Property(source.Name.CamelCase(), source.PropertyType.TypescriptName());
                var attributes = source.GetCustomAttributes(false).Where(t => t.GetType().IsPublic);

                if (getMethod.IsAbstract)
                {
                    target.Modifiers.Add(Modifier.Abstract);
                }

                if (getMethod.IsFamily)
                {
                    target.Modifiers.Add(Modifier.Protected);
                }
                else
                {
                    target.Modifiers.Add(Modifier.Public);
                }

                var propertyDocumentation = Documentation?.ForMember(source);

                if (propertyDocumentation != null)
                {
                    target.Comment = propertyDocumentation.Summary;
                }

                if (OutputContext.Properties?.Initialize ?? false)
                {
                    SetDefaultValue(source, target);
                }

                foreach (var attribute in attributes)
                {
                    var name      = attribute.GetType().PropertyDecoratorName();
                    var arguments = new ObjectLiteral(attribute);
                    target.Decorators.Add(new Decorator(name, new[] { arguments }));
                }

                @class.Members.Add(target);
            }

            var illegalProp = @class.Properties.SingleOrDefault(p => p.Name == "constructor");

            {
                if (illegalProp != null)
                {
                    const string prefix  = "_";
                    var          newName = prefix + illegalProp.Name;
                    while (@class.Properties.Any(p => p.Name == newName))
                    {
                        newName = prefix + newName;
                    }

                    illegalProp.Name = newName;
                }
            }
            return(@class);
        }
Esempio n. 18
0
        public static void DefineGlobals()
        {
            var g = Module.Global;

            Documentation.SectionIntroduction("reflection",
                                              "Predicates that can be used by a program to reason about itself.");

            Documentation.SectionIntroduction("reflection//static analysis",
                                              "Predicates that can be used by a program to check what tasks can call what other tasks.");

            Documentation.SectionIntroduction("reflection//dynamic analysis",
                                              "Predicates that can be used by a program to check what tasks have been called in this execution path.");

            // Argument is a compound task
            g["CompoundTask"] = new GeneralPrimitive(nameof(CompoundTask), CompoundTask)
                                .Arguments("x")
                                .Documentation("type testing", "True if x is a compound task, i.e. a task defined by rules.");

            // Second arg is a method of the first arg
            Func <CompoundTask, Method, bool>          inInMode  = (t, m) => m.Task == t;
            Func <CompoundTask, IEnumerable <Method> > inOutMode = t => t.Methods;
            Func <Method, IEnumerable <CompoundTask> > outInMode = m => new[] { m.Task };

            g["TaskMethod"] =
                new GeneralPredicate <CompoundTask, Method>("TaskMethod", inInMode, inOutMode, outInMode, null)
                .Arguments("?task", "?method")
                .Documentation("reflection//static analysis", "True when ?method is a method of ?task");

            // Gets the MethodCallFrame of the most recent call
            g["LastMethodCallFrame"] = new GeneralPrimitive("LastMethodCallFrame", LastMethodCallFrame)
                                       .Arguments("?frame")
                                       .Documentation("reflection//dynamic analysis", "Sets ?frame to the reflection information for the current method call.");

            // Second argument is in the caller chain leading to the first argument
            Func <MethodCallFrame, Method, bool>          inInMode1  = (f, m) => f.CallerChain.FirstOrDefault(a => a.Method == m) != null;
            Func <MethodCallFrame, IEnumerable <Method> > inOutMode1 = f => f.CallerChain.Select(a => a.Method);

            g["CallerChainAncestor"] =
                new GeneralPredicate <MethodCallFrame, Method>("CallerChainAncestor", inInMode1, inOutMode1, null, null)
                .Arguments("frame", "?method")
                .Documentation("reflection//dynamic analysis", "True if ?method called frame's method or some other method that eventually called this frame's method.");

            // Second argument is in the goal chain leading to the first argument
            Func <MethodCallFrame, Method, bool>          inInMode2  = (f, m) => f.GoalChain.FirstOrDefault(a => a.Method == m) != null;
            Func <MethodCallFrame, IEnumerable <Method> > inOutMode2 = f => f.GoalChain.Select(a => a.Method);

            g["GoalChainAncestor"] =
                new GeneralPredicate <MethodCallFrame, Method>("GoalChainAncestor", inInMode2, inOutMode2, null, null)
                .Arguments("frame", "?method")
                .Documentation("reflection//dynamic analysis", "True if a successful call to ?method preceded this frame.");

            // First argument calls the second argument
            g["TaskCalls"] = new GeneralPrimitive(nameof(TaskCalls), TaskCalls)
                             .Arguments("?caller", "?callee")
                             .Documentation("reflection//static analysis", "True if task ?caller has a method that calls ?callee");

            // Second argument is a call expression for a call in some method of first argument.
            g["TaskSubtask"] = new GeneralPrimitive(nameof(TaskSubtask), TaskSubtask)
                               .Arguments("?task", "?call")
                               .Documentation("reflection//static analysis", "True if task ?caller has a method that contains the call ?call.");
        }
 static void OpenDocs()
 {
     Documentation.Open("Packages/com.whilefalse.retro3d/README.md");
 }
Esempio n. 20
0
        public override void WriteDocumentation(DocumentationWriter writer)
        {
            writer.WriteHeader();
            writer.WritePageTitle(Name, Type.Kind.ToString());

            writer.Write(this, Documentation.GetSummary());

            List <IType> interfaces = Type.DirectBaseTypes.Where(t => t.Kind == TypeKind.Interface && t.GetDefinition().Accessibility == Accessibility.Public).ToList();

            writer.WriteLine("```csharp");
            writer.Write(CodeAmbience.ConvertSymbol(Type));
            IType baseType = Type.DirectBaseTypes.FirstOrDefault(t => t.Kind == TypeKind.Class && !t.IsKnownType(KnownTypeCode.Object) && !t.IsKnownType(KnownTypeCode.ValueType));

            if (baseType != null)
            {
                writer.Write(" : ");
                writer.Write(BaseTypeAmbience.ConvertType(baseType));
            }
            foreach (IType @interface in interfaces)
            {
                writer.WriteLine(baseType is null ? " :" : ",");
                baseType = Type;
                writer.Write(BaseTypeAmbience.ConvertType(@interface));
            }
            writer.Break();
            writer.WriteLine("```");

            bool needBreak = false;

            if (Type.Kind == TypeKind.Class)
            {
                writer.Write("Inheritance ");
                writer.Write(string.Join(" &#129106; ", Type.GetNonInterfaceBaseTypes().Where(t => t != Type).Select(writer.GetTypeLink)));
                writer.Write(" &#129106; ");
                writer.Write(Name);
                writer.WriteLine("  ");
                needBreak = true;
            }

            List <TypeDocItem> derived = writer.KnownItems.OfType <TypeDocItem>().Where(i => i.Type.DirectBaseTypes.Select(t => t is ParameterizedType g ? g.GetDefinition() : t).Contains(Type)).OrderBy(i => i.FullName).ToList();

            if (derived.Count > 0)
            {
                if (needBreak)
                {
                    writer.Break();
                }

                writer.Write("Derived  " + Environment.NewLine + "&#8627; ");
                writer.Write(string.Join("  " + Environment.NewLine + "&#8627; ", derived.Select(t => writer.GetLink(t))));
                writer.WriteLine("  ");
                needBreak = true;
            }

            // attribute

            if (interfaces.Count > 0)
            {
                if (needBreak)
                {
                    writer.Break();
                }

                writer.Write("Implements ");
                writer.Write(string.Join(", ", interfaces.Select(writer.GetTypeLink)));
                writer.WriteLine("  ");
            }

            writer.WriteDocItems(TypeParameters, "#### Type parameters");

            writer.Write("### Example", Documentation.GetExample(), this);
            writer.Write("### Remarks", Documentation.GetRemarks(), this);

            writer.WriteDirectChildrenLink <ConstructorDocItem>("Constructors");
            writer.WriteDirectChildrenLink <FieldDocItem>("Fields");
            writer.WriteDirectChildrenLink <PropertyDocItem>("Properties");
            writer.WriteDirectChildrenLink <MethodDocItem>("Methods");
            writer.WriteDirectChildrenLink <EventDocItem>("Events");
            writer.WriteDirectChildrenLink <OperatorDocItem>("Operators");

            if (writer.NestedTypeVisibility == NestedTypeVisibility.DeclaringType ||
                writer.NestedTypeVisibility == NestedTypeVisibility.Everywhere)
            {
                writer.WriteDirectChildrenLink <ClassDocItem>("Classes");
                writer.WriteDirectChildrenLink <StructDocItem>("Structs");
                writer.WriteDirectChildrenLink <InterfaceDocItem>("Interfaces");
                writer.WriteDirectChildrenLink <EnumDocItem>("Enums");
                writer.WriteDirectChildrenLink <DelegateDocItem>("Delegates");
            }
        }
Esempio n. 21
0
 public async Task CreatingDocumentationWithoutAssembliesFails()
 {
     _ = await Should.ThrowAsync <InvalidOperationException>(() => Documentation.CreateBuilder().BuildAsync());
 }
Esempio n. 22
0
        private static void HttpListenHandler(IAsyncResult result)
        {
            HttpListenerContext context = null;

            if (HttpListener == null)
            {
                return;
            }
            if (result != ApiListener.result)
            {
                return;
            }
            try
            {
                context = HttpListener.EndGetContext(result);

                string body = null;
                if (context.Request.HasEntityBody)
                {
                    using (System.IO.Stream bodyStream = context.Request.InputStream)
                    {
                        using (System.IO.StreamReader reader = new System.IO.StreamReader(bodyStream, context.Request.ContentEncoding))
                        {
                            body = reader.ReadToEnd();
                        }
                    }
                }

                byte[] responseBuffer;

                var    response = "ok";
                string command  = "Unknown Command";
                try
                {
                    var urlParams = new List <string>(context.Request.RawUrl.Split(new char[] { '/' })).Select(us => Uri.UnescapeDataString(us)).ToList();
                    if (!string.IsNullOrWhiteSpace(body))
                    {
                        urlParams.Add(body);
                    }
                    if (string.IsNullOrWhiteSpace(urlParams.FirstOrDefault()))
                    {
                        urlParams.RemoveAt(0);
                    }
                    if (string.IsNullOrWhiteSpace(urlParams.LastOrDefault()) && urlParams.Any())
                    {
                        urlParams.RemoveAt(urlParams.Count - 1);
                    }

                    if (!urlParams.Any())
                    {
                        response = Documentation.Function(null);
                    }
                    else if (urlParams[0] == "favicon.ico")
                    {
                        context.Response.StatusCode = 404;
                        response = "Not found.";
                    }
                    else
                    {
                        command = urlParams[0];
                        urlParams.RemoveAt(0);

                        if (!Commands.ContainsKey(command))
                        {
                            throw new ApiError($"Invalid Command \"{command}\"");
                        }

                        command  = Commands[command]?.Name; //normalize name for display during errors
                        response = Commands[command].Function(urlParams) ?? response;
                    }
                }
                catch (Exception e)
                {
                    response = $"{command}: {e.Message}";
                    context.Response.StatusCode = e is ApiError ? 400 : 500;
                }
                responseBuffer = Encoding.UTF8.GetBytes(response);
                context.Response.ContentType = "application/json; charset=utf-8";
                // Get a response stream and write the response to it.
                context.Response.ContentLength64 = responseBuffer.Length;
                using (System.IO.Stream output = context.Response.OutputStream)
                {
                    output.Write(responseBuffer, 0, responseBuffer.Length);
                    output.Close();
                }
                Log(Debug($"{context.Request.RawUrl} => {context.Response.StatusCode}: {response}"));
            }
            catch (Exception e) {
                Log(Critical($"{context?.Request?.RawUrl ?? "(Error getting accessed URL)"} => {e.Message}"));
            }
            finally
            {
                try
                {
                    if (HttpListener.IsListening)
                    {
                        Listen();
                    }
                }
                catch (ObjectDisposedException)
                { }
            }
        }
Esempio n. 23
0
        static void TestExamples()
        {
            success = 0;
            total   = 0;
            var sw = Stopwatch.StartNew();

            var doc = Documentation.Create(Parser.PrimaryContext);

            Console.WriteLine();

            foreach (var section in doc.Sections)
            {
                if (section is HelpFunctionSection)
                {
                    var f = (HelpFunctionSection)section;

                    foreach (var usage in f.Usages)
                    {
                        foreach (var example in usage.Examples)
                        {
                            if (example.IsFile)
                            {
                                continue;
                            }

                            total++;

                            try
                            {
                                var parser = YAMP.Parser.Parse(example.Example);
                                parser.Execute();
                                success++;
                            }
                            catch (Exception ex)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Caution:");
                                Console.ForegroundColor = ConsoleColor.Yellow;
                                Console.WriteLine(ex.Message);
                                Console.ResetColor();
                                Console.WriteLine("At example: " + example.Example);
                                Console.Write("For usage: " + usage.Usage);
                                Console.WriteLine("In function: " + f.Name);
                                Console.WriteLine();
                            }

                            if (total % 20 == 0)
                            {
                                Console.WriteLine("{0} elements have been processed . . .", total);
                            }
                        }
                    }
                }
            }

            sw.Stop();

            Console.WriteLine();
            Console.WriteLine("{0} / {1} tests completed successfully ({2} %)", success, total, success * 100 / total);
            Console.WriteLine("Time for the tests ... {0} ms", sw.ElapsedMilliseconds);
        }
Esempio n. 24
0
 public Documentation Save(Documentation item)
 {
     return(new DocumentationRepository().SaveOrUpdate(item));
 }
Esempio n. 25
0
        private TangerineApp(string[] args)
        {
            ChangeTangerineSettingsFolderIfNeed();
            Orange.UserInterface.Instance = new OrangeInterface();
            Orange.UserInterface.Instance.Initialize();
            Widget.EnableViewCulling = false;
            WidgetInput.AcceptMouseBeyondWidgetByDefault = false;

            if (!UserPreferences.Initialize())
            {
                UserPreferences.Instance.Clear();
                UserPreferences.Instance.Add(new AppUserPreferences());
                UserPreferences.Instance.Add(new UI.SceneView.SceneUserPreferences());
                UserPreferences.Instance.Add(new UI.Timeline.TimelineUserPreferences());
                UserPreferences.Instance.Add(new UI.FilesystemView.FilesystemUserPreferences());
                UserPreferences.Instance.Add(new CoreUserPreferences());
            }
#if WIN
            TangerineSingleInstanceKeeper.Initialize(args);
            TangerineSingleInstanceKeeper.AnotherInstanceArgsRecieved += OpenDocumentsFromArgs;
            Application.Exited += () => {
                TangerineSingleInstanceKeeper.Instance.ReleaseInstance();
            };
#endif
            switch (AppUserPreferences.Instance.ColorThemeKind)
            {
            case ColorTheme.ColorThemeKind.Light:
                SetColorTheme(ColorTheme.CreateLightTheme(), Theme.ColorTheme.CreateLightTheme());
                break;

            case ColorTheme.ColorThemeKind.Dark:
                SetColorTheme(ColorTheme.CreateDarkTheme(), Theme.ColorTheme.CreateDarkTheme());
                break;

            case ColorTheme.ColorThemeKind.Custom: {
                bool       isDark = AppUserPreferences.Instance.ColorTheme.IsDark;
                ColorTheme theme  = null;
                var        flags  =
                    BindingFlags.Public |
                    BindingFlags.GetProperty |
                    BindingFlags.SetProperty |
                    BindingFlags.Instance;
                foreach (var category in typeof(ColorTheme).GetProperties(flags))
                {
                    var categoryValue = category.GetValue(AppUserPreferences.Instance.ColorTheme);
                    if (categoryValue == null)
                    {
                        if (theme == null)
                        {
                            theme = isDark ? ColorTheme.CreateDarkTheme() : ColorTheme.CreateLightTheme();
                        }
                        category.SetValue(AppUserPreferences.Instance.ColorTheme, category.GetValue(theme));
                        category.SetValue(theme, null);
                    }
                }
                SetColorTheme(AppUserPreferences.Instance.ColorTheme, AppUserPreferences.Instance.LimeColorTheme);
                break;
            }
            }
            Application.InvalidateWindows();

            LoadFont();

            DockManager.Initialize(new Vector2(1024, 768));
            DockManager.Instance.DocumentAreaDropFilesGesture.Recognized += new ScenesDropHandler {
                ShouldCreateContextMenu = false
            }.Handle;
            TangerineMenu.Create();
            var mainWidget = DockManager.Instance.MainWindowWidget;
            mainWidget.Window.AllowDropFiles = true;
            mainWidget.AddChangeWatcher(() => Project.Current, _ => {
                SetupMainWindowTitle(mainWidget);
                TangerineMenu.RebuildCreateImportedTypeMenu();
            });
            mainWidget.AddChangeWatcher(() => CoreUserPreferences.Instance.AnimationMode, _ => Document.Current?.ForceAnimationUpdate());
            mainWidget.AddChangeWatcher(() => Document.Current?.Container, _ => Document.Current?.ForceAnimationUpdate());
            Application.Exiting += () => Project.Current.Close();
            Application.Exited  += () => {
                AppUserPreferences.Instance.DockState             = DockManager.Instance.ExportState();
                SceneUserPreferences.Instance.VisualHintsRegistry = VisualHintsRegistry.Instance;
                Core.UserPreferences.Instance.Save();
                Orange.The.Workspace.Save();
            };

            var timelinePanel      = new Panel("Timeline");
            var inspectorPanel     = new Panel("Inspector");
            var searchPanel        = new Panel("Hierarchy");
            var animationsPanel    = new Panel("Animations");
            var filesystemPanel    = new Panel("Filesystem");
            var consolePanel       = new Panel("Console");
            var backupHistoryPanel = new Panel("Backups");
            var documentPanel      = new Panel(DockManager.DocumentAreaId, undockable: false);
            documentPanel.PanelWidget = documentPanel.ContentWidget;
            var visualHintsPanel     = new Panel("Visual Hints");
            var attachmentPanel      = new Panel("Model3D Attachment");
            var remoteScriptingPanel = new Panel("Remote Scripting");
            var dockManager          = DockManager.Instance;
            new UI.Console(consolePanel);
            var root      = dockManager.Model.WindowPlacements.First();
            var placement = new LinearPlacement(LinearPlacementDirection.Horizontal);
            dockManager.AddPanel(timelinePanel, root, DockSite.Top, 0.3f);
            dockManager.DockPlacementTo(placement, root, DockSite.Bottom, 0.6f);
            dockManager.AppendPanelTo(documentPanel, placement, 0.5f);
            var commandHandlerList = CommandHandlerList.Global;
            var commandsDictionary = new Dictionary <string, Command> {
                { animationsPanel.Id, new Command(animationsPanel.Title) },
                { timelinePanel.Id, new Command(timelinePanel.Title) },
                { inspectorPanel.Id, new Command(inspectorPanel.Title) },
                { searchPanel.Id, new Command(searchPanel.Title) },
                { filesystemPanel.Id, new Command(filesystemPanel.Title) },
                { consolePanel.Id, new Command(consolePanel.Title) },
                { backupHistoryPanel.Id, new Command(backupHistoryPanel.Title) },
                { visualHintsPanel.Id, new Command(visualHintsPanel.Title) },
                { attachmentPanel.Id, new Command(attachmentPanel.Title) },
                { remoteScriptingPanel.Id, new Command(remoteScriptingPanel.Title) },
            };
            foreach (var pair in commandsDictionary)
            {
                commandHandlerList.Connect(pair.Value, new PanelCommandHandler(pair.Key));
                TangerineMenu.PanelsMenu.Add(pair.Value);
            }
            dockManager.AddPanel(inspectorPanel, placement, DockSite.Left);
            var filesystemPlacement = dockManager.AddPanel(filesystemPanel, placement, DockSite.Right);
            dockManager.AddPanel(searchPanel, filesystemPlacement, DockSite.Fill);
            dockManager.AddPanel(animationsPanel, filesystemPlacement, DockSite.Fill);
            dockManager.AddPanel(backupHistoryPanel, filesystemPlacement, DockSite.Fill);
            dockManager.AddPanel(consolePanel, filesystemPlacement, DockSite.Bottom, 0.3f);
            dockManager.AddPanel(visualHintsPanel, placement, DockSite.Right, 0.3f).Hidden     = true;
            dockManager.AddPanel(attachmentPanel, placement, DockSite.Bottom, 0.3f).Hidden     = true;
            dockManager.AddPanel(remoteScriptingPanel, placement, DockSite.Right, 0.3f).Hidden = true;
            DockManagerInitialState = dockManager.ExportState();
            var documentViewContainer = InitializeDocumentArea(dockManager);
            documentPanel.ContentWidget.Nodes.Add(dockManager.DocumentArea);
            dockManager.ImportState(AppUserPreferences.Instance.DockState);
            Document.CloseConfirmation += doc => {
                var alert = new AlertDialog($"Save the changes to document '{doc.Path}' before closing?", "Yes", "No", "Cancel");
                switch (alert.Show())
                {
                case 0: return(Document.CloseAction.SaveChanges);

                case 1: return(Document.CloseAction.DiscardChanges);

                case -1:
                default: return(Document.CloseAction.Cancel);
                }
            };
            mainWidget.Tasks.Add(HandleMissingDocumentsTask);
            Project.HandleMissingDocuments += missingDocuments => {
                foreach (var d in missingDocuments)
                {
                    missingDocumentsList.Add(d);
                }
            };
            Project.DocumentReloadConfirmation += doc => {
                if (doc.IsModified)
                {
                    var modifiedAlert = new AlertDialog($"{doc.Path}\n\nThis file has been modified by another program and has unsaved changes.\nDo you want to reload it from disk? ", "Yes", "No");
                    var res           = modifiedAlert.Show();
                    if (res == 1 || res == -1)
                    {
                        doc.History.ExternalModification();
                        return(false);
                    }
                    return(true);
                }
                if (CoreUserPreferences.Instance.ReloadModifiedFiles)
                {
                    return(true);
                }
                var alert = new AlertDialog($"{doc.Path}\n\nThis file has been modified by another program.\nDo you want to reload it from disk? ", "Yes, always", "Yes", "No");
                var r     = alert.Show();
                if (r == 0)
                {
                    CoreUserPreferences.Instance.ReloadModifiedFiles = true;
                    return(true);
                }
                if (r == 2)
                {
                    doc.History.ExternalModification();
                    return(false);
                }
                return(true);
            };

            Project.TempFileLoadConfirmation += path => {
                var alert = new AlertDialog($"Do you want to load autosaved version of '{path}'?", "Yes", "No");
                return(alert.Show() == 0);
            };

            Project.OpenFileOutsideProjectAttempt += (string filePath) => {
                var projectFilePath = SearhForCitproj(filePath);
                if (projectFilePath != null && Project.Current.CitprojPath != projectFilePath)
                {
                    var alert = new AlertDialog($"You're trying to open a document outside the project directory. Change the current project to '{Path.GetFileName(projectFilePath)}'?", "Yes", "No");
                    if (alert.Show() == 0)
                    {
                        if (FileOpenProject.Execute(projectFilePath))
                        {
                            Project.Current.OpenDocument(filePath, true);
                        }
                        return;
                    }
                }
                else if (projectFilePath == null)
                {
                    AlertDialog.Show("Can't open a document outside the project directory");
                }
            };
            Project.Tasks = dockManager.MainWindowWidget.Tasks;
            Project.Tasks.Add(new AutosaveProcessor(() => AppUserPreferences.Instance.AutosaveDelay));
            BackupManager.Instance.Activate(Project.Tasks);
            Document.NodeDecorators.AddFor <Spline>(n => n.CompoundPostPresenter.Add(new UI.SceneView.SplinePresenter()));
            Document.NodeDecorators.AddFor <Viewport3D>(n => n.CompoundPostPresenter.Add(new UI.SceneView.Spline3DPresenter()));
            Document.NodeDecorators.AddFor <Viewport3D>(n => n.CompoundPostPresenter.Add(new UI.SceneView.Animation3DPathPresenter()));
            Document.NodeDecorators.AddFor <Widget>(n => {
                if (n.AsWidget.SkinningWeights == null)
                {
                    n.AsWidget.SkinningWeights = new SkinningWeights();
                }
            });
            Document.NodeDecorators.AddFor <PointObject>(n => {
                if ((n as PointObject).SkinningWeights == null)
                {
                    (n as PointObject).SkinningWeights = new SkinningWeights();
                }
            });
            Animation.EasingEnabledChecker = (animation) => {
                var doc = Document.Current;
                return(doc == null || doc.PreviewScene || animation != doc.Animation);
            };
            if (SceneUserPreferences.Instance.VisualHintsRegistry != null)
            {
                VisualHintsRegistry.Instance = SceneUserPreferences.Instance.VisualHintsRegistry;
            }
            VisualHintsRegistry.Instance.RegisterDefaultHints();

            Document.NodeDecorators.AddFor <Node>(n => n.SetTangerineFlag(TangerineFlags.SceneNode, true));
            dockManager.UnhandledExceptionOccurred += e => {
                AlertDialog.Show(e.Message + "\n" + e.StackTrace);
                var doc = Document.Current;
                if (doc != null)
                {
                    while (doc.History.IsTransactionActive)
                    {
                        doc.History.EndTransaction();
                    }
                    var closeConfirmation = Document.CloseConfirmation;
                    try {
                        Document.CloseConfirmation = d => {
                            var alert = new AlertDialog($"Save the changes to document '{d.Path}' before closing?", "Yes", "No");
                            switch (alert.Show())
                            {
                            case 0: return(Document.CloseAction.SaveChanges);

                            default: return(Document.CloseAction.DiscardChanges);
                            }
                        };
                        var fullPath = doc.FullPath;

                        if (!File.Exists(fullPath))
                        {
                            doc.Save();
                        }
                        var path = doc.Path;
                        Project.Current.CloseDocument(doc);
                        Project.Current.OpenDocument(path);
                    } finally {
                        Document.CloseConfirmation = closeConfirmation;
                    }
                }
            };

            Document.NodeDecorators.AddFor <ParticleEmitter>(n => n.CompoundPostPresenter.Add(new UI.SceneView.ParticleEmitterPresenter()));
            DocumentHistory.AddOperationProcessorTypes(new[] {
                typeof(Core.Operations.TimelineHorizontalShift.Processor),
                typeof(Core.Operations.TimelineColumnRemove.Processor),
                typeof(Core.Operations.RemoveKeyframeRange.Processor),
                typeof(Core.Operations.SelectRow.Processor),
                typeof(Core.Operations.RenameAnimationProcessor),
                typeof(Core.Operations.SetProperty.Processor),
                typeof(Core.Operations.SetIndexedProperty.Processor),
                typeof(Core.Operations.RemoveKeyframe.Processor),
                typeof(Core.Operations.SetKeyframe.Processor),
                typeof(Core.Operations.InsertFolderItem.Processor),
                typeof(Core.Operations.AddIntoCollection <,> .Processor),
                typeof(Core.Operations.RemoveFromCollection <,> .Processor),
                typeof(Core.Operations.InsertIntoList.Processor),
                typeof(Core.Operations.RemoveFromList.Processor),
                typeof(Core.Operations.InsertIntoList <,> .Processor),
                typeof(Core.Operations.RemoveFromList <,> .Processor),
                typeof(Core.Operations.UnlinkFolderItem.Processor),
                typeof(Core.Operations.MoveNodes.Processor),
                typeof(Core.Operations.SetMarker.Processor),
                typeof(Core.Operations.DeleteMarker.Processor),
                typeof(Core.Operations.SetComponent.Processor),
                typeof(Core.Operations.DeleteComponent.Processor),
                typeof(Core.Operations.DistortionMeshProcessor),
                typeof(Core.Operations.SyncFolderDescriptorsProcessor),
                typeof(UI.SceneView.ResolutionPreviewOperation.Processor),
                typeof(UI.Timeline.Operations.SelectGridSpan.Processor),
                typeof(UI.Timeline.Operations.DeselectGridSpan.Processor),
                typeof(UI.Timeline.Operations.ClearGridSelection.Processor),
                typeof(UI.Timeline.Operations.ShiftGridSelection.Processor),
                typeof(UI.Timeline.Operations.SetCurrentColumn.Processor),
                typeof(UI.Timeline.Operations.SelectCurveKey.Processor),
                typeof(TriggersValidatorOnSetProperty),
                typeof(TriggersValidatorOnSetKeyframe),
                typeof(UpdateNodesAndApplyAnimatorsProcessor),
                typeof(RowsSynchronizer),
                typeof(Core.Operations.ReplaceContents.Processor),
                typeof(Core.Operations.DeleteRuler.Processor),
                typeof(Core.Operations.CreateRuler.Processor),
            });
            DocumentHistory.AddOperationProcessorTypes(UI.Timeline.Timeline.GetOperationProcessorTypes());

            RegisterCommands();
            InitializeHotkeys();

            AppUserPreferences.Instance.ToolbarModel.RefreshAfterLoad();
            Toolbar = new ToolbarView(dockManager.ToolbarArea, AppUserPreferences.Instance.ToolbarModel);
            RefreshCreateNodeCommands();
            Document.AttachingViews += doc => {
                if (doc.Views.Count == 0)
                {
                    doc.Views.AddRange(new IDocumentView[] {
                        new UI.Inspector.Inspector(inspectorPanel.ContentWidget),
                        new UI.Timeline.Timeline(timelinePanel),
                        new UI.SceneView.SceneView(documentViewContainer),
                        new Panels.HierarchyPanel(searchPanel.ContentWidget),
                        new Panels.BackupHistoryPanel(backupHistoryPanel.ContentWidget),
                        new Panels.AnimationsPanel(animationsPanel.ContentWidget),
                        // Use VisualHintsPanel sigleton because we need preserve its state between documents.
                        VisualHintsPanel.Instance ?? VisualHintsPanel.Initialize(visualHintsPanel),
                        new AttachmentPanel(attachmentPanel),
                    });
                    UI.SceneView.SceneView.ShowNodeDecorationsPanelButton.Clicked = () => dockManager.TogglePanel(visualHintsPanel);
                }
            };
            var proj = AppUserPreferences.Instance.CurrentProject;
            if (proj != null)
            {
                try {
                    new Project(proj).Open();
                } catch {
                    AlertDialog.Show($"Cannot open project '{proj}'. It may be deleted or be otherwise unavailable.");
                }
            }
            OpenDocumentsFromArgs(args);
            WidgetContext.Current.Root.AddChangeWatcher(() => Project.Current, project => TangerineMenu.OnProjectChanged(project));

            WidgetContext.Current.Root.AddChangeWatcher(() => ProjectUserPreferences.Instance.RecentDocuments.Count == 0 ?
                                                        null : ProjectUserPreferences.Instance.RecentDocuments[0], document => TangerineMenu.RebuildRecentDocumentsMenu());

            WidgetContext.Current.Root.AddChangeWatcher(() => AppUserPreferences.Instance.RecentProjects.Count == 0 ?
                                                        null : AppUserPreferences.Instance.RecentProjects[0], document => TangerineMenu.RebuildRecentProjectsMenu());

            new UI.FilesystemView.FilesystemPane(filesystemPanel);
            new UI.RemoteScripting.RemoteScriptingPane(remoteScriptingPanel);
            RegisterGlobalCommands();

            Documentation.Init();
            DocumentationComponent.Clicked = page => Documentation.ShowHelp(page);
        }
Esempio n. 26
0
 public ActionResult Navigation()
 {
     return(View(Documentation.GetAll()));
 }
Esempio n. 27
0
        private void Man(string[] args)
        {
            switch (args.Length)
            {
            case 1:
                if (args[0].ToLower().Equals("list"))
                {
                    foreach (string key in Documentation.Keys)
                    {
                        WriteLineColor(key, Cyan);
                    }
                    return;
                }
                string topic = args[0];
                if (Documentation.ContainsKey(topic))
                {
                    try
                    {
                        ManualObject obj = JsonConvert.DeserializeObject <ManualObject>(Documentation[topic]);
                        Console.WriteLine("7Sharp Manual");
                        Console.WriteLine();
                        Console.WriteLine(obj.title);
                        Console.WriteLine();
                        Console.WriteLine($"{new string('=', Console.WindowWidth)}\n");
                        foreach (ManualSection s in obj.sections)
                        {
                            Console.WriteLine(s.header);
                            Console.WriteLine();
                            foreach (ManualTextComponent c in s.text)
                            {
                                if (c.color == null)
                                {
                                    c.color = Gray.ToString();
                                }
                                if (c.back == null)
                                {
                                    c.back = Black.ToString();
                                }
                                Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), c.back);
                                Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), c.color);
                                Console.Write(c.text);
                                Console.ResetColor();
                            }
                            Console.WriteLine($"\n{new string('-', Console.WindowWidth)}\n");
                        }
                    }
                    catch (Exception e)
                    {
                        Utils.PrintError(e);
                    }
                }
                else
                {
                    WriteLineColor("Topic not found!\nType man list for a list of topics!", Red);
                    return;
                }
                break;

            default:
                WriteLineColor("Invalid syntax! man <topic>\nType man list for a list of topics!", Red);
                break;
            }
        }
Esempio n. 28
0
 public ActionResult Search(string query)
 {
     ViewData["query"] = query ?? string.Empty;
     return(View(Documentation.Search(query ?? string.Empty)));
 }
Esempio n. 29
0
 /// <summary>
 /// This function is the callback used to execute the command when the menu item is clicked.
 /// See the constructor to see how the menu item is associated with this function using
 /// OleMenuCommandService service and MenuCommand class.
 /// </summary>
 /// <param name="sender">Event sender.</param>
 /// <param name="e">Event args.</param>
 private void Execute(object sender, EventArgs e)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     Documentation.OpenLink(Documentation.Link.MainPage);
 }
 static void DrawDecalLayerNames(SerializedHDRenderPipelineGlobalSettings serialized, Editor owner)
 {
     m_ShowDecalLayerNames = CoreEditorUtils.DrawHeaderFoldout(Styles.decalLayersLabel, m_ShowDecalLayerNames,
                                                               documentationURL: Documentation.GetPageLink(DocumentationUrls.k_DecalLayers),
                                                               contextAction: pos => OnContextClickRenderingLayerNames(pos, serialized, section: 2));
     if (m_ShowDecalLayerNames)
     {
         using (new EditorGUI.IndentLevelScope())
         {
             using (var changed = new EditorGUI.ChangeCheckScope())
             {
                 EditorGUILayout.DelayedTextField(serialized.decalLayerName0, Styles.decalLayerName0);
                 EditorGUILayout.DelayedTextField(serialized.decalLayerName1, Styles.decalLayerName1);
                 EditorGUILayout.DelayedTextField(serialized.decalLayerName2, Styles.decalLayerName2);
                 EditorGUILayout.DelayedTextField(serialized.decalLayerName3, Styles.decalLayerName3);
                 EditorGUILayout.DelayedTextField(serialized.decalLayerName4, Styles.decalLayerName4);
                 EditorGUILayout.DelayedTextField(serialized.decalLayerName5, Styles.decalLayerName5);
                 EditorGUILayout.DelayedTextField(serialized.decalLayerName6, Styles.decalLayerName6);
                 EditorGUILayout.DelayedTextField(serialized.decalLayerName7, Styles.decalLayerName7);
                 if (changed.changed)
                 {
                     serialized.serializedObject?.ApplyModifiedProperties();
                     (serialized.serializedObject.targetObject as HDRenderPipelineGlobalSettings).UpdateRenderingLayerNames();
                 }
             }
         }
     }
 }
Esempio n. 31
0
 public void Delete(Documentation item)
 {
     new DocumentationRepository().Delete(item);
 }
Esempio n. 32
0
 public FrontPageBuilder(Documentation doc, string root)
 {
     _doc  = doc;
     _root = root;
 }
        /// <summary>
        /// Handles the event when the custom menu item "Documentation" is clicked.
        /// </summary>
        /// <param name="sender"> The object that raises the event. </param>
        /// <param name="e"> The event data. </param>
        private void MenuItemClickComponentDoc(object sender, EventArgs e)
        {
            string url = Documentation.ComponentWeblinks[this.GetType()];

            Documentation.OpenBrowser(url);
        }
Esempio n. 34
0
 public FormParentListEventArgs(Documentation.DocumentsList DocList)
 {
     _docList = DocList;
 }