fix popups: heavy/medium: restore state of factory after popup creation + delegate...
[idea/community.git] / platform / platform-api / src / com / intellij / openapi / ui / popup / util / PopupUtil.java
1 /*
2  * Copyright 2000-2009 JetBrains s.r.o.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.intellij.openapi.ui.popup.util;
17
18 import com.intellij.openapi.diagnostic.Logger;
19 import com.intellij.openapi.ui.popup.JBPopup;
20 import org.jetbrains.annotations.NotNull;
21 import org.jetbrains.annotations.Nullable;
22
23 import javax.swing.*;
24 import java.awt.*;
25 import java.lang.reflect.Method;
26
27 public class PopupUtil {
28   private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.ui.popup.util.PopupUtil");
29
30   private PopupUtil() {
31   }
32
33   @Nullable
34   public static Component getOwner(@Nullable Component c) {
35     if (c == null) return null;
36
37     final Window wnd = SwingUtilities.getWindowAncestor(c);
38     if (wnd instanceof JWindow) {
39       final JRootPane root = ((JWindow)wnd).getRootPane();
40       final JBPopup popup = (JBPopup)root.getClientProperty(JBPopup.KEY);
41       if (popup == null) return c;
42
43       final Component owner = popup.getOwner();
44       if (owner == null) return c;
45
46       return getOwner(owner);
47     }
48     else {
49       return c;
50     }
51   }
52
53   public static void setPopupType(@NotNull final PopupFactory factory, final int type) {
54     try {
55       final Method method = PopupFactory.class.getDeclaredMethod("setPopupType", int.class);
56       method.setAccessible(true);
57       method.invoke(factory, type);
58     }
59     catch (Throwable e) {
60       LOG.error(e);
61     }
62   }
63
64   public static int getPopupType(@NotNull final PopupFactory factory) {
65     try {
66       final Method method = PopupFactory.class.getDeclaredMethod("getPopupType");
67       method.setAccessible(true);
68       final Object result = method.invoke(factory);
69       return result instanceof Integer ? (Integer) result : -1;
70     }
71     catch (Throwable e) {
72       LOG.error(e);
73     }
74
75     return -1;
76   }
77
78 }