Codebase list jd-gui / 51036aa1-31f9-4199-8deb-e896fba34b49/upstream app / src / main / java / org / jd / gui / view / OpenTypeHierarchyView.java
51036aa1-31f9-4199-8deb-e896fba34b49/upstream

Tree @51036aa1-31f9-4199-8deb-e896fba34b49/upstream (Download .tar.gz)

OpenTypeHierarchyView.java @51036aa1-31f9-4199-8deb-e896fba34b49/upstreamraw · history · blame

  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
/*
 * Copyright (c) 2008-2019 Emmanuel Dupuy.
 * This project is distributed under the GPLv3 license.
 * This is a Copyleft license that gives the user the right to use,
 * copy and modify the code freely for non-commercial purposes.
 */

package org.jd.gui.view;

import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.api.model.TreeNodeData;
import org.jd.gui.api.model.Type;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.util.function.TriConsumer;
import org.jd.gui.util.swing.SwingUtil;
import org.jd.gui.view.component.Tree;
import org.jd.gui.view.renderer.TreeNodeRenderer;

import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.Future;

public class OpenTypeHierarchyView {
    protected static final ImageIcon ROOT_CLASS_ICON = new ImageIcon(OpenTypeHierarchyView.class.getClassLoader().getResource("org/jd/gui/images/generate_class.png"));
    protected static final ImageIcon ROOT_INTERFACE_ICON = new ImageIcon(OpenTypeHierarchyView.class.getClassLoader().getResource("org/jd/gui/images/generate_int.png"));

    protected static final TreeNodeComparator TREE_NODE_COMPARATOR = new TreeNodeComparator();

    protected API api;
    protected Collection<Future<Indexes>> collectionOfFutureIndexes;

    protected JDialog openTypeHierarchyDialog;
    protected Tree openTypeHierarchyTree;

    protected TriConsumer<Point, Collection<Container.Entry>, String> selectedTypeCallback;

    public OpenTypeHierarchyView(API api, JFrame mainFrame, TriConsumer<Point, Collection<Container.Entry>, String> selectedTypeCallback) {
        this.api = api;
        this.selectedTypeCallback = selectedTypeCallback;
        // Build GUI
        SwingUtil.invokeLater(() -> {
            openTypeHierarchyDialog = new JDialog(mainFrame, "Hierarchy Type", false);

            JPanel panel = new JPanel();
            panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            panel.setLayout(new BorderLayout());
            openTypeHierarchyDialog.add(panel);

            openTypeHierarchyTree = new Tree();
            openTypeHierarchyTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
            openTypeHierarchyTree.setCellRenderer(new TreeNodeRenderer());
            openTypeHierarchyTree.addMouseListener(new MouseAdapter() {
                @Override public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        onTypeSelected();
                    }
                }
            });
            openTypeHierarchyTree.addTreeExpansionListener(new TreeExpansionListener() {
                @Override public void treeExpanded(TreeExpansionEvent e) {
                    TreeNode node = (TreeNode)e.getPath().getLastPathComponent();
                    // Expand node and find the first leaf
                    while (node.getChildCount() > 0) {
                        if (((DefaultMutableTreeNode)node.getChildAt(0)).getUserObject() == null) {
                            // Remove dummy node and create children
                            populateTreeNode(node, null);
                        }
                        if (node.getChildCount() != 1) {
                            break;
                        }
                        node = ((TreeNode)node.getChildAt(0));
                    }
                    DefaultTreeModel model = (DefaultTreeModel)openTypeHierarchyTree.getModel();
                    model.reload((TreeNode)e.getPath().getLastPathComponent());
                    openTypeHierarchyTree.setSelectionPath(new TreePath(node.getPath()));
                }
                @Override public void treeCollapsed(TreeExpansionEvent e) {}
            });
            openTypeHierarchyTree.addKeyListener(new KeyAdapter() {
                @Override public void keyPressed(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_F4) {
                        TreeNode node = (TreeNode)openTypeHierarchyTree.getLastSelectedPathComponent();
                        if (node != null) {
                            updateTree(node.entry, node.typeName);
                        }
                    }
                }
            });

            JScrollPane openTypeHierarchyScrollPane = new JScrollPane(openTypeHierarchyTree);
            openTypeHierarchyScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            openTypeHierarchyScrollPane.setPreferredSize(new Dimension(400, 150));
            panel.add(openTypeHierarchyScrollPane, BorderLayout.CENTER);

            // Buttons "Open" and "Cancel"
            Box vbox = Box.createVerticalBox();
            panel.add(vbox, BorderLayout.SOUTH);
            vbox.add(Box.createVerticalStrut(25));
            Box hbox = Box.createHorizontalBox();
            vbox.add(hbox);
            hbox.add(Box.createHorizontalGlue());
            JButton openTypeHierarchyOpenButton = new JButton("Open");
            hbox.add(openTypeHierarchyOpenButton);
            openTypeHierarchyOpenButton.setEnabled(false);
            openTypeHierarchyOpenButton.addActionListener(e -> onTypeSelected());
            hbox.add(Box.createHorizontalStrut(5));
            JButton openTypeHierarchyCancelButton = new JButton("Cancel");
            hbox.add(openTypeHierarchyCancelButton);
            Action openTypeHierarchyCancelActionListener = new AbstractAction() {
                @Override public void actionPerformed(ActionEvent actionEvent) { openTypeHierarchyDialog.setVisible(false); }
            };
            openTypeHierarchyCancelButton.addActionListener(openTypeHierarchyCancelActionListener);

            openTypeHierarchyTree.addTreeSelectionListener(e -> {
                Object o = openTypeHierarchyTree.getLastSelectedPathComponent();
                if (o != null) {
                    o = ((TreeNode)o).entry;
                }
                openTypeHierarchyOpenButton.setEnabled(o != null);
            });

            // Last setup
            JRootPane rootPane = openTypeHierarchyDialog.getRootPane();
            rootPane.setDefaultButton(openTypeHierarchyOpenButton);
            rootPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "OpenTypeHierarchyView.cancel");
            rootPane.getActionMap().put("OpenTypeHierarchyView.cancel", openTypeHierarchyCancelActionListener);

            openTypeHierarchyDialog.setMinimumSize(openTypeHierarchyDialog.getSize());

            // Prepare to display
            openTypeHierarchyDialog.pack();
            openTypeHierarchyDialog.setLocationRelativeTo(mainFrame);
        });
    }

    public void show(Collection<Future<Indexes>> collectionOfFutureIndexes, Container.Entry entry, String typeName) {
        this.collectionOfFutureIndexes = collectionOfFutureIndexes;
        SwingUtil.invokeLater(() -> {
            updateTree(entry, typeName);
            openTypeHierarchyDialog.setVisible(true);
            openTypeHierarchyTree.requestFocus();
        });
    }

    public boolean isVisible() { return openTypeHierarchyDialog.isVisible(); }

    public void showWaitCursor() {
        SwingUtil.invokeLater(() -> openTypeHierarchyDialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)));
    }

    public void hideWaitCursor() {
        SwingUtil.invokeLater(() -> openTypeHierarchyDialog.setCursor(Cursor.getDefaultCursor()));
    }

    public void updateTree(Collection<Future<Indexes>> collectionOfFutureIndexes) {
        this.collectionOfFutureIndexes = collectionOfFutureIndexes;
        TreeNode selectedTreeNode = (TreeNode)openTypeHierarchyTree.getLastSelectedPathComponent();

        if (selectedTreeNode != null) {
            updateTree(selectedTreeNode.entry, selectedTreeNode.typeName);
        }
    }

    protected void updateTree(Container.Entry entry, String typeName) {
        SwingUtil.invokeLater(() -> {
            // Clear tree
            DefaultTreeModel model = (DefaultTreeModel)openTypeHierarchyTree.getModel();
            DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
            root.removeAllChildren();

            TreeNode selectedTreeNode = createTreeNode(entry, typeName);
            TreeNode parentTreeNode = createParentTreeNode(selectedTreeNode);

            root.add(parentTreeNode);
            model.reload();

            if (selectedTreeNode != null) {
                TreePath path = new TreePath(selectedTreeNode.getPath());
                // Expand
                openTypeHierarchyTree.expandPath(path);
                // Scroll to show tree node
                openTypeHierarchyTree.makeVisible(path);
                Rectangle bounds = openTypeHierarchyTree.getPathBounds(path);

                if(bounds != null) {
                    bounds.x = 0;

                    Rectangle lastRowBounds = openTypeHierarchyTree.getRowBounds(openTypeHierarchyTree.getRowCount()-1);

                    if (lastRowBounds != null) {
                        bounds.y = Math.max(bounds.y-30, 0);
                        bounds.height = Math.min(bounds.height+bounds.y+60, lastRowBounds.height+lastRowBounds.y) - bounds.y;
                    }

                    openTypeHierarchyTree.scrollRectToVisible(bounds);
                    openTypeHierarchyTree.scrollPathToVisible(path);
                    openTypeHierarchyTree.fireVisibleDataPropertyChange();
                }
                // Select tree node
                openTypeHierarchyTree.setSelectionPath(path);
            }
        });
    }

    protected TreeNode createTreeNode(Container.Entry entry, String typeName) {
        Type type = api.getTypeFactory(entry).make(api, entry, typeName);

        typeName = type.getName();

        List<Container.Entry> entries = getEntries(typeName);
        TreeNode treeNode = new TreeNode(entry, typeName, entries, new TreeNodeBean(type));
        List<String> childTypeNames = getSubTypeNames(typeName);

        if (childTypeNames != null) {
            // Add dummy node
            treeNode.add(new DefaultMutableTreeNode());
        }

        return treeNode;
    }

    /**
     * Create parent and sibling tree nodes
     */
    protected TreeNode createParentTreeNode(TreeNode treeNode) {
        Type type = api.getTypeFactory(treeNode.entry).make(api, treeNode.entry, treeNode.typeName);
        String superTypeName = type.getSuperName();

        if (superTypeName != null) {
            List<Container.Entry> superEntries = getEntries(superTypeName);

            // Search entry in the sane container of 'entry'
            Container.Entry superEntry = null;

            if ((superEntries != null) && !superEntries.isEmpty()) {
                for (Container.Entry se : superEntries) {
                    if (se.getContainer() == treeNode.entry.getContainer()) {
                        superEntry = se;
                        break;
                    }
                }

                if (superEntry == null) {
                    // Not found -> Choose 1st one
                    superEntry = superEntries.get(0);
                }
            } else {
                superEntry = null;
            }

            if (superEntry != null) {
                // Create parent tree node
                TreeNode superTreeNode = createTreeNode(superEntry, superTypeName);
                // Populate parent tree node
                populateTreeNode(superTreeNode, treeNode);
                // Recursive call
                return createParentTreeNode(superTreeNode);
            } else {
                // Entry not found --> Most probable hypothesis : Java type entry
                int lastPackageSeparatorIndex = superTypeName.lastIndexOf('/');
                String package_ = superTypeName.substring(0, lastPackageSeparatorIndex).replace('/', '.');
                String name = superTypeName.substring(lastPackageSeparatorIndex + 1).replace('$', '.');
                String label = (package_ != null) ? name + " - " + package_ : name;
                Icon icon = ((type.getFlags() & Type.FLAG_INTERFACE) == 0) ? ROOT_CLASS_ICON : ROOT_INTERFACE_ICON;
                TreeNode rootTreeNode = new TreeNode(null, superTypeName, null, new TreeNodeBean(label, icon));

                if (package_.startsWith("java.")) {
                    // If root type is a JDK type, do not create a tree node for each child types
                    rootTreeNode.add(treeNode);
                } else {
                    populateTreeNode(rootTreeNode, treeNode);
                }

                return rootTreeNode;
            }
        } else {
            // super type undefined
            return treeNode;
        }
    }

    /**
     * @param superTreeNode  node to populate
     * @param activeTreeNode active child node
     */
    protected void populateTreeNode(TreeNode superTreeNode, TreeNode activeTreeNode) {
        superTreeNode.removeAllChildren();

        // Search preferred container: if 'superTreeNode' is a root with an unknown super entry, uses the container of active child node
        Container.Entry notNullEntry = superTreeNode.entry;

        if (notNullEntry == null) {
            notNullEntry = activeTreeNode.entry;
        }

        Container preferredContainer = notNullEntry.getContainer();
        String activeTypName = null;

        if (activeTreeNode != null) {
            activeTypName = activeTreeNode.typeName;
        }

        List<String> subTypeNames = getSubTypeNames(superTreeNode.typeName);
        ArrayList<TreeNode> treeNodes = new ArrayList<>();

        for (String subTypeName : subTypeNames) {
            if (subTypeName.equals(activeTypName)) {
                treeNodes.add(activeTreeNode);
            } else {
                // Search entry in the sane container of 'superTreeNode.entry'
                List<Container.Entry> entries = getEntries(subTypeName);
                Container.Entry entry = null;

                for (Container.Entry e : entries) {
                    if (e.getContainer() == preferredContainer) {
                        entry = e;
                    }
                }

                if (entry == null) {
                    // Not found -> Choose 1st one
                    entry = entries.get(0);
                }
                if (entry != null) {
                    // Create type
                    Type t = api.getTypeFactory(entry).make(api, entry, subTypeName);
                    if (t != null) {
                        // Create tree node
                        treeNodes.add(createTreeNode(entry, t.getName()));
                    }
                }
            }
        }

        treeNodes.sort(TREE_NODE_COMPARATOR);

        for (TreeNode treeNode : treeNodes) {
            superTreeNode.add(treeNode);
        }
    }

    public void focus() {
        SwingUtil.invokeLater(() -> openTypeHierarchyTree.requestFocus());
    }

    protected void onTypeSelected() {
        TreeNode selectedTreeNode = (TreeNode)openTypeHierarchyTree.getLastSelectedPathComponent();

        if (selectedTreeNode != null) {
            TreePath path = new TreePath(selectedTreeNode.getPath());
            Rectangle bounds = openTypeHierarchyTree.getPathBounds(path);
            Point listLocation = openTypeHierarchyTree.getLocationOnScreen();
            Point leftBottom = new Point(listLocation.x+bounds.x, listLocation.y+bounds.y+bounds.height);
            selectedTypeCallback.accept(leftBottom, selectedTreeNode.entries, selectedTreeNode.typeName);
        }
    }

    @SuppressWarnings("unchecked")
    protected List<String> getSubTypeNames(String typeName) {
        ArrayList<String> result = new ArrayList<>();

        try {
            for (Future<Indexes> futureIndexes : collectionOfFutureIndexes) {
                if (futureIndexes.isDone()) {
                    Map<String, Collection> subTypeNames = futureIndexes.get().getIndex("subTypeNames");
                    if (subTypeNames != null) {
                        Collection<String> collection = subTypeNames.get(typeName);
                        if (collection != null) {
                            for (String tn : collection) {
                                if (tn != null) {
                                    result.add(tn);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            assert ExceptionUtil.printStackTrace(e);
        }

        return result;
    }

    @SuppressWarnings("unchecked")
    protected List<Container.Entry> getEntries(String typeName) {
        ArrayList<Container.Entry> result = new ArrayList<>();

        try {
            for (Future<Indexes> futureIndexes : collectionOfFutureIndexes) {
                if (futureIndexes.isDone()) {
                    Map<String, Collection> typeDeclarations = futureIndexes.get().getIndex("typeDeclarations");
                    if (typeDeclarations != null) {
                        Collection<Container.Entry> collection = typeDeclarations.get(typeName);
                        if (collection != null) {
                            for (Container.Entry e : collection) {
                                if (e != null) {
                                    result.add(e);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            assert ExceptionUtil.printStackTrace(e);
        }

        return result;
    }

    protected static class TreeNode extends DefaultMutableTreeNode {
        Container.Entry entry;
        String typeName;
        List<Container.Entry> entries;

        TreeNode(Container.Entry entry, String typeName, List<Container.Entry> entries, Object userObject) {
            super(userObject);
            this.entry = entry;
            this.typeName = typeName;
            this.entries = entries;
        }
    }

    // Graphic data for renderer
    protected static class TreeNodeBean implements TreeNodeData {
        String label;
        String tip;
        Icon icon;
        Icon openIcon;

        TreeNodeBean(Type type) {
            this.label = (type.getDisplayPackageName() != null) ? type.getDisplayTypeName() + " - " + type.getDisplayPackageName() : type.getDisplayTypeName();
            this.icon = type.getIcon();
        }

        TreeNodeBean(String label, Icon icon) {
            this.label = label;
            this.icon = icon;
        }

        @Override public String getLabel() { return label; }
        @Override public String getTip() { return tip; }
        @Override public Icon getIcon() { return icon; }
        @Override public Icon getOpenIcon() { return openIcon; }
    }

    protected static class TreeNodeComparator implements Comparator<TreeNode> {
        @Override
        public int compare(TreeNode tn1, TreeNode tn2) {
            return ((TreeNodeBean)tn1.getUserObject()).label.compareTo(((TreeNodeBean)tn2.getUserObject()).label);
        }
    }
}