-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
Copy pathComponentManagerImpl.kt
2418 lines (2147 loc) · 89.2 KB
/
ComponentManagerImpl.kt
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 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplaceGetOrSet", "ReplacePutWithAssignment", "LeakingThis",
"ReplaceJavaStaticMethodWithKotlinAnalog")
package com.intellij.serviceContainer
import com.intellij.concurrency.currentTemporaryThreadContextOrNull
import com.intellij.concurrency.resetThreadContext
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.LoadingState
import com.intellij.diagnostic.PluginException
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.idea.AppMode.isLightEdit
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.components.*
import com.intellij.openapi.components.ServiceDescriptor.PreloadMode
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.diagnostic.*
import com.intellij.openapi.extensions.*
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.extensions.impl.createExtensionPoints
import com.intellij.openapi.progress.*
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.platform.instanceContainer.internal.*
import com.intellij.platform.util.coroutines.namedChildScope
import com.intellij.util.concurrency.ThreadingAssertions
import com.intellij.util.concurrency.annotations.RequiresBlockingContext
import com.intellij.util.messages.*
import com.intellij.util.messages.impl.MessageBusEx
import com.intellij.util.messages.impl.MessageBusImpl
import com.intellij.util.runSuppressing
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import org.picocontainer.ComponentAdapter
import java.lang.StackWalker.StackFrame
import java.lang.invoke.MethodHandle
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Modifier
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicReference
import java.util.stream.Stream
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.streams.asSequence
internal val LOG: Logger
get() = logger<ComponentManagerImpl>()
@Internal
@JvmField
val useInstanceContainer: Boolean = System.getProperty("ide.instance.container") != "false"
private val methodLookup = MethodHandles.lookup()
@JvmField
@Internal
val emptyConstructorMethodType: MethodType = MethodType.methodType(Void.TYPE)
@JvmField
@Internal
val coroutineScopeMethodType: MethodType = MethodType.methodType(Void.TYPE, CoroutineScope::class.java)
private val applicationMethodType = MethodType.methodType(Void.TYPE, Application::class.java)
private val componentManagerMethodType = MethodType.methodType(Void.TYPE, ComponentManager::class.java)
@Internal
fun MethodHandles.Lookup.findConstructorOrNull(clazz: Class<*>, type: MethodType): MethodHandle? {
return try {
findConstructor(clazz, type)
}
catch (e: NoSuchMethodException) {
return null
}
catch (e: IllegalAccessException) {
return null
}
}
@Internal
abstract class ComponentManagerImpl(
internal val parent: ComponentManagerImpl?,
parentScope: CoroutineScope,
additionalContext: CoroutineContext,
) : ComponentManager, Disposable.Parent, MessageBusOwner, UserDataHolderBase(), ComponentManagerEx, ComponentStoreOwner {
protected enum class ContainerState {
PRE_INIT, COMPONENT_CREATED, DISPOSE_IN_PROGRESS, DISPOSED, DISPOSE_COMPLETED
}
protected constructor(parentScope: CoroutineScope) : this(
parent = null,
parentScope,
additionalContext = EmptyCoroutineContext,
)
protected constructor(parent: ComponentManagerImpl) : this(
parent,
parentScope = parent.getCoroutineScope(),
additionalContext = EmptyCoroutineContext,
)
companion object {
@Internal
@JvmField
val fakeCorePluginDescriptor = DefaultPluginDescriptor(PluginManagerCore.CORE_ID, null)
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
@Internal
@JvmField
val badWorkspaceComponents: Set<String> = java.util.Set.of(
"jetbrains.buildServer.codeInspection.InspectionPassRegistrar",
"jetbrains.buildServer.testStatus.TestStatusPassRegistrar",
"jetbrains.buildServer.customBuild.lang.gutterActions.CustomBuildParametersGutterActionsHighlightingPassRegistrar",
)
// not as a file level function to avoid scope cluttering
@Internal
fun createAllServices(componentManager: ComponentManagerImpl, requireEdt: Set<String>, requireReadAction: Set<String>) {
check(!useInstanceContainer)
for (o in componentManager.componentKeyToAdapter.values) {
if (o !is ServiceComponentAdapter) {
continue
}
val implementation = o.descriptor.serviceImplementation
try {
if (implementation == "org.jetbrains.plugins.groovy.mvc.MvcConsole") {
// NPE in RunnerContentUi.setLeftToolbar
continue
}
val init = { o.getInstance<Any>(componentManager, null) }
when {
requireEdt.contains(implementation) -> invokeAndWaitIfNeeded(null, init)
requireReadAction.contains(implementation) -> runReadAction(init)
else -> init()
}
}
catch (e: Throwable) {
LOG.error("Cannot create $implementation", e)
}
}
}
@Internal
suspend fun createAllServices2(
componentManager: ComponentManagerImpl,
requireEdt: Set<String>,
requireReadAction: Set<String>,
) {
check(useInstanceContainer)
// componentManager.serviceContainer.preloadAllInstances()
val holders = componentManager.serviceContainer.instanceHolders()
for (holder in holders) {
try {
when (val instanceClassName = holder.instanceClassName()) {
in requireEdt -> withContext(Dispatchers.EDT) {
holder.getInstanceInCallerContext(keyClass = null)
}
in requireReadAction -> readActionBlocking {
holder.getOrCreateInstanceBlocking(debugString = instanceClassName, keyClass = null)
}
else -> holder.getInstanceInCallerContext(keyClass = null)
}
}
catch (ce: CancellationException) {
currentCoroutineContext().ensureActive()
LOG.error("Cannot create ${holder}", ce)
}
catch (t: Throwable) {
LOG.error("Cannot create ${holder}", t)
}
}
}
}
private val scopeHolder = ScopeHolder(
parentScope,
additionalContext,
containerName = debugString(true),
)
open val supportedSignaturesOfLightServiceConstructors: List<MethodType> = java.util.List.of(
emptyConstructorMethodType,
coroutineScopeMethodType,
applicationMethodType,
componentManagerMethodType,
)
@Suppress("LeakingThis")
private val serviceContainer = InstanceContainerImpl(
scopeHolder = scopeHolder,
containerName = "${debugString(true)} services",
dynamicInstanceSupport = if (isLightServiceSupported) LightServiceInstanceSupport(
componentManager = this,
onDynamicInstanceRegistration = ::registerDynamicInstanceForUnloading
)
else null,
ordered = false,
)
val serviceContainerInternal: InstanceContainerInternal get() = serviceContainer
private val componentContainer = InstanceContainerImpl(
scopeHolder = scopeHolder,
containerName = "${debugString(true)} components",
dynamicInstanceSupport = null,
ordered = true,
)
private val pluginServicesStore = PluginServicesStore()
private fun registerDynamicInstanceForUnloading(instanceHolder: InstanceHolder) {
val pluginDescriptor = (instanceHolder.instanceClass().classLoader as? PluginAwareClassLoader)?.pluginDescriptor
if (pluginDescriptor is IdeaPluginDescriptor) {
pluginServicesStore.addDynamicService(pluginDescriptor, instanceHolder)
}
}
@Suppress("LeakingThis")
internal val dependencyResolver = ComponentManagerResolver(this)
private val _componentKeyToAdapter = ConcurrentHashMap<Any, ComponentAdapter>()
// String -> ServiceComponentAdapter or LightServiceComponentAdapter
// Class -> MyComponentAdapter
private val componentKeyToAdapter: ConcurrentHashMap<Any, ComponentAdapter>
get() {
check(!useInstanceContainer)
return _componentKeyToAdapter
}
private val _componentAdapters = LinkedHashSetWrapper<MyComponentAdapter>()
private val componentAdapters: LinkedHashSetWrapper<MyComponentAdapter>
get() {
check(!useInstanceContainer)
return _componentAdapters
}
protected val containerState = AtomicReference(ContainerState.PRE_INIT)
protected val containerStateName: String
get() = containerState.get().name
private val extensionArea = ExtensionsAreaImpl(this)
private var messageBus: MessageBusImpl? = null
@Volatile
private var isServicePreloadingCancelled = false
protected open fun debugString(short: Boolean = false): String {
return "${if (short) javaClass.simpleName else javaClass.name}@${System.identityHashCode(this)}"
}
internal val serviceParentDisposable: Disposable = Disposer.newDisposable("services of ${debugString()}")
protected open val isLightServiceSupported: Boolean
get() = parent?.parent == null
protected open val isMessageBusSupported: Boolean = parent?.parent == null
protected open val isComponentSupported: Boolean = true
@Volatile
@JvmField
internal var componentContainerIsReadonly: String? = null
@Suppress("MemberVisibilityCanBePrivate")
fun getCoroutineScope(): CoroutineScope {
if (parent?.parent == null) {
return scopeHolder.containerScope
}
else {
throw RuntimeException("Module doesn't have coroutineScope")
}
}
override val componentStore: IComponentStore
get() = getService(IComponentStore::class.java)!!
internal fun getComponentInstance(componentKey: Any): Any? {
assertComponentsSupported()
if (useInstanceContainer) {
return getComponentInstance2(componentKey)
}
val adapter = componentKeyToAdapter.get(componentKey)
?: if (componentKey is Class<*>) componentKeyToAdapter.get(componentKey.name) else null
return if (adapter == null) parent?.getComponentInstance(componentKey) else adapter.componentInstance
}
private fun getComponentInstance2(componentKey: Any): Any? {
val holder = ignoreDisposal {
when (componentKey) {
is String -> serviceContainer.getInstanceHolder(keyClassName = componentKey)
is Class<*> -> componentContainer.getInstanceHolder(keyClass = componentKey)
?: serviceContainer.getInstanceHolder(keyClass = componentKey)
else -> null
}
}
holder ?: return parent?.getComponentInstance(componentKey)
return holder.getOrCreateInstanceBlocking(componentKey.toString(), keyClass = null)
}
private fun registerAdapter(componentAdapter: ComponentAdapter, pluginDescriptor: PluginDescriptor?) {
if (componentKeyToAdapter.putIfAbsent(componentAdapter.componentKey, componentAdapter) != null) {
val error = "Key ${componentAdapter.componentKey} duplicated"
if (pluginDescriptor == null) {
throw PluginException.createByClass(error, null, componentAdapter.javaClass)
}
else {
throw PluginException(error, null, pluginDescriptor.pluginId)
}
}
}
fun forbidGettingServices(reason: String): AccessToken {
val token = object : AccessToken() {
override fun finish() {
componentContainerIsReadonly = null
}
}
componentContainerIsReadonly = reason
return token
}
private fun checkState() {
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
}
override fun getMessageBus(): MessageBus {
if (containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
val messageBus = messageBus
if (messageBus == null || !isMessageBusSupported) {
LOG.error("Do not use module level message bus")
return getOrCreateMessageBusUnderLock()
}
return messageBus
}
fun getDeprecatedModuleLevelMessageBus(): MessageBus {
if (containerState.get() >= ContainerState.DISPOSE_IN_PROGRESS) {
ProgressManager.checkCanceled()
throw AlreadyDisposedException("Already disposed: $this")
}
return messageBus ?: getOrCreateMessageBusUnderLock()
}
final override fun getExtensionArea(): ExtensionsAreaImpl = extensionArea
fun registerComponents() {
registerComponents(modules = PluginManagerCore.getPluginSet().getEnabledModules(), app = getApplication())
}
open fun registerComponents(modules: List<IdeaPluginDescriptorImpl>,
app: Application?,
precomputedExtensionModel: PrecomputedExtensionModel? = null,
listenerCallbacks: MutableList<in Runnable>? = null) {
val activityNamePrefix = activityNamePrefix()
var map: ConcurrentMap<String, MutableList<ListenerDescriptor>>? = null
val isHeadless = app == null || app.isHeadlessEnvironment
val isUnitTestMode = app?.isUnitTestMode ?: false
var activity = activityNamePrefix?.let { StartUpMeasurer.startActivity("${it}service and ep registration") }
// register services before registering extensions because plugins can access services in their extensions,
// which can be invoked right away if the plugin is loaded dynamically
val extensionPoints = if (precomputedExtensionModel == null) HashMap(extensionArea.nameToPointMap) else null
for (rootModule in modules) {
executeRegisterTask(rootModule) { module ->
val containerDescriptor = getContainerDescriptor(module)
registerServices(containerDescriptor.services, module)
registerComponents(pluginDescriptor = module, containerDescriptor = containerDescriptor, headless = isHeadless)
containerDescriptor.listeners?.let { listeners ->
var m = map
if (m == null) {
m = ConcurrentHashMap()
map = m
}
for (listener in listeners) {
if ((isUnitTestMode && !listener.activeInTestMode) || (isHeadless && !listener.activeInHeadlessMode)) {
continue
}
if (listener.os != null && !isSuitableForOs(listener.os)) {
continue
}
listener.pluginDescriptor = module
m.computeIfAbsent(listener.topicClassName) { ArrayList() }.add(listener)
}
}
if (extensionPoints != null) {
createExtensionPoints(points = containerDescriptor.extensionPoints ?: java.util.List.of(),
componentManager = this,
result = extensionPoints,
pluginDescriptor = module)
}
}
}
if (activity != null) {
activity = activity.endAndStart("${activityNamePrefix}extension registration")
}
if (precomputedExtensionModel == null) {
extensionArea.reset(extensionPoints!!)
for (rootModule in modules) {
executeRegisterTask(rootModule) { module ->
module.registerExtensions(nameToPoint = extensionPoints,
containerDescriptor = getContainerDescriptor(module),
listenerCallbacks = listenerCallbacks)
}
}
}
else {
registerExtensionPointsAndExtensionByPrecomputedModel(precomputedExtensionModel, listenerCallbacks)
}
activity?.end()
// app - phase must be set before getMessageBus()
if (parent == null && !LoadingState.COMPONENTS_REGISTERED.isOccurred /* loading plugin on the fly */) {
LoadingState.setCurrentState(LoadingState.COMPONENTS_REGISTERED)
}
// ensuring that `messageBus` is created, regardless of the lazy listener map state
if (isMessageBusSupported) {
val messageBus = getOrCreateMessageBusUnderLock()
map?.let {
(messageBus as MessageBusEx).setLazyListeners(it)
}
}
}
private fun registerExtensionPointsAndExtensionByPrecomputedModel(precomputedExtensionModel: PrecomputedExtensionModel,
listenerCallbacks: MutableList<in Runnable>?) {
val extensionArea = extensionArea
if (precomputedExtensionModel.extensionPoints.isEmpty()) {
return
}
val result = HashMap<String, ExtensionPointImpl<*>>()
for ((pluginDescriptor, points) in precomputedExtensionModel.extensionPoints) {
createExtensionPoints(points = points, componentManager = this, result = result, pluginDescriptor = pluginDescriptor)
}
assert(extensionArea.nameToPointMap.isEmpty())
extensionArea.reset(result)
for ((name, item) in precomputedExtensionModel.nameToExtensions) {
val point = result.get(name) ?: continue
for ((pluginDescriptor, extensions) in item) {
point.registerExtensions(descriptors = extensions, pluginDescriptor = pluginDescriptor, listenerCallbacks = listenerCallbacks)
}
}
}
private fun registerComponents(pluginDescriptor: IdeaPluginDescriptor, containerDescriptor: ContainerDescriptor, headless: Boolean) {
if (useInstanceContainer) {
registerComponents2(pluginDescriptor, containerDescriptor, headless)
return
}
for (descriptor in (containerDescriptor.components ?: java.util.List.of())) {
var implementationClassName = descriptor.implementationClass
if (headless && descriptor.headlessImplementationClass != null) {
if (descriptor.headlessImplementationClass.isEmpty()) {
continue
}
implementationClassName = descriptor.headlessImplementationClass
}
if (descriptor.os != null && !isSuitableForOs(descriptor.os)) {
continue
}
if (!isComponentSuitable(descriptor)) {
continue
}
val componentClassName = descriptor.interfaceClass ?: descriptor.implementationClass!!
try {
registerComponent(
interfaceClassName = componentClassName,
implementationClassName = implementationClassName,
config = descriptor,
pluginDescriptor = pluginDescriptor,
)
}
catch (e: StartupAbortedException) {
throw e
}
catch (e: CancellationException) {
throw e
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: PluginException) {
throw e
}
catch (e: Throwable) {
throw PluginException("Fatal error initializing '$componentClassName'", e, pluginDescriptor.pluginId)
}
}
}
private fun registerComponents2(pluginDescriptor: IdeaPluginDescriptor, containerDescriptor: ContainerDescriptor, headless: Boolean) {
try {
registerComponents2Inner(pluginDescriptor, containerDescriptor, headless)
}
catch (pce: CancellationException) {
ProgressManager.checkCanceled()
throw PluginException(pce, pluginDescriptor.pluginId)
}
catch (t: Throwable) {
throw PluginException(t, pluginDescriptor.pluginId)
}
}
private fun registerComponents2Inner(pluginDescriptor: IdeaPluginDescriptor,
containerDescriptor: ContainerDescriptor,
headless: Boolean) {
val components = containerDescriptor.components
if (components.isNullOrEmpty()) {
return
}
val pluginClassLoader = pluginDescriptor.pluginClassLoader
val registrationScope = if (pluginClassLoader is PluginAwareClassLoader) pluginClassLoader.pluginCoroutineScope else null
val registrar = componentContainer.startRegistration(registrationScope)
for (descriptor in components) {
if (descriptor.os != null && !isSuitableForOs(descriptor.os)) {
continue
}
if (!isComponentSuitable(descriptor)) {
continue
}
val implementationClassName = if (headless && descriptor.headlessImplementationClass != null) {
if (descriptor.headlessImplementationClass.isEmpty()) {
continue
}
descriptor.headlessImplementationClass
}
else {
descriptor.implementationClass
}
val keyClassName = descriptor.interfaceClass
?: descriptor.implementationClass!!
val keyClass = pluginDescriptor.classLoader.loadClass(keyClassName)
registrar.registerInitializer(
keyClassName = keyClassName,
ComponentDescriptorInstanceInitializer(
this,
pluginDescriptor,
keyClass,
implementationClassName
),
override = descriptor.overrides,
)
}
registrar.complete()
}
fun createInitOldComponentsTask(): (suspend () -> Unit)? {
if (useInstanceContainer) {
return createInitOldComponentsTask2()
}
if (componentAdapters.getImmutableSet().isEmpty()) {
containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED)
return null
}
return {
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstance<Any>(this, keyClass = null)
}
containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED)
}
}
private fun createInitOldComponentsTask2(): (suspend () -> Unit)? {
if (componentContainer.instanceHolders().isEmpty()) {
containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED)
return null
}
return {
componentContainer.preloadAllInstances()
containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED)
}
}
@Suppress("DuplicatedCode")
@Deprecated(message = "Use createComponentsNonBlocking")
protected fun createComponents() {
LOG.assertTrue(containerState.get() == ContainerState.PRE_INIT)
val activity = when (val activityNamePrefix = activityNamePrefix()) {
null -> null
else -> StartUpMeasurer.startActivity("$activityNamePrefix${StartUpMeasurer.Activities.CREATE_COMPONENTS_SUFFIX}")
}
if (useInstanceContainer) {
runBlockingInitialization {
componentContainer.preloadAllInstances()
}
}
else {
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstance<Any>(this, keyClass = null)
}
}
activity?.end()
LOG.assertTrue(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED))
}
@Suppress("DuplicatedCode")
@Internal
suspend fun createComponentsNonBlocking() {
LOG.assertTrue(containerState.get() == ContainerState.PRE_INIT)
val activity = when (val activityNamePrefix = activityNamePrefix()) {
null -> null
else -> StartUpMeasurer.startActivity("$activityNamePrefix${StartUpMeasurer.Activities.CREATE_COMPONENTS_SUFFIX}")
}
if (useInstanceContainer) {
componentContainer.preloadAllInstances()
}
else {
for (componentAdapter in componentAdapters.getImmutableSet()) {
componentAdapter.getInstanceAsync<Any>(this, keyClass = null)
}
}
activity?.end()
LOG.assertTrue(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED))
}
@TestOnly
fun registerComponentImplementation(key: Class<*>, implementation: Class<*>, shouldBeRegistered: Boolean) {
if (useInstanceContainer) {
registerComponentImplementation2(key, implementation, shouldBeRegistered)
return
}
checkState()
val oldAdapter = componentKeyToAdapter.remove(key) as MyComponentAdapter?
if (shouldBeRegistered) {
LOG.assertTrue(oldAdapter != null)
}
val pluginDescriptor = oldAdapter?.pluginDescriptor ?: DefaultPluginDescriptor("test registerComponentImplementation")
val newAdapter = MyComponentAdapter(componentKey = key,
implementationClassName = implementation.name,
pluginDescriptor = pluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(),
implementationClass = implementation)
componentKeyToAdapter.put(key, newAdapter)
if (oldAdapter == null) {
componentAdapters.add(newAdapter)
}
else {
componentAdapters.replace(oldAdapter, newAdapter)
}
}
private fun registerComponentImplementation2(key: Class<*>, implementation: Class<*>, shouldBeRegistered: Boolean) {
val oldHolder = checkState {
componentContainer.getInstanceHolder(keyClass = key)
}
val oldClassLoader = oldHolder?.instanceClass()?.classLoader as? PluginAwareClassLoader
val pluginId = oldClassLoader?.pluginId ?: PluginId.getId("test registerComponentImplementation")
componentContainer.registerInitializer(
keyClass = key,
initializer = ComponentClassInstanceInitializer(this, pluginId, key, implementation),
override = shouldBeRegistered,
)
}
@TestOnly
fun <T : Any> replaceComponentInstance(componentKey: Class<T>, componentImplementation: T, parentDisposable: Disposable?) {
if (useInstanceContainer) {
replaceComponentInstance2(componentKey, componentImplementation, parentDisposable)
return
}
checkState()
val oldAdapter = componentKeyToAdapter.get(componentKey) as MyComponentAdapter
val implClass = componentImplementation::class.java
val newAdapter = MyComponentAdapter(componentKey = componentKey,
implementationClassName = implClass.name,
pluginDescriptor = oldAdapter.pluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(value = componentImplementation),
implementationClass = implClass)
componentKeyToAdapter.put(componentKey, newAdapter)
componentAdapters.replace(oldAdapter, newAdapter)
if (parentDisposable != null) {
Disposer.register(parentDisposable) {
@Suppress("DEPRECATION")
if (componentImplementation is Disposable && !Disposer.isDisposed(componentImplementation)) {
Disposer.dispose(componentImplementation)
}
componentKeyToAdapter.put(componentKey, oldAdapter)
componentAdapters.replace(newAdapter, oldAdapter)
}
}
}
private fun <T : Any> replaceComponentInstance2(
componentKey: Class<T>,
componentImplementation: T,
parentDisposable: Disposable?,
) {
val unregisterHandle = componentContainer.replaceInstance(
keyClass = componentKey,
instance = componentImplementation,
)
if (parentDisposable != null) {
Disposer.register(parentDisposable) {
@Suppress("DEPRECATION")
if (componentImplementation is Disposable && !Disposer.isDisposed(componentImplementation)) {
Disposer.dispose(componentImplementation)
}
unregisterHandle.unregister()
}
}
}
private fun registerComponent(
interfaceClassName: String,
implementationClassName: String?,
config: ComponentConfig,
pluginDescriptor: IdeaPluginDescriptor,
) {
val interfaceClass = pluginDescriptor.classLoader.loadClass(interfaceClassName)
val options = config.options
if (config.overrides) {
unregisterComponent(interfaceClass) ?: throw PluginException("$config does not override anything", pluginDescriptor.pluginId)
}
// implementationClass == null means we want to unregister this component
if (implementationClassName == null) {
return
}
if (options != null && java.lang.Boolean.parseBoolean(options.get("workspace")) &&
!badWorkspaceComponents.contains(implementationClassName)) {
LOG.error("workspace option is deprecated (implementationClass=$implementationClassName)")
}
val adapter = MyComponentAdapter(componentKey = interfaceClass,
implementationClassName = implementationClassName,
pluginDescriptor = pluginDescriptor,
componentManager = this,
deferred = CompletableDeferred(),
implementationClass = null)
registerAdapter(adapter, adapter.pluginDescriptor)
componentAdapters.add(adapter)
}
open fun getApplication(): Application? {
return if (parent == null || this is Application) this as Application else parent.getApplication()
}
protected fun registerServices(services: List<ServiceDescriptor>, pluginDescriptor: IdeaPluginDescriptor) {
if (useInstanceContainer) {
registerServices2(pluginDescriptor, services)
return
}
checkState()
val app = getApplication()!!
for (descriptor in services) {
if (!isServiceSuitable(descriptor) || descriptor.os != null && !isSuitableForOs(descriptor.os)) {
continue
}
// Allow to re-define service implementations in plugins.
// Empty serviceImplementation means we want unregistering service.
// empty serviceImplementation means we want unregistering service
val implementation = when {
descriptor.testServiceImplementation != null && app.isUnitTestMode -> descriptor.testServiceImplementation
descriptor.headlessImplementation != null && app.isHeadlessEnvironment -> descriptor.headlessImplementation
else -> descriptor.serviceImplementation
}
val key = descriptor.serviceInterface ?: implementation
if (descriptor.overrides && componentKeyToAdapter.remove(key) == null) {
throw PluginException("Service $key doesn't override anything", pluginDescriptor.pluginId)
}
if (implementation != null) {
val componentAdapter = ServiceComponentAdapter(descriptor, pluginDescriptor, this)
val existingAdapter = componentKeyToAdapter.putIfAbsent(key, componentAdapter)
if (existingAdapter != null) {
throw PluginException("Key $key duplicated; existingAdapter: $existingAdapter; " +
"descriptor=${getServiceImplementation(descriptor, this)}, " +
" app=$app, current plugin=${pluginDescriptor.pluginId}", pluginDescriptor.pluginId)
}
}
}
}
private fun registerServices2(pluginDescriptor: IdeaPluginDescriptor, services: List<ServiceDescriptor>) {
LOG.trace { "${pluginDescriptor.pluginId} - registering services" }
try {
registerServices2Inner(services, pluginDescriptor)
}
catch (pce: CancellationException) {
ProgressManager.checkCanceled()
throw PluginException(pce, pluginDescriptor.pluginId)
}
catch (t: Throwable) {
throw PluginException(t, pluginDescriptor.pluginId)
}
finally {
LOG.trace { "${pluginDescriptor.pluginId} - end registering services" }
}
}
private fun registerServices2Inner(services: List<ServiceDescriptor>, pluginDescriptor: IdeaPluginDescriptor) {
if (services.isEmpty()) {
return
}
val pluginClassLoader = pluginDescriptor.pluginClassLoader
val registrationScope = if (pluginClassLoader is PluginAwareClassLoader) {
pluginClassLoader.pluginCoroutineScope
}
else {
null
}
val keyClassNames = ArrayList<String>()
val registrar = serviceContainer.startRegistration(registrationScope)
val app = getApplication()!!
for (descriptor in services) {
if (!isServiceSuitable(descriptor) || descriptor.os != null && !isSuitableForOs(descriptor.os)) {
continue
}
// Allow to re-define service implementations in plugins.
// Empty serviceImplementation means we want unregistering service.
val implementation = when {
descriptor.testServiceImplementation != null && app.isUnitTestMode -> descriptor.testServiceImplementation
descriptor.headlessImplementation != null && app.isHeadlessEnvironment -> descriptor.headlessImplementation
else -> descriptor.serviceImplementation
}
val key = descriptor.serviceInterface
?: implementation
if (descriptor.overrides) {
registrar.overrideInitializer(
keyClassName = key,
initializer = if (implementation == null) {
null
}
else {
keyClassNames.add(key)
ServiceDescriptorInstanceInitializer(
keyClassName = key,
instanceClassName = implementation,
componentManager = this,
pluginDescriptor,
serviceDescriptor = descriptor,
)
}
)
}
else {
keyClassNames.add(key)
registrar.registerInitializer(
keyClassName = key,
initializer = ServiceDescriptorInstanceInitializer(
keyClassName = key,
instanceClassName = checkNotNull(implementation),
componentManager = this,
pluginDescriptor,
serviceDescriptor = descriptor,
),
)
}
}
val handle: UnregisterHandle? = registrar.complete()
if (handle != null) {
pluginServicesStore.putServicesUnregisterHandle(pluginDescriptor, handle)
}
}
internal fun initializeComponent(component: Any, serviceDescriptor: ServiceDescriptor?, pluginId: PluginId?) {
if (serviceDescriptor == null || !isPreInitialized(component)) {
if (LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred) {
componentStore.initComponent(component, serviceDescriptor, pluginId)
}
else {
check(component !is PersistentStateComponent<*> || getApplication()!!.isUnitTestMode)
}
}
}
protected open fun isPreInitialized(component: Any): Boolean {
return component is PathMacroManager || component is IComponentStore || component is MessageBusFactory
}
protected abstract fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor
@Deprecated("Deprecated in interface")
final override fun <T : Any> getComponent(key: Class<T>): T? {
assertComponentsSupported()
checkState()
val adapter = getComponentAdapter(key)
if (adapter == null) {
checkCanceledIfNotInClassInit()
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
throwAlreadyDisposedError(key.name, this)
}
return null
}
if (adapter is ServiceComponentAdapter) {
LOG.error("$key it is a service, use getService instead of getComponent")
}
when (adapter) {
is BaseComponentAdapter -> {
check(!useInstanceContainer)
if (parent != null && adapter.componentManager !== this) {
LOG.error("getComponent must be called on appropriate container (current: $this, expected: ${adapter.componentManager})")
}
if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
adapter.throwAlreadyDisposedError(this)
}
return adapter.getInstance(adapter.componentManager, key)
}
is HolderAdapter -> {
check(useInstanceContainer)
// TODO asserts
val holder = adapter.holder
@Suppress("UNCHECKED_CAST")
return holder.getOrCreateInstanceBlocking(key.name, key) as T
}
else -> {
return null
}
}
}
@RequiresBlockingContext
final override fun <T : Any> getService(serviceClass: Class<T>): T? {
return doGetService(serviceClass, true) ?: return postGetService(serviceClass, createIfNeeded = true)
}
final override suspend fun <T : Any> getServiceAsync(keyClass: Class<T>): T {
if (useInstanceContainer) {
return serviceContainer.instance(keyClass)
}
val result = getServiceAsyncIfDefined(keyClass)
if (result == null && isLightServiceSupported && isLightService(keyClass)) {
return getOrCreateLightServiceAdapter(keyClass).getInstanceAsync(componentManager = this, keyClass = keyClass)
}
return result ?: throw RuntimeException("service is not defined for $keyClass")
}
override suspend fun <T : Any> getServiceAsyncIfDefined(keyClass: Class<T>): T? {
if (useInstanceContainer) {
val holder = serviceContainer.getInstanceHolder(keyClass) ?: return null
@Suppress("UNCHECKED_CAST")
return holder.getInstance(keyClass) as T