File: UiTranslationManager.java

package info (click to toggle)
android-platform-frameworks-base 1%3A14~beta1-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 326,092 kB
  • sloc: java: 2,032,373; xml: 343,016; cpp: 304,181; python: 3,683; ansic: 2,090; sh: 1,871; makefile: 117; sed: 19
file content (421 lines) | stat: -rw-r--r-- 17,784 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.view.translation;

import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.app.assist.ActivityId;
import android.content.ComponentName;
import android.content.Context;
import android.icu.util.ULocale;
import android.os.Binder;
import android.os.Bundle;
import android.os.IRemoteCallback;
import android.os.RemoteException;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.view.autofill.AutofillId;
import android.widget.TextView;

import com.android.internal.annotations.GuardedBy;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.function.Consumer;

/**
 * <p>The {@link UiTranslationManager} class provides ways for apps to use the ui translation
 * function in framework.
 *
 * <p> The UI translation provides ways for apps to support inline translation for the views. For
 * example the system supports text translation for {@link TextView}. To support UI translation for
 * your views, you should override the following methods to provide the content to be translated
 * and deal with the translated result. Here is an example for {@link TextView}-like views:
 *
 * <pre><code>
 * public class MyTextView extends View {
 *     public MyTextView(...) {
 *         // implements how to show the translated result in your View in
 *         // ViewTranslationCallback and set it by setViewTranslationCallback()
 *         setViewTranslationCallback(new MyViewTranslationCallback());
 *     }
 *
 *     public void onCreateViewTranslationRequest(int[] supportedFormats,
 *             Consumer<ViewTranslationRequest> requestsCollector) {
 *        // collect the information that needs to be translated
 *        ViewTranslationRequest.Builder requestBuilder =
 *                     new ViewTranslationRequest.Builder(getAutofillId());
 *        requestBuilder.setValue(ViewTranslationRequest.ID_TEXT,
 *                         TranslationRequestValue.forText(etText()));
 *        requestsCollector.accept(requestBuilder.build());
 *     }
 *
 *     public void onProvideContentCaptureStructure(
 *             ViewStructure structure, int flags) {
 *         // set ViewTranslationResponse
 *         super.onViewTranslationResponse(response);
 *     }
 * }
 * </code></pre>
 *
 * <p>If your view provides its own virtual hierarchy (for example, if it's a browser that draws the
 * HTML using {@link android.graphics.Canvas} or native libraries in a different render process),
 * you must override {@link View#onCreateVirtualViewTranslationRequests(long[], int[], Consumer)} to
 * provide the content to be translated and implement
 * {@link View#onVirtualViewTranslationResponses(android.util.LongSparseArray)} for the translated
 * result. You also need to implement {@link android.view.translation.ViewTranslationCallback} to
 * handle the translated information show or hide in your {@link View}.
 */
public final class UiTranslationManager {

    private static final String TAG = "UiTranslationManager";

    /**
     * The tag which uses for enabling debug log dump. To enable it, we can use command "adb shell
     * setprop log.tag.UiTranslation DEBUG".
     *
     * @hide
     */
    public static final String LOG_TAG = "UiTranslation";

    /**
     * The state the caller requests to enable UI translation.
     *
     * @hide
     */
    public static final int STATE_UI_TRANSLATION_STARTED = 0;
    /**
     * The state caller requests to pause UI translation. It will switch back to the original text.
     *
     * @hide
     */
    public static final int STATE_UI_TRANSLATION_PAUSED = 1;
    /**
     * The state caller requests to resume the paused UI translation. It will show the translated
     * text again if the text had been translated.
     *
     * @hide
     */
    public static final int STATE_UI_TRANSLATION_RESUMED = 2;
    /**
     * The state caller requests to disable UI translation when it no longer needs translation.
     *
     * @hide
     */
    public static final int STATE_UI_TRANSLATION_FINISHED = 3;

    /** @hide */
    @IntDef(prefix = {"STATE__TRANSLATION"}, value = {
            STATE_UI_TRANSLATION_STARTED,
            STATE_UI_TRANSLATION_PAUSED,
            STATE_UI_TRANSLATION_RESUMED,
            STATE_UI_TRANSLATION_FINISHED
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface UiTranslationState {
    }

    // Keys for the data transmitted in the internal UI Translation state callback.
    /** @hide */
    public static final String EXTRA_STATE = "state";
    /** @hide */
    public static final String EXTRA_SOURCE_LOCALE = "source_locale";
    /** @hide */
    public static final String EXTRA_TARGET_LOCALE = "target_locale";
    /** @hide */
    public static final String EXTRA_PACKAGE_NAME = "package_name";

    @NonNull
    private final Context mContext;

    private final ITranslationManager mService;

    /**
     * @hide
     */
    public UiTranslationManager(@NonNull Context context, ITranslationManager service) {
        mContext = Objects.requireNonNull(context);
        mService = service;
    }

    /**
     * @removed Use {@link #startTranslation(TranslationSpec, TranslationSpec, List, ActivityId,
     * UiTranslationSpec)} instead.
     * @hide
     */
    @RequiresPermission(android.Manifest.permission.MANAGE_UI_TRANSLATION)
    @Deprecated
    @SystemApi
    public void startTranslation(@NonNull TranslationSpec sourceSpec,
            @NonNull TranslationSpec targetSpec, @NonNull List<AutofillId> viewIds,
            @NonNull ActivityId activityId) {
        startTranslation(
                sourceSpec, targetSpec, viewIds, activityId,
                new UiTranslationSpec.Builder().setShouldPadContentForCompat(true).build());
    }

    /**
     * Request ui translation for a given Views.
     *
     * @param sourceSpec        {@link TranslationSpec} for the data to be translated.
     * @param targetSpec        {@link TranslationSpec} for the translated data.
     * @param viewIds           A list of the {@link View}'s {@link AutofillId} which needs to be
     *                          translated
     * @param activityId        the identifier for the Activity which needs ui translation
     * @param uiTranslationSpec configuration for translation of the specified views
     * @throws IllegalArgumentException if the no {@link View}'s {@link AutofillId} in the list
     * @hide
     */
    @RequiresPermission(android.Manifest.permission.MANAGE_UI_TRANSLATION)
    @SystemApi
    public void startTranslation(@NonNull TranslationSpec sourceSpec,
            @NonNull TranslationSpec targetSpec, @NonNull List<AutofillId> viewIds,
            @NonNull ActivityId activityId, @NonNull UiTranslationSpec uiTranslationSpec) {
        // TODO(b/177789967): Return result code or find a way to notify the status.
        Objects.requireNonNull(sourceSpec);
        Objects.requireNonNull(targetSpec);
        Objects.requireNonNull(viewIds);
        Objects.requireNonNull(activityId);
        Objects.requireNonNull(activityId.getToken());
        Objects.requireNonNull(uiTranslationSpec);
        if (viewIds.size() == 0) {
            throw new IllegalArgumentException("Invalid empty views: " + viewIds);
        }
        try {
            mService.updateUiTranslationState(STATE_UI_TRANSLATION_STARTED, sourceSpec,
                    targetSpec, viewIds, activityId.getToken(), activityId.getTaskId(),
                    uiTranslationSpec,
                    mContext.getUserId());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

    /**
     * Request to disable the ui translation. It will destroy all the {@link Translator}s and no
     * longer to show the translated text.
     *
     * @param activityId the identifier for the Activity which needs ui translation
     * @throws NullPointerException the activityId or
     *                              {@link android.app.assist.ActivityId#getToken()} is {@code null}
     * @hide
     */
    @RequiresPermission(android.Manifest.permission.MANAGE_UI_TRANSLATION)
    @SystemApi
    public void finishTranslation(@NonNull ActivityId activityId) {
        try {
            Objects.requireNonNull(activityId);
            Objects.requireNonNull(activityId.getToken());
            mService.updateUiTranslationState(STATE_UI_TRANSLATION_FINISHED,
                    null /* sourceSpec */, null /* targetSpec */, null /* viewIds */,
                    activityId.getToken(), activityId.getTaskId(), null /* uiTranslationSpec */,
                    mContext.getUserId());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

    /**
     * Request to pause the current ui translation's {@link Translator} which will switch back to
     * the original language.
     *
     * @param activityId the identifier for the Activity which needs ui translation
     * @throws NullPointerException the activityId or
     *                              {@link android.app.assist.ActivityId#getToken()} is {@code null}
     * @hide
     */
    @RequiresPermission(android.Manifest.permission.MANAGE_UI_TRANSLATION)
    @SystemApi
    public void pauseTranslation(@NonNull ActivityId activityId) {
        try {
            Objects.requireNonNull(activityId);
            Objects.requireNonNull(activityId.getToken());
            mService.updateUiTranslationState(STATE_UI_TRANSLATION_PAUSED,
                    null /* sourceSpec */, null /* targetSpec */, null /* viewIds */,
                    activityId.getToken(), activityId.getTaskId(), null /* uiTranslationSpec */,
                    mContext.getUserId());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

    /**
     * Request to resume the paused ui translation's {@link Translator} which will switch to the
     * translated language if the text had been translated.
     *
     * @param activityId the identifier for the Activity which needs ui translation
     * @throws NullPointerException the activityId or
     *                              {@link android.app.assist.ActivityId#getToken()} is {@code null}
     * @hide
     */
    @RequiresPermission(android.Manifest.permission.MANAGE_UI_TRANSLATION)
    @SystemApi
    public void resumeTranslation(@NonNull ActivityId activityId) {
        try {
            Objects.requireNonNull(activityId);
            Objects.requireNonNull(activityId.getToken());
            mService.updateUiTranslationState(STATE_UI_TRANSLATION_RESUMED,
                    null /* sourceSpec */, null /* targetSpec */, null /* viewIds */,
                    activityId.getToken(), activityId.getTaskId(), null /* uiTranslationSpec */,
                    mContext.getUserId());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

    /**
     * Register for notifications of UI Translation state changes on the foreground Activity. This
     * is available to the owning application itself and also the current input method.
     * <p>
     * The application whose UI is being translated can use this to customize the UI Translation
     * behavior in ways that aren't made easy by methods like
     * {@link View#onCreateViewTranslationRequest(int[], Consumer)}.
     * <p>
     * Input methods can use this to offer complementary features to UI Translation; for example,
     * enabling outgoing message translation when the system is translating incoming messages in a
     * communication app.
     * <p>
     * Starting from {@link android.os.Build.VERSION_CODES#TIRAMISU}, if Activities are already
     * being translated when a callback is registered, methods on the callback will be invoked for
     * each translated activity, depending on the state of translation:
     * <ul>
     *     <li>If translation is <em>not</em> paused,
     *     {@link UiTranslationStateCallback#onStarted} will be invoked.</li>
     *     <li>If translation <em>is</em> paused, {@link UiTranslationStateCallback#onStarted}
     *     will first be invoked, followed by {@link UiTranslationStateCallback#onPaused}.</li>
     * </ul>
     *
     * @param callback the callback to register for receiving the state change
     *                 notifications
     */
    public void registerUiTranslationStateCallback(
            @NonNull @CallbackExecutor Executor executor,
            @NonNull UiTranslationStateCallback callback) {
        Objects.requireNonNull(executor);
        Objects.requireNonNull(callback);
        synchronized (mCallbacks) {
            if (mCallbacks.containsKey(callback)) {
                Log.w(TAG, "registerUiTranslationStateCallback: callback already registered;"
                        + " ignoring.");
                return;
            }
            final IRemoteCallback remoteCallback =
                    new UiTranslationStateRemoteCallback(executor, callback);
            try {
                mService.registerUiTranslationStateCallback(remoteCallback, mContext.getUserId());
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
            mCallbacks.put(callback, remoteCallback);
        }
    }

    /**
     * Unregister {@code callback}.
     *
     * @see #registerUiTranslationStateCallback(Executor, UiTranslationStateCallback)
     */
    public void unregisterUiTranslationStateCallback(@NonNull UiTranslationStateCallback callback) {
        Objects.requireNonNull(callback);

        synchronized (mCallbacks) {
            final IRemoteCallback remoteCallback = mCallbacks.get(callback);
            if (remoteCallback == null) {
                Log.w(TAG, "unregisterUiTranslationStateCallback: callback not found; ignoring.");
                return;
            }
            try {
                mService.unregisterUiTranslationStateCallback(remoteCallback, mContext.getUserId());
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
            mCallbacks.remove(callback);
        }
    }

    /**
     * Notify apps the translation is finished because {@link #finishTranslation(ActivityId)} is
     * called or Activity is destroyed.
     *
     * @param activityDestroyed if the ui translation is finished because of activity destroyed.
     * @param activityId        the identifier for the Activity which needs ui translation
     * @param componentName     the ui translated Activity componentName.
     * @hide
     */
    public void onTranslationFinished(boolean activityDestroyed, ActivityId activityId,
            ComponentName componentName) {
        try {
            mService.onTranslationFinished(activityDestroyed, activityId.getToken(), componentName,
                    mContext.getUserId());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

    @NonNull
    @GuardedBy("mCallbacks")
    private final Map<UiTranslationStateCallback, IRemoteCallback> mCallbacks = new ArrayMap<>();

    private static class UiTranslationStateRemoteCallback extends IRemoteCallback.Stub {
        private final Executor mExecutor;
        private final UiTranslationStateCallback mCallback;
        private ULocale mSourceLocale;
        private ULocale mTargetLocale;

        UiTranslationStateRemoteCallback(Executor executor,
                UiTranslationStateCallback callback) {
            mExecutor = executor;
            mCallback = callback;
        }

        @Override
        public void sendResult(Bundle bundle) {
            Binder.withCleanCallingIdentity(() -> mExecutor.execute(() -> onStateChange(bundle)));
        }

        private void onStateChange(Bundle bundle) {
            int state = bundle.getInt(EXTRA_STATE);
            String packageName = bundle.getString(EXTRA_PACKAGE_NAME);
            switch (state) {
                case STATE_UI_TRANSLATION_STARTED:
                    mSourceLocale = bundle.getSerializable(EXTRA_SOURCE_LOCALE, ULocale.class);
                    mTargetLocale = bundle.getSerializable(EXTRA_TARGET_LOCALE, ULocale.class);
                    mCallback.onStarted(mSourceLocale, mTargetLocale, packageName);
                    break;
                case STATE_UI_TRANSLATION_RESUMED:
                    mCallback.onResumed(mSourceLocale, mTargetLocale, packageName);
                    break;
                case STATE_UI_TRANSLATION_PAUSED:
                    mCallback.onPaused(packageName);
                    break;
                case STATE_UI_TRANSLATION_FINISHED:
                    mCallback.onFinished(packageName);
                    break;
                default:
                    Log.wtf(TAG, "Unexpected translation state:" + state);
            }
        }
    }
}