private CachedData updateCachedAndSortOffsets(FoldRegion @Nullable [] visibleRegions, boolean fromRebuild) {
    if (!isFoldingEnabled()) {
      return null;
    }
    if (visibleRegions == null) {
      return rebuild();
    }

    List<FoldRegion> topLevel = new ArrayList<>(visibleRegions.length/2);

    for (FoldRegion region : visibleRegions) {
      if (!region.isValid()) {
        if (fromRebuild) {
          throw new RuntimeExceptionWithAttachments("FoldRegionsTree.rebuild() failed",
                                                    new Attachment("visibleRegions.txt", Arrays.toString(visibleRegions)));
        }
        return rebuild();
      }
      if (!region.isExpanded()) {
        topLevel.add(region);
      }
    }
    FoldRegion[] topLevelRegions = topLevel.toArray(FoldRegion.EMPTY_ARRAY);
    Arrays.sort(topLevelRegions, BY_END_OFFSET);

    int[] startOffsets = ArrayUtil.newIntArray(topLevelRegions.length);
    int[] endOffsets = ArrayUtil.newIntArray(topLevelRegions.length);
    int[] foldedLines = ArrayUtil.newIntArray(topLevelRegions.length);
    int[] customYAdjustment = ArrayUtil.newIntArray(topLevelRegions.length);

    int foldedLinesSum = 0;
    int currentCustomYAdjustment = 0;
    int lineHeight = getLineHeight();
    for (int i = 0; i < topLevelRegions.length; i++) {
      FoldRegion region = topLevelRegions[i];
      startOffsets[i] = region.getStartOffset();
      endOffsets[i] = region.getEndOffset() - 1;
      Document document = region.getDocument();
      foldedLinesSum += document.getLineNumber(region.getEndOffset()) - document.getLineNumber(region.getStartOffset());
      foldedLines[i] = foldedLinesSum;
      if (region instanceof CustomFoldRegion) {
        currentCustomYAdjustment += ((CustomFoldRegion)region).getHeightInPixels() - lineHeight;
      }
      customYAdjustment[i] = currentCustomYAdjustment;
    }

    CachedData data = new CachedData(visibleRegions, topLevelRegions, startOffsets, endOffsets, foldedLines, customYAdjustment);
    myCachedData = data;
    return data;
  }
private CachedData updateCachedAndSortOffsets(FoldRegion @Nullable [] visibleRegions, boolean fromRebuild)