public AbstractIndenter(
                ISyntaxFactsService syntaxFacts,
                SyntaxTree syntaxTree,
                IEnumerable<IFormattingRule> rules,
                OptionSet optionSet,
                TextLine lineToBeIndented,
                CancellationToken cancellationToken)
            {
                var syntaxRoot = syntaxTree.GetRoot(cancellationToken);

                this._syntaxFacts = syntaxFacts;
                this.OptionSet = optionSet;
                this.Tree = syntaxTree;
                this.LineToBeIndented = lineToBeIndented;
                this.TabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, syntaxRoot.Language);
                this.CancellationToken = cancellationToken;

                this.Rules = rules;
                this.Finder = new BottomUpBaseIndentationFinder(
                         new ChainedFormattingRules(this.Rules, OptionSet),
                         this.TabSize,
                         this.OptionSet.GetOption(FormattingOptions.IndentationSize, syntaxRoot.Language),
                         tokenStream: null,
                         lastToken: default(SyntaxToken));
            }
예제 #2
0
파일: CSVSheet.cs 프로젝트: pb0/ID0_Test
    CSVSheet(string filePath, TextLine textLine)
    {
        Assert.IsTrue(textLine != null);

        this.filePath = filePath;

        using (var lines = textLine.GetEnumerator())
        {
            lines.MoveNext();
            string colNames = lines.Current;
            lines.MoveNext();
            string colTypes = lines.Current;
            this.columnInfo = new ColumnInfo(colNames, colTypes, filePath);

            List<RowData> tempList = new List<RowData>();
            while (lines.MoveNext())
            {
                string line = lines.Current;
                if (!string.IsNullOrEmpty(line))
                {
                    var tokens = line.Split(',');
                    var newRow = new RowData(tokens);
                    Assert.IsTrue(newRow.IsValidInLength(columnInfo), string.Format("tokens.Length={0}, columnInfo.Length={1} in \n{2}", tokens.Length, columnInfo.Length, line));
                    int errIndex;
                    Assert.IsTrue(newRow.IsValidInType(columnInfo, out errIndex), errIndex < 0 ? string.Empty : string.Format("Converting error: [{0}] to {1} in {2}", tokens[errIndex], columnInfo[errIndex].Value, filePath));
                    tempList.Add(newRow);
                }
            }
            rows = tempList;
        }
    }
            protected IndentationResult GetIndentationOfLine(TextLine lineToMatch, int addedSpaces)
            {
                var firstNonWhitespace = lineToMatch.GetFirstNonWhitespacePosition();
                firstNonWhitespace = firstNonWhitespace ?? lineToMatch.End;

                return GetIndentationOfPosition(firstNonWhitespace.Value, addedSpaces);
            }
예제 #4
0
        private static void DrawTextLine(Graphics grph, TextLine line)
        {
            foreach (Word word in line.Words)
                DrawWord(grph, word);

            line.Draw(grph);
        }
예제 #5
0
 protected override AbstractIndenter GetIndenter(
     ISyntaxFactsService syntaxFacts, SyntaxTree syntaxTree, TextLine lineToBeIndented, IEnumerable<IFormattingRule> formattingRules, OptionSet optionSet, CancellationToken cancellationToken)
 {
     return new Indenter(
         syntaxFacts, syntaxTree, formattingRules,
         optionSet, lineToBeIndented, cancellationToken);
 }
 void PutText(int typeId, string text)
 {
     TextLine tl = new TextLine(typeId, text);
     lines.Insert(0, tl);
     if (maxLines > 0 && lines.Count > maxLines)
         lines.RemoveRange(maxLines, lines.Count - maxLines);
 }
예제 #7
0
    public Example_04()
    {
        String fileName = "data/happy-new-year.txt";

        FileStream fos = new FileStream("Example_04.pdf", FileMode.Create);
        BufferedStream bos = new BufferedStream(fos);

        PDF pdf = new PDF(bos);
        pdf.setCompressor(Compressor.ORIGINAL_ZLIB);

        Font f1 = new Font(
                pdf,
                "AdobeMingStd-Light",       // Chinese (Traditional) font
                CodePage.UNICODE);
        Font f2 = new Font(
                pdf,
                "AdobeSongStd-Light",       // Chinese (Simplified) font
                CodePage.UNICODE);
        Font f3 = new Font(
                pdf,
                "KozMinProVI-Regular",      // Japanese font
                CodePage.UNICODE);
        Font f4 = new Font(
                pdf,
                "AdobeMyungjoStd-Medium",   // Korean font
                CodePage.UNICODE);

        Page page = new Page(pdf, Letter.PORTRAIT);

        f1.SetSize(14);
        f2.SetSize(14);
        f3.SetSize(14);
        f4.SetSize(14);

        double x_pos = 100.0;
        double y_pos = 20.0;
        StreamReader reader = new StreamReader(
                new FileStream(fileName, FileMode.Open));
        TextLine text = new TextLine(f1);
        String line = null;
        while ((line = reader.ReadLine()) != null) {
            if (line.IndexOf("Simplified") != -1) {
                text.SetFont(f2);
            } else if (line.IndexOf("Japanese") != -1) {
                text.SetFont(f3);
            } else if (line.IndexOf("Korean") != -1) {
                text.SetFont(f4);
            }
            text.SetText(line);
            text.SetPosition(x_pos, y_pos += 24);
            text.DrawOn(page);
        }
        reader.Close();

        pdf.Flush();
        bos.Close();
    }
예제 #8
0
 public TextLineInfo(string file, IImage img, TextLine line, bool orient)
 {
     Line = line;
     var firstRect = line.Chars.First();
     Coordinate = new Point(firstRect.Left, firstRect.Top);
     FileName = file;
     Size = img.Size;
     Orientation = orient;
 }
예제 #9
0
        void CheckEqualLine(TextLine first, TextLine second)
        {
            Assert.Equal(first, second);
#if false
            // We do not guarantee either identity or Equals!
            Assert.Equal(first.Extent, second.Extent);
            Assert.Equal(first.ExtentIncludingLineBreak, second.ExtentIncludingLineBreak);
#endif
        }
예제 #10
0
 protected override bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
     IEnumerable<IFormattingRule> formattingRules,
     SyntaxNode root,
     TextLine line,
     OptionSet optionSet,
     CancellationToken cancellationToken)
 {
     return ShouldUseSmartTokenFormatterInsteadOfIndenter(
         formattingRules, (CompilationUnitSyntax)root, line, optionSet, cancellationToken);
 }
예제 #11
0
        public static bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
            IEnumerable<IFormattingRule> formattingRules,
            CompilationUnitSyntax root,
            TextLine line,
            OptionSet optionSet,
            CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(formattingRules);
            Contract.ThrowIfNull(root);

            if (!optionSet.GetOption(FeatureOnOffOptions.AutoFormattingOnReturn, LanguageNames.CSharp))
            {
                return false;
            }

            if (optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) != FormattingOptions.IndentStyle.Smart)
            {
                return false;
            }

            var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition();
            if (!firstNonWhitespacePosition.HasValue)
            {
                return false;
            }

            var token = root.FindToken(firstNonWhitespacePosition.Value);
            if (token.IsKind(SyntaxKind.None) ||
                token.SpanStart != firstNonWhitespacePosition)
            {
                return false;
            }

            // first see whether there is a line operation for current token
            var previousToken = token.GetPreviousToken(includeZeroWidth: true);

            // only use smart token formatter when we have two visible tokens.
            if (previousToken.Kind() == SyntaxKind.None || previousToken.IsMissing)
            {
                return false;
            }

            var lineOperation = FormattingOperations.GetAdjustNewLinesOperation(formattingRules, previousToken, token, optionSet);
            if (lineOperation == null || lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
            {
                // no indentation operation, nothing to do for smart token formatter
                return false;
            }

            // We're pressing enter between two tokens, have the formatter figure out hte appropriate
            // indentation.
            return true;
        }
예제 #12
0
        private static bool IsBlank(TextLine line)
        {
            var text = line.ToString();

            for (int i = 0; i < text.Length; i++)
            {
                if (!SyntaxFacts.IsWhitespace(text[i]))
                {
                    return false;
                }
            }

            return true;
        }
            public ItemGetter(
                AbstractOverrideCompletionProvider overrideCompletionProvider,
                Document document, int position, CancellationToken cancellationToken)
            {
                _provider = overrideCompletionProvider;
                _document = document;
                _position = position;
                _cancellationToken = cancellationToken;

                _text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                _syntaxTree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                _startLineNumber = _text.Lines.IndexOf(position);
                _startLine = _text.Lines[_startLineNumber];
            }
예제 #14
0
		public void SplitByLines(float _width, EFonts _font, float _newLineIndent, IDrawHelper _drawHelper)
		{
			var textLines = new List<TextLine>();

			var paragraphs = Text.Split(new[] {Environment.NewLine, "\t"}, StringSplitOptions.RemoveEmptyEntries);

			var sb = new StringBuilder();
			foreach (var paragraph in paragraphs)
			{
				sb.Clear();
				var x = _newLineIndent;

				var tl = new TextLine(x, Highlights);
				textLines.Add(tl);

				var part = paragraph.Split(Punctuation);
				var processedChars = 0;
				for (var partIndex = 0; partIndex < part.Length; partIndex++)
				{
					var addStr = part[partIndex];
					processedChars += addStr.Length;
					addStr += (processedChars == 0 || processedChars >= paragraph.Length)
					          	? ""
					          	: paragraph[processedChars].ToString(CultureInfo.InvariantCulture);
					processedChars++;
					var size = _drawHelper.MeasureString(_font, addStr);

					if (size.Width > (_width - x))
					{
						tl.Text = sb.ToString();
						sb.Clear();
						x = 0;
						tl = new TextLine(x, Highlights);
						textLines.Add(tl);
					}
					sb.Append(addStr);
					x += size.Width;
				}

				if (sb.Length > 0)
				{
					tl.Text = sb.ToString();
				}
			}
			m_textLines = textLines.ToArray();
		}
예제 #15
0
    TableGenerator(string resPath, string className)
    {
        TextAsset csvFile = Resources.Load(resPath) as TextAsset;
        Assert.IsTrue(csvFile != null, "File not found: " + resPath);

        TextLine textLine = new TextLine(csvFile.text);
        Assert.IsTrue(textLine != null);

        using (var lines = textLine.GetEnumerator())
        {
            lines.MoveNext();
            string colNames = lines.Current;
            lines.MoveNext();
            string colTypes = lines.Current;
            this.columnInfo = new ColumnInfo(colNames, colTypes, resPath);
        }
        this.className = className;
    }
 private ItemGetter(
     AbstractOverrideCompletionProvider overrideCompletionProvider,
     Document document, 
     int position, 
     SourceText text,
     SyntaxTree syntaxTree,
     int startLineNumber,
     TextLine startLine,
     CancellationToken cancellationToken)
 {
     _provider = overrideCompletionProvider;
     _document = document;
     _position = position;
     _text = text;
     _syntaxTree = syntaxTree;
     _startLineNumber = startLineNumber;
     _startLine = startLine;
     _cancellationToken = cancellationToken;
 }
예제 #17
0
        public void TestBackgroundBrush1()
        {
            var textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Fatal), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.ErrorBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Error), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.ErrorBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Warning), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.WarningBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Info), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.NormalBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Debug), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.NormalBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.None), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.NormalBackgroundBrush);
        }
            public AbstractIndenter(
                SyntacticDocument document,
                IEnumerable<IFormattingRule> rules,
                OptionSet optionSet,
                TextLine lineToBeIndented,
                CancellationToken cancellationToken)
            {
                this.OptionSet = optionSet;
                this.Document = document;
                this.LineToBeIndented = lineToBeIndented;
                this.TabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, this.Document.Root.Language);
                this.CancellationToken = cancellationToken;

                this.Rules = rules;
                this.Tree = this.Document.SyntaxTree;
                this.Finder = new BottomUpBaseIndentationFinder(
                         new ChainedFormattingRules(this.Rules, OptionSet),
                         this.TabSize,
                         this.OptionSet.GetOption(FormattingOptions.IndentationSize, this.Document.Root.Language),
                         tokenStream: null,
                         lastToken: default(SyntaxToken));
            }
예제 #19
0
        public void TestBackgroundBrush3()
        {
            _selected.Add(new LogLineIndex(0));

            var textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Fatal), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.SelectedBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Error), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.SelectedBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Warning), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.SelectedBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Info), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.SelectedBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Debug), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.SelectedBackgroundBrush);

            textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.None), _hovered, _selected, true);
            textLine.BackgroundBrush.Should().Be(TextHelper.SelectedBackgroundBrush);
        }
예제 #20
0
    public Example_27()
    {
        PDF pdf = new PDF(new BufferedStream(
                              new FileStream("Example_27.pdf", FileMode.Create)));

        Page page = new Page(pdf, Letter.PORTRAIT);

        // Thai font
        Font f1 = new Font(pdf,
                           new FileStream(
                               "fonts/Noto/NotoSansThai-Regular.ttf",
                               FileMode.Open,
                               FileAccess.Read));

        f1.SetSize(14f);

        // Latin font
        Font f2 = new Font(pdf,
                           new FileStream(
                               "fonts/Droid/DroidSans.ttf",
                               FileMode.Open,
                               FileAccess.Read));

        f2.SetSize(12f);

        // Hebrew font
        Font f3 = new Font(pdf,
                           new FileStream(
                               "fonts/Noto/NotoSansHebrew-Regular.ttf",
                               FileMode.Open,
                               FileAccess.Read));

        f3.SetSize(12f);

        // Arabic font
        Font f4 = new Font(pdf,
                           new FileStream(
                               "fonts/Noto/NotoNaskhArabic-Regular.ttf",
                               FileMode.Open,
                               FileAccess.Read));

        f4.SetSize(12f);

        float x = 50f;
        float y = 50f;

        TextLine text = new TextLine(f1);

        text.SetFallbackFont(f2);
        text.SetLocation(x, y);

        StringBuilder buf = new StringBuilder();

        for (int i = 0x0E01; i < 0x0E5B; i++)
        {
            if (i % 16 == 0)
            {
                text.SetText(buf.ToString());
                text.SetLocation(x, y += 24f);
                text.DrawOn(page);
                buf = new StringBuilder();
            }
            if (i > 0x0E30 && i < 0x0E3B)
            {
                buf.Append("\u0E01");
            }
            if (i > 0x0E46 && i < 0x0E4F)
            {
                buf.Append("\u0E2D");
            }
            buf.Append((char)i);
        }

        text.SetText(buf.ToString());
        text.SetLocation(x, y += 20f);
        text.DrawOn(page);

        y += 20f;

        String str = "\u0E1C\u0E1C\u0E36\u0E49\u0E07 abc 123";

        text.SetText(str);
        text.SetLocation(x, y);
        text.DrawOn(page);

        y += 20f;

        str = "כך נראית תחתית הטבלה עם סיום הפלייאוף התחתון:";
        str = Bidi.ReorderVisually(str);
        TextLine textLine = new TextLine(f3, str);

        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str      = "10. הפועל כפר סבא 38 נקודות (הפרש שערים 14-)";
        str      = Bidi.ReorderVisually(str);
        textLine = new TextLine(f3, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str      = "11. הפועל קריית שמונה 36 נקודות (הפרש שערים 7-)";
        str      = Bidi.ReorderVisually(str);
        textLine = new TextLine(f3, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str      = "12. הפועל חיפה 34 נקודות (הפרש שערים 10-)";
        str      = Bidi.ReorderVisually(str);
        textLine = new TextLine(f3, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str      = "13. הפועל עכו 34 נקודות (הפרש שערים 21-)";
        str      = Bidi.ReorderVisually(str);
        textLine = new TextLine(f3, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        y += 40f;

        str = Bidi.ReorderVisually(
            "قالت شركة PSA بيجو ستروين الفرنسية وشريكتها الصينية شركة دونغفينغ موترز الاربعاء إنهما اتفقتا");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str = Bidi.ReorderVisually(
            "على التعاون في تطوير السيارات التي تعمل بالطاقة الكهربائية اعتبارا من عام 2019.");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str = Bidi.ReorderVisually(
            "وجاء في تصريح اصدرته في باريس الشركة الفرنسية ان الشركتين ستنتجان نموذجا كهربائيا مشتركا تستخدمه كل");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str = Bidi.ReorderVisually(
            "من بيجو وسيتروين ودونغفينغ.");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str = Bidi.ReorderVisually(
            "وقالت إن الخطة تهدف الى تحقيق عائد يزيد على 100 مليار يوان (15,4 مليار دولار) بحلول عام 2020.");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        pdf.Close();
    }
예제 #21
0
 private void OpenNext()
 {
     try
     {
         file = GetFile();
         form.OpenFile(file);
         Text = file;
         var rotate = new Random().Next(4);
         for (var i = 0; i < rotate; i++)
             form.RotateButtonClick(null, null);
         state = form.state;
         if (data[file].Count == state.Lines.Length) OpenNext();
         line = GetLine();
         if (line == null) OpenNext();
         else imageBox.Image = state.OriginalImg.Copy(line.MBR);
     }
     catch (OutOfMemoryException)
     {
         MessageBox.Show("Примеры закончились");
     }
 }
        private List <Word> GetWordsForPositionSave(TextLine line, string value, ref float conf, ref int count, int x1 = 0, int x2 = 0)
        {
            var    tmpWords = new List <Word>();
            var    tmp = new List <Word>();
            string first, sFirst = GetFirstWordOfPhrase(value);
            string last = GetLastWordOfPhrase(value);

            if (line != null)
            {
                first = GetFirstWordOfPhrase(value);
                last  = GetLastWordOfPhrase(value);
                foreach (Word wv in line.Words)
                {
                    string s = wv.Text.Trim(CONSTANTS.charsToTrimLineForpossition);
                    if (!string.IsNullOrWhiteSpace(value) && !string.IsNullOrWhiteSpace(s) && s.Contains(first))
                    {
                        tmp.Clear();
                        if (x1 != 0 && x2 != 0)
                        {
                            if ((wv.Bounds.Left > x1 && wv.Bounds.Right < x2) || (wv.Bounds.Left < x1 && wv.Bounds.Right > x1) ||
                                (wv.Bounds.Left < x2 && wv.Bounds.Right > x2) || (wv.Bounds.Left < x1 && wv.Bounds.Right > x2))
                            {
                                tmpWords.Add(wv);
                                conf += wv.Confidence;
                                count++;
                                if (first.Equals(last))
                                {
                                    break;
                                }
                                else
                                {
                                    first = GetNextWordOfPhrase(first, value);
                                }
                            }
                            continue;
                        }
                        tmpWords.Add(wv);
                        conf += wv.Confidence;
                        count++;
                        if (first.Equals(last))
                        {
                            break;
                        }
                        else
                        {
                            first = GetNextWordOfPhrase(first, value);
                        }
                    }
                    else
                    {
                        tmp.AddRange(tmpWords);
                        tmpWords.Clear();
                        first = sFirst;
                    }
                }
            }

            if (tmpWords.Count == 0)
            {
                tmpWords = tmp;
            }
            return(tmpWords);
        }
예제 #23
0
        internal override IEnumerable <Drawable> AddLine(TextLine line, bool newLineIsParagraph)
        {
            if (!newLineIsParagraph)
            {
                AddInternal(new NewLineContainer(true));
            }

            var    sprites = new List <Drawable>();
            int    index   = 0;
            string str     = line.Text;

            while (index < str.Length)
            {
                Drawable placeholderDrawable  = null;
                int      nextPlaceholderIndex = str.IndexOf('[', index);
                // make sure we skip ahead to the next [ as long as the current [ is escaped
                while (nextPlaceholderIndex != -1 && str.IndexOf("[[", nextPlaceholderIndex, StringComparison.InvariantCulture) == nextPlaceholderIndex)
                {
                    nextPlaceholderIndex = str.IndexOf('[', nextPlaceholderIndex + 2);
                }

                string strPiece = null;
                if (nextPlaceholderIndex != -1)
                {
                    int placeholderEnd = str.IndexOf(']', nextPlaceholderIndex);
                    // make sure we skip  ahead to the next ] as long as the current ] is escaped
                    while (placeholderEnd != -1 && str.IndexOf("]]", placeholderEnd, StringComparison.InvariantCulture) == placeholderEnd)
                    {
                        placeholderEnd = str.IndexOf(']', placeholderEnd + 2);
                    }

                    if (placeholderEnd != -1)
                    {
                        strPiece = str.Substring(index, nextPlaceholderIndex - index);
                        string placeholderStr  = str.Substring(nextPlaceholderIndex + 1, placeholderEnd - nextPlaceholderIndex - 1).Trim();
                        string placeholderName = placeholderStr;
                        string paramStr        = "";
                        int    parensOpen      = placeholderStr.IndexOf('(');
                        if (parensOpen != -1)
                        {
                            placeholderName = placeholderStr.Substring(0, parensOpen).Trim();
                            int parensClose = placeholderStr.IndexOf(')', parensOpen);
                            if (parensClose != -1)
                            {
                                paramStr = placeholderStr.Substring(parensOpen + 1, parensClose - parensOpen - 1).Trim();
                            }
                            else
                            {
                                throw new ArgumentException($"Missing ) in placeholder {placeholderStr}.");
                            }
                        }

                        if (int.TryParse(placeholderStr, out int placeholderIndex))
                        {
                            if (placeholderIndex >= placeholders.Count)
                            {
                                throw new ArgumentException($"This text has {placeholders.Count} placeholders. But placeholder with index {placeholderIndex} was used.");
                            }
                            if (placeholderIndex < 0)
                            {
                                throw new ArgumentException($"Negative placeholder indices are invalid. Index {placeholderIndex} was used.");
                            }

                            placeholderDrawable = placeholders[placeholderIndex];
                        }
                        else
                        {
                            object[] args;
                            if (string.IsNullOrWhiteSpace(paramStr))
                            {
                                args = Array.Empty <object>();
                            }
                            else
                            {
                                string[] argStrs = paramStr.Split(',');
                                args = new object[argStrs.Length];
                                for (int i = 0; i < argStrs.Length; ++i)
                                {
                                    if (!int.TryParse(argStrs[i], out int argVal))
                                    {
                                        throw new ArgumentException($"The argument \"{argStrs[i]}\" in placeholder {placeholderStr} is not an integer.");
                                    }

                                    args[i] = argVal;
                                }
                            }

                            if (!iconFactories.TryGetValue(placeholderName, out Delegate cb))
                            {
                                throw new ArgumentException($"There is no placeholder named {placeholderName}.");
                            }

                            placeholderDrawable = (Drawable)cb.DynamicInvoke(args);
                        }
                        index = placeholderEnd + 1;
                    }
                }

                if (strPiece == null)
                {
                    strPiece = str.Substring(index);
                    index    = str.Length;
                }
                // unescape stuff
                strPiece = strPiece.Replace("[[", "[").Replace("]]", "]");
                sprites.AddRange(AddString(new TextLine(strPiece, line.CreationParameters), newLineIsParagraph));

                if (placeholderDrawable != null)
                {
                    if (placeholderDrawable.Parent != null)
                    {
                        throw new ArgumentException("All icons used by a customizable text container must not have a parent. If you get this error message it means one of your icon factories created a drawable that was already added to another parent, or you used a drawable as a placeholder that already has another parent or you used an index-based placeholder (like [2]) more than once.");
                    }
                    AddInternal(placeholderDrawable);
                }
            }

            return(sprites);
        }
예제 #24
0
        internal /*for testing*/ IEnumerable <IssueLocation> GetPreciseIssueLocations(TextLine line)
        {
            var lineText = line.ToString();

            var match = Regex.Match(lineText, PRECISE_ISSUE_LOCATION_PATTERN);

            if (match.Success)
            {
                return(CreateIssueLocations(match, line.LineNumber));
            }

            var patternWithoutLineStart = PRECISE_ISSUE_LOCATION_PATTERN.Substring(1);

            if (Regex.IsMatch(lineText, patternWithoutLineStart))
            {
                Execute.Assertion.FailWith($"Line matches expected location pattern, but doesn't start at the beginning of the line. Line: {line.LineNumber}");
            }

            return(Enumerable.Empty <IssueLocation>());
        }
예제 #25
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            Rect rect = new Rect(0.0, 0.0, base.ActualWidth, base.ActualHeight);
            JapaneseTextSource source = new JapaneseTextSource();

            source.Text = this.Text;
            JapaneseTextParagraphProperties textParagraphProperties = this.MakeTextProperties();

            source.JapaneseTextRunProperties = (JapaneseTextRunProperties)textParagraphProperties.DefaultTextRunProperties;
            source.IsVarticalWriting         = textParagraphProperties.IsVerticalWriting;
            if (textParagraphProperties.DefaultTextRunProperties.BackgroundBrush != null)
            {
                drawingContext.DrawRectangle(textParagraphProperties.DefaultTextRunProperties.BackgroundBrush, null, rect);
            }
            Rect   paddingRect = new Rect(this.Padding.Left, this.Padding.Top, Math.Max(0.0, base.ActualWidth - this.Padding.Left - this.Padding.Right), Math.Max(0.0, base.ActualHeight - this.Padding.Top - this.Padding.Bottom));
            Point  center      = new Point((paddingRect.Left + paddingRect.Right) / 2.0, (paddingRect.Top + paddingRect.Bottom) / 2.0);
            Point  startPosition;
            double paragraphWidth;

            if (textParagraphProperties.IsVerticalWriting)
            {
                Point     origin      = paddingRect.TopRight;
                Transform transOrigin = new RotateTransform(-90.0, center.X, center.Y);
                startPosition  = transOrigin.Transform(origin);
                paragraphWidth = Math.Abs(paddingRect.Height);
                Transform trans = new RotateTransform(90.0, center.X, center.Y);
                drawingContext.PushTransform(trans);
            }
            else
            {
                startPosition  = paddingRect.TopLeft;
                paragraphWidth = Math.Abs(paddingRect.Width);
            }
            startPosition.Y += textParagraphProperties.JapaneseTextRunProperties.FontRenderingEmSize;
            int           textStorePosition = 0;
            Point         linePosition      = startPosition;
            TextFormatter formatter         = TextFormatter.Create();

            while (textStorePosition < source.Text.Length)
            {
                using (TextLine textLine = formatter.FormatLine(source, textStorePosition, paragraphWidth, textParagraphProperties, null))
                {
                    foreach (IndexedGlyphRun indexedrun in textLine.GetIndexedGlyphRuns())
                    {
                        if (textParagraphProperties.IsVerticalWriting)
                        {
                            source.UniscribeIndexedGlyphRun(indexedrun);
                            Rect runRect;
                            if (source.GlyphCount != 0 && source.Glyphs[0] != 0)
                            {
                                Point ansiLinePosition = linePosition;
                                ansiLinePosition.Y -= textParagraphProperties.JapaneseTextRunProperties.FontRenderingEmSize / 2.0;
                                runRect             = this.DrawIndexedGlyphRun(drawingContext, indexedrun, ansiLinePosition, source, true);
                            }
                            else
                            {
                                Point ansiLinePosition = linePosition;
                                ansiLinePosition.Y -= textParagraphProperties.JapaneseTextRunProperties.FontRenderingEmSize / 10.0;
                                runRect             = this.DrawIndexedGlyphRun(drawingContext, indexedrun, ansiLinePosition, source, false);
                            }
                            linePosition.X += runRect.Width;
                        }
                        else
                        {
                            Rect runRect = this.DrawIndexedGlyphRun(drawingContext, indexedrun, linePosition, source, false);
                            linePosition.X += runRect.Width;
                        }
                    }
                    textStorePosition += textLine.Length;
                    linePosition.X     = startPosition.X;
                    linePosition.Y    += textLine.Height;
                }
            }
            if (textParagraphProperties.IsVerticalWriting)
            {
                drawingContext.Pop();
            }
        }
예제 #26
0
        private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
        {
            // moving up/down happens using the desired visual X position
            if (double.IsNaN(xPos))
            {
                xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
            }
            // now find the TextLine+VisualLine where the caret will end up in
            VisualLine targetVisualLine = visualLine;
            TextLine   targetLine;
            int        textLineIndex = visualLine.TextLines.IndexOf(textLine);

            switch (direction)
            {
            case CaretMovementType.LineUp:
            {
                // Move up: move to the previous TextLine in the same visual line
                // or move to the last TextLine of the previous visual line
                int prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
                if (textLineIndex > 0)
                {
                    targetLine = visualLine.TextLines[textLineIndex - 1];
                }
                else if (prevLineNumber >= 1)
                {
                    DocumentLine prevLine = textView.Document.GetLineByNumber(prevLineNumber);
                    targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
                    targetLine       = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
                }
                else
                {
                    targetLine = null;
                }
                break;
            }

            case CaretMovementType.LineDown:
            {
                // Move down: move to the next TextLine in the same visual line
                // or move to the first TextLine of the next visual line
                int nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
                if (textLineIndex < visualLine.TextLines.Count - 1)
                {
                    targetLine = visualLine.TextLines[textLineIndex + 1];
                }
                else if (nextLineNumber <= textView.Document.LineCount)
                {
                    DocumentLine nextLine = textView.Document.GetLineByNumber(nextLineNumber);
                    targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
                    targetLine       = targetVisualLine.TextLines[0];
                }
                else
                {
                    targetLine = null;
                }
                break;
            }

            case CaretMovementType.PageUp:
            case CaretMovementType.PageDown:
            {
                // Page up/down: find the target line using its visual position
                double yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
                if (direction == CaretMovementType.PageUp)
                {
                    yPos -= textView.RenderSize.Height;
                }
                else
                {
                    yPos += textView.RenderSize.Height;
                }
                DocumentLine newLine = textView.GetDocumentLineByVisualTop(yPos);
                targetVisualLine = textView.GetOrConstructVisualLine(newLine);
                targetLine       = targetVisualLine.GetTextLineByVisualYPosition(yPos);
                break;
            }

            default:
                throw new NotSupportedException(direction.ToString());
            }
            if (targetLine != null)
            {
                double yPos            = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
                int    newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);

                // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
                int targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
                if (newVisualColumn >= targetLineStartCol + targetLine.Length)
                {
                    if (newVisualColumn <= targetVisualLine.VisualLength)
                    {
                        newVisualColumn = targetLineStartCol + targetLine.Length - 1;
                    }
                }
                return(targetVisualLine.GetTextViewPosition(newVisualColumn));
            }
            else
            {
                return(caretPosition);
            }
        }
예제 #27
0
        private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
        {
            int newVC            = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
            TextViewPosition pos = visualLine.GetTextViewPosition(newVC);

            pos.IsAtEndOfLine = true;
            return(pos);
        }
예제 #28
0
        private static TextViewPosition GetStartOfLineCaretPosition(int oldVC, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
        {
            int newVC = visualLine.GetTextLineVisualStartColumn(textLine);

            if (newVC == 0)
            {
                newVC = visualLine.GetNextCaretPosition(newVC - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
            }
            if (newVC < 0)
            {
                throw ThrowUtil.NoValidCaretPosition();
            }
            // when the caret is already at the start of the text, jump to start before whitespace
            if (newVC == oldVC)
            {
                newVC = 0;
            }
            return(visualLine.GetTextViewPosition(newVC));
        }
예제 #29
0
        internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
        {
            switch (direction)
            {
            case CaretMovementType.None:
                return(caretPosition);

            case CaretMovementType.DocumentStart:
                desiredXPos = double.NaN;
                return(new TextViewPosition(0, 0));

            case CaretMovementType.DocumentEnd:
                desiredXPos = double.NaN;
                return(new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)));
            }
            DocumentLine caretLine  = textView.Document.GetLineByNumber(caretPosition.Line);
            VisualLine   visualLine = textView.GetOrConstructVisualLine(caretLine);
            TextLine     textLine   = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);

            switch (direction)
            {
            case CaretMovementType.CharLeft:
                desiredXPos = double.NaN;
                // do not move caret to previous line in virtual space
                if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
                {
                    return(caretPosition);
                }
                return(GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace));

            case CaretMovementType.Backspace:
                desiredXPos = double.NaN;
                return(GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace));

            case CaretMovementType.CharRight:
                desiredXPos = double.NaN;
                return(GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace));

            case CaretMovementType.WordLeft:
                desiredXPos = double.NaN;
                return(GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace));

            case CaretMovementType.WordRight:
                desiredXPos = double.NaN;
                return(GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace));

            case CaretMovementType.LineUp:
            case CaretMovementType.LineDown:
            case CaretMovementType.PageUp:
            case CaretMovementType.PageDown:
                return(GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos));

            case CaretMovementType.LineStart:
                desiredXPos = double.NaN;
                return(GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace));

            case CaretMovementType.LineEnd:
                desiredXPos = double.NaN;
                return(GetEndOfLineCaretPosition(visualLine, textLine));

            default:
                throw new NotSupportedException(direction.ToString());
            }
        }
        /// <summary>
        /// Methode gets a text from line and try to get relevant data based on dictionary
        /// Methode is called recursively, if key is found methode is called for the rest of the text if there are any keys
        /// if yes methode is called again
        /// if not then text is value for key in previous call and is saved to object
        /// </summary>
        /// <param name="line">Object Of TextLine</param>
        /// <param name="dic">Dictionary where is methode looking for keys</param>
        /// <param name="type">Type of object where the found data will be stored</param>
        /// <param name="data">Object for data</param>
        /// <returns></returns>
        private bool GetDataFromLine(TextLine line, ref string lineText, Dictionary <string, string> dictionary, Object data, bool isColumn = false, Column col = null, bool lookingForRight = false)
        {
            int    firstCharindex;
            int    keyLength;
            bool   keyFound    = false;
            int    similarity  = 0;
            bool   IndexIsNull = false;
            string stringKey   = string.Empty;

            CONSTANTS.Result res = CONSTANTS.Result.Continue;
            foreach (KeyValuePair <string, string> key in dictionary)
            {
                firstCharindex = lineText.ToLower().IndexOf(key.Key.Substring(0, 1).ToLower()); //  index of the first occurrence of the first character of the key
                keyLength      = key.Key.Length;                                                // length of the key
                while ((keyLength + firstCharindex) <= lineText.Length && firstCharindex != -1) // if the key is longet than found text it si not the text i'm looking for, go to next text
                {
                    stringKey  = lineText.Substring(firstCharindex, keyLength);                 // this is the text i got from OC
                    similarity = SimilarityService.GetSimilarity(key.Key.ToLower(), stringKey.ToLower());
                    if (similarity > CONSTANTS.SIMILARITY && !IsInMiddleOfWord(lineText, firstCharindex, keyLength, key.Key[0], key.Key[key.Key.Length - 1], stringKey))
                    {
                        if (col != null && data.GetType() == _eud.GetType())
                        {
                            // current column ended
                            col.Completed = true;
                            col.Bottom    = line.Words[0].Bounds.Top;
                        }
                        res = PrepareToSave(line, key, stringKey, ref lineText, firstCharindex, dictionary, data, ref keyFound, lookingForRight, ref isColumn, col);
                        if (res == CONSTANTS.Result.Continue)
                        {
                            break;
                        }
                        else if (res == CONSTANTS.Result.True)
                        {
                            return(true);
                        }
                        else if (res == CONSTANTS.Result.False)
                        {
                            return(false);
                        }
                        else if (res == CONSTANTS.Result.Break)
                        {
                            break;
                        }
                    }
                    else
                    {
                        string s     = lineText.Substring(lineText.IndexOf(stringKey) + 1).ToLower();
                        int    index = s.IndexOf(key.Key.Substring(0, 1).ToLower());
                        if (index == 0 && IndexIsNull || index == -1)
                        {
                            // nothing has been found, move to the next key
                            break;
                        }
                        if (index == 0)
                        {
                            IndexIsNull = true;
                        }

                        firstCharindex += index + 1;
                    }
                }
                if (res == CONSTANTS.Result.Break && lineText.Length < 10)
                {
                    break;
                }
                else if (res == CONSTANTS.Result.Continue)
                {
                    continue;
                }
                else
                {
                    continue;
                }
            }

            if (isColumn && !keyFound && col != null && col.FirstLineInColumn > 4)
            {
                // try different dictionary
                if (data.GetType() == _eud.GetType())
                {
                    foreach (Column c in _listOfColumns)
                    {
                        GetDataFromLine(line, ref lineText, _dic.clients, _listOfClients[c.Id - 1], false, col, false);
                    }
                }
                else
                {
                    GetDataFromLine(line, ref lineText, _dic.header, _eud, false, col, false);
                }
            }

            if (isColumn && col != null && !keyFound)
            {
                GetDataFromLine(line, ref lineText, _dic.header, _eud, false, col, false);
                if (_keysInRow == 0)
                {
                    Client client = (Client)data;
                    string s      = lineText.Trim(CONSTANTS.charsToTrim);
                    if (!string.IsNullOrEmpty(s) && s.Length >= 5)
                    {
                        switch (col.FirstLineInColumn)
                        {
                        case 1:
                            client.Name = lineText;
                            col.FirstLineInColumn++;
                            SavePossitionToLists("Name", string.Empty, client.Name, line, line, col.Text + " Meno");
                            break;

                        case 2:
                            client.Street = lineText;
                            col.FirstLineInColumn++;
                            SavePossitionToLists("Street", string.Empty, client.Street, line, line, col.Text + " Ulica");
                            break;

                        case 3:
                            client.PSCCity = lineText;
                            col.FirstLineInColumn++;
                            SavePossitionToLists("PSCCity", string.Empty, client.PSCCity, line, line, col.Text + " Psč");
                            break;

                        case 4:
                            client.State = lineText;
                            col.FirstLineInColumn++;
                            SavePossitionToLists("State", string.Empty, client.State, line, line, col.Text + " Štát");
                            break;
                        }
                    }
                }
            }


            if (_keysInRow >= 2)
            {
                return(false);
            }
            if (lookingForRight && _pair.Key != null)
            {
                return(true);
            }


            return(keyFound);
        }
        /// <summary>
        /// Methode look for value to key in column
        /// </summary>
        /// <param name="line">Current line</param>
        /// <param name="foundKey">Current key</param>
        /// <returns></returns>
        private string FindValueInColumn(TextLine line, string foundKey, string key, ref bool saved)
        {
            int    x1 = 0, x2 = 0;
            string firstWord = GetFirstWordOfPhrase(foundKey).Trim();
            string lastWord  = GetLastWordOfPhrase(foundKey).Trim();
            string res       = string.Empty;

            if (firstWord.Equals(lastWord))
            {
                Word w = line.Words.Where(c => c.Text.Trim(CONSTANTS.charsToTrim).Equals(foundKey.Trim())).FirstOrDefault();
                x1 = w.Bounds.Left;
                x2 = w.Bounds.Right;
            }
            else
            {
                bool found = false;
                var  tmp   = line.Words.Where(c => c.Text.Trim(CONSTANTS.charsToTrim).Equals(lastWord)).ToList();
                Word w     = tmp.FirstOrDefault();
                Word w2    = line.Words[line.Words.IndexOf(w)];
                var  index = line.Words.IndexOf(w);
                if (index != 0)
                {
                    while (index >= 0)
                    {
                        w2 = line.Words[line.Words.IndexOf(w2) - 1];
                        index--;
                        if (w2.Text.Trim(CONSTANTS.charsToTrim).Equals(lastWord))
                        {
                            if (tmp.IndexOf(w) + 1 < tmp.Count())
                            {
                                w     = tmp[tmp.IndexOf(w) + 1];
                                w2    = line.Words[line.Words.IndexOf(w)];
                                index = line.Words.IndexOf(w);
                                continue;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (w2.Text.Trim(CONSTANTS.charsToTrim).Equals(firstWord))
                        {
                            found = true;
                            break;
                        }
                        if (!found && index == 0)
                        {
                            if (tmp.IndexOf(w) + 1 < tmp.Count())
                            {
                                w     = tmp[tmp.IndexOf(w) + 1];
                                w2    = line.Words[line.Words.IndexOf(w)];
                                index = line.Words.IndexOf(w);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }

                x1 = w2.Bounds.Left;
                x2 = w.Bounds.Right;
            }

            try
            {
                for (int i = 1; i <= 2; i++)
                {
                    TextLine t = _p.Lines[_p.Lines.IndexOf(line) + i];
                    res = Common.GetWordsForColumn(new Column {
                        Left = x1, Right = x2
                    }, t);
                    if (!string.IsNullOrWhiteSpace(res) || i == 2)
                    {
                        SavePossitionToLists(key, foundKey.Trim(CONSTANTS.charsToTrimLineForpossition), res.Trim(CONSTANTS.charsToTrimLineForpossition), line, t, string.Empty, x1, x2);
                        saved = true;
                        break;
                    }
                }
            }
            catch (IndexOutOfRangeException e)
            {
                throw new Exception(e.Message);
            }

            return(res);
        }
 private void PushNewLine()
 {
     _endLine = new TextLine(_endLine.End, _endLine.Index + 1);
     _lines.Add(_endLine);
 }
예제 #33
0
        private void InsertExteriorTrivia(ITextView view, ITextBuffer subjectBuffer, DocumentOptionSet options, TextLine currentLine, TextLine previousLine)
        {
            var insertionText = CreateInsertionTextFromPreviousLine(previousLine, options);

            var firstNonWhitespaceOffset = currentLine.GetFirstNonWhitespaceOffset();
            var replaceSpan = firstNonWhitespaceOffset != null
                ? TextSpan.FromBounds(currentLine.Start, currentLine.Start + firstNonWhitespaceOffset.Value)
                : currentLine.Span;

            subjectBuffer.Replace(replaceSpan.ToSpan(), insertionText);

            view.TryMoveCaretToAndEnsureVisible(subjectBuffer.CurrentSnapshot.GetPoint(replaceSpan.Start + insertionText.Length));
        }
예제 #34
0
        public IEnumerable <TextLine> DivideTextItemsIntoLines(float availableWidth, float availableHeight)
        {
            var queue            = new Queue <ITextBlockItem>(RenderingQueue);
            var currentItemIndex = CurrentElementIndex;
            var currentHeight    = 0f;

            while (queue.Any())
            {
                var line = GetNextLine();

                if (!line.Elements.Any())
                {
                    yield break;
                }

                if (currentHeight + line.LineHeight > availableHeight + Size.Epsilon)
                {
                    yield break;
                }

                currentHeight += line.LineHeight;
                yield return(line);
            }

            TextLine GetNextLine()
            {
                var currentWidth = 0f;

                var currentLineElements = new List <TextLineElement>();

                while (true)
                {
                    if (!queue.Any())
                    {
                        break;
                    }

                    var currentElement = queue.Peek();

                    var measurementRequest = new TextMeasurementRequest
                    {
                        Canvas      = Canvas,
                        PageContext = PageContext,

                        StartIndex     = currentItemIndex,
                        AvailableWidth = availableWidth - currentWidth,

                        IsFirstElementInBlock = currentElement == Items.First(),
                        IsFirstElementInLine  = !currentLineElements.Any()
                    };

                    var measurementResponse = currentElement.Measure(measurementRequest);

                    if (measurementResponse == null)
                    {
                        break;
                    }

                    currentLineElements.Add(new TextLineElement
                    {
                        Item        = currentElement,
                        Measurement = measurementResponse
                    });

                    currentWidth    += measurementResponse.Width;
                    currentItemIndex = measurementResponse.NextIndex;

                    if (!measurementResponse.IsLast)
                    {
                        break;
                    }

                    currentItemIndex = 0;
                    queue.Dequeue();
                }

                return(TextLine.From(currentLineElements));
            }
        }
예제 #35
0
 internal /*for testing*/ IEnumerable <IssueLocation> GetBuildErrorsLocations(TextLine line)
 {
     return(GetLocations(line, BUILD_ERROR_LOCATION_PATTERN));
 }
        private CONSTANTS.Result PrepareToSave(TextLine line, KeyValuePair <string, string> key, string stringKey, ref string lineText, int firstCharIndex,
                                               Dictionary <string, string> dictionary, Object data, ref bool keyFound, bool lookingForRight,
                                               ref bool isColumn, Column col)
        {
            string stringKeyValue = string.Empty;

            if (lookingForRight)
            {
                _pair = key;
            }
            if (_dic.columns.ContainsKey(key.Key))
            {
                // it is a column
                _columnsCount++;
                Column column = GetColumnParam(_columnsCount, stringKey, line);
                column.Text = key.Key;
                if (ColumnAlreadyExists(column))
                {
                    column = null;
                    _columnsCount--;
                    return(CONSTANTS.Result.Continue);
                }
                Client n = new Client();
                n.ClientID = column.Text;
                EndRelativeColumn(column);
                var s = line.Text;
                TryGetRightXOfColumn(column, line, ref s, stringKey, n);
                _TempListOfColumn.Add(column);
                lineText = lineText.Replace(key.Key, string.Empty);
                _listOfClients.Add(n);
                s = s.Trim(CONSTANTS.charsToTrim);
                if (!(string.IsNullOrEmpty(s) || s.Length < 5)) // current column could be a column => check it
                {
                    s = s.Replace(stringKey, string.Empty);
                    GetDataFromLine(line, ref s, dictionary, n, true, column, false); // key word followed by (Odberatel)
                }

                return(CONSTANTS.Result.Break);
            }

            keyFound = true;
            if (isColumn && data.GetType() == _eud.GetType())
            {
                stringKeyValue = line.Text.Substring(firstCharIndex + stringKey.Length);
            }
            else
            {
                stringKeyValue = lineText.Substring(firstCharIndex + stringKey.Length);
            }
            if (!isColumn && _listOfClients.Count > 0 && data.GetType() == _listOfClients[0]?.GetType())
            {
                isColumn = true;
            }

            _keysInRow++;
            // there were key in the row, this should be it's value but it could contain more keys => check for another keys
            //if there are keys behind current key, look for more key, othervise this is it's value
            var dict = dictionary.ToDictionary(entry => entry.Key,
                                               entry => entry.Value);

            dict.Remove(key.Key);
            stringKeyValue = stringKeyValue.Trim(CONSTANTS.charsToTrimLine);
            if (!GetDataFromLine(line, ref stringKeyValue, dict, data, isColumn, col))
            {
                if (_dic.canDeleteKeys.Contains(key.Value))
                {
                    _keysToDelete.Add(key.Value);
                }
                bool saved = false;
                stringKeyValue = stringKeyValue.Trim(CONSTANTS.charsToTrimLine);
                if (string.IsNullOrEmpty(stringKeyValue) && _dic.valueInColumn.Contains(key.Value))
                {
                    stringKeyValue = FindValueInColumn(line, stringKey, key.Key, ref saved);
                }

                stringKeyValue = stringKeyValue.Trim(CONSTANTS.charsToTrimLineForpossition);


                stringKeyValue = SaveData(ref keyFound, isColumn, key, data, stringKeyValue, ref lineText, firstCharIndex);

                if (!saved)
                {
                    SavePossitionToLists(key.Value, stringKey.Trim(CONSTANTS.charsToTrimLineForpossition), stringKeyValue, line, line);
                }

                if (data.GetType() == typeof(Evidence))
                {
                    float fakeConf  = 0;
                    int   fakeCount = 0;
                    EndRelaticeColumnByText(GetWordsForPositionSave(line, stringKeyValue, ref fakeConf, ref fakeCount).FirstOrDefault());
                }
                if (_pair.Value != string.Empty && lookingForRight)
                {
                    return(CONSTANTS.Result.True);
                }

                if (lineText.Length < 5)
                {
                    return(CONSTANTS.Result.Break);
                }
            }
            if (_pair.Value != string.Empty && lookingForRight)
            {
                return(CONSTANTS.Result.True);
            }

            return(CONSTANTS.Result.Break);
        }
예제 #37
0
    public Example_15()
    {
        PDF pdf = new PDF(new BufferedStream(
                              new FileStream("Example_15.pdf", FileMode.Create)));

        Font f1 = new Font(pdf, CoreFont.HELVETICA_BOLD);
        Font f2 = new Font(pdf, CoreFont.HELVETICA);
        Font f3 = new Font(pdf, CoreFont.HELVETICA);
        Font f4 = new Font(pdf, CoreFont.HELVETICA_BOLD);
        Font f5 = new Font(pdf, CoreFont.HELVETICA);

        Page page = new Page(pdf, A4.PORTRAIT);

        List <List <Cell> > tableData = new List <List <Cell> >();
        List <Cell>         row       = null;
        Cell cell = null;

        for (int i = 0; i < 60; i++)
        {
            row = new List <Cell>();
            for (int j = 0; j < 5; j++)
            {
                if (i == 0)
                {
                    cell = new Cell(f1);
                }
                else
                {
                    cell = new Cell(f2);
                }

                cell.SetTopPadding(10f);
                cell.SetBottomPadding(10f);
                cell.SetLeftPadding(10f);
                cell.SetRightPadding(10f);

                //  cell.SetNoBorders();
                cell.SetText("Hello " + i + " " + j);

                CompositeTextLine composite = new CompositeTextLine(0f, 0f);
                composite.SetFontSize(12.0f);
                TextLine line1 = new TextLine(f3, "H");
                TextLine line2 = new TextLine(f4, "2");
                TextLine line3 = new TextLine(f5, "O");
                line2.SetTextEffect(Effect.SUBSCRIPT);
                composite.AddComponent(line1);
                composite.AddComponent(line2);
                composite.AddComponent(line3);

                if (i == 0 || j == 0)
                {
                    cell.SetCompositeTextLine(composite);
                    cell.SetBgColor(Color.deepskyblue);
                }
                else
                {
                    cell.SetBgColor(Color.dodgerblue);
                }
                cell.SetPenColor(Color.lightgray);
                cell.SetBrushColor(Color.black);
                row.Add(cell);
            }
            tableData.Add(row);
        }

        Table table = new Table();

        table.SetData(tableData, Table.DATA_HAS_2_HEADER_ROWS);
        table.SetCellBordersWidth(0.2f);
        table.SetLocation(70f, 30f);
        table.AutoAdjustColumnWidths();

        while (true)
        {
            Point    point = table.DrawOn(page);
            TextLine text  = new TextLine(f1, "Hello, World.");
            text.SetLocation(point.GetX() + table.GetWidth(), point.GetY());
            text.DrawOn(page);

            if (!table.HasMoreData())
            {
                break;
            }
            page = new Page(pdf, A4.PORTRAIT);
        }

        pdf.Close();
    }
 /// <summary>
 /// check whether the line is located at the end of the line
 /// </summary>
 private static bool LocatedAtTheEndOfLine(TextLine line, SyntaxToken lastToken)
 {
     return lastToken.IsMissing && lastToken.Span.End == line.EndIncludingLineBreak;
 }
예제 #39
0
        public WpfTextViewLine(IBufferGraph bufferGraph, LinePartsCollection linePartsCollection, int startColumn, int endColumn, ITextSnapshotLine bufferLine, SnapshotSpan span, ITextSnapshot visualSnapshot, TextLine textLine, double indentation, double virtualSpaceWidth)
        {
            if (bufferGraph == null)
            {
                throw new ArgumentNullException(nameof(bufferGraph));
            }
            if (linePartsCollection == null)
            {
                throw new ArgumentNullException(nameof(linePartsCollection));
            }
            if (bufferLine == null)
            {
                throw new ArgumentNullException(nameof(bufferLine));
            }
            if (span.Snapshot != bufferLine.Snapshot)
            {
                throw new ArgumentException();
            }
            if (visualSnapshot == null)
            {
                throw new ArgumentNullException(nameof(visualSnapshot));
            }
            if (textLine == null)
            {
                throw new ArgumentNullException(nameof(textLine));
            }

            this.IsValid             = true;
            this.bufferGraph         = bufferGraph;
            this.linePartsCollection = linePartsCollection;
            this.endColumn           = endColumn;
            this.visualSnapshot      = visualSnapshot;
            this.textLines           = new ReadOnlyCollection <TextLine>(new[] { textLine });
            Debug.Assert(textLines.Count == 1);            // Assumed by all code accessing TextLine prop
            this.realTopSpace    = 0;
            this.realBottomSpace = 0;
            this.realBaseline    = TextLine.Baseline;
            this.isFirstTextViewLineForSnapshotLine = span.Start == bufferLine.Start;
            this.isLastTextViewLineForSnapshotLine  = span.End == bufferLine.EndIncludingLineBreak;
            IsLastVisualLine              = bufferLine.LineNumber + 1 == bufferLine.Snapshot.LineCount && IsLastTextViewLineForSnapshotLine;
            this.lineBreakLength          = isLastTextViewLineForSnapshotLine ? bufferLine.LineBreakLength : 0;
            this.virtualSpaceWidth        = virtualSpaceWidth;
            this.textLeft                 = indentation;
            this.textWidth                = textLine.WidthIncludingTrailingWhitespace;
            this.extentIncludingLineBreak = span;
            this.realHeight               = textLine.Height + DEFAULT_TOP_SPACE + DEFAULT_BOTTOM_SPACE;
            this.realTextHeight           = textLine.TextHeight;
            this.endOfLineWidth           = Math.Floor(this.realTextHeight * 0.58333333333333337);  // Same as VS
            this.width  = this.textWidth + (this.lineBreakLength == 0 ? 0 : this.endOfLineWidth);
            this.change = TextViewLineChange.NewOrReformatted;
            SetLineTransform(DefaultLineTransform);
        }
        private void SavePossitionToLists(string key, string stringkey, string value, TextLine Keyline, TextLine valueLine, string colText = "", int x1 = 0, int x2 = 0)
        {
            if (!_p.ListOfKeyPossitions.Any(c => c.Key.Equals(key)))
            {
                List <Word> tmpKeyWords   = new List <Word>();
                List <Word> tmpValueWords = new List <Word>();
                float       conf          = 0;
                int         count         = 0;
                tmpKeyWords = GetWordsForPositionSave(Keyline, stringkey, ref conf, ref count);

                tmpValueWords = GetWordsForPositionSave(valueLine, value, ref conf, ref count, x1, x2);

                //key
                PossitionOfWord pk = new PossitionOfWord();
                if (stringkey != string.Empty)
                {
                    var v  = tmpKeyWords.First <Word>();
                    var vl = tmpKeyWords.Last <Word>();
                    pk.KeyBounds = new System.Drawing.Rectangle(v.Bounds.X, v.Bounds.Y, tmpKeyWords.Last <Word>().Bounds.Right - v.Bounds.Left, v.Bounds.Height);
                }
                if (key.Equals("Name") || key.Equals("Street") || key.Equals("PSCCity") || key.Equals("State"))
                {
                    pk.Key = colText;
                }
                else
                {
                    pk.Key = stringkey;
                }

                pk.Value = value;

                //value
                if (value == string.Empty || !tmpValueWords.Any())
                {
                    pk.ValueBounds = new System.Drawing.Rectangle(pk.KeyBounds.Right, pk.KeyBounds.Y, 100, pk.KeyBounds.Height);
                }
                else
                {
                    var w = tmpValueWords.First <Word>();
                    if (Keyline == valueLine)
                    {
                        // not a column
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            pk.ValueBounds = new System.Drawing.Rectangle(w.Bounds.X, w.Bounds.Y, tmpValueWords.Last <Word>().Bounds.Right - w.Bounds.Left, w.Bounds.Height);
                        }
                        else
                        {
                            var x     = w.Bounds.Right;
                            var y     = w.Bounds.Y;
                            var width = 0;
                            try
                            {
                                if (stringkey == string.Empty)
                                {
                                    width = tmpValueWords.Last <Word>().Bounds.Right - w.Bounds.Left;
                                }
                                else
                                {
                                    var vl = tmpKeyWords.Last <Word>();
                                    width = Keyline.Words[Keyline.Words.IndexOf(vl) + 1].Bounds.Left - vl.Bounds.Right;
                                }
                            }
                            catch (ArgumentOutOfRangeException e)
                            {
                                width = w.Bounds.Right + 50;
                            }
                            pk.ValueBounds = new System.Drawing.Rectangle(x, y, width, w.Bounds.Height);
                        }
                    }
                    else
                    {
                        // was looking in column
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            pk.ValueBounds = new System.Drawing.Rectangle(w.Bounds.X, w.Bounds.Y, tmpValueWords.Last <Word>().Bounds.Right - w.Bounds.Left, w.Bounds.Height);
                        }
                        else
                        {
                            pk.ValueBounds = new System.Drawing.Rectangle(x1, valueLine.Bounds.Y, x2 - x1, w.Bounds.Height);
                        }
                    }
                }

                pk.Confidence    = string.Format("{0:N2}%", (conf / count));
                pk.DictionaryKey = key;
                _p.ListOfKeyPossitions.Add(pk);
            }
        }
예제 #41
0
        public void TestColorByLevel2()
        {
            var textLine = new TextLine(new LogLine(0, 0, "foobar", LevelFlags.Fatal), _hovered, _selected, true);

            textLine.ColorByLevel.Should().BeTrue();
        }
예제 #42
0
    public Example_25()
    {
        PDF pdf = new PDF(new BufferedStream(
                              new FileStream("Example_25.pdf", FileMode.Create)));

        Font f1 = new Font(pdf, CoreFont.HELVETICA);
        Font f2 = new Font(pdf, CoreFont.HELVETICA_BOLD);
        Font f3 = new Font(pdf, CoreFont.HELVETICA);
        Font f4 = new Font(pdf, CoreFont.HELVETICA_BOLD);
        Font f5 = new Font(pdf, CoreFont.HELVETICA);
        Font f6 = new Font(pdf, CoreFont.HELVETICA_BOLD);

        Page page = new Page(pdf, Letter.PORTRAIT);

        CompositeTextLine composite = new CompositeTextLine(50f, 50f);

        composite.SetFontSize(14f);

        TextLine text1 = new TextLine(f1, "C");
        TextLine text2 = new TextLine(f2, "6");
        TextLine text3 = new TextLine(f3, "H");
        TextLine text4 = new TextLine(f4, "12");
        TextLine text5 = new TextLine(f5, "O");
        TextLine text6 = new TextLine(f6, "6");

        text1.SetColor(Color.dodgerblue);
        text3.SetColor(Color.dodgerblue);
        text5.SetColor(Color.dodgerblue);

        text2.SetTextEffect(Effect.SUBSCRIPT);
        text4.SetTextEffect(Effect.SUBSCRIPT);
        text6.SetTextEffect(Effect.SUBSCRIPT);

        composite.AddComponent(text1);
        composite.AddComponent(text2);
        composite.AddComponent(text3);
        composite.AddComponent(text4);
        composite.AddComponent(text5);
        composite.AddComponent(text6);

        float[] xy = composite.DrawOn(page);

        Box box = new Box();

        box.SetLocation(xy[0], xy[1]);
        box.SetSize(20f, 20f);
        box.DrawOn(page);

        CompositeTextLine composite2 = new CompositeTextLine(50f, 100f);

        composite2.SetFontSize(14f);

        text1 = new TextLine(f1, "SO");
        text2 = new TextLine(f2, "4");
        text3 = new TextLine(f4, "2-"); // Use bold font here

        text2.SetTextEffect(Effect.SUBSCRIPT);
        text3.SetTextEffect(Effect.SUPERSCRIPT);

        composite2.AddComponent(text1);
        composite2.AddComponent(text2);
        composite2.AddComponent(text3);

        composite2.DrawOn(page);
        composite2.SetLocation(100f, 150f);
        composite2.DrawOn(page);

        float[] yy    = composite2.GetMinMax();
        Line    line1 = new Line(50f, yy[0], 200f, yy[0]);
        Line    line2 = new Line(50f, yy[1], 200f, yy[1]);

        line1.DrawOn(page);
        line2.DrawOn(page);

        pdf.Close();
    }
        private static void RegisterCodeFixes(
            CodeFixContext context, TextLine startLine, TextLine middleLine, TextLine endLine)
        {
            var document = context.Document;

            var topText     = startLine.ToString()[s_mergeConflictLength..].Trim();
 protected abstract AbstractIndenter GetIndenter(
     ISyntaxFactsService syntaxFacts, SyntaxTree syntaxTree, TextLine lineToBeIndented, IEnumerable<IFormattingRule> formattingRules, OptionSet optionSet, CancellationToken cancellationToken);
        private async Task<Document> GenerateMemberAndUsingsAsync(
            Document document,
            CompletionItem completionItem,
            TextLine line,
            CancellationToken cancellationToken)
        {
            var syntaxFactory = document.GetLanguageService<SyntaxGenerator>();
            var codeGenService = document.GetLanguageService<ICodeGenerationService>();

            // Resolve member and type in our new, forked, solution
            var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(line.Start, cancellationToken);
            var symbols = MemberInsertionCompletionItem.GetSymbolsAsync(completionItem, document, cancellationToken).WaitAndGetResult(cancellationToken);
            var overriddenMember = symbols.First();

            // CodeGenerationOptions containing before and after
            var options = new CodeGenerationOptions(contextLocation: semanticModel.SyntaxTree.GetLocation(TextSpan.FromBounds(line.Start, line.Start)));

            var generatedMember = await GenerateMemberAsync(overriddenMember, containingType, document, completionItem, cancellationToken).ConfigureAwait(false);
            generatedMember = _annotation.AddAnnotationToSymbol(generatedMember);

            Document memberContainingDocument = null;
            if (generatedMember.Kind == SymbolKind.Method)
            {
                memberContainingDocument = codeGenService.AddMethodAsync(document.Project.Solution, containingType, (IMethodSymbol)generatedMember, options, cancellationToken).WaitAndGetResult(cancellationToken);
            }
            else if (generatedMember.Kind == SymbolKind.Property)
            {
                memberContainingDocument = codeGenService.AddPropertyAsync(document.Project.Solution, containingType, (IPropertySymbol)generatedMember, options, cancellationToken).WaitAndGetResult(cancellationToken);
            }
            else if (generatedMember.Kind == SymbolKind.Event)
            {
                memberContainingDocument = codeGenService.AddEventAsync(document.Project.Solution, containingType, (IEventSymbol)generatedMember, options, cancellationToken).WaitAndGetResult(cancellationToken);
            }

            return memberContainingDocument;
        }
예제 #46
0
        static IEnumerable <Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVC, int segmentEndVC)
        {
            TextLine lastTextLine = visualLine.TextLines.Last();
            Vector   scrollOffset = textView.ScrollOffset;

            for (int i = 0; i < visualLine.TextLines.Count; i++)
            {
                TextLine line           = visualLine.TextLines[i];
                double   y              = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop);
                int      visualStartCol = visualLine.GetTextLineVisualStartColumn(line);
                int      visualEndCol   = visualStartCol + line.Length;
                if (line == lastTextLine)
                {
                    visualEndCol -= 1;                     // 1 position for the TextEndOfParagraph
                }
                else
                {
                    visualEndCol -= line.TrailingWhitespaceLength;
                }

                if (segmentEndVC < visualStartCol)
                {
                    break;
                }
                if (lastTextLine != line && segmentStartVC > visualEndCol)
                {
                    continue;
                }
                int segmentStartVCInLine = Math.Max(segmentStartVC, visualStartCol);
                int segmentEndVCInLine   = Math.Min(segmentEndVC, visualEndCol);
                y -= scrollOffset.Y;
                Rect lastRect = Rect.Empty;
                if (segmentStartVCInLine == segmentEndVCInLine)
                {
                    // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit
                    // We need to return a rectangle to ensure empty lines are still visible
                    double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVCInLine);
                    pos -= scrollOffset.X;
                    // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active.
                    // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace.
                    // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace.
                    if (segmentEndVCInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVC > segmentEndVCInLine && line.TrailingWhitespaceLength == 0)
                    {
                        continue;
                    }
                    if (segmentStartVCInLine == visualStartCol && i > 0 && segmentStartVC < segmentStartVCInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0)
                    {
                        continue;
                    }
                    lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height);
                }
                else
                {
                    if (segmentStartVCInLine <= visualEndCol)
                    {
                        foreach (TextBounds b in line.GetTextBounds(segmentStartVCInLine, segmentEndVCInLine - segmentStartVCInLine))
                        {
                            double left  = b.Rectangle.Left - scrollOffset.X;
                            double right = b.Rectangle.Right - scrollOffset.X;
                            if (!lastRect.IsEmpty)
                            {
                                yield return(lastRect);
                            }
                            // left>right is possible in RTL languages
                            lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
                        }
                    }
                }
                // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection
                // after the line end.
                // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line.
                if (segmentEndVC > visualEndCol)
                {
                    double left, right;
                    if (segmentStartVC > visualLine.VisualLengthWithEndOfLineMarker)
                    {
                        // segmentStartVC is in virtual space
                        left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVC);
                    }
                    else
                    {
                        // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol,
                        // so we only need to do the remainder starting at visualEndCol.
                        // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap,
                        // so we'll need to include it here.
                        // For the last line, visualEndCol already includes the whitespace.
                        left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width);
                    }
                    if (line != lastTextLine || segmentEndVC == int.MaxValue)
                    {
                        // If word-wrap is enabled and the segment continues into the next line,
                        // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue),
                        // we select the full width of the viewport.
                        right = Math.Max(((IScrollInfo)textView).ExtentWidth, ((IScrollInfo)textView).ViewportWidth);
                    }
                    else
                    {
                        right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVC);
                    }
                    Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
                    if (!lastRect.IsEmpty)
                    {
                        if (extendSelection.IntersectsWith(lastRect))
                        {
                            lastRect.Union(extendSelection);
                            yield return(lastRect);
                        }
                        else
                        {
                            // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate.
                            yield return(lastRect);

                            yield return(extendSelection);
                        }
                    }
                    else
                    {
                        yield return(extendSelection);
                    }
                }
                else
                {
                    yield return(lastRect);
                }
            }
        }
 protected abstract bool HasPreprocessorCharacter(TextLine currentLine);
예제 #48
0
 public override TextLine this [int index] {
     get {
         var line = textDoc.GetLine(index + 1);
         return(TextLine.FromSpan(parent, new TextSpan(line.Offset, line.Length)));
     }
 }
 protected IndentationResult GetIndentationOfLine(TextLine lineToMatch)
 {
     return GetIndentationOfLine(lineToMatch, addedSpaces: 0);
 }
예제 #50
0
            public override TextLine GetLineFromPosition(int position)
            {
                var line = textDoc.GetLineByOffset(position);

                return(TextLine.FromSpan(parent, new TextSpan(line.Offset, line.Length)));
            }
 public LineTrackingStringBuffer()
 {
     _endLine = new TextLine(0, 0);
     _lines = new List<TextLine>() { _endLine };
 }
예제 #52
0
 public override TextLine this [int index] {
     get {
         var line = sourceText.Snapshot.GetLineFromLineNumber(index);
         return(TextLine.FromSpan(sourceText, TextSpan.FromBounds(line.Start, line.End)));
     }
 }
        private TextLine FindLine(int absoluteIndex)
        {
            TextLine selected = null;

            if (_currentLine != null)
            {
                if (_currentLine.Contains(absoluteIndex))
                {
                    // This index is on the last read line
                    selected = _currentLine;
                }
                else if (absoluteIndex > _currentLine.Index && _currentLine.Index + 1 < _lines.Count)
                {
                    // This index is ahead of the last read line
                    selected = ScanLines(absoluteIndex, _currentLine.Index);
                }
            }

            // Have we found a line yet?
            if (selected == null)
            {
                // Scan from line 0
                selected = ScanLines(absoluteIndex, 0);
            }

            Debug.Assert(selected == null || selected.Contains(absoluteIndex));
            _currentLine = selected;
            return selected;
        }
예제 #54
0
 internal /*for testing*/ IEnumerable <IssueLocation> GetIssueLocations(TextLine line)
 {
     return(GetLocations(line, ISSUE_LOCATION_PATTERN));
 }
예제 #55
0
 public TextLine()
 {
     TopLine = this;
 }
예제 #56
0
    private IEnumerator UseCoroutine()
    {
        pageManager.CreateText("The keypad has buttons labelled 0 to 9 and a small screen.\nOptions: 0-9, cancel");

        bool   quitting       = false;
        string enteredCode    = "";
        int    failedAttempts = 0;

        while (!quitting)
        {
            // Initialize input
            TextLine textLine = pageManager.CreateText("> ");
            List <StringConversion> stringConversions = new List <StringConversion>()
            {
                new StringConversion("0", "0"),
                new StringConversion("1", "1"),
                new StringConversion("2", "2"),
                new StringConversion("3", "3"),
                new StringConversion("4", "4"),
                new StringConversion("5", "5"),
                new StringConversion("6", "6"),
                new StringConversion("7", "7"),
                new StringConversion("8", "8"),
                new StringConversion("9", "9"),
                new StringConversion("cancel", "cancel")
            };
            inputModifier.RequestInput(textLine, stringConversions);

            // Await input
            while (!inputModifier.GetInputComplete())
            {
                yield return(null);
            }

            // Act on input
            if (inputModifier.GetConversionIndex() == 10)
            {
                quitting = true;
            }
            else
            {
                string enteredDigit = stringConversions[inputModifier.GetConversionIndex()].typedString;
                enteredCode += enteredDigit;
                if (enteredCode.Length == 4)
                {
                    if (enteredCode == correctCode)
                    {
                        pageManager.CreateText("The screen now reads " + enteredCode + ". The keypad beeps twice and you hear a clicking noise from inside the door. You've unlocked it!");
                        locked   = false;
                        quitting = true;
                    }
                    else
                    {
                        pageManager.CreateText("The screen now reads " + enteredCode + ". The keypad buzzes and nothing happens. That wasn't the right code.\nOptions: 0-9, cancel");
                        enteredCode = "";
                        failedAttempts++;
                    }
                }
                // After several attempts the player just has to type 1 digit.
                else if (enteredCode.Length == 1 && failedAttempts == maxFailedAttempts)
                {
                    pageManager.CreateText("The screen now reads " + enteredCode + ". The keypad beeps twice and you hear a clicking noise from inside the door. You've unlocked it! You're somewhat surprised that the code was just " + enteredCode + "...");
                    locked   = false;
                    quitting = true;
                }
                else
                {
                    pageManager.CreateText("The screen now reads " + enteredCode + ".\nOptions: 0-9, cancel");
                }
            }
        }

        inUse = false;
    }
 protected abstract bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
     IEnumerable<IFormattingRule> formattingRules, SyntaxNode root, TextLine line, OptionSet optionSet, CancellationToken cancellationToken);
예제 #58
0
 public void Add(TextLine line)
 {
     Lines.Add(line);
 }
예제 #59
0
        void CheckNotEqualLine(TextLine first, TextLine second)
        {
            Assert.NotEqual(first, second);
#if false
            Assert.NotEqual(first, second);
            Assert.NotEqual(first.Extent, second.Extent);
            Assert.NotEqual(first.ExtentIncludingLineBreak, second.ExtentIncludingLineBreak);
#endif
        }
예제 #60
0
        private bool trySplitSearchText(string text, out TextLine root)
        {
            text = text.ToUpper();
            var rs = getPinYinSplit().FindAll(text);

            root = new TextLine();
            List <TextLine> textLines = new List <TextLine>()
            {
                root
            };

            #region 初始化 TextLine
            for (int i = 0; i < text.Length; i++)
            {
                var c = text[i];
                if (_type == PinYinSearchType.PinYin && c >= 0x4e00 && c <= 0x9fa5)
                {
                    var pys = PinYinDict.GetAllPinYin(c);
                    if (pys.Count == 0)
                    {
                        pys.Add(" ");
                    }
                    for (int j = 0; j < pys.Count; j++)
                    {
                        var      py = pys[j].ToUpper();
                        TextLine tl;// = new TextLine();
                        if (j == 0)
                        {
                            tl = new TextLine(py[0], py, c);
                            textLines.Add(tl);
                        }
                        else
                        {
                            tl = new TextLine(py[0], py, c, textLines[i + 1]);
                        }
                        textLines[i].Add(tl);
                    }
                }
                else
                {
                    TextLine tl;
                    if (c >= 0x4e00 && c <= 0x9fa5)
                    {
                        var py = PinYinDict.GetPinYinFast(c);
                        tl = new TextLine(py[0], py, c);
                    }
                    else if (c >= '0' || c <= '9')
                    {
                        tl = new TextLine(c, null, (char)0);
                    }
                    else if (c >= 'A' || c <= 'Z')
                    {
                        tl = new TextLine(c, null, (char)0);
                    }
                    else
                    {
                        tl = new TextLine(' ', " ", c);
                    }
                    textLines[i].Add(tl);
                    textLines.Add(tl);
                }
            }
            #endregion

            #region 划分拼音
            foreach (var r in rs)
            {
                var tl2 = new TextLine(r.Keyword[0], r.Keyword, (char)0, textLines[r.End + 1]);
                textLines[r.Start].Add(tl2);
            }
            #endregion

            return(true);
        }