Welcome to mirror list, hosted at ThFree Co, Russian Federation.

EditorTab.java « app « processing « src « app - github.com/arduino/Arduino.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5e8f3e4bfcf744bf9099a282792cba0bdab87f90 (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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
  Part of the Arduino project - http://www.arduino.cc

  Copyright (c) 2015 Matthijs Kooijman
  Copyright (c) 2004-09 Ben Fry and Casey Reas
  Copyright (c) 2001-04 Massachusetts Institute of Technology

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License version 2
  as published by the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software Foundation,
  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package processing.app;

import static processing.app.I18n.tr;
import static processing.app.Theme.scale;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.IOException;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.ToolTipManager;
import javax.swing.border.MatteBorder;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.PlainDocument;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Document;

import org.apache.commons.lang3.StringUtils;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit;
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
import org.fife.ui.rtextarea.Gutter;
import org.fife.ui.rtextarea.RTextScrollPane;

import cc.arduino.UpdatableBoardsLibsFakeURLsHandler;
import processing.app.helpers.DocumentTextChangeListener;
import processing.app.syntax.ArduinoTokenMakerFactory;
import processing.app.syntax.PdeKeywords;
import processing.app.syntax.SketchTextArea;
import processing.app.syntax.SketchTextAreaEditorKit;
import processing.app.tools.DiscourseFormat;

/**
 * Single tab, editing a single file, in the main window.
 */
public class EditorTab extends JPanel implements SketchFile.TextStorage {
  protected Editor editor;
  protected SketchTextArea textarea;
  protected RTextScrollPane scrollPane;
  protected SketchFile file;
  protected boolean modified;
  /** Is external editing mode currently enabled? */
  protected boolean external;
  
  /**
   * Create a new EditorTab
   *
   * @param editor
   *          The Editor this tab runs in
   * @param file
   *          The file to display in this tab
   * @param contents
   *          Initial contents to display in this tab. Can be used when editing
   *          a file that doesn't exist yet. If null is passed, code.load() is
   *          called and displayed instead.
   * @throws IOException
   */
  public EditorTab(Editor editor, SketchFile file, String contents)
      throws IOException {
    super(new BorderLayout());

    // Load initial contents contents from file if nothing was specified.
    if (contents == null) {
      contents = file.load();
      modified = false;
    } else {
      modified = true;
    }

    this.editor = editor;
    this.file = file;
    RSyntaxDocument document = createDocument(contents);
    textarea = createTextArea(document);
    scrollPane = createScrollPane(textarea);
    file.setStorage(this);
    applyPreferences();
    add(scrollPane, BorderLayout.CENTER);
    editor.base.addEditorFontResizeMouseWheelListener(textarea);
  }

  private RSyntaxDocument createDocument(String contents) {
    RSyntaxDocument document = new RSyntaxDocument(new ArduinoTokenMakerFactory(editor.base.getPdeKeywords()), RSyntaxDocument.SYNTAX_STYLE_CPLUSPLUS);
    document.putProperty(PlainDocument.tabSizeAttribute, PreferencesData.getInteger("editor.tabs.size"));

    // insert the program text into the document object
    try {
      document.insertString(0, contents, null);
    } catch (BadLocationException bl) {
      bl.printStackTrace();
    }
    document.addDocumentListener(new DocumentTextChangeListener(
        () -> setModified(true)));
    return document;
  }
  
  private RTextScrollPane createScrollPane(SketchTextArea textArea) throws IOException {
    RTextScrollPane scrollPane = new RTextScrollPane(textArea, true);
    scrollPane.setBorder(new MatteBorder(0, 6, 0, 0, Theme.getColor("editor.bgcolor")));
    scrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
    scrollPane.setLineNumbersEnabled(PreferencesData.getBoolean("editor.linenumbers"));
    scrollPane.setIconRowHeaderEnabled(false);

    Gutter gutter = scrollPane.getGutter();
    gutter.setBookmarkingEnabled(false);
    //gutter.setBookmarkIcon(CompletionsRenderer.getIcon(CompletionType.TEMPLATE));
    gutter.setIconRowHeaderInheritsGutterBackground(true);

    return scrollPane;
  }

  private SketchTextArea createTextArea(RSyntaxDocument document)
      throws IOException {
    final SketchTextArea textArea = new SketchTextArea(document, editor.base.getPdeKeywords());
    textArea.setName("editor");
    textArea.setFocusTraversalKeysEnabled(false);
    //textArea.requestFocusInWindow();
    textArea.setMarkOccurrences(PreferencesData.getBoolean("editor.advanced"));
    textArea.setMarginLineEnabled(false);
    textArea.setCodeFoldingEnabled(PreferencesData.getBoolean("editor.code_folding"));
    textArea.setAutoIndentEnabled(PreferencesData.getBoolean("editor.indent"));
    textArea.setCloseCurlyBraces(PreferencesData.getBoolean("editor.auto_close_braces", true));
    textArea.setAntiAliasingEnabled(PreferencesData.getBoolean("editor.antialias"));
    textArea.setTabsEmulated(PreferencesData.getBoolean("editor.tabs.expand"));
    textArea.setTabSize(PreferencesData.getInteger("editor.tabs.size"));
    textArea.addHyperlinkListener(evt -> {
      try {
        UpdatableBoardsLibsFakeURLsHandler boardLibHandler = new UpdatableBoardsLibsFakeURLsHandler(editor.base);
        boardLibHandler.openBoardLibManager(evt.getURL());
      }
      catch (Exception e) {
        try {
          editor.platform.openURL(editor.getSketch().getFolder(), evt.getURL().toExternalForm());
        } catch (Exception f) {
          Base.showWarning(f.getMessage(), f.getMessage(), f);
        }
      }
    });
    textArea.addCaretListener(e -> {
      Element root = textArea.getDocument().getDefaultRootElement();
      int lineStart = root.getElementIndex(e.getMark());
      int lineEnd = root.getElementIndex(e.getDot());

      editor.lineStatus.set(lineStart, lineEnd);
    });
    textArea.addFocusListener(new FocusListener() {
      public void focusGained(FocusEvent e) {
        Element root = textArea.getDocument().getDefaultRootElement();
        int lineStart = root.getElementIndex(textArea.getCaret().getMark());
        int lineEnd = root.getElementIndex(textArea.getCaret().getDot());
        editor.lineStatus.set(lineStart, lineEnd);
      };
      public void focusLost(FocusEvent e) {};
    });
    ToolTipManager.sharedInstance().registerComponent(textArea);

    configurePopupMenu(textArea);
    return textArea;
  }

  private void configurePopupMenu(final SketchTextArea textarea){

    JPopupMenu menu = textarea.getPopupMenu();

    menu.addSeparator();

    JMenuItem item = editor.createToolMenuItem("cc.arduino.packages.formatter.AStyle");
    if (item == null) {
      throw new NullPointerException("Tool cc.arduino.packages.formatter.AStyle unavailable");
    }
    item.setName("menuToolsAutoFormat");

    menu.add(item);
    
    item = new JMenuItem(tr("Comment/Uncomment"), '/');
    item.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          handleCommentUncomment();
        }
    });
    menu.add(item);

    item = new JMenuItem(tr("Increase Indent"), ']');
    item.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          handleIndentOutdent(true);
        }
    });
    menu.add(item);

    item = new JMenuItem(tr("Decrease Indent"), '[');
    item.setName("menuDecreaseIndent");
    item.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          handleIndentOutdent(false);
        }
    });
    menu.add(item);

    item = new JMenuItem(tr("Copy for Forum"));
    item.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        handleDiscourseCopy();
      }
    });
    menu.add(item);

    item = new JMenuItem(tr("Copy as HTML"));
    item.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        handleHTMLCopy();
      }
    });
    menu.add(item);

    final JMenuItem referenceItem = new JMenuItem(tr("Find in Reference"));
    referenceItem.addActionListener(editor::handleFindReference);
    menu.add(referenceItem);  

    final JMenuItem openURLItem = new JMenuItem(tr("Open URL"));
    openURLItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Base.openURL(e.getActionCommand());
      }
    });
    menu.add(openURLItem);   
    
    menu.addPopupMenuListener(new PopupMenuListener() {

      @Override
      public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            String referenceFile = editor.base.getPdeKeywords().getReference(getCurrentKeyword());
            referenceItem.setEnabled(referenceFile != null);
    
            int offset = textarea.getCaretPosition();
            org.fife.ui.rsyntaxtextarea.Token token = RSyntaxUtilities.getTokenAtOffset(textarea, offset);
            if (token != null && token.isHyperlink()) {
              openURLItem.setEnabled(true);
              openURLItem.setActionCommand(token.getLexeme());
            } else {
              openURLItem.setEnabled(false);
            }
      }

      @Override
      public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
      }

      @Override
      public void popupMenuCanceled(PopupMenuEvent e) {
      }
    });

  }
  
  public void applyPreferences() {
    textarea.setCodeFoldingEnabled(PreferencesData.getBoolean("editor.code_folding"));
    scrollPane.setFoldIndicatorEnabled(PreferencesData.getBoolean("editor.code_folding"));
    scrollPane.setLineNumbersEnabled(PreferencesData.getBoolean("editor.linenumbers"));

    // apply the setting for 'use external editor', but only if it changed
    if (external != PreferencesData.getBoolean("editor.external")) {
      external = !external;
      if (external) {
        // disable line highlight and turn off the caret when disabling
        textarea.setBackground(Theme.getColor("editor.external.bgcolor"));
        textarea.setHighlightCurrentLine(false);
        textarea.setEditable(false);
        // Detach from the code, since we are no longer the authoritative source
        // for file contents.
        file.setStorage(null);
        // Reload, in case the file contents already changed.
        reload();
      } else {
        textarea.setBackground(Theme.getColor("editor.bgcolor"));
        textarea.setHighlightCurrentLine(Theme.getBoolean("editor.linehighlight"));
        textarea.setEditable(true);
        file.setStorage(this);
        // Reload once just before disabling external mode, to ensure we have
        // the latest contents.
        reload();
      }
    }
    // apply changes to the font size for the editor
    Font editorFont = scale(PreferencesData.getFont("editor.font"));
    
    // check whether a theme-defined editor font is available
    Font themeFont = Theme.getFont("editor.font");
    if (themeFont != null)
    {
      // Apply theme font if the editor font has *not* been changed by the user,
      // This allows themes to specify an editor font which will only be applied
      // if the user hasn't already changed their editor font via preferences.txt
      String defaultFontName = StringUtils.defaultIfEmpty(PreferencesData.getDefault("editor.font"), "").split(",")[0];
      if (defaultFontName.equals(editorFont.getName())) {
        editorFont = new Font(themeFont.getName(), themeFont.getStyle(), editorFont.getSize());
      }
    }
    
    textarea.setFont(editorFont);
    scrollPane.getGutter().setLineNumberFont(editorFont);
  }
  
  public void updateKeywords(PdeKeywords keywords) {
    // update GUI for "Find In Reference"
    textarea.setKeywords(keywords);
    // update document for syntax highlighting
    RSyntaxDocument document = (RSyntaxDocument) textarea.getDocument();
    document.setTokenMakerFactory(new ArduinoTokenMakerFactory(keywords));
    document.setSyntaxStyle(RSyntaxDocument.SYNTAX_STYLE_CPLUSPLUS);
  }

  /**
   * Called when this tab is made the current one, or when it is the current one
   * and the window is activated.
   */
  public void activated() {
    // When external editing is enabled, reload the text whenever we get activated.
    if (external) {
      reload();
    }
  }

  /**
   * Reload the contents of our file.
   */
  public void reload() {
    String text;
    try {
      text = file.load();
    } catch (IOException e) {
      System.err.println(I18n.format("Warning: Failed to reload file: \"{0}\"",
                                     file.getFileName()));
      return;
    }
    setText(text);
    setModified(false);
  }

  /**
   * Get the TextArea object for use (not recommended). This should only
   * be used in obscure cases that really need to hack the internals of the
   * JEditTextArea. Most tools should only interface via the get/set functions
   * found in this class. This will maintain compatibility with future releases,
   * which will not use TextArea.
   */
  public SketchTextArea getTextArea() {
    return textarea;
  }

  /**
   * Get the sketch this tab is editing a file from.
   */
  public SketchController getSketch() {
    return editor.getSketchController();
  }
  
  /**
   * Get the SketchFile that is being edited in this tab.
   */
  public SketchFile getSketchFile() {
    return this.file;
  }
  
  /**
   * Get the contents of the text area.
   */
  public String getText() {
    return textarea.getText();
  }

  /**
   * Replace the entire contents of this tab.
   */
  public void setText(String what) {
    // Remove all highlights, since these will all end up at the start of the
    // text otherwise. Preserving them is tricky, so better just remove them.
    textarea.removeAllLineHighlights();
    // Set the caret update policy to NEVER_UPDATE while completely replacing
    // the current text. Normally, the caret tracks inserts and deletions, but
    // replacing the entire text will always make the caret end up at the end,
    // which isn't really useful. With NEVER_UPDATE, the caret will just keep
    // its absolute position (number of characters from the start), which isn't
    // always perfect, but the best we can do without making a diff of the old
    // and new text and some guesswork.
    // Note that we cannot use textarea.setText() here, since that first removes
    // text and then inserts the new text. Even with NEVER_UPDATE, the caret
    // always makes sure to stay valid, so first removing all text makes it
    // reset to 0. Also note that simply saving and restoring the caret position
    // will work, but then the scroll position might change in response to the
    // caret position.
    DefaultCaret caret = (DefaultCaret) textarea.getCaret();
    int policy = caret.getUpdatePolicy();
    caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    try {
      Document doc = textarea.getDocument();
      int oldLength = doc.getLength();
      // The undo manager already seems to group the insert and remove together
      // automatically, but better be explicit about it.
      textarea.beginAtomicEdit();
      try {
        doc.insertString(oldLength, what, null);
        doc.remove(0, oldLength);
      } catch (BadLocationException e) {
        System.err.println("Unexpected failure replacing text");
      } finally {
        textarea.endAtomicEdit();
      }
    } finally {
      caret.setUpdatePolicy(policy);
    }
    // A trick to force textarea to recalculate the bracket matching rectangle.
    // In the worst case scenario, this should be ineffective.
    textarea.setLineWrap(textarea.getLineWrap());
  }

  /**
   * Is the text modified since the last save / load?
   */
  public boolean isModified() {
    return modified;
  }

  /**
   * Clear modified status. Should only be called by SketchFile through the
   * TextStorage interface.
   */
  public void clearModified() {
    setModified(false);
  }

  private void setModified(boolean value) {
    if (value != modified) {
      modified = value;
      // TODO: Improve decoupling
      editor.getSketchController().calcModified();
    }
  }

  public String getSelectedText() {
    return textarea.getSelectedText();
  }


  public void setSelectedText(String what) {
    textarea.replaceSelection(what);
  }

  public void setSelection(int start, int stop) {
    textarea.select(start, stop);
  }
  
  public int getScrollPosition() {
    return scrollPane.getVerticalScrollBar().getValue();
  }
    
  public void setScrollPosition(int pos) {
    scrollPane.getVerticalScrollBar().setValue(pos);
  }

  /**
   * Get the beginning point of the current selection.
   */
  public int getSelectionStart() {
    return textarea.getSelectionStart();
  }

  /**
   * Get the end point of the current selection.
   */
  public int getSelectionStop() {
    return textarea.getSelectionEnd();
  }

  /**
   * Get text for a specified line.
   */
  public String getLineText(int line) {
    try {
      return textarea.getText(textarea.getLineStartOffset(line), textarea.getLineEndOffset(line));
    } catch (BadLocationException e) {
      return "";
    }
  }

  /**
   * Jump to the given line
   * @param line The line number to jump to, 1-based. 
   */
  public void goToLine(int line) {
    if (line <= 0) {
      return;
    }
    try {
      textarea.setCaretPosition(textarea.getLineStartOffset(line - 1));
    } catch (BadLocationException e) {
      //ignore
    }
  }
  
  void handleCut() {
    textarea.cut();
  }
 
  void handleCopy() {
    textarea.copy();
  }
  
  void handlePaste() {
    textarea.paste();
  }
  
  void handleSelectAll() {
    textarea.selectAll();
  }

  void handleCommentUncomment() {
    Action action = textarea.getActionMap().get(RSyntaxTextAreaEditorKit.rstaToggleCommentAction);
    action.actionPerformed(null);
    // XXX: RSyntaxDocument doesn't fire DocumentListener events, it should be fixed in RSyntaxTextArea?
    editor.updateUndoRedoState();
  }

  void handleDiscourseCopy() {
    new DiscourseFormat(editor, this, false).show();
  }


  void handleHTMLCopy() {
    new DiscourseFormat(editor, this, true).show();
  }

  void handleIndentOutdent(boolean indent) {
    if (indent) {
      Action action = textarea.getActionMap().get(SketchTextAreaEditorKit.rtaIncreaseIndentAction);
      action.actionPerformed(null);
    } else {
      Action action = textarea.getActionMap().get(RSyntaxTextAreaEditorKit.rstaDecreaseIndentAction);
      action.actionPerformed(null);
    }
    // XXX: RSyntaxDocument doesn't fire DocumentListener events, it should be fixed in RSyntaxTextArea?
    editor.updateUndoRedoState();
  }

  void handleUndo() {
    textarea.undoLastAction();
  }
  
  void handleRedo() {
    textarea.redoLastAction();
  }
  
  public String getCurrentKeyword() {
    String text = "";
    if (textarea.getSelectedText() != null)
      text = textarea.getSelectedText().trim();

    try {
      int current = textarea.getCaretPosition();
      int startOffset = 0;
      int endIndex = current;
      String tmp = textarea.getDocument().getText(current, 1);
      // TODO probably a regexp that matches Arduino lang special chars
      // already exists.
      String regexp = "[\\s\\n();\\\\.!='\\[\\]{}]";

      while (!tmp.matches(regexp)) {
        endIndex++;
        tmp = textarea.getDocument().getText(endIndex, 1);
      }
      // For some reason document index start at 2.
      // if( current - start < 2 ) return;

      tmp = "";
      while (!tmp.matches(regexp)) {
        startOffset++;
        if (current - startOffset < 0) {
          tmp = textarea.getDocument().getText(0, 1);
          break;
        } else
          tmp = textarea.getDocument().getText(current - startOffset, 1);
      }
      startOffset--;

      int length = endIndex - current + startOffset;
      text = textarea.getDocument().getText(current - startOffset, length);

    } catch (BadLocationException bl) {
      bl.printStackTrace();
    }
    return text;
  }

  @Override
  public boolean requestFocusInWindow() {
    /** If focus is requested, focus the textarea instead. */
    return textarea.requestFocusInWindow();
  }

}