summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/notification/impl/NotificationsToolWindow.kt
blob: b9bce711ede214f2e64c9b1437f9f1f414d10b01 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.notification.impl

import com.intellij.UtilBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.ui.LafManagerListener
import com.intellij.idea.ActionsBundle
import com.intellij.notification.ActionCenter
import com.intellij.notification.EventLog
import com.intellij.notification.LogModel
import com.intellij.notification.Notification
import com.intellij.notification.impl.ui.NotificationsUtil
import com.intellij.notification.impl.widget.IdeNotificationArea
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Divider
import com.intellij.openapi.ui.NullableComponent
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.Clock
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.*
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBOptionButton
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.Alarm
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.ui.*
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.event.*
import java.util.*
import java.util.function.Consumer
import javax.accessibility.AccessibleContext
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.HyperlinkEvent
import javax.swing.event.PopupMenuEvent
import javax.swing.text.JTextComponent
import kotlin.streams.toList

internal class NotificationsToolWindowFactory : ToolWindowFactory, DumbAware {
  companion object {
    const val ID = "Notifications"

    internal val myModel = ApplicationNotificationModel()

    fun addNotification(project: Project?, notification: Notification) {
      if (ActionCenter.isEnabled() && notification.canShowFor(project)) {
        myModel.addNotification(project, notification)
      }
    }

    fun expire(notification: Notification) {
      myModel.expire(notification)
    }

    fun expireAll() {
      myModel.expireAll()
    }

    fun getStateNotifications(project: Project) = myModel.getStateNotifications(project)

    fun getNotifications(project: Project?) = myModel.getNotifications(project)
  }

  override fun isApplicable(project: Project) = ActionCenter.isEnabled()

  override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
    NotificationContent(project, toolWindow)
  }
}

internal class NotificationContent(val project: Project,
                                   private val toolWindow: ToolWindow) : Disposable, ToolWindowManagerListener {
  private val myMainPanel = JBPanelWithEmptyText(BorderLayout())

  private val myNotifications = ArrayList<Notification>()
  private val myIconNotifications = ArrayList<Notification>()

  private val suggestions: NotificationGroupComponent
  private val timeline: NotificationGroupComponent
  private val searchController: SearchController

  private val singleSelectionHandler = SingleTextSelectionHandler()

  private var myVisible = true

  private val mySearchUpdateAlarm = Alarm()

  init {
    myMainPanel.background = NotificationComponent.BG_COLOR
    setEmptyState()
    handleFocus()

    suggestions = NotificationGroupComponent(this, true, project)
    timeline = NotificationGroupComponent(this, false, project)
    searchController = SearchController(this, suggestions, timeline)

    myMainPanel.add(createSearchComponent(toolWindow), BorderLayout.NORTH)

    val splitter = MySplitter()
    splitter.firstComponent = suggestions
    splitter.secondComponent = timeline
    myMainPanel.add(splitter)

    suggestions.setRemoveCallback(Consumer(::remove))
    timeline.setClearCallback(::clear)

    Disposer.register(toolWindow.disposable, this)

    val content = ContentFactory.SERVICE.getInstance().createContent(myMainPanel, "", false)
    content.preferredFocusableComponent = myMainPanel

    val contentManager = toolWindow.contentManager
    contentManager.addContent(content)
    contentManager.setSelectedContent(content)

    project.messageBus.connect(toolWindow.disposable).subscribe(ToolWindowManagerListener.TOPIC, this)

    ApplicationManager.getApplication().messageBus.connect(toolWindow.disposable).subscribe(LafManagerListener.TOPIC, LafManagerListener {
      suggestions.updateLaf()
      timeline.updateLaf()
    })

    val newNotifications = ArrayList<Notification>()
    NotificationsToolWindowFactory.myModel.registerAndGetInitNotifications(this, newNotifications)
    for (notification in newNotifications) {
      add(notification)
    }
  }

  private fun createSearchComponent(toolWindow: ToolWindow): SearchTextField {
    val searchField = object : SearchTextField() {
      override fun updateUI() {
        super.updateUI()
        textEditor?.border = null
      }

      override fun preprocessEventForTextField(event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.VK_ESCAPE && event.id == KeyEvent.KEY_PRESSED) {
          isVisible = false
          searchController.cancelSearch()
          return true
        }
        return super.preprocessEventForTextField(event)
      }
    }
    searchField.textEditor.border = null
    searchField.border = JBUI.Borders.customLineBottom(JBColor.border())
    searchField.isVisible = false

    searchController.searchField = searchField

    searchField.addDocumentListener(object : DocumentAdapter() {
      override fun textChanged(e: DocumentEvent) {
        mySearchUpdateAlarm.cancelAllRequests()
        mySearchUpdateAlarm.addRequest(searchController::doSearch, 100, ModalityState.stateForComponent(searchField))
      }
    })

    val gearAction = object : DumbAwareAction() {
      override fun actionPerformed(e: AnActionEvent) {
        searchField.isVisible = true
        searchField.selectText()
        searchField.requestFocus()
        searchController.startSearch()
      }
    }

    val findAction = ActionManager.getInstance().getAction(IdeActions.ACTION_FIND)
    if (findAction == null) {
      gearAction.templatePresentation.text = ActionsBundle.actionText(IdeActions.ACTION_FIND)
    }
    else {
      gearAction.copyFrom(findAction)
      gearAction.registerCustomShortcutSet(findAction.shortcutSet, myMainPanel)
    }

    (toolWindow as ToolWindowEx).setAdditionalGearActions(DefaultActionGroup(gearAction))

    return searchField
  }

  fun setEmptyState() {
    myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.first.line"))
    @Suppress("DialogTitleCapitalization")
    myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.second.line"))
  }

  fun clearEmptyState() {
    myMainPanel.emptyText.clear()
  }

  private fun handleFocus() {
    val listener = AWTEventListener {
      if (it is MouseEvent && it.id == MouseEvent.MOUSE_PRESSED && !toolWindow.isActive && UIUtil.isAncestor(myMainPanel, it.component)) {
        it.component.requestFocus()
      }
    }
    Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.MOUSE_EVENT_MASK)
    Disposer.register(toolWindow.disposable, Disposable {
      Toolkit.getDefaultToolkit().removeAWTEventListener(listener)
    })
  }

  fun add(notification: Notification) {
    if (!NotificationsConfigurationImpl.getSettings(notification.groupId).isShouldLog) {
      return
    }
    if (notification.isSuggestionType) {
      suggestions.add(notification, singleSelectionHandler)
    }
    else {
      timeline.add(notification, singleSelectionHandler)
    }
    myNotifications.add(notification)
    myIconNotifications.add(notification)
    searchController.update()
    setStatusMessage(notification)
    updateIcon()
  }

  fun getStateNotifications() = ArrayList(myIconNotifications)

  fun getNotifications() = ArrayList(myNotifications)

  fun expire(notification: Notification?) {
    if (notification == null) {
      val notifications = ArrayList(myNotifications)

      myNotifications.clear()
      myIconNotifications.clear()
      suggestions.expireAll()
      timeline.expireAll()
      searchController.update()
      setStatusMessage(null)
      updateIcon()

      for (n in notifications) {
        n.expire()
      }
    }
    else {
      remove(notification)
    }
  }

  private fun remove(notification: Notification) {
    if (notification.isSuggestionType) {
      suggestions.remove(notification)
    }
    else {
      timeline.remove(notification)
    }
    myNotifications.remove(notification)
    myIconNotifications.remove(notification)
    searchController.update()
    setStatusMessage()
    updateIcon()
  }

  private fun clear(notifications: List<Notification>) {
    myNotifications.removeAll(notifications)
    myIconNotifications.removeAll(notifications)
    searchController.update()
    setStatusMessage()
    updateIcon()
  }

  override fun stateChanged(toolWindowManager: ToolWindowManager) {
    val visible = toolWindow.isVisible
    if (myVisible != visible) {
      myVisible = visible
      if (visible) {
        val ideFrame = WindowManager.getInstance().getIdeFrame(project)
        val balloonLayout = ideFrame!!.balloonLayout as BalloonLayoutImpl
        balloonLayout.closeAll()

        suggestions.updateComponents()
        timeline.updateComponents()
      }
      else {
        suggestions.clearNewState()
        timeline.clearNewState()
        myIconNotifications.clear()
        updateIcon()
      }
    }
  }

  private fun updateIcon() {
    toolWindow.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(myIconNotifications))
    LogModel.fireModelChanged()
  }

  private fun setStatusMessage() {
    setStatusMessage(myNotifications.findLast { it.isImportant || it.isImportantSuggestion })
  }

  private fun setStatusMessage(notification: Notification?) {
    EventLog.getLogModel(project).setStatusMessage(notification)
  }

  override fun dispose() {
    NotificationsToolWindowFactory.myModel.unregister(this)
    Disposer.dispose(mySearchUpdateAlarm)
  }

  fun fullRepaint() {
    myMainPanel.doLayout()
    myMainPanel.revalidate()
    myMainPanel.repaint()
  }
}

private class MySplitter : OnePixelSplitter(true, .5f) {
  override fun createDivider(): Divider {
    return object : OnePixelDivider(true, this) {
      override fun setVisible(aFlag: Boolean) {
        super.setVisible(aFlag)
        setResizeEnabled(aFlag)
        if (!aFlag) {
          setBounds(0, 0, 0, 0)
        }
      }

      override fun setBackground(bg: Color?) {
        super.setBackground(JBColor.border())
      }
    }
  }
}

private fun JComponent.mediumFontFunction() {
  font = JBFont.medium()
  val f: (JComponent) -> Unit = {
    it.font = JBFont.medium()
  }
  putClientProperty(NotificationGroupComponent.FONT_KEY, f)
}

private fun JComponent.smallFontFunction() {
  font = JBFont.small()
  val f: (JComponent) -> Unit = {
    it.font = JBFont.small()
  }
  putClientProperty(NotificationGroupComponent.FONT_KEY, f)
}

private class SearchController(private val mainContent: NotificationContent,
                               private val suggestions: NotificationGroupComponent,
                               private val timeline: NotificationGroupComponent) {
  lateinit var searchField: SearchTextField

  fun startSearch() {
    mainContent.clearEmptyState()

    if (searchField.text.isNotEmpty()) {
      doSearch()
    }
  }

  fun doSearch() {
    val query = searchField.text

    if (query.isEmpty()) {
      searchField.textEditor.background = UIUtil.getTextFieldBackground()
      clearSearch()
      return
    }

    var result = false
    val function: (NotificationComponent) -> Unit = {
      if (it.applySearchQuery(query)) {
        result = true
      }
    }
    suggestions.iterateComponents(function)
    timeline.iterateComponents(function)
    searchField.textEditor.background = if (result) UIUtil.getTextFieldBackground() else LightColors.RED
    mainContent.fullRepaint()
  }

  fun update() {
    if (searchField.isVisible && searchField.text.isNotEmpty()) {
      doSearch()
    }
  }

  fun cancelSearch() {
    mainContent.setEmptyState()
    clearSearch()
  }

  private fun clearSearch() {
    val function: (NotificationComponent) -> Unit = { it.applySearchQuery(null) }
    suggestions.iterateComponents(function)
    timeline.iterateComponents(function)
    mainContent.fullRepaint()
  }
}

private class NotificationGroupComponent(private val myMainContent: NotificationContent,
                                         private val mySuggestionType: Boolean,
                                         private val myProject: Project) :
  JPanel(BorderLayout()), NullableComponent {

  companion object {
    const val FONT_KEY = "FontFunction"
  }

  private val myTitle = JBLabel(
    IdeBundle.message(if (mySuggestionType) "notifications.toolwindow.suggestions" else "notifications.toolwindow.timeline"))

  private val myList = JPanel(VerticalLayout(JBUI.scale(10)))
  private val myScrollPane = object : JBScrollPane(myList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                   ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) {
    override fun setupCorners() {
      super.setupCorners()
      border = null
    }

    override fun updateUI() {
      super.updateUI()
      border = null
    }
  }

  private var myScrollValue = 0

  private val myEventHandler = ComponentEventHandler()

  private val myTimeComponents = ArrayList<JLabel>()
  private val myTimeAlarm = Alarm(myProject)

  private lateinit var myClearCallback: (List<Notification>) -> Unit
  private lateinit var myRemoveCallback: Consumer<Notification>

  init {
    background = NotificationComponent.BG_COLOR

    val mainPanel = JPanel(BorderLayout(0, JBUI.scale(8)))
    mainPanel.isOpaque = false
    mainPanel.border = JBUI.Borders.empty(8, 8, 0, 0)
    add(mainPanel)

    myTitle.mediumFontFunction()
    myTitle.foreground = NotificationComponent.INFO_COLOR

    if (mySuggestionType) {
      myTitle.border = JBUI.Borders.emptyLeft(10)
      mainPanel.add(myTitle, BorderLayout.NORTH)
    }
    else {
      val panel = JPanel(BorderLayout())
      panel.isOpaque = false
      panel.border = JBUI.Borders.emptyLeft(10)

      panel.add(myTitle, BorderLayout.WEST)

      val clearAll = LinkLabel(IdeBundle.message("notifications.toolwindow.timeline.clear.all"), null) { _: LinkLabel<Unit>, _: Unit? ->
        clearAll()
      }
      clearAll.mediumFontFunction()
      clearAll.border = JBUI.Borders.emptyRight(20)
      panel.add(clearAll, BorderLayout.EAST)

      mainPanel.add(panel, BorderLayout.NORTH)
    }

    myList.isOpaque = true
    myList.background = NotificationComponent.BG_COLOR
    myList.border = JBUI.Borders.emptyRight(10)

    myScrollPane.border = null
    mainPanel.add(myScrollPane)

    myScrollPane.verticalScrollBar.addAdjustmentListener {
      val value = it.value
      if (myScrollValue == 0 && value > 0 || myScrollValue > 0 && value == 0) {
        myScrollValue = value
        repaint()
      }
      else {
        myScrollValue = value
      }
    }

    myEventHandler.add(this)
  }

  fun updateLaf() {
    updateComponents()
    iterateComponents { it.updateLaf() }
  }

  override fun paintComponent(g: Graphics) {
    super.paintComponent(g)
    if (myScrollValue > 0) {
      g.color = JBColor.border()
      val y = myScrollPane.y - 1
      g.drawLine(0, y, width, y)
    }
  }

  fun add(notification: Notification, singleSelectionHandler: SingleTextSelectionHandler) {
    val component = NotificationComponent(myProject, notification, myTimeComponents, singleSelectionHandler)
    component.setNew(true)

    myList.add(component, 0)
    updateLayout()
    myEventHandler.add(component)

    updateContent()

    if (mySuggestionType) {
      component.setDoNotAskHandler { forProject ->
        component.myNotificationWrapper.notification!!
          .setDoNotAskFor(if (forProject) myProject else null)
          .also { myRemoveCallback.accept(it) }
          .hideBalloon()
      }

      component.setRemoveCallback(myRemoveCallback)
    }
  }

  private fun updateLayout() {
    val layout = myList.layout
    iterateComponents { component ->
      layout.removeLayoutComponent(component)
      layout.addLayoutComponent(null, component)
    }
  }

  fun setRemoveCallback(callback: Consumer<Notification>) {
    myRemoveCallback = callback
  }

  fun remove(notification: Notification) {
    val count = myList.componentCount
    for (i in 0 until count) {
      val component = myList.getComponent(i) as NotificationComponent
      if (component.myNotificationWrapper.notification === notification) {
        if (notification.isSuggestionType) {
          component.removeFromParent()
          myList.remove(i)
        }
        else {
          component.expire()
        }
        break
      }
    }
    updateContent()
  }

  fun setClearCallback(callback: (List<Notification>) -> Unit) {
    myClearCallback = callback
  }

  private fun clearAll() {
    val ideFrame = WindowManager.getInstance().getIdeFrame(myProject)
    val balloonLayout = ideFrame!!.balloonLayout as BalloonLayoutImpl
    balloonLayout.closeAll()

    val notifications = ArrayList<Notification>()
    iterateComponents {
      val notification = it.myNotificationWrapper.notification
      if (notification != null) {
        notifications.add(notification)
      }
    }
    clear()
    myClearCallback.invoke(notifications)
  }

  fun expireAll() {
    if (mySuggestionType) {
      clear()
    }
    else {
      iterateComponents {
        if (it.myNotificationWrapper.notification != null) {
          it.expire()
        }
      }
      updateContent()
    }
  }

  fun clear() {
    iterateComponents { it.removeFromParent() }
    myList.removeAll()
    updateContent()
  }

  fun clearNewState() {
    iterateComponents { it.setNew(false) }
  }

  fun updateComponents() {
    UIUtil.uiTraverser(this).filter(JComponent::class.java).forEach {
      val value = it.getClientProperty(FONT_KEY)
      if (value != null) {
        (value as (JComponent) -> Unit).invoke(it)
      }
    }
    myMainContent.fullRepaint()
  }

  inline fun iterateComponents(f: (NotificationComponent) -> Unit) {
    val count = myList.componentCount
    for (i in 0 until count) {
      f.invoke(myList.getComponent(i) as NotificationComponent)
    }
  }

  private fun updateContent() {
    if (!mySuggestionType && !myTimeAlarm.isDisposed) {
      myTimeAlarm.cancelAllRequests()

      object : Runnable {
        override fun run() {
          for (timeComponent in myTimeComponents) {
            timeComponent.text = formatPrettyDateTime(timeComponent.getClientProperty(NotificationComponent.TIME_KEY) as Long)
          }

          if (myTimeComponents.isNotEmpty() && !myTimeAlarm.isDisposed) {
            myTimeAlarm.addRequest(this, 30000)
          }
        }
      }.run()
    }

    myMainContent.fullRepaint()
  }

  private fun formatPrettyDateTime(time: Long): @NlsSafe String {
    val c = Calendar.getInstance()

    c.timeInMillis = Clock.getTime()
    val currentYear = c[Calendar.YEAR]
    val currentDayOfYear = c[Calendar.DAY_OF_YEAR]

    c.timeInMillis = time
    val year = c[Calendar.YEAR]
    val dayOfYear = c[Calendar.DAY_OF_YEAR]

    if (currentYear == year && currentDayOfYear == dayOfYear) {
      return DateFormatUtil.formatTime(time)
    }

    val isYesterdayOnPreviousYear = currentYear == year + 1 && currentDayOfYear == 1 && dayOfYear == c.getActualMaximum(
      Calendar.DAY_OF_YEAR)
    val isYesterday = isYesterdayOnPreviousYear || currentYear == year && currentDayOfYear == dayOfYear + 1
    if (isYesterday) {
      return UtilBundle.message("date.format.yesterday")
    }

    return DateFormatUtil.formatDate(time)
  }

  override fun isVisible(): Boolean {
    if (super.isVisible()) {
      val count = myList.componentCount
      for (i in 0 until count) {
        if (myList.getComponent(i).isVisible) {
          return true
        }
      }
    }
    return false
  }

  override fun isNull(): Boolean = !isVisible
}

private class NotificationComponent(val project: Project,
                                    notification: Notification,
                                    timeComponents: ArrayList<JLabel>,
                                    val singleSelectionHandler: SingleTextSelectionHandler) : JPanel() {

  companion object {
    val BG_COLOR = UIUtil.getListBackground()
    val INFO_COLOR = JBColor.namedColor("Label.infoForeground", JBColor(Gray.x80, Gray.x8C))
    internal const val NEW_COLOR_NAME = "NotificationsToolwindow.newNotification.background"
    internal val NEW_DEFAULT_COLOR = JBColor(0xE6EEF7, 0x45494A)
    val NEW_COLOR = JBColor.namedColor(NEW_COLOR_NAME, NEW_DEFAULT_COLOR)
    val NEW_HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.newNotification.hoverBackground", JBColor(0xE6EEF7, 0x45494A))
    val HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.Notification.hoverBackground", BG_COLOR)
    const val TIME_KEY = "TimestampKey"
  }

  val myNotificationWrapper = NotificationWrapper(notification)
  private var myIsNew = false
  private var myHoverState = false
  private val myMoreButton: Component?
  private var myMorePopupVisible = false
  private var myRoundColor = BG_COLOR
  private lateinit var myDoNotAskHandler: (Boolean) -> Unit
  private lateinit var myRemoveCallback: Consumer<Notification>
  private var myLafUpdater: Runnable? = null

  private var myMorePopup: JBPopup? = null
  var myMoreAwtPopup: JPopupMenu? = null
  var myDropDownPopup: JPopupMenu? = null

  init {
    isOpaque = true
    background = BG_COLOR
    border = JBUI.Borders.empty(10, 10, 10, 0)

    layout = object : BorderLayout(JBUI.scale(7), 0) {
      private var myEastComponent: Component? = null

      override fun addLayoutComponent(name: String?, comp: Component) {
        if (EAST == name) {
          myEastComponent = comp
        }
        else {
          super.addLayoutComponent(name, comp)
        }
      }

      override fun layoutContainer(target: Container) {
        super.layoutContainer(target)
        if (myEastComponent != null && myEastComponent!!.isVisible) {
          val insets = target.insets
          val height = target.height - insets.bottom - insets.top
          val component = myEastComponent!!
          component.setSize(component.width, height)
          val d = component.preferredSize
          component.setBounds(target.width - insets.right - d.width, insets.top, d.width, height)
        }
      }
    }

    val iconPanel = JPanel(BorderLayout())
    iconPanel.isOpaque = false
    iconPanel.add(JBLabel(NotificationsUtil.getIcon(notification)), BorderLayout.NORTH)
    add(iconPanel, BorderLayout.WEST)

    val centerPanel = JPanel(VerticalLayout(JBUI.scale(8)))
    centerPanel.isOpaque = false

    var titlePanel: JPanel? = null

    if (notification.hasTitle()) {
      val titleContent = NotificationsUtil.buildHtml(notification, null, false, null, null)
      val title = object : JBLabel(titleContent) {
        override fun updateUI() {
          val oldEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java)
          if (oldEditor != null) {
            singleSelectionHandler.remove(oldEditor)
          }

          super.updateUI()

          val newEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java)
          if (newEditor != null) {
            singleSelectionHandler.add(newEditor, true)
          }
        }
      }

      try {
        title.setCopyable(true)
      }
      catch (_: Exception) {
      }

      NotificationsManagerImpl.setTextAccessibleName(title, titleContent)

      val editor = UIUtil.findComponentOfType(title, JEditorPane::class.java)
      if (editor != null) {
        singleSelectionHandler.add(editor, true)
      }

      if (notification.isSuggestionType) {
        centerPanel.add(title)
      }
      else {
        titlePanel = JPanel(BorderLayout())
        titlePanel.isOpaque = false
        titlePanel.add(title)
        centerPanel.add(titlePanel)
      }
    }

    if (notification.hasContent()) {
      val textContent = NotificationsUtil.buildHtml(notification, null, true, null, null)
      val text = createTextComponent(textContent)

      NotificationsManagerImpl.setTextAccessibleName(text, textContent)

      singleSelectionHandler.add(text, true)

      if (!notification.hasTitle() && !notification.isSuggestionType) {
        titlePanel = JPanel(BorderLayout())
        titlePanel.isOpaque = false
        titlePanel.add(text)
        centerPanel.add(titlePanel)
      }
      else {
        centerPanel.add(text)
      }
    }
    else {
      myLafUpdater = Runnable(::updateColor)
    }

    val actions = notification.actions
    val actionsSize = actions.size
    val helpAction = notification.contextHelpAction

    if (actionsSize > 0 || helpAction != null) {
      val layout = HorizontalLayout(JBUIScale.scale(16))
      val actionPanel = JPanel(if (!notification.isSuggestionType && actions.size > 1) DropDownActionLayout(layout) else layout)
      actionPanel.isOpaque = false

      if (notification.isSuggestionType) {
        if (actionsSize > 0) {
          val button = JButton(actions[0].templateText)
          button.isOpaque = false
          button.addActionListener {
            runAction(actions[0], it.source)
          }
          actionPanel.add(button)

          if (actionsSize == 2) {
            actionPanel.add(createAction(actions[1]))
          }
          else if (actionsSize > 2) {
            actionPanel.add(MoreAction(this, actions))
          }
        }
      }
      else {
        if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST) {
          actionPanel.add(MyDropDownAction(this))
        }

        for (action in actions) {
          actionPanel.add(createAction(action))
        }

        if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_LEFTMOST) {
          actionPanel.add(MyDropDownAction(this))
        }
      }
      if (helpAction != null) {
        val presentation = helpAction.templatePresentation
        val helpLabel = ContextHelpLabel.create(StringUtil.defaultIfEmpty(presentation.text, ""), presentation.description)
        helpLabel.foreground = UIUtil.getLabelDisabledForeground()
        actionPanel.add(helpLabel)
      }
      centerPanel.add(actionPanel)
    }

    add(centerPanel)

    if (notification.isSuggestionType) {
      val group = DefaultActionGroup()
      group.isPopup = true

      if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) {
        group.add(object : DumbAwareAction(IdeBundle.message("action.text.settings")) {
          override fun actionPerformed(e: AnActionEvent) {
            doShowSettings()
          }
        })
        group.addSeparator()
      }

      val remindAction = RemindLaterManager.createAction(notification, DateFormatUtil.DAY)
      if (remindAction != null) {
        @Suppress("DialogTitleCapitalization")
        group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.remind.tomorrow")) {
          override fun actionPerformed(e: AnActionEvent) {
            remindAction.run()
            myRemoveCallback.accept(myNotificationWrapper.notification!!)
            myNotificationWrapper.notification!!.hideBalloon()
          }
        })
      }

      @Suppress("DialogTitleCapitalization")
      group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again.for.this.project")) {
        override fun actionPerformed(e: AnActionEvent) {
          myDoNotAskHandler.invoke(true)
        }
      })
      @Suppress("DialogTitleCapitalization")
      group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again")) {
        override fun actionPerformed(e: AnActionEvent) {
          myDoNotAskHandler.invoke(false)
        }
      })

      val presentation = Presentation()
      presentation.icon = AllIcons.Actions.More
      presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, java.lang.Boolean.TRUE)

      val button = object : ActionButton(group, presentation, ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) {
        override fun createAndShowActionGroupPopup(actionGroup: ActionGroup, event: AnActionEvent): JBPopup {
          myMorePopupVisible = true
          val popup = super.createAndShowActionGroupPopup(actionGroup, event)
          myMorePopup = popup
          popup.addListener(object : JBPopupListener {
            override fun onClosed(event: LightweightWindowEvent) {
              myMorePopup = null
              ApplicationManager.getApplication().invokeLater {
                myMorePopupVisible = false
                isVisible = myHoverState
              }
            }
          })
          return popup
        }
      }
      button.border = JBUI.Borders.emptyRight(5)
      button.isVisible = false
      myMoreButton = button

      val eastPanel = JPanel(BorderLayout())
      eastPanel.isOpaque = false
      eastPanel.add(button, BorderLayout.NORTH)
      add(eastPanel, BorderLayout.EAST)
      setComponentZOrder(eastPanel, 0)
    }
    else {
      val timeComponent = JBLabel(DateFormatUtil.formatPrettyDateTime(notification.timestamp))
      timeComponent.putClientProperty(TIME_KEY, notification.timestamp)
      timeComponent.verticalAlignment = SwingConstants.TOP
      timeComponent.verticalTextPosition = SwingConstants.TOP
      timeComponent.toolTipText = DateFormatUtil.formatDateTime(notification.timestamp)
      timeComponent.border = JBUI.Borders.emptyRight(10)
      timeComponent.smallFontFunction()
      timeComponent.foreground = INFO_COLOR

      timeComponents.add(timeComponent)

      if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) {
        val button = object: InplaceButton(IdeBundle.message("tooltip.turn.notification.off"), AllIcons.Ide.Notification.Gear,
                                   ActionListener { doShowSettings() }) {
          override fun setBounds(x: Int, y: Int, width: Int, height: Int) {
            super.setBounds(x, y - 1, width, height)
          }
        }
        button.setIcons(AllIcons.Ide.Notification.Gear, null, AllIcons.Ide.Notification.GearHover)
        myMoreButton = button

        val buttonWrapper = JPanel(BorderLayout())
        buttonWrapper.isOpaque = false
        buttonWrapper.border = JBUI.Borders.emptyRight(10)
        buttonWrapper.add(button, BorderLayout.NORTH)
        buttonWrapper.preferredSize = buttonWrapper.preferredSize

        button.isVisible = false

        val eastPanel = JPanel(BorderLayout())
        eastPanel.isOpaque = false
        eastPanel.add(buttonWrapper, BorderLayout.WEST)
        eastPanel.add(timeComponent, BorderLayout.EAST)
        titlePanel!!.add(eastPanel, BorderLayout.EAST)
      }
      else {
        titlePanel!!.add(timeComponent, BorderLayout.EAST)
        myMoreButton = null
      }
    }
  }

  private fun createAction(action: AnAction): JComponent {
    return LinkLabel(action.templateText, action.templatePresentation.icon, { link, _action -> runAction(_action, link) }, action)
  }

  private fun doShowSettings() {
    NotificationCollector.getInstance().logNotificationSettingsClicked(myNotificationWrapper.id, myNotificationWrapper.displayId,
                                                                       myNotificationWrapper.groupId)
    val configurable = NotificationsConfigurable()
    ShowSettingsUtil.getInstance().editConfigurable(project, configurable, Runnable {
      val runnable = configurable.enableSearch(myNotificationWrapper.groupId)
      runnable?.run()
    })
  }

  private fun runAction(action: AnAction, component: Any) {
    setNew(false)
    NotificationCollector.getInstance().logNotificationActionInvoked(null, myNotificationWrapper.notification!!, action,
                                                                     NotificationCollector.NotificationPlace.ACTION_CENTER)
    Notification.fire(myNotificationWrapper.notification!!, action, DataManager.getInstance().getDataContext(component as Component))
  }

  fun expire() {
    closePopups()
    myNotificationWrapper.notification = null
    setNew(false)

    for (component in UIUtil.findComponentsOfType(this, LinkLabel::class.java)) {
      component.isEnabled = false
    }

    val dropDownAction = UIUtil.findComponentOfType(this, MyDropDownAction::class.java)
    if (dropDownAction != null) {
      DataManager.removeDataProvider(dropDownAction)
    }
  }

  fun removeFromParent() {
    closePopups()
    for (component in UIUtil.findComponentsOfType(this, JTextComponent::class.java)) {
      singleSelectionHandler.remove(component)
    }
  }

  private fun closePopups() {
    myMorePopup?.cancel()
    myMoreAwtPopup?.isVisible = false
    myDropDownPopup?.isVisible = false
  }

  private fun createTextComponent(text: @Nls String): JEditorPane {
    val component = JEditorPane()
    component.isEditable = false
    component.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, java.lang.Boolean.TRUE)
    component.contentType = "text/html"
    component.isOpaque = false
    component.border = null

    NotificationsUtil.configureHtmlEditorKit(component)

    if (myNotificationWrapper.notification!!.listener != null) {
      component.addHyperlinkListener { e ->
        val notification = myNotificationWrapper.notification
        if (notification != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) {
          val listener = notification.listener
          if (listener != null) {
            NotificationCollector.getInstance().logHyperlinkClicked(notification)
            listener.hyperlinkUpdate(notification, e)
          }
        }
      }
    }

    component.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, StringUtil.unescapeXmlEntities(StringUtil.stripHtml(text, " ")))

    component.text = text

    component.isEditable = false
    if (component.caret != null) {
      component.caretPosition = 0
    }

    myLafUpdater = Runnable {
      NotificationsUtil.configureHtmlEditorKit(component)
      component.text = text
      component.revalidate()
      component.repaint()

      updateColor()
    }

    return component
  }

  fun updateLaf() {
    myLafUpdater?.run()
  }

  fun setDoNotAskHandler(handler: (Boolean) -> Unit) {
    myDoNotAskHandler = handler
  }

  fun setRemoveCallback(callback: Consumer<Notification>) {
    myRemoveCallback = callback
  }

  fun isHover(): Boolean = myHoverState

  fun setNew(state: Boolean) {
    if (myIsNew != state) {
      myIsNew = state
      updateColor()
    }
  }

  fun setHover(state: Boolean) {
    myHoverState = state
    if (myMoreButton != null) {
      if (!myMorePopupVisible) {
        myMoreButton.isVisible = state
      }
    }
    updateColor()
  }

  private fun updateColor() {
    if (myHoverState) {
      if (myIsNew) {
        setColor(NEW_HOVER_COLOR)
      }
      else {
        setColor(HOVER_COLOR)
      }
    }
    else if (myIsNew) {
      if (UIManager.getColor(NEW_COLOR_NAME) != null) {
        setColor(NEW_COLOR)
      }
      else {
        setColor(NEW_DEFAULT_COLOR)
      }
    }
    else {
      setColor(BG_COLOR)
    }
  }

  private fun setColor(color: Color) {
    myRoundColor = color
    repaint()
  }

  override fun paintComponent(g: Graphics) {
    super.paintComponent(g)
    if (myRoundColor !== BG_COLOR) {
      g.color = myRoundColor
      val config = GraphicsUtil.setupAAPainting(g)
      val cornerRadius = NotificationBalloonRoundShadowBorderProvider.CORNER_RADIUS.get()
      g.fillRoundRect(0, 0, width, height, cornerRadius, cornerRadius)
      config.restore()
    }
  }

  fun applySearchQuery(query: String?): Boolean {
    if (query == null) {
      isVisible = true
      return true
    }

    val result = matchQuery(query)
    isVisible = result
    return result
  }

  private fun matchQuery(query: @NlsSafe String): Boolean {
    if (myNotificationWrapper.title.contains(query, true)) {
      return true
    }
    val subtitle = myNotificationWrapper.subtitle
    if (subtitle != null && subtitle.contains(query, true)) {
      return true
    }
    if (myNotificationWrapper.content.contains(query, true)) {
      return true
    }
    for (action in myNotificationWrapper.actions) {
      if (action != null && action.contains(query, true)) {
        return true
      }
    }
    return false
  }
}

private class MoreAction(val notificationComponent: NotificationComponent, actions: List<AnAction>) :
  NotificationsManagerImpl.DropDownAction(null, null) {
  val group = DefaultActionGroup()

  init {
    val size = actions.size
    for (i in 1..size - 1) {
      group.add(actions[i])
    }

    setListener(LinkListener { link, _ ->
      val popup = NotificationsManagerImpl.showPopup(link, group)
      notificationComponent.myMoreAwtPopup = popup
      popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() {
        override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) {
          notificationComponent.myMoreAwtPopup = null
        }
      })
    }, null)

    text = IdeBundle.message("notifications.action.more")

    Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this)
  }
}

private class MyDropDownAction(val notificationComponent: NotificationComponent) : NotificationsManagerImpl.DropDownAction(null, null) {
  var collapseActionsDirection: Notification.CollapseActionsDirection = notificationComponent.myNotificationWrapper.notification!!.collapseDirection

  init {
    setListener(LinkListener { link, _ ->
      val group = DefaultActionGroup()
      val layout = link.parent.layout as DropDownActionLayout

      for (action in layout.actions) {
        if (!action.isVisible) {
          group.add(action.linkData)
        }
      }

      val popup = NotificationsManagerImpl.showPopup(link, group)
      notificationComponent.myDropDownPopup = popup
      popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() {
        override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) {
          notificationComponent.myDropDownPopup = null
        }
      })
    }, null)

    text = notificationComponent.myNotificationWrapper.notification!!.dropDownText
    isVisible = false

    Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this)
  }
}

private class NotificationWrapper(notification: Notification) {
  val title = notification.title
  val subtitle = notification.subtitle
  val content = notification.content
  val id = notification.id
  val displayId = notification.displayId
  val groupId = notification.groupId
  val actions: List<String?> = notification.actions.stream().map { it.templateText }.toList()
  var notification: Notification? = notification
}

private class DropDownActionLayout(layout: LayoutManager2) : FinalLayoutWrapper(layout) {
  val actions = ArrayList<LinkLabel<AnAction>>()
  private lateinit var myDropDownAction: MyDropDownAction

  override fun addLayoutComponent(comp: Component, constraints: Any?) {
    super.addLayoutComponent(comp, constraints)
    add(comp)
  }

  override fun addLayoutComponent(name: String?, comp: Component) {
    super.addLayoutComponent(name, comp)
    add(comp)
  }

  private fun add(component: Component) {
    if (component is MyDropDownAction) {
      myDropDownAction = component
    }
    else if (component is LinkLabel<*>) {
      @Suppress("UNCHECKED_CAST")
      actions.add(component as LinkLabel<AnAction>)
    }
  }

  override fun layoutContainer(parent: Container) {
    val width = parent.width

    myDropDownAction.isVisible = false
    for (action in actions) {
      action.isVisible = true
    }
    layout.layoutContainer(parent)

    val keepRightmost = myDropDownAction.collapseActionsDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST
    val collapseStart = if (keepRightmost) 0 else actions.size - 1
    val collapseDelta = if (keepRightmost) 1 else -1
    var collapseIndex = collapseStart

    if (parent.preferredSize.width > width) {
      myDropDownAction.isVisible = true
      actions[collapseIndex].isVisible = false
      collapseIndex += collapseDelta
      actions[collapseIndex].isVisible = false
      collapseIndex += collapseDelta
      layout.layoutContainer(parent)

      while (parent.preferredSize.width > width && collapseIndex >= 0 && collapseIndex < actions.size) {
        actions[collapseIndex].isVisible = false
        collapseIndex += collapseDelta
        layout.layoutContainer(parent)
      }
    }
  }
}

private class ComponentEventHandler {
  private var myHoverComponent: NotificationComponent? = null

  private val myMouseHandler = object : MouseAdapter() {
    override fun mouseMoved(e: MouseEvent) {
      if (myHoverComponent == null) {
        val component = ComponentUtil.getParentOfType(NotificationComponent::class.java, e.component)
        if (component != null) {
          if (!component.isHover()) {
            component.setHover(true)
          }
          myHoverComponent = component
        }
      }
    }

    override fun mouseExited(e: MouseEvent) {
      if (myHoverComponent != null) {
        val component = myHoverComponent!!
        if (component.isHover()) {
          component.setHover(false)
        }
        myHoverComponent = null
      }
    }
  }

  fun add(component: Component) {
    addAll(component) { c ->
      c.addMouseListener(myMouseHandler)
      c.addMouseMotionListener(myMouseHandler)
    }
  }

  private fun addAll(component: Component, listener: (Component) -> Unit) {
    listener.invoke(component)

    if (component is JBOptionButton) {
      component.addContainerListener(object : ContainerAdapter() {
        override fun componentAdded(e: ContainerEvent) {
          addAll(e.child, listener)
        }
      })
    }

    for (child in UIUtil.uiChildren(component)) {
      addAll(child, listener)
    }
  }
}

internal class ApplicationNotificationModel {
  private val myNotifications = ArrayList<Notification>()
  private val myProjectToModel = HashMap<Project, ProjectNotificationModel>()
  private val myLock = Object()

  internal fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) {
    synchronized(myLock) {
      notifications.addAll(myNotifications)
      myNotifications.clear()

      val model = myProjectToModel.getOrPut(content.project) { ProjectNotificationModel() }
      model.registerAndGetInitNotifications(content, notifications)
    }
  }

  internal fun unregister(content: NotificationContent) {
    synchronized(myLock) {
      myProjectToModel.remove(content.project)
    }
  }

  fun addNotification(project: Project?, notification: Notification) {
    val runnables = ArrayList<Runnable>()

    synchronized(myLock) {
      if (project == null) {
        if (myProjectToModel.isEmpty()) {
          myNotifications.add(notification)
        }
        else {
          for ((_project, model) in myProjectToModel.entries) {
            model.addNotification(_project, notification, myNotifications, runnables)
          }
        }
      }
      else {
        val model = myProjectToModel.getOrPut(project) {
          Disposer.register(project) {
            synchronized(myLock) {
              myProjectToModel.remove(project)
            }
          }
          ProjectNotificationModel()
        }
        model.addNotification(project, notification, myNotifications, runnables)
      }
    }

    for (runnable in runnables) {
      runnable.run()
    }
  }

  fun getStateNotifications(project: Project): List<Notification> {
    synchronized(myLock) {
      val model = myProjectToModel[project]
      if (model != null) {
        return model.getStateNotifications()
      }
    }
    return emptyList()
  }

  fun getNotifications(project: Project?): List<Notification> {
    synchronized(myLock) {
      if (project == null) {
        return ArrayList(myNotifications)
      }
      val model = myProjectToModel[project]
      if (model == null) {
        return ArrayList(myNotifications)
      }
      return model.getNotifications(myNotifications)
    }
  }

  fun expire(notification: Notification) {
    val runnables = ArrayList<Runnable>()

    synchronized(myLock) {
      myNotifications.remove(notification)
      for (model in myProjectToModel.values) {
        model.expire(notification, runnables)
      }
    }

    for (runnable in runnables) {
      runnable.run()
    }
  }

  fun expireAll() {
    val notifications = ArrayList<Notification>()
    val runnables = ArrayList<Runnable>()

    synchronized(myLock) {
      notifications.addAll(myNotifications)
      myNotifications.clear()
      for (model in myProjectToModel.values) {
        model.expireAll(notifications, runnables)
      }
    }

    for (runnable in runnables) {
      runnable.run()
    }

    for (notification in notifications) {
      notification.expire()
    }
  }
}

private class ProjectNotificationModel {
  private val myNotifications = ArrayList<Notification>()
  private var myContent: NotificationContent? = null

  fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) {
    notifications.addAll(myNotifications)
    myNotifications.clear()
    myContent = content
  }

  fun addNotification(project: Project,
                      notification: Notification,
                      appNotifications: List<Notification>,
                      runnables: MutableList<Runnable>) {
    if (myContent == null) {
      myNotifications.add(notification)

      val notifications = ArrayList(appNotifications)
      notifications.addAll(myNotifications)

      runnables.add(Runnable {
        EventLog.getLogModel(project).setStatusMessage(notification)

        val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(NotificationsToolWindowFactory.ID)
        if (toolWindow != null) {
          UIUtil.invokeLaterIfNeeded { toolWindow.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(notifications)) }
        }
      })
    }
    else {
      runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.add(notification) } })
    }
  }

  fun getStateNotifications(): List<Notification> {
    if (myContent == null) {
      return emptyList()
    }
    return myContent!!.getStateNotifications()
  }

  fun getNotifications(appNotifications: List<Notification>): List<Notification> {
    if (myContent == null) {
      val notifications = ArrayList(appNotifications)
      notifications.addAll(myNotifications)
      return notifications
    }
    return myContent!!.getNotifications()
  }

  fun expire(notification: Notification, runnables: MutableList<Runnable>) {
    myNotifications.remove(notification)
    if (myContent != null) {
      runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(notification) } })
    }
  }

  fun expireAll(notifications: MutableList<Notification>, runnables: MutableList<Runnable>) {
    notifications.addAll(myNotifications)
    myNotifications.clear()
    if (myContent != null) {
      runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(null) } })
    }
  }
}