diff-preview: extract Esc handler setup to common editor customizer
[idea/community.git] / platform / diff-impl / src / com / intellij / diff / editor / DiffFileEditorEscapeHandlerCustomizer.kt
1 // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
2 package com.intellij.diff.editor
3
4 import com.intellij.diff.impl.DiffRequestProcessor
5 import com.intellij.diff.util.DiffUserDataKeysEx
6 import com.intellij.diff.util.DiffUtil
7 import com.intellij.diff.util.FileEditorBase
8 import com.intellij.openapi.Disposable
9 import com.intellij.openapi.actionSystem.CommonShortcuts
10 import com.intellij.openapi.fileEditor.FileEditor
11 import com.intellij.openapi.util.Disposer
12 import com.intellij.openapi.vfs.VirtualFile
13 import java.awt.event.KeyEvent
14 import javax.swing.JComponent
15 import javax.swing.KeyStroke
16
17 class DiffFileEditorEscapeHandlerCustomizer : DiffRequestProcessorEditorCustomizer {
18
19   override fun customize(file: VirtualFile, editor: FileEditor, processor: DiffRequestProcessor) {
20     if (editor !is FileEditorBase) return
21
22     if (!DiffUtil.isUserDataFlagSet(DiffUserDataKeysEx.DIFF_IN_EDITOR_WITH_EXPLICIT_DISPOSABLE, processor.context)) {
23       Disposer.register(editor, Disposable {
24         Disposer.dispose(processor)
25       })
26     }
27     Disposer.register(processor, Disposable {
28       editor.firePropertyChange(FileEditor.PROP_VALID, true, false)
29     })
30
31     processor.component.registerKeyboardAction({ Disposer.dispose(editor) },
32                                                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW)
33
34     file.getUserData(DiffVirtualFile.ESCAPE_HANDLER)?.registerCustomShortcutSet(CommonShortcuts.ESCAPE, editor.component, editor)
35   }
36 }