1 package org.mozilla.geckoview.test;
2 
3 import android.util.Log;
4 
5 import androidx.annotation.NonNull;
6 import androidx.annotation.Nullable;
7 
8 import org.json.JSONException;
9 import org.json.JSONObject;
10 import org.mozilla.geckoview.GeckoResult;
11 import org.mozilla.geckoview.WebExtension;
12 
13 // Receives API calls from AppUiTestDelegate.jsm and forwards the calls to the
14 // Api impl.
15 public class TestRunnerApiEngine implements WebExtension.MessageDelegate {
16     private final static String LOGTAG = "TestRunnerAPI";
17 
18     public interface Api {
clickBrowserAction(String extensionId)19         GeckoResult<Void> clickBrowserAction(String extensionId);
clickPageAction(String extensionId)20         GeckoResult<Void> clickPageAction(String extensionId);
closePopup()21         GeckoResult<Void> closePopup();
awaitExtensionPopup(String extensionId)22         GeckoResult<Void> awaitExtensionPopup(String extensionId);
23     }
24 
25     private final Api mImpl;
26 
TestRunnerApiEngine(final Api impl)27     public TestRunnerApiEngine(final Api impl) {
28         mImpl = impl;
29     }
30 
31     @SuppressWarnings("unchecked")
handleMessage(final JSONObject message)32     private GeckoResult<Object> handleMessage(final JSONObject message) throws JSONException {
33         final String type = message.getString("type");
34 
35         Log.i(LOGTAG, "Test API: " + type);
36 
37         if ("clickBrowserAction".equals(type)) {
38             return (GeckoResult) mImpl.clickBrowserAction(message.getString("extensionId"));
39         } else if ("clickPageAction".equals(type)) {
40             return (GeckoResult) mImpl.clickPageAction(message.getString("extensionId"));
41         } else if ("closeBrowserAction".equals(type)) {
42             return (GeckoResult) mImpl.closePopup();
43         } else if ("closePageAction".equals(type)) {
44             return(GeckoResult)  mImpl.closePopup();
45         } else if ("awaitExtensionPanel".equals(type)) {
46             return (GeckoResult) mImpl.awaitExtensionPopup(message.getString("extensionId"));
47         }
48 
49         return GeckoResult.fromException(new RuntimeException("Unrecognized command " + type));
50     }
51 
52     @Nullable
53     @Override
onMessage(@onNull final String nativeApp, @NonNull final Object message, @NonNull final WebExtension.MessageSender sender)54     public GeckoResult<Object> onMessage(@NonNull final String nativeApp,
55                                          @NonNull final Object message,
56                                          @NonNull final WebExtension.MessageSender sender) {
57         try {
58             return handleMessage((JSONObject) message);
59         } catch (final JSONException ex) {
60             throw new RuntimeException(ex);
61         }
62     }
63 }
64