Exemple #1
0
        /// <summary>
        /// Locate value of attribute position for specified html tag
        /// </summary>
        public static TextRange GetTagAttributeValuePos(ref string pageHtml, string tagName, string attributeName, int start)
        {
            int tagStart, tagEnd;
            int attrStart;
            int valueStart;

            // Allocate result with default values
            TextRange result = new TextRange(-1, -1);

            // Incorrect input
            if (start >= pageHtml.Length)
                return result;

            // Correct tag name
            if (tagName[0] != '<')
                tagName = '<' + tagName;

            //=============================================================//

            // Find tag first position
            tagStart = StringCompare.IndexOfIgnoreCase(ref pageHtml, tagName, start);
            if (tagStart == -1)
                return result;

            // Locate end of tag
            tagEnd = StringCompare.IndexOfMatchCase(ref pageHtml, ">", tagStart);

            // Wrong html code
            if (tagEnd == -1)
                return result;

            // Find the Attribute position
            attrStart = StringCompare.IndexOfIgnoreCase(ref pageHtml, attributeName, tagStart);

            // There is no attribute, so go away!
            if (attrStart == -1 || attrStart >= tagEnd)
            {
                // Set found start position to result
                result.Start = tagStart;
                result.End = -1;
                return result;
            }

            // Find value start position
            valueStart = StringCompare.IndexOfMatchCase(ref pageHtml, '=', attrStart);

            // There is no value, so go away!
            if (valueStart == -1 || valueStart >= tagEnd)
            {
                // Set found start position to result
                result.Start = attrStart;
                result.End = -1;
                return result;
            }

            // Locate value of attribute position
            result = FindAttributeValuePosition(ref pageHtml, tagEnd, valueStart);

            return result;
        }
Exemple #2
0
 public Assign(string name, Element value, bool isMaybe, TextRange range)
     : base(isMaybe, range)
 {
     Contract.Requires<ArgumentNullException>(name != null);
     this.Name = name;
     this.Value = value;
 }
        protected JasmineElement(KarmaServiceProvider provider, string name,
			ProjectModelElementEnvoy projectFileEnvoy,
			TextRange textRange, IList<string> referencedFiles)
            : base(provider, name, projectFileEnvoy, textRange)
        {
            _referencedFiles = referencedFiles ?? new List<string>().AsReadOnly();
        }
        public CsvCompilationUnit CompilationUnit(TextRange textRange, IEnumerable<RowDeclarationSyntax> rows)
        {
            Assume.NotNull(textRange, nameof(textRange));
            Assume.NotNull(rows, nameof(rows));

            return new CsvCompilationUnit(textRange, rows);
        }
        public PostfixTemplateAcceptanceContext(
      [NotNull] IReferenceExpression referenceExpression,
      [NotNull] ICSharpExpression expression,
      TextRange replaceRange, TextRange expressionRange,
      bool canBeStatement, bool looseChecks)
        {
            ReferenceExpression = referenceExpression;
              Expression = expression;
              ExpressionType = expression.Type();
              ReplaceRange = replaceRange;
              ExpressionRange = expressionRange;
              CanBeStatement = canBeStatement;
              LooseChecks = looseChecks;

              ContainingFunction = Expression.GetContainingNode<ICSharpFunctionDeclaration>();

              var expressionReference = expression as IReferenceExpression;
              if (expressionReference != null)
              {
            ExpressionReferencedElement = expressionReference.Reference.Resolve().DeclaredElement;
              }
              else
              {
            var typeExpression = expression as IPredefinedTypeExpression;
            if (typeExpression != null)
            {
              var typeName = typeExpression.PredefinedTypeName;
              if (typeName != null)
            ExpressionReferencedElement = typeName.Reference.Resolve().DeclaredElement;
            }
              }
        }
            protected override void AcceptExpression(
        ITextControl textControl, ISolution solution, TextRange resultRange, ICSharpExpression expression)
            {
                // set selection for introduce field
                textControl.Selection.SetRanges(new[] {TextControlPosRange.FromDocRange(textControl, resultRange)});

                const string name = "IntroFieldAction";
                var rules = DataRules
                  .AddRule(name, ProjectModel.DataContext.DataConstants.SOLUTION, solution)
                  .AddRule(name, DataConstants.DOCUMENT, textControl.Document)
                  .AddRule(name, TextControl.DataContext.DataConstants.TEXT_CONTROL, textControl)
                  .AddRule(name, Psi.Services.DataConstants.SELECTED_EXPRESSION, expression);

                Lifetimes.Using(lifetime =>
                  WorkflowExecuter.ExecuteBatch(
                Shell.Instance.GetComponent<DataContexts>().CreateWithDataRules(lifetime, rules),
                new IntroFieldWorkflow(solution, null)));

                // todo: rename hotspots

                var ranges = textControl.Selection.Ranges.Value;
                if (ranges.Count == 1) // reset selection
                {
                  var endPos = ranges[0].End;
                  textControl.Selection.SetRanges(new[] {new TextControlPosRange(endPos, endPos)});
                }
            }
Exemple #7
0
 public static void divideToLines(Slides slides, Slide slide, TextRange textRange)
 {
     var slideNumber = slide.SlideIndex;
     float slideDuration = slide.SlideShowTransition.AdvanceTime;
     int divisionNumber = textRange.Lines().Count;
     float duration = durationAfterDivisions(slideDuration, divisionNumber / 2);
     string textFrmLines = "";
     foreach (TextRange line in textRange.Lines())
     {
         if (textFrmLines.Length > 0)
         {
             textFrmLines += line.Text;
             SlidesManipulation.createNewSlide(slides, ++slideNumber, textFrmLines.Trim(), duration);
             SlidesManipulation.createNewSlide(slides, ++slideNumber, "", 0.01F);
             textFrmLines = "";
         }
         else
         {
             textFrmLines += line.Text;
         }
     }
     //add the rest of textFrmLines
     if (textFrmLines.Length > 0)
     {
         SlidesManipulation.createNewSlide(slides, ++slideNumber, textFrmLines, duration);
         SlidesManipulation.createNewSlide(slides, ++slideNumber, "", 0.1F);
     }
         //delete slides
         slide.Delete();
         slides[slideNumber].Delete();
 }
 /// <summary>
 /// Selects the element.
 /// </summary>
 public override IEnumerable<TextRange> SelectElement(TextRange textRange)
 {
     return base.SelectElement(textRange).Where(line => {
         var text = TextRangeExtensions.GetText(line);
         return IsEmptyLineIncluded || !String.IsNullOrWhiteSpace(text);
     });
 }
        public static UnitTestElementDisposition BuildDisposition(UnitTestElement element, ScenarioLocation location, IProjectFile  projectFile)
        {
            var contents = File.ReadAllText(location.Path);
            var range = new TextRange(LineToOffset(contents, location.FromLine), LineToOffset(contents, location.ToLine));

            return new UnitTestElementDisposition(element, projectFile, range, new TextRange(0));
        }
Exemple #10
0
        public TypefaceListItem(Typeface typeface)
        {
            _displayName = GetDisplayName(typeface);
            _simulated = typeface.IsBoldSimulated || typeface.IsObliqueSimulated;

            this.FontFamily = typeface.FontFamily;
            this.FontWeight = typeface.Weight;
            this.FontStyle = typeface.Style;
            this.FontStretch = typeface.Stretch;

            string itemLabel = _displayName;

            if (_simulated)
            {
                string formatString = Properties.FontDialogResources.ResourceManager.GetString(
                    "simulated", 
                    CultureInfo.CurrentUICulture
                    );
                itemLabel = string.Format(formatString, itemLabel);
            }

            Text = itemLabel;
            ToolTip = itemLabel;

            // In the case of symbol font, apply the default message font to the text so it can be read.
            if (FontFamilyListItem.IsSymbolFont(typeface.FontFamily))
            {
                var range = new TextRange(ContentStart, ContentEnd);
                range.ApplyPropertyValue(TextBlock.FontFamilyProperty, SystemFonts.MessageFontFamily);
            }
        }
Exemple #11
0
		/// <summary>
		/// Locates @import rule value
		/// </summary>
		/// <param name="cssCodes"></param>
		/// <param name="startindex"></param>
		/// <param name="onlyWithoutUrlOption">Specifies that operator should not catch rule with URL attribute.</param>
		/// <param name="captureExactInUrl">Specifies that operator should strip the URL attribute if there is any</param>
		/// <returns></returns>
		public static TextRange FindImportRuleUrlPosition(ref string cssCodes, int startindex, bool onlyWithoutUrlOption, bool captureExactlyInUrl)
		{
			int valueStart, valueEnd;
			TextRange result = new TextRange(-1, -1);
			const string strCSSImportRule = "@import";
			const string strCSSUrlValue = "url(";

			//==============================
			if (startindex >= cssCodes.Length)
				return result;


			// Find first position
			valueStart = StringCompare.IndexOfIgnoreCase(ref cssCodes, strCSSImportRule, startindex);
			if (valueStart == -1)
				return result;

			valueStart += strCSSImportRule.Length;

			// 
			if (cssCodes.Substring(valueStart, 1).Trim().Length > 0)
				return result;
			else
				valueStart++;

			valueEnd = StringCompare.IndexOfMatchCase(ref cssCodes, ";", valueStart);

			if (valueEnd == -1)
				return result;
			else
			{
				int urlPos = StringCompare.IndexOfIgnoreCase(ref cssCodes, strCSSUrlValue, valueStart);
				if (urlPos != -1 && urlPos < valueEnd)
				{
					if (onlyWithoutUrlOption)
					{
						result.Start = valueEnd;
						result.End = -1;
						return result;
					}

					if (captureExactlyInUrl)
					{
						valueStart = urlPos + strCSSUrlValue.Length;

						urlPos = StringCompare.IndexOfMatchCase(ref cssCodes, ")", valueStart);
						if (urlPos != -1 && urlPos < valueEnd)
						{
							valueEnd = urlPos;
						}
					}
				}
			}

			result.Start = valueStart;
			result.End = valueEnd;
			return result;

		}
 /// <summary>
 /// Creates row node and appends it to actual document node
 /// </summary>
 public ICsvTreeFactory CreateRow(TextRange textRange)
 {
     Assume.NotNull(textRange, nameof(textRange));
     checkIsDocumentDefined();
     _actualRowDeclaration = new RowDeclarationSyntax(textRange);
     _csvCompilationUnits.Peek().AppendChild(_actualRowDeclaration);
     return this;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="TextDocument"/> class.
        /// </summary>
        public TextDocument(String text)
        {
            Assume.NotNull("text", text);

            Text = text;
            TextRange = CreateOrGetTextRange(0, text.Length);
            _root = TextRange;
        }
			public DeclaredElementInfo([NotNull] IDeclaredElement declaredElement, [NotNull] ISubstitution substitution, [NotNull] IFile file,
				TextRange sourceRange, [CanBeNull] IReference reference) {
				DeclaredElement = declaredElement;
				Substitution = substitution;
				File = file;
				SourceRange = sourceRange;
				Reference = reference;
			}
        /// <summary>
        /// Initializes a new instance of the <see cref="CsvCompilationUnit"/> class.
        /// </summary>
        public CsvCompilationUnit(TextRange textRange, IEnumerable<RowDeclarationSyntax> rows)
            : base(textRange)
        {
            Assume.NotNull(rows, nameof(rows));

            Rows = rows;
            this.AttachChildren(rows);
        }
Exemple #16
0
 protected Element(KarmaServiceProvider serviceProvider, string name, ProjectModelElementEnvoy projectFileEnvoy, TextRange textRange)
 {
     ServiceProvider = serviceProvider;
     ShortName = name;
     ProjectFileEnvoy = projectFileEnvoy;
     TextRange = textRange;
     State = UnitTestElementState.Valid;
 }
        public override UnitTestElementDisposition GetDisposition()
        {
            var projectFile = GetProjectFile(Scenario.Location.Path);
            var contents = File.ReadAllText(Scenario.Location.Path);
            var range = new TextRange(LineToOffset(contents, Scenario.Location.FromLine), LineToOffset(contents, Scenario.Location.ToLine));

            return new UnitTestElementDisposition(this, projectFile, range, new TextRange(0));
        }
        /// <summary>
        /// Removes the text.
        /// </summary>
        /// <param name="textRange">The text range.</param>
        /// <returns></returns>
        public TextDocument RemoveText(TextRange textRange)
        {
            Assume.NotNull(textRange, "textRange");

            ChangeText(textRange, String.Empty);
            removeTextRange(textRange);

            return this;
        }
        /// <summary>
        /// Creates the document node 
        /// </summary>
        public ICsvTreeFactory CreateDocument(TextRange textRange)
        {
            Assume.NotNull(textRange, nameof(textRange));
            var csvCompilationUnit = new CsvCompilationUnit(textRange);

            _csvCompilationUnits.Push(csvCompilationUnit);

            return this;
        }
   public PostfixLookupItem(
 [NotNull] PostfixTemplateAcceptanceContext context,
 [NotNull] string shortcut, [NotNull] string replaceTemplate)
   {
       myShortcut = shortcut;
         myReplaceTemplate = replaceTemplate;
         myReplaceRange = context.ReplaceRange;
         myExpressionRange = context.ExpressionRange;
   }
        public RowDeclarationSyntax Row(TextRange textRange, IEnumerable<CommaToken> commas, IEnumerable<FieldDeclarationSyntax> fields)
        {
            Assume.NotNull(commas, nameof(commas));
            Assume.NotNull(fields, nameof(fields));

            return new RowDeclarationSyntax(textRange) {
                Commas = commas,
                Fields = fields
            };
        }
        /// <summary>
        /// Creates comma and appends it to actual row
        /// </summary>
        /// <param name="textRange">The text range.</param>
        public ICsvTreeFactory CreateComma(TextRange textRange)
        {
            Assume.NotNull(textRange, nameof(textRange));
            checkIsRowAdded();

            var comma = new CommaToken(textRange);
            addChildToLastDefinedRow(comma);

            return this;
        }
        /// <summary>
        /// Creates field and appends it to actual row
        /// </summary>
        public ICsvTreeFactory CreateField(TextRange textRange)
        {
            Assume.NotNull(textRange, nameof(textRange));
            checkIsRowAdded();

            var field = new FieldDeclarationSyntax(textRange);
            addChildToLastDefinedRow(field);

            return this;
        }
        public override UnitTestElementDisposition GetDisposition()
        {
            var projectFile = GetProjectFile(_path);

            var range = new TextRange(0, 0);
            var location = new UnitTestElementLocation(projectFile, range, range);

            var unitTestElementLocations = new[] { location };
            return new UnitTestElementDisposition(unitTestElementLocations, this);
        }
            protected override void DoApply(TextLayout layout, TextRange range)
            {
                Typography tp = new Typography(this.dwFactory);
                tp.AddFeature(new FontFeature()
                    {
                        NameTag = tag,
                        Value = 1
                    });

                layout.SetTypography(tp, range);
            }
        /// <summary>
        /// Creates the boolean constant.
        /// </summary>
        public JsonNode CreateBooleanConstant(TextRange textRange)
        {
            Assume.NotNull(textRange, nameof(textRange));
            var text = textRange.GetText();
            Boolean value;
            if (text == "false") value = false;
            else if (text == "true") value = true;
            else throw new NotSupportedException(String.Format("Invalid text of boolean constant: {0}.", text));

            return new BooleanConstant(value, textRange);
        }
        /// <summary>
        /// Creates the number constant.
        /// </summary>
        public JsonNode CreateNumberConstant(TextRange textRange)
        {
            Assume.NotNull(textRange, nameof(textRange));
            var text = textRange.GetText();
            Decimal value;

            if (!Decimal.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
                throw new NotSupportedException(String.Format("Not supported number format: {0}", text));

            return new NumberConstant(value, textRange);
        }
        public void PositionComparer_ShouldReturnZero_WhenTextRangesAreEqualByPosition()
        {
            // Given
            var firstTextRange = new TextRange(0, 5);
            var secondTextRange = new TextRange(0, 5);

            // When
            var result = TextRange.PositionComparer.Compare(firstTextRange, secondTextRange);

            // Then
            Assert.That(result, Is.EqualTo(0));
        }
        public void PositionComparer_ShouldReturnMinusOne_WhenTheSecondContainsTheFirstOne()
        {
            // Given
            var firstTextRange = new TextRange(1, 3);
            var secondTextRange = new TextRange(0, 5);

            // When
            var result = TextRange.PositionComparer.Compare(firstTextRange, secondTextRange);

            // Then
            Assert.That(result, Is.EqualTo(-1));
        }
        public void PositionComparer_ShouldReturnOne_WhenTheSecondTextRangeStopIsLesserThanTheFirstOne()
        {
            // Given
            var firstTextRange = new TextRange(0, 5);
            var secondTextRange = new TextRange(0, 3);

            // When
            var result = TextRange.PositionComparer.Compare(firstTextRange, secondTextRange);

            // Then
            Assert.That(result, Is.EqualTo(1));
        }
Exemple #31
0
        private void AppendText(FlowDocument document, IEnumerable <ILogMessage> logMessages)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }
            if (logTextBox != null && logMessages != null)
            {
                var paragraph        = (Paragraph)document.Blocks.AsEnumerable().First();
                var stringComparison = SearchMatchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
                var searchToken      = SearchToken;
                foreach (var message in logMessages.Where(x => ShouldDisplayMessage(x.Type)))
                {
                    var lineText = message + Environment.NewLine;
                    var logColor = GetLogColor(message.Type);
                    if (string.IsNullOrEmpty(searchToken))
                    {
                        paragraph.Inlines.Add(new Run(lineText)
                        {
                            Foreground = logColor
                        });
                    }
                    else
                    {
                        do
                        {
                            int tokenIndex = lineText.IndexOf(searchToken, stringComparison);
                            if (tokenIndex == -1)
                            {
                                paragraph.Inlines.Add(new Run(lineText)
                                {
                                    Foreground = logColor
                                });
                                break;
                            }
                            bool acceptResult = true;
                            if (SearchMatchWord && lineText.Length > 1)
                            {
                                if (tokenIndex > 0)
                                {
                                    char c = lineText[tokenIndex - 1];
                                    if ((c >= 'A' && c <= 'A') || (c >= 'a' && c <= 'z'))
                                    {
                                        acceptResult = false;
                                    }
                                }
                                if (tokenIndex + searchToken.Length < lineText.Length)
                                {
                                    char c = lineText[tokenIndex + searchToken.Length];
                                    if ((c >= 'A' && c <= 'A') || (c >= 'a' && c <= 'z'))
                                    {
                                        acceptResult = false;
                                    }
                                }
                            }

                            if (acceptResult)
                            {
                                if (tokenIndex > 0)
                                {
                                    paragraph.Inlines.Add(new Run(lineText.Substring(0, tokenIndex))
                                    {
                                        Foreground = logColor
                                    });
                                }

                                var tokenRun = new Run(lineText.Substring(tokenIndex, searchToken.Length))
                                {
                                    Background = SearchMatchBrush, Foreground = logColor
                                };
                                paragraph.Inlines.Add(tokenRun);
                                var tokenRange = new TextRange(tokenRun.ContentStart, tokenRun.ContentEnd);
                                searchMatches.Add(tokenRange);
                                lineText = lineText.Substring(tokenIndex + searchToken.Length);
                            }
                        } while (lineText.Length > 0);
                    }
                }
            }
        }
        private TextRange CreateTextRange()
        {
            var range = new TextRange(this.rtbContent.Selection.Start, this.rtbContent.Selection.End);

            return(range);
        }
Exemple #33
0
        /// <summary>
        /// Removes nodes from the tree collection if node range is
        /// // partially or entirely within the deleted region.
        /// This is needed since parsing is asynchronous and without
        /// removing damaged nodes so intellisense will still be able
        /// to find them in the tree which actually they are gone.
        /// Returns true if full parse required.
        /// </summary>
        /// <param name="node">Node to start from</param>
        /// <param name="range">Range to invalidate elements in</param>
        internal bool InvalidateInRange(IAstNode node, ITextRange range, out bool nodesChanged)
        {
            var  removedElements   = new List <IAstNode>();
            bool fullParseRequired = false;
            int  firstToRemove     = -1;
            int  lastToRemove      = -1;

            nodesChanged = false;

            for (int i = 0; i < node.Children.Count; i++)
            {
                var  child       = node.Children[i];
                bool removeChild = false;

                if (range.Start == child.Start && range.Length == 0)
                {
                    // Change is right before the node
                    break;
                }

                if (!removeChild && TextRange.Intersect(range, child))
                {
                    bool childElementsChanged;

                    if (child is TokenNode)
                    {
                        childElementsChanged = true;
                        fullParseRequired    = true;
                        nodesChanged         = true;
                    }
                    else
                    {
                        fullParseRequired |= InvalidateInRange(child, range, out childElementsChanged);
                        if (childElementsChanged)
                        {
                            nodesChanged = true;
                        }
                    }

                    removeChild = true;
                }

                if (removeChild)
                {
                    if (firstToRemove < 0)
                    {
                        firstToRemove = i;
                    }

                    lastToRemove = i;
                }
            }

            if (firstToRemove >= 0)
            {
                for (int i = firstToRemove; i <= lastToRemove; i++)
                {
                    IAstNode child = node.Children[i];
                    removedElements.Add(child);

                    _astRoot.Errors.RemoveInRange(child);
                }

                node.RemoveChildren(firstToRemove, lastToRemove - firstToRemove + 1);
            }

            if (removedElements.Count > 0)
            {
                nodesChanged = true;
                FireOnNodesRemoved(removedElements);
            }

            return(fullParseRequired);
        }
Exemple #34
0
        public static async Task FormatMessage(IGuildUser user, IMessage msg, IMessageChannel channel, RichTextBox rtb, System.Windows.Threading.Dispatcher Dispatcher, string text = null)
        {
            for (int i = 0; i < rtb.Document.Blocks.OfType <Paragraph>().Count(); i++)
            {
                Paragraph p  = rtb.Document.Blocks.OfType <Paragraph>().ElementAt(i) as Paragraph;
                TextRange tr = new TextRange(p.ContentStart, p.ContentEnd);
                foreach (KeyValuePair <string, GuildEmote> emote in DiscordWindow.AvailableEmotes)
                {
                    try
                    {
                        while (tr.Text.Contains(emote.Key))
                        {
                            Inline inline = (await Dispatcher.InvokeAsync(() => p.Inlines)).First(inl => new TextRange(inl.ContentStart, inl.ContentEnd).Text.Contains(emote.Key));
                            tr = new TextRange(inline.ContentStart, inline.ContentEnd);
                            while (tr.Text.Contains(emote.Key))
                            {
                                TextPointer tp = inline.ContentStart;
                                while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith(emote.Key))
                                {
                                    tp = await Dispatcher.InvokeAsync(() => tp.GetNextInsertionPosition(LogicalDirection.Forward));
                                }
                                tr = await Dispatcher.InvokeAsync(() => new TextRange(tp, tp.GetPositionAtOffset(emote.Key.Length)));

                                await Dispatcher.InvokeAsync(() =>
                                {
                                    tr.Text = "";
                                    System.Windows.Controls.Image img = new System.Windows.Controls.Image();
                                    img.Source  = Images.GetImage(emote.Value.Url);
                                    img.Stretch = Stretch.Uniform;
                                    img.Height  = 20;
                                    new InlineUIContainer(img, tp);
                                });

                                tr = new TextRange(p.ContentStart, p.ContentEnd);
                            }
                        }
                    }
                    catch { }
                }

                List <ulong> mentionedUserIds = new List <ulong>();
                mentionedUserIds.AddRange(msg.MentionedUserIds);

                if (text != null)
                {
                    string matches = Regex.Replace(text, "[^<>@!]", "");

                    if (ulong.TryParse(matches, out ulong id))
                    {
                        mentionedUserIds.Add(id);
                    }
                }

                foreach (ulong id in msg.MentionedUserIds)
                {
                    SocketGuildUser usr = (SocketGuildUser)App.DiscordWindow.Client.GetChannel(msg.Channel.Id).Users.FirstOrDefault(u => u.Id == id);
                    if (usr != null)
                    {
                        try
                        {
                            for (int j = 0; j < (await Dispatcher.InvokeAsync(() => p.Inlines)).Count; j++)
                            {
                                Inline inline = (await Dispatcher.InvokeAsync(() => p.Inlines)).ElementAt(j);
                                tr = new TextRange(inline.ContentStart, inline.ContentEnd);

                                TextPointer tp      = inline.ContentStart;
                                string      mention = "";
                                if (tr.Text.Contains(usr.Mention))
                                {
                                    mention = usr.Mention;
                                    while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith(usr.Mention))
                                    {
                                        tp = await Dispatcher.InvokeAsync(() => tp.GetNextInsertionPosition(LogicalDirection.Forward));
                                    }
                                    tr = await Dispatcher.InvokeAsync(() => new TextRange(tp, tp.GetPositionAtOffset(usr.Mention.Length)));

                                    await Dispatcher.InvokeAsync(() => tr.Text = "");
                                }
                                else if (tr.Text.Contains($"<@{usr.Id}>"))
                                {
                                    mention = $"<@{usr.Id}>";
                                    while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith(mention))
                                    {
                                        tp = await Dispatcher.InvokeAsync(() => tp.GetNextInsertionPosition(LogicalDirection.Forward));
                                    }
                                    tr = await Dispatcher.InvokeAsync(() => new TextRange(tp, tp.GetPositionAtOffset($"<@{usr.Id}>".Length)));

                                    await Dispatcher.InvokeAsync(() => tr.Text = "");
                                }

                                if (mention != "")
                                {
                                    await Dispatcher.InvokeAsync(async() =>
                                    {
                                        Run cont        = new Run($"@{Tools.Name(usr)}", tp);
                                        cont.FontWeight = FontWeights.SemiBold;
                                        cont.ToolTip    = new ToolTip();
                                        (cont.ToolTip as ToolTip).Content = $"@{usr.Username}#{usr.Discriminator} / {usr.Status}";
                                        cont.ContextMenu = await Tools.GetUserContextMenu(usr, rtb);
                                        cont.Style       = App.Current.Resources["mentionRun"] as Style;
                                        cont.PreviewMouseRightButtonDown += (s, e) => cont.ContextMenu.IsOpen = true;
                                        cont.PreviewMouseLeftButtonDown  += (s, e) => App.DiscordWindow.ShowUserDetails(usr, rtb);

                                        if (App.Config.General.UserColourMentions)
                                        {
                                            MediaColor?fg = Tools.GetUserColour(usr, user.Guild);
                                            if (fg.HasValue)
                                            {
                                                cont.Foreground         = new SolidColorBrush(fg.Value);
                                                cont.Background         = new SolidColorBrush(Tools.GetUserColour(usr, user.Guild).Value);
                                                cont.Background.Opacity = 0.33;
                                            }
                                            else
                                            {
                                                SolidColorBrush newBrush = App.ForegroundBrush;
                                                newBrush.Opacity         = 0.33;
                                                cont.Background          = newBrush;
                                            }
                                        }
                                        else
                                        {
                                            SolidColorBrush newBrush = App.ForegroundBrush;
                                            newBrush.Opacity         = 0.33;
                                            cont.Background          = newBrush;
                                        }
                                    });
                                }
                            }
                        }
                        catch { }
                    }
                }

                List <ulong> mentionedChannelIds = new List <ulong>();
                mentionedChannelIds.AddRange(msg.MentionedChannelIds);

                if (text != null)
                {
                    string matches = Regex.Replace(text, "[^<>#!]", "");

                    if (ulong.TryParse(matches, out ulong id))
                    {
                        mentionedChannelIds.Add(id);
                    }
                }

                foreach (ulong id in mentionedChannelIds)
                {
                    IMessageChannel mentioned = (await(channel as ITextChannel).Guild.GetTextChannelsAsync()).FirstOrDefault(u => u.Id == id);
                    if (mentioned != null)
                    {
                        try
                        {
                            for (int j = 0; j < (await Dispatcher.InvokeAsync(() => p.Inlines)).Count; j++)
                            {
                                Inline inline = (await Dispatcher.InvokeAsync(() => p.Inlines)).ElementAt(j);

                                tr = new TextRange(inline.ContentStart, inline.ContentEnd);

                                TextPointer tp = inline.ContentStart;
                                if (tr.Text.Contains($"<#{mentioned.Id}>"))
                                {
                                    while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith($"<#{mentioned.Id}>"))
                                    {
                                        tp = await Dispatcher.InvokeAsync(() => tp.GetNextInsertionPosition(LogicalDirection.Forward));
                                    }
                                    tr = await Dispatcher.InvokeAsync(() => new TextRange(tp, tp.GetPositionAtOffset($"<#{mentioned.Id}>".Length)));

                                    await Dispatcher.InvokeAsync(() =>
                                    {
                                        tr.Text                = "";
                                        Run userMention        = new Run($"#{mentioned.ToString()}", tp);
                                        userMention.FontWeight = FontWeights.SemiBold;
                                        userMention.Background = App.SecondaryBackgroundBrush;

                                        userMention.PreviewMouseLeftButtonDown += async(object s, MouseButtonEventArgs ev) =>
                                        {
                                            await App.DiscordWindow.Refresh(mentioned);
                                        };
                                    });
                                }
                            }
                        }
                        catch { }
                    }
                }

                foreach (ulong id in msg.MentionedRoleIds)
                {
                    IRole mentioned = (channel as ITextChannel).Guild.Roles.FirstOrDefault(u => u.Id == id);
                    if (mentioned != null)
                    {
                        try
                        {
                            for (int j = 0; j < (await Dispatcher.InvokeAsync(() => p.Inlines)).Count; j++)
                            {
                                Inline inline = (await Dispatcher.InvokeAsync(() => p.Inlines)).ElementAt(j);

                                tr = new TextRange(inline.ContentStart, inline.ContentEnd);

                                TextPointer tp = inline.ContentStart;
                                if (tr.Text.Contains($"<@&{mentioned.Id}>"))
                                {
                                    while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith($"<@&{mentioned.Id}>"))
                                    {
                                        tp = await Dispatcher.InvokeAsync(() => tp.GetNextInsertionPosition(LogicalDirection.Forward));
                                    }
                                    tr = await Dispatcher.InvokeAsync(() => new TextRange(tp, tp.GetPositionAtOffset($"<@&{mentioned.Id}>".Length)));

                                    await Dispatcher.InvokeAsync(() =>
                                    {
                                        tr.Text                = "";
                                        Run userMention        = new Run($"@{mentioned.ToString()}", tp);
                                        userMention.FontWeight = FontWeights.SemiBold;
                                        userMention.Style      = App.Current.Resources["mentionRun"] as Style;

                                        userMention.Background = System.Windows.Media.Brushes.Transparent;

                                        if (mentioned.Color.RawValue != Discord.Color.Default.RawValue)
                                        {
                                            userMention.Foreground         = new SolidColorBrush(MediaColor.FromRgb(mentioned.Color.R, mentioned.Color.G, mentioned.Color.B));
                                            userMention.Background         = new SolidColorBrush(MediaColor.FromRgb(mentioned.Color.R, mentioned.Color.G, mentioned.Color.B));
                                            userMention.Background.Opacity = 0.33;
                                        }
                                    });
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
        }
Exemple #35
0
        public virtual IList <ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            List <ClassificationSpan> classifications = new List <ClassificationSpan>();

            if (_suspended)
            {
                return(classifications);
            }

            ITextSnapshot textSnapshot = TextBuffer.CurrentSnapshot;

            if (span.Length <= 2)
            {
                string ws = textSnapshot.GetText(span);
                if (String.IsNullOrWhiteSpace(ws))
                {
                    return(classifications);
                }
            }

            // Token collection at this point contains valid tokens at least to a point
            // of the most recent change. We can reuse existing tokens but may also need
            // to tokenize to get tokens for the recently changed range.
            if (span.End > _lastValidPosition)
            {
                // Span is beyond the last position we know about. We need to tokenize new area.
                // tokenize from end of the last good token. If last token intersected last change
                // it would have been removed from the collection by now.

                int tokenizeFrom   = Tokens.Count > 0 ? Tokens[Tokens.Count - 1].End : new SnapshotPoint(textSnapshot, 0);
                var tokenizeAnchor = GetAnchorPosition(tokenizeFrom);

                if (tokenizeAnchor < tokenizeFrom)
                {
                    Tokens.RemoveInRange(TextRange.FromBounds(tokenizeAnchor, span.End));
                    RemoveSensitiveTokens(tokenizeAnchor, Tokens);

                    tokenizeFrom = tokenizeAnchor;
                    VerifyTokensSorted();
                }

                var newTokens = Tokenizer.Tokenize(new TextProvider(TextBuffer.CurrentSnapshot), tokenizeFrom, span.End - tokenizeFrom);
                if (newTokens.Count > 0)
                {
                    Tokens.Add(newTokens);
                    _lastValidPosition = newTokens[newTokens.Count - 1].End;
                }
            }

            var tokensInSpan = Tokens.ItemsInRange(TextRange.FromBounds(span.Start, span.End));

            foreach (var token in tokensInSpan)
            {
                var compositeToken = token as ICompositeToken;

                if (compositeToken != null)
                {
                    AddClassificationFromCompositeToken(classifications, textSnapshot, compositeToken);
                }
                else
                {
                    AddClassificationFromToken(classifications, textSnapshot, token);
                }
            }

            return(classifications);
        }
        /// <summary>
        /// Handles the mouse press and the associated code.
        /// </summary>
        /// <param name="point">The point.</param>
        /// <param name="button">The button.</param>
        /// <param name="modifier">The state.</param>
        /// <param name="eventType">The event type that triggered the press.</param>
        /// <returns>If handled, <see langword="true"/>. Otherwise,
        /// <see langword="false"/>.</returns>
        public bool HandleMousePress(
            PointD point,
            uint button,
            ModifierType modifier,
            EventType eventType)
        {
            // If we don't have a buffer, we don't do anything.
            if (displayContext.Renderer == null)
            {
                return(false);
            }

            // If we are pressing the left button (button 1) then we move the caret
            // over. If we are pressing the right button, we only change the position
            // if we don't already have a selection.
            if (button == 1 ||
                (button == 3 && displayContext.Caret.Selection.IsEmpty))
            {
                // Figure out if we are clicking inside the text area.
                if (point.X >= displayContext.TextX)
                {
                    // Figure out text-relative coordinates.
                    var textPoint = new PointD(point.X - displayContext.TextX, point.Y);

                    // Grab the anchor position of the selection since that will
                    // remain the same after the command.
                    Caret     caret             = displayContext.Caret;
                    TextRange previousSelection = caret.Selection;

                    // Keep track of the selection so we can drag-select.
                    if (button == 1)
                    {
                        inTextSelect          = true;
                        previousTextSelection = previousSelection;
                    }

                    // Mark that we are starting a new action and fire events so
                    // other listeners and handle it.
                    InAction = true;

                    // Perform the appropriate action.
                    try
                    {
                        switch (eventType)
                        {
                        case EventType.TwoButtonPress:
                            MoveActions.SelectWord(this);
                            break;

                        case EventType.ThreeButtonPress:
                            MoveActions.SelectLine(this);
                            break;

                        default:
                            MoveActions.Point(this, textPoint);
                            break;
                        }
                    }
                    finally
                    {
                        InAction = false;
                    }

                    // If we are holding down the shift-key, then we want to
                    // restore the previous selection anchor.
                    if ((modifier & ModifierType.ShiftMask) == ModifierType.ShiftMask)
                    {
                        // Restore the anchor position which will extend the selection back.
                        displayContext.Caret.Selection =
                            new TextRange(
                                previousSelection.FirstTextPosition,
                                displayContext.Caret.Selection.LastTextPosition);

                        // Check to see if the selection changed.
                        if (previousSelection != displayContext.Caret.Selection)
                        {
                            displayContext.Renderer.UpdateSelection(
                                displayContext, previousSelection);
                        }
                    }
                    else if (!previousSelection.IsEmpty)
                    {
                        displayContext.Renderer.UpdateSelection(displayContext, previousSelection);
                    }

                    // Redraw the widget.
                    displayContext.RequestRedraw(displayContext.Caret.GetDrawRegion());
                }
            }

            // If we are pressing the right mouse, then show the context menu.
            if (button == 3)
            {
                // Create the context menu for this position.
                Menu contextMenu = CreateContextMenu();

                // Attach the menu and show it to the user.
                if (contextMenu != null)
                {
                    contextMenu.AttachToWidget((EditorView)displayContext, null);
                    contextMenu.Popup();
                    contextMenu.ShowAll();
                }
            }

            // We haven't handled it, so return false so the rest of Gtk can
            // decide what to do with the input.
            return(false);
        }
Exemple #37
0
        /// <summary>
        /// Search in the rich text the value entered in the search textbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void f_searchButton_Click(object sender, RoutedEventArgs e)
        {
            // Get all text
            TextRange v_textRange = new TextRange(f_RichTextBox.Document.ContentStart, f_RichTextBox.Document.ContentEnd);

            // Setting the default color of the text
            v_textRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
            v_textRange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Transparent);

            // If the rich text and the search textbox are not empty
            if (!string.IsNullOrWhiteSpace(v_textRange.Text) && !string.IsNullOrEmpty(f_searchText.Text))
            {
                // Sets the number of iterations
                m_wordNumber = Tools.Search(v_textRange.Text, f_searchText.Text);
                int v_textFoundNumber = 0;

                // Enables arrows depending on the number of results
                bool v_wordFound = m_wordNumber > 0;
                f_nextWord.IsEnabled     = v_wordFound;
                f_previousWord.IsEnabled = v_wordFound;

                // Sets the pointer
                if (v_wordFound)
                {
                    m_wordNumberPointer = 1;
                    v_textFoundNumber   = 1;
                }
                else
                {
                    m_wordNumberPointer = 0;
                }

                // Highlights the searched text
                IEnumerable <TextRange> v_wordRanges = Tools.GetAllWordRanges(f_RichTextBox.Document, f_searchText.Text);
                m_correctWordRanges = new List <TextRange>();

                // For each text found
                foreach (TextRange wordRange in v_wordRanges)
                {
                    // Adds to the correct TextRange
                    if (string.Equals(wordRange.Text, f_searchText.Text, StringComparison.CurrentCultureIgnoreCase))
                    {
                        m_correctWordRanges.Add(wordRange);
                    }
                }

                // Colors depending on the rank in the text
                foreach (TextRange v_wordRange in m_correctWordRanges)
                {
                    // Colors the word depending on its number
                    Tools.StyleTextDependingOnRank(v_wordRange, v_textFoundNumber, 1, Brushes.LightGreen, Brushes.LightBlue);
                    ++v_textFoundNumber;
                }

                // Displays the number of iterations found
                f_searchNumber.Content = string.Concat(m_wordNumberPointer, " / ", m_wordNumber);
            }
            else if (string.IsNullOrEmpty(f_searchText.Text))
            {
                // No text to search
                MessageBox.Show("Aucun texte à chercher !", "Aucun texte à chercher", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        public ChangeInLinesInfo GetChangeInLines(IReadOnlyList <VisualTextLine> lines, TextRange range)
        {
            var orderedRanges = (new[] { range.StartPosition, range.EndPosition }).OrderBy(elem => elem.Line).ThenBy(elem => elem.Column).ToArray();
            var pair          = new TextRange {
                StartPosition = orderedRanges[0],
                EndPosition   = orderedRanges[1]
            };
            var rangeEnd = -1;

            if (pair.StartPosition.Line == pair.EndPosition.Line)
            {
                rangeEnd = pair.EndPosition.Line;
            }
            else
            {
                rangeEnd = pair.EndPosition.Line + 1;
            }

            var firstPart  = Cut(lines[pair.StartPosition.Line], 0, pair.StartPosition.Column);
            var secondPart = Cut(lines[pair.EndPosition.Line], pair.EndPosition.Column);

            return(new ChangeInLinesInfo {
                LinesToChange = new Dictionary <TextPosition, VisualTextLine> {
                    [new TextPosition(pair.StartPosition.Column, pair.StartPosition.Line)] =
                        VisualTextLine.MergeLines(new[] { firstPart, secondPart }, firstPart.Index)
                },
                LinesToRemove = Enumerable.Range(pair.StartPosition.Line, rangeEnd).ToList()
            });
        }
Exemple #39
0
        private bool IsCaretPositionValid()
        {
            var text = new TextRange(richTextBox1.CaretPosition, richTextBox1.CaretPosition.DocumentEnd).Text;

            return(!text.Contains(">"));
        }
Exemple #40
0
        private void richTextBox1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (lstOptions.Visibility == Visibility.Visible)
            {
                if (e.Key == Key.Escape)
                {
                    this.HideOptions();
                }
                else
                {
                    lstOptions.Focus();
                }
                return;
            }

            if (!IsCaretPositionValid())
            {
                this.richTextBox1.CaretPosition = this.richTextBox1.CaretPosition.DocumentEnd;
                return;
            }

            if (e.Key == Key.Space)
            {
                var command = new TextRange(richTextBox1.CaretPosition.GetLineStartPosition(0),
                                            richTextBox1.CaretPosition).Text;
                command = command.Substring(command.IndexOf(">") + 1).Trim();
                ShowOptions(command);
                return;
            }

            if (e.Key == Key.Enter)
            {
                var command = GetCommand();
                if (this.IsProcessRunning)
                {
                    this.WriteInput(command);
                }
                else
                {
                    RunCommand(command);
                    e.Handled = true;
                }
            }
            else if (e.Key == Key.Up)
            {
                GetCommand(--commandIdx);
                e.Handled = true;
            }
            else if (e.Key == Key.Down)
            {
                GetCommand(++commandIdx);
                e.Handled = true;
            }
            else if (e.Key == Key.Escape)
            {
                ChangePrompt("", BRUSH_PROMPT);
                this.HideOptions();
            }
            else if (e.Key == Key.Back)
            {
                var text = new TextRange(richTextBox1.CaretPosition.GetLineStartPosition(0),
                                         richTextBox1.CaretPosition).Text;
                if (text.EndsWith(">") && text.IndexOf(">") == text.Length - 1)
                {
                    e.Handled = true;
                }
            }
            else if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
            {
                if (IsProcessRunning)
                {
                    SendShutdownToConsole();
                    e.Handled = true;
                }
            }
            else if (lstOptions.Visibility == Visibility.Visible)
            {
                //lstOptions.KeyDown()
            }
        }
Exemple #41
0
 protected Element(KarmaServiceProvider serviceProvider, string name, ProjectModelElementEnvoy projectFileEnvoy, TextRange textRange)
 {
     ServiceProvider  = serviceProvider;
     ShortName        = name;
     ProjectFileEnvoy = projectFileEnvoy;
     TextRange        = textRange;
     State            = UnitTestElementState.Valid;
 }
Exemple #42
0
        private static MiscTooltipContent TryCreateMiscContent([CanBeNull] RichTextBlock textBlock, TextRange range)
        {
            if (textBlock == null)
            {
                return(null);
            }

            RichText text = textBlock.RichText;

            if (text.IsEmpty)
            {
                return(null);
            }

            return(new MiscTooltipContent(text, range));
        }
Exemple #43
0
        private static IssueTooltipContent TryCreateIssueContent([NotNull] IHighlighting highlighting, TextRange trackingRange,
                                                                 [CanBeNull] RichTextBlock textBlock, Severity severity, [NotNull] IContextBoundSettingsStore settings, [CanBeNull] ISolution solution)
        {
            if (textBlock == null || !severity.IsIssue())
            {
                return(null);
            }

            RichText text = textBlock.RichText;

            if (text.IsEmpty)
            {
                return(null);
            }

            if (settings.GetValue((IssueTooltipSettings s) => s.ColorizeElementsInErrors))
            {
                RichText enhancedText = TryEnhanceHighlighting(highlighting, settings, solution);
                if (!enhancedText.IsNullOrEmpty())
                {
                    text = enhancedText;
                }
            }

            var issueContent = new IssueTooltipContent(text, trackingRange);

            if (settings.GetValue((IssueTooltipSettings s) => s.ShowIcon))
            {
                issueContent.Icon = severity.TryGetIcon();
            }
            return(issueContent);
        }
Exemple #44
0
        public void rdbSingleUserRepinByKeyword()
        {
            try
            {
                objRepinByKeywordManager.rdbSingleUserRepinByKeyword   = true;
                objRepinByKeywordManager.rdbMultipleUserRepinByKeyword = false;
                btnKeyword_RepinByKeyword_Browse.Visibility            = Visibility.Hidden;
                btnMessage_RepinByKeyword_Browse.Visibility            = Visibility.Hidden;
                txtKeywordBoard.Visibility                   = Visibility.Hidden;
                txtMessage_RepinByKeyword.Visibility         = Visibility.Hidden;
                lbBoardWithKeyword_RepinByKeyword.Visibility = Visibility.Hidden;
                lblMessage_RepinByKeyword.Visibility         = Visibility.Hidden;
                lblHints_RepinByKeyword.Visibility           = Visibility.Hidden;

                ClGlobul.lstRepinByKeyword.Clear();
                ClGlobul.lstMsgRepinByKeyword.Clear();
                #region BoardUrl
                try
                {
                    UserControl_SingleUser obj = new UserControl_SingleUser();
                    obj.UserControlHeader.Text         = "Enter BoardName and Keyword Here ";
                    obj.txtEnterSingleMessages.ToolTip = "Format :- Niche::BoardName::Keyword";
                    var window = new ModernDialog
                    {
                        Content = obj
                    };
                    window.ShowInTaskbar = true;
                    window.MinWidth      = 100;
                    window.MinHeight     = 300;
                    Button customButton = new Button()
                    {
                        Content = "SAVE"
                    };
                    customButton.Click += (ss, ee) => { closeEvent(); window.Close(); };
                    window.Buttons      = new Button[] { customButton };

                    window.ShowDialog();

                    MessageBoxButton btnC = MessageBoxButton.YesNo;
                    var result            = ModernDialog.ShowMessage("Are you sure want to save ?", "Message Box", btnC);

                    if (result == MessageBoxResult.Yes)
                    {
                        TextRange textRange = new TextRange(obj.txtEnterSingleMessages.Document.ContentStart, obj.txtEnterSingleMessages.Document.ContentEnd);

                        if (!string.IsNullOrEmpty(textRange.Text))
                        {
                            string   enterText = textRange.Text;
                            string[] arr       = Regex.Split(enterText, "\r\n");

                            foreach (var arr_item in arr)
                            {
                                if (!string.IsNullOrEmpty(arr_item) || !arr_item.Contains(""))
                                {
                                    ClGlobul.lstRepinByKeyword.Add(arr_item);
                                }
                            }
                        }
                        GlobusLogHelper.log.Info(" => [ BoardName and BoardUrl with Niche Loaded : " + ClGlobul.lstRepinByKeyword.Count + " ]");
                        GlobusLogHelper.log.Debug("BoardName and BoardUrl with Niche : " + ClGlobul.lstRepinByKeyword.Count);
                    }
                }
                catch (Exception ex)
                {
                    GlobusLogHelper.log.Error(" Error :" + ex.StackTrace);
                }
                #endregion

                SingleUserMessageRepinByKeyword();
            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Error(" Error :" + ex.StackTrace);
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Topmost  = false;
            errorOccurred = false;
            TextRange _text = new TextRange(comments.Document.ContentStart, comments.Document.ContentEnd);
            String    cmt   = _text.Text;

            cmt = cmt.Remove(cmt.Length - 2);
            try
            {
                String sql = "EXEC SearchBaghVillaFSimple N'" + address_Txt.Text + "',N'" + area_Low.Text + "',N'"
                             + area_High.Text + "',N'" + owner.Text + "',N'"
                             + MyPriceTextBox.getStringFromMasked(price_Low.Text) + "',N'"
                             + MyPriceTextBox.getStringFromMasked(price_High.Text) + "',N'" + cmt + "'";

                DataTable dt = DB.execSqlReturnDataTable(sql, DBComboBox.SelectedIndex);

                if (Show3D_checkBox.IsChecked == true)
                {
                    Result3D res3d = new Result3D();
                    res3d.dt = dt;
                    res3d.Show();
                }
                else
                {
                    ResultWindow res = new ResultWindow();
                    res.session = session;
                    res.which   = Codes.BaghVillaForooshi;

                    res.dt = dt.Copy();
                    if (cols == null)
                    {
                        cols = new string[dt.Columns.Count];
                        for (int i = 0; i < cols.Length; i++)
                        {
                            cols[i] = dt.Columns[i].ColumnName;
                        }
                    }
                    for (int i = 1; i < cols.Length; i++)
                    {
                        if (i == 2 || i == 24)
                        {
                            continue;
                        }
                        if ((area_Low.Text.Trim().Length != 0 || area_High.Text.Trim().Length != 0) && i == 3)
                        {
                            continue;
                        }
                        if (owner.Text.Trim().Length != 0 && i == 20)
                        {
                            continue;
                        }
                        dt.Columns.Remove(cols[i]);
                    }
                    res.gridView.DataSource = dt;
                    res.dbIndex             = DBComboBox.SelectedIndex;
                    res.Show();
                }
            }
            catch (Exception)
            {
                errorOccurred = true;
                MessageBox.Show("خطا در اتصال و یا اجرای درخواست از پایگاه داده ها", "خطا", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #46
0
        private void LoadNotes()
        {
            var count = 0;

            if (File.Exists("NotesFile"))
            {
                var fs = new FileStream("NotesFile", FileMode.Open);
                if (fs != null)
                {
                    int      contentIndicator;
                    double   height;
                    double   width;
                    double   x;
                    double   y;
                    bool     topmost;
                    int      backgroundColorIndex;
                    int      foregroundColorIndex;
                    DateTime alarmTime;
                    string   loadRepeatNumber;

                    var reader = new StreamReader(fs);
                    var str    = reader.ReadLine();
                    ExtractValues(out contentIndicator, str, out height, out width, out x, out y, out topmost,
                                  out backgroundColorIndex,
                                  out foregroundColorIndex, out alarmTime, out loadRepeatNumber);
                    AppWindow.Height  = height;
                    AppWindow.Width   = width;
                    AppWindow.Top     = y;
                    AppWindow.Left    = x;
                    AppWindow.Topmost = topmost;

                    count = contentIndicator;
                    for (var i = 0; i < count; i++)
                    {
                        var line = reader.ReadLine();

                        ExtractValues(out contentIndicator, line, out height, out width, out x, out y, out topmost,
                                      out backgroundColorIndex, out foregroundColorIndex, out alarmTime, out loadRepeatNumber);

                        var filename = i.ToString();
                        filename = filename.Trim();

                        var w2 = new Window2
                        {
                            Title         = "Sticky Note",
                            Tag           = ArrayPos,
                            Height        = height,
                            Width         = width,
                            Left          = x,
                            Top           = y,
                            ShowInTaskbar = false,
                            Topmost       = topmost,
                            TopmostWindow = topmost
                        };

                        if (w2.Topmost)
                        {
                            try
                            {
                                var m = LogicalTreeHelper.FindLogicalNode(w2, "AlwaysOnTop") as MenuItem;
                                m.IsChecked = true;
                            }
                            catch (Exception)
                            {
                            }
                        }
                        if (backgroundColorIndex > -1)
                        {
                            w2.Background           = Window2.ChangeBackgroundColor(Dialog.ColorArray[backgroundColorIndex]);
                            w2.BackgroundColorIndex = backgroundColorIndex;
                        }
                        if (foregroundColorIndex > -1)
                        {
                            w2.Foreground           = Dialog.ColorArrayForeground[foregroundColorIndex];
                            w2.ForegroundColorIndex = foregroundColorIndex;
                        }
                        w2.Alarm            = alarmTime;
                        w2.RepetitionNumber = loadRepeatNumber.Contains("null") ? "null" : loadRepeatNumber;


                        CheckIfAlarmFires(w2);

                        WindowArray[ArrayPos] = w2;
                        ArrayPos++;

                        var noteFiles = new FileStream(filename, FileMode.Open);

                        var rtb = ((RichTextBox)((StackPanel)(w2.Content)).Children[1]);
                        var tr  = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
                        try
                        {
                            tr.Load(noteFiles, contentIndicator == 0 ? DataFormats.XamlPackage : DataFormats.Xaml);
                        }
                        catch (Exception)
                        {
                        }
                        noteFiles.Close();
                    }
                    fs.Close();
                }
            }
            for (var i = ++count; i < 100; i++)
            {
                if (File.Exists(i.ToString()))
                {
                    File.Delete(i.ToString());
                }
            }
        }
        private void addTable(Section section)
        {
            String[]   header = { "Name", "Capital", "Continent", "Area", "Population" };
            String[][] data   =
            {
                new String[] { "Argentina",                "Buenos Aires", "South America", "2777815", "32300003"  },
                new String[] { "Bolivia",                  "La Paz",       "South America", "1098575", "7300000"   },
                new String[] { "Brazil",                   "Brasilia",     "South America", "8511196", "150400000" },
                new String[] { "Canada",                   "Ottawa",       "North America", "9976147", "26500000"  },
                new String[] { "Chile",                    "Santiago",     "South America", "756943",  "13200000"  },
                new String[] { "Colombia",                 "Bagota",       "South America", "1138907", "33000000"  },
                new String[] { "Cuba",                     "Havana",       "North America", "114524",  "10600000"  },
                new String[] { "Ecuador",                  "Quito",        "South America", "455502",  "10600000"  },
                new String[] { "El Salvador",              "San Salvador", "North America", "20865",   "5300000"   },
                new String[] { "Guyana",                   "Georgetown",   "South America", "214969",  "800000"    },
                new String[] { "Jamaica",                  "Kingston",     "North America", "11424",   "2500000"   },
                new String[] { "Mexico",                   "Mexico City",  "North America", "1967180", "88600000"  },
                new String[] { "Nicaragua",                "Managua",      "North America", "139000",  "3900000"   },
                new String[] { "Paraguay",                 "Asuncion",     "South America", "406576",  "4660000"   },
                new String[] { "Peru",                     "Lima",         "South America", "1285215", "21600000"  },
                new String[] { "United States of America", "Washington",   "North America", "9363130", "249200000" },
                new String[] { "Uruguay",                  "Montevideo",   "South America", "176140",  "3002000"   },
                new String[] { "Venezuela",                "Caracas",      "South America", "912047",  "19700000"  }
            };
            Spire.Doc.Table table = section.AddTable(true);
            table.ResetCells(data.Length + 1, header.Length);

            // ***************** First Row *************************
            TableRow row = table.Rows[0];

            row.IsHeader            = true;
            row.Height              = 20; //unit: point, 1point = 0.3528 mm
            row.HeightType          = TableRowHeightType.Exactly;
            row.RowFormat.BackColor = Color.Gray;
            for (int i = 0; i < header.Length; i++)
            {
                row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                Paragraph p = row.Cells[i].AddParagraph();
                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                TextRange txtRange = p.AppendText(header[i]);
                txtRange.CharacterFormat.Bold = true;
            }

            for (int r = 0; r < data.Length; r++)
            {
                TableRow dataRow = table.Rows[r + 1];
                dataRow.Height              = 20;
                dataRow.HeightType          = TableRowHeightType.Exactly;
                dataRow.RowFormat.BackColor = Color.Empty;
                for (int c = 0; c < data[r].Length; c++)
                {
                    dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    dataRow.Cells[c].AddParagraph().AppendText(data[r][c]);
                }
            }

            for (int j = 1; j < table.Rows.Count; j++)
            {
                if (j % 2 == 0)
                {
                    TableRow row2 = table.Rows[j];
                    for (int f = 0; f < row2.Cells.Count; f++)
                    {
                        row2.Cells[f].CellFormat.BackColor = Color.LightBlue;
                    }
                }
            }
        }
Exemple #48
0
        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            var contentIndicator = new string[ArrayPos];

            var index = 0;

            for (var i = 0; i < ArrayPos; i++)
            {
                if (WindowArray[i] != null)
                {
                    var w   = ((Window2)(WindowArray[i]));
                    var rtb = ((RichTextBox)(((StackPanel)(w.Content)).Children[1]));
                    var tr  = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);

                    var mstream = new MemoryStream();
                    XamlWriter.Save(rtb.Document, mstream);
                    mstream.Seek(0, SeekOrigin.Begin);
                    var stringReader = new StreamReader(mstream);
                    var str          = stringReader.ReadToEnd();
                    stringReader.Close();

                    var fs     = new FileStream(index.ToString(), FileMode.Create);
                    var width  = (w.ActualWidth > 50) ? (w.ActualWidth) : 200;
                    var height = (w.ActualHeight > 60) ? w.ActualHeight : 200;
                    if (str.Contains("payload"))
                    {
                        contentIndicator[index] = "0 |" + w.Top + "|" + w.Left + "|" +
                                                  height + "|" +
                                                  width + "|" + w.Topmost +
                                                  "|" + w.BackgroundColorIndex + "|" +
                                                  w.ForegroundColorIndex + "|" +
                                                  w.Alarm.TimeOfDay + "|" + w.Alarm.Date.ToShortDateString() +
                                                  "|" + w.RepetitionNumber;
                        tr.Save(fs, DataFormats.XamlPackage);
                    }
                    else
                    {
                        contentIndicator[index] = "1 |" + w.Top + "|" + w.Left + "|" +
                                                  height + "|" +
                                                  width + "|" + w.Topmost +
                                                  "|" + w.BackgroundColorIndex + "|" +
                                                  w.ForegroundColorIndex + "|" +
                                                  w.Alarm.TimeOfDay + "|" + w.Alarm.Date.ToShortDateString() +
                                                  "|" + w.RepetitionNumber;
                        tr.Save(fs, DataFormats.Xaml);
                    }
                    index++;
                    fs.Close();
                    ((Window2)(WindowArray[i])).Close();
                }
            }

            if (File.Exists("NotesFile"))
            {
                File.Delete("NotesFile");
            }
            var mainDataFile = new FileStream("NotesFile", FileMode.OpenOrCreate);
            var writer       = new StreamWriter(mainDataFile);

            writer.WriteLine(index + "|" + AppWindow.Top + "|" + AppWindow.Left + "|" +
                             AppWindow.ActualHeight + "|" + AppWindow.ActualWidth + "|" +
                             AppWindow.Topmost + "|-1" + "|-1" + "|" + DateTime.Now.TimeOfDay +
                             "|" +
                             DateTime.Now.Date.ToShortDateString() + "|null");
            for (var i = 0; i < index; i++)
            {
                writer.WriteLine(contentIndicator[i]);
            }
            writer.Close();
            mainDataFile.Close();
        }
Exemple #49
0
        static internal void doInsertHtmlCloseTag(char newChar)
        {
            LangType docType = LangType.L_TEXT;

            Win32.SendMessage(PluginBase.nppData._nppHandle, (uint)NppMsg.NPPM_GETCURRENTLANGTYPE, 0, ref docType);
            bool isDocTypeHTML = (docType == LangType.L_HTML || docType == LangType.L_XML || docType == LangType.L_PHP);

            if (!doCloseTag || !isDocTypeHTML)
            {
                return;
            }

            if (newChar != '>')
            {
                return;
            }

            int bufCapacity = 512;
            var pos         = editor.GetCurrentPos();
            int currentPos  = pos.Value;
            int beginPos    = currentPos - (bufCapacity - 1);
            int startPos    = (beginPos > 0) ? beginPos : 0;
            int size        = currentPos - startPos;

            if (size < 3)
            {
                return;
            }

            using (TextRange tr = new TextRange(startPos, currentPos, bufCapacity))
            {
                editor.GetTextRange(tr);
                string buf = tr.lpstrText;

                if (buf[size - 2] == '/')
                {
                    return;
                }

                int pCur = size - 2;
                while ((pCur > 0) && (buf[pCur] != '<') && (buf[pCur] != '>'))
                {
                    pCur--;
                }

                if (buf[pCur] == '<')
                {
                    pCur++;

                    var insertString = new StringBuilder("</");

                    while (regex.IsMatch(buf[pCur].ToString()))
                    {
                        insertString.Append(buf[pCur]);
                        pCur++;
                    }
                    insertString.Append('>');

                    if (insertString.Length > 3)
                    {
                        editor.BeginUndoAction();
                        editor.ReplaceSel(insertString.ToString());
                        editor.SetSel(pos, pos);
                        editor.EndUndoAction();
                    }
                }
            }
        }
Exemple #50
0
        public static void Clear(this RichTextBox textBox)
        {
            TextRange textRange = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);

            textRange.Text = "";
        }
Exemple #51
0
        protected virtual void OnTextChanged(int start, int oldLength, int newLength)
        {
            // Invalidate items starting from start of the change and onward

            // Expand range to take into accound token that might be just touching
            // changed area. For example, in PHP / is punctuation token and adding *
            // to it should remove / so tokenizer can recreate comment token.
            // However / is technically outside of the changed area and hence may end up
            // lingering on.

            int initialIndex = -1;
            int changeStart  = start;

            var touchingTokens = Tokens.GetItemsContainingInclusiveEnd(start);

            if (touchingTokens != null && touchingTokens.Count > 0)
            {
                initialIndex = touchingTokens.Min();
                start        = Tokens[initialIndex].Start;
            }

            // nothing is touching but we still might have tokens right after us
            if (initialIndex < 0)
            {
                initialIndex = Tokens.GetFirstItemAfterOrAtPosition(start);
            }

            if (initialIndex == 0)
            {
                start = Tokens[0].Start;
            }
            else
            {
                while (initialIndex > 0)
                {
                    if (Tokens[initialIndex - 1].End == start)
                    {
                        start = Tokens[initialIndex - 1].Start;
                        initialIndex--;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            _lastValidPosition = Math.Min(_lastValidPosition, start);
            if (Tokens.Count > 0)
            {
                Tokens.RemoveInRange(TextRange.FromBounds(_lastValidPosition, Tokens[Tokens.Count - 1].End), true);
            }

            // In line-based tokenizers like SaSS or Jade we need to start at the beginning
            // of the line i.e. at 'anchor' position that is calculated depending on
            // the particular language syntax.

            _lastValidPosition = GetAnchorPosition(_lastValidPosition);
            RemoveSensitiveTokens(_lastValidPosition, Tokens);
            VerifyTokensSorted();
            _lastValidPosition = Tokens.Count > 0 ? Math.Min(_lastValidPosition, Tokens[Tokens.Count - 1].End) : 0;

            ClassificationChanged?.Invoke(this, new ClassificationChangedEventArgs(
                                              new SnapshotSpan(TextBuffer.CurrentSnapshot, Span.FromBounds(_lastValidPosition, TextBuffer.CurrentSnapshot.Length)))
                                          );
        }
Exemple #52
0
        public static string GetText(this RichTextBox textBox)
        {
            TextRange textRange = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);

            return(textRange.Text);
        }
Exemple #53
0
        public DocumentNode EvaluateResourceAndCollectionPath(DocumentNodePath nodePath, ResourceReferenceType referenceType, DocumentNode keyNode, ICollection <DocumentCompositeNode> resourcesHostNodePath, ICollection <IDocumentRoot> relatedRoots, ICollection <string> warnings, out bool invalidForwardReference)
        {
            Uri           uri;
            DocumentNode  documentNode;
            IDocumentRoot applicationRoot;
            IDocumentRoot documentRoot = nodePath.RootNode.DocumentRoot;

            if (this.documentRootResolver != null)
            {
                applicationRoot = this.documentRootResolver.ApplicationRoot;
            }
            else
            {
                applicationRoot = null;
            }
            IDocumentRoot documentRoot1 = applicationRoot;
            bool          flag          = (documentRoot1 == null ? false : documentRoot1.RootNode != null);
            IDocumentRoot documentRoot2 = null;

            invalidForwardReference = false;
            if (referenceType != ResourceReferenceType.Static)
            {
                DocumentNode node = nodePath.Node;
                while (node != null)
                {
                    if (flag && node.DocumentRoot != null && node == node.DocumentRoot.RootNode && PlatformTypes.ResourceDictionary.IsAssignableFrom(node.Type))
                    {
                        string documentUrl             = node.Context.DocumentUrl;
                        DocumentCompositeNode rootNode = documentRoot1.RootNode as DocumentCompositeNode;
                        if (rootNode != null && Uri.TryCreate(documentUrl, UriKind.Absolute, out uri) && ResourceNodeHelper.FindReferencedDictionaries(rootNode).Contains <Uri>(uri))
                        {
                            documentRoot2 = node.DocumentRoot;
                            break;
                        }
                    }
                    DocumentNode documentNode1 = this.EvaluateResourceAtSpecificNode(node, keyNode, resourcesHostNodePath, relatedRoots, warnings);
                    if (documentNode1 != null)
                    {
                        return(documentNode1);
                    }
                    node = node.Parent;
                    if (node == null || nodePath == null)
                    {
                        continue;
                    }
                    DocumentNode containerNode  = nodePath.ContainerNode;
                    DocumentNode styleForSetter = ExpressionEvaluator.GetStyleForSetter(node);
                    if (styleForSetter == null || styleForSetter != containerNode)
                    {
                        styleForSetter = ExpressionEvaluator.GetStyleForResourceEntry(node);
                        if (styleForSetter == null)
                        {
                            if (node != containerNode)
                            {
                                continue;
                            }
                            nodePath = null;
                        }
                        else
                        {
                            if (styleForSetter == containerNode)
                            {
                                nodePath = null;
                            }
                            node = styleForSetter.Parent;
                        }
                    }
                    else
                    {
                        nodePath = nodePath.GetContainerOwnerPath();
                        if (nodePath == null)
                        {
                            continue;
                        }
                        node = nodePath.Node;
                    }
                }
            }
            else
            {
                DocumentNode documentNode2 = null;
                for (DocumentNode i = nodePath.Node; i != null; i = i.Parent)
                {
                    ISupportsResources resourcesCollection = ResourceNodeHelper.GetResourcesCollection(i);
                    if (resourcesCollection != null)
                    {
                        ResourceSite resourceSite  = new ResourceSite(i.Context, resourcesCollection);
                        DocumentNode documentNode3 = null;
                        if (ResourceNodeHelper.IsResourceDictionary(resourcesCollection))
                        {
                            int siteChildIndex = -1;
                            if (documentNode2 != null)
                            {
                                siteChildIndex = documentNode2.SiteChildIndex;
                            }
                            documentNode3 = this.EvaluateResourceAtSpecificSite(resourceSite, keyNode, resourcesHostNodePath, relatedRoots, siteChildIndex, warnings);
                        }
                        else if (ResourceNodeHelper.IsResourceContainer(resourcesCollection, documentNode2))
                        {
                            documentNode3 = this.EvaluateResourceAtSpecificSite(resourceSite, keyNode, resourcesHostNodePath, relatedRoots, -1, warnings);
                        }
                        if (documentNode3 != null)
                        {
                            if (keyNode != null && keyNode.Parent != null && keyNode.Parent.Parent == i)
                            {
                                ITextRange nodeSpan  = DocumentNodeHelper.GetNodeSpan(keyNode.Parent);
                                ITextRange textRange = DocumentNodeHelper.GetNodeSpan(documentNode3);
                                if (!TextRange.IsNull(textRange) && !TextRange.IsNull(nodeSpan) && nodeSpan.Offset < textRange.Offset)
                                {
                                    documentNode3           = null;
                                    invalidForwardReference = true;
                                }
                            }
                            if (documentNode3 != null)
                            {
                                return(documentNode3);
                            }
                        }
                    }
                    documentNode2 = i;
                }
            }
            if (flag)
            {
                DocumentNode documentNode4 = this.EvaluateResourceAtSpecificNode(documentRoot1.RootNode, keyNode, resourcesHostNodePath, relatedRoots, warnings);
                if (documentNode4 != null)
                {
                    if (relatedRoots != null && documentNode4.DocumentRoot != documentRoot2)
                    {
                        relatedRoots.Add(documentRoot1);
                    }
                    return(documentNode4);
                }
            }
            if (documentRoot != null)
            {
                using (IEnumerator <IDocumentRoot> enumerator = documentRoot.DesignTimeResources.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        IDocumentRoot current       = enumerator.Current;
                        DocumentNode  documentNode5 = this.EvaluateResourceAtSpecificNode(current.RootNode, keyNode, resourcesHostNodePath, relatedRoots, warnings);
                        if (documentNode5 == null)
                        {
                            continue;
                        }
                        if (relatedRoots != null && documentNode5.DocumentRoot != documentRoot2)
                        {
                            relatedRoots.Add(current);
                        }
                        documentNode = documentNode5;
                        return(documentNode);
                    }
                    return(null);
                }
                return(documentNode);
            }
            return(null);
        }
        public void CreateDocument(MemberInfo_ViewModel info, Image image, ref int i)
        {
            //Create New Word
            Document doc = new Document();

            if (image != null)
            {
                Image resize = (Image)(new Bitmap(image, new System.Drawing.Size(900, 1000)));
                doc.Background.Type    = BackgroundType.Picture;
                doc.Background.Picture = resize;
            }

            //Add Section
            Spire.Doc.Section section = doc.AddSection();
            section.PageSetup.PageSize             = PageSize.A4;
            section.PageSetup.Borders.Bottom.Space = 0;
            //Add Paragraph
            Paragraph pHeader = section.AddParagraph();
            //Header
            TextRange textRangel = pHeader.AppendText("HỒ SƠ HỌC VIÊN");

            textRangel.CharacterFormat.Bold      = true;
            textRangel.CharacterFormat.TextColor = System.Drawing.Color.Blue;
            textRangel.CharacterFormat.FontSize  = 24;
            textRangel.CharacterFormat.FontName  = "Calibri Light (Headings)";
            pHeader.Format.HorizontalAlignment   = Spire.Doc.Documents.HorizontalAlignment.Center;
            pHeader.Format.AfterSpacing          = 5;
            //SKU
            draw(doc, 210, 22, 20, 5, "SKU: " + info.SKU);
            //Register Number
            draw(doc, 210, 22, 260, -9, "SỐ ĐĂNG KÝ: " + info.RegisterNumber);
            //Name
            draw(doc, 450, 22, 20, 8, "HỌ TÊN: " + info.FullName);
            //Quốc Tịch
            draw(doc, 450, 22, 20, 25, "QUỐC TỊCH: " + info.Nation);
            //Address
            draw(doc, 450, 22, 20, 42, "ĐỊA CHỈ: " + info.Address);
            //PHONE
            draw(doc, 450, 22, 20, 60, "SỐ ĐIỆN THOẠI: " + info.PhoneNumber);
            //Image
            imageDraw(doc, 145, 115, 15, 75, info.Image);
            //Register Day
            draw(doc, 320, 22, 150, 67, "NGÀY ĐĂNG KÝ: " + info.Register_day.ToShortDateString());
            // Day of Birth
            draw(doc, 320, 22, 150, 90, "NGÀY SINH : " + info.Day_of_Birth.ToShortDateString());
            //Place of Birth
            draw(doc, 320, 22, 150, 115, "NƠI SINH: " + info.Place_of_Birth);
            //Class
            draw(doc, 320, 22, 150, 139, "LỚP: " + info.Class_Name);
            //Cap 1-6

            draw(doc, 450, 22, 20, 160, "CẤP 6: " + (info.listLevel["Cap6"] != DateTime.MinValue ? info.listLevel["Cap6"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 177, "CẤP 5: " + (info.listLevel["Cap5"] != DateTime.MinValue ? info.listLevel["Cap5"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 193, "CẤP 4: " + (info.listLevel["Cap4"] != DateTime.MinValue ? info.listLevel["Cap4"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 209, "CẤP 3: " + (info.listLevel["Cap3"] != DateTime.MinValue ? info.listLevel["Cap3"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 225, "CẤP 2: " + (info.listLevel["Cap2"] != DateTime.MinValue ? info.listLevel["Cap2"].ToShortDateString() : ""));
            draw(doc, 450, 22, 20, 240, "CẤP 1: " + (info.listLevel["Cap1"] != DateTime.MinValue ? info.listLevel["Cap1"].ToShortDateString() : ""));

            draw(doc, 210, 22, 20, 260, "I DAN VN: " + (info.listLevel["DANVN1"] != DateTime.MinValue ? info.listLevel["DANVN1"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 278, "II DAN VN: " + (info.listLevel["DANVN2"] != DateTime.MinValue ? info.listLevel["DANVN2"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 296, "III DAN VN: " + (info.listLevel["DANVN3"] != DateTime.MinValue ? info.listLevel["DANVN3"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 314, "IV DAN VN: " + (info.listLevel["DANVN4"] != DateTime.MinValue ? info.listLevel["DANVN4"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 332, "V DAN VN: " + (info.listLevel["DANVN5"] != DateTime.MinValue ? info.listLevel["DANVN5"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 350, "VI DAN VN: " + (info.listLevel["DANVN6"] != DateTime.MinValue ? info.listLevel["DANVN6"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 368, "VII DAN VN: " + (info.listLevel["DANVN7"] != DateTime.MinValue ? info.listLevel["DANVN7"].ToShortDateString() : ""));
            draw(doc, 210, 22, 20, 384, "VIII DAN VN: " + (info.listLevel["DANVN8"] != DateTime.MinValue ? info.listLevel["DANVN8"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 150, "I DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI1"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI1"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 168, "II DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI2"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI2"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 185, "III DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI3"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI3"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 204, "IV DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI4"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI4"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 220, "V DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI5"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI5"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 238, "VI DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI6"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI6"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 256, "VII DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI7"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI7"].ToShortDateString() : ""));
            draw(doc, 210, 22, 260, 274, "VIII DAN AIKIDAI: " + (info.listLevel["DANAIKIKAI8"] != DateTime.MinValue ? info.listLevel["DANAIKIKAI8"].ToShortDateString() : ""));


            //Save and launch
            i++;
            doc.SaveToFile("MemberInfo" + i + ".docx", FileFormat.Docx);

            Process myProcess = new Process();

            try
            {
                myProcess = Process.Start("MemberInfo" + i + ".docx");
            }
            catch { }
        }
Exemple #55
0
        public static void FindAndReplace(RichTextBox rtb, string findText, string replaceText)
        {
            var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);

            textRange.Text = textRange.Text.Replace(findText, replaceText);
        }
Exemple #56
0
        public void DeCipher(bool decipher)
        {
            string strContent = "";         //zde se uloží text, který budeme (de)šifrovat
            string strKey     = tbKey.Text; //klíč
            string strOutput  = "";         //zde se uloží text, který bude výsledkem (de)šifrování
            bool   err        = false;      //informace o tom, zade se objevila určitá chyba


            if (!decipher)   //pokud šifrujeme, uložíme text z RichTextBoxu pro šifrování
            {
                strContent = new TextRange(rtbInput.Document.ContentStart, rtbInput.Document.ContentEnd).Text.Trim();
            }
            else            //pokud dešifrujeme, uložíme text z RichTextBoxu pro dešifrování
            {
                strContent = new TextRange(rtbOutput.Document.ContentStart, rtbOutput.Document.ContentEnd).Text.Replace("\r\n", "");
            }


            if (strContent == "")               //pokud je text prázdný, vypíšeme chybu
            {
                tbErr.Foreground = Brushes.Red; //červený text
                tbErr.Clear();                  //smazání všeho na TextBoxu
                if (!decipher)                  //vypsání chyby podle toho, zda šifrujeme, nebo dešifrujeme
                {
                    tbErr.AppendText("NOTHING TO CIPHER");
                }
                else
                {
                    tbErr.AppendText("NOTHING TO DECIPHER");
                }
                err = true;                     //uložení informace o chybě
            }
            if (strKey == "")                   //pokud je klíč prázdný, vypíšeme chybu
            {
                if (err)                        //pokud nasatla předchozí chyba, připíšeme tuto pod ní
                {
                    tbErr.AppendText("\nNO KEY");
                }
                else                                //pokud nenastala předchozí chyba, vypíšeme tuto
                {
                    tbErr.Foreground = Brushes.Red; //červený text
                    tbErr.Clear();                  //smazání všeho na TextBoxu
                    tbErr.AppendText("NO KEY");     //vypsání chyby
                }
            }
            else if (!err)      //pokud nenastala žádná chyba, (de)šifrujeme
            {
                tbErr.Clear();

                for (int i = 0; i < strContent.Length; i++)                         //procházíme jednotlivé znaky textu
                {
                    strOutput += (char)(strContent[i] ^ strKey[i % strKey.Length]); //provedeme XOR operaci na jednotlivé
                }
                //znaky textu a klíče, viz readme
                if (!decipher)
                {              //pokud jsme šifrovali, vypíšeme výsledek do RichTextBoxu dešifrování
                    rtbOutput.Document.Blocks.Clear();
                    rtbOutput.AppendText(strOutput);
                }
                else
                {              //pokud jsme dešifrovali, vypíšeme výsledek do RichTextBoxu šifrování
                    rtbInput.Document.Blocks.Clear();
                    rtbInput.AppendText(strOutput);
                }
            }
        }
Exemple #57
0
        public static void AppendText(this RichTextBox textBox, string text)
        {
            TextRange textRange = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);

            textRange.Text += text;
        }
        private void txtStatus_TextChanged(object sender, TextChangedEventArgs e)
        {
            string desktopPath  = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string settingsPath = desktopPath + "\\CodeVoidProject\\CodeVoid\\CodeVoidWPF\\bin\\Debug\\Data\\DarkModeFix.txt";

            using (StreamReader sr = new StreamReader(settingsPath))
            {
                string line;
                line = sr.ReadLine();
                if (line.Contains("DarkMode:True"))
                {
                    txtStatus.Background = Brushes.DarkGray;
                }
                else
                {
                    //do something..
                }
            }

            if (txtStatus.Document == null)
            {
                return;
            }
            txtStatus.TextChanged -= txtStatus_TextChanged;

            m_blueTags.Clear();
            gr_Tags.Clear();
            yellow_Tags.Clear();

            Console.WriteLine();
            TextPointer navigator       = txtStatus.Document.ContentStart;
            TextPointer grnavigator     = txtStatus.Document.ContentStart;
            TextPointer yellownavigator = txtStatus.Document.ContentStart;

            while (navigator.CompareTo(txtStatus.Document.ContentEnd) < 0)
            {
                TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
                if (context == TextPointerContext.ElementStart && navigator.Parent is Run)
                {
                    text = ((Run)navigator.Parent).Text; //fix 2
                    if (text != "")
                    {
                        CheckWordsInRun((Run)navigator.Parent);
                    }
                }
                navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
            }
            while (grnavigator.CompareTo(txtStatus.Document.ContentEnd) < 0)
            {
                TextPointerContext grcontext = grnavigator.GetPointerContext(LogicalDirection.Backward);
                if (grcontext == TextPointerContext.ElementStart && grnavigator.Parent is Run)
                {
                    grtext = ((Run)grnavigator.Parent).Text; //fix 2
                    if (grtext != "")
                    {
                        grCheckWordsInRun((Run)grnavigator.Parent);
                    }
                }
                grnavigator = grnavigator.GetNextContextPosition(LogicalDirection.Forward);
            }
            while (yellownavigator.CompareTo(txtStatus.Document.ContentEnd) < 0)
            {
                TextPointerContext yellowcontext = yellownavigator.GetPointerContext(LogicalDirection.Backward);
                if (yellowcontext == TextPointerContext.ElementStart && yellownavigator.Parent is Run)
                {
                    yellowtext = ((Run)yellownavigator.Parent).Text; //fix 2
                    if (yellowtext != "")
                    {
                        yellowCheckWordsInRun((Run)yellownavigator.Parent);
                    }
                }
                yellownavigator = yellownavigator.GetNextContextPosition(LogicalDirection.Forward);
            }
            for (int i = 0; i < m_blueTags.Count; i++)
            {
                try
                {
                    TextRange range = new TextRange(m_blueTags[i].StartPosition, m_blueTags[i].EndPosition);
                    range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
                    range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
                }
                catch { }
            }
            for (int i = 0; i < gr_Tags.Count; i++)
            {
                try
                {
                    Console.WriteLine();
                    TextRange grrange = new TextRange(gr_Tags[i].grStartPosition, gr_Tags[i].grEndPosition);
                    grrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Green));
                    grrange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
                }
                catch { }
            }
            for (int i = 0; i < yellow_Tags.Count; i++)
            {
                try
                {
                    Console.WriteLine();
                    TextRange yellowrange = new TextRange(yellow_Tags[i].yellowStartPosition, yellow_Tags[i].yellowEndPosition);
                    yellowrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.GreenYellow));
                    yellowrange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
                }
                catch { }
            }
            txtStatus.TextChanged += txtStatus_TextChanged;
        }
Exemple #59
0
        private static ITooltipContent[] GetTooltipContents([NotNull] IHighlighter highlighter, TextRange range,
                                                            [NotNull] IDocumentMarkup documentMarkup, [CanBeNull] ISolution solution, bool skipIdentifierHighlighting)
        {
            if (highlighter.Attributes.Effect.Type == EffectType.GUTTER_MARK)
            {
                return(EmptyArray <ITooltipContent> .Instance);
            }

            var highlighting = highlighter.UserData as IHighlighting;

            if (highlighting != null)
            {
                IDocument document = documentMarkup.Document;
                IContextBoundSettingsStore settings = document.GetSettings();

                Severity            severity     = HighlightingSettingsManager.Instance.GetSeverity(highlighting, document, solution);
                IssueTooltipContent issueContent = TryCreateIssueContent(highlighting, range, highlighter.RichTextToolTip, severity, settings, solution);
                if (issueContent != null)
                {
                    return new ITooltipContent[] { issueContent }
                }
                ;

                if (solution != null && IsIdentifierHighlighting(highlighting))
                {
                    if (skipIdentifierHighlighting)
                    {
                        return(EmptyArray <ITooltipContent> .Instance);
                    }
                    IdentifierTooltipContent[] identifierContents = GetIdentifierTooltipContents(highlighter, solution, settings);

                    // ReSharper disable once CoVariantArrayConversion
                    return(identifierContents);
                }
            }

            MiscTooltipContent miscContent = TryCreateMiscContent(highlighter.RichTextToolTip, range);

            if (miscContent != null)
            {
                return new ITooltipContent[] { miscContent }
            }
            ;

            return(EmptyArray <ITooltipContent> .Instance);
        }
        private void ChangeFontSize()
        {
            TextRange tr = new TextRange(MainText.Document.ContentStart, MainText.Document.ContentEnd);

            tr.ApplyPropertyValue(FontSizeProperty, Font_Size.Value);
        }