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 17package com.google.android.droiddriver.instrumentation; 18 19import android.graphics.Bitmap; 20import android.graphics.Canvas; 21import android.graphics.Rect; 22import android.graphics.RectF; 23import android.graphics.Bitmap.Config; 24import android.util.Log; 25import android.view.View; 26 27import com.google.android.droiddriver.base.BaseUiDevice; 28import com.google.android.droiddriver.base.DroidDriverContext; 29import com.google.android.droiddriver.util.Logs; 30 31class InstrumentationUiDevice extends BaseUiDevice { 32 private final DroidDriverContext<View, ViewElement> context; 33 34 InstrumentationUiDevice(DroidDriverContext<View, ViewElement> context) { 35 this.context = context; 36 } 37 38 @Override 39 protected Bitmap takeScreenshot() { 40 ScreenshotRunnable screenshotRunnable = 41 new ScreenshotRunnable(context.getDriver().getRootElement().getRawElement()); 42 context.runOnMainSync(screenshotRunnable); 43 return screenshotRunnable.screenshot; 44 } 45 46 @Override 47 protected DroidDriverContext<View, ViewElement> getContext() { 48 return context; 49 } 50 51 private static class ScreenshotRunnable implements Runnable { 52 private final View rootView; 53 Bitmap screenshot; 54 55 private ScreenshotRunnable(View rootView) { 56 this.rootView = rootView; 57 } 58 59 @Override 60 public void run() { 61 try { 62 rootView.destroyDrawingCache(); 63 rootView.buildDrawingCache(false); 64 Bitmap drawingCache = rootView.getDrawingCache(); 65 int[] xy = new int[2]; 66 rootView.getLocationOnScreen(xy); 67 if (xy[0] == 0 && xy[1] == 0) { 68 screenshot = Bitmap.createBitmap(drawingCache); 69 } else { 70 Canvas canvas = new Canvas(); 71 Rect rect = new Rect(0, 0, drawingCache.getWidth(), drawingCache.getHeight()); 72 rect.offset(xy[0], xy[1]); 73 screenshot = 74 Bitmap.createBitmap(rect.width() + xy[0], rect.height() + xy[1], Config.ARGB_8888); 75 canvas.setBitmap(screenshot); 76 canvas.drawBitmap(drawingCache, null, new RectF(rect), null); 77 canvas.setBitmap(null); 78 } 79 rootView.destroyDrawingCache(); 80 } catch (Throwable e) { 81 Logs.log(Log.ERROR, e); 82 } 83 } 84 } 85} 86