1 /* 2 * Copyright 2013, Stephan Aßmus <superstippi@gmx.de>. 3 * All rights reserved. Distributed under the terms of the MIT License. 4 */ 5 6 #include "TextSpan.h" 7 8 9 TextSpan::TextSpan() 10 : 11 fText(), 12 fCharCount(0), 13 fStyle() 14 { 15 } 16 17 18 TextSpan::TextSpan(const BString& text, const CharacterStyle& style) 19 : 20 fText(text), 21 fCharCount(text.CountChars()), 22 fStyle(style) 23 { 24 } 25 26 27 TextSpan::TextSpan(const TextSpan& other) 28 : 29 fText(other.fText), 30 fCharCount(other.fCharCount), 31 fStyle(other.fStyle) 32 { 33 } 34 35 36 TextSpan& 37 TextSpan::operator=(const TextSpan& other) 38 { 39 fText = other.fText; 40 fCharCount = other.fCharCount; 41 fStyle = other.fStyle; 42 43 return *this; 44 } 45 46 47 bool 48 TextSpan::operator==(const TextSpan& other) const 49 { 50 return fCharCount == other.fCharCount 51 && fStyle == other.fStyle 52 && fText == other.fText; 53 } 54 55 56 bool 57 TextSpan::operator!=(const TextSpan& other) const 58 { 59 return !(*this == other); 60 } 61 62 63 void 64 TextSpan::SetText(const BString& text) 65 { 66 fText = text; 67 fCharCount = fText.CountChars(); 68 } 69 70 71 void 72 TextSpan::SetStyle(const CharacterStyle& style) 73 { 74 fStyle = style; 75 } 76 77 78 bool 79 TextSpan::Append(const BString& text) 80 { 81 return Insert(fCharCount, text); 82 } 83 84 85 bool 86 TextSpan::Insert(int32 offset, const BString& text) 87 { 88 _TruncateInsert(offset); 89 90 fText.InsertChars(text, offset); 91 92 int32 charCount = fText.CountChars(); 93 bool success = charCount > fCharCount; 94 fCharCount = charCount; 95 96 return success; 97 } 98 99 100 bool 101 TextSpan::Remove(int32 start, int32 count) 102 { 103 _TruncateRemove(start, count); 104 105 if (count > 0) { 106 fText.RemoveChars(start, count); 107 108 int32 charCount = fText.CountChars(); 109 bool success = charCount < fCharCount; 110 fCharCount = charCount; 111 112 return success; 113 } 114 return true; 115 } 116 117 118 TextSpan 119 TextSpan::SubSpan(int32 start, int32 count) const 120 { 121 _TruncateRemove(start, count); 122 123 BString subString; 124 if (count > 0) 125 fText.CopyCharsInto(subString, start, count); 126 127 return TextSpan(subString, fStyle); 128 } 129 130 131 // #pragma mark - private 132 133 134 void 135 TextSpan::_TruncateInsert(int32& start) const 136 { 137 if (start < 0) 138 start = 0; 139 140 if (start >= fCharCount) 141 start = fCharCount; 142 } 143 144 145 void 146 TextSpan::_TruncateRemove(int32& start, int32& count) const 147 { 148 if (count < 0) { 149 count = 0; 150 return; 151 } 152 153 if (start < 0) { 154 count += start; 155 start = 0; 156 } 157 158 if (start < fCharCount) { 159 if (start + count > fCharCount) 160 count = fCharCount - start; 161 } else { 162 count = 0; 163 } 164 } 165