summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/execution/console/ConsoleHistoryController.java
blob: 9aab415d5e704855d86c3e5c2dc21864792c0636 (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
/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * 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.intellij.execution.console;

import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.execution.process.ConsoleHistoryModel;
import com.intellij.lang.Language;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.UndoConstants;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actions.ContentChooser;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringHash;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.SafeFileOutputStream;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.xml.XppReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import java.awt.event.KeyEvent;
import java.io.*;
import java.util.List;
import java.util.ListIterator;

/**
 * @author gregsh
 */
public class ConsoleHistoryController {

  private static final int VERSION = 1;

  private static final Logger LOG = Logger.getInstance("com.intellij.execution.console.ConsoleHistoryController");

  private final LanguageConsoleImpl myConsole;
  private final AnAction myHistoryNext = new MyAction(true);
  private final AnAction myHistoryPrev = new MyAction(false);
  private final AnAction myBrowseHistory = new MyBrowseAction();
  private boolean myMultiline;
  private final ModelHelper myHelper;
  private long myLastSaveStamp;

  public ConsoleHistoryController(@NotNull String type, @Nullable String persistenceId,
                                  @NotNull LanguageConsoleImpl console, @NotNull ConsoleHistoryModel model) {
    myHelper = new ModelHelper(type, StringUtil.isEmpty(persistenceId) ? console.getProject().getPresentableUrl() : persistenceId, model);
    myConsole = console;
  }

  public boolean isMultiline() {
    return myMultiline;
  }

  public ConsoleHistoryController setMultiline(boolean  multiline) {
    myMultiline = multiline;
    return this;
  }

  public ConsoleHistoryModel getModel() {
    return myHelper.getModel();
  }

  public void install() {
    if (myHelper.getId() != null) {
      ApplicationManager.getApplication().getMessageBus().connect(myConsole).subscribe(
        ProjectEx.ProjectSaved.TOPIC, new ProjectEx.ProjectSaved() {
        @Override
        public void saved(@NotNull final Project project) {
          saveHistory();
        }
      });
      Disposer.register(myConsole, new Disposable() {
        @Override
        public void dispose() {
          saveHistory();
        }
      });
      loadHistory(myHelper.getId());
    }
    configureActions();
    myLastSaveStamp = getCurrentTimeStamp();
  }

  private long getCurrentTimeStamp() {
    return getModel().getModificationCount() + myConsole.getEditorDocument().getModificationStamp();
  }

  private void configureActions() {
    EmptyAction.setupAction(myHistoryNext, "Console.History.Next", null);
    EmptyAction.setupAction(myHistoryPrev, "Console.History.Previous", null);
    EmptyAction.setupAction(myBrowseHistory, "Console.History.Browse", null);
    if (!myMultiline) {
      AnAction up = ActionManager.getInstance().getActionOrStub(IdeActions.ACTION_EDITOR_MOVE_CARET_UP);
      AnAction down = ActionManager.getInstance().getActionOrStub(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN);
      if (up != null && down != null) {
        myHistoryNext.registerCustomShortcutSet(up.getShortcutSet(), null);
        myHistoryPrev.registerCustomShortcutSet(down.getShortcutSet(), null);
      }
      else {
        myHistoryNext.registerCustomShortcutSet(KeyEvent.VK_UP, 0, null);
        myHistoryPrev.registerCustomShortcutSet(KeyEvent.VK_DOWN, 0, null);
      }
    }
    myHistoryNext.registerCustomShortcutSet(myHistoryNext.getShortcutSet(), myConsole.getCurrentEditor().getComponent());
    myHistoryPrev.registerCustomShortcutSet(myHistoryPrev.getShortcutSet(), myConsole.getCurrentEditor().getComponent());
    myBrowseHistory.registerCustomShortcutSet(myBrowseHistory.getShortcutSet(), myConsole.getCurrentEditor().getComponent());
  }

  /**
   * Use this method if you decided to change the id for your console but don't want your users to loose their current histories
   * @param id previous id id
   * @return true if some text has been loaded; otherwise false
   */
  public boolean loadHistory(String id) {
    String prev = myHelper.getContent();
    boolean result = myHelper.loadHistory(id);
    String userValue = myHelper.getContent();
    if (prev != userValue && userValue != null) {
      setConsoleText(userValue, false, false);
    }
    return result;
  }

  private void saveHistory() {
    if (myLastSaveStamp == getCurrentTimeStamp()) return;
    myHelper.setContent(myConsole.getEditorDocument().getText());
    myHelper.saveHistory();
    myLastSaveStamp = getCurrentTimeStamp();
  }

  private static void cleanupOldFiles(final File dir) {
    final long keep10weeks = 10 * 1000L * 60 * 60 * 24 * 7;
    final long curTime = System.currentTimeMillis();
    File[] files = dir.listFiles();
    if (files != null) {
      for (File file : files) {
        if (file.isFile() && file.getName().endsWith(".hist.xml") && curTime - file.lastModified() > keep10weeks) {
          file.delete();
        }
      }
    }
  }

  public AnAction getHistoryNext() {
    return myHistoryNext;
  }

  public AnAction getHistoryPrev() {
    return myHistoryPrev;
  }

  public AnAction getBrowseHistory() {
    return myBrowseHistory;
  }

  protected void setConsoleText(final String command, final boolean storeUserText, final boolean regularMode) {
    if (regularMode && myMultiline && StringUtil.isEmptyOrSpaces(command)) return;
    final Editor editor = myConsole.getCurrentEditor();
    final Document document = editor.getDocument();
    new WriteCommandAction.Simple(myConsole.getProject()) {
      @Override
      public void run() {
        if (storeUserText) {
          myHelper.setContent(document.getText());
        }
        String text = StringUtil.notNullize(command);
        int offset;
        if (regularMode) {
          if (myMultiline) {
            offset = insertTextMultiline(text, editor, document);
          }
          else {
            document.setText(text);
            offset = document.getTextLength();
          }
        }
        else {
          offset = 0;
          try {
            document.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
            document.setText(text);
          }
          finally {
            document.putUserData(UndoConstants.DONT_RECORD_UNDO, null);
          }
        }
        editor.getCaretModel().moveToOffset(offset);
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
      }
    }.execute();
  }

  protected int insertTextMultiline(String text, Editor editor, Document document) {
    TextRange selection = EditorUtil.getSelectionInAnyMode(editor);

    int start = document.getLineStartOffset(document.getLineNumber(selection.getStartOffset()));
    int end = document.getLineEndOffset(document.getLineNumber(selection.getEndOffset()));

    document.replaceString(start, end, text);
    editor.getSelectionModel().setSelection(start, start + text.length());
    return start;
  }

  private class MyAction extends AnAction {
    private final boolean myNext;

    public MyAction(final boolean next) {
      myNext = next;
      getTemplatePresentation().setVisible(false);
    }

    @Override
    public void actionPerformed(final AnActionEvent e) {
      final String command;
      if (myNext) {
        command = getModel().getHistoryNext();
        if (!myMultiline && command == null) return;
      }
      else {
        if (!myMultiline && getModel().getHistoryCursor() < 0) return;
        command = ObjectUtils.chooseNotNull(getModel().getHistoryPrev(), myMultiline ? "" : StringUtil.notNullize(myHelper.getContent()));
      }
      setConsoleText(command, myNext && getModel().getHistoryCursor() == 0, true);
    }

    @Override
    public void update(final AnActionEvent e) {
      super.update(e);
      e.getPresentation().setEnabled(myMultiline || canMoveInEditor(myNext));
    }
  }

  private boolean canMoveInEditor(final boolean next) {
    final Editor consoleEditor = myConsole.getCurrentEditor();
    final Document document = consoleEditor.getDocument();
    final CaretModel caretModel = consoleEditor.getCaretModel();

    if (LookupManager.getActiveLookup(consoleEditor) != null) return false;

    if (next) {
      return document.getLineNumber(caretModel.getOffset()) == 0;
    }
    else {
      final int lineCount = document.getLineCount();
      return (lineCount == 0 || document.getLineNumber(caretModel.getOffset()) == lineCount - 1) &&
             StringUtil.isEmptyOrSpaces(document.getText().substring(caretModel.getOffset()));
    }
  }



  private class MyBrowseAction extends AnAction {

    @Override
    public void update(final AnActionEvent e) {
      e.getPresentation().setEnabled(getModel().getHistorySize() > 0);
    }

    @Override
    public void actionPerformed(final AnActionEvent e) {
      String s1 = KeymapUtil.getFirstKeyboardShortcutText(myHistoryNext);
      String s2 = KeymapUtil.getFirstKeyboardShortcutText(myHistoryPrev);
      String title = myConsole.getTitle() + " History" +
                     (StringUtil.isNotEmpty(s1) && StringUtil.isNotEmpty(s2) ?" (" +s1+ " and " +s2+ " while in editor)" : "");
      final ContentChooser<String> chooser = new ContentChooser<String>(myConsole.getProject(), title, true) {

        @Override
        protected void removeContentAt(String content) {
          getModel().removeFromHistory(content);
        }

        @Override
        protected String getStringRepresentationFor(String content) {
          return content;
        }

        @Override
        protected List<String> getContents() {
          return getModel().getHistory();
        }

        @Override
        protected Editor createIdeaEditor(String text) {
          PsiFile consoleFile = myConsole.getFile();
          Language language = consoleFile.getLanguage();
          Project project = consoleFile.getProject();

          PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(
            "a."+consoleFile.getFileType().getDefaultExtension(),
            language,
            StringUtil.convertLineSeparators(new String(text)), false, true);
          VirtualFile virtualFile = psiFile.getViewProvider().getVirtualFile();
          if (virtualFile instanceof LightVirtualFile) ((LightVirtualFile)virtualFile).setWritable(false);
          Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
          EditorFactory editorFactory = EditorFactory.getInstance();
          EditorEx editor = (EditorEx)editorFactory.createViewer(document, project);
          editor.getSettings().setFoldingOutlineShown(false);
          editor.getSettings().setLineMarkerAreaShown(false);
          editor.getSettings().setIndentGuidesShown(false);

          SyntaxHighlighter highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, psiFile.getViewProvider().getVirtualFile());
          editor.setHighlighter(new LexerEditorHighlighter(highlighter, editor.getColorsScheme()));
          return editor;
        }
      };
      chooser.setContentIcon(null);
      chooser.setSplitterOrientation(false);
      chooser.setSelectedIndex(Math.max(getModel().getHistoryCursor(), 0));
      chooser.show();
      if (chooser.isOK()) {
        setConsoleText(chooser.getSelectedText(), false, true);
      }
    }
  }

  public static class ModelHelper {
    private final String myType;
    private final String myId;
    private final ConsoleHistoryModel myModel;
    private String myContent;

    public ModelHelper(String type, String id, ConsoleHistoryModel model) {
      myType = type;
      myId = id;
      myModel = model;
    }

    public ConsoleHistoryModel getModel() {
      return myModel;
    }

    public void setContent(String userValue) {
      myContent = userValue;
    }

    public String getId() {
      return myId;
    }

    public String getContent() {
      return myContent;
    }

    private String getHistoryFilePath(final String id) {
      return PathManager.getSystemPath() + File.separator +
             "userHistory" + File.separator +
             myType + Long.toHexString(StringHash.calc(id)) + ".hist.xml";
    }

    public boolean loadHistory(String id) {
      File file = new File(getHistoryFilePath(id));
      if (!file.exists()) return false;
      HierarchicalStreamReader xmlReader = null;
      try {
        xmlReader = new XppReader(new InputStreamReader(new FileInputStream(file), CharsetToolkit.UTF8));
        String text = loadHistory(xmlReader, id);
        if (text != null) {
          myContent = text;
          return true;
        }
      }
      catch (Exception ex) {
        //noinspection ThrowableResultOfMethodCallIgnored
        Throwable cause = ExceptionUtil.getRootCause(ex);
        if (cause instanceof EOFException) {
          LOG.warn("Failed to load " + myType + " console history from: " + file.getPath(), ex);
          return false;
        }
        else {
          LOG.error(ex);
        }
      }
      finally {
        if (xmlReader != null) {
          xmlReader.close();
        }
      }
      return false;
    }

    private void saveHistory() {
      final File file = new File(getHistoryFilePath(myId));
      final File dir = file.getParentFile();
      if (!dir.exists() && !dir.mkdirs() || !dir.isDirectory()) {
        LOG.error("failed to create folder: " + dir.getAbsolutePath());
        return;
      }

      OutputStream os = null;
      try {
        final XmlSerializer serializer = XmlPullParserFactory.newInstance().newSerializer();
        try {
          serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-indentation", "  ");
        }
        catch (Exception ignored) {
          // not recognized
        }
        serializer.setOutput(os = new SafeFileOutputStream(file), CharsetToolkit.UTF8);
        saveHistory(serializer);
        serializer.flush();
      }
      catch (Exception ex) {
        LOG.error(ex);
      }
      finally {
        try {
          os.close();
        }
        catch (Exception ignored) {
          // nothing
        }
      }
      cleanupOldFiles(dir);
    }

    @Nullable
    private String loadHistory(HierarchicalStreamReader in, String expectedId) {
      if (!in.getNodeName().equals("console-history")) return null;
      int version = StringUtil.parseInt(in.getAttribute("version"), 0);
      String id = in.getAttribute("id");
      if (!expectedId.equals(id)) return null;
      List<String> entries = ContainerUtil.newArrayList();
      String consoleContent = null;
      while (in.hasMoreChildren()) {
        in.moveDown();
        if ("history-entry".equals(in.getNodeName())) {
          entries.add(StringUtil.notNullize(in.getValue()));
        }
        else if ("console-content".equals(in.getNodeName())) {
          consoleContent = StringUtil.notNullize(in.getValue());
        }
        in.moveUp();
      }
      for (ListIterator<String> iterator = entries.listIterator(entries.size()); iterator.hasPrevious(); ) {
        String entry = iterator.previous();
        getModel().addToHistory(entry);
      }
      return consoleContent;
    }

    private void saveHistory(XmlSerializer out) throws IOException {
      out.startDocument(CharsetToolkit.UTF8, null);
      out.startTag(null, "console-history");
      out.attribute(null, "version", String.valueOf(VERSION));
      out.attribute(null, "id", myId);
      try {
        for (String s : getModel().getHistory()) {
          textTag(out, "history-entry", s);
        }
        String current = myContent;
        if (StringUtil.isNotEmpty(current)) {
          textTag(out, "console-content", current);
        }
      }
      finally {
        out.endTag(null, "console-history");
        out.endDocument();
      }
    }
  }

  private static void textTag(@NotNull XmlSerializer out, @NotNull String tag, @NotNull String text) throws IOException {
    out.startTag(null, tag);
    try {
      out.cdsect(text);
    }
    finally {
      out.endTag(null, tag);
    }
  }
}