-
Notifications
You must be signed in to change notification settings - Fork 0
/
ViewServer.java
854 lines (752 loc) · 26.8 KB
/
ViewServer.java
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
/*
* Copyright (C) 2011 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 com.android.debug.hv;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewDebug;
/**
* <p>This class can be used to enable the use of HierarchyViewer inside an
* application. HierarchyViewer is an Android SDK tool that can be used
* to inspect and debug the user interface of running applications. For
* security reasons, HierarchyViewer does not work on production builds
* (for instance phones bought in store.) By using this class, you can
* make HierarchyViewer work on any device. You must be very careful
* however to only enable HierarchyViewer when debugging your
* application.</p>
*
* <p>To use this view server, your application must require the INTERNET
* permission.</p>
*
* <p>The recommended way to use this API is to register activities when
* they are created, and to unregister them when they get destroyed:</p>
*
* <pre>
* public class MyActivity extends Activity {
* public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* // Set content view, etc.
* ViewServer.get(this).addWindow(this);
* }
*
* public void onDestroy() {
* super.onDestroy();
* ViewServer.get(this).removeWindow(this);
* }
*
* public void onResume() {
* super.onResume();
* ViewServer.get(this).setFocusedWindow(this);
* }
* }
* </pre>
*
* <p>
* In a similar fashion, you can use this API with an InputMethodService:
* </p>
*
* <pre>
* public class MyInputMethodService extends InputMethodService {
* public void onCreate() {
* super.onCreate();
* View decorView = getWindow().getWindow().getDecorView();
* String name = "MyInputMethodService";
* ViewServer.get(this).addWindow(decorView, name);
* }
*
* public void onDestroy() {
* super.onDestroy();
* View decorView = getWindow().getWindow().getDecorView();
* ViewServer.get(this).removeWindow(decorView);
* }
*
* public void onStartInput(EditorInfo attribute, boolean restarting) {
* super.onStartInput(attribute, restarting);
* View decorView = getWindow().getWindow().getDecorView();
* ViewServer.get(this).setFocusedWindow(decorView);
* }
* }
* </pre>
*/
public class ViewServer implements Runnable {
/**
* The default port used to start view servers.
*/
private static final int VIEW_SERVER_DEFAULT_PORT = 4939;
private static final int VIEW_SERVER_MAX_CONNECTIONS = 10;
private static final String BUILD_TYPE_USER = "user";
// Debug facility
private static final String LOG_TAG = "ViewServer";
private static final String VALUE_PROTOCOL_VERSION = "4";
private static final String VALUE_SERVER_VERSION = "4";
// Protocol commands
// Returns the protocol version
private static final String COMMAND_PROTOCOL_VERSION = "PROTOCOL";
// Returns the server version
private static final String COMMAND_SERVER_VERSION = "SERVER";
// Lists all of the available windows in the system
private static final String COMMAND_WINDOW_MANAGER_LIST = "LIST";
// Keeps a connection open and notifies when the list of windows changes
private static final String COMMAND_WINDOW_MANAGER_AUTOLIST = "AUTOLIST";
// Returns the focused window
private static final String COMMAND_WINDOW_MANAGER_GET_FOCUS = "GET_FOCUS";
private ServerSocket mServer;
private final int mPort;
private Thread mThread;
private ExecutorService mThreadPool;
private final List<WindowListener> mListeners =
new CopyOnWriteArrayList<ViewServer.WindowListener>();
private final HashMap<View, String> mWindows = new HashMap<View, String>();
private final ReentrantReadWriteLock mWindowsLock = new ReentrantReadWriteLock();
private View mFocusedWindow;
private final ReentrantReadWriteLock mFocusLock = new ReentrantReadWriteLock();
private static ViewServer sServer;
/**
* Returns a unique instance of the ViewServer. This method should only be
* called from the main thread of your application. The server will have
* the same lifetime as your process.
*
* If your application does not have the <code>android:debuggable</code>
* flag set in its manifest, the server returned by this method will
* be a dummy object that does not do anything. This allows you to use
* the same code in debug and release versions of your application.
*
* @param context A Context used to check whether the application is
* debuggable, this can be the application context
*/
public static ViewServer get(Context context) {
ApplicationInfo info = context.getApplicationInfo();
if (BUILD_TYPE_USER.equals(Build.TYPE) &&
(info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
if (sServer == null) {
sServer = new ViewServer(ViewServer.VIEW_SERVER_DEFAULT_PORT);
}
if (!sServer.isRunning()) {
try {
sServer.start();
} catch (IOException e) {
Log.d(LOG_TAG, "Error:", e);
}
}
} else {
sServer = new NoopViewServer();
}
return sServer;
}
private ViewServer() {
mPort = -1;
}
/**
* Creates a new ViewServer associated with the specified window manager on the
* specified local port. The server is not started by default.
*
* @param port The port for the server to listen to.
*
* @see #start()
*/
private ViewServer(int port) {
mPort = port;
}
/**
* Starts the server.
*
* @return True if the server was successfully created, or false if it already exists.
* @throws IOException If the server cannot be created.
*
* @see #stop()
* @see #isRunning()
* @see WindowManagerService#startViewServer(int)
*/
public boolean start() throws IOException {
if (mThread != null) {
return false;
}
mThread = new Thread(this, "Local View Server [port=" + mPort + "]");
mThreadPool = Executors.newFixedThreadPool(VIEW_SERVER_MAX_CONNECTIONS);
mThread.start();
return true;
}
/**
* Stops the server.
*
* @return True if the server was stopped, false if an error occurred or if the
* server wasn't started.
*
* @see #start()
* @see #isRunning()
* @see WindowManagerService#stopViewServer()
*/
public boolean stop() {
if (mThread != null) {
mThread.interrupt();
if (mThreadPool != null) {
try {
mThreadPool.shutdownNow();
} catch (SecurityException e) {
Log.w(LOG_TAG, "Could not stop all view server threads");
}
}
mThreadPool = null;
mThread = null;
try {
mServer.close();
mServer = null;
return true;
} catch (IOException e) {
Log.w(LOG_TAG, "Could not close the view server");
}
}
mWindowsLock.writeLock().lock();
try {
mWindows.clear();
} finally {
mWindowsLock.writeLock().unlock();
}
mFocusLock.writeLock().lock();
try {
mFocusedWindow = null;
} finally {
mFocusLock.writeLock().unlock();
}
return false;
}
/**
* Indicates whether the server is currently running.
*
* @return True if the server is running, false otherwise.
*
* @see #start()
* @see #stop()
* @see WindowManagerService#isViewServerRunning()
*/
public boolean isRunning() {
return mThread != null && mThread.isAlive();
}
/**
* Invoke this method to register a new view hierarchy.
*
* @param activity The activity whose view hierarchy/window to register
*
* @see #addWindow(View, String)
* @see #removeWindow(Activity)
*/
public void addWindow(Activity activity) {
String name = activity.getTitle().toString();
if (TextUtils.isEmpty(name)) {
name = activity.getClass().getCanonicalName() +
"/0x" + System.identityHashCode(activity);
} else {
name += "(" + activity.getClass().getCanonicalName() + ")";
}
addWindow(activity.getWindow().getDecorView(), name);
}
/**
* Invoke this method to unregister a view hierarchy.
*
* @param activity The activity whose view hierarchy/window to unregister
*
* @see #addWindow(Activity)
* @see #removeWindow(View)
*/
public void removeWindow(Activity activity) {
removeWindow(activity.getWindow().getDecorView());
}
/**
* Invoke this method to register a new view hierarchy.
*
* @param view A view that belongs to the view hierarchy/window to register
* @name name The name of the view hierarchy/window to register
*
* @see #removeWindow(View)
*/
public void addWindow(View view, String name) {
mWindowsLock.writeLock().lock();
try {
mWindows.put(view.getRootView(), name);
} finally {
mWindowsLock.writeLock().unlock();
}
fireWindowsChangedEvent();
}
/**
* Invoke this method to unregister a view hierarchy.
*
* @param view A view that belongs to the view hierarchy/window to unregister
*
* @see #addWindow(View, String)
*/
public void removeWindow(View view) {
View rootView;
mWindowsLock.writeLock().lock();
try {
rootView = view.getRootView();
mWindows.remove(rootView);
} finally {
mWindowsLock.writeLock().unlock();
}
mFocusLock.writeLock().lock();
try {
if (mFocusedWindow == rootView) {
mFocusedWindow = null;
}
} finally {
mFocusLock.writeLock().unlock();
}
fireWindowsChangedEvent();
}
/**
* Invoke this method to change the currently focused window.
*
* @param activity The activity whose view hierarchy/window hasfocus,
* or null to remove focus
*/
public void setFocusedWindow(Activity activity) {
setFocusedWindow(activity.getWindow().getDecorView());
}
/**
* Invoke this method to change the currently focused window.
*
* @param view A view that belongs to the view hierarchy/window that has focus,
* or null to remove focus
*/
public void setFocusedWindow(View view) {
mFocusLock.writeLock().lock();
try {
mFocusedWindow = view == null ? null : view.getRootView();
} finally {
mFocusLock.writeLock().unlock();
}
fireFocusChangedEvent();
}
/**
* Main server loop.
*/
public void run() {
try {
mServer = new ServerSocket(mPort, VIEW_SERVER_MAX_CONNECTIONS, InetAddress.getLocalHost());
} catch (Exception e) {
Log.w(LOG_TAG, "Starting ServerSocket error: ", e);
}
while (mServer != null && Thread.currentThread() == mThread) {
// Any uncaught exception will crash the system process
try {
Socket client = mServer.accept();
if (mThreadPool != null) {
mThreadPool.submit(new ViewServerWorker(client));
} else {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.w(LOG_TAG, "Connection error: ", e);
}
}
}
private static boolean writeValue(Socket client, String value) {
boolean result;
BufferedWriter out = null;
try {
OutputStream clientStream = client.getOutputStream();
out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024);
out.write(value);
out.write("\n");
out.flush();
result = true;
} catch (Exception e) {
result = false;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
result = false;
}
}
}
return result;
}
private void fireWindowsChangedEvent() {
for (WindowListener listener : mListeners) {
listener.windowsChanged();
}
}
private void fireFocusChangedEvent() {
for (WindowListener listener : mListeners) {
listener.focusChanged();
}
}
private void addWindowListener(WindowListener listener) {
if (!mListeners.contains(listener)) {
mListeners.add(listener);
}
}
private void removeWindowListener(WindowListener listener) {
mListeners.remove(listener);
}
private interface WindowListener {
void windowsChanged();
void focusChanged();
}
private static class UncloseableOutputStream extends OutputStream {
private final OutputStream mStream;
UncloseableOutputStream(OutputStream stream) {
mStream = stream;
}
public void close() throws IOException {
// Don't close the stream
}
public boolean equals(Object o) {
return mStream.equals(o);
}
public void flush() throws IOException {
mStream.flush();
}
public int hashCode() {
return mStream.hashCode();
}
public String toString() {
return mStream.toString();
}
public void write(byte[] buffer, int offset, int count)
throws IOException {
mStream.write(buffer, offset, count);
}
public void write(byte[] buffer) throws IOException {
mStream.write(buffer);
}
public void write(int oneByte) throws IOException {
mStream.write(oneByte);
}
}
private static class NoopViewServer extends ViewServer {
private NoopViewServer() {
}
@Override
public boolean start() throws IOException {
return false;
}
@Override
public boolean stop() {
return false;
}
@Override
public boolean isRunning() {
return false;
}
@Override
public void addWindow(Activity activity) {
}
@Override
public void removeWindow(Activity activity) {
}
@Override
public void addWindow(View view, String name) {
}
@Override
public void removeWindow(View view) {
}
@Override
public void setFocusedWindow(Activity activity) {
}
@Override
public void setFocusedWindow(View view) {
}
@Override
public void run() {
}
}
private class ViewServerWorker implements Runnable, WindowListener {
private Socket mClient;
private boolean mNeedWindowListUpdate;
private boolean mNeedFocusedWindowUpdate;
private final Object[] mLock = new Object[0];
public ViewServerWorker(Socket client) {
mClient = client;
mNeedWindowListUpdate = false;
mNeedFocusedWindowUpdate = false;
}
public void run() {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(mClient.getInputStream()), 1024);
final String request = in.readLine();
String command;
String parameters;
int index = request.indexOf(' ');
if (index == -1) {
command = request;
parameters = "";
} else {
command = request.substring(0, index);
parameters = request.substring(index + 1);
}
boolean result;
if (COMMAND_PROTOCOL_VERSION.equalsIgnoreCase(command)) {
result = writeValue(mClient, VALUE_PROTOCOL_VERSION);
} else if (COMMAND_SERVER_VERSION.equalsIgnoreCase(command)) {
result = writeValue(mClient, VALUE_SERVER_VERSION);
} else if (COMMAND_WINDOW_MANAGER_LIST.equalsIgnoreCase(command)) {
result = listWindows(mClient);
} else if (COMMAND_WINDOW_MANAGER_GET_FOCUS.equalsIgnoreCase(command)) {
result = getFocusedWindow(mClient);
} else if (COMMAND_WINDOW_MANAGER_AUTOLIST.equalsIgnoreCase(command)) {
result = windowManagerAutolistLoop();
} else {
result = windowCommand(mClient, command, parameters);
}
if (!result) {
Log.w(LOG_TAG, "An error occurred with the command: " + command);
}
} catch(IOException e) {
Log.w(LOG_TAG, "Connection error: ", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (mClient != null) {
try {
mClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private boolean windowCommand(Socket client, String command, String parameters) {
boolean success = true;
BufferedWriter out = null;
try {
// Find the hash code of the window
int index = parameters.indexOf(' ');
if (index == -1) {
index = parameters.length();
}
final String code = parameters.substring(0, index);
int hashCode = (int) Long.parseLong(code, 16);
// Extract the command's parameter after the window description
if (index < parameters.length()) {
parameters = parameters.substring(index + 1);
} else {
parameters = "";
}
final View window = findWindow(hashCode);
if (window == null) {
return false;
}
// call stuff
final Method dispatch = ViewDebug.class.getDeclaredMethod("dispatchCommand",
View.class, String.class, String.class, OutputStream.class);
dispatch.setAccessible(true);
dispatch.invoke(null, window, command, parameters,
new UncloseableOutputStream(client.getOutputStream()));
if (!client.isOutputShutdown()) {
out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
out.write("DONE\n");
out.flush();
}
} catch (Exception e) {
Log.w(LOG_TAG, "Could not send command " + command +
" with parameters " + parameters, e);
success = false;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
success = false;
}
}
}
return success;
}
private View findWindow(int hashCode) {
if (hashCode == -1) {
View window = null;
mWindowsLock.readLock().lock();
try {
window = mFocusedWindow;
} finally {
mWindowsLock.readLock().unlock();
}
return window;
}
mWindowsLock.readLock().lock();
try {
for (Entry<View, String> entry : mWindows.entrySet()) {
if (System.identityHashCode(entry.getKey()) == hashCode) {
return entry.getKey();
}
}
} finally {
mWindowsLock.readLock().unlock();
}
return null;
}
private boolean listWindows(Socket client) {
boolean result = true;
BufferedWriter out = null;
try {
mWindowsLock.readLock().lock();
OutputStream clientStream = client.getOutputStream();
out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024);
for (Entry<View, String> entry : mWindows.entrySet()) {
out.write(Integer.toHexString(System.identityHashCode(entry.getKey())));
out.write(' ');
out.append(entry.getValue());
out.write('\n');
}
out.write("DONE.\n");
out.flush();
} catch (Exception e) {
result = false;
} finally {
mWindowsLock.readLock().unlock();
if (out != null) {
try {
out.close();
} catch (IOException e) {
result = false;
}
}
}
return result;
}
private boolean getFocusedWindow(Socket client) {
boolean result = true;
String focusName = null;
BufferedWriter out = null;
try {
OutputStream clientStream = client.getOutputStream();
out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024);
View focusedWindow = null;
mFocusLock.readLock().lock();
try {
focusedWindow = mFocusedWindow;
} finally {
mFocusLock.readLock().unlock();
}
if (focusedWindow != null) {
mWindowsLock.readLock().lock();
try {
focusName = mWindows.get(mFocusedWindow);
} finally {
mWindowsLock.readLock().unlock();
}
out.write(Integer.toHexString(System.identityHashCode(focusedWindow)));
out.write(' ');
out.append(focusName);
}
out.write('\n');
out.flush();
} catch (Exception e) {
result = false;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
result = false;
}
}
}
return result;
}
public void windowsChanged() {
synchronized (mLock) {
mNeedWindowListUpdate = true;
mLock.notifyAll();
}
}
public void focusChanged() {
synchronized (mLock) {
mNeedFocusedWindowUpdate = true;
mLock.notifyAll();
}
}
private boolean windowManagerAutolistLoop() {
addWindowListener(this);
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(mClient.getOutputStream()));
while (!Thread.interrupted()) {
boolean needWindowListUpdate = false;
boolean needFocusedWindowUpdate = false;
synchronized (mLock) {
while (!mNeedWindowListUpdate && !mNeedFocusedWindowUpdate) {
mLock.wait();
}
if (mNeedWindowListUpdate) {
mNeedWindowListUpdate = false;
needWindowListUpdate = true;
}
if (mNeedFocusedWindowUpdate) {
mNeedFocusedWindowUpdate = false;
needFocusedWindowUpdate = true;
}
}
if (needWindowListUpdate) {
out.write("LIST UPDATE\n");
out.flush();
}
if (needFocusedWindowUpdate) {
out.write("FOCUS UPDATE\n");
out.flush();
}
}
} catch (Exception e) {
Log.w(LOG_TAG, "Connection error: ", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// Ignore
}
}
removeWindowListener(this);
}
return true;
}
}
}