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
|
/*
* 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.service.translation;
import static android.view.translation.TranslationManager.STATUS_SYNC_CALL_FAIL;
import static android.view.translation.TranslationManager.STATUS_SYNC_CALL_SUCCESS;
import static android.view.translation.Translator.EXTRA_SERVICE_BINDER;
import static android.view.translation.Translator.EXTRA_SESSION_ID;
import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
import android.annotation.CallSuper;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ParceledListSlice;
import android.os.BaseBundle;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.IBinder;
import android.os.ICancellationSignal;
import android.os.Looper;
import android.os.RemoteException;
import android.os.ResultReceiver;
import android.util.Log;
import android.view.translation.ITranslationDirectManager;
import android.view.translation.ITranslationServiceCallback;
import android.view.translation.TranslationCapability;
import android.view.translation.TranslationContext;
import android.view.translation.TranslationManager;
import android.view.translation.TranslationRequest;
import android.view.translation.TranslationResponse;
import android.view.translation.TranslationSpec;
import android.view.translation.Translator;
import com.android.internal.os.IResultReceiver;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
/**
* Service for translating text.
* @hide
*/
@SystemApi
public abstract class TranslationService extends Service {
private static final String TAG = "TranslationService";
/**
* The {@link Intent} that must be declared as handled by the service.
*
* <p>To be supported, the service must also require the
* {@link android.Manifest.permission#BIND_TRANSLATION_SERVICE} permission so
* that other applications can not abuse it.
*/
public static final String SERVICE_INTERFACE =
"android.service.translation.TranslationService";
/**
* Name under which a TranslationService component publishes information about itself.
*
* <p>This meta-data should reference an XML resource containing a
* <code><{@link
* android.R.styleable#TranslationService translation-service}></code> tag.
*
* <p>Here's an example of how to use it on {@code AndroidManifest.xml}:
* <pre> <translation-service
* android:settingsActivity="foo.bar.SettingsActivity"
* . . .
* /></pre>
*/
public static final String SERVICE_META_DATA = "android.translation_service";
private Handler mHandler;
private ITranslationServiceCallback mCallback;
/**
* Binder to receive calls from system server.
*/
private final ITranslationService mInterface = new ITranslationService.Stub() {
@Override
public void onConnected(IBinder callback) {
mHandler.sendMessage(obtainMessage(TranslationService::handleOnConnected,
TranslationService.this, callback));
}
@Override
public void onDisconnected() {
mHandler.sendMessage(obtainMessage(TranslationService::onDisconnected,
TranslationService.this));
}
@Override
public void onCreateTranslationSession(TranslationContext translationContext,
int sessionId, IResultReceiver receiver) throws RemoteException {
mHandler.sendMessage(obtainMessage(TranslationService::handleOnCreateTranslationSession,
TranslationService.this, translationContext, sessionId, receiver));
}
@Override
public void onTranslationCapabilitiesRequest(@TranslationSpec.DataFormat int sourceFormat,
@TranslationSpec.DataFormat int targetFormat,
@NonNull ResultReceiver resultReceiver) throws RemoteException {
mHandler.sendMessage(
obtainMessage(TranslationService::handleOnTranslationCapabilitiesRequest,
TranslationService.this, sourceFormat, targetFormat,
resultReceiver));
}
};
/**
* Interface definition for a callback to be invoked when the translation is compleled.
* @removed use a {@link Consumer} instead.
*/
@Deprecated
public interface OnTranslationResultCallback {
/**
* Notifies the Android System that a translation request
* {@link TranslationService#onTranslationRequest(TranslationRequest, int,
* CancellationSignal, OnTranslationResultCallback)} was successfully fulfilled by the
* service.
*
* <p>This method should always be called, even if the service cannot fulfill the request
* (in which case it should be called with a TranslationResponse with
* {@link android.view.translation.TranslationResponse#TRANSLATION_STATUS_UNKNOWN_ERROR},
* or {@link android.view.translation.TranslationResponse
* #TRANSLATION_STATUS_LANGUAGE_UNAVAILABLE}).
*
* @param response translation response for the provided request infos.
*
* @throws IllegalStateException if this method was already called.
*/
void onTranslationSuccess(@NonNull TranslationResponse response);
/**
* @removed use {@link #onTranslationSuccess} with an error response instead.
*/
@Deprecated
void onError();
}
/**
* Binder that receives calls from the app.
*/
private final ITranslationDirectManager mClientInterface =
new ITranslationDirectManager.Stub() {
@Override
public void onTranslationRequest(TranslationRequest request, int sessionId,
ICancellationSignal transport, ITranslationCallback callback)
throws RemoteException {
final Consumer<TranslationResponse> consumer =
new OnTranslationResultCallbackWrapper(callback);
mHandler.sendMessage(obtainMessage(TranslationService::onTranslationRequest,
TranslationService.this, request, sessionId,
CancellationSignal.fromTransport(transport),
consumer));
}
@Override
public void onFinishTranslationSession(int sessionId) throws RemoteException {
mHandler.sendMessage(obtainMessage(
TranslationService::onFinishTranslationSession,
TranslationService.this, sessionId));
}
};
@CallSuper
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper(), null, true);
BaseBundle.setShouldDefuse(true);
}
@Override
@Nullable
public final IBinder onBind(@NonNull Intent intent) {
if (SERVICE_INTERFACE.equals(intent.getAction())) {
return mInterface.asBinder();
}
Log.w(TAG, "Tried to bind to wrong intent (should be " + SERVICE_INTERFACE + ": " + intent);
return null;
}
/**
* Called when the Android system connects to service.
*
* <p>You should generally do initialization here rather than in {@link #onCreate}.
*/
public void onConnected() {
}
/**
* Called when the Android system disconnects from the service.
*
* <p> At this point this service may no longer be an active {@link TranslationService}.
* It should not make calls on {@link TranslationManager} that requires the caller to be
* the current service.
*/
public void onDisconnected() {
}
/**
* Called to notify the service that a session was created
* (see {@link android.view.translation.Translator}).
*
* <p>The service must call {@code callback.accept()} to acknowledge whether the session is
* supported and created successfully. If the translation context is not supported, the service
* should call back with {@code false}.</p>
*
* @param translationContext the {@link TranslationContext} of the session being created.
* @param sessionId the id of the session.
* @param callback {@link Consumer} to notify whether the session was successfully created.
*/
// TODO(b/176464808): the session id won't be unique cross client/server process. Need to find
// solution to make it's safe.
public abstract void onCreateTranslationSession(@NonNull TranslationContext translationContext,
int sessionId, @NonNull Consumer<Boolean> callback);
/**
* @removed use {@link #onCreateTranslationSession(TranslationContext, int, Consumer)}
* instead.
*/
@Deprecated
public void onCreateTranslationSession(@NonNull TranslationContext translationContext,
int sessionId) {
// no-op
}
/**
* Called when a translation session is finished.
*
* <p>The translation session is finished when the client calls {@link Translator#destroy()} on
* the corresponding translator.
*
* @param sessionId id of the session that finished.
*/
public abstract void onFinishTranslationSession(int sessionId);
/**
* @removed use
* {@link #onTranslationRequest(TranslationRequest, int, CancellationSignal, Consumer)} instead.
*/
@Deprecated
public void onTranslationRequest(@NonNull TranslationRequest request, int sessionId,
@Nullable CancellationSignal cancellationSignal,
@NonNull OnTranslationResultCallback callback) {
// no-op
}
/**
* Called to the service with a {@link TranslationRequest} to be translated.
*
* <p>The service must call {@code callback.accept()} with the {@link TranslationResponse}. If
* {@link TranslationRequest#FLAG_PARTIAL_RESPONSES} was set, the service may call
* {@code callback.accept()} multiple times with partial responses.</p>
*
* @param request The translation request containing the data to be translated.
* @param sessionId id of the session that sent the translation request.
* @param cancellationSignal A {@link CancellationSignal} that notifies when a client has
* cancelled the operation in progress.
* @param callback {@link Consumer} to pass back the translation response.
*/
public abstract void onTranslationRequest(@NonNull TranslationRequest request, int sessionId,
@Nullable CancellationSignal cancellationSignal,
@NonNull Consumer<TranslationResponse> callback);
/**
* Called to request a set of {@link TranslationCapability}s that are supported by the service.
*
* <p>The set of translation capabilities are limited to those supporting the source and target
* {@link TranslationSpec.DataFormat}. e.g. Calling this with
* {@link TranslationSpec#DATA_FORMAT_TEXT} as source and target returns only capabilities that
* translates text to text.</p>
*
* <p>Must call {@code callback.accept} to pass back the set of translation capabilities.</p>
*
* @param sourceFormat data format restriction of the translation source spec.
* @param targetFormat data format restriction of the translation target spec.
* @param callback {@link Consumer} to pass back the set of translation capabilities.
*/
public abstract void onTranslationCapabilitiesRequest(
@TranslationSpec.DataFormat int sourceFormat,
@TranslationSpec.DataFormat int targetFormat,
@NonNull Consumer<Set<TranslationCapability>> callback);
/**
* Called by the service to notify an update in existing {@link TranslationCapability}s.
*
* @param capability the updated {@link TranslationCapability} with its new states and flags.
*/
public final void updateTranslationCapability(@NonNull TranslationCapability capability) {
Objects.requireNonNull(capability, "translation capability should not be null");
final ITranslationServiceCallback callback = mCallback;
if (callback == null) {
Log.w(TAG, "updateTranslationCapability(): no server callback");
return;
}
try {
callback.updateTranslationCapability(capability);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
}
private void handleOnConnected(@NonNull IBinder callback) {
mCallback = ITranslationServiceCallback.Stub.asInterface(callback);
onConnected();
}
// TODO(b/176464808): Need to handle client dying case
private void handleOnCreateTranslationSession(@NonNull TranslationContext translationContext,
int sessionId, IResultReceiver resultReceiver) {
onCreateTranslationSession(translationContext, sessionId,
new Consumer<Boolean>() {
@Override
public void accept(Boolean created) {
try {
if (!created) {
Log.w(TAG, "handleOnCreateTranslationSession(): context="
+ translationContext + " not supported by service.");
resultReceiver.send(STATUS_SYNC_CALL_FAIL, null);
return;
}
final Bundle extras = new Bundle();
extras.putBinder(EXTRA_SERVICE_BINDER, mClientInterface.asBinder());
extras.putInt(EXTRA_SESSION_ID, sessionId);
resultReceiver.send(STATUS_SYNC_CALL_SUCCESS, extras);
} catch (RemoteException e) {
Log.w(TAG, "RemoteException sending client interface: " + e);
}
}
});
}
private void handleOnTranslationCapabilitiesRequest(
@TranslationSpec.DataFormat int sourceFormat,
@TranslationSpec.DataFormat int targetFormat,
@NonNull ResultReceiver resultReceiver) {
onTranslationCapabilitiesRequest(sourceFormat, targetFormat,
new Consumer<Set<TranslationCapability>>() {
@Override
public void accept(Set<TranslationCapability> values) {
if (!isValidCapabilities(sourceFormat, targetFormat, values)) {
throw new IllegalStateException("Invalid capabilities and "
+ "format compatibility");
}
final Bundle bundle = new Bundle();
final ParceledListSlice<TranslationCapability> listSlice =
new ParceledListSlice<>(Arrays.asList(
values.toArray(new TranslationCapability[0])));
bundle.putParcelable(TranslationManager.EXTRA_CAPABILITIES, listSlice);
resultReceiver.send(STATUS_SYNC_CALL_SUCCESS, bundle);
}
});
}
/**
* Helper method to validate capabilities and format compatibility.
*/
private boolean isValidCapabilities(@TranslationSpec.DataFormat int sourceFormat,
@TranslationSpec.DataFormat int targetFormat, Set<TranslationCapability> capabilities) {
if (sourceFormat != TranslationSpec.DATA_FORMAT_TEXT
&& targetFormat != TranslationSpec.DATA_FORMAT_TEXT) {
return true;
}
for (TranslationCapability capability : capabilities) {
if (capability.getState() == TranslationCapability.STATE_REMOVED_AND_AVAILABLE) {
return false;
}
}
return true;
}
}
|