summaryrefslogtreecommitdiff
path: root/src/com/google/devrel/cluestick/studioclient/SearchResultsView.java
blob: 4c671ee8205fb441f048c19ab1b697c807c09266 (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
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.devrel.cluestick.studioclient;

import com.google.devrel.cluestick.searchservice.CluestickSearch;
import com.google.devrel.cluestick.searchservice.EventLog;

import com.appspot.cluestick_server.search.model.Result;
import com.intellij.CommonBundle;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.OnePixelSplitter;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SmartExpander;
import com.intellij.util.ui.tree.TreeUtil;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

/**
 * SearchResultsView extends JPanel to show the entire Cluestick sample widget.
 */
public class SearchResultsView extends JPanel implements Disposable {

  private static final Logger LOG = Logger
      .getInstance("#com.google.devrel.cluestick.studioclient.SearchResultsView");

  private final EventLog eventLog;
  private final Splitter splitter;
  private final SearchResultsTree tree;
  private final Browser browser;
  private final JComponent secondComponent;
  private Runnable closeAction;

  public SearchResultsView(@NotNull final Project project, @NotNull final Symbol symbol,
      @NotNull final List<Result> results) {
    eventLog = new EventLog(ServiceManager.getService(CluestickSearch.class));

    setLayout(new BorderLayout());

    tree = new SearchResultsTree(symbol, results);
    tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
      @Override
      public void valueChanged(TreeSelectionEvent e) {
        syncBrowser();
      }
    });
    SmartExpander.installOn(tree);
    browser = new CodeBrowser(project, eventLog);

    splitter = new OnePixelSplitter(false, 0.5f);
    splitter.setFirstComponent(ScrollPaneFactory.createScrollPane(tree));

    secondComponent = ScrollPaneFactory.createScrollPane(browser.getPanel());
    splitter.setSecondComponent(secondComponent);
    secondComponent.setVisible(false);  // initially hide browser

    add(splitter, BorderLayout.CENTER);

    createActionsPanel();

    // Add action listeners. These listeners don't do anything if the target node isn't a leaf,
    // because trunk nodes respond by opening/closing on these same events. Users should use the
    // popup menu to open any relevant URLs instead.

    new DoubleClickListener() {
      @Override
      protected boolean onDoubleClick(MouseEvent event) {
        TreeNode node = getSingleSelectedNode();
        TreePath path = tree.getClosestPathForLocation(event.getX(), event.getY());
        if (node != null && node.isLeaf() && path != null && tree.isPathSelected(path)) {
          invokeSelectAction(node);
          return true;
        }
        return false;
      }
    }.installOn(tree);

    tree.addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(KeyEvent e) {
        TreeNode node = getSingleSelectedNode();
        if (node != null && node.isLeaf() && e.getKeyCode() == KeyEvent.VK_ENTER) {
          invokeSelectAction(node);
        }
      }
    });

    DefaultActionGroup actionGroup = new DefaultActionGroup();
    actionGroup.add(new OpenURLAction());
    ActionManager actionManager = ActionManager.getInstance();
    PopupHandler.installPopupHandler(tree, actionGroup, ActionPlaces.USAGE_VIEW_POPUP, actionManager);

    TreeUtil.expandAll(tree);
  }

  /**
   * @param close The code to run when the Close button is pressed.
   */
  public void setClose(Runnable close) {
    this.closeAction = close;
  }

  private void invokeSelectAction(@Nullable TreeNode node) {
    String url = getURLForNode(node);
    if (url != null) {
      openExternalBrowser(url);
    }
  }

  @Nullable private String getURLForNode(@Nullable TreeNode node) {
    if (node instanceof SearchResultsNode) {
      String url = ((SearchResultsNode) node).getURL();
      if (!StringUtil.isEmpty(url)) {
        return url;
      }
    }
    return null;
  }

  private void openExternalBrowser(@NotNull String url) {
    LOG.info(String.format("Opening URL: `%s`", url));

    // In nearly all cases, this will load the user's browser with the target URL. However,
    // swallow its exceptions for sanity.
    try {
      Desktop.getDesktop().browse(new URI(url));
    } catch (URISyntaxException ignored) {
      // Thrown if the URL is bad.
    } catch (IOException ignored) {
      // Thrown if a browser can't be found or run.
    } catch (RuntimeException ignored) {
      // Thrown on a variety of other reasons, see-
      // http://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html#browse(java.net.URI)
    }
  }

  /**
   * Create and add a JPanel containing default actions. This just includes Close for now.
   */
  private void createActionsPanel() {
    DefaultActionGroup group = new DefaultActionGroup();
    group.add(new CloseAction());

    ActionManager actionManager = ActionManager.getInstance();
    JComponent actionsToolbar = actionManager
        .createActionToolbar(ActionPlaces.CODE_INSPECTION, group, false).getComponent();

    JPanel actionsPanel = new JPanel(new BorderLayout());
    actionsPanel.add(actionsToolbar, BorderLayout.WEST);
    add(actionsPanel, BorderLayout.WEST);
  }

  @Override
  public void dispose() {
    splitter.dispose();
    eventLog.cancel();

    if (browser instanceof Disposable) {
      ((Disposable) browser).dispose();
    }
  }

  private TreeNode getSingleSelectedNode() {
    TreeSelectionModel selectionModel = tree.getSelectionModel();
    if (selectionModel.getSelectionCount() == 1) {
      TreePath pathSelected = tree.getSelectionModel().getLeadSelectionPath();
      if (pathSelected != null) {
        return (TreeNode) pathSelected.getLastPathComponent();
      }
    }
    return null;
  }

  private void syncBrowser() {
    boolean visible = false;
    TreeNode node = getSingleSelectedNode();
    if (node instanceof SearchResultsNode) {
      Result result = ((SearchResultsNode) node).getSearchResult();
      if (result != null && showInBrowser(result)) {
        visible = true;
      }
    }

    if (!visible) {
      browser.showEmpty();
    }
    if (secondComponent.isVisible() != visible) {
      secondComponent.setVisible(visible);
      splitter.doLayout();
      splitter.doLayout();  // run twice, in case skipNextLayouting() was called on Splitter
    }
  }

  /**
   * Shows the given {@link Result} inside the current {@link Browser}.
   * @param result The result to show.
   * @return Whether the result could be shown.
   */
  private boolean showInBrowser(@NotNull Result result) {
    // TODO(thorogood): Make this part of Browser interface.
    if (result.getCode() == null) {
      return false;
    }

    Cursor currentCursor = getCursor();
    setCursor(new Cursor(Cursor.WAIT_CURSOR));
    browser.showResult(result);
    setCursor(currentCursor);
    return true;
  }

  private class OpenURLAction extends AnAction {
    private OpenURLAction() {
      super(IdeBundle.message("open.url.in.browser.tooltip"), null, null);
    }

    @Override
    public void update(AnActionEvent e) {
      String url = getURLForNode(getSingleSelectedNode());
      e.getPresentation().setVisible(url != null);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      invokeSelectAction(getSingleSelectedNode());
    }
  }

  private class CloseAction extends AnAction implements DumbAware {
    private CloseAction() {
      super(CommonBundle.message("action.close"), null, AllIcons.Actions.Cancel);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      if (closeAction != null) {
        closeAction.run();
      }
    }
  }
}