private void moveUpAndDownPage(boolean _up) {
   int index = tabbedPanel.getSelectedIndex();
   if (index < 0) return;
   Editor page = pageList.get(index);
   if (page == null) return;
   if (_up) {
     if (index == 0) return;
     pageList.removeElementAt(index);
     pageList.insertElementAt(page, index - 1);
     tabbedPanel.removeTabAt(index);
     tabbedPanel.insertTab(
         page.isActive() ? page.getName() : page.getName() + " (D)",
         null,
         page.getComponent(),
         tooltip,
         index - 1);
   } else {
     if (index == (pageList.size() - 1)) return;
     pageList.removeElementAt(index);
     pageList.insertElementAt(page, index + 1);
     tabbedPanel.removeTabAt(index);
     tabbedPanel.insertTab(
         page.isActive() ? page.getName() : page.getName() + " (D)",
         null,
         page.getComponent(),
         tooltip,
         index + 1);
   }
   tabbedPanel.setSelectedComponent(page.getComponent());
   changed = true;
 }
  private void removeFromEditor() {
    Editor editor = mySearchResults.getEditor();
    if (myReplacementBalloon != null) {
      myReplacementBalloon.hide();
    }

    if (editor != null) {

      for (VisibleAreaListener visibleAreaListener : myVisibleAreaListenersToRemove) {
        editor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener);
      }
      myVisibleAreaListenersToRemove.clear();
      Project project = mySearchResults.getProject();
      if (project != null && !project.isDisposed()) {
        for (RangeHighlighter h : myHighlighters) {
          HighlightManager.getInstance(project).removeSegmentHighlighter(editor, h);
        }
        if (myCursorHighlighter != null) {
          HighlightManager.getInstance(project)
              .removeSegmentHighlighter(editor, myCursorHighlighter);
          myCursorHighlighter = null;
        }
      }
      myHighlighters.clear();
      if (myListeningSelection) {
        editor.getSelectionModel().removeSelectionListener(this);
        myListeningSelection = false;
      }
    }
  }
 /** Creates a new page of the given type with the given code */
 protected Editor createPage(String _type, String _name, String _code) {
   Editor page = new CodeEditor(ejs, this);
   page.setName(_name);
   if (_code != null) page.readString(_code);
   else page.clear();
   return page;
 }
 public StringBuffer saveStringBuffer() {
   StringBuffer save = new StringBuffer();
   for (java.util.Enumeration<Editor> e = pageList.elements(); e.hasMoreElements(); ) {
     Editor page = e.nextElement();
     save.append(
         "<"
             + name
             + ".Page>\n"
             + "<Type>"
             + typeOfPage(page)
             + "</Type>\n"
             + "<Name>"
             + page.getName()
             + "</Name>\n"
             + "<Active>"
             + page.isActive()
             + "</Active>\n"
             + "<"
             + contentDelim
             + ">\n");
     save.append(page.saveStringBuffer());
     save.append("</" + contentDelim + ">\n" + "</" + name + ".Page>\n");
   }
   return save;
 }
 public StringBuffer generateCode(int _type, String _info) {
   StringBuffer code = new StringBuffer();
   String genName, passName;
   int index = name.lastIndexOf('.');
   if (index >= 0) genName = name.substring(index + 1).toLowerCase();
   else genName = name.toLowerCase();
   if (_info != null && _info.trim().length() > 0) passName = _info;
   else {
     passName = getName();
     if (passName.startsWith("Osejs.")) passName = passName.substring(6);
   }
   index = 0;
   for (Editor editor : pageList) {
     if (editor instanceof CodeEditor) {
       index++;
       ((CodeEditor) editor).setCodeName(genName + index);
     } else if (editor instanceof EquationEditor) {
       index++;
       ((EquationEditor) editor).setCodeName(genName + index);
     }
     // if (editor.isActive())
     code.append(editor.generateCode(_type, passName));
   }
   return code;
 }
  /**
   * Configures given editor to wrap at given width, assuming characters are of given width
   *
   * @return whether any actual wraps of editor contents were created as a result of turning on soft
   *     wraps
   */
  @TestOnly
  public static boolean configureSoftWraps(
      Editor editor, final int visibleWidth, final int charWidthInPixels) {
    editor.getSettings().setUseSoftWraps(true);
    SoftWrapModelImpl model = (SoftWrapModelImpl) editor.getSoftWrapModel();
    model.setSoftWrapPainter(
        new SoftWrapPainter() {
          @Override
          public int paint(
              @NotNull Graphics g,
              @NotNull SoftWrapDrawingType drawingType,
              int x,
              int y,
              int lineHeight) {
            return charWidthInPixels;
          }

          @Override
          public int getDrawingHorizontalOffset(
              @NotNull Graphics g,
              @NotNull SoftWrapDrawingType drawingType,
              int x,
              int y,
              int lineHeight) {
            return charWidthInPixels;
          }

          @Override
          public int getMinDrawingWidth(@NotNull SoftWrapDrawingType drawingType) {
            return charWidthInPixels;
          }

          @Override
          public boolean canUse() {
            return true;
          }

          @Override
          public void reinit() {}
        });
    model.reinitSettings();

    SoftWrapApplianceManager applianceManager = model.getApplianceManager();
    applianceManager.setWidthProvider(
        new SoftWrapApplianceManager.VisibleAreaWidthProvider() {
          @Override
          public int getVisibleAreaWidth() {
            return visibleWidth;
          }
        });
    model.setEditorTextRepresentationHelper(
        new DefaultEditorTextRepresentationHelper(editor) {
          @Override
          public int charWidth(char c, int fontType) {
            return charWidthInPixels;
          }
        });
    applianceManager.registerSoftWrapIfNecessary();
    return !model.getRegisteredSoftWraps().isEmpty();
  }
Esempio n. 7
0
  /** Add import statements to the current tab for the specified library */
  public void importLibrary(UserLibrary lib) throws IOException {
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    List<String> list = lib.getIncludes();
    if (list == null) {
      File srcFolder = lib.getSrcFolder();
      String[] headers = Base.headerListFromIncludePath(srcFolder);
      list = Arrays.asList(headers);
    }
    if (list.isEmpty()) {
      return;
    }

    // import statements into the main sketch file (code[0])
    // if the current code is a .java file, insert into current
    // if (current.flavor == PDE) {
    SketchFile file = editor.getCurrentTab().getSketchFile();
    if (file.isExtension(Sketch.SKETCH_EXTENSIONS)) editor.selectTab(0);

    // could also scan the text in the file to see if each import
    // statement is already in there, but if the user has the import
    // commented out, then this will be a problem.
    StringBuilder buffer = new StringBuilder();
    for (String aList : list) {
      buffer.append("#include <");
      buffer.append(aList);
      buffer.append(">\n");
    }
    buffer.append('\n');
    buffer.append(editor.getCurrentTab().getText());
    editor.getCurrentTab().setText(buffer.toString());
    editor.getCurrentTab().setSelection(0, 0); // scroll to start
  }
  private void altCommitToOriginal(@NotNull DocumentEvent e) {
    final PsiFile origPsiFile =
        PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument);
    String newText = myNewDocument.getText();
    // prepare guarded blocks
    LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>();
    int count = 0;
    for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) {
      String replacement = o.getUserData(REPLACEMENT_KEY);
      String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement));
      newText =
          newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset());
      replacementMap.put(tempText, replacement);
    }
    // run preformat processors
    final int hostStartOffset = myAltFullRange.getStartOffset();
    myEditor.getCaretModel().moveToOffset(hostStartOffset);
    for (CopyPastePreProcessor preProcessor :
        Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
      newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null);
    }
    myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText);
    // replace temp strings for guarded blocks
    for (String tempText : replacementMap.keySet()) {
      int idx =
          CharArrayUtil.indexOf(
              myOrigDocument.getCharsSequence(),
              tempText,
              hostStartOffset,
              myAltFullRange.getEndOffset());
      myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText));
    }
    // JAVA: fix occasional char literal concatenation
    fixDocumentQuotes(myOrigDocument, hostStartOffset - 1);
    fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset());

    // reformat
    PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument);
    Runnable task =
        () -> {
          try {
            CodeStyleManager.getInstance(myProject)
                .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true);
          } catch (IncorrectOperationException e1) {
            // LOG.error(e);
          }
        };
    DocumentUtil.executeInBulk(myOrigDocument, true, task);

    PsiElement newInjected =
        InjectedLanguageManager.getInstance(myProject)
            .findInjectedElementAt(origPsiFile, hostStartOffset);
    DocumentWindow documentWindow =
        newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected);
    if (documentWindow != null) {
      myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset()));
      myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }
  }
 private void releaseAllEditors() {
   for (final Editor editor : myEditors.values()) {
     if (!editor.isDisposed()) {
       EditorFactory.getInstance().releaseEditor(editor);
     }
   }
   myEditors.clear();
 }
Esempio n. 10
0
  /** Remove a piece of code from the sketch and from the disk. */
  public void handleDeleteCode() throws IOException {
    SketchFile current = editor.getCurrentTab().getSketchFile();
    editor.status.clearState();
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    // if read-only, give an error
    if (isReadOnly(
        BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath())) {
      // if the files are read-only, need to first do a "save as".
      Base.showMessage(
          tr("Sketch is Read-Only"),
          tr(
              "Some files are marked \"read-only\", so you'll\n"
                  + "need to re-save the sketch in another location,\n"
                  + "and try again."));
      return;
    }

    // confirm deletion with user, yes/no
    Object[] options = {tr("OK"), tr("Cancel")};
    String prompt =
        current.isPrimary()
            ? tr("Are you sure you want to delete this sketch?")
            : I18n.format(tr("Are you sure you want to delete \"{0}\"?"), current.getPrettyName());
    int result =
        JOptionPane.showOptionDialog(
            editor,
            prompt,
            tr("Delete"),
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);
    if (result == JOptionPane.YES_OPTION) {
      if (current.isPrimary()) {
        sketch.delete();
        editor.base.handleClose(editor);
      } else {
        // delete the file
        if (!current.delete(sketch.getBuildPath().toPath())) {
          Base.showMessage(
              tr("Couldn't do it"),
              I18n.format(tr("Could not delete \"{0}\"."), current.getFileName()));
          return;
        }

        // just set current tab to the main tab
        editor.selectTab(0);

        // update the tabs
        editor.header.repaint();
      }
    }
  }
 private void renameCurrentPage(String _name) {
   int index = tabbedPanel.getSelectedIndex();
   if (index < 0) return;
   _name = getUniqueName(_name); // Gonzalo 070128
   tabbedPanel.setTitleAt(index, _name);
   Editor page = pageList.get(index);
   page.setName(_name);
   if (!page.isActive()) tabbedPanel.setTitleAt(index, page.getName() + " (D)");
   changed = true;
 }
Esempio n. 12
0
  private void updateCursorHighlighting(boolean scroll) {
    hideBalloon();

    if (myCursorHighlighter != null) {
      HighlightManager.getInstance(mySearchResults.getProject())
          .removeSegmentHighlighter(mySearchResults.getEditor(), myCursorHighlighter);
      myCursorHighlighter = null;
    }

    final FindResult cursor = mySearchResults.getCursor();
    Editor editor = mySearchResults.getEditor();
    SelectionModel selection = editor.getSelectionModel();
    if (cursor != null) {
      Set<RangeHighlighter> dummy = new HashSet<RangeHighlighter>();
      highlightRange(
          cursor, new TextAttributes(null, null, Color.BLACK, EffectType.ROUNDED_BOX, 0), dummy);
      if (!dummy.isEmpty()) {
        myCursorHighlighter = dummy.iterator().next();
      }

      if (scroll) {
        if (mySearchResults.getFindModel().isGlobal()) {
          FoldingModel foldingModel = editor.getFoldingModel();
          final FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions();

          foldingModel.runBatchFoldingOperation(
              new Runnable() {
                @Override
                public void run() {
                  for (FoldRegion region : allRegions) {
                    if (!region.isValid()) continue;
                    if (cursor.intersects(TextRange.create(region))) {
                      region.setExpanded(true);
                    }
                  }
                }
              });
          selection.setSelection(cursor.getStartOffset(), cursor.getEndOffset());

          editor.getCaretModel().moveToOffset(cursor.getEndOffset());
          editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
        } else {
          if (!SearchResults.insideVisibleArea(editor, cursor)) {
            LogicalPosition pos = editor.offsetToLogicalPosition(cursor.getStartOffset());
            editor.getScrollingModel().scrollTo(pos, ScrollType.CENTER);
          }
        }
      }
      editor
          .getScrollingModel()
          .runActionOnScrollingFinished(
              new Runnable() {
                @Override
                public void run() {
                  showReplacementPreview();
                }
              });
    }
  }
 public void showPage(Editor anEditor) {
   for (int i = 0, n = tabbedPanel.getComponentCount(); i < n; i++) {
     if (tabbedPanel.getComponent(i) == anEditor.getComponent()) {
       //        System.out.println ("Found editor "+anEditor.getName()+ " at i="+i);
       ejs.showPanel(defaultHeader);
       cardLayout.show(finalPanel, anEditor.getName());
       tabbedPanel.setSelectedComponent(anEditor.getComponent());
       return;
     }
   }
 }
  /**
   * Emulates pressing <code>Enter</code> at current caret position.
   *
   * @param editor target editor
   * @param project target project
   * @param shifts two-elements array which is expected to be filled with the following info: 1. The
   *     first element holds added lines number; 2. The second element holds added symbols number;
   */
  private static void emulateEnter(
      @NotNull final Editor editor, @NotNull Project project, int[] shifts) {
    final DataContext dataContext = prepareContext(editor.getComponent(), project);
    int caretOffset = editor.getCaretModel().getOffset();
    Document document = editor.getDocument();
    SelectionModel selectionModel = editor.getSelectionModel();
    int startSelectionOffset = 0;
    int endSelectionOffset = 0;
    boolean restoreSelection = selectionModel.hasSelection();
    if (restoreSelection) {
      startSelectionOffset = selectionModel.getSelectionStart();
      endSelectionOffset = selectionModel.getSelectionEnd();
      selectionModel.removeSelection();
    }
    int textLengthBeforeWrap = document.getTextLength();
    int lineCountBeforeWrap = document.getLineCount();

    DataManager.getInstance()
        .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, true);
    CommandProcessor commandProcessor = CommandProcessor.getInstance();
    try {
      Runnable command =
          new Runnable() {
            @Override
            public void run() {
              EditorActionManager.getInstance()
                  .getActionHandler(IdeActions.ACTION_EDITOR_ENTER)
                  .execute(editor, dataContext);
            }
          };
      if (commandProcessor.getCurrentCommand() == null) {
        commandProcessor.executeCommand(editor.getProject(), command, WRAP_LINE_COMMAND_NAME, null);
      } else {
        command.run();
      }
    } finally {
      DataManager.getInstance()
          .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, null);
    }
    int symbolsDiff = document.getTextLength() - textLengthBeforeWrap;
    if (restoreSelection) {
      int newSelectionStart = startSelectionOffset;
      int newSelectionEnd = endSelectionOffset;
      if (startSelectionOffset >= caretOffset) {
        newSelectionStart += symbolsDiff;
      }
      if (endSelectionOffset >= caretOffset) {
        newSelectionEnd += symbolsDiff;
      }
      selectionModel.setSelection(newSelectionStart, newSelectionEnd);
    }
    shifts[0] = document.getLineCount() - lineCountBeforeWrap;
    shifts[1] = symbolsDiff;
  }
 private void copyPage() {
   int index = tabbedPanel.getSelectedIndex();
   if (index < 0) return;
   Editor page = pageList.get(index);
   if (page == null) return;
   addPage(
       typeOfPage(page),
       this.getUniqueName(page.getName()),
       page.saveStringBuffer().toString(),
       true);
   changed = true;
 }
 private void setStructureViewSelectionFromPropertiesFile(@NotNull Editor propertiesFileEditor) {
   int line = propertiesFileEditor.getCaretModel().getLogicalPosition().line;
   Document document = propertiesFileEditor.getDocument();
   if (line >= document.getLineCount()) {
     return;
   }
   final String propertyName = getPropertyName(document, line);
   if (propertyName == null) {
     return;
   }
   setStructureViewSelection(propertyName);
 }
Esempio n. 17
0
  private boolean upload(String suggestedClassName, boolean usingProgrammer) throws Exception {

    UploaderUtils uploaderInstance = new UploaderUtils();
    Uploader uploader = uploaderInstance.getUploaderByPreferences(false);

    boolean success = false;
    do {
      if (uploader.requiresAuthorization()
          && !PreferencesData.has(uploader.getAuthorizationKey())) {
        PasswordAuthorizationDialog dialog =
            new PasswordAuthorizationDialog(
                editor, tr("Type board password to upload a new sketch"));
        dialog.setLocationRelativeTo(editor);
        dialog.setVisible(true);

        if (dialog.isCancelled()) {
          editor.statusNotice(tr("Upload cancelled"));
          return false;
        }

        PreferencesData.set(uploader.getAuthorizationKey(), dialog.getPassword());
      }

      List<String> warningsAccumulator = new LinkedList<>();
      try {
        success =
            uploaderInstance.upload(
                sketch, uploader, suggestedClassName, usingProgrammer, false, warningsAccumulator);
      } finally {
        if (uploader.requiresAuthorization() && !success) {
          PreferencesData.remove(uploader.getAuthorizationKey());
        }
      }

      for (String warning : warningsAccumulator) {
        System.out.print(tr("Warning"));
        System.out.print(": ");
        System.out.println(warning);
      }

    } while (uploader.requiresAuthorization() && !success);

    if (!success) {
      String errorMessage = uploader.getFailureMessage();
      if (errorMessage.equals("")) {
        errorMessage = tr("An error occurred while uploading the sketch");
      }
      editor.statusError(errorMessage);
    }

    return success;
  }
 private int widestEditor(final List<Editor> editors) {
   int maxWidth = 0;
   int idxMax = 0;
   for (int i = 0; i < editors.size(); i++) {
     Editor editor = editors.get(i);
     final int wholeWidth = editor.getContentComponent().getWidth();
     if (wholeWidth > maxWidth) {
       maxWidth = wholeWidth;
       idxMax = i;
     }
   }
   return idxMax;
 }
Esempio n. 19
0
  public void mousePressed(MouseEvent e) {
    
    // jdf
    if (!isEnabled())
      return;
    
    final int x = e.getX();
    final int y = e.getY();

    int sel = findSelection(x, y);
    ///if (sel == -1) return false;
    if (sel == -1) return;
    currentRollover = -1;

    switch (sel) {
    case RUN:
      editor.handleRun(e.isShiftDown());
      break;

//    case STOP:
//      editor.handleStop();
//      break;
//
    case OPEN:
      popup = menu.getPopupMenu();
      popup.show(EditorToolbar.this, x, y);
      break;

    case NEW:
      if (shiftPressed) {
        editor.base.handleNew();
      } else {
      editor.base.handleNewReplace();
      }
      break;

    case SAVE:
      editor.handleSave(false);
      break;

    case EXPORT:
      boolean t = e.isControlDown();
      editor.handleExport(e.isShiftDown(),autoOpenSerialMonitor ? !t : t); // Control is down if autoOpenSerialMonitor is true in preferences
      break;

    case SERIAL:
      editor.handleSerial();
      handleMouse(e);
      break;
    }
  }
    private void recalculateMaxValues() {
      myIdxLeft = widestEditor(myLeftEditors);
      final Editor leftEditor = myLeftEditors.get(myIdxLeft);
      final int wholeWidth = leftEditor.getContentComponent().getWidth();
      final Rectangle va = leftEditor.getScrollingModel().getVisibleArea();
      final int visibleLeft = leftEditor.xyToVisualPosition(new Point(va.width, 0)).column;

      myMaxColumnsLeft = (int) (visibleLeft * ((double) wholeWidth / va.getWidth()));

      myIdxRight = widestEditor(myRightEditors);
      final Editor rightEditor = myRightEditors.get(myIdxRight);
      final int wholeWidthRight = rightEditor.getContentComponent().getWidth();
      final Rectangle vaRight = rightEditor.getScrollingModel().getVisibleArea();
      final int visibleRight = rightEditor.xyToVisualPosition(new Point(va.width, 0)).column;

      myMaxColumnsRight = (int) (visibleRight * ((double) wholeWidthRight / vaRight.getWidth()));

      myByLeft = !(myMaxColumnsLeft <= visibleLeft);
      if (!myByLeft) {
        // check right editor
        if (myLeftScroll.getVisibleAmount() != visibleRight) {
          myLeftScroll.setVisibleAmount(visibleRight);
        }
        myLeftScroll.setMaximum(myMaxColumnsRight);
      } else {
        if (myLeftScroll.getVisibleAmount() != visibleLeft) {
          myLeftScroll.setVisibleAmount(visibleLeft);
        }
        myLeftScroll.setMaximum(myMaxColumnsLeft);
      }
    }
  private void setPropertiesFileSelectionFromStructureView(@NotNull Editor propertiesFileEditor) {
    String selectedPropertyName = getSelectedPropertyName();
    if (selectedPropertyName == null) {
      return;
    }

    Document document = propertiesFileEditor.getDocument();
    for (int i = 0; i < document.getLineCount(); i++) {
      String propertyName = getPropertyName(document, i);
      if (selectedPropertyName.equals(propertyName)) {
        propertiesFileEditor.getCaretModel().moveToLogicalPosition(new LogicalPosition(i, 0));
        return;
      }
    }
  }
Esempio n. 22
0
 /** Add an assignment to the Editor for processing. */
 public void addAssignment(Assignment a) throws Exception {
   try {
     editor.addAssignment(a);
   } catch (Exception e) {
     throw (e);
   }
 }
 public static void setEditorVisibleSize(Editor editor, int widthInChars, int heightInChars) {
   Dimension size =
       new Dimension(
           widthInChars * EditorUtil.getSpaceWidth(Font.PLAIN, editor),
           heightInChars * editor.getLineHeight());
   ((EditorEx) editor).getScrollPane().getViewport().setExtentSize(size);
 }
 private void scrollMain(int scrollPosCorrected, final List<ScrollingModel> models) {
   final int pointX =
       (int) myEditor.logicalPositionToXY(new LogicalPosition(0, scrollPosCorrected)).getX();
   for (ScrollingModel model : models) {
     model.scrollHorizontally(pointX);
   }
 }
Esempio n. 25
0
  /** Handler for the Rename Code menu option. */
  public void handleRenameCode() {
    SketchFile current = editor.getCurrentTab().getSketchFile();

    editor.status.clearState();
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    if (current.isPrimary() && editor.untitled) {
      Base.showMessage(
          tr("Sketch is Untitled"),
          tr("How about saving the sketch first \n" + "before trying to rename it?"));
      return;
    }

    // if read-only, give an error
    if (isReadOnly(
        BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath())) {
      // if the files are read-only, need to first do a "save as".
      Base.showMessage(
          tr("Sketch is Read-Only"),
          tr(
              "Some files are marked \"read-only\", so you'll\n"
                  + "need to re-save the sketch in another location,\n"
                  + "and try again."));
      return;
    }

    // ask for new name of file (internal to window)
    // TODO maybe just popup a text area?
    renamingCode = true;
    String prompt = current.isPrimary() ? "New name for sketch:" : "New name for file:";
    String oldName = current.getPrettyName();
    editor.status.edit(prompt, oldName);
  }
Esempio n. 26
0
  private static void renderHull(PtEntry pt) {
    Inf inf = Inf.create();
    int count = 30;
    PtEntry ptStart = pt;
    do {
      inf.update();
      if (pt.prev(true) != null) {
        boolean valley = false;

        valley =
            (pt.prev(true).source() == pt.source() && pt.prev(true).orig().next(true) != pt.orig());

        V.pushColor(MyColor.cBLUE);
        V.pushStroke(valley ? STRK_RUBBERBAND : STRK_THICK);
        V.drawLine(pt.prev(true), pt);
        V.pop(2);
      }
      V.pushColor(MyColor.cDARKGREEN);
      V.mark(pt, MARK_DISC, .6);
      V.pop();
      if (Editor.withLabels(true)) {
        StringBuilder sb = new StringBuilder();
        sb.append(" #" + pt.id());
        if (pt.source() != null) sb.append(" <" + pt.source() + ">");

        V.pushScale(.6);
        V.draw(sb.toString(), MyMath.ptOnCircle(pt, MyMath.radians(30), 3), TX_FRAME | TX_BGND);
        V.pop();
      }
      pt = pt.next(true);
      if (count-- == 0) V.draw("too many points rendering!", 50, 50, TX_CLAMP);
    } while (pt != ptStart && count > 0);
  }
Esempio n. 27
0
 /** Add an assignment to a specific client for processing. */
 public void addAssignment(int ClientID, Assignment a) throws Exception {
   try {
     editor.addAssignment(ClientID, a);
   } catch (Exception e) {
     throw (e);
   }
 }
  private void updateTextElement(final PsiElement elt) {
    final String newText = getNewText(elt);
    if (newText == null || Comparing.strEqual(newText, myEditor.getDocument().getText())) return;
    CommandProcessor.getInstance()
        .runUndoTransparentAction(
            new Runnable() {
              @Override
              public void run() {
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            Document fragmentDoc = myEditor.getDocument();
                            fragmentDoc.setReadOnly(false);

                            fragmentDoc.replaceString(0, fragmentDoc.getTextLength(), newText);
                            fragmentDoc.setReadOnly(true);
                            myEditor.getCaretModel().moveToOffset(0);
                            myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
                          }
                        });
              }
            });
  }
  @Override
  public void paintComponent(Graphics g) {
    if (Editor.get() == null) return;

    TileMap map = Editor.get().getTileMap();

    TextureManager textureManager = Editor.get().getWindow().getTextureManager();

    clear(g, getWidth() / Window.TEXTURES_SIZE + 1, getHeight() / Window.TEXTURES_SIZE + 1, map);

    if (map != null) {
      for (int x = 0; x < map.getWidth(); x++) {
        for (int y = 0; y < map.getHeight(); y++) {
          Tile tile = map.getTile(x, y);

          if (!tile.getTexture().equals(Texture.AIR))
            textureManager.drawTexture(
                g,
                tile.getTexture(),
                x * Window.TEXTURES_SIZE + OFFSET * Window.TEXTURES_SIZE,
                y * Window.TEXTURES_SIZE + OFFSET * Window.TEXTURES_SIZE,
                Window.TEXTURES_SIZE);
        }
      }

      g.setColor(Color.WHITE);
      g.drawRect(
          (int) (map.getSpawnX() * Window.TEXTURES_SIZE) + OFFSET * Window.TEXTURES_SIZE,
          (int) (map.getSpawnY() * Window.TEXTURES_SIZE)
              + OFFSET * Window.TEXTURES_SIZE
              - Window.TEXTURES_SIZE * 2,
          Window.TEXTURES_SIZE,
          Window.TEXTURES_SIZE * 2);
      g.drawString(
          "SPAWN",
          (int) (map.getSpawnX() * Window.TEXTURES_SIZE) + OFFSET * Window.TEXTURES_SIZE - 1,
          (int) (map.getSpawnY() * Window.TEXTURES_SIZE) + OFFSET * Window.TEXTURES_SIZE);
    }

    g.setColor(Color.RED);

    g.drawLine(selectX * 32 - 1, selectY * 32 - 1, selectX * 32 + 32, selectY * 32 - 1);
    g.drawLine(selectX * 32 - 1, selectY * 32 - 1, selectX * 32 - 1, selectY * 32 + 32);
    g.drawLine(selectX * 32 + 32, selectY * 32 - 1, selectX * 32 + 32, selectY * 32 + 32);
    g.drawLine(selectX * 32 - 1, selectY * 32 + 32, selectX * 32 + 32, selectY * 32 + 32);
    // g.fillRect(100, 100, 200, 200);
  }
 public void nextPanel(final BeforeAfter<ShiftedSimpleContent> diff, final DiffPanel diffPanel) {
   final Editor editor1 = ((DiffPanelImpl) diffPanel).getEditor1();
   myLeftModels.add(editor1.getScrollingModel());
   final Editor editor2 = ((DiffPanelImpl) diffPanel).getEditor2();
   myRightModels.add(editor2.getScrollingModel());
   if (myEditor == null) {
     myEditor = editor1;
   }
   myLeftEditors.add(editor1);
   myRightEditors.add(editor2);
   ((EditorEx) editor1).setHorizontalScrollbarVisible(false);
   ((EditorEx) editor1).setVerticalScrollbarVisible(false);
   ((EditorEx) editor1).getScrollPane().setWheelScrollingEnabled(false);
   ((EditorEx) editor2).setHorizontalScrollbarVisible(false);
   ((EditorEx) editor2).setVerticalScrollbarVisible(false);
   ((EditorEx) editor2).getScrollPane().setWheelScrollingEnabled(false);
 }