-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewDebug.java
More file actions
1666 lines (1468 loc) · 59.9 KB
/
Copy pathViewDebug.java
File metadata and controls
1666 lines (1468 loc) · 59.9 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
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.view;
import android.annotation.NonNull;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Debug;
import android.os.Handler;
import android.os.RemoteException;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* Various debugging/tracing tools related to {@link View} and the view hierarchy.
*/
public class ViewDebug {
/**
* @deprecated This flag is now unused
*/
@Deprecated
public static final boolean TRACE_HIERARCHY = false;
/**
* @deprecated This flag is now unused
*/
@Deprecated
public static final boolean TRACE_RECYCLER = false;
/**
* Enables detailed logging of drag/drop operations.
* @hide
*/
public static final boolean DEBUG_DRAG = false;
/**
* This annotation can be used to mark fields and methods to be dumped by
* the view server. Only non-void methods with no arguments can be annotated
* by this annotation.
*/
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExportedProperty {
/**
* When resolveId is true, and if the annotated field/method return value
* is an int, the value is converted to an Android's resource name.
*
* @return true if the property's value must be transformed into an Android
* resource name, false otherwise
*/
boolean resolveId() default false;
/**
* A mapping can be defined to map int values to specific strings. For
* instance, View.getVisibility() returns 0, 4 or 8. However, these values
* actually mean VISIBLE, INVISIBLE and GONE. A mapping can be used to see
* these human readable values:
*
* <pre>
* @ViewDebug.ExportedProperty(mapping = {
* @ViewDebug.IntToString(from = 0, to = "VISIBLE"),
* @ViewDebug.IntToString(from = 4, to = "INVISIBLE"),
* @ViewDebug.IntToString(from = 8, to = "GONE")
* })
* public int getVisibility() { ...
* <pre>
*
* @return An array of int to String mappings
*
* @see android.view.ViewDebug.IntToString
*/
IntToString[] mapping() default { };
/**
* A mapping can be defined to map array indices to specific strings.
* A mapping can be used to see human readable values for the indices
* of an array:
*
* <pre>
* @ViewDebug.ExportedProperty(indexMapping = {
* @ViewDebug.IntToString(from = 0, to = "INVALID"),
* @ViewDebug.IntToString(from = 1, to = "FIRST"),
* @ViewDebug.IntToString(from = 2, to = "SECOND")
* })
* private int[] mElements;
* <pre>
*
* @return An array of int to String mappings
*
* @see android.view.ViewDebug.IntToString
* @see #mapping()
*/
IntToString[] indexMapping() default { };
/**
* A flags mapping can be defined to map flags encoded in an integer to
* specific strings. A mapping can be used to see human readable values
* for the flags of an integer:
*
* <pre>
* @ViewDebug.ExportedProperty(flagMapping = {
* @ViewDebug.FlagToString(mask = ENABLED_MASK, equals = ENABLED, name = "ENABLED"),
* @ViewDebug.FlagToString(mask = ENABLED_MASK, equals = DISABLED, name = "DISABLED"),
* })
* private int mFlags;
* <pre>
*
* A specified String is output when the following is true:
*
* @return An array of int to String mappings
*/
FlagToString[] flagMapping() default { };
/**
* When deep export is turned on, this property is not dumped. Instead, the
* properties contained in this property are dumped. Each child property
* is prefixed with the name of this property.
*
* @return true if the properties of this property should be dumped
*
* @see #prefix()
*/
boolean deepExport() default false;
/**
* The prefix to use on child properties when deep export is enabled
*
* @return a prefix as a String
*
* @see #deepExport()
*/
String prefix() default "";
/**
* Specifies the category the property falls into, such as measurement,
* layout, drawing, etc.
*
* @return the category as String
*/
String category() default "";
/**
* Indicates whether or not to format an {@code int} or {@code byte} value as a hex string.
*
* @return true if the supported values should be formatted as a hex string.
*/
boolean formatToHexString() default false;
/**
* Indicates whether or not the key to value mappings are held in adjacent indices.
*
* Note: Applies only to fields and methods that return String[].
*
* @return true if the key to value mappings are held in adjacent indices.
*/
boolean hasAdjacentMapping() default false;
}
/**
* Defines a mapping from an int value to a String. Such a mapping can be used
* in an @ExportedProperty to provide more meaningful values to the end user.
*
* @see android.view.ViewDebug.ExportedProperty
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface IntToString {
/**
* The original int value to map to a String.
*
* @return An arbitrary int value.
*/
int from();
/**
* The String to use in place of the original int value.
*
* @return An arbitrary non-null String.
*/
String to();
}
/**
* Defines a mapping from a flag to a String. Such a mapping can be used
* in an @ExportedProperty to provide more meaningful values to the end user.
*
* @see android.view.ViewDebug.ExportedProperty
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface FlagToString {
/**
* The mask to apply to the original value.
*
* @return An arbitrary int value.
*/
int mask();
/**
* The value to compare to the result of:
* <code>original value & {@link #mask()}</code>.
*
* @return An arbitrary value.
*/
int equals();
/**
* The String to use in place of the original int value.
*
* @return An arbitrary non-null String.
*/
String name();
/**
* Indicates whether to output the flag when the test is true,
* or false. Defaults to true.
*/
boolean outputIf() default true;
}
/**
* This annotation can be used to mark fields and methods to be dumped when
* the view is captured. Methods with this annotation must have no arguments
* and must return a valid type of data.
*/
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CapturedViewProperty {
/**
* When retrieveReturn is true, we need to retrieve second level methods
* e.g., we need myView.getFirstLevelMethod().getSecondLevelMethod()
* we will set retrieveReturn = true on the annotation of
* myView.getFirstLevelMethod()
* @return true if we need the second level methods
*/
boolean retrieveReturn() default false;
}
/**
* Allows a View to inject custom children into HierarchyViewer. For example,
* WebView uses this to add its internal layer tree as a child to itself
* @hide
*/
public interface HierarchyHandler {
/**
* Dumps custom children to hierarchy viewer.
* See ViewDebug.dumpViewWithProperties(Context, View, BufferedWriter, int)
* for the format
*
* An empty implementation should simply do nothing
*
* @param out The output writer
* @param level The indentation level
*/
public void dumpViewHierarchyWithProperties(BufferedWriter out, int level);
/**
* Returns a View to enable grabbing screenshots from custom children
* returned in dumpViewHierarchyWithProperties.
*
* @param className The className of the view to find
* @param hashCode The hashCode of the view to find
* @return the View to capture from, or null if not found
*/
public View findHierarchyView(String className, int hashCode);
}
private static HashMap<Class<?>, Method[]> mCapturedViewMethodsForClasses = null;
private static HashMap<Class<?>, Field[]> mCapturedViewFieldsForClasses = null;
// Maximum delay in ms after which we stop trying to capture a View's drawing
private static final int CAPTURE_TIMEOUT = 4000;
private static final String REMOTE_COMMAND_CAPTURE = "CAPTURE";
private static final String REMOTE_COMMAND_DUMP = "DUMP";
private static final String REMOTE_COMMAND_DUMP_THEME = "DUMP_THEME";
private static final String REMOTE_COMMAND_INVALIDATE = "INVALIDATE";
private static final String REMOTE_COMMAND_REQUEST_LAYOUT = "REQUEST_LAYOUT";
private static final String REMOTE_PROFILE = "PROFILE";
private static final String REMOTE_COMMAND_CAPTURE_LAYERS = "CAPTURE_LAYERS";
private static final String REMOTE_COMMAND_OUTPUT_DISPLAYLIST = "OUTPUT_DISPLAYLIST";
private static HashMap<Class<?>, Field[]> sFieldsForClasses;
private static HashMap<Class<?>, Method[]> sMethodsForClasses;
private static HashMap<AccessibleObject, ExportedProperty> sAnnotations;
/**
* @deprecated This enum is now unused
*/
@Deprecated
public enum HierarchyTraceType {
INVALIDATE,
INVALIDATE_CHILD,
INVALIDATE_CHILD_IN_PARENT,
REQUEST_LAYOUT,
ON_LAYOUT,
ON_MEASURE,
DRAW,
BUILD_CACHE
}
/**
* @deprecated This enum is now unused
*/
@Deprecated
public enum RecyclerTraceType {
NEW_VIEW,
BIND_VIEW,
RECYCLE_FROM_ACTIVE_HEAP,
RECYCLE_FROM_SCRAP_HEAP,
MOVE_TO_SCRAP_HEAP,
MOVE_FROM_ACTIVE_TO_SCRAP_HEAP
}
/**
* Returns the number of instanciated Views.
*
* @return The number of Views instanciated in the current process.
*
* @hide
*/
public static long getViewInstanceCount() {
return Debug.countInstancesOfClass(View.class);
}
/**
* Returns the number of instanciated ViewAncestors.
*
* @return The number of ViewAncestors instanciated in the current process.
*
* @hide
*/
public static long getViewRootImplCount() {
return Debug.countInstancesOfClass(ViewRootImpl.class);
}
/**
* @deprecated This method is now unused and invoking it is a no-op
*/
@Deprecated
@SuppressWarnings({ "UnusedParameters", "deprecation" })
public static void trace(View view, RecyclerTraceType type, int... parameters) {
}
/**
* @deprecated This method is now unused and invoking it is a no-op
*/
@Deprecated
@SuppressWarnings("UnusedParameters")
public static void startRecyclerTracing(String prefix, View view) {
}
/**
* @deprecated This method is now unused and invoking it is a no-op
*/
@Deprecated
@SuppressWarnings("UnusedParameters")
public static void stopRecyclerTracing() {
}
/**
* @deprecated This method is now unused and invoking it is a no-op
*/
@Deprecated
@SuppressWarnings({ "UnusedParameters", "deprecation" })
public static void trace(View view, HierarchyTraceType type) {
}
/**
* @deprecated This method is now unused and invoking it is a no-op
*/
@Deprecated
@SuppressWarnings("UnusedParameters")
public static void startHierarchyTracing(String prefix, View view) {
}
/**
* @deprecated This method is now unused and invoking it is a no-op
*/
@Deprecated
public static void stopHierarchyTracing() {
}
static void dispatchCommand(View view, String command, String parameters,
OutputStream clientStream) throws IOException {
// Paranoid but safe...
view = view.getRootView();
if (REMOTE_COMMAND_DUMP.equalsIgnoreCase(command)) {
dump(view, false, true, clientStream);
} else if (REMOTE_COMMAND_DUMP_THEME.equalsIgnoreCase(command)) {
dumpTheme(view, clientStream);
} else if (REMOTE_COMMAND_CAPTURE_LAYERS.equalsIgnoreCase(command)) {
captureLayers(view, new DataOutputStream(clientStream));
} else {
final String[] params = parameters.split(" ");
if (REMOTE_COMMAND_CAPTURE.equalsIgnoreCase(command)) {
capture(view, clientStream, params[0]);
} else if (REMOTE_COMMAND_OUTPUT_DISPLAYLIST.equalsIgnoreCase(command)) {
outputDisplayList(view, params[0]);
} else if (REMOTE_COMMAND_INVALIDATE.equalsIgnoreCase(command)) {
invalidate(view, params[0]);
} else if (REMOTE_COMMAND_REQUEST_LAYOUT.equalsIgnoreCase(command)) {
requestLayout(view, params[0]);
} else if (REMOTE_PROFILE.equalsIgnoreCase(command)) {
profile(view, clientStream, params[0]);
}
}
}
/** @hide */
public static View findView(View root, String parameter) {
// Look by type/hashcode
if (parameter.indexOf('@') != -1) {
final String[] ids = parameter.split("@");
final String className = ids[0];
final int hashCode = (int) Long.parseLong(ids[1], 16);
View view = root.getRootView();
if (view instanceof ViewGroup) {
return findView((ViewGroup) view, className, hashCode);
}
} else {
// Look by id
final int id = root.getResources().getIdentifier(parameter, null, null);
return root.getRootView().findViewById(id);
}
return null;
}
private static void invalidate(View root, String parameter) {
final View view = findView(root, parameter);
if (view != null) {
view.postInvalidate();
}
}
private static void requestLayout(View root, String parameter) {
final View view = findView(root, parameter);
if (view != null) {
root.post(new Runnable() {
public void run() {
view.requestLayout();
}
});
}
}
private static void profile(View root, OutputStream clientStream, String parameter)
throws IOException {
final View view = findView(root, parameter);
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(clientStream), 32 * 1024);
if (view != null) {
profileViewAndChildren(view, out);
} else {
out.write("-1 -1 -1");
out.newLine();
}
out.write("DONE.");
out.newLine();
} catch (Exception e) {
android.util.Log.w("View", "Problem profiling the view:", e);
} finally {
if (out != null) {
out.close();
}
}
}
/** @hide */
public static void profileViewAndChildren(final View view, BufferedWriter out)
throws IOException {
profileViewAndChildren(view, out, true);
}
private static void profileViewAndChildren(final View view, BufferedWriter out, boolean root)
throws IOException {
long durationMeasure =
(root || (view.mPrivateFlags & View.PFLAG_MEASURED_DIMENSION_SET) != 0)
? profileViewOperation(view, new ViewOperation<Void>() {
public Void[] pre() {
forceLayout(view);
return null;
}
private void forceLayout(View view) {
view.forceLayout();
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
final int count = group.getChildCount();
for (int i = 0; i < count; i++) {
forceLayout(group.getChildAt(i));
}
}
}
public void run(Void... data) {
view.measure(view.mOldWidthMeasureSpec, view.mOldHeightMeasureSpec);
}
public void post(Void... data) {
}
})
: 0;
long durationLayout =
(root || (view.mPrivateFlags & View.PFLAG_LAYOUT_REQUIRED) != 0)
? profileViewOperation(view, new ViewOperation<Void>() {
public Void[] pre() {
return null;
}
public void run(Void... data) {
view.layout(view.mLeft, view.mTop, view.mRight, view.mBottom);
}
public void post(Void... data) {
}
}) : 0;
long durationDraw =
(root || !view.willNotDraw() || (view.mPrivateFlags & View.PFLAG_DRAWN) != 0)
? profileViewOperation(view, new ViewOperation<Object>() {
public Object[] pre() {
final DisplayMetrics metrics =
(view != null && view.getResources() != null) ?
view.getResources().getDisplayMetrics() : null;
final Bitmap bitmap = metrics != null ?
Bitmap.createBitmap(metrics, metrics.widthPixels,
metrics.heightPixels, Bitmap.Config.RGB_565) : null;
final Canvas canvas = bitmap != null ? new Canvas(bitmap) : null;
return new Object[] {
bitmap, canvas
};
}
public void run(Object... data) {
if (data[1] != null) {
view.draw((Canvas) data[1]);
}
}
public void post(Object... data) {
if (data[1] != null) {
((Canvas) data[1]).setBitmap(null);
}
if (data[0] != null) {
((Bitmap) data[0]).recycle();
}
}
}) : 0;
out.write(String.valueOf(durationMeasure));
out.write(' ');
out.write(String.valueOf(durationLayout));
out.write(' ');
out.write(String.valueOf(durationDraw));
out.newLine();
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
final int count = group.getChildCount();
for (int i = 0; i < count; i++) {
profileViewAndChildren(group.getChildAt(i), out, false);
}
}
}
interface ViewOperation<T> {
T[] pre();
void run(T... data);
void post(T... data);
}
private static <T> long profileViewOperation(View view, final ViewOperation<T> operation) {
final CountDownLatch latch = new CountDownLatch(1);
final long[] duration = new long[1];
view.post(new Runnable() {
public void run() {
try {
T[] data = operation.pre();
long start = Debug.threadCpuTimeNanos();
//noinspection unchecked
operation.run(data);
duration[0] = Debug.threadCpuTimeNanos() - start;
//noinspection unchecked
operation.post(data);
} finally {
latch.countDown();
}
}
});
try {
if (!latch.await(CAPTURE_TIMEOUT, TimeUnit.MILLISECONDS)) {
Log.w("View", "Could not complete the profiling of the view " + view);
return -1;
}
} catch (InterruptedException e) {
Log.w("View", "Could not complete the profiling of the view " + view);
Thread.currentThread().interrupt();
return -1;
}
return duration[0];
}
/** @hide */
public static void captureLayers(View root, final DataOutputStream clientStream)
throws IOException {
try {
Rect outRect = new Rect();
try {
root.mAttachInfo.mSession.getDisplayFrame(root.mAttachInfo.mWindow, outRect);
} catch (RemoteException e) {
// Ignore
}
clientStream.writeInt(outRect.width());
clientStream.writeInt(outRect.height());
captureViewLayer(root, clientStream, true);
clientStream.write(2);
} finally {
clientStream.close();
}
}
private static void captureViewLayer(View view, DataOutputStream clientStream, boolean visible)
throws IOException {
final boolean localVisible = view.getVisibility() == View.VISIBLE && visible;
if ((view.mPrivateFlags & View.PFLAG_SKIP_DRAW) != View.PFLAG_SKIP_DRAW) {
final int id = view.getId();
String name = view.getClass().getSimpleName();
if (id != View.NO_ID) {
name = resolveId(view.getContext(), id).toString();
}
clientStream.write(1);
clientStream.writeUTF(name);
clientStream.writeByte(localVisible ? 1 : 0);
int[] position = new int[2];
// XXX: Should happen on the UI thread
view.getLocationInWindow(position);
clientStream.writeInt(position[0]);
clientStream.writeInt(position[1]);
clientStream.flush();
Bitmap b = performViewCapture(view, true);
if (b != null) {
ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(b.getWidth() *
b.getHeight() * 2);
b.compress(Bitmap.CompressFormat.PNG, 100, arrayOut);
clientStream.writeInt(arrayOut.size());
arrayOut.writeTo(clientStream);
}
clientStream.flush();
}
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
int count = group.getChildCount();
for (int i = 0; i < count; i++) {
captureViewLayer(group.getChildAt(i), clientStream, localVisible);
}
}
if (view.mOverlay != null) {
ViewGroup overlayContainer = view.getOverlay().mOverlayViewGroup;
captureViewLayer(overlayContainer, clientStream, localVisible);
}
}
private static void outputDisplayList(View root, String parameter) throws IOException {
final View view = findView(root, parameter);
view.getViewRootImpl().outputDisplayList(view);
}
/** @hide */
public static void outputDisplayList(View root, View target) {
root.getViewRootImpl().outputDisplayList(target);
}
private static void capture(View root, final OutputStream clientStream, String parameter)
throws IOException {
final View captureView = findView(root, parameter);
capture(root, clientStream, captureView);
}
/** @hide */
public static void capture(View root, final OutputStream clientStream, View captureView)
throws IOException {
Bitmap b = performViewCapture(captureView, false);
if (b == null) {
Log.w("View", "Failed to create capture bitmap!");
// Send an empty one so that it doesn't get stuck waiting for
// something.
b = Bitmap.createBitmap(root.getResources().getDisplayMetrics(),
1, 1, Bitmap.Config.ARGB_8888);
}
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(clientStream, 32 * 1024);
b.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
} finally {
if (out != null) {
out.close();
}
b.recycle();
}
}
private static Bitmap performViewCapture(final View captureView, final boolean skipChildren) {
if (captureView != null) {
final CountDownLatch latch = new CountDownLatch(1);
final Bitmap[] cache = new Bitmap[1];
captureView.post(new Runnable() {
public void run() {
try {
cache[0] = captureView.createSnapshot(
Bitmap.Config.ARGB_8888, 0, skipChildren);
} catch (OutOfMemoryError e) {
Log.w("View", "Out of memory for bitmap");
} finally {
latch.countDown();
}
}
});
try {
latch.await(CAPTURE_TIMEOUT, TimeUnit.MILLISECONDS);
return cache[0];
} catch (InterruptedException e) {
Log.w("View", "Could not complete the capture of the view " + captureView);
Thread.currentThread().interrupt();
}
}
return null;
}
/**
* Dumps the view hierarchy starting from the given view.
* @deprecated See {@link #dumpv2(View, ByteArrayOutputStream)} below.
* @hide
*/
public static void dump(View root, boolean skipChildren, boolean includeProperties,
OutputStream clientStream) throws IOException {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(clientStream, "utf-8"), 32 * 1024);
View view = root.getRootView();
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
dumpViewHierarchy(group.getContext(), group, out, 0,
skipChildren, includeProperties);
}
out.write("DONE.");
out.newLine();
} catch (Exception e) {
android.util.Log.w("View", "Problem dumping the view:", e);
} finally {
if (out != null) {
out.close();
}
}
}
/**
* Dumps the view hierarchy starting from the given view.
* Rather than using reflection, it uses View's encode method to obtain all the properties.
* @hide
*/
public static void dumpv2(@NonNull final View view, @NonNull ByteArrayOutputStream out)
throws InterruptedException {
final ViewHierarchyEncoder encoder = new ViewHierarchyEncoder(out);
final CountDownLatch latch = new CountDownLatch(1);
view.post(new Runnable() {
@Override
public void run() {
view.encode(encoder);
latch.countDown();
}
});
latch.await(2, TimeUnit.SECONDS);
encoder.endStream();
}
/**
* Dumps the theme attributes from the given View.
* @hide
*/
public static void dumpTheme(View view, OutputStream clientStream) throws IOException {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(clientStream, "utf-8"), 32 * 1024);
String[] attributes = getStyleAttributesDump(view.getContext().getResources(),
view.getContext().getTheme());
if (attributes != null) {
for (int i = 0; i < attributes.length; i += 2) {
if (attributes[i] != null) {
out.write(attributes[i] + "\n");
out.write(attributes[i + 1] + "\n");
}
}
}
out.write("DONE.");
out.newLine();
} catch (Exception e) {
android.util.Log.w("View", "Problem dumping View Theme:", e);
} finally {
if (out != null) {
out.close();
}
}
}
/**
* Gets the style attributes from the {@link Resources.Theme}. For debugging only.
*
* @param resources Resources to resolve attributes from.
* @param theme Theme to dump.
* @return a String array containing pairs of adjacent Theme attribute data: name followed by
* its value.
*
* @hide
*/
private static String[] getStyleAttributesDump(Resources resources, Resources.Theme theme) {
TypedValue outValue = new TypedValue();
String nullString = "null";
int i = 0;
int[] attributes = theme.getAllAttributes();
String[] data = new String[attributes.length * 2];
for (int attributeId : attributes) {
try {
data[i] = resources.getResourceName(attributeId);
data[i + 1] = theme.resolveAttribute(attributeId, outValue, true) ?
outValue.coerceToString().toString() : nullString;
i += 2;
// attempt to replace reference data with its name
if (outValue.type == TypedValue.TYPE_REFERENCE) {
data[i - 1] = resources.getResourceName(outValue.resourceId);
}
} catch (Resources.NotFoundException e) {
// ignore resources we can't resolve
}
}
return data;
}
private static View findView(ViewGroup group, String className, int hashCode) {
if (isRequestedView(group, className, hashCode)) {
return group;
}
final int count = group.getChildCount();
for (int i = 0; i < count; i++) {
final View view = group.getChildAt(i);
if (view instanceof ViewGroup) {
final View found = findView((ViewGroup) view, className, hashCode);
if (found != null) {
return found;
}
} else if (isRequestedView(view, className, hashCode)) {
return view;
}
if (view.mOverlay != null) {
final View found = findView((ViewGroup) view.mOverlay.mOverlayViewGroup,
className, hashCode);
if (found != null) {
return found;
}
}
if (view instanceof HierarchyHandler) {
final View found = ((HierarchyHandler)view)
.findHierarchyView(className, hashCode);
if (found != null) {
return found;
}
}
}
return null;
}
private static boolean isRequestedView(View view, String className, int hashCode) {
if (view.hashCode() == hashCode) {
String viewClassName = view.getClass().getName();
if (className.equals("ViewOverlay")) {
return viewClassName.equals("android.view.ViewOverlay$OverlayViewGroup");
} else {
return className.equals(viewClassName);
}
}
return false;
}
private static void dumpViewHierarchy(Context context, ViewGroup group,
BufferedWriter out, int level, boolean skipChildren, boolean includeProperties) {
if (!dumpView(context, group, out, level, includeProperties)) {
return;
}
if (skipChildren) {
return;
}
final int count = group.getChildCount();
for (int i = 0; i < count; i++) {
final View view = group.getChildAt(i);
if (view instanceof ViewGroup) {
dumpViewHierarchy(context, (ViewGroup) view, out, level + 1, skipChildren,
includeProperties);
} else {
dumpView(context, view, out, level + 1, includeProperties);
}
if (view.mOverlay != null) {
ViewOverlay overlay = view.getOverlay();
ViewGroup overlayContainer = overlay.mOverlayViewGroup;
dumpViewHierarchy(context, overlayContainer, out, level + 2, skipChildren,
includeProperties);
}
}
if (group instanceof HierarchyHandler) {
((HierarchyHandler)group).dumpViewHierarchyWithProperties(out, level + 1);
}
}
private static boolean dumpView(Context context, View view,
BufferedWriter out, int level, boolean includeProperties) {
try {
for (int i = 0; i < level; i++) {
out.write(' ');
}
String className = view.getClass().getName();
if (className.equals("android.view.ViewOverlay$OverlayViewGroup")) {
className = "ViewOverlay";