File: mozc_response_parser.cc

package info (click to toggle)
mozc 2.23.2815.102+dfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 138,784 kB
  • sloc: cpp: 223,701; java: 46,355; xml: 32,265; python: 8,557; lisp: 2,184; ansic: 763; sh: 121; yacc: 93; makefile: 83
file content (448 lines) | stat: -rw-r--r-- 16,483 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// Copyright 2010-2012, Google Inc.
// Copyright 2012~2013, Weng Xuetian <wengxt@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "unix/fcitx/mozc_response_parser.h"

#include <string>
#include <vector>

#include "base/logging.h"
#include "base/process.h"
#include "base/util.h"
#include "protocol/commands.pb.h"
#include "unix/fcitx/fcitx_mozc.h"
#include "unix/fcitx/surrounding_text_util.h"
#include <fcitx/candidate.h>

namespace {

// Returns a position that determines a preedit cursor position _AND_ top-left
// position of a candidate window. Note that we can't set these two positions
// independently. That's a SCIM's limitation.
uint32 GetCursorPosition(const mozc::commands::Output &response) {
    if (!response.has_preedit()) {
        return 0;
    }
    if (response.preedit().has_highlighted_position()) {
        return response.preedit().highlighted_position();
    }
    return response.preedit().cursor();
}

string CreateDescriptionString(const string &description) {
    return " [" + description + "]";
}

}  // namespace

namespace mozc {

namespace fcitx {

MozcResponseParser::MozcResponseParser()
        : use_annotation_(false) {
}

MozcResponseParser::~MozcResponseParser() {
}

void MozcResponseParser::UpdateDeletionRange(const mozc::commands::Output& response, FcitxMozc* fcitx_mozc) const
{
    if (response.has_deletion_range() &&
        response.deletion_range().offset() <= 0 &&
        response.deletion_range().offset() + response.deletion_range().length() >= 0) {
        FcitxInstanceDeleteSurroundingText(fcitx_mozc->GetInstance(),
                                           FcitxInstanceGetCurrentIC(fcitx_mozc->GetInstance()),
                                           response.deletion_range().offset(),
                                           response.deletion_range().length());
    }
}

void MozcResponseParser::LaunchTool(const mozc::commands::Output& response, FcitxMozc* fcitx_mozc) const
{
    FCITX_UNUSED(fcitx_mozc);
    if (response.has_launch_tool_mode()) {
        fcitx_mozc->GetClient()->LaunchToolWithProtoBuf(response);
    }
}

void MozcResponseParser::ExecuteCallback(const mozc::commands::Output& response, FcitxMozc* fcitx_mozc) const
{
    if (!response.has_callback()) {
        return;
    }

    if (!response.callback().has_session_command()) {
        LOG(ERROR) << "callback does not have session_command";
        return;
    }

    const commands::SessionCommand &callback_command =
        response.callback().session_command();

    if (!callback_command.has_type()) {
        LOG(ERROR) << "callback_command has no type";
        return;
    }

    commands::SessionCommand session_command;
    session_command.set_type(callback_command.type());

    // TODO(nona): Make a function to handle CONVERT_REVERSE.
    // Used by CONVERT_REVERSE and/or UNDO
    // This value represents how many characters are selected as a relative
    // distance of characters. Positive value represents forward text selection
    // and negative value represents backword text selection.
    // Note that you should not allow 0x80000000 for |relative_selected_length|
    // because you cannot safely use |-relative_selected_length| nor
    // |abs(relative_selected_length)| in this case due to integer overflow.
    SurroundingTextInfo surrounding_text_info;

    switch (callback_command.type()) {
        case commands::SessionCommand::UNDO:
            break;
        case commands::SessionCommand::CONVERT_REVERSE: {

            if (!GetSurroundingText(fcitx_mozc->GetInstance(),
                                    &surrounding_text_info)) {
                return;
            }

            session_command.set_text(surrounding_text_info.selection_text);
            break;
        }
        default:
            return;
    }

    commands::Output new_output;
    if (!fcitx_mozc->SendCommand(session_command, &new_output)) {
        LOG(ERROR) << "Callback Command Failed";
        return;
    }

    if (callback_command.type() == commands::SessionCommand::CONVERT_REVERSE) {
        // We need to remove selected text as a first step of reconversion.
        commands::DeletionRange *range = new_output.mutable_deletion_range();
        // Use DeletionRange field to remove the selected text.
        // For forward selection (that is, |relative_selected_length > 0|), the
        // offset should be a negative value to delete preceding text.
        // For backward selection (that is, |relative_selected_length < 0|),
        // IBus and/or some applications seem to expect |offset == 0| somehow.
        const int32 offset = surrounding_text_info.relative_selected_length > 0
            ? -surrounding_text_info.relative_selected_length  // forward selection
            : 0;                         // backward selection
        range->set_offset(offset);
        range->set_length(abs(surrounding_text_info.relative_selected_length));
    }

    VLOG(1) << "New output" << new_output.DebugString();

    ParseResponse(new_output, fcitx_mozc);
}

bool MozcResponseParser::ParseResponse(const mozc::commands::Output &response,
                                       FcitxMozc *fcitx_mozc) const {
    DCHECK(fcitx_mozc);
    if (!fcitx_mozc) {
        return false;
    }

    fcitx_mozc->SetUsage("", "");

    UpdateDeletionRange(response, fcitx_mozc);

    // We should check the mode field first since the response for a
    // SWITCH_INPUT_MODE request only contains mode and id fields.
    if (response.has_mode()) {
        fcitx_mozc->SetCompositionMode(response.mode());
    }

    if (!response.consumed()) {
        // The key was not consumed by Mozc.
        return false;
    }

    if (response.has_result()) {
        const mozc::commands::Result &result = response.result();
        ParseResult(result, fcitx_mozc);
    }

    // First, determine the cursor position.
    if (response.has_preedit()) {
        const mozc::commands::Preedit &preedit = response.preedit();
        ParsePreedit(preedit, GetCursorPosition(response), fcitx_mozc);
    }

    // Then show the candidate window.
    if (response.has_candidates()) {
        const mozc::commands::Candidates &candidates = response.candidates();
        ParseCandidates(candidates, fcitx_mozc);
    }

    if (response.has_url()) {
        const string &url = response.url();
        fcitx_mozc->SetUrl(url);
    }
    LaunchTool(response, fcitx_mozc);
    ExecuteCallback(response, fcitx_mozc);

    return true;  // mozc consumed the key.
}

void MozcResponseParser::set_use_annotation(bool use_annotation) {
    use_annotation_ = use_annotation;
}

void MozcResponseParser::ParseResult(const mozc::commands::Result &result,
                                     FcitxMozc *fcitx_mozc) const {
    switch (result.type()) {
    case mozc::commands::Result::NONE: {
        fcitx_mozc->SetAuxString("No result");  // not a fatal error.
        break;
    }
    case mozc::commands::Result::STRING: {
        fcitx_mozc->SetResultString(result.value());
        break;
    }
    }
}

static boolean FcitxMozcPaging(void* arg, boolean prev)
{
    FcitxMozc* mozc = static_cast<FcitxMozc*>(arg);
    return mozc->paging(prev);
}

void MozcResponseParser::ParseCandidates(
    const mozc::commands::Candidates &candidates, FcitxMozc *fcitx_mozc) const {
    const commands::Footer &footer = candidates.footer();
    bool hasPrev = false;
    bool hasNext = false;
    if (candidates.has_footer()) {
        string auxString;
        if (footer.has_label()) {
            // TODO(yusukes,mozc-team): label() is not localized. Currently, it's always
            // written in Japanese (in UTF-8).
            auxString += footer.label();
        } else if (footer.has_sub_label()) {
            // Windows client shows sub_label() only when label() is not specified. We
            // follow the policy.
            auxString += footer.sub_label();
        }

        if (footer.has_index_visible() && footer.index_visible()) {
            // Max size of candidates is 200 so 128 is sufficient size for the buffer.
            char index_buf[128] = {0};
            const int result = snprintf(index_buf,
                                        sizeof(index_buf) - 1,
                                        "%s%d/%d",
                                        (auxString.empty() ? "" : " "),
                                        candidates.focused_index() + 1,
                                        candidates.size());
            DCHECK_GE(result, 0) << "snprintf in ComposeAuxiliaryText failed";
            auxString += index_buf;

            if (candidates.candidate_size() > 0) {

                if (candidates.candidate(0).index() > 0) {
                    hasPrev = true;
                }
                if (candidates.candidate(candidates.candidate_size() - 1).index() + 1 < candidates.size()) {
                    hasNext = true;
                }
            }
        }
        fcitx_mozc->SetAuxString(auxString);
    }

    FcitxCandidateWordList* candList = FcitxInputStateGetCandidateList(fcitx_mozc->GetInputState());
    FcitxCandidateWordReset(candList);
    FcitxCandidateWordSetPageSize(candList, 9);
    if (candidates.has_direction() &&
        candidates.direction() == commands::Candidates::HORIZONTAL) {
        FcitxCandidateWordSetLayoutHint(candList, CLH_Horizontal);
    } else {
        FcitxCandidateWordSetLayoutHint(candList, CLH_Vertical);
    }

    std::map<int32, std::pair<string, string> > usage_map;
    if (candidates.has_usages()) {
        const commands::InformationList& usages = candidates.usages();
        for (size_t i = 0; i < usages.information().size(); ++i) {
            const commands::Information& information = usages.information(i);
            if (!information.has_id() || !information.has_description())
                continue;
            usage_map[information.id()].first = information.title();
            usage_map[information.id()].second = information.description();
        }
    }

#define EMPTY_STR_CHOOSE "\0\0\0\0\0\0\0\0\0\0"
    std::vector<char> choose;

    int focused_index = -1;
    int local_index = -1;
    if (candidates.has_focused_index()) {
        focused_index = candidates.focused_index();
    }
    for (int i = 0; i < candidates.candidate_size(); ++i) {
        const commands::Candidates::Candidate& candidate = candidates.candidate(i);
        const uint32 index = candidate.index();
        FcitxMessageType type;
        if (focused_index != -1 && index == focused_index) {
            local_index = i;
            type = MSG_FIRSTCAND;
        } else {
            type = MSG_OTHER;
        }
        int32* id = (int32*) fcitx_utils_malloc0(sizeof(int32));
        FcitxCandidateWord candWord;
        candWord.callback = FcitxMozcGetCandidateWord;
        candWord.extraType = MSG_OTHER;
        candWord.strExtra = NULL;
        candWord.priv = id;
        candWord.strWord = NULL;
        candWord.wordType = type;
        candWord.owner = fcitx_mozc;

        string value;
        if (use_annotation_ &&
                candidate.has_annotation() &&
                candidate.annotation().has_prefix()) {
            value = candidate.annotation().prefix();
        }
        value += candidate.value();
        if (use_annotation_ &&
                candidate.has_annotation() &&
                candidate.annotation().has_suffix()) {
            value += candidate.annotation().suffix();
        }
        if (use_annotation_ &&
                candidate.has_annotation() &&
                candidate.annotation().has_description()) {
            // Display descriptions ([HALF][KATAKANA], [GREEK], [Black square], etc).
            value += CreateDescriptionString(
                         candidate.annotation().description());
        }

        if (use_annotation_ && focused_index != -1 && index == focused_index) {
            local_index = i;
            type = MSG_FIRSTCAND;

            if (candidate.has_information_id()) {
                std::map<int32, std::pair<string, string> >::iterator it =
                    usage_map.find(candidate.information_id());
                if (it != usage_map.end()) {
                    fcitx_mozc->SetUsage(it->second.first, it->second.second);
                }
                value += CreateDescriptionString(_("Press Ctrl+Alt+H to show usages."));
            }
        }

        if (candidate.has_annotation() &&
            candidate.annotation().has_shortcut()) {
            choose.push_back(candidate.annotation().shortcut().c_str()[0]);
        }

        candWord.strWord = strdup(value.c_str());

        if (candidate.has_id()) {
            const int32 cid = candidate.id();
            DCHECK_NE(kBadCandidateId, cid) << "Unexpected id is passed.";
            *id = cid;
        } else {
            // The parent node of the cascading window does not have an id since the
            // node does not contain a candidate word.
            *id = kBadCandidateId;
        }
        FcitxCandidateWordAppend(candList, &candWord);
    }

    while (choose.size() < 10) {
        choose.push_back('\0');
    }

    if (footer.has_index_visible() && footer.index_visible())
        FcitxCandidateWordSetChoose(candList, choose.data());
    else
        FcitxCandidateWordSetChoose(candList, EMPTY_STR_CHOOSE);
    FcitxCandidateWordSetFocus(candList, local_index);
    FcitxCandidateWordSetOverridePaging(candList, hasPrev, hasNext, FcitxMozcPaging, fcitx_mozc, NULL);
}

static int GetRawCursorPos(const char * str, int upos)
{
    unsigned int i;
    int pos = 0;
    for (i = 0; i < upos; i++) {
        pos += fcitx_utf8_char_len(fcitx_utf8_get_nth_char((char*)str, i));
    }
    return pos;
}


void MozcResponseParser::ParsePreedit(const mozc::commands::Preedit &preedit,
                                      uint32 position,
                                      FcitxMozc *fcitx_mozc) const {
    PreeditInfo *info = new PreeditInfo;
    std::string s;

    for (int i = 0; i < preedit.segment_size(); ++i) {
        const mozc::commands::Preedit_Segment &segment = preedit.segment(i);
        const std::string &str = segment.value();
        FcitxMessageType type = MSG_INPUT;

        switch (segment.annotation()) {
        case mozc::commands::Preedit_Segment::NONE:
            type = (FcitxMessageType) (MSG_INPUT | MSG_NOUNDERLINE);
            break;
        case mozc::commands::Preedit_Segment::UNDERLINE:
            type = (FcitxMessageType) (MSG_TIPS);
            break;
        case mozc::commands::Preedit_Segment::HIGHLIGHT:
            type = (FcitxMessageType) (MSG_CODE | MSG_NOUNDERLINE | MSG_HIGHLIGHT);
            break;
        }
        s += str;

        PreeditItem item;
        item.type = type;
        item.str = str;
        info->preedit.push_back(item);
    }
    info->cursor_pos = GetRawCursorPos(s.c_str(), position);

    fcitx_mozc->SetPreeditInfo(info);
}

}  // namespace fcitx

}  // namespace mozc