Example #1
1
        /// <summary>
        /// Syntax highlights the given source code using the rules and styles of the specified programming language
        /// </summary>
        /// <param name="textformatter">The formatter to be called back to apply the appropriate formatting to a specified range of the text</param>
        /// <param name="language">The programming language in which the text is written</param>
        /// <param name="text">The source code to be syntax highlighted</param>
        /// <param name="offset">Optional parameter: the position in the text where the highlightning begins</param>
        public void Colorize(TextFormatter textformatter, string language, string text, int offset = 0)
        {
            // Check for invalid or unavaliable language
            Language lang;
            try
            {
                lang = this.languages[language];
            }
            catch (KeyNotFoundException e)
            {
                throw new InvalidLanguageException(language, e);
            }
            if (lang.InvalidRegex)
            {
                throw new InvalidRegexException(language);
            }

            // Syntax higlightning using the regular expressions
            foreach (Match match in lang.MasterRegex.Matches(text))
            {
                foreach (LanguageElement element in lang.Elements)
                {
                    if (match.Groups[element.Name].Success)
                    {
                        // callback to the formatter for every language element found
                        textformatter.ColorRangeOfText(match.Index + offset, match.Length, element.Color, element.CharFormat);

                        // Recursive call if it finds a code block written in a different programming language
                        if (element.SubLanguage != null)
                            this.Colorize(textformatter, element.SubLanguage.Name, text.Substring(match.Index, match.Length), match.Index);
                    }
                }
            }
        }
		public static void TestFormat(string srcPath, string goldPath)
		{
			var formatter = new TextFormatter();
			string result;
			using (var reader = new StreamReader(srcPath))
				result = string.Format("<html>\r\n\t<body>\r\n{0}\r\n\t</body>\r\n</html>", formatter.Format(reader.ReadToEnd()));

			CompareSamples(goldPath, result);
		}
		public string[] Format(string markup)
		{
			var formatter = new TextFormatter();

			var output = formatter.Format(markup);
			var result = string.Format("<html>\r\n\t<body>\r\n{0}\r\n\t</body>\r\n</html>", output);

			return result.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
		}
        public void FormatsWithNoTokens()
        {
            TextFormatter formatter = new TextFormatter("no tokens");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("no tokens", actual);
        }
 public XmlDocLanguageWriter(ILanguage language, IDocumentationLoader docLoader, bool injectXmlDoc)
 {
     _language = language;
     _docLoader = docLoader;
     _injectXmlDoc = injectXmlDoc;
     _configuration = new LanguageConfiguration();
     _formatter = new TextFormatter();
     _writer = language.GetWriter(_formatter, _configuration);
 }
        public void FormatsMixedTextAndTokens()
        {
            TextFormatter formatter = new TextFormatter("some {newline} mixed{tab}text");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("some " + Environment.NewLine + " mixed\ttext", actual);
        }
        public void FormatsWithTwoConstants()
        {
            TextFormatter formatter = new TextFormatter("{newline}{tab}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual(Environment.NewLine + "\t", actual);
        }
    public GameWorldTextRenderer(TextFormatter formatter, Vector3 position)
    {
        this.formatter = formatter;

        gameObject = new GameObject(tagName(formatter.GetId()));
        UpdatePosition(position);

        textMesh = gameObject.AddComponent<TextMesh>();
        textMesh.fontSize = (int) (100 * GameMapSizeFactor.GetFactorForCurrentMapRelativeToFirstMap());
        textMesh.anchor = TextAnchor.UpperCenter;
        textMesh.alignment = TextAlignment.Center;
        textMesh.color = Color.yellow;
        textMesh.fontStyle = FontStyle.Bold;
    }
        public void DictionaryTokenCanHandleInternalParenthesisAsLongAsTheyAreNotFollowedByACurlyBracket()
        {
            TextFormatter formatter = new TextFormatter("{dictionary(({key})-{value} - )}");
            CustomLogEntry entry = new CustomLogEntry();
            Dictionary<string, object> hash = new Dictionary<string, object>();
            hash["key1"] = "value1";
            hash["key2"] = "value2";
            entry.ExtendedProperties = hash;

            string actual = formatter.Format(entry);

            Assert.AreEqual("(key1)-value1 - (key2)-value2 - ", actual);
        }
        public void FormatsTimestampWithNoFormat()
        {
            TextFormatter formatter = new TextFormatter("Timestamp: {timestamp}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Timestamp: " + entry.TimeStamp.ToString(CultureInfo.CurrentCulture), actual);
        }
        public static string Generate(
            ClassStatement classStatement,
            TextFormatter textFormatter
            )
        {
            var classTokenMap = new Dictionary <string, string>
            {
                { "[[INTERFACE_SECTION]]", string.Empty },
                { "[[EXTENDED_CLASSES_SECTION]]", string.Empty },
                { "[[WHERE_CONSTRAINT]]", string.Empty },
                { "[[CLASS_GENERICS]]", string.Empty },
                { "[[STATIC_ACCESSORS]]", string.Empty },
                { "[[STATIC_PROPERTIES]]", string.Empty },
                { "[[STATIC_METHODS]]", string.Empty },
                { "[[ACCESSORS]]", string.Empty },
                { "[[PROPERTIES]]", string.Empty },
                { "[[CONSTRUCTOR]]", string.Empty },
                { "[[METHODS]]", string.Empty },
                { "[[ASSEMBLY]]", classStatement.ProjectAssembly },
                { "[[CLASS_NAME]]", string.Empty },
                { "[[NAMESPACE]]", string.Empty },
                { "[[BASE_CONSTRUCTOR]]", string.Empty },
                { "[[INTERFACE_POSTFIX]]", string.Empty },
            };

            // Group Parts of the Class
            var staticAccessors    = classStatement.AccessorStatements.Where(a => a.IsStatic);
            var staticProperties   = classStatement.PublicPropertyStatements.Where(a => a.IsStatic);
            var staticMethods      = classStatement.PublicMethodStatements.Where(a => a.IsStatic).Distinct();
            var accessors          = classStatement.AccessorStatements.Where(a => !a.IsStatic);
            var properties         = classStatement.PublicPropertyStatements.Where(a => !a.IsStatic);
            var constructorDetails = classStatement.ConstructorStatement;
            var methods            = classStatement.PublicMethodStatements.Where(a => !a.IsStatic).Distinct();

            // Templates
            var classGenerationTemplates = ReadTemplates.Read();

            var classTemplate = classGenerationTemplates.Class;

            // Generate Tokens
            var namespaceReplaced = classStatement.Namespace;

            if (string.IsNullOrWhiteSpace(namespaceReplaced))
            {
                namespaceReplaced = string.Empty;
                classTemplate     = classGenerationTemplates.ClassWithNoNamespace;
            }
            classTokenMap["[[NAMESPACE]]"]  = namespaceReplaced;
            classTokenMap["[[CLASS_NAME]]"] = classStatement.Name;

            classTokenMap["[[INTERFACE_SECTION]]"] = InterfaceSectionWriter.Write(
                classStatement,
                classGenerationTemplates
                );
            classTokenMap["[[INTERFACE_POSTFIX]]"] = classStatement.IsInterface ? Constants.INTERFACE_POSTFIX : string.Empty;
            classTokenMap["[[CLASS_GENERICS]]"]    = BuildClassGenerics(
                classStatement
                );
            classTokenMap["[[JSON_CONVERTER_CLASS_GENERICS]]"] = BuildJsonConvertClassGenerics(
                classStatement
                );
            classTokenMap["[[EXTENDED_CLASSES_SECTION]]"] = BuildExtendedClassesSection(
                classStatement
                );
            classTokenMap["[[WHERE_CONSTRAINT]]"] = classStatement.GenericTypes.Any()
                ? string.Join(
                "",
                classStatement.GenericTypes.Select(
                    genericType => $" where {genericType.Name} : CachedEntity, new()"
                    )
                )
                : string.Empty;
            classTokenMap["[[STATIC_ACCESSORS]]"] = AccessorsSectionWriter.Write(
                classStatement,
                staticAccessors,
                classGenerationTemplates
                );
            classTokenMap["[[STATIC_PROPERTIES]]"] = PropertiesSectionWriter.Write(
                classStatement,
                staticProperties,
                classGenerationTemplates
                );
            classTokenMap["[[STATIC_METHODS]]"] = MethodsSectionWriter.Write(
                classStatement,
                staticMethods,
                classGenerationTemplates
                );
            classTokenMap["[[ACCESSORS]]"] = AccessorsSectionWriter.Write(
                classStatement,
                accessors,
                classGenerationTemplates
                );
            classTokenMap["[[PROPERTIES]]"] = PropertiesSectionWriter.Write(
                classStatement,
                properties,
                classGenerationTemplates
                );
            classTokenMap["[[CONSTRUCTOR]]"] = ConstructorSectionWriter.Write(
                classStatement,
                constructorDetails,
                classGenerationTemplates
                );
            classTokenMap["[[BASE_CONSTRUCTOR]]"] = BaseConstructorSectionWriter.Write(
                classStatement,
                constructorDetails,
                classGenerationTemplates
                );
            classTokenMap["[[METHODS]]"] = MethodsSectionWriter.Write(
                classStatement,
                methods,
                classGenerationTemplates
                );

            var classStringBuilder = new StringBuilder(
                classTemplate
                );

            classStringBuilder = classTokenMap.Aggregate(
                classStringBuilder,
                (acc, token) => acc.Replace(
                    token.Key,
                    token.Value
                    )
                );

            return(textFormatter.Format(
                       classStringBuilder.ToString()
                       ));
        }
Example #12
0
 public void Setup()
 {
     writer         = new TestWriter();
     textFormatter  = new TextFormatter(writer);
     eventFormatter = new EventFormatter(textFormatter);
 }
        public void FormatsErrorMessagesToken()
        {
            TextFormatter formatter = new TextFormatter("Errors: {errorMessages}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();
            entry.AddErrorMessage("an error message");

            string actual = formatter.Format(entry);

            Assert.AreEqual("Errors: " + entry.ErrorMessages, actual);
        }
        public void FormatReflectedPropertyTokenFunctionPropertyFoundAndNullValue()
        {
            CustomLogEntry entry = new CustomLogEntry();

            ILogFormatter formatter = new TextFormatter("Reflected Property Value: {property(MyPropertyThatReturnsNull)}");
            string actual = formatter.Format(entry);

            string expected = "Reflected Property Value: ";
            Assert.AreEqual(expected, actual);
        }
        public void FormatterIsReusableBug1769()
        {
            ILogFormatter formatter = new TextFormatter("{message}");

            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            entry.Message = "message1";
            Assert.AreEqual(entry.Message, formatter.Format(entry));

            entry.Message = "message2";
            Assert.AreEqual(entry.Message, formatter.Format(entry));

            entry.Message = "message3";
            Assert.AreEqual(entry.Message, formatter.Format(entry));
        }
Example #16
0
        public void Limit_WhenOverLimit_IsLimited(string input, int characterCount, string expected)
        {
            var result = TextFormatter.Limit(input, characterCount);

            Assert.Equal(expected, result);
        }
Example #17
0
        IEnumerable <TextBlock> BuildPointsHeadings()
        {
            var assets    = Resolve <IAssetManager>();
            var settings  = Resolve <ISettings>();
            var member    = Resolve <IParty>()[_activeMember];
            var formatter = new TextFormatter(assets, settings.Gameplay.Language);

            string S(SystemTextId id) => assets.LoadString(id, settings.Gameplay.Language);

            if (member == null)
            {
                yield break;
            }

            foreach (var block in formatter.Format(S(SystemTextId.Inv1_LifePoints)).Item1)
            {
                block.Arrangement = TextArrangement.NoWrap;
                block.Alignment   = TextAlignment.Right;
                yield return(block);
            }

            if (member.Apparent.Magic.SpellPointsMax > 0)
            {
                foreach (var block in formatter.Format(S(SystemTextId.Inv1_SpellPoints)).Item1)
                {
                    block.Arrangement = TextArrangement.ForceNewLine | TextArrangement.NoWrap;
                    block.Alignment   = TextAlignment.Right;
                    yield return(block);
                }
            }
            else
            {
                yield return new TextBlock("")
                       {
                           Arrangement = TextArrangement.ForceNewLine
                       }
            };

            foreach (var block in formatter.Format(S(SystemTextId.Inv1_ExperiencePoints)).Item1)
            {
                block.Arrangement = TextArrangement.ForceNewLine | TextArrangement.NoWrap;

                block.Alignment = TextAlignment.Right;
                yield return(block);
            }

            foreach (var block in formatter.Format(S(SystemTextId.Inv1_TrainingPoints)).Item1)
            {
                block.Arrangement = TextArrangement.ForceNewLine | TextArrangement.NoWrap;
                block.Alignment   = TextAlignment.Right;
                yield return(block);
            }
        }

        IEnumerable <TextBlock> BuildPoints()
        {
            var member = Resolve <IParty>()[_activeMember];

            if (member == null)
            {
                yield break;
            }

            yield return(new TextBlock($"{member.Apparent.Combat.LifePoints}/{member.Apparent.Combat.LifePointsMax}")
            {
                Arrangement = TextArrangement.NoWrap
            });

            yield return(new TextBlock(
                             member.Apparent.Magic.SpellPointsMax > 0
                    ? $"{member.Apparent.Magic.SpellPoints}/{member.Apparent.Magic.SpellPointsMax}"
                    : "")
            {
                Arrangement = TextArrangement.ForceNewLine | TextArrangement.NoWrap
            });

            yield return(new TextBlock($"{member.Apparent.Combat.ExperiencePoints}")
            {
                Arrangement = TextArrangement.ForceNewLine | TextArrangement.NoWrap
            });

            yield return(new TextBlock($"{member.Apparent.Combat.TrainingPoints}")
            {
                Arrangement = TextArrangement.ForceNewLine | TextArrangement.NoWrap
            });
        }
    }
Example #18
0
        public void Limit_WhenNullOrEmpty_ReturnsEmptyString(string input)
        {
            var result = TextFormatter.Limit(input, 10);

            Assert.Equal(result, string.Empty);
        }
Example #19
0
        public void Limit_WhenWhitespace_ReturnsWhitespace(string input)
        {
            var result = TextFormatter.Limit(input, 10);

            Assert.Equal(result, input);
        }
Example #20
0
        static void Main(string[] args)
        {
            PerfTracker.StartupEvent("Entered main");
            Event.AddEventsFromAssembly(Assembly.GetAssembly(typeof(UAlbion.Api.Event)));
            Event.AddEventsFromAssembly(Assembly.GetAssembly(typeof(UAlbion.Core.Events.HelpEvent)));
            Event.AddEventsFromAssembly(Assembly.GetAssembly(typeof(UAlbion.Core.Veldrid.Events.InputEvent)));
            Event.AddEventsFromAssembly(Assembly.GetAssembly(typeof(UAlbion.Editor.EditorSetPropertyEvent)));
            Event.AddEventsFromAssembly(Assembly.GetAssembly(typeof(UAlbion.Formats.ScriptEvents.PartyMoveEvent)));
            Event.AddEventsFromAssembly(Assembly.GetAssembly(typeof(UAlbion.Game.Events.StartEvent)));
            Event.AddEventsFromAssembly(Assembly.GetAssembly(typeof(UAlbion.Game.Veldrid.Debugging.HideDebugWindowEvent)));
            Event.AddEventsFromAssembly(Assembly.GetAssembly(typeof(IsoYawEvent)));
            PerfTracker.StartupEvent("Built event parsers");

            var commandLine = new CommandLineOptions(args);

            if (commandLine.Mode == ExecutionMode.Exit)
            {
                return;
            }

            PerfTracker.StartupEvent($"Running as {commandLine.Mode}");
            var disk     = new FileSystem();
            var jsonUtil = new FormatJsonUtil();

            var baseDir = ConfigUtil.FindBasePath(disk);

            if (baseDir == null)
            {
                throw new InvalidOperationException("No base directory could be found.");
            }

            PerfTracker.StartupEvent($"Found base directory {baseDir}");

            if (commandLine.Mode == ExecutionMode.ConvertAssets)
            {
                ConvertAssets.Convert(
                    disk,
                    jsonUtil,
                    commandLine.ConvertFrom,
                    commandLine.ConvertTo,
                    commandLine.DumpIds,
                    commandLine.DumpAssetTypes,
                    commandLine.ConvertFilePattern);
                return;
            }

            var(exchange, services) = AssetSystem.SetupAsync(baseDir, disk, jsonUtil).Result;
            if (commandLine.NeedsEngine)
            {
                BuildEngine(commandLine, exchange);
            }
            services.Add(new StdioConsoleReader());

            var assets = exchange.Resolve <IAssetManager>();

            AutodetectLanguage(exchange, assets);

            switch (commandLine.Mode) // ConvertAssets handled above as it requires a specialised asset system setup
            {
            case ExecutionMode.Game: Albion.RunGame(exchange, services, baseDir, commandLine); break;

            case ExecutionMode.BakeIsometric: IsometricTest.Run(exchange, commandLine); break;

            case ExecutionMode.DumpData:
                PerfTracker.BeginFrame();     // Don't need to show verbose startup logging while dumping
                var tf = new TextFormatter();
                exchange.Attach(tf);
                var parsedIds = commandLine.DumpIds?.Select(AssetId.Parse).ToArray();

                if ((commandLine.DumpFormats & DumpFormats.Json) != 0)
                {
                    DumpJson.Dump(baseDir, assets, commandLine.DumpAssetTypes, parsedIds);
                }

                if ((commandLine.DumpFormats & DumpFormats.Text) != 0)
                {
                    DumpText.Dump(assets, baseDir, tf, commandLine.DumpAssetTypes, parsedIds);
                }

                if ((commandLine.DumpFormats & DumpFormats.Png) != 0)
                {
                    var dumper = new DumpGraphics();
                    exchange.Attach(dumper);
                    dumper.Dump(baseDir, commandLine.DumpAssetTypes, commandLine.DumpFormats, parsedIds);
                }

                //if ((commandLine.DumpFormats & DumpFormats.Tiled) != 0)
                //    DumpTiled.Dump(baseDir, assets, commandLine.DumpAssetTypes, parsedIds);
                break;

            case ExecutionMode.Exit: break;
            }

            Console.WriteLine("Exiting");
            exchange.Dispose();
        }
        public override void Setup()
        {
            // string txt = ".\n...\n.....\nHELLO\n.....\n...\n.";
            // string txt = "┌──┴──┐\n┤HELLO├\n└──┬──┘";
            string txt = "HELLO WORLD";

            var color1 = new ColorScheme {
                Normal = Application.Driver.MakeAttribute(Color.Black, Color.Gray)
            };
            var color2 = new ColorScheme {
                Normal = Application.Driver.MakeAttribute(Color.Black, Color.DarkGray)
            };

            var txts  = new List <Label> ();           // single line
            var mtxts = new List <Label> ();           // multi line

            // Horizontal Single-Line

            var labelHL = new Label("Left")
            {
                X = 1, Y = 1, Width = 9, Height = 1, TextAlignment = TextAlignment.Right, ColorScheme = Colors.ColorSchemes ["Dialog"]
            };
            var labelHC = new Label("Centered")
            {
                X = 1, Y = 2, Width = 9, Height = 1, TextAlignment = TextAlignment.Right, ColorScheme = Colors.ColorSchemes ["Dialog"]
            };
            var labelHR = new Label("Right")
            {
                X = 1, Y = 3, Width = 9, Height = 1, TextAlignment = TextAlignment.Right, ColorScheme = Colors.ColorSchemes ["Dialog"]
            };
            var labelHJ = new Label("Justified")
            {
                X = 1, Y = 4, Width = 9, Height = 1, TextAlignment = TextAlignment.Right, ColorScheme = Colors.ColorSchemes ["Dialog"]
            };

            var txtLabelHL = new Label(txt)
            {
                X = Pos.Right(labelHL) + 1, Y = Pos.Y(labelHL), Width = Dim.Fill(1) - 9, Height = 1, ColorScheme = color1, TextAlignment = TextAlignment.Left
            };
            var txtLabelHC = new Label(txt)
            {
                X = Pos.Right(labelHC) + 1, Y = Pos.Y(labelHC), Width = Dim.Fill(1) - 9, Height = 1, ColorScheme = color2, TextAlignment = TextAlignment.Centered
            };
            var txtLabelHR = new Label(txt)
            {
                X = Pos.Right(labelHR) + 1, Y = Pos.Y(labelHR), Width = Dim.Fill(1) - 9, Height = 1, ColorScheme = color1, TextAlignment = TextAlignment.Right
            };
            var txtLabelHJ = new Label(txt)
            {
                X = Pos.Right(labelHJ) + 1, Y = Pos.Y(labelHJ), Width = Dim.Fill(1) - 9, Height = 1, ColorScheme = color2, TextAlignment = TextAlignment.Justified
            };

            txts.Add(txtLabelHL); txts.Add(txtLabelHC); txts.Add(txtLabelHR); txts.Add(txtLabelHJ);

            Win.Add(labelHL); Win.Add(txtLabelHL);
            Win.Add(labelHC); Win.Add(txtLabelHC);
            Win.Add(labelHR); Win.Add(txtLabelHR);
            Win.Add(labelHJ); Win.Add(txtLabelHJ);

            // Vertical Single-Line

            var labelVT = new Label("Top")
            {
                X = Pos.AnchorEnd(8), Y = 1, Width = 2, Height = 9, ColorScheme = color1, TextDirection = TextDirection.TopBottom_LeftRight, VerticalTextAlignment = VerticalTextAlignment.Bottom
            };
            var labelVM = new Label("Middle")
            {
                X = Pos.AnchorEnd(6), Y = 1, Width = 2, Height = 9, ColorScheme = color1, TextDirection = TextDirection.TopBottom_LeftRight, VerticalTextAlignment = VerticalTextAlignment.Bottom
            };
            var labelVB = new Label("Bottom")
            {
                X = Pos.AnchorEnd(4), Y = 1, Width = 2, Height = 9, ColorScheme = color1, TextDirection = TextDirection.TopBottom_LeftRight, VerticalTextAlignment = VerticalTextAlignment.Bottom
            };
            var labelVJ = new Label("Justified")
            {
                X = Pos.AnchorEnd(2), Y = 1, Width = 1, Height = 9, ColorScheme = color1, TextDirection = TextDirection.TopBottom_LeftRight, VerticalTextAlignment = VerticalTextAlignment.Bottom
            };

            var txtLabelVT = new Label(txt)
            {
                X = Pos.X(labelVT), Y = Pos.Bottom(labelVT) + 1, Width = 1, Height = Dim.Fill(1), ColorScheme = color1, TextDirection = TextDirection.TopBottom_LeftRight, VerticalTextAlignment = VerticalTextAlignment.Top
            };
            var txtLabelVM = new Label(txt)
            {
                X = Pos.X(labelVM), Y = Pos.Bottom(labelVM) + 1, Width = 1, Height = Dim.Fill(1), ColorScheme = color2, TextDirection = TextDirection.TopBottom_LeftRight, VerticalTextAlignment = VerticalTextAlignment.Middle
            };
            var txtLabelVB = new Label(txt)
            {
                X = Pos.X(labelVB), Y = Pos.Bottom(labelVB) + 1, Width = 1, Height = Dim.Fill(1), ColorScheme = color1, TextDirection = TextDirection.TopBottom_LeftRight, VerticalTextAlignment = VerticalTextAlignment.Bottom
            };
            var txtLabelVJ = new Label(txt)
            {
                X = Pos.X(labelVJ), Y = Pos.Bottom(labelVJ) + 1, Width = 1, Height = Dim.Fill(1), ColorScheme = color2, TextDirection = TextDirection.TopBottom_LeftRight, VerticalTextAlignment = VerticalTextAlignment.Justified
            };

            txts.Add(txtLabelVT); txts.Add(txtLabelVM); txts.Add(txtLabelVB); txts.Add(txtLabelVJ);

            Win.Add(labelVT); Win.Add(txtLabelVT);
            Win.Add(labelVM); Win.Add(txtLabelVM);
            Win.Add(labelVB); Win.Add(txtLabelVB);
            Win.Add(labelVJ); Win.Add(txtLabelVJ);

            // Multi-Line

            var container = new View()
            {
                X = 0, Y = Pos.Bottom(txtLabelHJ), Width = Dim.Fill(31), Height = Dim.Fill(7), ColorScheme = color2
            };

            var txtLabelTL = new Label(txt)
            {
                X = 1 /*                    */, Y = 1, Width = Dim.Percent(100f / 3f), Height = Dim.Percent(100f / 3f), TextAlignment = TextAlignment.Left, VerticalTextAlignment = VerticalTextAlignment.Top, ColorScheme = color1
            };
            var txtLabelTC = new Label(txt)
            {
                X = Pos.Right(txtLabelTL) + 2, Y = 1, Width = Dim.Percent(100f / 3f), Height = Dim.Percent(100f / 3f), TextAlignment = TextAlignment.Centered, VerticalTextAlignment = VerticalTextAlignment.Top, ColorScheme = color1
            };
            var txtLabelTR = new Label(txt)
            {
                X = Pos.Right(txtLabelTC) + 2, Y = 1, Width = Dim.Percent(100f, true), Height = Dim.Percent(100f / 3f), TextAlignment = TextAlignment.Right, VerticalTextAlignment = VerticalTextAlignment.Top, ColorScheme = color1
            };

            var txtLabelML = new Label(txt)
            {
                X = Pos.X(txtLabelTL) /*    */, Y = Pos.Bottom(txtLabelTL) + 1, Width = Dim.Width(txtLabelTL), Height = Dim.Percent(100f / 3f), TextAlignment = TextAlignment.Left, VerticalTextAlignment = VerticalTextAlignment.Middle, ColorScheme = color1
            };
            var txtLabelMC = new Label(txt)
            {
                X = Pos.X(txtLabelTC) /*    */, Y = Pos.Bottom(txtLabelTC) + 1, Width = Dim.Width(txtLabelTC), Height = Dim.Percent(100f / 3f), TextAlignment = TextAlignment.Centered, VerticalTextAlignment = VerticalTextAlignment.Middle, ColorScheme = color1
            };
            var txtLabelMR = new Label(txt)
            {
                X = Pos.X(txtLabelTR) /*    */, Y = Pos.Bottom(txtLabelTR) + 1, Width = Dim.Percent(100f, true), Height = Dim.Percent(100f / 3f), TextAlignment = TextAlignment.Right, VerticalTextAlignment = VerticalTextAlignment.Middle, ColorScheme = color1
            };

            var txtLabelBL = new Label(txt)
            {
                X = Pos.X(txtLabelML) /*    */, Y = Pos.Bottom(txtLabelML) + 1, Width = Dim.Width(txtLabelML), Height = Dim.Percent(100f, true), TextAlignment = TextAlignment.Left, VerticalTextAlignment = VerticalTextAlignment.Bottom, ColorScheme = color1
            };
            var txtLabelBC = new Label(txt)
            {
                X = Pos.X(txtLabelMC) /*    */, Y = Pos.Bottom(txtLabelMC) + 1, Width = Dim.Width(txtLabelMC), Height = Dim.Percent(100f, true), TextAlignment = TextAlignment.Centered, VerticalTextAlignment = VerticalTextAlignment.Bottom, ColorScheme = color1
            };
            var txtLabelBR = new Label(txt)
            {
                X = Pos.X(txtLabelMR) /*    */, Y = Pos.Bottom(txtLabelMR) + 1, Width = Dim.Percent(100f, true), Height = Dim.Percent(100f, true), TextAlignment = TextAlignment.Right, VerticalTextAlignment = VerticalTextAlignment.Bottom, ColorScheme = color1
            };

            mtxts.Add(txtLabelTL); mtxts.Add(txtLabelTC); mtxts.Add(txtLabelTR);
            mtxts.Add(txtLabelML); mtxts.Add(txtLabelMC); mtxts.Add(txtLabelMR);
            mtxts.Add(txtLabelBL); mtxts.Add(txtLabelBC); mtxts.Add(txtLabelBR);

            // Save Alignments in Data
            foreach (var t in mtxts)
            {
                t.Data = new { h = t.TextAlignment, v = t.VerticalTextAlignment };
            }

            container.Add(txtLabelTL);
            container.Add(txtLabelTC);
            container.Add(txtLabelTR);

            container.Add(txtLabelML);
            container.Add(txtLabelMC);
            container.Add(txtLabelMR);

            container.Add(txtLabelBL);
            container.Add(txtLabelBC);
            container.Add(txtLabelBR);

            Win.Add(container);


            // Edit Text

            var editText = new TextView()
            {
                X           = 1,
                Y           = Pos.Bottom(container) + 1,
                Width       = Dim.Fill(10),
                Height      = Dim.Fill(1),
                ColorScheme = color2,
                Text        = txt
            };

            editText.MouseClick += (m) => {
                foreach (var v in txts)
                {
                    v.Text = editText.Text;
                }
                foreach (var v in mtxts)
                {
                    v.Text = editText.Text;
                }
            };

            Win.KeyUp += (m) => {
                foreach (var v in txts)
                {
                    v.Text = editText.Text;
                }
                foreach (var v in mtxts)
                {
                    v.Text = editText.Text;
                }
            };

            editText.SetFocus();

            Win.Add(editText);


            // JUSTIFY CHECKBOX

            var justifyCheckbox = new CheckBox("Justify")
            {
                X      = Pos.Right(container) + 1,
                Y      = Pos.Y(container) + 1,
                Width  = Dim.Fill(10),
                Height = 1
            };

            justifyCheckbox.Toggled += (prevtoggled) => {
                if (prevtoggled)
                {
                    foreach (var t in mtxts)
                    {
                        t.TextAlignment         = (TextAlignment)((dynamic)t.Data).h;
                        t.VerticalTextAlignment = (VerticalTextAlignment)((dynamic)t.Data).v;
                    }
                }
                else
                {
                    foreach (var t in mtxts)
                    {
                        if (TextFormatter.IsVerticalDirection(t.TextDirection))
                        {
                            t.VerticalTextAlignment = VerticalTextAlignment.Justified;
                            t.TextAlignment         = ((dynamic)t.Data).h;
                        }
                        else
                        {
                            t.TextAlignment         = TextAlignment.Justified;
                            t.VerticalTextAlignment = ((dynamic)t.Data).v;
                        }
                    }
                }
            };

            Win.Add(justifyCheckbox);


            // Direction Options

            var directionsEnum = Enum.GetValues(typeof(Terminal.Gui.TextDirection)).Cast <Terminal.Gui.TextDirection> ().ToList();

            var directionOptions = new RadioGroup(directionsEnum.Select(e => NStack.ustring.Make(e.ToString())).ToArray())
            {
                X               = Pos.Right(container) + 1,
                Y               = Pos.Bottom(justifyCheckbox) + 1,
                Width           = Dim.Fill(10),
                Height          = Dim.Fill(1),
                HotKeySpecifier = '\xffff'
            };

            directionOptions.SelectedItemChanged += (ev) => {
                foreach (var v in mtxts)
                {
                    v.TextDirection = (TextDirection)ev.SelectedItem;
                }
            };

            Win.Add(directionOptions);
        }
Example #22
0
        void Build(SourcePackage upk)
        {
            // Avoid multiple visits
            upk.Flags &= ~SourcePackageFlags.Project;

            try
            {
                var cacheDir = Path.Combine(upk.CacheDirectory, "ux" + Version);
                var listFile = Path.Combine(cacheDir, upk.Name + ".g");

                if (!IsDirty(upk, listFile))
                {
                    foreach (var line in File.ReadAllText(listFile).Split('\n'))
                    {
                        if (line.Length > 0)
                        {
                            upk.SourceFiles.Add(line.Trim());
                        }
                    }
                    return;
                }

                var unoFiles       = new List <string>();
                var generatedPath  = Path.Combine(cacheDir, upk.Name + ".unoproj.g.uno");
                var compiler       = CompilerReflection.ILCache.Create(Log, upk);
                var markupLog      = new CompilerReflection.MarkupErrorLog(Log, upk);
                var sourceFilePath = generatedPath.ToRelativePath(upk.SourceDirectory).NativeToUnix();
                var uxSrc          = upk.UXFiles.Select(x => new UXIL.Compiler.UXSource(Path.Combine(upk.SourceDirectory, x.NativePath)));
                var doc            = UXIL.Compiler.Compile(new Reflection.CompilerDataTypeProvider(compiler), uxSrc, upk.SourceDirectory, upk.Name, generatedPath, markupLog);

                if (Log.HasErrors)
                {
                    return;
                }

                Disk.CreateDirectory(cacheDir);
                if (doc == null)
                {
                    File.WriteAllText(listFile, "");
                    return;
                }

                var garbage = new List <IDisposable>();
                using (var sw = Disk.CreateText(generatedPath))
                {
                    using (var cw = new TextFormatter(sw))
                    {
                        CodeGenerator.GenerateCode(doc, cw, markupLog, className => {
                            var gp  = Path.Combine(cacheDir, className + ".g.uno");
                            var ret = new TextFormatter(Disk.CreateText(gp));
                            unoFiles.Add(gp.ToRelativePath(upk.SourceDirectory).NativeToUnix());
                            garbage.Add(ret);
                            return(ret);
                        });
                    }
                }

                foreach (var g in garbage)
                {
                    g.Dispose();
                }

                unoFiles.Add(sourceFilePath);
                File.WriteAllText(listFile, string.Join("\n", unoFiles));

                foreach (var f in unoFiles)
                {
                    upk.SourceFiles.Add(new FileItem(f));
                }
            }
            catch (Exception e)
            {
                Log.Error(upk.Source, null, e.Message);
            }
        }
 static LogEntry()
 {
     isFullyTrusted    = typeof(LogEntry).Assembly.IsFullyTrusted;
     toStringFormatter = new TextFormatter();
 }
Example #24
0
        //-------------------------------------------------------------------
        //
        //  Internal Methods
        //
        //-------------------------------------------------------------------

        #region Internal Methods

        /// <summary>
        /// Create and format text line.
        /// </summary>
        /// <param name="dcp">First character position for the line.</param>
        /// <param name="formatWidth">Width to pass to LS formatter.</param>
        /// <param name="paragraphWidth">Line wrapping width.</param>
        /// <param name="lineProperties">Line's properties.</param>
        /// <param name="textRunCache">Run cache.</param>
        /// <param name="formatter">Text formatter.</param>
        /// <remarks>
        /// formatWidth/paragraphWidth is an attempt to work around bug 114719.
        /// Unfortunately, Line Services cannot guarantee that once a line
        /// has been measured, measuring the same content with the actual line
        /// width will produce the same line.
        ///
        /// For example, suppose we format dcp 0 with paragraphWidth = 100.
        /// Suppose this results in a line from dcp 0 - 10, with width = 95.
        ///
        /// We would expect that a call to FormatLine with dcp = 0,
        /// paragraphWidth = 95 would result in the same 10 char line.
        /// But in practice it might return a 9 char line.
        ///
        /// The workaround is to pass in an explicit formatting width across
        /// multiple calls, even if the paragraphWidth changes.
        /// </remarks>
        internal void Format(int dcp, double formatWidth, double paragraphWidth, LineProperties lineProperties, TextRunCache textRunCache, TextFormatter formatter)
        {
            _lineProperties = lineProperties;
            _dcp            = dcp;
            _paragraphWidth = paragraphWidth;

            // We must ignore TextAlignment here since formatWidth does not
            // necessarilly equal paragraphWidth.  We'll adjust on later calls.
            lineProperties.IgnoreTextAlignment = (lineProperties.TextAlignment != TextAlignment.Justify);
            try
            {
                _line = formatter.FormatLine(this, dcp, formatWidth, lineProperties, null, textRunCache);
            }
            finally
            {
                lineProperties.IgnoreTextAlignment = false;
            }
        }
        public void TextFromatterWithEmptyTemplateUsesDefaultTemplate()
        {
            TextFormatter formatter = new TextFormatter("");

            LogEntry entry = CommonUtil.GetDefaultLogEntry();
            entry.Title = Guid.NewGuid().ToString();
            entry.AppDomainName = Guid.NewGuid().ToString();
            entry.MachineName = Guid.NewGuid().ToString();
            entry.ManagedThreadName = Guid.NewGuid().ToString();
            entry.Message = Guid.NewGuid().ToString();
            string category = Guid.NewGuid().ToString();
            entry.Categories = new string[] { category };
            entry.ProcessName = Guid.NewGuid().ToString();

            string formattedMessage = formatter.Format(entry);

            Assert.IsTrue(formattedMessage.IndexOf(AppDomain.CurrentDomain.FriendlyName) != -1);
            Assert.IsTrue(formattedMessage.IndexOf(entry.Title) != -1);
            Assert.IsTrue(formattedMessage.IndexOf(Environment.MachineName) != -1);
            Assert.IsTrue(formattedMessage.IndexOf(entry.ManagedThreadName) != -1);
            Assert.IsTrue(formattedMessage.IndexOf(entry.Message) != -1);
            Assert.IsTrue(formattedMessage.IndexOf(entry.Title) != -1);
            Assert.IsTrue(formattedMessage.IndexOf(category) != -1);
            Assert.IsTrue(formattedMessage.IndexOf(LogEntry.GetProcessName()) != -1);
        }
        public void FormatsLocalProcessNameToken()
        {
            var formatter = new TextFormatter("Process name: {localProcessName}");
            var entry = CommonUtil.GetDefaultLogEntry();
            entry.ProcessName = "__some process__";

            var actual = formatter.Format(entry);

            Assert.AreEqual("Process name: " + LogEntry.GetProcessName(), actual);
        }
        public void TimeStampTokenLocalTimeWithFormat()
        {
            CustomLogEntry entry = new CustomLogEntry();
            entry.TimeStamp = DateTime.MaxValue;
            ILogFormatter formatter = new TextFormatter("TimeStamp: {timestamp(local:F)}");
            string actual = formatter.Format(entry);

            string expected = string.Concat("TimeStamp: " + DateTime.MaxValue.ToLocalTime().ToString("F", CultureInfo.CurrentCulture));
            Assert.AreEqual(expected, actual);
        }
        public void FormatsThreadIdToken()
        {
            TextFormatter formatter = new TextFormatter("Thread id: {win32ThreadId}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Thread id: " + entry.Win32ThreadId, actual);
        }
Example #29
0
        public void LimitWithElipses_WhenUnderLimit_NotLimited(string input, int characterCount, string expected)
        {
            var result = TextFormatter.LimitWithElipses(input, characterCount);

            Assert.Equal(expected, result);
        }
        //above; this is mostly for the purposes of when the player is initiating fights with the intern
        //basically it's like a mock parts[] array in BasicCommandParser.cs
        //this array will be used in the place of parts[] as the parameters for the ProcessFightCommand method

        public void Talk(string word)
        {
            switch (talkBranch)
            {
            case 0:
                TextFormatter.PrintLinePositive("You: Hi intern guy!");
                TextFormatter.PrintLineWarning("Intern: Hello! You need anything? :D");
                //below line introduces the player to how to use the talk command -> "talk [one of the offered choices]"
                TextFormatter.PrintLineSpecial("'talk ____'");
                //below line (along with all similar lines) is structured to give the player multiple choices to talk about
                //it's not the same set of words each time because we want some ~variety~ to the player's conversation
                TextFormatter.PrintLineSpecial("[JOKE] [THREAT] [CHITCHAT] [QUESTION] [GOODBYE]");
                convoIntern = true;
                talkBranch  = 1;
                break;

            case 0.5:
                //this case, 0.5, is specifically created to serve the purpose of talking to the intern again
                //while at the same time (most importantly), making it seem like you're really talking to the intern AGAIN
                TextFormatter.PrintLinePositive("You: Hi, again, intern guy.");
                TextFormatter.PrintLineWarning("Intern: Hello! Suprised to see you again so quick, you still need anything?");
                TextFormatter.PrintLineSpecial("'talk ____'");
                TextFormatter.PrintLineSpecial("[JOKE] [THREAT] [CHITCHAT] [QUESTION] [GOODBYE]");
                convoIntern = true;
                talkBranch  = 1;
                break;

            case 1:
                switch (word)
                {
                case "joke":
                    TextFormatter.PrintLinePositive("You: What did the clock do when it was hungry?");
                    TextFormatter.PrintLineWarning("Intern: Went back for seconds.");
                    TextFormatter.PrintLineSpecial("[REPRIMAND] [JOKE] [LAUGH] [GOODBYE]");
                    talkBranch = 2;
                    break;

                case "threat":
                    TextFormatter.PrintLinePositive("You: FIGHT ME OR ELSE!!!");
                    TextFormatter.PrintLineWarning("Intern: or else... what? It sounds like you're just going to fight me either way...");
                    TextFormatter.PrintLineSpecial("[APOLOGIZE] [TAUNT] [THREAT] [GOODBYE]");
                    talkBranch = 3;
                    break;

                case "chitchat":
                    TextFormatter.PrintLinePositive("You: Nope, don't need anything, thanks. How's life going?");
                    TextFormatter.PrintLineWarning("Intern: Stuff's going good! Loving this job so far!");
                    TextFormatter.PrintLineSpecial("[AWKWARD] [GOODBYE]");
                    talkBranch = 4;
                    break;

                case "question":
                    TextFormatter.PrintLinePositive("You: What do you exactly do here, again? ");
                    TextFormatter.PrintLineWarning("Intern: Uh...I'm your lab assistant. You tell me to do stuff. Also, by the way, the tub of Purell you asked for is ready in the storage room. Let me know if you need any help with it.");
                    TextFormatter.PrintLineSpecial("[PURELL] [LIFE] [QUEST] [GOODBYE]");
                    talkBranch = 5;
                    break;

                case "goodbye":
                    TextFormatter.PrintLinePositive("You: GOODBYE!");
                    TextFormatter.PrintLineWarning("Intern: uh, ok... bye...");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                default:
                    TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                    //this is most normal way to say: don't try using anything besides the many multiple choices offered to you
                    break;
                }
                break;

            //result of "joke"
            case 2:
                switch (word)
                {
                case "reprimand":
                    TextFormatter.PrintLinePositive("You: LISTEN YOUNG'UN, YOU SHOULD KNOW BETTER THAN TO SPOIL THE PUNCHLINE OF A GOOD OL' JOKE!");
                    TextFormatter.PrintLineWarning("Intern: Okay, then I'll tell you a joke. Why aren't koalas considered as bears?");
                    TextFormatter.PrintLineSpecial("[WHY] [SCIENTIFIC] [PUNCHLINE] [PUNCH] [LAUGH] [GOODBYE]");
                    talkBranch = 6;
                    break;

                case "joke":
                    TextFormatter.PrintLinePositive("You: Here's another one for ya then: why did the bike fall dow-");
                    TextFormatter.PrintLineWarning("Intern: because it was two-tired.");
                    TextFormatter.PrintLineSpecial("[CRY] [SCREAM] [LAUGH] [GOODBYE]");
                    talkBranch = 7;
                    break;

                case "laugh":
                    TextFormatter.PrintLinePositive("You: AHAHAHAHAHHAAHAHA!!!");
                    TextFormatter.PrintLineWarning("Intern: Are you really laughing at your own joke?");
                    TextFormatter.PrintLineSpecial("[CONFRONT] [LAUGH] [GOODBYE]");
                    talkBranch = 8;
                    break;

                case "goodbye":
                    TextFormatter.PrintLinePositive("You: Hmmph! GOODBYE THEN.");
                    TextFormatter.PrintLineWarning("Intern: Bye! :D");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                default:
                    TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                    break;
                }
                break;

            case 3:
                switch (word)
                {
                case "apologize":
                    TextFormatter.PrintLinePositive("You: i'm sorry...you're right...that was weird and dumb of me...violence is never okay...T-T");
                    TextFormatter.PrintLineWarning("Intern: Haha, it's all good, boss. I'm always here if you need someone to talk to :3");
                    TextFormatter.PrintLineSpecial("[PURELL] [LIFE] [QUEST] [GOODBYE]");
                    talkBranch = 0.5;
                    break;

                case "taunt":
                    TextFormatter.PrintLinePositive("You: YOU SCARED?");
                    TextFormatter.PrintLineWarning("Intern: nope. just confused why you're suddenly trying to fight people now...");
                    TextFormatter.PrintLineSpecial("You: HYAAA! TAKE THAT!");
                    TheGame.ProcessFightCommand(internArray);
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "threat":
                    TextFormatter.PrintLinePositive("You: YEAH. MAYBE I AM GOING TO FIGHT YOU EITHER WAY. YOU SHOULD BE SCARED RIGHT NOW, KID. >:(");
                    TextFormatter.PrintLineWarning("Intern: I'M NOT SCARED. LET'S FIGHT.");
                    TextFormatter.PrintLinePositive("You: TAKE THAT THEN! SUPRISE ATTACK!");
                    TheGame.ProcessFightCommand(internArray);
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "goodbye":
                    TextFormatter.PrintLinePositive("You: ...goodbye...");
                    TextFormatter.PrintLineWarning("Intern: ...");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                default:
                    TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                    break;
                }
                break;

            case 4:
                switch (word)
                {
                case "awkward":
                    TextFormatter.PrintLinePositive("You:...uh, I'm not great at casual chitchat so I think it's best we make a mutual agreement to end the conversation and for me to just shuffle away. Good with you?");
                    TextFormatter.PrintLineWarning("Intern: yeah...this is awkward...see ya boss.");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "goodbye":
                    TextFormatter.PrintLinePositive("You: goodbye. :|");
                    TextFormatter.PrintLineWarning("Intern: goodbye. :|");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                default:
                    TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                    break;
                }
                break;

            case 5:
                switch (word)
                {
                case "purell":
                    TextFormatter.PrintLinePositive("You: Where's the tub of Purell, again?");
                    TextFormatter.PrintLineWarning("Intern: Just in the backroom! To the south of us! Also, if you were thinking about bathing in it... do not bathe in it.");
                    TextFormatter.PrintLinePositive("You: Wh-");
                    TextFormatter.PrintWarning("Intern: Just... don't. I still get shivers down my spine when I think about it. It's not as nice as you think.");
                    TextFormatter.PrintLinePositive("You: Okay...bye then...thanks for your...advice... 0____________0");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "life":
                    TextFormatter.PrintLinePositive("You: What's the meaning of life?");
                    TextFormatter.PrintLineWarning("Intern: To wash your hands constantly. 20 seconds! Don't forget! ;)");
                    TextFormatter.PrintLinePositive("You: Okay never mind...you're hopeless. Bye intern guy.");
                    TextFormatter.PrintWarning("Intern: Byeeee :P");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "quest":
                    TextFormatter.PrintLinePositive("You: Hey...intern guy?");
                    TextFormatter.PrintLineWarning("Intern: Yeah...?");
                    TextFormatter.PrintLinePositive("You: I dunno... I guess I'm just nervous about this whole QUEST thing. I don't have any CLUE what I'm supposed to do. I don't even know if I'm going to see this lab again...");
                    TextFormatter.PrintWarning("Intern: Aw boss, it's going to be okay. That's for sure. Let your ANGER TOWARDS BIG 'RONA FUEL YOUR DECISION MAKING. Also, you know Bertha is upstairs, right? I've been visiting her a lot lately. She's a really good listener!");
                    TextFormatter.PrintLinePositive("You: Thanks, intern guy. I feel a lot better now. I hope I'll see you again...someday...");
                    TextFormatter.PrintWarning("Hope to see you again, too!");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "goodbye":
                    TextFormatter.PrintLinePositive("You: Cool! See you then!");
                    TextFormatter.PrintLineWarning("Intern: *mumble* *mumble* (took me 10 hours and 500 bottles of mini Purell. MINI BOTTLES. BECAUSE THAT'S THE ONLY KIND WE HAD AT THE LAB. But do I get a 'thank you'? or even a 'bye FRIEND'?... no i do not. >:( )");
                    TextFormatter.PrintLineWarning("Intern:...see you...boss friend... T-T");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                default:
                    TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                    break;
                }
                break;

            case 6:
                switch (word)
                {
                case "why":
                    TextFormatter.PrintLinePositive("You: Why.");
                    TextFormatter.PrintLineWarning("Intern: Because they don't KOALA-fy!");
                    TextFormatter.PrintLinePositive("You: ...goodbye.");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "scientific":
                    TextFormatter.PrintLinePositive("You: ACTUALLY, koala's aren't bears at all. They are marsupials.");
                    TextFormatter.PrintLineWarning("Intern: ...that was way worse than saying the actual punchline of the joke.");
                    TextFormatter.PrintLinePositive("You: I know. Goodbye intern man.");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "punchline":
                    TextFormatter.PrintLinePositive("You: Because they don't KOALA-fy!!");
                    TextFormatter.PrintLineWarning("Intern: ...that was mean and hurtful...goodbye.");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "punch":
                    TextFormatter.PrintLinePositive("You: TAKE THIS!");
                    TextFormatter.PrintLineWarning("Intern: wha-");
                    TheGame.ProcessFightCommand(internArray);
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "laugh":
                    TextFormatter.PrintLinePositive("You: HAHAHAHAHAHA!");
                    TextFormatter.PrintLineWarning("Intern: Okay, there's no punchline yet...this is weird...goodbye...?");
                    TextFormatter.PrintLinePositive("You: hehehehe.");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "goodbye":
                    TextFormatter.PrintLinePositive("No, I'm leaving. This is a toxic relationship and a dangerous environment. Goodbye.");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                default:
                    TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                    break;
                }
                break;

            case 7:
                switch (word)
                {
                case "cry":
                    TextFormatter.PrintLinePositive("You: *crying uncontrollably* T-T");
                    TextFormatter.PrintLineWarning("Intern: Aw it's going to be okay, boss :3 *pats you on back*");
                    TextFormatter.PrintLinePositive("You: *staggers away, still sobbing*");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "scream":
                    TextFormatter.PrintLinePositive("You: AHHHHHHHHHHHHHHH!");
                    TextFormatter.PrintLineWarning("Intern: O___o goodbye then...");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "laugh":
                    TextFormatter.PrintLinePositive("You: hahahahaha...*walks away w/o saying goodbye*");
                    TextFormatter.PrintLineWarning("Intern: *staring from a distance* why is boss still laughing? weird....");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "goodbye":
                    TextFormatter.PrintLinePositive("You: GOODBYE. >:O");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                default:
                    TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                    break;
                }
                break;

            case 8:
                switch (word)
                {
                case "confront":
                    TextFormatter.PrintLinePositive("You: YES I AM AND I'M NOT ASHAMED OF IT. GOODBYE.");
                    TextFormatter.PrintLineWarning("Intern: Whatever you say, boss!");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "laugh":
                    TextFormatter.PrintLinePositive("You: AHAHHAHAHAHAHAHA.");
                    TextFormatter.PrintLineWarning("Intern: You're scaring me. Bye! *ducks and covers under his desk*");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                case "goodbye":
                    TextFormatter.PrintLinePositive("You: heh...bye intern boy...");
                    TextFormatter.PrintLineWarning("Intern: bye boss boy...");
                    convoIntern = false;
                    talkBranch  = 0.5;
                    break;

                default:
                    TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                    break;
                }
                break;

            default:
                TextFormatter.PrintLineWarning("You're all for free speech, but you think it's for the best if you just stick to regular conversation stuff.");
                convoIntern = false;
                talkBranch  = 0.5;
                break;
            }
        }
Example #31
0
        TypeConversion GetDelegateConversion(Source src, DelegateType dt)
        {
            var paramConversions = dt.Parameters.Select(GetParamConversion).ToArray();
            var returnConversion = GetConversion(src, dt.ReturnType);
            var compiledType     = Helpers.CompiledType(dt);

            var foreignType = "::uObjC::Function<" +
                              returnConversion.ForeignType +
                              ((paramConversions.Length > 0) ? ", " : "") +
                              ForeignTypes(paramConversions) + ">";

            Func <string, string> fromUno = (string x) =>
            {
                var convertedArguments = paramConversions.Select((p, i) => p.ToUno(dt.Parameters[i].Name)).ToList();
                var preStatements      = convertedArguments.SelectMany(a => a.PreStatements).ToList();
                var arguments          = convertedArguments.Select((arg, i) => Helpers.StringExpr(dt.Parameters[i].Type, arg.Expression)).ToArray();
                var postStatements     = convertedArguments.SelectMany(a => a.PostStatements).ToList();

                using (var tw = new StringWriter())
                {
                    using (var ftw = new TextFormatter(tw))
                    {
                        ftw.WriteLine("[] (id<UnoObject> __delegateRef) -> " + foreignType);
                        ftw.Indent("{");
                        ftw.WriteLine("return __delegateRef == nil ? (" + foreignType + ")nil : (^ " + returnConversion.ForeignType + " " +
                                      ForeignTypeParamList(paramConversions, dt.Parameters.Select(p => p.Name).ToArray()));
                        ftw.Indent("{");
                        ftw.WriteLine("::uForeignPool __foreignPool;");
                        ftw.WriteLine(compiledType + " __unoDelegate = (" + compiledType + ")__delegateRef.unoObject;");
                        ftw.WriteLines(ReturnWithPrePostStatements(
                                           dt.ReturnType,
                                           preStatements,
                                           returnConversion.FromUno(Helpers.CallDelegate(Helpers.StringExpr(dt, "__unoDelegate"), arguments)),
                                           postStatements));
                        ftw.Unindent("});");
                        ftw.Unindent();
                        ftw.Write("} ([::StrongUnoObject strongUnoObjectWithUnoObject: " + x + "])");
                        return(tw.ToString());
                    }
                }
            };

            Func <string, string> toUno = (string x) =>
            {
                var convertedArguments = paramConversions.Select((p, i) => p.FromUno(GetDelegateArgumentString(dt.Parameters[i]))).ToList();
                var preStatements      = convertedArguments.SelectMany(a => a.PreStatements).ToList();
                var arguments          = convertedArguments.Select(a => a.Expression).ToList();
                var postStatements     = convertedArguments.SelectMany(a => a.PostStatements).ToList();

                using (var tw = new StringWriter())
                {
                    using (var ftw = new TextFormatter(tw))
                    {
                        ftw.Write("::uObjC::NewUnoDelegate(" + Helpers.TypeOf(dt) + ", ");
                        string fptrType = "::uObjC::RawFunction<void, " + Helpers.CompiledType(Essentials.Object) +
                                          ((paramConversions.Length) > 0 ? ", " : "") +
                                          string.Join(", ", paramConversions.Select(GetDelegateParameterType)) +
                                          (dt.ReturnType.IsVoid ? "" : (", " + Helpers.CompiledType(returnConversion.UnoType) + "*")) +
                                          ">";
                        ftw.Write("(void*) (" + fptrType + ") [] (");
                        ftw.Write(Helpers.CompiledType(Essentials.Object) + " __this" +
                                  ((paramConversions.Length > 0) ? ", " : "") +
                                  string.Join(", ", paramConversions.Select((p, i) => GetDelegateParameterType(p) + " " + dt.Parameters[i].Name)) +
                                  (dt.ReturnType.IsVoid ? "" : (", " + GetDelegateReturnType(returnConversion) + " __ret")));
                        ftw.Write(")");
                        ftw.EndLine();
                        ftw.Indent("{");
                        ftw.WriteLine(Helpers.CompiledType(_objCObject) + " __thisObj = (" + Helpers.CompiledType(_objCObject) + ")__this;");
                        preStatements.ForEach(ftw.WriteLine);
                        ftw.BeginLine();
                        if (!dt.ReturnType.IsVoid)
                        {
                            ftw.Write(GetDelegateReturnString(returnConversion, "__ret") + " = ");
                        }
                        ftw.Write(returnConversion.ToUno("((" + foreignType + ")" + Helpers.CallStatic(_getHandle, Helpers.StringExpr(_objCObject, "__thisObj")) +
                                                         ")(" + string.Join(", ", arguments) + ")") + ";");
                        ftw.EndLine();
                        postStatements.ForEach(ftw.WriteLine);
                        ftw.Unindent();
                        ftw.Write("}, " + Helpers.CallStatic(_newObjCObject, Helpers.StringExpr(_objCID, x)) + ")");
                        return(tw.ToString());
                    }
                }
            };

            return(TypeConversion.Boxed(
                       dt,
                       foreignType,
                       fromUno,
                       toUno));
        }
Example #32
0
        public void LimitWithElipsesOnWordBoundary_WhenNullOrEmpty_ReturnsEmptyString(string input)
        {
            var result = TextFormatter.LimitWithElipsesOnWordBoundary(input, 10);

            Assert.Equal(result, string.Empty);
        }
        private void ReportMissingCategories(List <string> missingCategories, LogEntry logEntry)
        {
            try
            {
                LogEntry reportingLogEntry = new LogEntry();
                reportingLogEntry.Severity = TraceEventType.Error;
                reportingLogEntry.Message  = string.Format(Resources.Culture, Resources.MissingCategories, TextFormatter.FormatCategoriesCollection(missingCategories), logEntry.ToString());
                reportingLogEntry.EventId  = LogWriterFailureEventID;

                structureHolder.ErrorsTraceSource.TraceData(reportingLogEntry.Severity, reportingLogEntry.EventId, reportingLogEntry);
            }
            catch (Exception ex)
            {
                instrumentationProvider.FireFailureLoggingErrorEvent(Resources.FailureWhileReportingMissingCategories, ex);
            }
        }
Example #34
0
        public void LimitWithElipsesOnWordBoundary_WhenWhitespace_ReturnsWhitespace(string input)
        {
            var result = TextFormatter.LimitWithElipsesOnWordBoundary(input, 10);

            Assert.Equal(result, input);
        }
        public void FormatsThreadNameToken()
        {
            TextFormatter formatter = new TextFormatter("Thread name: {threadName}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Thread name: " + entry.ManagedThreadName, actual);
        }
Example #36
0
        public void LimitWithElipsesOnWordBoundary_WhenOverLimit_IsLimited(string input, int characterCount, string expected)
        {
            var result = TextFormatter.LimitWithElipsesOnWordBoundary(input, characterCount);

            Assert.Equal(expected, result);
        }
        public void FormatsActivityIdToken()
        {
            TextFormatter formatter = new TextFormatter("Activity id: {activity}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Activity id: " + entry.ActivityId.ToString("D", CultureInfo.CurrentCulture), actual);
        }
Example #38
0
        public void FirstLetterToUpperCase_WhenNullOrEmpty_ReturnsEmptyString(string input)
        {
            var result = TextFormatter.FirstLetterToUpperCase(input);

            Assert.Equal(result, string.Empty);
        }
        public void FormatsCategoryToken()
        {
            TextFormatter formatter = new TextFormatter("Categories: {category}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Categories: " + TextFormatter.FormatCategoriesCollection(entry.Categories), actual);
        }
Example #40
0
        public void FirstLetterToUpperCase_WhenWhitespace_ReturnsWhitespace(string input)
        {
            var result = TextFormatter.FirstLetterToUpperCase(input);

            Assert.Equal(result, input);
        }
        public void FormatsLocalTimestampWithCustomFormat()
        {
            TextFormatter formatter = new TextFormatter("Timestamp: {timestamp(local:dd-MM-yyyy hh:mm)}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Timestamp: " + entry.TimeStamp.ToLocalTime().ToString("dd-MM-yyyy hh:mm", CultureInfo.CurrentCulture), actual);
        }
Example #42
0
        public void FirstLetterToUpperCase_CanConvert(string input, string expected)
        {
            var result = TextFormatter.FirstLetterToUpperCase(input);

            Assert.Equal(expected, result);
        }
        public void FormatsPropertyToken()
        {
            TextFormatter formatter = new TextFormatter("Reflected Property Value: {property(MyProperty)}");
            CustomLogEntry entry = new CustomLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Reflected Property Value: myPropertyValue", actual);
        }
Example #44
0
        public void RemoveDiacritics_WhenNullOrEmpty_ReturnsEmptyString(string input)
        {
            var result = TextFormatter.PascalCaseToSentence(input);

            Assert.Equal(result, string.Empty);
        }
Example #45
0
        public void RemoveDiacritics_WhenWhitespace_ReturnsWhitespace(string input)
        {
            var result = TextFormatter.PascalCaseToSentence(input);

            Assert.Equal(result, input);
        }
Example #46
0
        public void RemoveDiacritics_CanRemoveDiacritics(string input, string expected)
        {
            var result = TextFormatter.RemoveDiacritics(input);

            Assert.Equal(expected, result);
        }
        public void FormatsMessageToken()
        {
            TextFormatter formatter = new TextFormatter("Message: {message}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Message: " + entry.Message, actual);
        }
Example #48
0
        public void PascalCaseToSentence_KeepsAcronymsIntact(string input, string expected)
        {
            var result = TextFormatter.PascalCaseToSentence(input);

            Assert.Equal(expected, result);
        }
 string FormatEntry(string template,
                    LogEntry entry)
 {
     TextFormatter formatter = new TextFormatter(template);
     return formatter.Format(entry);
 }
Example #50
0
        public void Pascalize_WhenNullOrWhitespace_ReturnsEmptyString(string input)
        {
            var result = TextFormatter.Pascalize(input);

            Assert.Equal(result, string.Empty);
        }
        public void TimeStampTokenUtcTime()
        {
            CustomLogEntry entry = new CustomLogEntry();
            entry.TimeStamp = DateTime.MaxValue;

            ILogFormatter formatter = new TextFormatter("TimeStamp: {timestamp}");
            string actual = formatter.Format(entry);

            string expected = string.Concat("TimeStamp: " + DateTime.MaxValue.ToString());
            Assert.AreEqual(expected, actual);
        }
		private int WriteTypeDeclaration(ITypeDeclaration typeDeclaration, ILanguageWriterConfiguration configuration)
		{
			ILanguage language = LanguageManager.ActiveLanguage;
			ITranslator translator = TranslatorManager.CreateDisassembler("Xml", null);

			int exceptions = 0;
			using (StreamWriter streamWriter = CreateTypeDeclarationFile(typeDeclaration))
			{
				INamespace namespaceItem = new Namespace();
				namespaceItem.Name = typeDeclaration.Namespace;

				try
				{
					if (language.Translate)
					{
						typeDeclaration = translator.TranslateTypeDeclaration(typeDeclaration, true, true);
					}
					namespaceItem.Types.Add(typeDeclaration);
				}
				catch (Exception ex)
				{
					streamWriter.WriteLine(ex.ToString());
					WriteLine(ex.ToString());
					exceptions++;
				}
				
				TextFormatter formatter = new TextFormatter();
				ILanguageWriter writer = language.GetWriter(formatter, configuration);
				try
				{
					writer.WriteNamespace(namespaceItem);
				}
				catch (Exception exception)
				{
					streamWriter.WriteLine(exception.ToString());
					WriteLine(exception.ToString());
				}

				string output = formatter.ToString().Replace("\r\n", "\n").Replace("\n", "\r\n");
				streamWriter.WriteLine(output);
			}
			
			return exceptions;
		}
        public void FormatsPriorityToken()
        {
            TextFormatter formatter = new TextFormatter("Priority: {priority}");
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            string actual = formatter.Format(entry);

            Assert.AreEqual("Priority: " + entry.Priority.ToString(CultureInfo.CurrentCulture), actual);
        }
        private int WriteAssemblyInfo(IAssembly assembly, ILanguageWriterConfiguration configuration)
        {
            ILanguage language = LanguageManager.ActiveLanguage;
            ITranslator translator = TranslatorManager.CreateDisassembler("Xml", null);

            int exceptions = 0;

            using (StreamWriter streamWriter = CreateFile(string.Empty, "AssemblyInfo"))
            {
                TextFormatter formatter = new TextFormatter();
                try
                {
                    ILanguageWriter writer = language.GetWriter(formatter, configuration);
                    assembly = translator.TranslateAssembly(assembly, false);
                    writer.WriteAssembly(assembly);

                    foreach (IModule module in assembly.Modules)
                    {
                        IModule visitedModule = translator.TranslateModule(module, false);
                        writer.WriteModule(visitedModule);

                        foreach (IAssemblyReference assemblyReference in module.AssemblyReferences)
                        {
                            IAssemblyReference visitedAssemblyReference = translator.TranslateAssemblyReference(assemblyReference);
                            writer.WriteAssemblyReference(visitedAssemblyReference);
                        }

                        foreach (IModuleReference moduleReference in module.ModuleReferences)
                        {
                            IModuleReference visitedModuleReference = translator.TranslateModuleReference(moduleReference);
                            writer.WriteModuleReference(visitedModuleReference);
                        }
                    }

                    foreach (IResource resource in assembly.Resources)
                    {
                        writer.WriteResource(resource);
                    }
                }
                catch (Exception exception)
                {
                    streamWriter.WriteLine(exception.ToString());
                    WriteLine(exception.ToString());
                    exceptions++;
                }

                string output = formatter.ToString().Replace("\r\n", "\n").Replace("\n", "\r\n");
                streamWriter.WriteLine(output);
            }
            return exceptions;
        }
Example #55
0
        public void Pascalize_CanDoBasicConversion(string input, string expected)
        {
            var result = TextFormatter.Pascalize(input);

            Assert.Equal(expected, result);
        }
Example #56
0
        /// <summary>
        /// Initializes a new instance of <see cref="FileDialog"/>
        /// </summary>
        /// <param name="title">The title.</param>
        /// <param name="prompt">The prompt.</param>
        /// <param name="nameDirLabel">The name of the directory field label.</param>
        /// <param name="nameFieldLabel">The name of the file field label..</param>
        /// <param name="message">The message.</param>
        /// <param name="allowedTypes">The allowed types.</param>
        public FileDialog(ustring title, ustring prompt, ustring nameDirLabel, ustring nameFieldLabel, ustring message,
                          List <string> allowedTypes = null) : base(title)//, Driver.Cols - 20, Driver.Rows - 5, null)
        {
            this.message = new Label(message)
            {
                X = 1,
                Y = 0,
            };
            Add(this.message);
            var msgLines = TextFormatter.MaxLines(message, Driver.Cols - 20);

            this.nameDirLabel = new Label(nameDirLabel.IsEmpty ? "Directory: " : $"{nameDirLabel}: ")
            {
                X        = 1,
                Y        = 1 + msgLines,
                AutoSize = true
            };

            dirEntry = new TextField("")
            {
                X     = Pos.Right(this.nameDirLabel),
                Y     = 1 + msgLines,
                Width = Dim.Fill() - 1,
            };
            dirEntry.TextChanged += (e) => {
                DirectoryPath  = dirEntry.Text;
                nameEntry.Text = ustring.Empty;
            };
            Add(this.nameDirLabel, dirEntry);

            this.nameFieldLabel = new Label(nameFieldLabel.IsEmpty ? "File: " : $"{nameFieldLabel}: ")
            {
                X        = 1,
                Y        = 3 + msgLines,
                AutoSize = true
            };
            nameEntry = new TextField("")
            {
                X     = Pos.Left(dirEntry),
                Y     = 3 + msgLines,
                Width = Dim.Percent(70, true)
            };
            Add(this.nameFieldLabel, nameEntry);

            cmbAllowedTypes = new ComboBox()
            {
                X        = Pos.Right(nameEntry) + 2,
                Y        = Pos.Top(nameEntry),
                Width    = Dim.Fill(1),
                Height   = allowedTypes != null ? allowedTypes.Count + 1 : 1,
                Text     = allowedTypes?.Count > 0 ? allowedTypes [0] : string.Empty,
                ReadOnly = true
            };
            cmbAllowedTypes.SetSource(allowedTypes ?? new List <string> ());
            cmbAllowedTypes.OpenSelectedItem += (e) => AllowedFileTypes = cmbAllowedTypes.Text.ToString().Split(';');
            Add(cmbAllowedTypes);

            dirListView = new DirListView(this)
            {
                X      = 1,
                Y      = 3 + msgLines + 2,
                Width  = Dim.Fill() - 1,
                Height = Dim.Fill() - 2,
            };
            DirectoryPath = Path.GetFullPath(Environment.CurrentDirectory);
            Add(dirListView);

            AllowedFileTypes             = cmbAllowedTypes.Text.ToString().Split(';');
            dirListView.DirectoryChanged = (dir) => { nameEntry.Text = ustring.Empty; dirEntry.Text = dir; };
            dirListView.FileChanged      = (file) => nameEntry.Text = file == ".." ? "" : file;
            dirListView.SelectedChanged  = (file) => nameEntry.Text = file.Item1 == ".." ? "" : file.Item1;
            this.cancel          = new Button("Cancel");
            this.cancel.Clicked += () => {
                Cancel();
            };
            AddButton(cancel);

            this.prompt = new Button(prompt.IsEmpty ? "Ok" : prompt)
            {
                IsDefault = true,
                Enabled   = nameEntry.Text.IsEmpty ? false : true
            };
            this.prompt.Clicked += () => {
                if (this is OpenDialog)
                {
                    if (!dirListView.GetValidFilesName(nameEntry.Text.ToString(), out string res))
                    {
                        nameEntry.Text = res;
                        dirListView.SetNeedsDisplay();
                        return;
                    }
                    if (!dirListView.canChooseDirectories && !dirListView.ExecuteSelection(false))
                    {
                        return;
                    }
                }
                else if (this is SaveDialog)
                {
                    var name = nameEntry.Text.ToString();
                    if (FilePath.IsEmpty || name.Split(',').Length > 1)
                    {
                        return;
                    }
                    var ext = name.EndsWith(cmbAllowedTypes.Text.ToString())
                                                ? "" : cmbAllowedTypes.Text.ToString();
                    FilePath = Path.Combine(FilePath.ToString(), $"{name}{ext}");
                }
                canceled = false;
                Application.RequestStop();
            };
            AddButton(this.prompt);

            nameEntry.TextChanged += (e) => {
                if (nameEntry.Text.IsEmpty)
                {
                    this.prompt.Enabled = false;
                }
                else
                {
                    this.prompt.Enabled = true;
                }
            };

            Width  = Dim.Percent(80);
            Height = Dim.Percent(80);

            // On success, we will set this to false.
            canceled = true;

            KeyPress += (e) => {
                if (e.KeyEvent.Key == Key.Esc)
                {
                    Cancel();
                    e.Handled = true;
                }
            };
            void Cancel()
            {
                canceled = true;
                Application.RequestStop();
            }
        }
Example #57
0
        private string FormatEntry(string template, LogEntry entry)
        {
            TextFormatterData data = new TextFormatterData();
            data.Template.Value = template;

            TextFormatter formatter = new TextFormatter(data);
            return formatter.Format(entry);
        }
        public async Task <PageBlockTypeFileDetails> ExecuteAsync(GetPageBlockTypeFileDetailsByFileNameQuery query, IExecutionContext executionContext)
        {
            var viewPath = _viewLocator.GetPathByFileName(query.FileName);

            if (string.IsNullOrEmpty(viewPath))
            {
                throw new FileNotFoundException($"Page block type view file '{query.FileName}' not found.", query.FileName);
            }

            var view = await _viewFileReader.ReadViewFileAsync(viewPath);

            if (view == null)
            {
                throw new FileNotFoundException($"Page block type view file '{query.FileName}' not found at location '{viewPath}'.", viewPath);
            }

            var parsedData           = ParseViewFile(view);
            var pageTemplateFileInfo = new PageBlockTypeFileDetails();

            pageTemplateFileInfo.Name        = StringHelper.FirstNonEmpty(parsedData.Name, TextFormatter.PascalCaseToSentence(query.FileName));
            pageTemplateFileInfo.Description = parsedData.Description;
            pageTemplateFileInfo.Templates   = await MapChildTemplates(query.FileName);

            return(pageTemplateFileInfo);
        }
        private int WriteTypeDeclaration(ITypeDeclaration typeDeclaration, ILanguageWriterConfiguration configuration)
        {
            ILanguage language = LanguageManager.ActiveLanguage;
            ITranslator translator = TranslatorManager.CreateDisassembler("Xml", null);

            int exceptions = 0;
            using (StreamWriter streamWriter = CreateTypeDeclarationFile(typeDeclaration))
            {
                INamespace namespaceItem = new Namespace();
                namespaceItem.Name = typeDeclaration.Namespace;

                TextFormatter formatter = new TextFormatter();
                ILanguageWriter writer = language.GetWriter(formatter, configuration);
                try
                {
                    if (language.Translate)
                    {
                        typeDeclaration = translator.TranslateTypeDeclaration(typeDeclaration, true, true);
                    }
                    namespaceItem.Types.Add(typeDeclaration);

                    #region 2010-11-11 lhm  字段, 方法加入完整的命名空间
                    string strnamespace;
                    string strname;
                    string strfield;
                    foreach (IFieldDeclaration fieldDeclaration in typeDeclaration.Fields)
                    {
                        IFieldDeclaration fieldDeclaration2 = translator.TranslateFieldDeclaration(fieldDeclaration);
                        //(((Reflector.CodeModel.Memory.ArrayCreateExpression))((fieldDeclaration).Initializer)).Type
                        if ((fieldDeclaration).Initializer is Reflector.CodeModel.Memory.ArrayCreateExpression) //字段为数组类型并且初始化了值
                        {
                            strnamespace = ((((Reflector.CodeModel.Memory.ArrayCreateExpression)fieldDeclaration.Initializer).Type as Reflector.CodeModel.IType) as ITypeReference).Namespace;
                            strname = ((((Reflector.CodeModel.Memory.ArrayCreateExpression)fieldDeclaration.Initializer).Type as Reflector.CodeModel.IType) as ITypeReference).Name;
                        }
                        else if (((Reflector.CodeModel.Memory.FieldDeclaration)(fieldDeclaration)).FieldType is Reflector.CodeModel.IArrayType)//字段为数组类型无初始化值
                        {
                            strnamespace = ((((Reflector.CodeModel.IArrayType)((((Reflector.CodeModel.Memory.FieldDeclaration)(fieldDeclaration)).FieldType)))).ElementType as ITypeReference).Namespace;
                            strname = ((((Reflector.CodeModel.IArrayType)((((Reflector.CodeModel.Memory.FieldDeclaration)(fieldDeclaration)).FieldType)))).ElementType as ITypeReference).Name;
                        }
                        else
                        {
                            strnamespace = ((((Reflector.CodeModel.Memory.FieldDeclaration)(fieldDeclaration2)).FieldType as Reflector.CodeModel.IType) as ITypeReference).Namespace;
                            strname = ((((Reflector.CodeModel.Memory.FieldDeclaration)(fieldDeclaration2)).FieldType as Reflector.CodeModel.IType) as ITypeReference).Name;
                        }
                        strfield = fieldDeclaration2.Name;
                        streamWriter.WriteLine(string.Format("//#hmstart-{0}.{1} {2}#hmend", strnamespace, strname, strfield));
                    }

                    streamWriter.WriteLine(("//Type: " + typeDeclaration.Namespace + "." + typeDeclaration.Name));

                    foreach (IMethodDeclaration methodDeclaration in typeDeclaration.Methods)
                    {
                        streamWriter.WriteLine(("//Method: " + methodDeclaration));

                        int icount = ((Reflector.CodeModel.Memory.MethodDeclaration)(methodDeclaration)).Parameters.Count;
                        if (icount ==0) continue;
                        foreach (IParameterDeclaration fieldDeclaration in ((Reflector.CodeModel.Memory.MethodDeclaration)(methodDeclaration)).Parameters)
                        {
                            if (fieldDeclaration.ParameterType is Reflector.CodeModel.Memory.ArrayType)
                            {
                                strnamespace = ((((Reflector.CodeModel.Memory.ArrayType)((fieldDeclaration.ParameterType as Reflector.CodeModel.IType)))).ElementType as ITypeReference).Namespace;
                                strname = ((((Reflector.CodeModel.Memory.ArrayType)((fieldDeclaration.ParameterType as Reflector.CodeModel.IType)))).ElementType as ITypeReference).Name;

                            }
                            else if (fieldDeclaration.ParameterType is Reflector.CodeModel.Memory.ReferenceType)
                            {
                                strnamespace = ((((Reflector.CodeModel.Memory.ReferenceType)((fieldDeclaration.ParameterType as Reflector.CodeModel.IType)))).ElementType as ITypeReference).Namespace;
                                strname = ((((Reflector.CodeModel.Memory.ReferenceType)((fieldDeclaration.ParameterType as Reflector.CodeModel.IType)))).ElementType as ITypeReference).Name;
                            }
                            else
                            {
                                strnamespace = ((fieldDeclaration.ParameterType as Reflector.CodeModel.IType) as ITypeReference).Namespace;
                                strname = ((fieldDeclaration.ParameterType as Reflector.CodeModel.IType) as ITypeReference).Name;

                            }
                            strfield = fieldDeclaration.Name;
                            streamWriter.WriteLine(string.Format("//#p_hmstart-{0}.{1} {2}#p_hmend", strnamespace, strname, strfield));
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    streamWriter.WriteLine(ex.ToString());
                    WriteLine(ex.ToString());
                    exceptions++;
                }

                try
                {
                    writer.WriteNamespace(namespaceItem);
                }
                catch (Exception exception)
                {
                    streamWriter.WriteLine(exception.ToString());
                    WriteLine(exception.ToString());
                }

                string output = formatter.ToString().Replace("\r\n", "\n").Replace("\n", "\r\n");
                streamWriter.WriteLine(output);
            }

            return exceptions;
        }
Example #60
0
        string WrapBody(Function f, string body)
        {
            var paramConversions  = new List <ParamTypeConversion>();
            var paramNames        = new List <string>();
            var foreignParamNames = new List <string>();

            if (!f.IsStatic && body.Contains("_this"))
            {
                paramConversions.Add(
                    GetParamConversion(
                        new Parameter(
                            f.Source,
                            new NewObject[0],
                            ParameterModifier.This,
                            f.DeclaringType,
                            "@IL$$",
                            null)));
                paramNames.Add("@IL$$");
                foreignParamNames.Add("_this");
            }

            paramConversions.AddRange(f.Parameters.Select(GetParamConversion));
            paramNames.AddRange(f.Parameters.Select((x, i) => "@IL$" + i));
            foreignParamNames.AddRange(f.Parameters.Select(x => x.UnoName));

            var returnConversion = GetConversion(f.Source, f.ReturnType);

            var convertedArguments = paramConversions.Select((p, i) => p.FromUno(paramNames[i])).ToList();
            var preStatements      = convertedArguments.SelectMany(x => x.PreStatements).ToList();
            var arguments          = convertedArguments.Select(x => x.Expression).ToList();
            var postStatements     = convertedArguments.SelectMany(x => x.PostStatements).ToList();

            if (paramConversions.All(x => x.IsIdentity) &&
                returnConversion.IsIdentity &&
                preStatements.Count == 0 &&
                postStatements.Count == 0 &&
                f.Parameters.All(p => p.Name == p.UnoName))
            {
                return(WithObjCAutoreleasePool(body));
            }
            else
            {
                using (var tw = new StringWriter())
                {
                    using (var ftw = new TextFormatter(tw))
                    {
                        ftw.BeginLine();
                        ftw.Write("[] ");
                        ftw.Write(ForeignTypeParamList(paramConversions, foreignParamNames.ToArray()));
                        ftw.Write(" -> ");
                        ftw.Write(returnConversion.ForeignType);
                        ftw.EndLine();
                        ftw.Indent("{");
                        ftw.WriteLines(body);
                        ftw.Unindent();
                        ftw.Write("} (");
                        ftw.Write(string.Join(", ", arguments));
                        ftw.Write(")");
                        return(WithObjCAutoreleasePool(ReturnWithPrePostStatements(f.ReturnType, preStatements, returnConversion.ToUno(tw.ToString()), postStatements)));
                    }
                }
            }
        }