/**
   * Launches the python process.
   *
   * <p>Modelled after Ant & Java runners see WorkbenchLaunchConfigurationDelegate::launch
   */
  @Override
  public void launch(
      ILaunchConfiguration conf, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }

    monitor.beginTask("Preparing configuration", 1);
    monitor.worked(1);

    ProcessServer p = new ProcessServer();
    String label = "Debug Server";
    HashMap<String, String> processAttributes = new HashMap<String, String>();
    processAttributes.put(IProcess.ATTR_PROCESS_TYPE, Constants.PROCESS_TYPE);
    processAttributes.put(IProcess.ATTR_PROCESS_LABEL, label);
    processAttributes.put(DebugPlugin.ATTR_CAPTURE_OUTPUT, "true");

    IProcess pro = DebugPlugin.newProcess(launch, p, label, processAttributes);

    RemoteDebuggerServer.getInstance().setLaunch(launch, p, pro);
  }
  public void launch(
      ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {

    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }
    PHPexeItem phpExeItem = PHPLaunchUtilities.getPHPExe(configuration);
    if (phpExeItem == null) {
      Logger.log(Logger.ERROR, "Launch configuration could not find PHP exe item"); // $NON-NLS-1$
      monitor.setCanceled(true);
      monitor.done();
      return;
    }
    // get the launch info: php exe, php ini
    final String phpExeString =
        configuration.getAttribute(IPHPDebugConstants.ATTR_EXECUTABLE_LOCATION, (String) null);
    final String phpIniString =
        configuration.getAttribute(IPHPDebugConstants.ATTR_INI_LOCATION, (String) null);
    final String phpScriptString =
        configuration.getAttribute(IPHPDebugConstants.ATTR_FILE, (String) null);
    if (phpScriptString == null || phpScriptString.trim().length() == 0) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      displayErrorMessage(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_0);
      return;
    }
    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }

    // locate the project from the php script
    final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    final IPath filePath = new Path(phpScriptString);
    final IResource scriptRes = workspaceRoot.findMember(filePath);
    if (scriptRes == null) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      displayErrorMessage(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_1);
      return;
    }

    // resolve php exe location
    final IPath phpExe = new Path(phpExeString);

    // resolve project directory
    IProject project = scriptRes.getProject();

    // Set Project Name as this is required by the source lookup computer
    // delegate
    final String projectString = project.getFullPath().toString();
    ILaunchConfigurationWorkingCopy wc = null;
    if (configuration.isWorkingCopy()) {
      wc = (ILaunchConfigurationWorkingCopy) configuration;
    } else {
      wc = configuration.getWorkingCopy();
    }
    wc.setAttribute(IPHPDebugConstants.PHP_Project, projectString);
    wc.setAttribute(
        IDebugParametersKeys.TRANSFER_ENCODING, PHPProjectPreferences.getTransferEncoding(project));
    wc.setAttribute(
        IDebugParametersKeys.OUTPUT_ENCODING, PHPProjectPreferences.getOutputEncoding(project));
    wc.doSave();

    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }

    IPath projectLocation = project.getRawLocation();
    if (projectLocation == null) {
      projectLocation = project.getLocation();
    }

    // resolve the script location, but not relative to anything
    IPath phpFile = scriptRes.getLocation();

    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }

    // Resolve the PHP ini location
    // Locate the php ini by using the attribute. If the attribute was null,
    // try to locate an ini that exists next to the executable.
    File phpIni =
        (phpIniString != null && new File(phpIniString).exists())
            ? new File(phpIniString)
            : PHPINIUtil.findPHPIni(phpExeString);
    File tempIni = PHPINIUtil.prepareBeforeLaunch(phpIni, phpExeString, project);
    launch.setAttribute(IDebugParametersKeys.PHP_INI_LOCATION, tempIni.getAbsolutePath());

    // add process type to process attributes, basically the name of the exe
    // that was launched
    final Map<String, String> processAttributes = new HashMap<String, String>();
    String programName = phpExe.lastSegment();
    final String extension = phpExe.getFileExtension();
    if (extension != null) {
      programName = programName.substring(0, programName.length() - (extension.length() + 1));
    }
    programName = programName.toLowerCase();

    // used by the console colorer extension to determine what class to use
    // should allow the console color providers and line trackers to work
    // process.setAttribute(IProcess.ATTR_PROCESS_TYPE,
    // IPHPConstants.PHPProcessType);

    processAttributes.put(IProcess.ATTR_PROCESS_TYPE, programName);
    // used by the Console to give that console a name
    processAttributes.put(IProcess.ATTR_CMDLINE, phpScriptString);

    if (monitor.isCanceled()) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      return;
    }

    // determine the environment variables
    String[] envVarString = null;
    DBGpTarget target = null;
    if (mode.equals(ILaunchManager.DEBUG_MODE)) {
      // check the launch for stop at first line, if not there go to
      // project specifics
      boolean stopAtFirstLine = PHPProjectPreferences.getStopAtFirstLine(project);
      stopAtFirstLine =
          configuration.getAttribute(IDebugParametersKeys.FIRST_LINE_BREAKPOINT, stopAtFirstLine);
      String sessionID = DBGpSessionHandler.getInstance().generateSessionId();
      String ideKey = null;
      if (phpExeItem != null) {
        DBGpProxyHandler proxyHandler =
            DBGpProxyHandlersManager.INSTANCE.getHandler(phpExeItem.getUniqueId());
        if (proxyHandler != null && proxyHandler.useProxy()) {
          ideKey = proxyHandler.getCurrentIdeKey();
          if (proxyHandler.registerWithProxy() == false) {
            displayErrorMessage(
                PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_2
                    + proxyHandler.getErrorMsg());
            DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
            return;
          }
        } else {
          ideKey = DBGpSessionHandler.getInstance().getIDEKey();
        }
      }
      target = new DBGpTarget(launch, phpFile.lastSegment(), ideKey, sessionID, stopAtFirstLine);
      target.setPathMapper(PathMapperRegistry.getByLaunchConfiguration(configuration));
      DBGpSessionHandler.getInstance().addSessionListener(target);
      envVarString = createDebugLaunchEnvironment(configuration, sessionID, ideKey, phpExe);

      int requestPort = getDebugPort(phpExeItem);
      // Check that the debug daemon is functional
      // DEBUGGER - Make sure that the active debugger id is indeed Zend's
      // debugger
      if (!PHPLaunchUtilities.isDebugDaemonActive(
          requestPort, XDebugCommunicationDaemon.XDEBUG_DEBUGGER_ID)) {
        PHPLaunchUtilities.showLaunchErrorMessage(
            NLS.bind(
                PHPDebugCoreMessages.ExeLaunchConfigurationDelegate_PortInUse,
                requestPort,
                phpExeItem.getName()));
        monitor.setCanceled(true);
        monitor.done();
        return;
      }

    } else {
      envVarString =
          PHPLaunchUtilities.getEnvironment(configuration, new String[] {getLibraryPath(phpExe)});
    }

    IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 30);
    subMonitor.beginTask(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_3, 10);

    // determine the working directory. default is the location of the
    // script
    IPath workingPath = phpFile.removeLastSegments(1);
    File workingDir = workingPath.makeAbsolute().toFile();

    boolean found = false;
    for (int i = 0; i < envVarString.length && !found; i++) {
      String envEntity = envVarString[i];
      String[] elements = envEntity.split("="); // $NON-NLS-1$
      if (elements.length > 0 && elements[0].equals("XDEBUG_WORKING_DIR")) { // $NON-NLS-1$
        found = true;
        workingPath = new Path(elements[1]);
        File temp = workingPath.makeAbsolute().toFile();
        if (temp.exists()) {
          workingDir = temp;
        }
      }
    }

    // Detect PHP SAPI type and thus where we need arguments
    File phpExeFile = new File(phpExeString);
    String sapiType = null;
    String phpV = null;
    PHPexeItem[] items = PHPexes.getInstance().getAllItems();
    for (PHPexeItem item : items) {
      if (item.getExecutable().equals(phpExeFile)) {
        sapiType = item.getSapiType();
        phpV = item.getVersion();
        break;
      }
    }
    String[] args = null;
    if (PHPexeItem.SAPI_CLI.equals(sapiType)) {
      args = PHPLaunchUtilities.getProgramArguments(launch.getLaunchConfiguration());
    }

    // define the command line for launching
    String[] cmdLine = null;
    cmdLine =
        PHPLaunchUtilities.getCommandLine(
            configuration,
            phpExe.toOSString(),
            tempIni.toString(),
            phpFile.toOSString(),
            args,
            phpV);

    // Launch the process
    final Process phpExeProcess = DebugPlugin.exec(cmdLine, workingDir, envVarString);
    // Attach a crash detector
    new Thread(new ProcessCrashDetector(launch, phpExeProcess)).start();

    IProcess eclipseProcessWrapper = null;
    if (phpExeProcess != null) {
      subMonitor.worked(10);
      eclipseProcessWrapper =
          DebugPlugin.newProcess(launch, phpExeProcess, phpExe.toOSString(), processAttributes);
      if (eclipseProcessWrapper == null) {

        // another error so we stop everything somehow
        phpExeProcess.destroy();
        subMonitor.done();
        DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
        throw new CoreException(new Status(IStatus.ERROR, PHPDebugPlugin.ID, 0, null, null));
      }

      // if launching in debug mode, create the debug infrastructure and
      // link it with the launched process
      if (mode.equals(ILaunchManager.DEBUG_MODE) && target != null) {
        target.setProcess(eclipseProcessWrapper);
        launch.addDebugTarget(target);
        subMonitor.subTask(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_4);
        target.waitForInitialSession(
            (DBGpBreakpointFacade) IDELayerFactory.getIDELayer(),
            XDebugPreferenceMgr.createSessionPreferences(),
            monitor);
      }

    } else {
      // we did not launch
      if (mode.equals(ILaunchManager.DEBUG_MODE)) {
        DBGpSessionHandler.getInstance().removeSessionListener(target);
      }
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
    }
    subMonitor.done();
  }
예제 #3
0
  /**
   * the command has been executed, so extract extract the needed information from the application
   * context.
   */
  public Object execute(ExecutionEvent event) throws ExecutionException {
    log.fine("Message to start PVS was received");
    window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    if (PVSExecutionManager.INST().isPVSRunning()) {
      MessageDialog.openInformation(
          window.getShell(), "PVS Running", "An instance of PVS is already running.");
    } else {
      try {
        final PVSConsole console = PVSConsole.getConsole();
        console.activate();
        console.clearConsole();
        final IOConsoleOutputStream outStream = console.newOutputStream();
        Map<String, String> attributes = new HashMap<String, String>();
        attributes.put(IProcess.ATTR_CMDLINE, PVSExecutionManager.INST().getPVSStartingCommand());
        ILaunch launch = new Launch(null, ILaunchManager.RUN_MODE, null);
        IProcess process =
            DebugPlugin.newProcess(
                launch, PVSExecutionManager.INST().startPVS(), Activator.name, attributes);
        PVSExecutionManager.INST().setIProcess(process);
        DebugPlugin.getDefault().getLaunchManager().addLaunch(launch);
        DebugPlugin.getDefault().addDebugEventListener(PVSExecutionManager.INST());
        PVSJsonWrapper.init();
        PVSExecutionManager.INST().removeRespondListeners();
        PVSExecutionManager.INST()
            .addListener(
                new PVSRespondListener() {

                  @Override
                  public void onMessageReceived(String message) {
                    log.log(Level.INFO, "Message received: {0}", message);
                    try {
                      outStream.write(message);
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }

                  @Override
                  public void onMessageReceived(JSONObject message) {
                    log.log(Level.INFO, "JSON received: {0}", message);
                    PVSJsonWrapper.INST().addToJSONQueue(message);
                  }

                  @Override
                  public void onPromptReceived(List<String> previousLines, String prompt) {
                    log.log(Level.INFO, "Prompt received: {0}", prompt);
                    try {
                      outStream.write(prompt);
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                    PVSPromptProcessor.processPrompt(previousLines, prompt);
                  }
                });
        IStreamsProxy streamProxy = process.getStreamsProxy();
        IStreamMonitor outMonitor = streamProxy.getOutputStreamMonitor();
        outMonitor.addListener(new PVSStreamListener(EclipsePluginUtil.getLispType()));

        IOConsoleKeyboardReader.init(console);
        IOConsoleKeyboardReader.INST()
            .addListener(
                new IOConsoleKeyboardReader.IOConsoleKeyboardReaderListener() {
                  public void onTextReceived(String text) {
                    PVSExecutionManager.INST().writeToPVS(text);
                  }
                });
        IOConsoleKeyboardReader.INST().start();
        Thread.sleep(500);
        restorePVSContext();
      } catch (IOException e) {
        log.severe("Failed to start PVS");
        MessageDialog.openInformation(window.getShell(), "Error", "Failed to start PVS");
      } catch (InterruptedException e) {
        log.severe("Failed to restore PVS context");
        MessageDialog.openInformation(
            window.getShell(), "Error", "Failed to restore the PVS context");
      } catch (PVSException e) {
        log.severe("Failed to restore PVS context");
        MessageDialog.openInformation(
            window.getShell(), "Error", "Failed to restore the PVS context");
      }
    }
    return null;
  }
예제 #4
0
  public void launchBrowser(
      ILaunch launch,
      ILaunchConfiguration configuration,
      IResourceResolver resourceResolver,
      IBrowserTabChooser browserTabChooser,
      String url,
      IProgressMonitor monitor,
      boolean enableDebugging,
      List<String> extraCommandLineArgs)
      throws CoreException {
    try {
      if (launchSemaphore.tryAcquire()) {
        try {
          SDBGLaunchConfigWrapper launchConfig = new SDBGLaunchConfigWrapper(configuration);
          launchConfig.markAsLaunched();

          monitor.beginTask("Launching Chrome...", enableDebugging ? 7 : 2);

          // avg: 0.434 sec (old: 0.597)
          LogTimer timer = new LogTimer("Chrome debug startup");

          // avg: 55ms
          timer.startTask("Chrome startup");

          // for now, check if browser is open, and connection is alive
          boolean restart =
              browserProcess == null
                  || isProcessTerminated(browserProcess)
                  || WebkitDebugTarget.getActiveTarget() == null
                  || !WebkitDebugTarget.getActiveTarget().canTerminate();

          // we only re-cycle the debug connection if we're launching the same launch configuration
          if (!restart) {
            if (!WebkitDebugTarget.getActiveTarget()
                .getLaunch()
                .getLaunchConfiguration()
                .equals(launch.getLaunchConfiguration())) {
              restart = true;
            }
          }

          if (!restart) {
            if (enableDebugging != WebkitDebugTarget.getActiveTarget().getEnableBreakpoints()) {
              restart = true;
            }
          }

          CoreLaunchUtils.removeTerminatedLaunches();

          File browserExecutable = getBrowserExecutable();

          if (!restart && url != null && resourceResolver != null) {
            DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);

            try {
              WebkitDebugTarget.getActiveTarget()
                  .navigateToUrl(
                      launch.getLaunchConfiguration(),
                      url,
                      true /*enableBreakpoints*/,
                      resourceResolver);
            } catch (IOException e) {
              SDBGDebugCorePlugin.logError(e);
            }
          } else {
            terminateExistingBrowserProcess();

            StringBuilder processDescription = new StringBuilder();

            int[] devToolsPortNumberHolder = new int[1];
            ListeningStream browserOutput =
                startNewBrowserProcess(
                    launchConfig,
                    url,
                    monitor,
                    enableDebugging,
                    processDescription,
                    extraCommandLineArgs,
                    devToolsPortNumberHolder);

            sleep(100);

            monitor.worked(1);

            if (isProcessTerminated(browserProcess)) {
              SDBGDebugCorePlugin.logError("Browser output: " + browserOutput.toString());

              throw new CoreException(
                  new Status(
                      IStatus.ERROR,
                      SDBGDebugCorePlugin.PLUGIN_ID,
                      "Could not launch browser - process terminated on startup"
                          + getProcessStreamMessage(browserOutput.toString())));
            }

            if (enableDebugging) {
              connectToChromiumDebug(
                  browserExecutable.getName(),
                  launch,
                  launchConfig,
                  url,
                  monitor,
                  browserProcess,
                  timer,
                  true /*enableBreakpoints*/,
                  null,
                  devToolsPortNumberHolder[0],
                  20 * 1000L /*maxStartupDelay*/,
                  browserOutput,
                  processDescription.toString(),
                  resourceResolver,
                  browserTabChooser,
                  false /*remote*/);
            } else {
              registerProcess(
                  launch,
                  launchConfig,
                  DebugPlugin.newProcess(
                      launch,
                      browserProcess,
                      browserExecutable.getName()
                          + " - run only, debugging DISABLED ("
                          + new Date()
                          + ")"),
                  processDescription.toString());
            }
          }

          DebugUIHelper.getHelper().activateApplication(browserExecutable, "Chrome");

          timer.stopTask();
          timer.stopTimer();
          monitor.done();
        } finally {
          launchSemaphore.release();
        }
      }
    } catch (CoreException e) {
      DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
      throw e;
    }
  }