BidiRun.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // RichTextKit
  2. // Copyright © 2019-2020 Topten Software. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. // not use this product except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Text;
  18. using Topten.RichTextKit.Utils;
  19. namespace Topten.RichTextKit
  20. {
  21. internal struct BidiRun
  22. {
  23. public Directionality Direction;
  24. public int Start;
  25. public int Length;
  26. public int End => Start + Length;
  27. public override string ToString()
  28. {
  29. return $"{Start} - {End} - {Direction}";
  30. }
  31. public static IEnumerable<BidiRun> CoalescLevels(Slice<sbyte> levels)
  32. {
  33. if (levels.Length == 0)
  34. yield break;
  35. int startRun = 0;
  36. sbyte runLevel = levels[0];
  37. for (int i = 1; i < levels.Length; i++)
  38. {
  39. if (levels[i] == runLevel)
  40. continue;
  41. // End of this run
  42. yield return new BidiRun()
  43. {
  44. Direction = (runLevel & 0x01) == 0 ? Directionality.L : Directionality.R,
  45. Start = startRun,
  46. Length = i - startRun,
  47. };
  48. // Move to next run
  49. startRun = i;
  50. runLevel = levels[i];
  51. }
  52. yield return new BidiRun()
  53. {
  54. Direction = (runLevel & 0x01) == 0 ? Directionality.L : Directionality.R,
  55. Start = startRun,
  56. Length = levels.Length - startRun,
  57. };
  58. }
  59. }
  60. }