1 // Copyright 2010-2013, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 #include "unix/fcitx/surrounding_text_util.h"
31 
32 #include <limits>
33 #include <string>
34 #include <fcitx/instance.h>
35 #if 0
36 #include <fcitx/module/clipboard/fcitx-clipboard.h>
37 #endif
38 
39 #include "base/port.h"
40 #include "base/logging.h"
41 #include "base/util.h"
42 
43 namespace mozc {
44 namespace fcitx {
45 
GetSafeDelta(uint from,uint to,int32 * delta)46 bool SurroundingTextUtil::GetSafeDelta(uint from, uint to, int32 *delta) {
47   DCHECK(delta);
48 
49   static_assert(sizeof(int64) >= sizeof(uint),
50                 "int64 must be sufficient to store a guint value.");
51   static_assert(sizeof(int64) == sizeof(llabs(0)),
52                 "|llabs(0)| must returns a 64-bit integer.");
53   const int64 kInt32AbsMax =
54       llabs(static_cast<int64>(std::numeric_limits<int32>::max()));
55   const int64 kInt32AbsMin =
56       llabs(static_cast<int64>(std::numeric_limits<int32>::min()));
57   const int64 kInt32SafeAbsMax =
58       std::min(kInt32AbsMax, kInt32AbsMin);
59 
60   const int64 diff = static_cast<int64>(from) - static_cast<int64>(to);
61   if (llabs(diff) > kInt32SafeAbsMax) {
62     return false;
63   }
64 
65   *delta = static_cast<int32>(diff);
66   return true;
67 }
68 
69 namespace {
70 
71 // Moves |iter| with |skip_count| characters.
72 // Returns false if |iter| reaches to the end before skipping
73 // |skip_count| characters.
Skip(ConstChar32Iterator * iter,size_t skip_count)74 bool Skip(ConstChar32Iterator *iter, size_t skip_count) {
75   for (size_t i = 0; i < skip_count; ++i) {
76     if (iter->Done()) {
77       return false;
78     }
79     iter->Next();
80   }
81   return true;
82 }
83 
84 // Returns true if |prefix_iter| is the prefix of |iter|.
85 // Returns false if |prefix_iter| is an empty sequence.
86 // Otherwise returns false.
87 // This function receives ConstChar32Iterator as pointer because
88 // ConstChar32Iterator is defined as non-copyable.
StartsWith(ConstChar32Iterator * iter,ConstChar32Iterator * prefix_iter)89 bool StartsWith(ConstChar32Iterator *iter,
90                 ConstChar32Iterator *prefix_iter) {
91   if (iter->Done() || prefix_iter->Done()) {
92     return false;
93   }
94 
95   while (true) {
96     if (iter->Get() != prefix_iter->Get()) {
97       return false;
98     }
99     prefix_iter->Next();
100     if (prefix_iter->Done()) {
101       return true;
102     }
103     iter->Next();
104     if (iter->Done()) {
105       return false;
106     }
107   }
108 }
109 
110 
111 // Returns true if |surrounding_text| contains |selected_text|
112 // from |cursor_pos| to |*anchor_pos|.
113 // Otherwise returns false.
SearchAnchorPosForward(const string & surrounding_text,const string & selected_text,size_t selected_chars_len,uint cursor_pos,uint * anchor_pos)114 bool SearchAnchorPosForward(
115     const string &surrounding_text,
116     const string &selected_text,
117     size_t selected_chars_len,
118     uint cursor_pos,
119     uint *anchor_pos) {
120 
121   ConstChar32Iterator iter(surrounding_text);
122   // Move |iter| to cursor pos.
123   if (!Skip(&iter, cursor_pos)) {
124     return false;
125   }
126 
127   ConstChar32Iterator sel_iter(selected_text);
128   if (!StartsWith(&iter, &sel_iter)) {
129     return false;
130   }
131   *anchor_pos = cursor_pos + selected_chars_len;
132   return true;
133 }
134 
135 // Returns true if |surrounding_text| contains |selected_text|
136 // from |*anchor_pos| to |cursor_pos|.
137 // Otherwise returns false.
SearchAnchorPosBackward(const string & surrounding_text,const string & selected_text,size_t selected_chars_len,uint cursor_pos,uint * anchor_pos)138 bool SearchAnchorPosBackward(
139     const string &surrounding_text,
140     const string &selected_text,
141     size_t selected_chars_len,
142     uint cursor_pos,
143     uint *anchor_pos) {
144   if (cursor_pos < selected_chars_len) {
145     return false;
146   }
147 
148   ConstChar32Iterator iter(surrounding_text);
149   // Skip |iter| to (potential) anchor pos.
150   const uint skip_count = cursor_pos - selected_chars_len;
151   DCHECK_LE(skip_count, cursor_pos);
152   if (!Skip(&iter, skip_count)) {
153     return false;
154   }
155 
156   ConstChar32Iterator sel_iter(selected_text);
157   if (!StartsWith(&iter, &sel_iter)) {
158     return false;
159   }
160   *anchor_pos = cursor_pos - selected_chars_len;
161   return true;
162 }
163 
164 }  // namespace
165 
GetAnchorPosFromSelection(const string & surrounding_text,const string & selected_text,uint cursor_pos,uint * anchor_pos)166 bool SurroundingTextUtil::GetAnchorPosFromSelection(
167     const string &surrounding_text,
168     const string &selected_text,
169     uint cursor_pos,
170     uint *anchor_pos) {
171   DCHECK(anchor_pos);
172 
173   if (surrounding_text.empty()) {
174     return false;
175   }
176 
177   if (selected_text.empty()) {
178     return false;
179   }
180 
181   const size_t selected_chars_len = Util::CharsLen(selected_text);
182 
183   if (SearchAnchorPosForward(surrounding_text, selected_text,
184                              selected_chars_len,
185                              cursor_pos, anchor_pos)) {
186     return true;
187   }
188 
189   return SearchAnchorPosBackward(surrounding_text, selected_text,
190                                  selected_chars_len,
191                                  cursor_pos, anchor_pos);
192 }
193 
GetSurroundingText(FcitxInstance * instance,SurroundingTextInfo * info)194 bool GetSurroundingText(FcitxInstance* instance,
195                         SurroundingTextInfo *info) {
196     FcitxInputContext* ic = FcitxInstanceGetCurrentIC(instance);
197     if (!ic || !(ic->contextCaps & CAPACITY_SURROUNDING_TEXT)) {
198         return false;
199     }
200 
201     uint cursor_pos = 0;
202     uint anchor_pos = 0;
203     char* str = NULL;
204 
205     if (!FcitxInstanceGetSurroundingText(instance, ic, &str, &cursor_pos, &anchor_pos)) {
206         return false;
207     }
208 
209     const string surrounding_text(str);
210     free(str);
211 
212 #if 0
213     if (cursor_pos == anchor_pos) {
214         const char* primary = NULL;
215 
216         if ((primary = FcitxClipboardGetPrimarySelection(instance, NULL)) != NULL) {
217             uint new_anchor_pos = 0;
218             const string primary_text(primary);
219             if (SurroundingTextUtil::GetAnchorPosFromSelection(
220                 surrounding_text, primary_text,
221                 cursor_pos, &new_anchor_pos)) {
222                 anchor_pos = new_anchor_pos;
223             }
224         }
225     }
226 #endif
227 
228     if (!SurroundingTextUtil::GetSafeDelta(cursor_pos, anchor_pos,
229                                            &info->relative_selected_length)) {
230         LOG(ERROR) << "Too long text selection.";
231         return false;
232     }
233 
234     const size_t selection_start = std::min(cursor_pos, anchor_pos);
235     const size_t selection_length = std::abs(info->relative_selected_length);
236     Util::SubStringPiece(surrounding_text, 0, selection_start)
237        .CopyToString(&info->preceding_text);
238     Util::SubStringPiece(surrounding_text, selection_start, selection_length)
239        .CopyToString(&info->selection_text);
240     Util::SubStringPiece(surrounding_text, selection_start + selection_length)
241        .CopyToString(&info->following_text);
242     return true;
243 }
244 
245 }  // namespace fcitx
246 }  // namespace mozc
247