-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGoNativeActivity.java
More file actions
2078 lines (1889 loc) · 90.5 KB
/
Copy pathGoNativeActivity.java
File metadata and controls
2078 lines (1889 loc) · 90.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.golang.app;
import android.app.Activity;
import android.app.Dialog;
import android.app.NativeActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.content.ClipData;
import android.hardware.Camera;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemClock;
import java.util.ArrayList;
import java.util.List;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.graphics.Canvas;
import android.graphics.Paint;
public class GoNativeActivity extends NativeActivity {
private static GoNativeActivity goNativeActivity;
private static final String TAG = "croc";
private static final int FILE_OPEN_CODE = 1;
private static final int FILE_SAVE_CODE = 2;
private static final int INTENT_OPEN_CODE = 3;
private static final int DEFAULT_INPUT_TYPE = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
private static final int DEFAULT_KEYBOARD_CODE = 0;
private static final int SINGLELINE_KEYBOARD_CODE = 1;
private static final int NUMBER_KEYBOARD_CODE = 2;
private static final int PASSWORD_KEYBOARD_CODE = 3;
private native void filePickerReturned(String str);
private native void insetsChanged(int top, int bottom, int left, int right);
private native void keyboardTyped(String str);
private native void keyboardDelete();
private native void backPressed();
private native void setDarkMode(boolean dark);
private native void lifecycleEvent(String event);
private native void intentURI(String uri);
private native void intentText(String text);
// Built-in QR scanner: feed one NV21 preview frame to Go.
// Returns true to keep streaming (Go re-adds the buffer),
// false to stop (decode hit / cancel / closed / error).
private native boolean cameraFrame(byte[] data, int w, int h);
private void logIntentURI(String uri) {
Log.d(TAG, "Java: intentURI sending to Go: " + uri);
intentURI(uri);
}
private void logIntentText(String text) {
Log.d(TAG, "Java: intentText sending to Go: " + (text != null && text.length() > 50 ? text.substring(0, 50) + "..." : text));
intentText(text);
}
private EditText mTextEdit;
private boolean ignoreKey = false;
private boolean keyboardUp = false;
private ArrayList<String> pendingIntentURIs = null;
private static boolean permissionRequested = false;
public GoNativeActivity() {
super();
goNativeActivity = this;
}
String getTmpdir() {
return getCacheDir().getAbsolutePath();
}
void updateLayout() {
try {
WindowInsets insets = getWindow().getDecorView().getRootWindowInsets();
if (insets == null) {
return;
}
insetsChanged(insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetBottom(),
insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetRight());
} catch (java.lang.NoSuchMethodError e) {
Rect insets = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(insets);
View view = findViewById(android.R.id.content).getRootView();
insetsChanged(insets.top, view.getHeight() - insets.height() - insets.top,
insets.left, view.getWidth() - insets.width() - insets.left);
}
}
static void showKeyboard(int keyboardType) {
goNativeActivity.doShowKeyboard(keyboardType);
goNativeActivity.keyboardUp = true;
}
void doShowKeyboard(final int keyboardType) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int imeOptions = EditorInfo.IME_FLAG_NO_ENTER_ACTION;
int inputType = DEFAULT_INPUT_TYPE;
String keys = "";
switch (keyboardType) {
case DEFAULT_KEYBOARD_CODE:
imeOptions = EditorInfo.IME_FLAG_NO_ENTER_ACTION;
break;
case SINGLELINE_KEYBOARD_CODE:
imeOptions = EditorInfo.IME_ACTION_DONE;
break;
case NUMBER_KEYBOARD_CODE:
imeOptions = EditorInfo.IME_ACTION_DONE;
inputType |= InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL;
keys = "0123456789.,-' "; // work around android bug where some number keys are blocked
break;
case PASSWORD_KEYBOARD_CODE:
imeOptions = EditorInfo.IME_ACTION_DONE;
inputType |= InputType.TYPE_TEXT_VARIATION_PASSWORD;
default:
Log.e("Fyne", "unknown keyboard type, use default");
}
mTextEdit.setImeOptions(imeOptions|EditorInfo.IME_FLAG_NO_FULLSCREEN);
mTextEdit.setInputType(inputType);
if (keys != "") {
mTextEdit.setKeyListener(DigitsKeyListener.getInstance(keys));
}
mTextEdit.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
keyboardTyped("\n");
}
return false;
}
});
// always place one character so all keyboards can send backspace
ignoreKey = true;
mTextEdit.setText(" ");
mTextEdit.setSelection(mTextEdit.getText().length());
ignoreKey = false;
mTextEdit.setVisibility(View.VISIBLE);
mTextEdit.bringToFront();
mTextEdit.requestFocus();
InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m.showSoftInput(mTextEdit, 0);
}
});
}
static void hideKeyboard() {
goNativeActivity.doHideKeyboard();
goNativeActivity.keyboardUp = false;
}
static void startCrocsonService() {
try {
Class<?> serviceClass = Class.forName("com.github.abakum.crocson.CrocsonService");
Intent intent = new Intent(goNativeActivity, serviceClass);
if (Build.VERSION.SDK_INT >= 26) {
goNativeActivity.startForegroundService(intent);
} else {
goNativeActivity.startService(intent);
}
Log.d(TAG, "Java: Foreground service started (API " + Build.VERSION.SDK_INT + ")");
} catch (Exception e) {
Log.e(TAG, "Java: startCrocsonService failed: " + e.getMessage());
}
}
static void stopCrocsonService() {
try {
Class<?> serviceClass = Class.forName("com.github.abakum.crocson.CrocsonService");
Intent intent = new Intent(goNativeActivity, serviceClass);
goNativeActivity.stopService(intent);
Log.d(TAG, "Java: Foreground service stopped");
} catch (Exception e) {
Log.e(TAG, "Java: stopCrocsonService failed: " + e.getMessage());
}
}
private static WifiManager.MulticastLock multicastLock;
static boolean acquireMulticastLock() {
try {
if (multicastLock != null && multicastLock.isHeld()) {
return true;
}
if (goNativeActivity == null) {
return false;
}
WifiManager wm = (WifiManager) goNativeActivity.getSystemService(Context.WIFI_SERVICE);
if (wm == null) {
return false;
}
multicastLock = wm.createMulticastLock("croc");
multicastLock.setReferenceCounted(false);
multicastLock.acquire();
return true;
} catch (Throwable t) {
Log.e(TAG, "acquireMulticastLock failed", t);
return false;
}
}
static boolean releaseMulticastLock() {
try {
if (multicastLock != null && multicastLock.isHeld()) {
multicastLock.release();
}
return true;
} catch (Throwable t) {
Log.e(TAG, "releaseMulticastLock failed", t);
return false;
}
}
// ----------------------------------------------------------------------
// Built-in QR scanner camera (Camera1). Deprecated but framework-only:
// fyne's android build compiles project .java against android.jar only,
// so CameraX/AndroidX cannot be used.
// ----------------------------------------------------------------------
private static final int CAMERA_PERMISSION_CODE = 201;
private static Camera qrCamera = null;
private static volatile boolean qrCameraRunning = false;
// Состояние фонарика QR-камеры. Инвертируется тапом по оверлею превью;
// применяется на камерном потоке как FLASH_MODE_TORCH/OFF. Сбрасывается в OFF
// при остановке камеры (один переключатель на живую сессию).
private static volatile boolean qrFlashOn = false;
// Задняя камера поддерживает FLASH_MODE_TORCH (запрос один раз в startCameraWithHolder).
// Гарант для toggleCameraFlash (молчаливый no-op если false).
private static volatile boolean qrFlashTorchSupported = false;
private static int qrPreviewWidth = 0;
private static int qrPreviewHeight = 0;
private static int qrFrameCount = 0;
// Reused buffer holding the centered square of the Y plane, pre-cropped on the
// camera thread so Go only receives the square Y (drops chroma, halves JNI
// traffic). Sized to min(previewW, previewH)^2; rotation-invariant (the
// centered square of the raw frame is the same at any grip).
private static byte[] qrSquareBuf = null;
private static int qrSquareSide = 0;
// Dedicated camera thread: Camera.open()/config/startPreview/release must
// never run on the UI or GL thread (blocking -> ANR / visual freeze). All
// camera hardware ops happen on this HandlerThread's Handler.
private static HandlerThread qrCameraThread = null;
private static Handler qrCameraHandler = null;
// Native full-screen Dialog hosting a SurfaceView color preview. The camera
// is given the SurfaceView's Surface (setPreviewDisplay) — a real, consumed
// native surface (separate window, like Fyne's own GLSurfaceView) instead of
// a dummy unconsumed SurfaceTexture: that is what keeps the capture pipeline
// from stalling on old Camera1->Camera2 HALs (Android 9/10 freeze). SurfaceView
// is used (not TextureView) because a TextureView surface never materializes
// in this GL/Fyne NativeActivity (black preview on emulator + device).
private static Dialog qrDialog = null;
private static SurfaceView qrSurface = null;
// True while the camera Dialog is up & the camera is running. Guards the
// lifecycle "pause" dismiss (skips the first-run permission-request pause,
// which happens before any camera Dialog is shown).
private static volatile boolean qrDialogShown = false;
// Back-camera sensor orientation (degrees), cached at camera open so
// reapplyPreviewOrientation can recompute the display angle on rotation
// without re-querying CameraInfo.
private static int qrSensorOrientJava = 90;
// Decode-feed throttle: preview is rendered natively at full rate, so Go only
// needs a few fps for QR decode. Timestamp (uptimeMillis) of the last frame
// forwarded to Go; frames arriving sooner than 100 ms are dropped here.
private static long qrLastDecodeFeedMs = 0;
// Preview-size bounds {largeBound, smallBound} derived from the physical display
// edges minus total system insets, captured on the UI thread in showCameraDialog
// and read by startCameraWithHolder on the camera thread (so the camera thread
// never touches Display/WindowInsets). Orientation-independent -> the chosen
// preview fits in BOTH portrait and landscape (no overflow after rotation).
private static volatile int qrBoundLarge = 0;
private static volatile int qrBoundSmall = 0;
private static final Camera.PreviewCallback qrPreviewCallback = new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (!qrCameraRunning || data == null || camera == null) {
return;
}
int n = ++qrFrameCount;
if (n == 1 || n % 30 == 0) {
Log.d(TAG, "Java: onPreviewFrame #" + n + " " + qrPreviewWidth + "x" + qrPreviewHeight);
}
// Throttle decode feed to ~10 fps: preview is a native color surface
// now, Go only needs a few frames/sec for QR decode. This cuts JNI
// traffic + Go GC pressure ~3x while keeping the visible preview full
// rate. When throttled, just re-add the buffer and keep streaming.
boolean keep = true;
if (SystemClock.uptimeMillis() - qrLastDecodeFeedMs >= 100) {
qrLastDecodeFeedMs = SystemClock.uptimeMillis();
try {
if (goNativeActivity != null) {
keep = goNativeActivity.feedSquareFrame(data);
}
} catch (Throwable t) {
Log.e(TAG, "Java: cameraFrame threw: " + t.getMessage());
keep = false;
}
}
if (keep && qrCameraRunning) {
camera.addCallbackBuffer(data);
} else {
// stop on Go's request; release off the camera callback thread
// (dismissCameraDialog posts stop to the camera HandlerThread).
qrCameraRunning = false;
dismissCameraDialog();
}
}
};
static boolean hasCameraPermission() {
try {
if (goNativeActivity == null) return false;
return goNativeActivity.checkSelfPermission("android.permission.CAMERA") == PackageManager.PERMISSION_GRANTED;
} catch (Throwable t) {
Log.e(TAG, "Java: hasCameraPermission failed: " + t.getMessage());
return false;
}
}
static boolean requestCameraPermission() {
try {
if (goNativeActivity == null) return false;
goNativeActivity.requestPermissions(new String[]{"android.permission.CAMERA"}, CAMERA_PERMISSION_CODE);
return true;
} catch (Throwable t) {
Log.e(TAG, "Java: requestCameraPermission failed: " + t.getMessage());
return false;
}
}
private static int findBackCameraId() {
int numberOfCameras = Camera.getNumberOfCameras();
Camera.CameraInfo info = new Camera.CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
return i;
}
}
return numberOfCameras > 0 ? 0 : -1;
}
// Sensor orientation (degrees, CCW) of the back camera. Used by Go to rotate
// the NV21 Y plane: setDisplayOrientation only affects SurfaceView/SurfaceTexture
// output, NOT the raw preview bytes delivered to onPreviewFrame, so the buffer
// always arrives in the sensor's native (landscape) orientation.
static int getCameraSensorOrientation() {
try {
int id = findBackCameraId();
if (id < 0) return -1;
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(id, info);
return info.orientation;
} catch (Throwable t) {
Log.e(TAG, "Java: getCameraSensorOrientation failed: " + t.getMessage());
return -1;
}
}
// Current display rotation in degrees (0/90/180/270), relative to the
// device's natural orientation; -1 if unavailable. Used by Go to rotate the
// NV21 Y plane so the QR preview/decode matches the screen orientation.
static int getDeviceRotation() {
try {
if (goNativeActivity == null) return -1;
int r = goNativeActivity.getWindowManager().getDefaultDisplay().getRotation();
if (r == android.view.Surface.ROTATION_0) return 0;
if (r == android.view.Surface.ROTATION_90) return 90;
if (r == android.view.Surface.ROTATION_180) return 180;
if (r == android.view.Surface.ROTATION_270) return 270;
return -1;
} catch (Throwable t) {
Log.e(TAG, "Java: getDeviceRotation failed: " + t.getMessage());
return -1;
}
}
// Usable screen size (px) minus current system insets (status bar / nav bar).
// UI-thread only. Falls back to raw getSize() when insets are unavailable.
private static int[] getUsableScreenSize() {
int screenW = 640;
int screenH = 480;
try {
android.graphics.Point p = new android.graphics.Point();
goNativeActivity.getWindowManager().getDefaultDisplay().getSize(p);
screenW = p.x;
screenH = p.y;
WindowInsets insets = goNativeActivity.getWindow().getDecorView().getRootWindowInsets();
if (insets != null) {
screenW -= (insets.getSystemWindowInsetLeft() + insets.getSystemWindowInsetRight());
screenH -= (insets.getSystemWindowInsetTop() + insets.getSystemWindowInsetBottom());
}
} catch (Throwable ignored) {}
if (screenW < 1) screenW = 1;
if (screenH < 1) screenH = 1;
return new int[]{screenW, screenH};
}
// Orientation-independent bounds {largeBound, smallBound} for camera preview dims,
// from the physical display edges minus total system insets. UI-thread only.
// Using physical edges (not current-orientation W/H) makes a preview chosen here
// fit in BOTH portrait and landscape, so it cannot overflow after rotation:
// shortEdge - sumInsets <= usable small side in any orientation (sumInsets >= the
// bars on the short edge in any orientation). Conservative on some devices but
// never overflows.
private static int[] getPreviewBounds() {
int realW = 1080, realH = 1920;
int sum = 0;
try {
android.graphics.Point p = new android.graphics.Point();
goNativeActivity.getWindowManager().getDefaultDisplay().getRealSize(p);
realW = p.x;
realH = p.y;
WindowInsets insets = goNativeActivity.getWindow().getDecorView().getRootWindowInsets();
if (insets != null) {
sum = (insets.getSystemWindowInsetTop() + insets.getSystemWindowInsetBottom()
+ insets.getSystemWindowInsetLeft() + insets.getSystemWindowInsetRight());
}
} catch (Throwable ignored) {}
int shortEdge = Math.min(realW, realH);
int longEdge = Math.max(realW, realH);
int smallBound = Math.max(1, shortEdge - sum);
int largeBound = Math.max(1, longEdge - sum);
return new int[]{largeBound, smallBound};
}
// Largest-area preview whose sides fit largeBound x smallBound (orientation-
// independent physical-edge bounds); falls back to the smallest-area preview if
// none fits. null if no sizes.
private static Camera.Size choosePreviewSize(List<Camera.Size> sizes, int largeBound, int smallBound) {
if (sizes == null || sizes.isEmpty()) return null;
Camera.Size best = null;
Camera.Size smallest = sizes.get(0);
for (Camera.Size s : sizes) {
int area = s.width * s.height;
if (area < smallest.width * smallest.height) smallest = s;
if (Math.max(s.width, s.height) <= largeBound && Math.min(s.width, s.height) <= smallBound) {
if (best == null || area > best.width * best.height) best = s;
}
}
return best != null ? best : smallest;
}
// Dialog W/H for a camera resolution, swapping dimensions in portrait so the
// landscape-sensor preview matches the upright screen orientation.
private static int[] computeDialogSize(int screenW, int screenH, int camW, int camH) {
if (screenW > screenH) return new int[]{camW, camH};
return new int[]{camH, camW};
}
// Lazily start the dedicated camera HandlerThread. Camera.open()/config/
// startPreview/release must run off the UI and GL threads (blocking there
// -> ANR / visual freeze, which was part of the Android 9/10 hang).
private static void ensureCameraThread() {
if (qrCameraThread == null) {
qrCameraThread = new HandlerThread("qrCamera");
qrCameraThread.start();
qrCameraHandler = new Handler(qrCameraThread.getLooper());
}
}
// Кастомный оверлей для отрисовки затенения и рамки квадрата
static class QrOverlayView extends View {
private final Paint shadowPaint;
private final Paint windowPaint;
public QrOverlayView(Context context) {
super(context);
setWillNotDraw(false);
setBackgroundColor(Color.TRANSPARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
shadowPaint = new Paint();
shadowPaint.setColor(Color.parseColor("#66000000")); // 40% черный
shadowPaint.setStyle(Paint.Style.FILL);
windowPaint = new Paint();
windowPaint.setAntiAlias(true);
windowPaint.setColor(Color.parseColor("#40FFFFFF")); // 25% белый
windowPaint.setStyle(Paint.Style.STROKE);
windowPaint.setStrokeWidth(4);
}
// Этот метод вызывается Android автоматически при любом изменении размеров экрана/повороте
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
invalidate(); // Принудительно заставляем View вызвать onDraw с новыми размерами
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
// Если размеры еще не инициализированы, пропускаем шаг
if (width == 0 || height == 0) return;
if (width < height) {
// 1. ПОРТРЕТ: Окно во всю ширину. Затеняем только верх и низ.
float top = (height - width) / 2f;
float bottom = top + width;
canvas.drawRect(0, 0, width, top, shadowPaint);
canvas.drawRect(0, bottom, width, height, shadowPaint);
canvas.drawRect(0, top, width, bottom, windowPaint);
} else {
// 2. ЛАНДШАФТ: Окно во всю высоту. Затеняем только бока.
float left = (width - height) / 2f;
float right = left + height;
canvas.drawRect(0, 0, left, height, shadowPaint);
canvas.drawRect(right, 0, width, height, shadowPaint);
canvas.drawRect(left, 0, right, height, windowPaint);
}
}
}
static void showCameraDialog() {
ensureCameraThread();
if (goNativeActivity == null) return;
goNativeActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (qrDialog != null) {
qrDialogShown = true;
Log.d(TAG, "Java: showCameraDialog already shown, skipping");
return;
}
final Activity act = goNativeActivity;
try {
int[] usable = getUsableScreenSize();
int screenW = usable[0];
int screenH = usable[1];
int[] bounds = getPreviewBounds();
int largeBound = bounds[0];
int smallBound = bounds[1];
qrBoundLarge = largeBound;
qrBoundSmall = smallBound;
Log.d(TAG, "Java: showCameraDialog usable size=" + screenW + "x" + screenH + " bounds large=" + largeBound + " small=" + smallBound);
int cameraW = 640, cameraH = 480;
Log.d(TAG, "Java: camera preview resolution=" + cameraW + "x" + cameraH);
int[] dialog = computeDialogSize(screenW, screenH, cameraW, cameraH);
int dialogW = dialog[0];
int dialogH = dialog[1];
Log.d(TAG, "Java: showCameraDialog calculated dialog size=" + dialogW + "x" + dialogH);
final int finalW = dialogW;
final int finalH = dialogH;
final Dialog d = new Dialog(act);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (d.getWindow() != null) {
d.getWindow().setLayout(finalW, finalH);
d.getWindow().setBackgroundDrawable(
new android.graphics.drawable.ColorDrawable(Color.BLACK));
// Центрируем диалог
d.getWindow().setGravity(Gravity.CENTER);
}
SurfaceView surface = new SurfaceView(act);
surface.setLayoutParams(new ViewGroup.LayoutParams(finalW, finalH));
// surface.setZOrderMediaOverlay(true);
final SurfaceView sv = surface;
sv.getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder h) {
Log.d(TAG, "Java: surfaceCreated, setting fixed size " + finalW + "x" + finalH);
h.setFixedSize(finalW, finalH);
startCameraOnThread(h);
}
public void surfaceChanged(SurfaceHolder h, int f, int w, int hh) {
Log.d(TAG, "Java: surfaceChanged format=" + f + " size=" + w + "x" + hh);
}
public void surfaceDestroyed(SurfaceHolder h) {
Log.d(TAG, "Java: surfaceDestroyed");
dismissCameraDialog();
}
});
FrameLayout root = new FrameLayout(act);
root.setLayoutParams(new ViewGroup.LayoutParams(finalW, finalH));
root.setBackgroundColor(Color.TRANSPARENT);
// 1. Добавляем превью камеры вниз
root.addView(sv);
// 2. Добавляем полупрозрачный оверлей с прозрачным окном поверх камеры
QrOverlayView overlayView = new QrOverlayView(act);
// overlayView.setLayoutParams(new ViewGroup.LayoutParams(finalW, finalH));
overlayView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
root.addView(overlayView);
overlayView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { toggleCameraFlash(); }
});
qrSurface = sv;
d.setContentView(root);
d.setCancelable(true);
d.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface di) {
Log.d(TAG, "Java: dialog cancelled");
cancelCameraDialog();
}
});
qrDialog = d;
qrDialogShown = true;
d.show();
Log.d(TAG, "Java: showCameraDialog shown successfully " + finalW + "x" + finalH);
} catch (Throwable t) {
Log.e(TAG, "Java: showCameraDialog failed: " + t.getMessage(), t);
failCameraOpen();
}
}
});
}
// Cancel (Cancel button / hardware Back): dismiss + release, then tell Go.
private static void cancelCameraDialog() {
dismissCameraDialog();
if (goNativeActivity != null) goNativeActivity.lifecycleEvent("qrCancel");
}
private static void startCameraOnThread(final SurfaceHolder h) {
ensureCameraThread();
qrCameraHandler.post(new Runnable() {
@Override
public void run() { startCameraWithHolder(h); }
});
}
// Open + configure the back camera against the given (real) SurfaceHolder
// and start streaming. Runs on the camera HandlerThread.
private static boolean startCameraWithHolder(SurfaceHolder h) {
if (qrCamera != null) return true; // already running
int width = 0, height = 0;
int rotate = 90; // display orientation (refined below; hoisted for sizeDialogToCamera)
try {
int id = findBackCameraId();
if (id < 0) {
Log.e(TAG, "Java: startCamera: no camera available");
failCameraOpen();
return false;
}
Camera c = Camera.open(id);
try {
Camera.Parameters params = c.getParameters();
try {
params.setPreviewFormat(ImageFormat.NV21);
} catch (Throwable ignored) {}
try {
List<Camera.Size> sizes = params.getSupportedPreviewSizes();
int lg = qrBoundLarge > 0 ? qrBoundLarge : 640;
int sm = qrBoundSmall > 0 ? qrBoundSmall : 480;
Camera.Size chosen = choosePreviewSize(sizes, lg, sm);
if (chosen != null) {
params.setPreviewSize(chosen.width, chosen.height);
width = chosen.width;
height = chosen.height;
}
} catch (Throwable ignored) {}
try {
List<String> modes = params.getSupportedFocusModes();
if (modes != null && modes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
} catch (Throwable ignored) {}
try {
List<String> flashModes = params.getSupportedFlashModes();
qrFlashTorchSupported = flashModes != null
&& flashModes.contains(Camera.Parameters.FLASH_MODE_TORCH);
} catch (Throwable ignored) { qrFlashTorchSupported = false; }
// Preview FPS range — pick the range with the highest max, and among
// those the smallest min (most flexible), so auto-exposure can adapt.
// Forcing the fixed 30000-30000 (the old tie-break) is fragile on old
// HALs and is what produced the ~15 fps / freeze on Android 9/10.
try {
List<int[]> ranges = params.getSupportedPreviewFpsRange();
int[] picked = null;
if (ranges != null) {
for (int[] r : ranges) {
if (r == null || r.length < 2) continue;
if (picked == null || r[1] > picked[1]
|| (r[1] == picked[1] && r[0] < picked[0])) {
picked = r;
}
}
}
if (picked != null) {
params.setPreviewFpsRange(picked[0], picked[1]);
Log.d(TAG, "Java: previewFpsRange " + picked[0] + "-" + picked[1]);
}
} catch (Throwable ignored) {}
try {
c.setParameters(params);
} catch (Throwable ignored) {}
} catch (Throwable t) {
Log.e(TAG, "Java: startCamera configure failed: " + t.getMessage());
}
if (width == 0 || height == 0) {
Camera.Parameters p = c.getParameters();
if (p != null) {
Camera.Size ps = p.getPreviewSize();
if (ps != null) {
width = ps.width;
height = ps.height;
}
}
}
try {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(id, info);
qrSensorOrientJava = info.orientation;
// Back-camera formula (Android docs): rotate by
// (sensorOrientation - displayRotation). getDeviceRotation() is the
// same source the pre-change Go qrRot used (=> 1x 90 deg CW in
// portrait), so preview and decode agree. Portrait => 90 deg CW.
int degrees = getDeviceRotation();
if (degrees < 0) degrees = 0;
rotate = (info.orientation - degrees + 360) % 360;
c.setDisplayOrientation(rotate);
} catch (Throwable ignored) {}
// Real, consumed native surface: the SurfaceView's Surface (a separate
// window) consumes the preview, so the capture pipeline never stalls
// (unlike the old dummy unconsumed SurfaceTexture(0)).
try {
c.setPreviewDisplay(h);
Log.d(TAG, "Java: startCamera setPreviewDisplay ok");
} catch (Throwable t) {
Log.e(TAG, "Java: startCamera setPreviewDisplay failed: " + t.getMessage());
}
qrPreviewWidth = width;
qrPreviewHeight = height;
updateDialogSizeToCameraResolution(width, height);
int side = Math.max(1, Math.min(width, height));
qrSquareSide = side;
qrSquareBuf = new byte[side * side];
qrFrameCount = 0;
qrLastDecodeFeedMs = 0;
c.setPreviewCallbackWithBuffer(qrPreviewCallback);
int bufSize = Math.max(1, width) * Math.max(1, height)
* ImageFormat.getBitsPerPixel(ImageFormat.NV21) / 8;
// Prime several buffers so the camera always has one ready to fill
// (one buffer can starve the capture pipeline). On `keep` the returned
// buffer is re-added, keeping the pool topped up.
for (int i = 0; i < 3; i++) c.addCallbackBuffer(new byte[bufSize]);
qrCamera = c;
qrCameraRunning = true;
c.startPreview();
// Уважать последний тап пользователя (напр. тап в окне до открытия камеры).
applyCameraFlash(c);
Log.d(TAG, "Java: startCamera " + width + "x" + height);
return true;
} catch (Throwable t) {
Log.e(TAG, "Java: startCamera failed: " + t.getMessage());
qrPreviewWidth = 0;
qrPreviewHeight = 0;
failCameraOpen();
return false;
}
}
private static void failCameraOpen() {
qrCameraRunning = false;
qrDialogShown = false;
dismissCameraDialog();
if (goNativeActivity != null) goNativeActivity.lifecycleEvent("cameraOpenFailed");
}
// Переключить фонарик. Вызывается из click-listener'а оверлея (UI-поток).
// Инвертирует желаемое состояние и применяет на камерном потоке (все camera-операции
// только на qrCameraHandler). Молчаливый no-op, если задняя камера без FLASH_MODE_TORCH.
private static void toggleCameraFlash() {
if (!qrFlashTorchSupported) return;
qrFlashOn = !qrFlashOn;
final boolean on = qrFlashOn;
ensureCameraThread();
qrCameraHandler.post(new Runnable() {
@Override
public void run() {
Camera c = qrCamera;
if (c != null) applyCameraFlash(c, on);
}
});
}
// Применить текущее qrFlashOn к открытой камере. Камерный поток.
private static void applyCameraFlash(Camera c) { applyCameraFlash(c, qrFlashOn); }
private static void applyCameraFlash(Camera c, boolean on) {
try {
Camera.Parameters params = c.getParameters();
params.setFlashMode(on ? Camera.Parameters.FLASH_MODE_TORCH
: Camera.Parameters.FLASH_MODE_OFF);
c.setParameters(params);
} catch (Throwable t) {
Log.e(TAG, "Java: setFlashMode failed: " + t.getMessage());
}
}
// Recompute + apply the preview display orientation for the current device
// rotation. Called from onConfigurationChanged while the camera Dialog is up,
// since configChanges="orientation|..." absorbs rotation without recreating
// the activity (so a single setDisplayOrientation at open would go stale).
// Mirrors the pre-change Go behavior of re-reading getDeviceRotation per
// frame. setDisplayOrientation only rotates the surface display, never the
// onPreviewFrame bytes (Go's qrRot keeps decode upright independently).
private static void reapplyPreviewOrientation() {
final Camera c = qrCamera;
if (c == null) return;
int degrees = getDeviceRotation();
if (degrees < 0) degrees = 0;
final int rotate = (qrSensorOrientJava - degrees + 360) % 360;
qrCameraHandler.post(new Runnable() {
@Override
public void run() { try { c.setDisplayOrientation(rotate); } catch (Throwable ignored) {} }
});
}
private static void updateDialogSizeToCameraResolution(final int cameraW, final int cameraH) {
if (goNativeActivity == null) return;
goNativeActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (qrDialog == null || !qrDialog.isShowing()) return;
try {
int[] usable = getUsableScreenSize();
int screenW = usable[0];
int screenH = usable[1];
int[] dialog = computeDialogSize(screenW, screenH, cameraW, cameraH);
int dialogW = dialog[0];
int dialogH = dialog[1];
Window window = qrDialog.getWindow();
if (window != null) {
window.setLayout(dialogW, dialogH);
Log.d(TAG, "Java: dialog resized to camera resolution " + dialogW + "x" + dialogH);
}
if (qrSurface != null) {
ViewGroup.LayoutParams params = qrSurface.getLayoutParams();
if (params.width != dialogW || params.height != dialogH) {
params.width = dialogW;
params.height = dialogH;
qrSurface.setLayoutParams(params);
SurfaceHolder holder = qrSurface.getHolder();
if (holder != null) {
holder.setFixedSize(dialogW, dialogH);
Log.d(TAG, "Java: surface holder resized to " + dialogW + "x" + dialogH);
}
}
}
} catch (Throwable t) {
Log.e(TAG, "Java: updateDialogSizeToCameraResolution failed: " + t.getMessage());
}
}
});
}
// Idempotent: dismiss the native camera Dialog and release the camera. Safe
// to call when nothing is open. Called from Go (decode hit / pause), from
// cancel, and from onPause.
static void dismissCameraDialog() {
qrDialogShown = false;
ensureCameraThread();
qrCameraHandler.post(new Runnable() {
@Override
public void run() { stopCamera(); }
});
if (goNativeActivity != null) {
goNativeActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Dialog d = qrDialog;
qrDialog = null;
qrSurface = null;
if (d != null) {
try { if (d.isShowing()) d.dismiss(); } catch (Throwable ignored) {}
}
Log.d(TAG, "Java: dismissCameraDialog done");
}
});
} else {
qrDialog = null;
qrSurface = null;
}
}
static void stopCamera() {
qrCameraRunning = false;
Camera c = qrCamera;
qrCamera = null;
qrSquareBuf = null;
qrSquareSide = 0;
qrBoundLarge = 0;
qrBoundSmall = 0;
qrFlashOn = false;
qrFlashTorchSupported = false;
if (c == null) return;
try { c.setPreviewCallbackWithBuffer(null); } catch (Throwable ignored) {}
try { c.stopPreview(); } catch (Throwable ignored) {}
try { c.release(); } catch (Throwable ignored) {}
Log.d(TAG, "Java: stopCamera");
}
// Extract the centered square of the Y plane (the first w*h bytes of the NV21
// buffer) into the reused qrSquareBuf and hand it to Go as a side x side
// square. Falls back to passing the raw NV21 frame when the buffer is
// unavailable or the frame is too small (Go's cropCenterSquare then squares
// it). Returns true to keep streaming, false to stop.
private boolean feedSquareFrame(byte[] data) {
int pw = qrPreviewWidth;
int ph = qrPreviewHeight;
int side = qrSquareSide;
byte[] buf = qrSquareBuf;
if (buf != null && side > 0 && pw > 0 && ph > 0 && data.length >= pw * ph
&& pw >= side && ph >= side) {
int xoff = (pw - side) / 2;
int yoff = (ph - side) / 2;
for (int r = 0; r < side; r++) {
System.arraycopy(data, (yoff + r) * pw + xoff, buf, r * side, side);
}
return cameraFrame(buf, side, side);
}
return cameraFrame(data, pw, ph);