
package sc.tool.screenshot;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.media.Image;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Toast;


public class ScreenTool
{
	// new Handler(Looper.getMainLooper()).postDelayed(r, 5000);
	
	/** Activity截取屏幕并自动保存 */
	public static boolean GetScreen(Activity activity)
	{
		Bitmap pic = GetScreen_Pic(activity);
		String picPath = GetDir() + NewName();
		
		boolean result = SavePic(pic, picPath);
		Toast.makeText(activity, "截屏已保存" + "\n" + picPath, Toast.LENGTH_SHORT).show();
		
		return result;
	}
	
	/** 基于Activity的截屏（无需申请权限或root,仅能截取到当前Activity界面） */
	private static Bitmap GetScreen_Pic(Activity activity)
	{
		View decorView = activity.getWindow().getDecorView();    	// 获取当前activity所在的最顶层的view--DecorView
		// int statusBarHeight = GetStatusBarHeight(activity);
		decorView.setDrawingCacheEnabled(true);         			// 启用绘图缓存
		decorView.buildDrawingCache();                  			// 强制构建绘图缓存（防止上面启用绘图缓存的操作失败）
		Bitmap bitmap = decorView.getDrawingCache();     			// 获取绘图缓存中的 bitmap
		bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight());	// 创建副本作为返回对象
		
		// // 裁切图像，去除状态栏
		// int newBmpHeight = bitmap.getHeight() - statusBarHeight; // 最终截取的图片的高度（取出状态栏之后的高度）
		// bitmap = Bitmap.createBitmap(bitmap, 0, statusBarHeight, bitmap.getWidth(), newBmpHeight);
		// decorView.setDrawingCacheEnabled(false); // createBitmap完成之后一定要置为false，否则短时间内多次截图时内容不会变化！
		
		return bitmap;
	}
	
	/** 获取Activity状态栏高度 */
	private static int GetStatusBarHeight(Activity activity)
	{
		View decorView = activity.getWindow().getDecorView();	// 获取当前activity所在的最顶层的view--DecorView
		Rect rect = new Rect();
		decorView.getWindowVisibleDisplayFrame(rect);
		return rect.top;
	}
	
	/** 获取图像保存路径 */
	private static String GetDir()
	{
		String path = "sc/screeenShot/";
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))	// 如果SD存储设备可用
		{
			path = Environment.getExternalStorageDirectory().getPath() + File.separator + path;
			File dir = new File(path);
			if (!dir.exists()) dir.mkdirs();   // 创建目录
		}
		return path;
	}
	
	private static int count = 0;
	private static String preTime = "";
	
	/** 获取图像名称 */
	private static String NewName()
	{
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String date = formatter.format(new Date());
		
		DateFormat formatter2 = new SimpleDateFormat("HH.mm.ss");
		String time = formatter2.format(new Date());
		
		if (!preTime.equals(time))
		{
			count = 1;
			preTime = time;
		}
		else count++;
		
		String fileName = date + "_" + time + "_" + count + ".png";
		return fileName;
	}
	
	/** 保存 bitmap到指定的文件路径 */
	private static boolean SavePic(Bitmap bitmap, String picPath)
	{
		boolean saveSuccess = false;
		if (bitmap != null)
		{
			try
			{
				File file = new File(picPath);
				
				File dir = file.getParentFile();
				if (!dir.exists()) dir.mkdirs();   			// 创建目录
				if (!file.exists()) file.createNewFile();	// 创建新的文件
					
				FileOutputStream fos = new FileOutputStream(file);
				saveSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);	// 根据指定的格式、质量、输出流 将bitmap保存到本地，并返回是否保存成功
				fos.flush();
				fos.close();    // 关闭流防止溢出
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
		return saveSuccess;
	}
	
	/** 保存 bitmap，自动生成图像名称 */
	public static boolean SaveScreen(final Context context, Bitmap pic)
	{
		if (pic == null) return false;
		
		final String picPath = GetDir() + NewName();
		boolean result = SavePic(pic, picPath);
		
		// 显示提示信息
		Runnable r = new Runnable()
		{
			@Override
			public void run()
			{
				Toast.makeText(context, "截屏已保存" + "\n" + picPath, Toast.LENGTH_SHORT).show();
			}
		};
		new Handler(Looper.getMainLooper()).post(r);
		
		return result;
	}
	
	/** 保存 bitmap，自动生成图像名称 */
	public static boolean SaveScreen(Bitmap pic)
	{
		if (pic == null) return false;
		
		String picPath = GetDir() + NewName();
		boolean result = SavePic(pic, picPath);
		// Toast.makeText(activity, "截屏已保存" + "\n" + picPath, Toast.LENGTH_SHORT).show();
		
		return result;
	}
	
	/** Image转化为Bitmap */
	public static Bitmap ToBitmap(Image image)
	{
		int width = image.getWidth();
		int height = image.getHeight();
		
		final Image.Plane[] planes = image.getPlanes();
		final ByteBuffer buffer = planes[0].getBuffer();
		int pixelStride = planes[0].getPixelStride();
		int rowStride = planes[0].getRowStride();
		int rowPadding = rowStride - pixelStride * width;
		Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
		bitmap.copyPixelsFromBuffer(buffer);
		
		bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
		image.close();
		
		return bitmap;
	}
	
	// ----------
	
	/** 系统命令截屏，需要root权限 */
	public Bitmap captureScreenSystem(Activity activity)
	{
		// 获取屏幕大小：
		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager WM = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
		Display display = WM.getDefaultDisplay();
		display.getMetrics(metrics);
		int height = metrics.heightPixels; 	// 屏幕高
		int width = metrics.widthPixels; 	// 屏幕的宽
		
		// 获取显示方式
		int pixelformat = display.getPixelFormat();
		PixelFormat localPixelFormat1 = new PixelFormat();
		PixelFormat.getPixelFormatInfo(pixelformat, localPixelFormat1);
		int deepth = localPixelFormat1.bytesPerPixel;		// 位深
		byte[] piex = new byte[height * width * deepth];
		try
		{
			Runtime.getRuntime().exec(new String[] { "/system/bin/su", "-c", "chmod 777 /dev/graphics/fb0" });
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		try
		{
			// 获取fb0数据输入流
			InputStream stream = new FileInputStream(new File("/dev/graphics/fb0"));
			DataInputStream dStream = new DataInputStream(stream);
			dStream.readFully(piex);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		// 保存图片
		int[] colors = new int[height * width];
		for (int m = 0; m < colors.length; m++)
		{
			int r = (piex[m * 4] & 0xFF);
			int g = (piex[m * 4 + 1] & 0xFF);
			int b = (piex[m * 4 + 2] & 0xFF);
			int a = (piex[m * 4 + 3] & 0xFF);
			colors[m] = (a << 24) + (r << 16) + (g << 8) + b;
			
		}
		
		// piex生成Bitmap
		Bitmap bitmap = Bitmap.createBitmap(colors, width, height, Bitmap.Config.ARGB_8888);
		return bitmap;
	}
	
	// ----------
	
	/** 对WebView进行截图 */
	public static Bitmap captureWebView1(WebView webView)
	{
		Picture snapShot = webView.capturePicture();
		Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(), snapShot.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bmp);
		snapShot.draw(canvas);
		return bmp;
	}
	
	// 判断当前界面显示的是哪个Activity
	public static String getTopActivity(Context context)
	{
		ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		Log.d("Chunna.zheng", "pkg:" + cn.getPackageName());// 包名
		Log.d("Chunna.zheng", "cls:" + cn.getClassName());// 包名加类名
		return cn.getClassName();
	}
	
}
