| 1 | package io.github.leexeo.cage.mobile; |
| 2 | |
| 3 | import android.animation.ValueAnimator; |
| 4 | import android.app.Activity; |
| 5 | import android.content.Intent; |
| 6 | import android.content.pm.PackageManager; |
| 7 | import android.graphics.*; |
| 8 | import android.hardware.Camera; |
| 9 | import android.os.Bundle; |
| 10 | import android.view.*; |
| 11 | import android.view.animation.LinearInterpolator; |
| 12 | import android.widget.*; |
| 13 | import com.google.zxing.*; |
| 14 | import com.google.zxing.common.HybridBinarizer; |
| 15 | import com.google.zxing.qrcode.QRCodeReader; |
| 16 | |
| 17 | |
| 18 | @SuppressWarnings("deprecation") |
| 19 | public final class ScanActivity extends Activity implements SurfaceHolder.Callback, Camera.PreviewCallback { |
| 20 | private Camera camera; |
| 21 | private SurfaceView preview; |
| 22 | private TextView message; |
| 23 | private Finder finder; |
| 24 | private final QRCodeReader reader = new QRCodeReader(); |
| 25 | private boolean resumed, finished; |
| 26 | private static final int PERMISSION = 1; |
| 27 | private int dp(float n) { return Math.round(n * getResources().getDisplayMetrics().density); } |
| 28 | |
| 29 | @Override public void onCreate(Bundle state) { |
| 30 | super.onCreate(state); |
| 31 | getWindow().getDecorView().setSystemUiVisibility(0); |
| 32 | getWindow().setStatusBarColor(0xff141716); getWindow().setNavigationBarColor(0xff141716); |
| 33 | FrameLayout frame = new FrameLayout(this); frame.setBackgroundColor(0xff141716); |
| 34 | preview = new SurfaceView(this); |
| 35 | frame.addView(preview,new FrameLayout.LayoutParams(-1,-1,Gravity.CENTER)); |
| 36 | preview.getHolder().addCallback(this); |
| 37 | finder = new Finder(); frame.addView(finder,new FrameLayout.LayoutParams(-1,-1)); |
| 38 | LinearLayout bar = new LinearLayout(this);bar.setGravity(Gravity.CENTER_VERTICAL);bar.setPadding(dp(12),0,dp(20),0); |
| 39 | Button cancel = new Button(this);cancel.setText("取消");cancel.setTextColor(Color.WHITE);cancel.setTextSize(15); |
| 40 | cancel.setBackgroundColor(Color.TRANSPARENT);cancel.setOnClickListener(v -> finish());bar.addView(cancel,new LinearLayout.LayoutParams(dp(72),dp(56))); |
| 41 | TextView title = new TextView(this);title.setText("扫描电脑二维码");title.setTextColor(Color.WHITE);title.setTextSize(18);title.setTypeface(Typeface.DEFAULT,Typeface.BOLD); |
| 42 | bar.addView(title); frame.addView(bar,new FrameLayout.LayoutParams(-1,dp(64),Gravity.TOP)); |
| 43 | LinearLayout instructions = new LinearLayout(this);instructions.setOrientation(LinearLayout.VERTICAL);instructions.setGravity(Gravity.CENTER); |
| 44 | instructions.setPadding(dp(24),dp(12),dp(24),dp(20)); |
| 45 | TextView heading = new TextView(this);heading.setText("连接你的电脑");heading.setTextSize(22);heading.setTextColor(Color.WHITE);heading.setTypeface(Typeface.DEFAULT,Typeface.BOLD);instructions.addView(heading); |
| 46 | message = new TextView(this);message.setGravity(Gravity.CENTER);message.setTextSize(15);message.setPadding(0,dp(12),0,dp(10)); |
| 47 | message.setTextColor(0xffe1e5e2);message.setText("将 Cage 配对二维码放入框内\n在电脑「设置 → 远程连接」中生成"); |
| 48 | message.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);instructions.addView(message); |
| 49 | TextView privacy = new TextView(this);privacy.setText("仅识别 Cage 配对码");privacy.setTextSize(12);privacy.setTextColor(0xffa9b4ae);instructions.addView(privacy); |
| 50 | FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(-1,-2,Gravity.BOTTOM);frame.addView(instructions,copy); |
| 51 | frame.setOnApplyWindowInsetsListener((view,insets) -> { |
| 52 | view.setPadding(insets.getSystemWindowInsetLeft(),insets.getSystemWindowInsetTop(),insets.getSystemWindowInsetRight(),insets.getSystemWindowInsetBottom());return insets; |
| 53 | }); |
| 54 | setContentView(frame); |
| 55 | if(checkSelfPermission(android.Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) |
| 56 | requestPermissions(new String[]{android.Manifest.permission.CAMERA},PERMISSION); |
| 57 | } |
| 58 | @Override public void onRequestPermissionsResult(int id,String[] names,int[] results) { |
| 59 | super.onRequestPermissionsResult(id,names,results); |
| 60 | if(id!=PERMISSION)return; |
| 61 | if(results.length>0 && results[0]==PackageManager.PERMISSION_GRANTED) start(); |
| 62 | else finishWithError("相机权限未开启。可返回使用配对码,或在系统设置中允许相机访问。"); |
| 63 | } |
| 64 | private void finishWithError(String error) {setResult(RESULT_CANCELED,new Intent().putExtra("error",error));finish();} |
| 65 | private void start() { |
| 66 | if(!resumed || isFinishing() || camera!=null || !preview.getHolder().getSurface().isValid() || |
| 67 | checkSelfPermission(android.Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) return; |
| 68 | try { |
| 69 | camera=Camera.open(); |
| 70 | Camera.Parameters p=camera.getParameters(); |
| 71 | if(p.getSupportedFocusModes()!=null && p.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { |
| 72 | p.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);camera.setParameters(p); |
| 73 | } |
| 74 | Camera.CameraInfo info=new Camera.CameraInfo();Camera.getCameraInfo(0,info); |
| 75 | int rotation=(info.orientation-getWindowManager().getDefaultDisplay().getRotation()*90+360)%360; |
| 76 | camera.setDisplayOrientation(rotation); |
| 77 | |
| 78 | Camera.Size size=p.getPreviewSize(); |
| 79 | preview.post(() -> { |
| 80 | int width=(rotation%180==0)?size.width:size.height, height=(rotation%180==0)?size.height:size.width; |
| 81 | View parent=(View)preview.getParent(); |
| 82 | float scale=Math.max((float)parent.getWidth()/width,(float)parent.getHeight()/height); |
| 83 | preview.setLayoutParams(new FrameLayout.LayoutParams(Math.round(width*scale),Math.round(height*scale),Gravity.CENTER)); |
| 84 | }); |
| 85 | camera.setPreviewDisplay(preview.getHolder());camera.setPreviewCallback(this);camera.startPreview();finder.animateScan(true); |
| 86 | } catch(Exception e){stop();finishWithError("无法打开相机,请重试或返回使用配对码。");} |
| 87 | } |
| 88 | private void stop(){finder.animateScan(false);if(camera!=null){camera.setPreviewCallback(null);camera.release();camera=null;}} |
| 89 | @Override public void onPreviewFrame(byte[] data,Camera source){ |
| 90 | if(data==null || isFinishing() || finished)return; |
| 91 | Camera.Size size=source.getParameters().getPreviewSize(); |
| 92 | try{ |
| 93 | PlanarYUVLuminanceSource pixels=new PlanarYUVLuminanceSource(data,size.width,size.height,0,0,size.width,size.height,false); |
| 94 | String code=reader.decode(new BinaryBitmap(new HybridBinarizer(pixels))).getText(); |
| 95 | if(code.startsWith("CAGE1:") && code.length()<=4096){ |
| 96 | finished=true;finder.performHapticFeedback(HapticFeedbackConstants.CONFIRM); |
| 97 | setResult(RESULT_OK,new Intent().putExtra("code",code));finish(); |
| 98 | } else message.setText("请扫描 Cage 配对二维码\n在电脑「设置 → 远程连接」中生成"); |
| 99 | } catch(ReaderException ignored){} finally {reader.reset();} |
| 100 | } |
| 101 | @Override public void onResume(){super.onResume();resumed=true;start();} |
| 102 | @Override public void onPause(){resumed=false;stop();super.onPause();} |
| 103 | public void surfaceCreated(SurfaceHolder h){start();} |
| 104 | public void surfaceChanged(SurfaceHolder h,int f,int w,int height){start();} |
| 105 | public void surfaceDestroyed(SurfaceHolder h){stop();} |
| 106 | |
| 107 | private final class Finder extends View { |
| 108 | private final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG); |
| 109 | private final ValueAnimator sweep=ValueAnimator.ofFloat(0,1); |
| 110 | private float progress=.5f; |
| 111 | Finder(){ |
| 112 | super(ScanActivity.this);setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); |
| 113 | sweep.setDuration(2400);sweep.setRepeatCount(ValueAnimator.INFINITE);sweep.setRepeatMode(ValueAnimator.REVERSE);sweep.setInterpolator(new LinearInterpolator()); |
| 114 | sweep.addUpdateListener(value -> {progress=(float)value.getAnimatedValue();invalidate();}); |
| 115 | } |
| 116 | void animateScan(boolean running){ |
| 117 | if(running && ValueAnimator.areAnimatorsEnabled()){if(!sweep.isStarted())sweep.start();} |
| 118 | else {sweep.cancel();progress=.5f;invalidate();} |
| 119 | } |
| 120 | @Override protected void onDraw(Canvas canvas){ |
| 121 | float side=Math.max(dp(96),Math.min(dp(280),Math.min(getWidth()-dp(56),getHeight()-dp(250)))); |
| 122 | float left=(getWidth()-side)/2, top=dp(72)+Math.max(0,(getHeight()-dp(250)-side)/2); |
| 123 | RectF box=new RectF(left,top,left+side,top+side); |
| 124 | Path shade=new Path();shade.setFillType(Path.FillType.EVEN_ODD); |
| 125 | shade.addRect(0,0,getWidth(),getHeight(),Path.Direction.CW);shade.addRoundRect(box,dp(18),dp(18),Path.Direction.CW); |
| 126 | paint.setStyle(Paint.Style.FILL);paint.setColor(0xb8141716);canvas.drawPath(shade,paint); |
| 127 | paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(dp(1));paint.setColor(0x70ffffff);canvas.drawRoundRect(box,dp(18),dp(18),paint); |
| 128 | paint.setColor(0xffe8b79d);paint.setStrokeWidth(dp(4));paint.setStrokeCap(Paint.Cap.ROUND); |
| 129 | for(int x=0;x<2;x++)for(int y=0;y<2;y++){ |
| 130 | canvas.save();canvas.translate(x==0?box.left:box.right,y==0?box.top:box.bottom);canvas.scale(x==0?1:-1,y==0?1:-1); |
| 131 | Path corner=new Path();corner.moveTo(0,dp(30));corner.lineTo(0,dp(18));corner.quadTo(0,0,dp(18),0);corner.lineTo(dp(30),0);canvas.drawPath(corner,paint);canvas.restore(); |
| 132 | } |
| 133 | canvas.save();canvas.clipRect(box);float line=box.top+dp(24)+(side-dp(48))*progress; |
| 134 | paint.setStyle(Paint.Style.FILL);paint.setShader(new LinearGradient(0,line-dp(28),0,line,0x00e8b79d,0x35e8b79d,Shader.TileMode.CLAMP)); |
| 135 | canvas.drawRect(box.left+dp(10),line-dp(28),box.right-dp(10),line,paint);paint.setShader(null); |
| 136 | paint.setColor(0xffe8b79d);canvas.drawRoundRect(box.left+dp(12),line,box.right-dp(12),line+dp(2),dp(1),dp(1),paint);canvas.restore(); |
| 137 | } |
| 138 | } |
| 139 | } |