forked from flutter/flutter-intellij
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlutterApp.java
904 lines (761 loc) · 28.3 KB
/
FlutterApp.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
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
/*
* Copyright 2016 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run.daemon;
import com.google.common.base.Stopwatch;
import com.google.gson.JsonObject;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.history.LocalHistory;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.EventDispatcher;
import com.intellij.util.concurrency.AppExecutorUtil;
import io.flutter.FlutterMessages;
import io.flutter.FlutterUtils;
import io.flutter.ObservatoryConnector;
import io.flutter.bazel.Workspace;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.logging.FlutterConsoleLogManager;
import io.flutter.pub.PubRoot;
import io.flutter.pub.PubRoots;
import io.flutter.run.FlutterDebugProcess;
import io.flutter.run.FlutterDevice;
import io.flutter.run.FlutterLaunchMode;
import io.flutter.run.common.RunMode;
import io.flutter.settings.FlutterSettings;
import io.flutter.utils.MostlySilentColoredProcessHandler;
import io.flutter.utils.ProgressHelper;
import io.flutter.utils.StreamSubscription;
import io.flutter.utils.UrlUtils;
import io.flutter.utils.VmServiceListenerAdapter;
import io.flutter.vmService.DisplayRefreshRateManager;
import io.flutter.vmService.ServiceExtensions;
import io.flutter.vmService.VMServiceManager;
import org.dartlang.vm.service.VmService;
import org.dartlang.vm.service.element.Event;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
// TODO(devoncarew): Move this class up to the io.flutter.run package.
/**
* A running Flutter app.
*/
public class FlutterApp implements Disposable {
private static final Logger LOG = Logger.getInstance(FlutterApp.class);
private static final Key<FlutterApp> FLUTTER_APP_KEY = new Key<>("FLUTTER_APP_KEY");
private final @NotNull Project myProject;
private final @Nullable Module myModule;
private final @NotNull RunMode myMode;
private final @NotNull FlutterDevice myDevice;
private final @NotNull ProcessHandler myProcessHandler;
private final @NotNull ExecutionEnvironment myExecutionEnvironment;
private final @NotNull DaemonApi myDaemonApi;
private final @NotNull GeneralCommandLine myCommand;
private @Nullable String myAppId;
private @Nullable String myWsUrl;
private @Nullable String myBaseUri;
private @Nullable ConsoleView myConsole;
private FlutterConsoleLogManager myFlutterConsoleLogManager;
/**
* The command with which the app was launched.
* <p>
* Should be "run" if the app was `flutter run` and "attach" if the app was `flutter attach`.
*/
private @Nullable String myLaunchMode;
private @Nullable List<PubRoot> myPubRoots;
private int reloadCount;
private int userReloadCount;
private int restartCount;
private long maxFileTimestamp;
/**
* Non-null when the debugger is paused.
*/
private @Nullable Runnable myResume;
private final AtomicReference<State> myState = new AtomicReference<>(State.STARTING);
private final EventDispatcher<FlutterAppListener> listenersDispatcher = EventDispatcher.create(FlutterAppListener.class);
private final ObservatoryConnector myConnector;
private @Nullable FlutterDebugProcess myFlutterDebugProcess;
private @Nullable VmService myVmService;
private @Nullable VMServiceManager myVMServiceManager;
private static final Key<FlutterApp> APP_KEY = Key.create("FlutterApp");
public static void addToEnvironment(@NotNull ExecutionEnvironment env, @NotNull FlutterApp app) {
env.putUserData(APP_KEY, app);
}
@Nullable
public static FlutterApp fromEnv(@NotNull ExecutionEnvironment env) {
return env.getUserData(APP_KEY);
}
FlutterApp(@NotNull Project project,
@Nullable Module module,
@NotNull RunMode mode,
@NotNull FlutterDevice device,
@NotNull ProcessHandler processHandler,
@NotNull ExecutionEnvironment executionEnvironment,
@NotNull DaemonApi daemonApi,
@NotNull GeneralCommandLine command) {
myProject = project;
myModule = module;
myMode = mode;
myDevice = device;
myProcessHandler = processHandler;
myProcessHandler.putUserData(FLUTTER_APP_KEY, this);
myExecutionEnvironment = executionEnvironment;
myDaemonApi = daemonApi;
myCommand = command;
maxFileTimestamp = System.currentTimeMillis();
myConnector = new ObservatoryConnector() {
@Override
public @Nullable
String getWebSocketUrl() {
// Don't try to use observatory until the flutter command is done starting up.
if (getState() != State.STARTED) return null;
return myWsUrl;
}
public @Nullable
String getBrowserUrl() {
String url = myWsUrl;
if (url == null) return null;
if (url.startsWith("ws:")) {
url = "http:" + url.substring(3);
}
if (url.endsWith("/ws")) {
url = url.substring(0, url.length() - 3);
}
return url;
}
@Override
public String getRemoteBaseUrl() {
return myBaseUri;
}
@Override
public void onDebuggerPaused(@NotNull Runnable resume) {
myResume = resume;
}
@Override
public void onDebuggerResumed() {
myResume = null;
}
};
}
@NotNull
public GeneralCommandLine getCommand() {
return myCommand;
}
@Nullable
public static FlutterApp fromProcess(@NotNull ProcessHandler process) {
return process.getUserData(FLUTTER_APP_KEY);
}
@Nullable
public static FlutterApp firstFromProjectProcess(@NotNull Project project) {
final List<RunContentDescriptor> runningProcesses =
ExecutionManager.getInstance(project).getContentManager().getAllDescriptors();
for (RunContentDescriptor descriptor : runningProcesses) {
final ProcessHandler process = descriptor.getProcessHandler();
if (process != null) {
final FlutterApp app = FlutterApp.fromProcess(process);
if (app != null) {
return app;
}
}
}
return null;
}
@NotNull
public static List<FlutterApp> allFromProjectProcess(@NotNull Project project) {
final List<FlutterApp> allRunningApps = new ArrayList<>();
final List<RunContentDescriptor> runningProcesses =
ExecutionManager.getInstance(project).getContentManager().getAllDescriptors();
for (RunContentDescriptor descriptor : runningProcesses) {
final ProcessHandler process = descriptor.getProcessHandler();
if (process != null) {
final FlutterApp app = FlutterApp.fromProcess(process);
if (app != null) {
allRunningApps.add(app);
}
}
}
return allRunningApps;
}
/**
* Creates a process that will launch the flutter app.
* <p>
* (Assumes we are launching it in --machine mode.)
*/
@NotNull
public static FlutterApp start(@NotNull ExecutionEnvironment env,
@NotNull Project project,
@Nullable Module module,
@NotNull RunMode mode,
@NotNull FlutterDevice device,
@NotNull GeneralCommandLine command,
@Nullable String analyticsStart,
@Nullable String analyticsStop)
throws ExecutionException {
LOG.info(analyticsStart + " " + project.getName() + " (" + mode.mode() + ")");
LOG.info(command.toString());
Consumer<String> onTextAvailable = null;
if (WorkspaceCache.getInstance(project).isBazel()) {
Workspace workspace = WorkspaceCache.getInstance(project).get();
assert (workspace != null);
String configWarningPrefix = workspace.getConfigWarningPrefix();
if (configWarningPrefix != null) {
onTextAvailable = text -> {
if (text.startsWith(configWarningPrefix)) {
FlutterMessages.showWarning(
"Configuration warning",
UrlUtils.generateHtmlFragmentWithHrefTags(text.substring(configWarningPrefix.length())),
null
);
}
};
}
}
final ProcessHandler process = new MostlySilentColoredProcessHandler(command, onTextAvailable);
Disposer.register(project, process::destroyProcess);
final DaemonApi api = new DaemonApi(process);
final FlutterApp app = new FlutterApp(project, module, mode, device, process, env, api, command);
process.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull ProcessEvent event) {
LOG.info(analyticsStop + " " + project.getName() + " (" + mode.mode() + ")");
Disposer.dispose(app);
}
});
api.listen(process, new FlutterAppDaemonEventListener(app, project));
return app;
}
@NotNull
public RunMode getMode() {
return myMode;
}
/**
* Returns the process running the daemon.
*/
@NotNull
public ProcessHandler getProcessHandler() {
return myProcessHandler;
}
@NotNull
public ObservatoryConnector getConnector() {
return myConnector;
}
/** @noinspection BooleanMethodIsAlwaysInverted*/
public boolean appSupportsHotReload() {
// Introspect based on registered services.
if (myVMServiceManager != null && myVMServiceManager.hasAnyRegisteredServices()) {
return myVMServiceManager.hasRegisteredService("reloadSources");
}
return true;
}
public State getState() {
return myState.get();
}
public boolean isStarted() {
final State state = myState.get();
return state != State.STARTING && state != State.TERMINATED;
}
public boolean isReloading() {
return myState.get() == State.RELOADING || myState.get() == State.RESTARTING;
}
public boolean isConnected() {
return myState.get() != State.TERMINATING && myState.get() != State.TERMINATED;
}
void setAppId(@NotNull String id) {
myAppId = id;
}
void setWsUrl(@NotNull String url) {
myWsUrl = url;
}
void setBaseUri(@NotNull String uri) {
myBaseUri = uri;
}
void setLaunchMode(@Nullable String launchMode) {
myLaunchMode = launchMode;
}
/**
* Perform a hot restart of the the app.
*/
public CompletableFuture<DaemonApi.RestartResult> performRestartApp(@NotNull String reason) {
if (myAppId == null) {
FlutterUtils.warn(LOG, "cannot restart Flutter app because app id is not set");
final CompletableFuture<DaemonApi.RestartResult> result = new CompletableFuture<>();
result.completeExceptionally(new IllegalStateException("cannot restart Flutter app because app id is not set"));
return result;
}
restartCount++;
userReloadCount = 0;
LocalHistory.getInstance().putSystemLabel(getProject(), "Flutter hot restart");
maxFileTimestamp = System.currentTimeMillis();
changeState(State.RESTARTING);
final CompletableFuture<DaemonApi.RestartResult> future =
myDaemonApi.restartApp(myAppId, true, false, reason);
future.thenAccept(result -> changeState(State.STARTED));
future.thenRun(this::notifyAppRestarted);
return future;
}
private void notifyAppReloaded() {
listenersDispatcher.getMulticaster().notifyAppReloaded();
}
private void notifyAppRestarted() {
listenersDispatcher.getMulticaster().notifyAppRestarted();
}
public boolean isSameModule(@Nullable final Module other) {
return Objects.equals(myModule, other);
}
/**
* @return whether the latest of the version of the file is running.
*/
public boolean isLatestVersionRunning(VirtualFile file) {
return file != null && file.getTimeStamp() <= maxFileTimestamp;
}
/**
* Indicate that we are about the start hot reload for this app.
* <p>
* This state change is useful as we can delay the actual hot reload slightly, but still change the
* app state in order to prevent starting two simultaneous hot reloads.
* <p>
* Return the previous app state.
*/
public State transitionStartingHotReload() {
final State newState = State.RELOADING;
final State oldState = myState.getAndSet(newState);
if (oldState != newState) {
listenersDispatcher.getMulticaster().stateChanged(newState);
}
return oldState;
}
/**
* Cancel a hot reload state and restore the app's previous state (generally, `State.STARTED`).
*/
public void cancelHotReloadState(@Nullable State previousState) {
if (previousState != null) {
changeState(previousState);
}
}
/**
* Perform a hot reload of the app.
*/
public CompletableFuture<DaemonApi.RestartResult> performHotReload(boolean pauseAfterRestart, @NotNull String reason) {
if (myAppId == null) {
FlutterUtils.warn(LOG, "cannot reload Flutter app because app id is not set");
if (getState() == State.RELOADING) {
changeState(State.STARTED);
}
final CompletableFuture<DaemonApi.RestartResult> result = new CompletableFuture<>();
result.completeExceptionally(new IllegalStateException("cannot reload Flutter app because app id is not set"));
return result;
}
reloadCount++;
userReloadCount++;
LocalHistory.getInstance().putSystemLabel(getProject(), "hot reload #" + userReloadCount);
maxFileTimestamp = System.currentTimeMillis();
changeState(State.RELOADING);
final CompletableFuture<DaemonApi.RestartResult> future =
myDaemonApi.restartApp(myAppId, false, pauseAfterRestart, reason);
future.thenAccept(result -> changeState(State.STARTED));
future.thenRun(this::notifyAppReloaded);
return future;
}
public CompletableFuture<DaemonApi.DevToolsAddress> serveDevTools() {
return myDaemonApi.devToolsServe();
}
public CompletableFuture<String> togglePlatform() {
if (myAppId == null) {
FlutterUtils.warn(LOG, "cannot invoke togglePlatform on Flutter app because app id is not set");
return CompletableFuture.completedFuture(null);
}
final CompletableFuture<JsonObject> result = callServiceExtension(ServiceExtensions.togglePlatformMode.getExtension());
return result.thenApply(obj -> {
//noinspection CodeBlock2Expr
return obj.get("value").getAsString();
});
}
public CompletableFuture<String> togglePlatform(String platform) {
if (myAppId == null) {
FlutterUtils.warn(LOG, "cannot invoke togglePlatform on Flutter app because app id is not set");
return CompletableFuture.completedFuture(null);
}
final Map<String, Object> params = new HashMap<>();
params.put("value", platform);
return callServiceExtension(ServiceExtensions.togglePlatformMode.getExtension(), params).thenApply(obj -> {
//noinspection CodeBlock2Expr
return obj != null ? obj.get("value").getAsString() : null;
});
}
public CompletableFuture<JsonObject> callServiceExtension(String methodName) {
return callServiceExtension(methodName, new HashMap<>());
}
public CompletableFuture<JsonObject> callServiceExtension(String methodName, Map<String, Object> params) {
if (myAppId == null) {
FlutterUtils.warn(LOG, "cannot invoke " + methodName + " on Flutter app because app id is not set");
return CompletableFuture.completedFuture(null);
}
if (isFlutterIsolateSuspended()) {
return whenFlutterIsolateResumed().thenComposeAsync(
(ignored) -> myDaemonApi.callAppServiceExtension(myAppId, methodName, params)
);
}
else {
// TODO(devoncarew): Convert this to using the service protocol (instead of the daemon protocol).
return myDaemonApi.callAppServiceExtension(myAppId, methodName, params);
}
}
@SuppressWarnings("UnusedReturnValue")
public CompletableFuture<Boolean> callBooleanExtension(String methodName, boolean enabled) {
final Map<String, Object> params = new HashMap<>();
params.put("enabled", enabled);
return callServiceExtension(methodName, params).thenApply(obj -> {
//noinspection CodeBlock2Expr
return obj == null ? null : obj.get("enabled").getAsBoolean();
});
}
/**
* Call a boolean service extension only if it is already present, skipping otherwise.
* <p>
* Only use this method if you are confident there will not be a race condition where
* the service extension is registered shortly after this method is called.
*/
@SuppressWarnings("UnusedReturnValue")
public CompletableFuture<Boolean> maybeCallBooleanExtension(String methodName, boolean enabled) {
if (getVMServiceManager() != null && getVMServiceManager().hasServiceExtensionNow(methodName)) {
return callBooleanExtension(methodName, enabled);
}
return CompletableFuture.completedFuture(false);
}
@Nullable
public StreamSubscription<Boolean> hasServiceExtension(String name, Consumer<Boolean> onData) {
if (getVMServiceManager() == null) {
return null;
}
return getVMServiceManager().hasServiceExtension(name, onData);
}
public void hasServiceExtension(String name, Consumer<Boolean> onData, Disposable parentDisposable) {
if (getVMServiceManager() != null) {
getVMServiceManager().hasServiceExtension(name, onData, parentDisposable);
}
}
public void setConsole(@Nullable ConsoleView console) {
myConsole = console;
}
@Nullable
public ConsoleView getConsole() {
return myConsole;
}
/**
* Transitions to a new state and fires events.
* <p>
* If no change is needed, returns false and does not fire events.
*/
boolean changeState(@NotNull State newState) {
final State oldState = myState.getAndSet(newState);
if (oldState == newState) {
return false; // debounce
}
listenersDispatcher.getMulticaster().stateChanged(newState);
return true;
}
/**
* Starts shutting down the process.
* <p>
* If possible, we want to shut down gracefully by sending a stop command to the application.
*/
public Future shutdownAsync() {
final FutureTask done = new FutureTask<>(() -> null);
if (!changeState(State.TERMINATING)) {
done.run();
return done; // Debounce; already shutting down.
}
if (myResume != null) {
myResume.run();
}
final String appId = myAppId;
if (appId == null) {
// If it it didn't finish starting up, shut down abruptly.
myProcessHandler.destroyProcess();
done.run();
return done;
}
// Do the rest in the background to avoid freezing the Swing dispatch thread.
AppExecutorUtil.getAppExecutorService().submit(() -> {
// Try to shut down gracefully (need to wait for a response).
final Future stopDone;
if (DaemonEvent.AppStarting.LAUNCH_MODE_ATTACH.equals(myLaunchMode)) {
stopDone = myDaemonApi.detachApp(appId);
}
else {
stopDone = myDaemonApi.stopApp(appId);
}
try {
// We wait for a maximum of 10 seconds to allow the process to shut down gracefully
stopDone.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
// Ignore errors from app.stop.
}
// If it didn't work, shut down abruptly.
myProcessHandler.destroyProcess();
myDaemonApi.cancelPending();
done.run();
});
return done;
}
public void addStateListener(@NotNull FlutterAppListener listener) {
listenersDispatcher.addListener(listener);
listener.stateChanged(myState.get());
}
public void removeStateListener(@NotNull FlutterAppListener listener) {
listenersDispatcher.removeListener(listener);
}
public FlutterLaunchMode getLaunchMode() {
return FlutterLaunchMode.fromEnv(myExecutionEnvironment);
}
public boolean isSessionActive() {
final FlutterDebugProcess debugProcess = getFlutterDebugProcess();
return isStarted() && debugProcess != null && debugProcess.getVmConnected() &&
!debugProcess.getSession().isStopped();
}
@NotNull
public FlutterDevice device() {
return myDevice;
}
@Nullable
public String deviceId() {
return myDevice.deviceId();
}
public void setFlutterDebugProcess(FlutterDebugProcess flutterDebugProcess) {
myFlutterDebugProcess = flutterDebugProcess;
}
public FlutterDebugProcess getFlutterDebugProcess() {
return myFlutterDebugProcess;
}
public void setVmServices(@NotNull VmService vmService, VMServiceManager vmServiceManager) {
myVmService = vmService;
myVMServiceManager = vmServiceManager;
myVmService.addVmServiceListener(new VmServiceListenerAdapter() {
@Override
public void received(String streamId, Event event) {
if (StringUtil.equals(streamId, VmService.EXTENSION_STREAM_ID)) {
if (StringUtil.equals("Flutter.Frame", event.getExtensionKind())) {
listenersDispatcher.getMulticaster().notifyFrameRendered();
}
}
}
});
listenersDispatcher.getMulticaster().notifyVmServiceAvailable(vmService);
// Init the app's FlutterConsoleLogManager.
getFlutterConsoleLogManager();
}
@Nullable
public VmService getVmService() {
return myVmService;
}
@Nullable
public VMServiceManager getVMServiceManager() {
return myVMServiceManager;
}
@Nullable
public DisplayRefreshRateManager getDisplayRefreshRateManager() {
return myVMServiceManager != null ? myVMServiceManager.displayRefreshRateManager : null;
}
@NotNull
public Project getProject() {
return myProject;
}
@NotNull
public List<PubRoot> getPubRoots() {
if (myPubRoots == null) {
myPubRoots = PubRoots.forProject(myProject);
}
return myPubRoots;
}
@Nullable
public Module getModule() {
return myModule;
}
public FlutterConsoleLogManager getFlutterConsoleLogManager() {
if (myFlutterConsoleLogManager == null) {
assert (getConsole() != null);
myFlutterConsoleLogManager = new FlutterConsoleLogManager(getConsole(), this);
if (FlutterSettings.getInstance().isShowStructuredErrors()) {
// Calling this will override the default Flutter stdout error display.
hasServiceExtension(ServiceExtensions.toggleShowStructuredErrors.getExtension(), (present) -> {
if (present) {
callBooleanExtension(ServiceExtensions.toggleShowStructuredErrors.getExtension(), true);
}
});
}
}
return myFlutterConsoleLogManager;
}
@Override
public String toString() {
return myExecutionEnvironment + ":" + deviceId();
}
public boolean isFlutterIsolateSuspended() {
if (!isSessionActive() || myVMServiceManager.getCurrentFlutterIsolateRaw() == null) {
// The isolate cannot be suspended if it isn't running yet.
return false;
}
return getFlutterDebugProcess().isIsolateSuspended(myVMServiceManager.getCurrentFlutterIsolateRaw().getId());
}
private CompletableFuture<?> whenFlutterIsolateResumed() {
if (!isFlutterIsolateSuspended()) {
return CompletableFuture.completedFuture(null);
}
return getFlutterDebugProcess().whenIsolateResumed(myVMServiceManager.getCurrentFlutterIsolateRaw().getId());
}
public interface FlutterAppListener extends EventListener {
default void stateChanged(State newState) {
}
default void notifyAppReloaded() {
}
default void notifyAppRestarted() {
}
default void notifyFrameRendered() {
}
default void notifyVmServiceAvailable(VmService vmService) {
}
}
public enum State {STARTING, STARTED, RELOADING, RESTARTING, TERMINATING, TERMINATED}
@Override
public void dispose() {
}
}
/**
* Listens for events while running or debugging an app.
*/
class FlutterAppDaemonEventListener implements DaemonEvent.Listener {
private static final Logger LOG = Logger.getInstance(FlutterAppDaemonEventListener.class);
private final @NotNull FlutterApp app;
private final @NotNull ProgressHelper progress;
private final AtomicReference<Stopwatch> stopwatch = new AtomicReference<>();
FlutterAppDaemonEventListener(@NotNull FlutterApp app, @NotNull Project project) {
this.app = app;
this.progress = new ProgressHelper(project);
}
// process lifecycle
@Override
public void processWillTerminate() {
progress.cancel();
// Shutdown must be sync so that we prevent the processTerminated() event from being delivered
// until a graceful shutdown has been tried.
try {
app.shutdownAsync().get(100, TimeUnit.MILLISECONDS);
}
catch (TimeoutException e) {
LOG.info("app shutdown took longer than 100ms");
}
catch (Exception e) {
FlutterUtils.warn(LOG, "exception while shutting down Flutter App", e);
}
}
@Override
public void processTerminated(int exitCode) {
progress.cancel();
app.changeState(FlutterApp.State.TERMINATED);
}
// daemon domain
@Override
public void onDaemonLog(@NotNull DaemonEvent.DaemonLog message) {
final ConsoleView console = app.getConsole();
if (console == null) return;
if (message.log != null) {
console.print(message.log + "\n", message.error ? ConsoleViewContentType.ERROR_OUTPUT : ConsoleViewContentType.NORMAL_OUTPUT);
}
}
@Override
public void onDaemonLogMessage(@NotNull DaemonEvent.DaemonLogMessage message) {
LOG.info("flutter app: " + message.message);
}
// app domain
@Override
public void onAppStarting(DaemonEvent.AppStarting event) {
app.setAppId(event.appId);
app.setLaunchMode(event.launchMode);
}
@Override
public void onAppDebugPort(@NotNull DaemonEvent.AppDebugPort debugInfo) {
app.setWsUrl(debugInfo.wsUri);
// Print the connection info to the console.
final ConsoleView console = app.getConsole();
if (console != null) {
console.print("Debug service listening on " + debugInfo.wsUri + "\n", ConsoleViewContentType.NORMAL_OUTPUT);
}
String uri = debugInfo.baseUri;
if (uri != null) {
if (uri.startsWith("file:")) {
// Convert the file: url to a path.
try {
uri = new URL(uri).getPath();
if (uri.endsWith(File.separator)) {
uri = uri.substring(0, uri.length() - 1);
}
}
catch (MalformedURLException e) {
// ignore
}
}
app.setBaseUri(uri);
}
}
@Override
public void onAppStarted(DaemonEvent.AppStarted started) {
app.changeState(FlutterApp.State.STARTED);
}
@Override
public void onAppLog(@NotNull DaemonEvent.AppLog message) {
final ConsoleView console = app.getConsole();
if (console == null) return;
console.print(message.log + "\n", message.error ? ConsoleViewContentType.ERROR_OUTPUT : ConsoleViewContentType.NORMAL_OUTPUT);
}
@Override
public void onAppProgressStarting(@NotNull DaemonEvent.AppProgress event) {
progress.start(event.message);
if (event.getType().startsWith("hot.")) {
// We clear the console view in order to help indicate that a reload is happening.
if (app.getConsole() != null) {
if (!FlutterSettings.getInstance().isVerboseLogging() && !FlutterSettings.getInstance().isPerserveLogsDuringHotReloadAndRestart()) {
app.getConsole().clear();
}
}
stopwatch.set(Stopwatch.createStarted());
}
if (app.getConsole() != null) {
app.getConsole().print(event.message + "\n", ConsoleViewContentType.NORMAL_OUTPUT);
}
}
@Override
public void onAppProgressFinished(@NotNull DaemonEvent.AppProgress event) {
progress.done();
}
@Override
public void onAppStopped(@NotNull DaemonEvent.AppStopped stopped) {
if (stopped.error != null && app.getConsole() != null) {
app.getConsole().print("Finished with error: " + stopped.error + "\n", ConsoleViewContentType.ERROR_OUTPUT);
}
progress.cancel();
app.getProcessHandler().destroyProcess();
}
}