@Override
  public StyledString getStyledText(Object element) {
    if (element instanceof IResource) {
      IResource resource = (IResource) element;

      // Un-analyzed resources are grey.
      if (!DartCore.isAnalyzed(resource)) {
        return new StyledString(resource.getName(), StyledString.QUALIFIER_STYLER);
      }

      StyledString string = new StyledString(resource.getName());

      DartElement dartElement = DartCore.create(resource);

      // Append the library name to library units.
      if (dartElement instanceof CompilationUnit) {
        if (((CompilationUnit) dartElement).definesLibrary()) {
          DartLibrary library = ((CompilationUnit) dartElement).getLibrary();

          string.append(" [" + library.getDisplayName() + "]", StyledString.QUALIFIER_STYLER);
        }
      }

      return string;
    }

    return workbenchLabelProvider.getStyledText(element);
  }
  private boolean isValidSelectedFile() {
    if (selectedFile == null) {
      return false;
    }

    if (!DartCore.isDartLikeFileName(selectedFile.getName())) {
      return false;
    }

    DartElement element = DartCore.create(selectedFile);

    if (element instanceof CompilationUnit) {
      CompilationUnit cu = (CompilationUnit) element;

      DartLibrary lib = cu.getLibrary();

      if (lib instanceof DartLibraryImpl) {
        DartLibraryImpl impl = (DartLibraryImpl) lib;

        return impl.hasMain() && !impl.isBrowserApplication();
      }
    }

    return false;
  }
  /**
   * Starts pub serve for a given launch configuration. Checks if the current pub serve is for the
   * same pubspec.yaml, if not then starts up pub serve.
   *
   * @param wrapper - the launch config wrapper
   * @return - true if pub serve starts
   */
  public boolean startPubServe(DartLaunchConfigWrapper wrapper) {

    // TODO(keertip): output to process console
    console = DartCore.getConsole();

    if (currentLaunch != null) {
      IResource resource = currentLaunch.getApplicationResource();
      if (resource != null) {
        // check if previous launch and new launch share the same pubspec. If so, and pub serve is
        // running, then current pub serve can be used.
        IContainer appDir = DartCore.getApplicationDirectory(resource);
        if (appDir.equals(DartCore.getApplicationDirectory(wrapper.getApplicationResource()))) {
          // TODO(keertip): make this separate checks so that new connection can be started without
          // starting new process
          if (process != null
              && !isTerminated()
              && pubConnection != null
              && pubConnection.isConnected()) {
            console.printSeparator("Starting pub serve : " + resource.getProject().getName());
            // make sure pub is serving the directory, send serve directory command
            boolean isServed = serveDirectory(wrapper.getApplicationResource());
            if (isServed) {
              currentLaunch = wrapper;
              return true;
            }
          }
        }
      }
    }

    // terminate existing pub serve if any
    dispose();
    return runPubServe(wrapper);
  }
  private boolean runPubServe(DartLaunchConfigWrapper wrapper) {

    stdOut = new StringBuilder();
    stdError = new StringBuilder();
    IResource resource = wrapper.getApplicationResource();
    console.printSeparator("Starting pub serve : " + resource.getProject().getName());

    workingDir = DartCore.getApplicationDirectory(resource);

    List<String> args = buildPubServeCommand();
    String dirName = getPubserveRootDir(workingDir, resource);
    if (dirName != null) {
      args.add(getPubserveRootDir(workingDir, resource));
    }
    ProcessBuilder builder = new ProcessBuilder();
    builder.command(args);

    builder.directory(workingDir.getLocation().toFile());

    try {
      process = builder.start();
    } catch (IOException e) {
      DartCore.logError(e);
      return false;
    }

    Thread stdoutThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                copyStream(process.getInputStream(), stdOut, true);
              }
            });
    stdoutThread.start();

    Thread stderrThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                copyStream(process.getErrorStream(), stdError, true);
              }
            });
    stderrThread.start();

    while (!isTerminated() && !stdOut.toString().contains(LOCAL_HOST_ADDR)) {
      try {
        Thread.sleep(200);
      } catch (Exception exception) {

      }
    }

    if (isTerminated()) {
      return false;
    }
    currentLaunch = wrapper;
    return true;
  }
 /** Initialize this index with information from the user libraries. */
 private boolean indexUserLibraries() {
   boolean librariesIndexed = true;
   try {
     AnalysisServer analysisServer = PackageLibraryManagerProvider.getDefaultAnalysisServer();
     SavedContext savedContext = analysisServer.getSavedContext();
     DartModel model = DartCore.create(ResourcesPlugin.getWorkspace().getRoot());
     for (DartProject project : model.getDartProjects()) {
       for (DartLibrary library : project.getDartLibraries()) {
         CompilationUnit compilationUnit = library.getDefiningCompilationUnit();
         if (compilationUnit == null) {
           continue;
         }
         IResource libraryResource = compilationUnit.getResource();
         if (libraryResource == null) {
           continue;
         }
         IPath libraryLocation = libraryResource.getLocation();
         if (libraryLocation == null) {
           continue;
         }
         File libraryFile = libraryLocation.toFile();
         savedContext.resolve(libraryFile, null);
       }
     }
   } catch (Exception exception) {
     librariesIndexed = false;
     DartCore.logError("Could not index user libraries", exception);
   }
   return librariesIndexed;
 }
  /**
   * Process the given resource within the context of the given working set in order to record the
   * data and relationships found within the resource.
   */
  public void indexResource(File libraryFile, File sourceFile, DartUnit dartUnit)
      throws DartModelException {

    // Get the LibrarySource

    LibrarySource librarySource = dartUnit.getLibrary().getSource();

    // Get the DartLibrary

    DartLibraryImpl library;
    IResource resource = ResourceUtil.getResource(libraryFile);
    if (resource == null) {
      library = new DartLibraryImpl(librarySource);
    } else {
      DartElement element = DartCore.create(resource);
      if (element instanceof CompilationUnitImpl) {
        element = ((CompilationUnitImpl) element).getLibrary();
      }
      if (!(element instanceof DartLibrary)) {
        DartCore.logError("Expected library to be associated with " + libraryFile);
        return;
      }
      library = (DartLibraryImpl) element;
    }

    // Get the CompilationUnit

    DartSource unitSource = (DartSource) dartUnit.getSourceInfo().getSource();
    CompilationUnit compilationUnit;
    IResource res = ResourceUtil.getResource(sourceFile);
    if (res != null) {
      DefaultWorkingCopyOwner workingCopy = DefaultWorkingCopyOwner.getInstance();
      compilationUnit = new CompilationUnitImpl(library, (IFile) res, workingCopy);
    } else {
      String relPath = unitSource.getRelativePath();
      compilationUnit = new ExternalCompilationUnitImpl(library, relPath, unitSource);
    }

    URI unitUri = unitSource.getUri();
    Resource indexerResource;
    if (PackageLibraryManager.isDartUri(unitUri)) {
      indexerResource =
          new Resource(
              ResourceFactory.composeResourceId(
                  librarySource.getUri().toString(), unitUri.toString()));
    } else if (PackageLibraryManager.isPackageUri(unitUri)) {
      indexerResource =
          new Resource(
              ResourceFactory.composeResourceId(
                  libraryFile.toURI().toString(), sourceFile.toURI().toString()));
    } else {
      indexerResource = ResourceFactory.getResource(compilationUnit);
    }

    // Queue the resource to be indexed

    indexResource(indexerResource, libraryFile, compilationUnit, dartUnit);
  }
 /**
  * Returns a map of installed packages to the respective version number.
  *
  * @param lockFile the pubspec.lock file
  * @return Map<String,String> Map<packageName,versionNumber>
  */
 public static Map<String, String> getPackageVersionMap(IResource lockFile) {
   try {
     return getPackageVersionMap(IFileUtilities.getContents((IFile) lockFile));
   } catch (CoreException exception) {
     DartCore.logError(exception);
   } catch (IOException exception) {
     DartCore.logError(exception);
   }
   return null;
 }
  @Override
  public void activateApplication(File application, String name) {
    if (DartCore.isMac()) {
      activateApplicationMacOS(application);
    } else if (DartCore.isWindows()) {
      bringWindowToFrontWin32(".*" + name + "\\z");
    } else if (DartCore.isLinux()) {
      // This is not necessary on Linux.

    }
  }
 public final void runSafe() {
   try {
     run();
   } catch (Exception e) {
     // Don't log here... let caller determine what to do
     handleException(e);
   } catch (LinkageError e) {
     DartCore.logError(e);
     handleException(e);
   } catch (AssertionError e) {
     DartCore.logError(e);
     handleException(e);
   }
 }
Exemple #10
0
  private String getProcessStreamMessage(String output) {
    StringBuilder msg = new StringBuilder();

    if (output.length() != 0) {
      msg.append("Dartium stdout: ").append(output).append("\n");
    }

    boolean expired = false;

    if (output.length() != 0) {
      if (output.indexOf("Dartium build has expired") != -1) {
        expired = true;
      }

      if (expired) {
        msg.append("\nThis build of Dartium has expired.\n\n");
        msg.append("Please download a new Dart Editor or Dartium build from \n");
        msg.append("http://www.dartlang.org/downloads.html.");
      }
    }

    if (DartCore.isLinux() && !expired) {
      msg.append("\nFor information on how to setup your machine to run Dartium visit ");
      msg.append("http://code.google.com/p/dart/wiki/PreparingYourMachine#Linux");
    }

    if (msg.length() != 0) {
      msg.insert(0, ":\n\n");
    } else {
      msg.append(".");
    }

    return msg.toString();
  }
  private void initFromPrefs() {
    IPreferenceStore editorPreferences = EditorsPlugin.getDefault().getPreferenceStore();
    IPreferenceStore toolsPreferences = PreferenceConstants.getPreferenceStore();

    lineNumbersCheck.setSelection(
        editorPreferences.getBoolean(
            AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER));
    printMarginCheck.setSelection(DartFormatter.getMaxLineLengthEnabled());
    printMarginText.setText(DartFormatter.getMaxLineLength());
    printMarginText.setEnabled(printMarginCheck.getSelection());

    enableAutoCompletion.setSelection(
        toolsPreferences.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION));
    if (!DartCoreDebug.ENABLE_ANALYSIS_SERVER) {
      enableFolding.setSelection(
          toolsPreferences.getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED));
    }
    removeTrailingWhitespaceCheck.setSelection(
        toolsPreferences.getBoolean(PreferenceConstants.EDITOR_REMOVE_TRAILING_WS));
    formatCheck.setSelection(
        toolsPreferences.getBoolean(PreferenceConstants.EDITOR_FORMAT_ON_SAVES));

    IEclipsePreferences prefs = DartCore.getPlugin().getPrefs();
    if (prefs != null) {
      runPubAutoCheck.setSelection(prefs.getBoolean(DartCore.PUB_AUTO_RUN_PREFERENCE, true));
      enableAnalysisServerButton.setSelection(
          prefs.getBoolean(DartCoreDebug.ENABLE_ANALYSIS_SERVER_PREF, true));
    }
  }
Exemple #12
0
 @Override
 public Void visitImportDirective(DartImportDirective node) {
   DartLibrary library = compilationUnit.getLibrary();
   try {
     if (Objects.equal(compilationUnit, library.getDefiningCompilationUnit())) {
       DartImport[] imports = library.getImports();
       for (DartImport imprt : imports) {
         // on URI of library - return defining Unit of imported Library
         SourceRange uriRange = imprt.getUriRange();
         if (SourceRangeUtils.contains(uriRange, startOffset)) {
           resolvedElement = null;
           foundElement = imprt.getLibrary().getDefiningCompilationUnit();
           wordRegion = new Region(uriRange.getOffset(), uriRange.getLength());
           candidateRegion = new Region(0, 0);
           throw new DartElementFoundException();
         }
         // on #import directive - return DartImport element
         SourceRange sourceRange = imprt.getSourceRange();
         if (SourceRangeUtils.contains(sourceRange, startOffset)) {
           resolvedElement = null;
           foundElement = imprt;
           wordRegion = new Region(sourceRange.getOffset(), sourceRange.getLength());
           candidateRegion = new Region(sourceRange.getOffset(), sourceRange.getLength());
           throw new DartElementFoundException();
         }
       }
     }
   } catch (DartModelException e) {
     DartCore.logError("Cannot access imports of " + library.getElementName(), e);
   }
   return super.visitImportDirective(node);
 }
 /** Run the "pub get" command against every pubspec in the workspace. */
 private void runPubNow() {
   final String pubCmd = RunPubJob.INSTALL_COMMAND;
   Job firstJob = null;
   Job previousJob = null;
   for (Project proj : DartCore.getProjectManager().getProjects()) {
     for (final PubFolder pubFolder : proj.getPubFolders()) {
       final RunPubJob job = new RunPubJob(pubFolder.getResource(), pubCmd, true);
       if (firstJob == null) {
         firstJob = job;
       } else {
         previousJob.addJobChangeListener(
             new JobChangeAdapter() {
               @Override
               public void done(IJobChangeEvent event) {
                 //
                 // When one job completes, schedule the next unless the user cancels
                 //
                 if (event.getResult().getSeverity() != IStatus.CANCEL) {
                   job.schedule();
                 }
               }
             });
       }
       previousJob = job;
     }
   }
   firstJob.schedule();
 }
 /**
  * Return the project with the given root directory, loading it if it is not already loaded. This
  * method assumes that there is no conflict with project names.
  *
  * @param projectRootDirectory the root directory of the project
  * @return the project with the given root directory
  * @throws CoreException
  * @throws FileNotFoundException if a required file or directory does not exist
  * @throws IOException if a required file cannot be accessed
  * @throws SAXException if the .project file is not valid
  */
 public static DartProject loadDartProject(final IPath projectRootDirectory)
     throws CoreException, FileNotFoundException, IOException, SAXException {
   final String projectName = getProjectName(projectRootDirectory);
   final IWorkspace workspace = ResourcesPlugin.getWorkspace();
   final IProject project = workspace.getRoot().getProject(projectName);
   if (!project.exists()) {
     ResourcesPlugin.getWorkspace()
         .run(
             new IWorkspaceRunnable() {
               @Override
               public void run(IProgressMonitor monitor) throws CoreException {
                 IProjectDescription description = workspace.newProjectDescription(projectName);
                 if (!workspace.getRoot().getLocation().isPrefixOf(projectRootDirectory)) {
                   description.setLocation(projectRootDirectory);
                 }
                 project.create(description, null);
                 project.open(null);
               }
             },
             null);
   }
   DartProject dartProject = DartCore.create(project);
   // waitForJobs();
   return dartProject;
 }
Exemple #15
0
  /** Parse a single file and report the errors/warnings */
  static DartUnit parse(
      AnalysisServer server, File libraryFile, LibrarySource librarySource, File sourceFile) {
    ErrorListener errorListener = new ErrorListener(server);
    DartSource source = new UrlDartSource(sourceFile, librarySource);

    String sourceCode = null;
    try {
      sourceCode = FileUtilities.getContents(sourceFile);
    } catch (IOException e) {
      errorListener.onError(newIoError(source, e));
    }

    DartUnit dartUnit = null;
    if (sourceCode != null) {
      try {
        DartParser parser = new DartParser(source, sourceCode, errorListener);
        dartUnit = parser.parseUnit(source);
      } catch (Throwable e) {
        DartCore.logError("Exception while parsing " + sourceFile.getPath(), e);
        errorListener.onError(newParseFailure(source, e));
      }
    }

    errorListener.notifyParsed(libraryFile, sourceFile, dartUnit);
    return dartUnit != null ? dartUnit : new DartUnit(source, false);
  }
 @Override
 public LibrarySource getImportFor(String relPath) throws IOException {
   try {
     return wrappedSource.getImportFor(relPath);
   } catch (Exception exception) {
     DartCore.logInformation("Could not find import: '" + relPath + "'", exception);
     return null;
   }
 }
 /** Returns navigation targets for the given context, may be empty, but not {@code null}. */
 public static com.google.dart.server.Element[] getNavigationTargets(String file, int offset) {
   NavigationRegion[] regions = DartCore.getAnalysisServerData().getNavigation(file);
   for (NavigationRegion navigationRegion : regions) {
     if (navigationRegion.containsInclusive(offset)) {
       return navigationRegion.getTargets();
     }
   }
   return com.google.dart.server.Element.EMPTY_ARRAY;
 }
Exemple #18
0
 @Override
 public boolean visit(IResourceProxy proxy, IProgressMonitor monitor) throws CoreException {
   if (proxy.getType() == IResource.FILE) {
     if (DartCore.isHTMLLikeFileName(proxy.getName())) {
       processHtml((IFile) proxy.requestResource());
     }
   }
   return true;
 }
  public DartBasePreferencePage() {
    setPreferenceStore(DartToolsPlugin.getDefault().getPreferenceStore());

    noDefaultAndApplyButton();

    if (DartCore.isPluginsBuild()) {
      setDescription("Dart Editor version " + DartToolsPlugin.getVersionString()); // $NON-NLS-1$
    }
  }
 private static CompilationUnit getCompilationUnit(IMarker marker) {
   IResource res = marker.getResource();
   if (res instanceof IFile && res.isAccessible()) {
     DartElement element = DartCore.create((IFile) res);
     if (element instanceof CompilationUnit) {
       return (CompilationUnit) element;
     }
   }
   return null;
 }
 @Override
 public void run() {
   for (IFile file : files) {
     try {
       format(file, new NullProgressMonitor());
     } catch (Exception e) {
       DartCore.logError(e);
     }
   }
 }
 @Override
 public void handleResult(PubResult<String> result) {
   if (result.isError()) {
     done[0] = false;
   } else {
     DartCore.getConsole().println("Serving from " + result.getResult());
     done[0] = true;
   }
   latch.countDown();
 }
  private String getParentDirectory() {
    IDialogSettings settings =
        DartToolsPlugin.getDefault().getDialogSettingsSection(NEW_APPPLICATION_SETTINGS);
    String path = settings.get(PARENT_DIR);
    if (path != null) {
      return path;
    }

    return DartCore.getUserDefaultDartFolder();
  }
 /**
  * Initialize this index from the given file.
  *
  * @param indexFile the file from which this index is to be initialized
  * @return <code>true</code> if the index was correctly initialized
  */
 private boolean initializeIndexFrom(File indexFile) {
   if (indexFile == null) {
     if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
       DartCore.logInformation("Index file was null");
     }
     return false;
   } else if (!indexFile.exists()) {
     if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
       DartCore.logInformation("Index file " + indexFile.getAbsolutePath() + " does not exist");
     }
     return false;
   }
   if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
     DartCore.logInformation(
         "About to initialize the index from file "
             + indexFile.getAbsolutePath()
             + " (size = "
             + indexFile.getTotalSpace()
             + " bytes)");
   }
   try {
     boolean wasRead = readIndexFrom(indexFile);
     if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
       logIndexStats("After initializing the index from file " + indexFile.getAbsolutePath());
     }
     synchronized (indexStore) {
       return wasRead && indexStore.getResourceCount() > 0;
     }
   } catch (Exception exception) {
     DartCore.logError("Could not read index file " + indexFile.getAbsolutePath(), exception);
   }
   if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
     logIndexStats("Deleting corrupted index file " + indexFile.getAbsolutePath());
   }
   try {
     indexFile.delete();
   } catch (Exception exception) {
     DartCore.logError(
         "Could not delete corrupt index file " + indexFile.getAbsolutePath(), exception);
   }
   return false;
 }
 /**
  * Write the contents of this index to the given file.
  *
  * @param indexFile the file to which this index will be written
  * @throws IOException if the index could not be written to the given file
  */
 private void writeIndexTo(File indexFile) {
   boolean successfullyWritten = true;
   ObjectOutputStream output = null;
   try {
     output = new ObjectOutputStream(new FileOutputStream(indexFile));
     long startTime = System.currentTimeMillis();
     writeIndex(output);
     if (DartCoreDebug.PERF_INDEX) {
       long endTime = System.currentTimeMillis();
       DartCore.logInformation("Writing the index took " + (endTime - startTime) + " ms");
     }
   } catch (IOException exception) {
     successfullyWritten = false;
     DartCore.logError(
         "Could not write index file: \"" + indexFile.getAbsolutePath() + "\"", exception);
   } finally {
     if (output != null) {
       try {
         output.flush();
       } catch (IOException exception) {
         successfullyWritten = false;
         DartCore.logError(
             "Could not flush index file after write: \"" + indexFile.getAbsolutePath() + "\"",
             exception);
       }
       try {
         output.close();
       } catch (IOException exception) {
         successfullyWritten = false;
         DartCore.logError(
             "Could not close index file after write: \"" + indexFile.getAbsolutePath() + "\"",
             exception);
       }
     }
   }
   if (!successfullyWritten) {
     if (!indexFile.delete()) {
       DartCore.logError(
           "Could not delete corrupted index file: \"" + indexFile.getAbsolutePath() + "\"");
     }
   }
 }
 private static String maybeSwapDefaultEditorDescriptor(String editorId) {
   if (!DartCore.isPluginsBuild() && editorId.equals(ID_ORG_ECLIPSE_UI_DEFAULT_TEXT_EDITOR)) {
     /*
      * TODO (rdayal): Once we modify Eclipse's default text editor so that it does not add a bunch
      * of context menu contributions that we do not need (and can't get rid of via activies), we
      * can get rid of the SimpleTextEditor.
      */
     return DartUI.ID_DEFAULT_TEXT_EDITOR;
   }
   return editorId;
 }
  @Override
  public Image getImage(Object element) {
    if (element instanceof IResource) {
      IResource resource = (IResource) element;

      if (!DartCore.isAnalyzed(resource)) {
        if (resource instanceof IFile) {
          return DartToolsPlugin.getImage(IGNORE_FILE_ICON);
        }

        if (resource instanceof IFolder) {
          return DartToolsPlugin.getImage(IGNORE_FOLDER_ICON);
        }
      }

      if (resource instanceof IFile
          && resource.getParent() instanceof IProject
          && resource.getName().equals(DartCore.BUILD_DART_FILE_NAME)) {
        return DartToolsPlugin.getImage(BUILD_FILE_ICON);
      }

      DartElement dartElement = DartCore.create(resource);

      // Return a different icon for library units.
      if (dartElement instanceof CompilationUnit) {
        if (((CompilationUnit) dartElement).definesLibrary()) {
          return DartToolsPlugin.getImage(LIBRARY_ICON);
        }
      }

      if (element instanceof IFolder) {
        IFolder folder = (IFolder) element;

        if (DartCore.isPackagesDirectory(folder)) {
          return DartToolsPlugin.getImage(PACKAGES_FOLDER_ICON);
        }
      }
    }

    return workbenchLabelProvider.getImage(element);
  }
Exemple #28
0
  /**
   * Runs the pub command and displays the output in the console.
   *
   * @return the result of running the pub command
   */
  @Override
  public IStatus run(IProgressMonitor monitor) {
    IStatus status = runSilent(monitor);

    if (!status.isOK()) {
      MessageConsole console = DartCore.getConsole();
      console.printSeparator(NLS.bind(PubMessages.RunPubJob_running, command));
      console.println(status.getMessage());
    }

    return status;
  }
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    IStatus status = DartSdkManager.getManager().upgrade(monitor);

    if (!status.isOK()) {
      if (status.getException() != null) {
        DartCore.logError(status.getException());
      }
    }

    return status;
  }
Exemple #30
0
 /**
  * Answer the absolute file for the specified URI
  *
  * @return the file or <code>null</code> if unknown
  */
 static File toFile(AnalysisServer server, URI uri) {
   String scheme = uri.getScheme();
   if (scheme == null || "file".equals(scheme)) {
     File file = new File(uri.getPath());
     if (file.isAbsolute()) {
       return file;
     }
     DartCore.logError("Non absolute path: " + file);
     return null;
   }
   if (SystemLibraryManager.isDartUri(uri)) {
     URI resolveUri = server.getLibraryManager().resolveDartUri(uri);
     if (resolveUri == null) {
       DartCore.logError("Failed to resolve: " + uri);
       return null;
     }
     return new File(resolveUri.getPath());
   }
   DartCore.logError("Unknown library scheme : " + uri);
   return null;
 }