blob: aef4bd6c7351095f49c21f46b4e59facd626fa77 [file] [log] [blame]
/*
* Copyright (C) 2019 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.textclassifier.intent;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
import android.view.textclassifier.Log;
import android.view.textclassifier.TextClassifier;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Preconditions;
import com.google.android.textclassifier.AnnotatorModel;
import com.google.android.textclassifier.RemoteActionTemplate;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* Creates intents based on {@link RemoteActionTemplate} objects for a ClassificationResult.
*
* @hide
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public final class TemplateClassificationIntentFactory implements ClassificationIntentFactory {
private static final String TAG = TextClassifier.DEFAULT_LOG_TAG;
private final TemplateIntentFactory mTemplateIntentFactory;
private final ClassificationIntentFactory mFallback;
public TemplateClassificationIntentFactory(TemplateIntentFactory templateIntentFactory,
ClassificationIntentFactory fallback) {
mTemplateIntentFactory = Objects.requireNonNull(templateIntentFactory);
mFallback = Objects.requireNonNull(fallback);
}
/**
* Returns a list of {@link LabeledIntent}
* that are constructed from the classification result.
*/
@NonNull
@Override
public List<LabeledIntent> create(
Context context,
String text,
boolean foreignText,
@Nullable Instant referenceTime,
@Nullable AnnotatorModel.ClassificationResult classification) {
if (classification == null) {
return Collections.emptyList();
}
RemoteActionTemplate[] remoteActionTemplates = classification.getRemoteActionTemplates();
if (remoteActionTemplates == null) {
// RemoteActionTemplate is missing, fallback.
Log.w(TAG, "RemoteActionTemplate is missing, fallback to"
+ " LegacyClassificationIntentFactory.");
return mFallback.create(context, text, foreignText, referenceTime, classification);
}
final List<LabeledIntent> labeledIntents =
mTemplateIntentFactory.create(remoteActionTemplates);
if (foreignText) {
ClassificationIntentFactory.insertTranslateAction(labeledIntents, context, text.trim());
}
return labeledIntents;
}
}