1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.server.wm; 18 19 import static junit.framework.Assert.assertTrue; 20 21 import androidx.test.platform.app.InstrumentationRegistry; 22 23 import com.android.compatibility.common.util.SystemUtil; 24 25 import java.io.IOException; 26 import java.util.regex.Matcher; 27 import java.util.regex.Pattern; 28 29 /** 30 * A session to enable/disable the feature to ignore 31 * {@link android.app.Activity#setRequestedOrientation(int)} 32 */ 33 public class IgnoreOrientationRequestSession implements AutoCloseable { 34 private static final String WM_SET_IGNORE_ORIENTATION_REQUEST = 35 "wm set-ignore-orientation-request "; 36 private static final String WM_GET_IGNORE_ORIENTATION_REQUEST = 37 "wm get-ignore-orientation-request"; 38 private static final Pattern IGNORE_ORIENTATION_REQUEST_PATTERN = 39 Pattern.compile("ignoreOrientationRequest (true|false) for displayId=\\d+"); 40 41 final boolean mInitialIgnoreOrientationRequest; 42 IgnoreOrientationRequestSession(boolean enable)43 public IgnoreOrientationRequestSession(boolean enable) { 44 Matcher matcher = IGNORE_ORIENTATION_REQUEST_PATTERN.matcher( 45 executeShellCommand(WM_GET_IGNORE_ORIENTATION_REQUEST)); 46 assertTrue("get-ignore-orientation-request should match pattern", 47 matcher.find()); 48 mInitialIgnoreOrientationRequest = Boolean.parseBoolean(matcher.group(1)); 49 50 executeShellCommand(WM_SET_IGNORE_ORIENTATION_REQUEST + (enable ? "true" : "false")); 51 } 52 53 @Override close()54 public void close() { 55 executeShellCommand(WM_SET_IGNORE_ORIENTATION_REQUEST + mInitialIgnoreOrientationRequest); 56 } 57 executeShellCommand(String command)58 private static String executeShellCommand(String command) { 59 try { 60 return SystemUtil.runShellCommand(InstrumentationRegistry.getInstrumentation(), 61 command); 62 } catch (IOException e) { 63 throw new RuntimeException(e); 64 } 65 } 66 } 67