1 /* 2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_IME_TEXT_SELECTION_H 17 #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_IME_TEXT_SELECTION_H 18 19 #include <cstdint> 20 #include <iomanip> 21 #include <limits> 22 #include <sstream> 23 #include <string> 24 25 #include "core/common/ime/constant.h" 26 27 namespace OHOS::Ace { 28 29 /** 30 * Stands for what text is selected and how the directional is. 31 * We use base/extent to indicate the start/end position because of uncertain direction. 32 */ 33 struct TextSelection { 34 TextSelection() = default; TextSelectionTextSelection35 TextSelection(int32_t base, int32_t extent) : baseOffset(base), extentOffset(extent) {} 36 UpdateTextSelection37 void Update(int32_t base, int32_t extent) 38 { 39 baseOffset = base; 40 extentOffset = extent; 41 } 42 43 // Usually called when none is selected. UpdateTextSelection44 void Update(int32_t both) 45 { 46 baseOffset = both; 47 extentOffset = both; 48 } 49 50 bool operator==(const TextSelection& other) const 51 { 52 return baseOffset == other.baseOffset && extentOffset == other.extentOffset; 53 } 54 55 bool operator!=(const TextSelection& other) const 56 { 57 return !operator==(other); 58 } 59 60 /** 61 * @brief Get first selected character in the text. 62 */ GetStartTextSelection63 inline int32_t GetStart() const 64 { 65 return std::min(baseOffset, extentOffset); 66 } 67 68 /** 69 * @brief Get last selected character in the text. 70 */ GetEndTextSelection71 inline int32_t GetEnd() const 72 { 73 return std::max(baseOffset, extentOffset); 74 } 75 76 /** 77 * @brief Whether selection is valid. 78 */ IsValidTextSelection79 inline bool IsValid() const 80 { 81 return baseOffset > -1 && extentOffset > -1; 82 } 83 ToStringTextSelection84 std::string ToString() const 85 { 86 std::stringstream ss; 87 ss << "Selection (" << baseOffset << ", " << extentOffset << ")"; 88 std::string output = ss.str(); 89 return output; 90 } 91 92 // May larger than, smaller than or equal to extentOffset. 93 int32_t baseOffset = -1; 94 95 // When paints caret, this is where the caret position is. 96 int32_t extentOffset = -1; 97 98 TextAffinity affinity = TextAffinity::UPSTREAM; 99 }; 100 101 } // namespace OHOS::Ace 102 103 #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_IME_TEXT_SELECTION_H 104