1 /* 2 * Copyright (C) 2013 DroidDriver committers 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 io.appium.droiddriver.finders; 18 19 import android.util.Log; 20 21 import io.appium.droiddriver.UiElement; 22 import io.appium.droiddriver.exceptions.ElementNotFoundException; 23 import io.appium.droiddriver.util.Logs; 24 25 /** 26 * Traverses the UiElement tree and returns the first UiElement satisfying 27 * {@link #predicate}. 28 */ 29 public class MatchFinder implements Finder { 30 protected final Predicate<? super UiElement> predicate; 31 32 public MatchFinder(Predicate<? super UiElement> predicate) { 33 if (predicate == null) { 34 this.predicate = Predicates.any(); 35 } else { 36 this.predicate = predicate; 37 } 38 } 39 40 @Override 41 public String toString() { 42 return predicate.toString(); 43 } 44 45 @Override 46 public UiElement find(UiElement context) { 47 if (matches(context)) { 48 Logs.log(Log.INFO, "Found match: " + context); 49 return context; 50 } 51 for (UiElement child : context.getChildren(UiElement.VISIBLE)) { 52 try { 53 return find(child); 54 } catch (ElementNotFoundException enfe) { 55 // Do nothing. Continue searching. 56 } 57 } 58 throw new ElementNotFoundException(this); 59 } 60 61 /** 62 * Returns true if the {@code element} matches this finder. This can be used 63 * to test the exact match of {@code element} when this finder is used in 64 * {@link By#anyOf(MatchFinder...)}. 65 * 66 * @param element The element to validate against 67 * @return true if the element matches 68 */ 69 public final boolean matches(UiElement element) { 70 return predicate.apply(element); 71 } 72 } 73