Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF RichTextBox SelectionChanged Performance

I'm working on a word processor-type app using the WPF RichTextBox. I'm using the SelectionChanged event to figure out what the font, font weight, style, etc. is of the current selection in the RTB using the following code:

private void richTextBox_SelectionChanged(object sender, RoutedEventArgs e)
    {
        TextSelection selection = richTextBox.Selection;

        if (selection.GetPropertyValue(FontFamilyProperty) != DependencyProperty.UnsetValue)
        {
            //we have a single font in the selection
            SelectionFontFamily = (FontFamily)selection.GetPropertyValue(FontFamilyProperty);
        }
        else
        {
            SelectionFontFamily = null;
        }

        if (selection.GetPropertyValue(FontWeightProperty) == DependencyProperty.UnsetValue)
        {
            SelectionIsBold = false;
        }
        else
        {
            SelectionIsBold = (FontWeights.Bold == ((FontWeight)selection.GetPropertyValue(FontWeightProperty)));
        }

        if (selection.GetPropertyValue(FontStyleProperty) == DependencyProperty.UnsetValue)
        {
            SelectionIsItalic = false;
        }
        else
        {
            SelectionIsItalic = (FontStyles.Italic == ((FontStyle)selection.GetPropertyValue(FontStyleProperty)));
        }

        if (selection.GetPropertyValue(Paragraph.TextAlignmentProperty) != DependencyProperty.UnsetValue)
        {
            SelectionIsLeftAligned = (TextAlignment)selection.GetPropertyValue(Paragraph.TextAlignmentProperty) == TextAlignment.Left;
            SelectionIsCenterAligned = (TextAlignment)selection.GetPropertyValue(Paragraph.TextAlignmentProperty) == TextAlignment.Center;
            SelectionIsRightAligned = (TextAlignment)selection.GetPropertyValue(Paragraph.TextAlignmentProperty) == TextAlignment.Right;
            SelectionIsJustified = (TextAlignment)selection.GetPropertyValue(Paragraph.TextAlignmentProperty) == TextAlignment.Justify;
        }            
    }

SelectionFontFamily, SelectionIsBold, etc. are each a DependencyProperty on the hosting UserControl with a Binding Mode of OneWayToSource. They are bound to a ViewModel, which in turn has a View bound to it that has the Font combo box, bold, italic, underline, etc. controls on it. When the selection in the RTB changes, those controls are also updated to reflect what's been selected. This works great.

Unfortunately, it works at the expense of performance, which is seriously impacted when selecting large amounts of text. Selecting everything is noticeably slow, and then using something like Shift+Arrow Keys to change the selection is very slow. Too slow to be acceptable.

Am I doing something wrong? Are there any suggestions on how to achieve reflecting the attributes of the selected text in the RTB to bound controls without killing the performance of the RTB in the process?

like image 935
Scott Avatar asked Aug 12 '10 22:08

Scott


1 Answers

Your two main causes of performance problems are:

  1. You call selection.GetPropertyValue() more times than necessary
  2. You recompute every time the selection changes

The GetPropertyValue() method must internally scan through every element in the document, which makes it slow. So instead of calling it multiple times with the same argument, store the return values:

private void HandleSelectionChange()
{
  var family = selection.GetPropertyValue(FontFamilyProperty);
  var weight = selection.GetPropertyValue(FontWeightProperty);
  var style = selection.GetPropertyValue(FontStyleProperty);
  var align = selection.GetPropertyValue(Paragraph.TextAlignmentProperty);

  var unset = DependencyProperty.UnsetValue;

  SelectionFontFamily = family!=unset ? (FontFamily)family : null;
  SelectionIsBold = weight!=unset && (FontWeight)weight == FontWeight.Bold;
  SelectionIsItalic = style!=unset && (FontStyle)style == FontStyle.Italic;

  SelectionIsLeftAligned = align!=unset && (TextAlignment)align == TextAlignment.Left;     
  SelectionIsCenterAligned = align!=unset && (TextAlignment)align == TextAlignment.Center;    
  SelectionIsRightAligned = align!=unset && (TextAlignment)align == TextAlignment.Right;
  SelectionIsJustified = align!=unset && (TextAlignment)align == TextAlignment.Justify;
}

This will be about 3x faster, but to make it feel really snappy to the end-user, don't update the settings instantly on every change. Instead, update on ContextIdle:

bool _queuedChange;

private void richTextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
  if(!_queuedChange)
  {
    _queuedChange = true;
    Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, (Action)(() =>
    {
      _queuedChange = false;
      HandleSelectionChange();
    }));
  }
}

This calls the HandleSelctionChanged() method (above) to actually handle the selection change, but delays the call until ContextIdle dispatcher priority and also queues only one update no matter how many selection change events come in.

Additional speedups possible

The above code makes all four GetPropertyValue in a single DispatcherOperation, which means that you may still have a "lag" as long as the four calls. To reduce the lag an additional 4x, make only one GetPropertyValue per DispatcherOperation. So, for example, the first DispatcherOperation will call GetPropertyValue(FontFamilyProperty), store the result in a field, and schedule the next DispatcherOperation to get the font weight. Each subsequent DispatcherOperation will do the same.

If this additional speedup is still not enough, the next step would be to split the selection into smaller pieces, call GetPropertyValue on each piece in a separate DispatcherOperation, then combine the results you get.

To get the absolute maximum smoothness, you could implement your own code for GetPropertyValue (just iterate the ContentElements in the selection) that works incrementally and returns after checking, say, 100 elements. The next time you call it it would pick up where it left off. This would guarantee your ability to prevent any discernable lag by varying the amount of work done per DispatcherOperation.

Would threading help?

You ask in the comments whether this is possible to do using threading. The answer is that you can use a thread to orchestrate the work, but since you must always Dispatcher.Invoke back to the main thread to call GetPropertyValue, you will still block your UI thread for the entire duration of each GetPropertyValue call, so its granularity is still an issue. In other words, threading doesn't really buy you anything except perhaps the ability to avoid the use of a state machine for splitting your work up into bite-size chunks.

like image 122
Ray Burns Avatar answered Oct 03 '22 08:10

Ray Burns