Пример #1
0
  /** User clicks Finish */
  @Override
  public boolean performFinish() {
    try {
      // Create file object
      IFile file = doCreateNew(new NullProgressMonitor());
      if (file == null) {
        // that's ok, as it just didn't create a file (but maybe a folder)...
        return true;
      }

      // Scroll to file in package explorer
      BasicNewResourceWizard.selectAndReveal(file, workbench.getActiveWorkbenchWindow());

      // Open editor on new file.
      IWorkbenchWindow dw = workbench.getActiveWorkbenchWindow();
      try {
        if (dw != null) {
          IWorkbenchPage page = dw.getActivePage();
          if (page != null) {
            IEditorPart openEditor = IDE.openEditor(page, file, true);
            afterEditorCreated(openEditor);
          }
        }
      } catch (PartInitException e) {
        Log.log(e);
        return false;
      }
    } catch (Exception e) {
      Log.log(e);
      return false;
    }
    return true;
  }
Пример #2
0
  @Override
  protected String perform(IAction action, IProgressMonitor monitor) throws Exception {
    try {
      final PyHierarchyView view;
      IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
      IWorkbenchPage page = workbenchWindow.getActivePage();
      view =
          (PyHierarchyView)
              page.showView(
                  "com.python.pydev.ui.hierarchy.PyHierarchyView",
                  null,
                  IWorkbenchPage.VIEW_VISIBLE);

      ProgressMonitorDialog monitorDialog =
          new AsynchronousProgressMonitorDialog(EditorUtils.getShell());
      try {
        IRunnableWithProgress operation =
            new IRunnableWithProgress() {

              public void run(final IProgressMonitor monitor)
                  throws InvocationTargetException, InterruptedException {
                try {
                  final HierarchyNodeModel model;

                  // set whatever is needed for the hierarchy
                  IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
                  if (pyRefactoring instanceof IPyRefactoring2) {
                    RefactoringRequest refactoringRequest = getRefactoringRequest(monitor);
                    IPyRefactoring2 r2 = (IPyRefactoring2) pyRefactoring;
                    model = r2.findClassHierarchy(refactoringRequest, false);

                    if (monitor.isCanceled()) {
                      return;
                    }
                    Runnable r =
                        new Runnable() {
                          public void run() {
                            if (!monitor.isCanceled()) {
                              view.setHierarchy(model);
                            }
                          }
                        };
                    Display.getDefault().asyncExec(r);
                  }
                } catch (Exception e) {
                  Log.log(e);
                }
              }
            };

        boolean fork = true;
        monitorDialog.run(fork, true, operation);
      } catch (Throwable e) {
        Log.log(e);
      }
    } catch (Exception e) {
      Log.log(e);
    }
    return "";
  }
Пример #3
0
  /**
   * Formats the given selection
   *
   * @see IFormatter
   */
  public void formatSelection(
      IDocument doc, int[] regionsForSave, IPyEdit edit, PySelection ps, FormatStd formatStd) {
    //        Formatter formatter = new Formatter();
    //        formatter.formatSelection(doc, startLine, endLineIndex, edit, ps);

    @SuppressWarnings({"rawtypes", "unchecked"})
    List<Tuple3<Integer, Integer, String>> replaces = new ArrayList();

    String docContents = doc.get();
    String delimiter = PySelection.getDelimiter(doc);
    IDocument formatted;
    try {
      formatted = new Document(formatAll(formatStd, true, docContents, delimiter));
    } catch (SyntaxErrorException e) {
      return;
    }
    // Actually replace the formatted lines: in our formatting, lines don't change, so, this is OK
    // :)
    try {
      for (int i : regionsForSave) {
        IRegion r = doc.getLineInformation(i);
        int iStart = r.getOffset();
        int iEnd = r.getOffset() + r.getLength();

        String line = PySelection.getLine(formatted, i);
        replaces.add(new Tuple3<Integer, Integer, String>(iStart, iEnd - iStart, line));
      }

    } catch (BadLocationException e) {
      Log.log(e);
      return;
    }

    // Apply the formatting from bottom to top (so that the indexes are still valid).
    Collections.reverse(replaces);
    for (Tuple3<Integer, Integer, String> tup : replaces) {
      try {
        doc.replace(tup.o1, tup.o2, tup.o3);
      } catch (BadLocationException e) {
        Log.log(e);
      }
    }

    if (formatStd.addNewLineAtEndOfFile) {
      try {
        int len = doc.getLength();
        if (len > 0) {
          char lastChar = doc.getChar(len - 1);
          if (lastChar != '\r' && lastChar != '\n') {
            doc.replace(len, 0, PySelection.getDelimiter(doc));
          }
        }
      } catch (Throwable e) {
        Log.log(e);
      }
    }
  }
Пример #4
0
  protected void discoverDefaultVersion(final String projectType, final String projectInterpreter) {
    defaultVersion =
        DJANGO_14; // It should be discovered below, but if not found for some reason, this will be
                   // the default.

    SystemPythonNature nature;
    try {
      final int interpreterType = PythonNature.getInterpreterTypeFromVersion(projectType);
      IInterpreterManager interpreterManagerFromType =
          PydevPlugin.getInterpreterManagerFromType(interpreterType);
      IInterpreterInfo interpreterInfo;
      if (IPythonNature.DEFAULT_INTERPRETER.equals(projectInterpreter)) {
        interpreterInfo = interpreterManagerFromType.getDefaultInterpreterInfo(false);

      } else {
        interpreterInfo = interpreterManagerFromType.getInterpreterInfo(projectInterpreter, null);
      }
      nature = new SystemPythonNature(interpreterManagerFromType, interpreterInfo);
      AbstractRunner runner = UniversalRunner.getRunner(nature);

      Tuple<String, String> output =
          runner.runCodeAndGetOutput(
              GET_DJANGO_VERSION, new String[] {}, null, new NullProgressMonitor());

      String err = output.o2.trim();
      String out = output.o1.trim();
      if (err.length() > 0) {
        Log.log("Error attempting to determine Django version: " + err);

      } else {
        // System.out.println("Gotten version: "+out);
        if (out.startsWith("0.")) {
          setDefaultVersion(DjangoSettingsPage.DJANGO_11_OR_EARLIER);

        } else if (out.startsWith("1.")) {
          out = out.substring(2);
          if (out.startsWith("0") || out.startsWith("1")) {
            setDefaultVersion(DjangoSettingsPage.DJANGO_11_OR_EARLIER);

          } else if (out.startsWith("2") || out.startsWith("3")) {
            setDefaultVersion(DjangoSettingsPage.DJANGO_12_OR_13);

          } else {
            // Later version
            setDefaultVersion(DjangoSettingsPage.DJANGO_14);
          }
        }
      }

    } catch (Exception e) {
      Log.log("Unable to determine Django version.", e);
    }
  }
Пример #5
0
  /** Utility routine to remove a PythonNature from a project. */
  public static synchronized void removeNature(IProject project, IProgressMonitor monitor)
      throws CoreException {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }

    PythonNature nature = PythonNature.getPythonNature(project);
    if (nature == null) {
      return;
    }

    try {
      // we have to set the nature store to stop listening changes to .pydevproject
      nature.pythonNatureStore.setProject(null);
    } catch (Exception e) {
      Log.log(e);
    }

    try {
      // we have to remove the project from the pythonpath nature too...
      nature.pythonPathNature.setProject(null, null);
    } catch (Exception e) {
      Log.log(e);
    }

    // notify listeners that the pythonpath nature is now empty for this project
    try {
      PythonNatureListenersManager.notifyPythonPathRebuilt(project, null);
    } catch (Exception e) {
      Log.log(e);
    }

    try {
      // actually remove the pydev configurations
      IResource member = project.findMember(".pydevproject");
      if (member != null) {
        member.delete(true, null);
      }
    } catch (CoreException e) {
      Log.log(e);
    }

    // and finally... remove the nature

    IProjectDescription description = project.getDescription();
    List<String> natures = new ArrayList<String>(Arrays.asList(description.getNatureIds()));
    natures.remove(PYTHON_NATURE_ID);
    description.setNatureIds(natures.toArray(new String[natures.size()]));
    project.setDescription(description, monitor);
  }
  /**
   * Launches the python process.
   *
   * <p>Modelled after Ant & Java runners see WorkbenchLaunchConfigurationDelegate::launch
   */
  public void launch(
      ILaunchConfiguration conf, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {

    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }

    monitor.beginTask("Preparing configuration", 3);

    try {
      PythonRunnerConfig runConfig =
          new PythonRunnerConfig(conf, mode, getRunnerConfigRun(conf, mode, launch));

      monitor.worked(1);
      try {
        PythonRunner.run(runConfig, launch, monitor);
      } catch (IOException e) {
        Log.log(e);
        finishLaunchWithError(launch);
        throw new CoreException(
            PydevDebugPlugin.makeStatus(
                IStatus.ERROR, "Unexpected IO Exception in Pydev debugger", null));
      }
    } catch (final InvalidRunException e) {
      handleError(launch, e);
    } catch (final MisconfigurationException e) {
      handleError(launch, e);
    }
  }
Пример #7
0
  /**
   * THIS CODE IS COPIED FROM org.eclipse.debug.internal.core.LaunchManager
   *
   * <p>changed so that we always set the PYTHONPATH in the environment
   *
   * @return the system environment with the PYTHONPATH env variable added for a given project (if
   *     it is null, return it with the default PYTHONPATH added).
   */
  public static String[] getEnvironment(
      IPythonNature pythonNature, IInterpreterInfo interpreter, IInterpreterManager manager)
      throws CoreException {
    String[] env;

    String pythonPathEnvStr = "";
    try {

      if (interpreter != null) { // check if we have a default interpreter.
        pythonPathEnvStr = makePythonPathEnvString(pythonNature, interpreter, manager);
      }
      env = createEnvWithPythonpath(pythonPathEnvStr, pythonNature, manager);

    } catch (Exception e) {
      Log.log(e);
      // We cannot get it. Log it and keep with the default.
      env = getDefaultSystemEnvAsArray(pythonNature);
    }

    if (interpreter != null) {
      env = interpreter.updateEnv(env);
    }

    return env;
  }
Пример #8
0
    @Override
    public void run() {
      try {
        PySelection selection = new PySelection(edit);

        ScriptConsole console = ScriptConsole.getActiveScriptConsole();

        if (console == null) {
          // if no console is available, create it (if possible).
          PydevConsoleFactory factory = new PydevConsoleFactory();
          String cmd = null;

          // Check if the current selection should be sent to the editor.
          if (InteractiveConsolePrefs.getSendCommandOnCreationFromEditor()) {
            cmd = getCommandToSend(edit, selection);
            if (cmd != null) {
              cmd = "\n" + cmd;
            }
          }
          factory.createConsole(cmd);

        } else {
          if (console instanceof ScriptConsole) {
            // ok, console available
            sendCommandToConsole(selection, console, this.edit);
          }
        }
      } catch (Exception e) {
        Log.log(e);
      }
    }
  /**
   * Creates the dialog according to the Eclipse version we have (on 3.2, the old API is used)
   *
   * @param pythonNatures
   */
  public static SelectionDialog create(
      Shell shell, List<AbstractAdditionalTokensInfo> additionalInfo, String selectedText) {
    boolean expectedError = true;
    try {
      GlobalsTwoPanelElementSelector2 newDialog =
          new GlobalsTwoPanelElementSelector2(shell, true, selectedText);
      // If we were able to instance it, the error is no longer expected!
      expectedError = false;

      newDialog.setElements(additionalInfo);
      return newDialog;
    } catch (Throwable e) {
      // That's OK: it's only available for Eclipse 3.3 onwards.
      if (expectedError) {
        Log.log(e);
      }
    }

    // If it got here, we were unable to create the new dialog (show the old -- compatible with 3.2)
    GlobalsTwoPaneElementSelector dialog;
    dialog = new GlobalsTwoPaneElementSelector(shell);
    dialog.setMessage("Filter");
    if (selectedText != null && selectedText.length() > 0) {
      dialog.setFilter(selectedText);
    }

    List<IInfo> lst = new ArrayList<IInfo>();

    for (AbstractAdditionalTokensInfo info : additionalInfo) {
      lst.addAll(info.getAllTokens());
    }

    dialog.setElements(lst.toArray());
    return dialog;
  }
Пример #10
0
  /** @throws CoreException */
  private void restartShell() throws CoreException {
    synchronized (ioLock) {
      if (!isInRestart) { // we don't want to end up in a loop here...
        isInRestart = true;
        try {
          if (finishedForGood) {
            throw new RuntimeException(
                "Shells are already finished for good, so, it is an invalid state to try to restart a new shell.");
          }

          try {
            this.endIt();
          } catch (Exception e) {
          }
          try {
            synchronized (this) {
              this.startIt(shellInterpreter);
            }
          } catch (Exception e) {
            Log.log(IStatus.ERROR, "ERROR restarting shell.", e);
          }
        } finally {
          isInRestart = false;
        }
      }
    }
  }
Пример #11
0
 /** IConsole: Add a link to the console */
 public void addLink(IHyperlink link, int offset, int length) {
   try {
     super.addHyperlink(link, offset, length);
   } catch (BadLocationException e) {
     Log.log(e);
   }
 }
  public void checkAllNow() {
    // Add all to be tracked
    Map<IInterpreterManager, Map<String, IInterpreterInfo>> addedToTrack = job.addAllToTrack();

    // remove from the preferences any ignore the user had set previously
    Set<Entry<IInterpreterManager, Map<String, IInterpreterInfo>>> entrySet =
        addedToTrack.entrySet();
    IPreferenceStore preferences = PydevPrefs.getPreferences();
    for (Entry<IInterpreterManager, Map<String, IInterpreterInfo>> entry : entrySet) {
      Set<Entry<String, IInterpreterInfo>> entrySet2 = entry.getValue().entrySet();
      for (Entry<String, IInterpreterInfo> entry2 : entrySet2) {
        String key = SynchSystemModulesManager.createKeyForInfo(entry2.getValue());
        preferences.setValue(key, "");
      }
    }
    if (preferences instanceof IPersistentPreferenceStore) {
      IPersistentPreferenceStore iPersistentPreferenceStore =
          (IPersistentPreferenceStore) preferences;
      try {
        iPersistentPreferenceStore.save();
      } catch (IOException e) {
        Log.log(e);
      }
    }

    // schedule changes to be executed.
    job.scheduleLater(0);
  }
Пример #13
0
  /** @return a set with the currently opened files in the PyEdit editors. */
  public static Set<IFile> getOpenFiles() {
    Set<IFile> ret = new HashSet<IFile>();
    IWorkbenchWindow activeWorkbenchWindow = EditorUtils.getActiveWorkbenchWindow();
    if (activeWorkbenchWindow == null) {
      return ret;
    }

    IWorkbenchPage[] pages = activeWorkbenchWindow.getPages();
    for (int i = 0; i < pages.length; i++) {
      IEditorReference[] editorReferences = pages[i].getEditorReferences();

      for (int j = 0; j < editorReferences.length; j++) {
        IEditorReference iEditorReference = editorReferences[j];
        if (!PyEdit.EDITOR_ID.equals(iEditorReference.getId())) {
          continue; // Only PyDev editors...
        }
        try {
          IEditorInput editorInput = iEditorReference.getEditorInput();
          if (editorInput == null) {
            continue;
          }
          IFile file = (IFile) editorInput.getAdapter(IFile.class);
          if (file != null) {
            ret.add(file);
          }
        } catch (Exception e1) {
          Log.log(e1);
        }
      }
    }
    return ret;
  }
Пример #14
0
 public void popTemporaryModule(String moduleName) {
   synchronized (lockTemporaryModules) {
     if (temporaryModules == null) {
       return;
     }
     FastStack<IModule> stack = temporaryModules.get(moduleName);
     if (stack == null) {
       // try to make it null when possible
       temporaryModules = null;
       return;
     }
     try {
       stack.pop();
       if (stack.size() == 0) {
         temporaryModules.remove(moduleName);
       }
       if (temporaryModules.size() == 0) {
         // try to make it null when possible (so that we don't have to sync later on)
         temporaryModules = null;
       }
     } catch (Exception e) {
       Log.log(e);
     }
   }
 }
 protected void validatePage() {
   try {
     if (textProject != null) {
       if (checkError(checkValidProject(textProject.getText()))) {
         return;
       }
     }
     if (textSourceFolder != null) {
       if (checkError(checkValidSourceFolder(textSourceFolder.getText()))) {
         return;
       }
     }
     if (textPackage != null) {
       if (checkError(checkValidPackage(textPackage.getText()))) {
         return;
       }
     }
     if (textName != null) {
       if (checkError(checkValidName(textName.getText()))) {
         return;
       }
     }
     if (checkAdditionalErrors()) {
       return;
     }
     setErrorMessage(null);
     setMessage(getDescription());
     setPageComplete(true);
   } catch (Exception e) {
     Log.log(e);
     setErrorMessage("Error while validating page:" + e.getMessage());
     setPageComplete(false);
   }
 }
Пример #16
0
  private boolean isDjangoHandledModule(
      String djangoModulesHandling, IEditorInput input, String lastSegment) {
    boolean handled = false;
    if (djangoModulesHandling
            == PyTitlePreferencesPage.TITLE_EDITOR_DJANGO_MODULES_SHOW_PARENT_AND_DECORATE
        || djangoModulesHandling == PyTitlePreferencesPage.TITLE_EDITOR_DJANGO_MODULES_DECORATE) {

      if (input instanceof IFileEditorInput) {
        IFileEditorInput iFileEditorInput = (IFileEditorInput) input;
        IFile file = iFileEditorInput.getFile();
        IProject project = file.getProject();
        try {
          if (project.hasNature(PythonNature.DJANGO_NATURE_ID)) {
            if (PyTitlePreferencesPage.isDjangoModuleToDecorate(lastSegment)) {
              // remove the module name.
              handled = true;
            }
          }
        } catch (CoreException e) {
          Log.log(e);
        }
      }
    }
    return handled;
  }
Пример #17
0
  public static Object getAdapterFromActualObject(IResource actualObject2, Class adapter) {
    if (IProject.class.equals(adapter)
        || IResource.class.equals(adapter)
        || IFolder.class.equals(adapter)
        || IContainer.class.equals(adapter)
        || IFile.class.equals(adapter)
        || ResourceMapping.class.equals(adapter)
        || IFileStore.class.equals(adapter)) {
      return actualObject2.getAdapter(adapter);
    }

    try {
      if (IWatchExpressionFactoryAdapter2.class.equals(adapter)) {
        return actualObject2.getAdapter(adapter);
      }
    } catch (Throwable e) {
      // Ignore (not available in eclipse 3.2)
    }

    if (IDeferredWorkbenchAdapter.class.equals(adapter)
        || IWorkbenchAdapter2.class.equals(adapter)
        || IWorkbenchAdapter.class.equals(adapter)) {
      return null;
    }
    synchronized (lock) {
      if (!logged.contains(adapter)) {
        logged.add(adapter);
        // Only log once per session.
        Log.logInfo("Did not expect adapter request: " + adapter);
      }
    }
    return null;
  }
  public boolean beforePerformArrangeImports(PySelection ps, PyEdit edit, IFile f) {
    int oldSelection = ps.getRegion().getOffset();

    IDocumentExtension4 doc = (IDocumentExtension4) ps.getDoc();
    if (edit != null) {
      if (!ensureParsed(edit)) {
        return true;
      }
      // Check that the editor time is actually the same as the document time.
      long docTime = doc.getModificationStamp();

      if (docTime != edit.getAstModificationTimeStamp()) {
        return true;
      }
      ErrorDescription errorDescription = edit.getErrorDescription();
      if (errorDescription != null) {
        return true; // Don't remove unused imports if we have syntax errors.
      }
    }

    try {
      findAndDeleteUnusedImports(ps, edit, doc, f);
    } catch (Exception e) {
      Log.log(e);
    }
    ps.setSelection(oldSelection, oldSelection);
    return true;
  }
Пример #19
0
  @Override
  public void createPartControl(Composite parent) {
    super.createPartControl(parent);
    try {
      ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();

      fProjectionSupport =
          new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
      fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error");
      fProjectionSupport.addSummarizableAnnotationType(
          "org.eclipse.ui.workbench.texteditor.warning");
      fProjectionSupport.setHoverControlCreator(
          new IInformationControlCreator() {
            @Override
            public IInformationControl createInformationControl(Shell shell) {
              return new DefaultInformationControl(shell);
            }
          });
      fProjectionSupport.install();

      if (isFoldingEnabled()) {
        projectionViewer.doOperation(ProjectionViewer.TOGGLE);
      }
    } catch (Exception e) {
      Log.log(e);
    }
  }
Пример #20
0
  /**
   * @param process process from where the output should be gotten
   * @param executionString string to execute (only for errors)
   * @param monitor monitor for giving progress
   * @return a tuple with the output of stdout and stderr
   */
  public static Tuple<String, String> getProcessOutput(
      Process process, String executionString, IProgressMonitor monitor, String encoding) {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    if (process != null) {

      try {
        process.getOutputStream().close(); // we won't write to it...
      } catch (IOException e2) {
      }

      monitor.setTaskName("Reading output...");
      monitor.worked(5);
      // No need to synchronize as we'll waitFor() the process before getting the contents.
      ThreadStreamReader std = new ThreadStreamReader(process.getInputStream(), false, encoding);
      ThreadStreamReader err = new ThreadStreamReader(process.getErrorStream(), false, encoding);

      std.start();
      err.start();

      boolean interrupted = true;
      while (interrupted) {
        interrupted = false;
        try {
          monitor.setTaskName("Waiting for process to finish.");
          monitor.worked(5);
          process.waitFor(); // wait until the process completion.
        } catch (InterruptedException e1) {
          interrupted = true;
        }
      }

      try {
        // just to see if we get something after the process finishes (and let the other threads
        // run).
        Object sync = new Object();
        synchronized (sync) {
          sync.wait(50);
        }
      } catch (Exception e) {
        // ignore
      }
      return new Tuple<String, String>(std.getContents(), err.getContents());

    } else {
      try {
        throw new CoreException(
            PydevPlugin.makeStatus(
                IStatus.ERROR,
                "Error creating process - got null process(" + executionString + ")",
                new Exception("Error creating process - got null process.")));
      } catch (CoreException e) {
        Log.log(IStatus.ERROR, e.getMessage(), e);
      }
    }
    return new Tuple<String, String>(
        "", "Error creating process - got null process(" + executionString + ")"); // no output
  }
 @Override
 public void postCommand(AbstractDebuggerCommand cmd) {
   try {
     scriptConsoleCommunication.postCommand(cmd);
   } catch (Exception e) {
     Log.log(e);
   }
 }
Пример #22
0
 /*
  * Beep...humm... yeah....beep....ehehheheh
  */
 protected static void beep(Exception e) {
   try {
     PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getDisplay().beep();
   } catch (Throwable x) {
     // ignore, workbench has still not been created
   }
   Log.log(e);
 }
Пример #23
0
 private static void dbg(String string, int priority) {
   if (priority <= DEBUG_SHELL) {
     System.out.println(string);
   }
   if (DebugSettings.DEBUG_CODE_COMPLETION) {
     Log.toLogFile(string, AbstractShell.class);
   }
 }
Пример #24
0
  /**
   * @param markOccurrencesRequest
   * @return true if the annotations were removed and added without any problems and false otherwise
   */
  @Override
  protected synchronized Map<Annotation, Position> getAnnotationsToAddAsMap(
      final BaseEditor baseEditor,
      IAnnotationModel annotationModel,
      MarkOccurrencesRequest markOccurrencesRequest,
      IProgressMonitor monitor)
      throws BadLocationException {
    PyEdit pyEdit = (PyEdit) baseEditor;
    PySourceViewer viewer = pyEdit.getPySourceViewer();
    if (viewer == null || monitor.isCanceled()) {
      return null;
    }
    if (viewer.getIsInToggleCompletionStyle() || monitor.isCanceled()) {
      return null;
    }

    PyMarkOccurrencesRequest pyMarkOccurrencesRequest =
        (PyMarkOccurrencesRequest) markOccurrencesRequest;
    Set<ASTEntry> occurrences = pyMarkOccurrencesRequest.getOccurrences();
    if (occurrences == null) {
      if (DEBUG) {
        System.out.println("Occurrences == null");
      }
      return null;
    }

    IDocument doc = pyEdit.getDocument();
    Map<Annotation, Position> toAddAsMap = new HashMap<Annotation, Position>();
    boolean markOccurrencesInStrings = MarkOccurrencesPreferencesPage.useMarkOccurrencesInStrings();

    // get the annotations to add
    for (ASTEntry entry : occurrences) {
      if (!markOccurrencesInStrings) {
        if (entry.node instanceof Name) {
          Name name = (Name) entry.node;
          if (name.ctx == Name.Artificial) {
            continue;
          }
        }
      }

      SimpleNode node = entry.getNameNode();
      IRegion lineInformation = doc.getLineInformation(node.beginLine - 1);

      try {
        Annotation annotation = new Annotation(getOccurrenceAnnotationsType(), false, "occurrence");
        Position position =
            new Position(
                lineInformation.getOffset() + node.beginColumn - 1,
                pyMarkOccurrencesRequest.getInitialName().length());
        toAddAsMap.put(annotation, position);

      } catch (Exception e) {
        Log.log(e);
      }
    }
    return toAddAsMap;
  }
 /**
  * Removes all the info associated with a given module
  *
  * @param moduleName the name of the module we want to remove info from
  */
 public void removeInfoFromModule(String moduleName, boolean generateDelta) {
   if (DebugSettings.DEBUG_ANALYSIS_REQUESTS) {
     Log.toLogFile(this, "Removing ast info from: " + moduleName);
   }
   synchronized (lock) {
     removeInfoFromMap(moduleName, topLevelInitialsToInfo);
     removeInfoFromMap(moduleName, innerInitialsToInfo);
   }
 }
  /**
   * @return the breakpoint in the line the user clicked last or null if there is no such
   *     breakpoint.
   */
  protected IBreakpoint getBreakpointFromLastLineOfActivityInCurrentEditor() {
    List<IBreakpoint> breakpoints = getBreakpointsFromCurrentFile(true);
    int size = breakpoints.size();
    if (size == 0) {
      return null;

    } else if (size == 1) {
      return breakpoints.get(0);

    } else if (size > 1) {
      Log.log("Did not expect more than one breakpoint in the current line. Returning first.");
      return breakpoints.get(0);

    } else {
      Log.log("Unexpected condition!");
      return null;
    }
  }
Пример #27
0
 /**
  * Pre-initializes the shell (NOT in a thread, as we may need it shortly, so, no use in putting it
  * into a thread)
  *
  * @throws MisconfigurationException
  * @throws CoreException
  * @throws IOException
  * @throws PythonNatureWithoutProjectException
  */
 private void lazyStartShell(CompletionRequest request)
     throws IOException, CoreException, MisconfigurationException,
         PythonNatureWithoutProjectException {
   try {
     if (DebugSettings.DEBUG_CODE_COMPLETION) {
       Log.toLogFile(this, "AbstractShell.getServerShell");
     }
     if (CompiledModule.COMPILED_MODULES_ENABLED) {
       AbstractShell.getServerShell(
           request.nature, AbstractShell.COMPLETION_SHELL); // just start it
     }
     if (DebugSettings.DEBUG_CODE_COMPLETION) {
       Log.toLogFile(this, "END AbstractShell.getServerShell");
     }
   } catch (RuntimeException e) {
     throw e;
   }
 }
Пример #28
0
  public void run(IAction action) {
    FastStringBuffer buf = new FastStringBuffer();
    try {
      PyEdit pyEdit = getPyEdit();

      PySelection pySelection = new PySelection(pyEdit);

      IPythonNature nature = pyEdit.getPythonNature();
      File editorFile = pyEdit.getEditorFile();

      if (editorFile != null) {
        if (nature != null) {
          String mod = nature.resolveModule(editorFile);
          if (mod != null) {
            buf.append(mod);

          } else {
            // Support for external files (not in PYTHONPATH).
            buf.append(FullRepIterable.getFirstPart(editorFile.getName()));
          }
        } else {
          buf.append(FullRepIterable.getFirstPart(editorFile.getName()));
        }
      }

      List<stmtType> path =
          FastParser.parseToKnowGloballyAccessiblePath(
              pySelection.getDoc(), pySelection.getStartLineIndex());
      for (stmtType stmtType : path) {
        if (buf.length() > 0) {
          buf.append('.');
        }
        buf.append(NodeUtils.getRepresentationString(stmtType));
      }

    } catch (MisconfigurationException e1) {
      Log.log(e1);
      return;
    }

    Transfer[] dataTypes = new Transfer[] {TextTransfer.getInstance()};
    Object[] data = new Object[] {buf.toString()};

    Clipboard clipboard = new Clipboard(EditorUtils.getShell().getDisplay());
    try {
      clipboard.setContents(data, dataTypes);
    } catch (SWTError e) {
      if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) {
        throw e;
      }
      MessageDialog.openError(
          EditorUtils.getShell(), "Error copying to clipboard.", e.getMessage());
    } finally {
      clipboard.dispose();
    }
  }
  private void finishLaunchWithError(ILaunch launch) {
    try {
      launch.terminate();

      ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
      launchManager.removeLaunch(launch);
    } catch (Throwable x) {
      Log.log(x);
    }
  }
Пример #30
0
 /** Overridden to open the given files with the match provided by the platform. */
 @Override
 protected void openFiles(List<IFile> filesSelected) {
   for (IFile f : filesSelected) {
     try {
       IDE.openEditor(page, f, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
     } catch (PartInitException e) {
       Log.log(e);
     }
   }
 }