diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12641fe44..da8cd7caf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,33 +5,31 @@ name: Java CI with Maven on: push: - branches: [ master ] + branches: + - master + - release/** pull_request: - branches: [ master ] + branches: + - master + - release/** jobs: - build: + build_linux: - runs-on: - - self-hosted - - eclipse - - BrnoUBU0004 + runs-on: [self-hosted, eclipse, BrnoUBU0004] steps: - - uses: actions/checkout@v2 - - - name: Clone IDF Release From Github - uses: actions/checkout@v2 - with: - repository: espressif/esp-idf - path: dependencies/idf-tools - submodules: 'true' - ref: release/v5.1 + - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v2 with: - python-version: '3.10' + python-version: '3.10' + + - name: Install ESP-IDF via eim + uses: espressif/install-esp-idf-action@v1 + with: + version: 'v5.3' - name: Set up Maven uses: stCarolas/setup-maven@v5 @@ -42,8 +40,9 @@ jobs: uses: actions/setup-java@v4 with: java-version: '21' - distribution: 'temurin' - + distribution: 'temurin' + cache: 'maven' + - name: Build with Maven run: export NO_AT_BRIDGE=1 && mvn clean verify -Djarsigner.skip=true -DskipTests=false -DtestWorkspace=/opt/actions-runner/_work/workspace diff --git a/.github/workflows/ci_windows.yml b/.github/workflows/ci_windows.yml index d0c05ed9a..89f5f3f64 100644 --- a/.github/workflows/ci_windows.yml +++ b/.github/workflows/ci_windows.yml @@ -5,9 +5,13 @@ name: Java CI with Maven on Windows on: push: - branches: [ master ] + branches: + - master + - release/** pull_request: - branches: [ master ] + branches: + - master + - release/** jobs: build_windows: diff --git a/bundles/com.espressif.idf.core/META-INF/MANIFEST.MF b/bundles/com.espressif.idf.core/META-INF/MANIFEST.MF index a8ca2a54c..c44487277 100644 --- a/bundles/com.espressif.idf.core/META-INF/MANIFEST.MF +++ b/bundles/com.espressif.idf.core/META-INF/MANIFEST.MF @@ -45,6 +45,7 @@ Export-Package: com.espressif.idf.core, com.espressif.idf.core.tools, com.espressif.idf.core.tools.util, com.espressif.idf.core.tools.vo, + com.espressif.idf.core.tools.watcher, com.espressif.idf.core.util, com.espressif.idf.core.variable, org.json.simple, diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/IDFCorePreferenceConstants.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/IDFCorePreferenceConstants.java index 1338b5152..2fde5d21c 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/IDFCorePreferenceConstants.java +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/IDFCorePreferenceConstants.java @@ -7,14 +7,11 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ProjectScope; -import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.ConfigurationScope; import org.eclipse.core.runtime.preferences.DefaultScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; -import com.espressif.idf.core.util.IDFUtil; - /** * @author Kondal Kolipaka * @@ -32,16 +29,6 @@ public class IDFCorePreferenceConstants public static final boolean CMAKE_CCACHE_DEFAULT_STATUS = true; public static final boolean AUTOMATE_BUILD_HINTS_DEFAULT_STATUS = true; public static final boolean HIDE_ERRORS_IDF_COMPONENTS_DEFAULT_STATUS = true; - public static final String IDF_GITHUB_ASSETS = "IDF_GITHUB_ASSETS"; //$NON-NLS-1$ - public static final String IDF_GITHUB_ASSETS_DEFAULT_GLOBAL = "dl.espressif.com/github_assets"; //$NON-NLS-1$ - public static final String IDF_GITHUB_ASSETS_DEFAULT_CHINA = "dl.espressif.cn/github_assets"; //$NON-NLS-1$ - public static final String PIP_EXTRA_INDEX_URL = "PIP_EXTRA_INDEX_URL"; //$NON-NLS-1$ - public static final String PIP_EXTRA_INDEX_URL_DEFAULT_GLOBAL = "https://dl.espressif.com/pypi"; //$NON-NLS-1$ - public static final String PIP_EXTRA_INDEX_URL_DEFAULT_CHINA = "https://dl.espressif.cn/pypi"; //$NON-NLS-1$ - public static final String IDF_TOOLS_PATH = "IDF_TOOLS_PATH"; //$NON-NLS-1$ - public static final String IDF_TOOLS_PATH_DEFAULT = Platform.getOS().equals(Platform.OS_WIN32) - ? IDFUtil.resolveEnvVariable("%USERPROFILE%\\.espressif") //$NON-NLS-1$ - : IDFUtil.resolveEnvVariable("$HOME/.espressif"); //$NON-NLS-1$ /** * Returns the node in the preference in the given context. diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/IDFEnvironmentVariables.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/IDFEnvironmentVariables.java index e60d02acd..12867f621 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/IDFEnvironmentVariables.java +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/IDFEnvironmentVariables.java @@ -18,7 +18,6 @@ import org.eclipse.cdt.managedbuilder.envvar.IBuildEnvironmentVariable; import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.util.IDFUtil; import com.espressif.idf.core.util.StringUtil; /** @@ -52,6 +51,8 @@ public class IDFEnvironmentVariables public static final String IDF_CCACHE_ENABLE = "IDF_CCACHE_ENABLE"; //$NON-NLS-1$ + public static final String ESP_IDF_EIM_ID = "ESP_IDF_EIM_ID"; //$NON-NLS-1$ + /** * @param variableName Environment variable Name * @return IEnvironmentVariable @@ -129,16 +130,12 @@ public Map getSystemEnvMap() IEnvironmentVariableManager buildEnvironmentManager = CCorePlugin.getDefault().getBuildEnvironmentManager(); IEnvironmentVariable[] variables = buildEnvironmentManager.getVariables((ICConfigurationDescription) null, true); - Map envMap = IDFUtil.getSystemEnv(); + Map envMap = new HashMap(System.getenv()); if (variables != null) { for (IEnvironmentVariable iEnvironmentVariable : variables) { String key = iEnvironmentVariable.getName(); - if (key.equals(IDFCorePreferenceConstants.IDF_TOOLS_PATH)) - { - continue; - } String value = iEnvironmentVariable.getValue(); envMap.put(key, value); } diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/IDFBuildConfiguration.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/IDFBuildConfiguration.java index e3e8fd541..981f6bab3 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/IDFBuildConfiguration.java +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/IDFBuildConfiguration.java @@ -359,9 +359,6 @@ private void runCmakeBuildCommand(IConsole console, IProgressMonitor monitor, IP } } - envVars.add(new EnvironmentVariable(IDFCorePreferenceConstants.IDF_TOOLS_PATH, - IDFUtil.getIDFToolsPathFromPreferences())); - String buildCommand = getProperty(BUILD_COMMAND); if (buildCommand.isBlank()) { @@ -479,10 +476,8 @@ private void runCmakeCommand(IConsole console, IProgressMonitor monitor, IProjec // Set PYTHONUNBUFFERED to 1/TRUE to dump the messages back immediately without // buffering IEnvironmentVariable bufferEnvVar = new EnvironmentVariable("PYTHONUNBUFFERED", "1"); //$NON-NLS-1$ //$NON-NLS-2$ - IEnvironmentVariable idfToolsPathEnvVar = new EnvironmentVariable(IDFCorePreferenceConstants.IDF_TOOLS_PATH, - IDFUtil.getIDFToolsPathFromPreferences()); - Process p = startBuildProcess(command, new IEnvironmentVariable[] { bufferEnvVar, idfToolsPathEnvVar }, + Process p = startBuildProcess(command, new IEnvironmentVariable[] { bufferEnvVar }, workingDir, errConsole, monitor); if (p == null) { diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/Messages.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/Messages.java index 52b468c4e..aa552a03d 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/Messages.java +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/Messages.java @@ -33,8 +33,23 @@ public class Messages extends NLS public static String ToolsInitializationDifferentPathMessageBoxOptionYes; public static String ToolsInitializationDifferentPathMessageBoxOptionNo; public static String IDFToolChainsMissingErrorMsg; + + public static String ToolsInitializationEimMissingMsgBoxTitle; + public static String ToolsInitializationEimMissingMsgBoxMessage; public static String RefreshingProjects_JobName; + + public static String NoActiveEspIdfInWorkspaceMsgTitle; + public static String NoActiveEspIdfInWorkspaceMsg; + + public static String OldConfigFoundMsgBoxTitle; + public static String OldConfigFoundMsgBoxMsg; + public static String OldConfigExportDirectorSelectionDialogTitle; + public static String OldConfigExportDirectorSelectionDialogInfo; + public static String OldConfigExportCompleteSuccessMsgTitle; + public static String OldConfigExportCompleteSuccessMsg; + public static String OldConfigExportCompleteFailMsgTitle; + public static String OldConfigExportCompleteFailMsg; static { diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/messages.properties b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/messages.properties index db0836990..6efb0de45 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/messages.properties +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/build/messages.properties @@ -19,9 +19,23 @@ IDFBuildConfiguration_ParseCommand=Parse Compile Commands File IncreasePartitionSizeTitle=Low Application Partition Size IncreasePartitionSizeMessage=Less than 30% of application partition size is free({0} of {1} bytes), would you like to increase it? Please click here to check more details. ToolsInitializationDifferentPathMessageBoxTitle=Different IDF path found in the config file +ToolsInitializationEimMissingMsgBoxTitle=ESP-IDF Not Found +ToolsInitializationEimMissingMsgBoxMessage=ESP-IDF is not found on your system. To use the IDE, install ESP-IDF using EIM - GUI Installer. \n\nOnce installed, the IDE will automatically detect ESP-IDF. You can verify and activate it from the ESP-IDF Manager, accessible via the menu: Espressif > ESP-IDF Manager.\n\n ToolsInitializationDifferentPathMessageBoxMessage=A different ESP-IDF path was found in the esp_idf.json.json configuration file. Do you want to install the tools in the new path or the old path? Please click on the appropriate button.\nNew Path: {0}\nOld Path: {1} ToolsInitializationDifferentPathMessageBoxOptionYes=Use New Path ToolsInitializationDifferentPathMessageBoxOptionNo=Use Old Path RefreshingProjects_JobName=Refreshing Projects... IDFBuildConfiguration_PreCheck_DifferentIdfPath=The project was built using the ESP-IDF located at the {0} path.\nThe currently active ESP-IDF path in the IDE is {1}.\nPlease clean the project using "ESP-IDF:Project Full Clean" menu option to use the active ESP-IDF configuration. -IDFToolChainsMissingErrorMsg=Toolchains are missing. Please use ESP-IDF Manager for configuring \ No newline at end of file +IDFToolChainsMissingErrorMsg=Toolchains are missing. Please use ESP-IDF Manager for configuring + +NoActiveEspIdfInWorkspaceMsgTitle=ESP-IDF Setup +NoActiveEspIdfInWorkspaceMsg=ESP-IDF is required to use Espressif IDE. Would you like to configure it now? + +OldConfigFoundMsgBoxTitle=Old Configuration Found +OldConfigFoundMsgBoxMsg=An old ESP-IDF configuration has been detected.\nIf you want to use these you need to export these configuration and pass them on to EIM for updated configurations.\nWould you like to export these settings?\n\nPress 'Yes' to choose a location to save. +OldConfigExportDirectorSelectionDialogTitle=Select Destination +OldConfigExportDirectorSelectionDialogInfo=Choose a directory to save the exported settings. +OldConfigExportCompleteSuccessMsgTitle=Export Successful +OldConfigExportCompleteSuccessMsg=The configuration has been successfully copied to:\n{0} +OldConfigExportCompleteFailMsgTitle=Export Failed +OldConfigExportCompleteFailMsg=An error occurred while copying the configuration.\n{0} \ No newline at end of file diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/toolchain/ESPToolChainManager.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/toolchain/ESPToolChainManager.java index f0717c527..c633aab39 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/toolchain/ESPToolChainManager.java +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/toolchain/ESPToolChainManager.java @@ -177,7 +177,7 @@ public File findToolChain(List paths, String filePattern) private Path[] getDirectories(String path) { - return Arrays.stream(path.split(File.pathSeparator)).map(String::trim).map(Paths::get).filter(Files::exists) + return Arrays.stream(path.split(File.pathSeparator)).map(String::trim).map(Paths::get).filter(Files::exists).filter(Files::isDirectory) .toArray(Path[]::new); } @@ -316,7 +316,7 @@ protected String getIdfToolsExportPath() Logger.log(commands.toString()); IStatus idfToolsExportStatus = new ProcessBuilderFactory().runInBackground(commands, - org.eclipse.core.runtime.Path.ROOT, IDFUtil.getSystemEnv()); + org.eclipse.core.runtime.Path.ROOT, System.getenv()); if (idfToolsExportStatus != null && idfToolsExportStatus.isOK()) { String message = idfToolsExportStatus.getMessage(); diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/EimConstants.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/EimConstants.java new file mode 100644 index 000000000..1a43560ef --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/EimConstants.java @@ -0,0 +1,22 @@ +package com.espressif.idf.core.tools; + +public interface EimConstants +{ + String EIM_JSON = "eim_idf.json"; //$NON-NLS-1$ + + String EIM_POSIX_DIR = System.getProperty("user.home").concat("/.espressif/tools/"); //$NON-NLS-1$//$NON-NLS-2$ + + String EIM_WIN_DIR = "C:\\Espressif\\tools\\"; //$NON-NLS-1$ + + String EIM_WIN_PATH = EIM_WIN_DIR + EIM_JSON; + + String EIM_URL = "https://dl.espressif.com/dl/eim/"; //$NON-NLS-1$ + + String EIM_POSIX_PATH = EIM_POSIX_DIR + EIM_JSON; + + String INSTALL_TOOLS_FLAG = "INSTALL_TOOLS_FLAG"; //$NON-NLS-1$ + + String TOOL_SET_CONFIG_LEGACY_CONFIG_FILE = "tool_set_config.json"; //$NON-NLS-1$ + + String OLD_CONFIG_EXPORTED_FLAG = "OLD_CONFIG_EXPORTED_FLAG"; //$NON-NLS-1$ +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/EimIdfConfiguratinParser.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/EimIdfConfiguratinParser.java new file mode 100644 index 000000000..6073b914d --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/EimIdfConfiguratinParser.java @@ -0,0 +1,47 @@ +package com.espressif.idf.core.tools; + +import java.io.FileReader; +import java.io.IOException; + +import org.eclipse.core.runtime.Platform; + +import com.espressif.idf.core.tools.vo.EimJson; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class EimIdfConfiguratinParser +{ + private EimJson eimJson; + private Gson gson; + + public EimIdfConfiguratinParser() + { + gson = new GsonBuilder().setPrettyPrinting().enableComplexMapKeySerialization() + .excludeFieldsWithoutExposeAnnotation().create(); + } + + private void load() throws IOException + { + try (FileReader fileReader = new FileReader( + Platform.getOS().equals(Platform.OS_WIN32) ? EimConstants.EIM_WIN_PATH : EimConstants.EIM_POSIX_PATH)) + { + eimJson = gson.fromJson(fileReader, EimJson.class); + } + } + + + public EimJson getEimJson(boolean reload) throws IOException + { + if (reload) + { + load(); + } + + if (eimJson == null) + { + load(); + } + + return eimJson; + } +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/IToolsInstallationWizardConstants.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/IToolsInstallationWizardConstants.java deleted file mode 100644 index e64cb5bc8..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/IToolsInstallationWizardConstants.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright 2022 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools; - -/** - * Interface to store the constants related to tools management wizard - * - * @author Ali Azam Rana - * - */ -public interface IToolsInstallationWizardConstants -{ - String PYTHON_PATH_NODE_KEY = "PYTHON_EXECUTABLE"; //$NON-NLS-1$ - - String GIT_PATH_NODE_KEY = "GIT_EXECUTABLE"; //$NON-NLS-1$ - - String ESPRESSIF_LOGO = "icons/tools/espressif-logo.png"; //$NON-NLS-1$ - - String INSTALL_TOOLS_FLAG = "INSTALL_TOOLS_FLAG"; //$NON-NLS-1$ - - String TOOL_SET_CONFIG_FILE = "tool_set_config.json"; //$NON-NLS-1$ -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/IToolsJsonKeys.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/IToolsJsonKeys.java deleted file mode 100644 index bf8bc42ea..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/IToolsJsonKeys.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.espressif.idf.core.tools; - -/** - * Keys in the tools.json file mentioned here for the better usage - * - * @author Ali Azam Rana - * - */ -public interface IToolsJsonKeys -{ - String URL_KEY = "url"; //$NON-NLS-1$ - - String SIZE_KEY = "size"; //$NON-NLS-1$ - - String SHA256_KEY = "sha256"; //$NON-NLS-1$ - - String STATUS_KEY = "status"; //$NON-NLS-1$ - - String VERSION_KEY = "version"; //$NON-NLS-1$ - - String VERSIONS_VO_KEY = "versions"; //$NON-NLS-1$ - - String VERSION_CMD_KEY = "version_cmd"; //$NON-NLS-1$ - - String VERSION_REGEX = "version_regex"; //$NON-NLS-1$ - - String SUPPORTED_TARGETS_KEY = "supported_targets"; //$NON-NLS-1$ - - String NAME_KEY = "name"; //$NON-NLS-1$ - - String LICENSE_KEY = "license"; //$NON-NLS-1$ - - String INSTALL_KEY = "install"; //$NON-NLS-1$ - - String INFO_URL_KEY = "info_url"; //$NON-NLS-1$ - - String EXPORT_VARS_KEY = "export_vars"; //$NON-NLS-1$ - - String EXPORT_PATHS_KEY = "export_paths"; //$NON-NLS-1$ - - String DESCRIPTION_KEY = "description"; //$NON-NLS-1$ - - String TOOLS_KEY = "tools"; //$NON-NLS-1$ - - String PLATFORM_OVERRIDES_KEY = "platform_overrides"; //$NON-NLS-1$ - - String PLATFORMS_KEY = "platforms"; //$NON-NLS-1$ -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/JsonKey.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/JsonKey.java deleted file mode 100644 index 0eca4e6ff..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/JsonKey.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.espressif.idf.core.tools; - -import static java.lang.annotation.ElementType.FIELD; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(FIELD) -@Retention(RetentionPolicy.RUNTIME) -/** - * Annotation to apply a json key to the vos - * @author Ali Azam Rana - * - */ -public @interface JsonKey -{ - /** - * the json key name associated with the field - * @return JSON Key name associated with the field - */ - String key_name(); -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/Messages.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/Messages.java new file mode 100644 index 000000000..7b133213f --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/Messages.java @@ -0,0 +1,27 @@ +package com.espressif.idf.core.tools; + +import org.eclipse.osgi.util.NLS; + + +public class Messages extends NLS +{ + private static final String BUNDLE_NAME = "com.espressif.idf.core.tools.messages"; //$NON-NLS-1$ + + public static String InstallToolsHandler_CopyingOpenOCDRules; + public static String InstallToolsHandler_OpenOCDRulesCopyWarning; + public static String InstallToolsHandler_OpenOCDRulesCopyWarningMessage; + public static String InstallToolsHandler_OpenOCDRulesNotCopied; + public static String InstallToolsHandler_OpenOCDRulesCopyPaths; + public static String InstallToolsHandler_OpenOCDRulesCopyError; + public static String InstallToolsHandler_OpenOCDRulesCopied; + + static + { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } + + private Messages() + { + } +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/SetupToolsInIde.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/SetupToolsInIde.java new file mode 100644 index 000000000..90e5f1c11 --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/SetupToolsInIde.java @@ -0,0 +1,564 @@ +/******************************************************************************* + * Copyright 2025 Espressif Systems (Shanghai) PTE LTD. All rights reserved. + * Use is subject to license terms. + *******************************************************************************/ +package com.espressif.idf.core.tools; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.MessageBox; +import org.eclipse.ui.console.MessageConsoleStream; + +import com.espressif.idf.core.IDFConstants; +import com.espressif.idf.core.IDFCorePlugin; +import com.espressif.idf.core.IDFEnvironmentVariables; +import com.espressif.idf.core.ProcessBuilderFactory; +import com.espressif.idf.core.logging.Logger; +import com.espressif.idf.core.toolchain.ESPToolChainManager; +import com.espressif.idf.core.tools.util.ToolsUtility; +import com.espressif.idf.core.tools.vo.EimJson; +import com.espressif.idf.core.tools.vo.IdfInstalled; +import com.espressif.idf.core.util.IDFUtil; +import com.espressif.idf.core.util.StringUtil; + +/** + * This job is responsible for setting up the esp-idf in the IDE + * @author Ali Azam Rana + * + */ +public class SetupToolsInIde extends Job +{ + private EimJson eimJson; + private IdfInstalled idfInstalled; + private MessageConsoleStream errorConsoleStream; + private MessageConsoleStream standardConsoleStream; + private Map envVarsFromActivationScriptMap; + private Map existingEnvVarsInIdeForRollback; + + public SetupToolsInIde(IdfInstalled idfInstalled, EimJson eimJson, MessageConsoleStream errorConsoleStream, MessageConsoleStream standardConsoleStream) + { + super("Tools Setup"); //$NON-NLS-1$ + this.idfInstalled = idfInstalled; + this.eimJson = eimJson; + this.errorConsoleStream = errorConsoleStream; + this.standardConsoleStream = standardConsoleStream; + } + + @Override + protected IStatus run(IProgressMonitor monitor) + { + return setupTools(monitor); + } + + public void rollback() + { + IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); + + for (Entry entry : existingEnvVarsInIdeForRollback.entrySet()) + { + idfEnvironmentVariables.addEnvVariable(entry.getKey(), entry.getValue()); + } + IDFUtil.updateEspressifPrefPageOpenocdPath(); + try + { + setUpToolChainsAndTargets(true); + } + catch (Exception e) + { + Logger.log(e); + } + } + + private IStatus setupTools(IProgressMonitor monitor) + { + monitor.beginTask("Setting up tools in IDE", 7); //$NON-NLS-1$ + monitor.worked(1); + List arguemnts = new ArrayList<>(); + Map env = new HashMap<>(System.getenv()); + addGitToEnvironment(env, eimJson.getGitPath()); + arguemnts = ToolsUtility.getExportScriptCommand(idfInstalled.getActivationScript()); + final ProcessBuilderFactory processBuilderFactory = new ProcessBuilderFactory(); + try + { + monitor.setTaskName("Running Activation Script"); //$NON-NLS-1$ + IStatus status = processBuilderFactory.runInBackground(arguemnts, Path.ROOT, System.getenv()); + if (status == null) + { + Logger.log(IDFCorePlugin.getPlugin(), IDFCorePlugin.errorStatus("Status returned null from activation script process", null)); //$NON-NLS-1$ + return IDFCorePlugin.errorStatus("Status returned null from activation script process", null); //$NON-NLS-1$ + } + + if (status.getSeverity() == IStatus.ERROR) + { + log(status.getException() != null ? status.getException().getMessage() : status.getMessage(), IStatus.ERROR); + return status; + } + + // now setup in IDE + + String activationScriptOutput = status.getMessage(); + if (StringUtil.isEmpty(activationScriptOutput)) + { + log("Activation Script Output must not be empty", IStatus.ERROR); //$NON-NLS-1$ + return IDFCorePlugin.errorStatus("Activation Script Output must not be empty", null); //$NON-NLS-1$ + } + + monitor.worked(1); + + log(activationScriptOutput, IStatus.OK); + monitor.setTaskName("Processing output from activation script"); //$NON-NLS-1$ + log("Processing output from activation script", IStatus.INFO); //$NON-NLS-1$ + envVarsFromActivationScriptMap = parseEnvKeys(activationScriptOutput); + monitor.worked(1); + + monitor.setTaskName("Setting up IDE environment"); //$NON-NLS-1$ + log("Setting up IDE environment variables", IStatus.INFO); //$NON-NLS-1$ + setupEnvVarsInEclipse(); + monitor.worked(1); + + monitor.setTaskName("Setting up toolchains"); //$NON-NLS-1$ + log("Setting up toolchains", IStatus.INFO); //$NON-NLS-1$ + setUpToolChainsAndTargets(false); + monitor.worked(1); + + monitor.setTaskName("Installing pyhton dependency web-socket"); //$NON-NLS-1$ + log("Installing pyhton dependency web-socket", IStatus.INFO); //$NON-NLS-1$ + handleWebSocketClientInstall(); + monitor.worked(1); + + monitor.setTaskName("Copying OpenOCD Rules"); //$NON-NLS-1$ + log("Copying OpenOCD Rules", IStatus.INFO); //$NON-NLS-1$ + copyOpenOcdRules(); + monitor.worked(1); + + log("Tools Setup complete", IStatus.INFO); //$NON-NLS-1$ + + return Status.OK_STATUS; + } + catch (IOException e) + { + Logger.log(e); + return IDFCorePlugin.errorStatus(e.getMessage(), e); + } + } + + private void copyOpenOcdRules() + { + if (Platform.getOS().equals(Platform.OS_LINUX) + && !IDFUtil.getOpenOCDLocation().equalsIgnoreCase(StringUtil.EMPTY)) + { + log(Messages.InstallToolsHandler_CopyingOpenOCDRules, IStatus.OK); + // Copy the rules to the idf + StringBuilder pathToRules = new StringBuilder(); + pathToRules.append(IDFUtil.getOpenOCDLocation()); + pathToRules.append("/../share/openocd/contrib/60-openocd.rules"); //$NON-NLS-1$ + File rulesFile = new File(pathToRules.toString()); + if (rulesFile.exists()) + { + java.nio.file.Path source = Paths.get(pathToRules.toString()); + java.nio.file.Path target = Paths.get("/etc/udev/rules.d/60-openocd.rules"); //$NON-NLS-1$ + log(String.format(Messages.InstallToolsHandler_OpenOCDRulesCopyPaths, source.toString(), + target.toString()), IStatus.OK); + + Display.getDefault().syncExec(new Runnable() + { + @Override + public void run() + { + try + { + if (target.toFile().exists()) + { + MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell(), + SWT.ICON_WARNING | SWT.YES | SWT.NO); + messageBox.setText(Messages.InstallToolsHandler_OpenOCDRulesCopyWarning); + messageBox.setMessage(Messages.InstallToolsHandler_OpenOCDRulesCopyWarningMessage); + int response = messageBox.open(); + if (response == SWT.YES) + { + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); + } + else + { + log(Messages.InstallToolsHandler_OpenOCDRulesNotCopied, IStatus.ERROR); + return; + } + } + else + { + Files.copy(source, target); + } + + log(Messages.InstallToolsHandler_OpenOCDRulesCopied, IStatus.OK); + } + catch (IOException e) + { + Logger.log(e); + log(Messages.InstallToolsHandler_OpenOCDRulesCopyError, IStatus.ERROR); + } + } + }); + } + } + } + + private IStatus handleWebSocketClientInstall() + { + String websocketClient = "websocket-client"; //$NON-NLS-1$ + // pip install websocket-client + List arguments = new ArrayList(); + final String pythonEnvPath = IDFUtil.getIDFPythonEnvPath(envVarsFromActivationScriptMap.get(IDFEnvironmentVariables.IDF_PYTHON_ENV_PATH)); + if (pythonEnvPath == null || !new File(pythonEnvPath).exists()) + { + log(String.format("%s executable not found. Unable to run `%s -m pip install websocket-client`", //$NON-NLS-1$ + IDFConstants.PYTHON_CMD, IDFConstants.PYTHON_CMD), IStatus.ERROR); + return IDFCorePlugin.errorStatus( + String.format("%s executable not found. Unable to run `%s -m pip install websocket-client`", //$NON-NLS-1$ + IDFConstants.PYTHON_CMD, IDFConstants.PYTHON_CMD), + null); + } + arguments.add(pythonEnvPath); + arguments.add("-m"); //$NON-NLS-1$ + arguments.add("pip"); //$NON-NLS-1$ + arguments.add("list"); //$NON-NLS-1$ + + ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); + + try + { + log("Executing " + arguments.toString(), IStatus.OK); //$NON-NLS-1$) + + Map environment = new HashMap<>(System.getenv()); + prepEnvMap(environment); + Logger.log(environment.toString()); + + IStatus status = processRunner.runInBackground(arguments, org.eclipse.core.runtime.Path.ROOT, environment); + if (status == null) + { + Logger.log(IDFCorePlugin.getPlugin(), + IDFCorePlugin.errorStatus("Unable to get the process status.", null)); //$NON-NLS-1$ + log("Unable to get the process status", IStatus.ERROR); //$NON-NLS-1$ + return IDFCorePlugin.errorStatus("Unable to get the process status.", null); //$NON-NLS-1$ + } + + String cmdOutput = status.getMessage(); + if (cmdOutput.contains(websocketClient)) + { + return IDFCorePlugin.okStatus("websocket-client already installed", null); //$NON-NLS-1$ + } + + // websocket client not installed so installing it now. + arguments.remove(arguments.size() - 1); + arguments.add("install"); //$NON-NLS-1$ + arguments.add(websocketClient); + + status = processRunner.runInBackground(arguments, org.eclipse.core.runtime.Path.ROOT, environment); + if (status == null) + { + Logger.log(IDFCorePlugin.getPlugin(), + IDFCorePlugin.errorStatus("Unable to get the process status.", null)); //$NON-NLS-1$ + log("Unable to get the process status", IStatus.ERROR); //$NON-NLS-1$ + return IDFCorePlugin.errorStatus("Unable to get the process status.", null); //$NON-NLS-1$ + } + + log(status.getMessage(), IStatus.OK); + + return status; + } + catch (Exception e1) + { + Logger.log(IDFCorePlugin.getPlugin(), e1); + if (errorConsoleStream != null) + { + errorConsoleStream.println(e1.getLocalizedMessage()); + } + return IDFCorePlugin.errorStatus(e1.getLocalizedMessage(), e1); // $NON-NLS-1$; + } + } + + private String replacePathVariable(String value) + { + // Get system PATH + Map systemEnv = new HashMap<>(System.getenv()); + String pathEntry = systemEnv.get("PATH"); //$NON-NLS-1$ + if (pathEntry == null) + { + pathEntry = systemEnv.get("Path"); // for Windows //$NON-NLS-1$ + if (pathEntry == null) // no idea + { + Logger.log(new Exception("No PATH found in the system environment variables")); //$NON-NLS-1$ + } + } + + if (!StringUtil.isEmpty(pathEntry)) + { + value = value.concat(File.pathSeparator).concat(pathEntry); + } + + if (Platform.getOS().equals(Platform.OS_MACOSX)) + { + value = value.concat(File.pathSeparator).concat("/opt/homebrew/bin").concat(File.pathSeparator).concat("/usr/local/bin"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + return value; + } + + private IStatus loadTargetsAvailableFromIdfInCurrentToolSet(boolean rollback) + { + List arguments = new ArrayList(); + arguments.add(rollback + ? IDFUtil.getIDFPythonEnvPath( + existingEnvVarsInIdeForRollback.get(IDFEnvironmentVariables.IDF_PYTHON_ENV_PATH)) + : IDFUtil.getIDFPythonEnvPath( + envVarsFromActivationScriptMap.get(IDFEnvironmentVariables.IDF_PYTHON_ENV_PATH))); + arguments + .add(IDFUtil + .getIDFPythonScriptFile( + rollback ? existingEnvVarsInIdeForRollback.get(IDFEnvironmentVariables.IDF_PATH) + : envVarsFromActivationScriptMap.get(IDFEnvironmentVariables.IDF_PATH)) + .getAbsolutePath()); + arguments.add(IDFConstants.IDF_LIST_TARGETS_CMD); + log("Executing:" + arguments.toString(), IStatus.OK); //$NON-NLS-1$ + + Map env = new HashMap(System.getenv()); + prepEnvMap(env); + ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); + StringBuilder output = new StringBuilder(); + int waitCount = 10; + try + { + Process process = processRunner.run(arguments, org.eclipse.core.runtime.Path.ROOT, env); + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line; + while ((line = reader.readLine()) != null) + { + output.append(line).append(System.lineSeparator()); + } + + while (process.isAlive() && waitCount > 0) + { + try + { + Thread.sleep(300); + } + catch (InterruptedException e) + { + Logger.log(e); + } + waitCount--; + } + + if (waitCount == 0) + { + log("Process possibly stuck", IStatus.ERROR); //$NON-NLS-1$ + return Status.CANCEL_STATUS; + } + + IStatus status = new Status(process.exitValue() == 0 ? IStatus.OK : IStatus.ERROR, IDFCorePlugin.PLUGIN_ID, + process.exitValue(), output.toString(), null); + if (status.getSeverity() == IStatus.ERROR) + { + log(status.getException() != null ? status.getException().getMessage() : status.getMessage(), IStatus.ERROR); + } + + log(status.getMessage(), IStatus.OK); + + return status; + } + catch (IOException e) + { + log(e.getMessage(), e); + return IDFCorePlugin.errorStatus(e.getMessage(), e); + } + } + + private void prepEnvMap(Map env) + { + env.put("PYTHONUNBUFFERED", "1"); //$NON-NLS-1$ //$NON-NLS-2$ + loadIdfPathWithSystemPath(env); + addGitToEnvironment(env, eimJson.getGitPath()); + } + + private void loadIdfPathWithSystemPath(Map systemEnv) + { + String idfExportPath = envVarsFromActivationScriptMap.get(IDFEnvironmentVariables.PATH); + String pathVar = "PATH"; // for Windows //$NON-NLS-1$ + String pathEntry = systemEnv.get(pathVar); // $NON-NLS-1$ + if (pathEntry == null) + { + pathVar = "Path"; //$NON-NLS-1$ + pathEntry = systemEnv.get(pathVar); + if (pathEntry == null) // no idea + { + Logger.log(new Exception("No PATH found in the system environment variables")); //$NON-NLS-1$ + } + } + + if (!StringUtil.isEmpty(pathEntry)) + { + idfExportPath = idfExportPath.replace("$PATH", pathEntry); // macOS //$NON-NLS-1$ + idfExportPath = idfExportPath.replace("%PATH%", pathEntry); // Windows //$NON-NLS-1$ + } + systemEnv.put(pathVar, idfExportPath); + for (Entry entry : envVarsFromActivationScriptMap.entrySet()) + { + if (entry.getKey().equals(IDFEnvironmentVariables.PATH)) + continue; + + systemEnv.put(entry.getKey(), entry.getValue()); + } + } + + private void setUpToolChainsAndTargets(boolean rollback) + { + IStatus status = loadTargetsAvailableFromIdfInCurrentToolSet(rollback); + if (status.getSeverity() == IStatus.ERROR) + { + Logger.log("Unable to get IDF targets from current toolset"); //$NON-NLS-1$ + return; + } + + List targets = extractTargets(status.getMessage()); + ESPToolChainManager espToolChainManager = new ESPToolChainManager(); + espToolChainManager.removeLaunchTargetsNotPresent(targets); + espToolChainManager.removeCmakeToolChains(); + espToolChainManager.removeStdToolChains(); + espToolChainManager.configureToolChain(targets); + } + + private List extractTargets(String input) + { + List targets = new ArrayList(); + Pattern pattern = Pattern.compile("^esp32.*", Pattern.MULTILINE); //$NON-NLS-1$ + Matcher matcher = pattern.matcher(input); + while (matcher.find()) + { + targets.add(matcher.group()); + } + return targets; + } + + private void setupEnvVarsInEclipse() + { + createExistingBackup(); + IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); + for (Entry entry : envVarsFromActivationScriptMap.entrySet()) + { + idfEnvironmentVariables.addEnvVariable(entry.getKey(), entry.getValue()); + } + + String path = replacePathVariable(envVarsFromActivationScriptMap.get(IDFEnvironmentVariables.PATH)); + idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.PATH, path); + + idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.IDF_COMPONENT_MANAGER, "1"); //$NON-NLS-1$ + // IDF_MAINTAINER=1 to be able to build with the clang toolchain + idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.IDF_MAINTAINER, "1"); //$NON-NLS-1$ + idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.ESP_IDF_EIM_ID, idfInstalled.getId()); + + IDFUtil.updateEspressifPrefPageOpenocdPath(); + } + + private void createExistingBackup() + { + if (existingEnvVarsInIdeForRollback == null) + { + existingEnvVarsInIdeForRollback = new HashMap<>(); + } + + IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); + existingEnvVarsInIdeForRollback.putAll(idfEnvironmentVariables.getEnvMap()); + } + + private Map parseEnvKeys(String activationScriptOutput) + { + return Arrays.stream(activationScriptOutput.split(System.lineSeparator())).map(String::trim) + .filter(line -> line.contains("=")) //$NON-NLS-1$ + .map(line -> line.split("=", 2)) //$NON-NLS-1$ + .filter(parts -> parts.length == 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) + .collect(Collectors.toMap(parts -> parts[0].trim(), parts -> parts[1].trim())); + } + + private void log(final String message, final int severity) + { + Logger.log(message); + if (severity == IStatus.ERROR) + { + printToErrorConsole(message); + } + else + { + printToStandardConsole(message); + } + + } + + private void log(final String message, Exception e) + { + Logger.log(message); + Logger.log(e); + printToErrorConsole(message); + + } + + private void printToErrorConsole(String message) + { + if (errorConsoleStream != null) + { + errorConsoleStream.println(message); + } + } + + private void printToStandardConsole(String message) + { + if (standardConsoleStream != null) + { + standardConsoleStream.println(message); + } + } + + private void addGitToEnvironment(Map envMap, String executablePath) + { + IPath gitPath = new Path(executablePath); + if (gitPath.toFile().exists()) + { + String gitDir = gitPath.removeLastSegments(1).toOSString(); + String path1 = envMap.get("PATH"); //$NON-NLS-1$ + String path2 = envMap.get("Path"); //$NON-NLS-1$ + if (!StringUtil.isEmpty(path1) && !path1.contains(gitDir)) // Git not found on the PATH environment + { + path1 = gitDir.concat(";").concat(path1); //$NON-NLS-1$ + envMap.put("PATH", path1); //$NON-NLS-1$ + } + else if (!StringUtil.isEmpty(path2) && !path2.contains(gitDir)) // Git not found on the Path environment + { + path2 = gitDir.concat(";").concat(path2); //$NON-NLS-1$ + envMap.put("Path", path2); //$NON-NLS-1$ + } + } + } + +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolInitializer.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolInitializer.java new file mode 100644 index 000000000..3c3d51f81 --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolInitializer.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright 2025 Espressif Systems (Shanghai) PTE LTD. All rights reserved. + * Use is subject to license terms. + *******************************************************************************/ +package com.espressif.idf.core.tools; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Platform; +import org.osgi.service.prefs.Preferences; + +import com.espressif.idf.core.logging.Logger; +import com.espressif.idf.core.tools.vo.EimJson; + +/** + * Initializer class to be used on startup of eclipse and also + * to help with tools initialization + * @author Ali Azam Rana + * + */ +public class ToolInitializer +{ + private final Preferences preferences; + private final EimIdfConfiguratinParser parser; + + public ToolInitializer(Preferences preferences) + { + this.preferences = preferences; + this.parser = new EimIdfConfiguratinParser(); + } + + public boolean isEimInstalled() + { + return isEimIdfJsonPresent(); + } + + public EimJson loadEimJson() + { + try + { + return parser.getEimJson(true); + } + catch (IOException e) + { + Logger.log(e); + return null; + } + } + + public boolean isOldEspIdfConfigPresent() + { + return getOldConfigFile().exists(); + } + + public void exportOldConfigIfNeeded(String exportPath) throws IOException + { + File oldConfig = getOldConfigFile(); + if (oldConfig.exists()) + { + File destinationFile = new File(exportPath, oldConfig.getName()); + Files.copy(oldConfig.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + preferences.putBoolean(EimConstants.OLD_CONFIG_EXPORTED_FLAG, true); + } + } + + public boolean isOldConfigExported() + { + return preferences.getBoolean(EimConstants.OLD_CONFIG_EXPORTED_FLAG, false); + } + + private File getOldConfigFile() + { + IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation(); + return new File(path.toOSString(), EimConstants.TOOL_SET_CONFIG_LEGACY_CONFIG_FILE); + } + + private boolean isEimIdfJsonPresent() + { + String path = Platform.getOS().equals(Platform.OS_WIN32) ? EimConstants.EIM_WIN_PATH + : EimConstants.EIM_POSIX_PATH; + return new File(path).exists(); + } + + public boolean isEspIdfSet() + { + return preferences.getBoolean(EimConstants.INSTALL_TOOLS_FLAG, false); + } +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolSetConfigurationManager.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolSetConfigurationManager.java deleted file mode 100644 index e24d81ee1..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolSetConfigurationManager.java +++ /dev/null @@ -1,279 +0,0 @@ -/******************************************************************************* - * Copyright 2024 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.cdt.cmake.core.ICMakeToolChainFile; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; - -import com.espressif.idf.core.IDFEnvironmentVariables; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.toolchain.ESPToolChainManager; -import com.espressif.idf.core.toolchain.ESPToolchain; -import com.espressif.idf.core.tools.vo.IDFToolSet; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -/** - * The class is responsible for managing the idf tool sets - * export and import configuration params from json in workspace - * - * @author Ali Azam Rana - * - */ -public class ToolSetConfigurationManager -{ - private List idfToolSets; - private Gson gson; - private boolean reload; - - public ToolSetConfigurationManager() - { - gson = new GsonBuilder().setPrettyPrinting().enableComplexMapKeySerialization() - .excludeFieldsWithoutExposeAnnotation().create(); - } - - public void delete(IDFToolSet idfToolSet) - { - reload = true; - getIdfToolSets(false); - // cleanup the env and toolchains - IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); - idfEnvironmentVariables.removeAllEnvVariables(); - try - { - ESPToolChainManager espToolChainManager = new ESPToolChainManager(); - espToolChainManager.removeCmakeToolChains(); - espToolChainManager.removeStdToolChains(); - } - catch (Exception e) - { - Logger.log(e); - } - - // update the json now to remove the idf from it. - List idfToolSetsToExport = new ArrayList(); - for (IDFToolSet idfTool : idfToolSets) - { - if (idfTool.getIdfLocation().equals(idfToolSet.getIdfLocation())) - { - continue; - } - - idfToolSetsToExport.add(idfTool); - } - - try (FileWriter fileWriter = new FileWriter(toolSetConfigFilePath())) - { - gson.toJson(idfToolSetsToExport, fileWriter); - } - catch (IOException e) - { - Logger.log(e); - } - getIdfToolSets(false); - reload = false; - } - - public boolean isToolSetAlreadyPresent(String idfPath) - { - List idfToolSets = getIdfToolSets(false); - if (idfToolSets == null) - { - return false; - } - return idfToolSets.stream().filter(toolSet -> toolSet.getIdfLocation().equals(idfPath)).findAny().isPresent(); - } - - public List getIdfToolSets(boolean loadToolchains) - { - if (reload || idfToolSets == null || idfToolSets.isEmpty()) - { - idfToolSets = importToolSets(); - } - - if (loadToolchains && idfToolSets != null) - { - try - { - loadToolChainsInImportedToolSets(); - } - catch (CoreException e) - { - Logger.log(e); - } - } - return idfToolSets; - } - - private List importToolSets() - { - Type listType = new TypeToken>() - { - }.getType(); - List idfToolSets = new ArrayList<>(); - File toolSetFile = new File(toolSetConfigFilePath()); - if (!toolSetFile.exists()) - { - try - { - toolSetFile.createNewFile(); - } - catch (IOException e) - { - Logger.log(e); - } - } - - try (FileReader fileReader = new FileReader(toolSetConfigFilePath())) - { - idfToolSets = gson.fromJson(fileReader, listType); - } - catch (IOException e) - { - Logger.log(e); - } - - return idfToolSets; - } - - private void loadToolChainsInImportedToolSets() throws CoreException - { - ESPToolChainManager espToolChainManager = new ESPToolChainManager(); - for (IDFToolSet idfToolSet : idfToolSets) - { - String pathToLookForToolChains = idfToolSet.getEnvVars().get(IDFEnvironmentVariables.PATH); - String idfPath = idfToolSet.getEnvVars().get(IDFEnvironmentVariables.IDF_PATH); - Logger.log("Using: " + idfPath + " to find toolchains"); //$NON-NLS-1$//$NON-NLS-2$ - Logger.log("Env used: " + idfToolSet.getEnvVars()); //$NON-NLS-1$ - List espToolChains = espToolChainManager - .getStdToolChains(Arrays.asList(pathToLookForToolChains.split(File.pathSeparator)), idfPath); - idfToolSet.setEspStdToolChains(espToolChains); - List cMakeToolChainFiles = espToolChainManager.getCmakeToolChains(idfPath); - idfToolSet.setEspCmakeToolChainFiles(cMakeToolChainFiles); - } - } - - /** - * Looks for the existing idf tools from the given location if they are found it replaces the previous one - * - * @param idfToolSet IDFToolSet to add {@link IDFToolSet}@ - */ - public void export(IDFToolSet idfToolSet) - { - File toolSetConfigFile = new File(toolSetConfigFilePath()); - List idfToolSets = null; - Type listType = new TypeToken>() - { - }.getType(); - - if (toolSetConfigFile.exists()) - { - try (FileReader fileReader = new FileReader(toolSetConfigFile)) - { - idfToolSets = gson.fromJson(fileReader, listType); - } - catch (IOException e) - { - Logger.log(e); - return; - } - } - if (idfToolSets == null) - { - idfToolSets = new ArrayList<>(); - } - - // If the toolSet to be exported is active, set all others to inactive - if (idfToolSet.isActive()) - { - for (IDFToolSet toolSet : idfToolSets) - { - toolSet.setActive(false); // Set all to inactive - } - } - - boolean found = false; - for (int i = 0; i < idfToolSets.size(); i++) - { - IDFToolSet existingToolSet = idfToolSets.get(i); - if (existingToolSet.getId() == idfToolSet.getId()) - { - idfToolSets.set(i, idfToolSet); - found = true; - break; - } - } - - // If the toolSet was not found, add it to the list - if (!found) - { - idfToolSets.add(idfToolSet); - } - - try (FileWriter fileWriter = new FileWriter(toolSetConfigFile)) - { - gson.toJson(idfToolSets, fileWriter); - } - catch (IOException e) - { - Logger.log(e); - } - - } - - public void updateToolSetConfiguration(IDFToolSet idfToolSet) - { - reload = true; - getIdfToolSets(false); - List idfToolSetsToExport = new ArrayList(); - for (IDFToolSet existingIdfToolSet : idfToolSets) - { - if (idfToolSet.getId() == existingIdfToolSet.getId()) - { - idfToolSetsToExport.add(idfToolSet); - } - else - { - idfToolSetsToExport.add(existingIdfToolSet); - } - } - - try (FileWriter fileWriter = new FileWriter(toolSetConfigFilePath())) - { - gson.toJson(idfToolSets, fileWriter); - } - catch (IOException e) - { - Logger.log(e); - } - } - - private String toolSetConfigFilePath() - { - IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation(); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(path.toOSString()); - stringBuilder.append(File.separatorChar); - stringBuilder.append(IToolsInstallationWizardConstants.TOOL_SET_CONFIG_FILE); - return stringBuilder.toString(); - } - - public void setReload(boolean reload) - { - this.reload = reload; - } -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsJsonParser.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsJsonParser.java deleted file mode 100644 index bb35f5d14..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsJsonParser.java +++ /dev/null @@ -1,238 +0,0 @@ -/******************************************************************************* - * Copyright 2021 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.runtime.Platform; - -import com.espressif.idf.core.tools.vo.ToolsVO; -import com.espressif.idf.core.tools.vo.VersionDetailsVO; -import com.espressif.idf.core.tools.vo.VersionsVO; -import com.espressif.idf.core.util.IDFUtil; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.stream.JsonReader; - -/** - * Tools json parser. - * - * @author Ali Azam Rana - * - */ -public class ToolsJsonParser -{ - private Gson gson; - private List toolsList; - private List requiredToolsList; - private static final String[] REQUIRED_TOOLS = new String[] {"cmake", "dfu-util", "ninja"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - public ToolsJsonParser() - { - gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); - toolsList = new ArrayList<>(); - requiredToolsList = new ArrayList<>(); - } - - public void loadJson() throws Exception - { - toolsList.clear(); - JsonReader jsonReader = new JsonReader(new FileReader(IDFUtil.getIDFToolsJsonFileForInstallation())); - JsonObject jsonObject = gson.fromJson(jsonReader, JsonObject.class); - JsonArray jsonArray = jsonObject.get(IToolsJsonKeys.TOOLS_KEY).getAsJsonArray(); - List reqToolsNamesList = Arrays.asList(REQUIRED_TOOLS); - for (int i = 0; i < jsonArray.size(); i++) - { - JsonObject toolsJsonObject = jsonArray.get(i).getAsJsonObject(); - ToolsVO toolsVO = new ToolsVO(); - toolsVO.setDescription(toolsJsonObject.get(IToolsJsonKeys.DESCRIPTION_KEY).getAsString()); - if (toolsJsonObject.get(IToolsJsonKeys.EXPORT_PATHS_KEY).getAsJsonArray().size() > 0) - { - toolsVO.setExportPaths(getStringsListFromJsonArray( - toolsJsonObject.get(IToolsJsonKeys.EXPORT_PATHS_KEY).getAsJsonArray().get(0).getAsJsonArray())); - } - toolsVO.setExportVars( - getExportVarsMapFromJsonObject(toolsJsonObject.get(IToolsJsonKeys.EXPORT_VARS_KEY).getAsJsonObject())); - toolsVO.setInfoUrl(toolsJsonObject.get(IToolsJsonKeys.INFO_URL_KEY).getAsString()); - toolsVO.setInstallType(toolsJsonObject.get(IToolsJsonKeys.INSTALL_KEY).getAsString()); - toolsVO.setLicesnse(toolsJsonObject.get(IToolsJsonKeys.LICENSE_KEY).getAsString()); - toolsVO.setName(toolsJsonObject.get(IToolsJsonKeys.NAME_KEY).getAsString()); - if (toolsJsonObject.get(IToolsJsonKeys.SUPPORTED_TARGETS_KEY) != null) - { - toolsVO.setSupportedTargets( - getStringsListFromJsonArray(toolsJsonObject.get(IToolsJsonKeys.SUPPORTED_TARGETS_KEY).getAsJsonArray())); - } - toolsVO.setVersionCmd(getStringsListFromJsonArray(toolsJsonObject.get(IToolsJsonKeys.VERSION_CMD_KEY).getAsJsonArray())); - toolsVO.setVersionRegex(toolsJsonObject.get(IToolsJsonKeys.VERSION_REGEX).getAsString()); - toolsVO.setVersionVO(getVersions(toolsJsonObject.get(IToolsJsonKeys.VERSIONS_VO_KEY).getAsJsonArray())); - toolsVO.setVersion(jsonObject.get(IToolsJsonKeys.VERSION_KEY).getAsString()); - JsonElement jsonElement = toolsJsonObject.get(IToolsJsonKeys.PLATFORM_OVERRIDES_KEY); - if (jsonElement != null) - { - adjustPlatformOverrides(jsonElement.getAsJsonArray(), toolsVO); - } - - toolsList.add(toolsVO); - if (reqToolsNamesList.contains(toolsVO.getName())) - { - requiredToolsList.add(toolsVO); - } - } - } - - private void adjustPlatformOverrides(JsonArray jsonArray, ToolsVO toolsVO) throws Exception - { - String currentOS = Platform.getOS(); - if (currentOS.equals(Platform.OS_WIN32)) - { - currentOS = "win"; //$NON-NLS-1$ - } - - if (currentOS.contains(Platform.OS_MACOSX)) - { - Process p = Runtime.getRuntime().exec("uname -m"); //$NON-NLS-1$ - InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream()); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - String output = bufferedReader.readLine(); - if (!output.contains("arm64")) //$NON-NLS-1$ - { - currentOS = "macos"; //$NON-NLS-1$ - } - else - { - currentOS = "macos-".concat(output); //$NON-NLS-1$ - inputStreamReader.close(); - bufferedReader.close(); - } - } - - for (int i = 0; i < jsonArray.size(); i++) - { - JsonObject jsonObject = jsonArray.get(i).getAsJsonObject(); - JsonArray platformArray = jsonObject.get(IToolsJsonKeys.PLATFORMS_KEY).getAsJsonArray(); - for (int j = 0; j < platformArray.size(); j++) - { - String platform = platformArray.get(j).getAsString(); - if (platform.contains(currentOS)) - { - Set keys = jsonObject.keySet(); - keys.remove(IToolsJsonKeys.PLATFORMS_KEY); - for(String key : keys) - { - JsonElement element = jsonObject.get(key); - if (element.isJsonArray()) - { - List list = getStringsListFromJsonArray(element.getAsJsonArray().get(0).getAsJsonArray()); - injectOverride(toolsVO, key, list); - } - else - { - injectOverride(toolsVO, key, element.getAsString()); - } - } - } - } - } - } - - private void injectOverride(ToolsVO toolsVO, String key, Object val) throws Exception - { - Field[] allFields = ToolsVO.class.getDeclaredFields(); - for (Field field : allFields) - { - if (field.isAnnotationPresent(JsonKey.class)) - { - JsonKey ann = field.getAnnotation(JsonKey.class); - if (ann.key_name().equals(key)) - { - field.trySetAccessible(); - field.set(toolsVO, val); - return; - } - } - } - } - - private List getVersions(JsonArray jsonArray) - { - List versionsVOs = new ArrayList(); - for (int i = 0; i < jsonArray.size(); i++) - { - JsonObject jsonObject = jsonArray.get(i).getAsJsonObject(); - VersionsVO versionsVO = new VersionsVO(); - Map versionDetailMap = new HashMap<>(); - for (String key : jsonObject.keySet()) - { - if (key.equalsIgnoreCase(IToolsJsonKeys.NAME_KEY) || key.equalsIgnoreCase(IToolsJsonKeys.STATUS_KEY)) - { - continue; - } - - VersionDetailsVO versionDetailsVO = new VersionDetailsVO(); - JsonObject osVersionDetailsObject = jsonObject.get(key).getAsJsonObject(); - versionDetailsVO.setSha256(osVersionDetailsObject.get(IToolsJsonKeys.SHA256_KEY).getAsString()); - versionDetailsVO.setSize(osVersionDetailsObject.get(IToolsJsonKeys.SIZE_KEY).getAsDouble()); - versionDetailsVO.setUrl(osVersionDetailsObject.get(IToolsJsonKeys.URL_KEY).getAsString()); - versionDetailMap.put(key, versionDetailsVO); - } - - versionsVO.setName(jsonObject.get(IToolsJsonKeys.NAME_KEY).getAsString()); - versionsVO.setStatus(jsonObject.get(IToolsJsonKeys.STATUS_KEY).getAsString()); - versionsVO.setVersionOsMap(versionDetailMap); - versionsVOs.add(versionsVO); - - } - - return versionsVOs; - } - - private List getStringsListFromJsonArray(JsonArray jsonArray) - { - List stringList = new ArrayList(); - if (jsonArray == null) - { - return stringList; - } - - for (int i = 0; i < jsonArray.size(); i++) - { - stringList.add(jsonArray.get(i).getAsString()); - } - return stringList; - } - - private Map getExportVarsMapFromJsonObject(JsonObject exportVars) - { - Map exportVarMap = new HashMap<>(); - for (String key : exportVars.keySet()) - { - exportVarMap.put(key, exportVars.get(key).getAsString()); - } - return exportVarMap; - } - - public List getToolsList() - { - return toolsList; - } - - public List getRequiredToolsList() - { - return requiredToolsList; - - } -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsPlatformMapping.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsPlatformMapping.java deleted file mode 100644 index 853e4363f..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsPlatformMapping.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright 2022 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools; - -import java.util.Arrays; - -import org.eclipse.core.runtime.Platform; - -import com.espressif.idf.core.logging.Logger; - -/** - * Mapping /tools/tools.json os to Eclipse platform os & arch - * - * @author kondal kolipaka - * - */ -public enum ToolsPlatformMapping -{ - // @formatter:off - - WIN32("win32", Platform.OS_WIN32,Platform.ARCH_X86), //$NON-NLS-1$ - WIN64("win64", Platform.OS_WIN32, Platform.ARCH_X86_64), //$NON-NLS-1$ - MACOS("macos", Platform.OS_MACOSX, Platform.ARCH_X86_64), //$NON-NLS-1$ - MACOSARM64("macos-arm64", Platform.OS_MACOSX, Platform.ARCH_AARCH64), //$NON-NLS-1$ - LINUXAMD64("linux-amd64", Platform.OS_LINUX, Platform.ARCH_X86_64), //$NON-NLS-1$ - LINUXARM64("linux-arm64", Platform.OS_LINUX, "arm64"), //$NON-NLS-1$ //$NON-NLS-2$ - LINUXARMEL("linux-armel", Platform.OS_LINUX, "armel"), //$NON-NLS-1$ //$NON-NLS-2$ - LINUXARMHF("linux-armhf", Platform.OS_LINUX, "armhf"), //$NON-NLS-1$ //$NON-NLS-2$ - LINUXI686("linux-i686", Platform.OS_LINUX, "i686"); //$NON-NLS-1$ //$NON-NLS-2$ - - // @formatter:on - - private final String toolsOS; - private final String os; - private final String arch; - - ToolsPlatformMapping(String toolsOS, String os, String arch) - { - this.toolsOS = toolsOS; - this.os = os; - this.arch = arch; - } - - public String getToolsOS() - { - return toolsOS; - } - - public String getOS() - { - return os; - } - - public String getArch() - { - return arch; - } - - public static boolean isSupported(String toolsOS) - { - final String os = Platform.getOS(); - final String arch = Platform.getOSArch(); - Logger.log("toolsOS:" + toolsOS + " os:" + os + " arch:" + arch, true); - - return Arrays.stream(ToolsPlatformMapping.values()).filter( - entry -> entry.getToolsOS().equals(toolsOS) && entry.getArch().equals(arch) && entry.getOS().equals(os)) - .count() > 0; - } - -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsSystemWrapper.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsSystemWrapper.java deleted file mode 100644 index 5ac2d9356..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/ToolsSystemWrapper.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright 2023 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools; - -import com.espressif.idf.core.SystemWrapper; - -/** - * Tools System wrapper to make sure to avoid the - * system path when verifying for validation after tools installation - * @author Ali Azam Rana - * - */ -public class ToolsSystemWrapper implements SystemWrapper -{ - private String path; - - public ToolsSystemWrapper(String path) - { - this.path = path; - } - - @Override - public String getPathEnv() - { - return path; - } - - @Override - public String getEnvExecutables() - { - return System.getenv(PATHEXT); - } - -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/messages.properties b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/messages.properties new file mode 100644 index 000000000..405d211cc --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/messages.properties @@ -0,0 +1,7 @@ +InstallToolsHandler_CopyingOpenOCDRules=Copying OpenOCD Rules +InstallToolsHandler_OpenOCDRulesCopyPaths=Copying File: %s to destination: %s +InstallToolsHandler_OpenOCDRulesCopyWarning=Warning +InstallToolsHandler_OpenOCDRulesCopyWarningMessage=The rules file is already present in the /etc/udev/rules.d/ directory, Do you want to replace the file with the file from OpenOCD directory +InstallToolsHandler_OpenOCDRulesNotCopied=Rules Not Copied to system +InstallToolsHandler_OpenOCDRulesCopyError=Unable to copy rules for OpenOCD to system directory, try running the eclipse with sudo command +InstallToolsHandler_OpenOCDRulesCopied=Rules Copied to system diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/util/ToolsUtility.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/util/ToolsUtility.java index 843d430f0..637b85369 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/util/ToolsUtility.java +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/util/ToolsUtility.java @@ -4,41 +4,17 @@ *******************************************************************************/ package com.espressif.idf.core.tools.util; -import java.io.BufferedInputStream; +import java.io.BufferedReader; import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.security.MessageDigest; -import java.text.DecimalFormat; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; -import org.apache.commons.compress.archivers.ArchiveEntry; -import org.apache.commons.compress.archivers.ArchiveInputStream; -import org.apache.commons.compress.archivers.ArchiveStreamFactory; -import org.apache.commons.compress.archivers.tar.TarArchiveEntry; -import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; -import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; -import org.apache.commons.compress.utils.IOUtils; -import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Platform; -import org.tukaani.xz.XZInputStream; import com.espressif.idf.core.IDFEnvironmentVariables; -import com.espressif.idf.core.SystemExecutableFinder; import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.tools.ToolsSystemWrapper; -import com.espressif.idf.core.tools.vo.ToolsVO; -import com.espressif.idf.core.util.FileUtil; -import com.espressif.idf.core.util.IDFUtil; -import com.espressif.idf.core.util.StringUtil; +import com.espressif.idf.core.tools.vo.IdfInstalled; /** * Utility class for Tools Management operations @@ -48,285 +24,78 @@ */ public class ToolsUtility { - private static final String SLASH = "\\"; //$NON-NLS-1$ - - private static final String FORWARD_SLASH = "/"; //$NON-NLS-1$ - - public static final String ESPRESSIF_HOME_DIR = System.getProperty("user.home").concat("/.espressif"); //$NON-NLS-1$ //$NON-NLS-2$ - - public static final String ESPRESSIF_HOME_TOOLS_DIR = ESPRESSIF_HOME_DIR.concat("/tools"); //$NON-NLS-1$ - - public static boolean isToolInstalled(String toolName, String versionsName) + public static String getIdfVersion(IdfInstalled idfInstalled, String gitPath) { - File homeDir = new File(ESPRESSIF_HOME_DIR); - if (!homeDir.exists()) - { - return false; - } + String activationScript = idfInstalled.getActivationScript(); + String espIdfVersion = null; - File toolDirectory = new File(ESPRESSIF_HOME_TOOLS_DIR.concat(FORWARD_SLASH).concat(toolName) - .concat(FORWARD_SLASH).concat(versionsName)); - if (toolDirectory.exists()) - { - IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); - String pathValue = idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.PATH); - String[] splittedPaths = pathValue.split(File.pathSeparator); - String directorySplittor = Platform.getOS().equals(Platform.OS_WIN32) ? SLASH : FORWARD_SLASH; - for (String splittedPath : splittedPaths) - { - if (splittedPath.contains(toolName.concat(directorySplittor).concat(versionsName))) - { - return true; - } - } - } - - return false; - } - - public static void removeToolDirectory(String toolName) throws IOException - { - File toolDirectory = new File(ESPRESSIF_HOME_TOOLS_DIR.concat(FORWARD_SLASH).concat(toolName)); - if (!toolDirectory.exists()) + try { - return; - } - FileUtil.deleteDirectory(toolDirectory); - } + // Determine the command to execute based on the OS + List args = getExportScriptCommand(activationScript); + String[] command = args.toArray(new String[args.size()]); + // Execute the script + ProcessBuilder processBuilder = new ProcessBuilder(command); + processBuilder.directory(new File(activationScript).getParentFile()); + processBuilder.redirectErrorStream(true); - public static String getFileExtension(String filename) - { - return Optional.ofNullable(filename).filter(f -> f.contains(".")) //$NON-NLS-1$ - .map(f -> f.substring(filename.lastIndexOf(".") + 1)).get(); //$NON-NLS-1$ - } + Process process = processBuilder.start(); - public static void extractZip(String zipFilePath, String extractDirectory) - { - InputStream inputStream = null; - try - { - Path filePath = Paths.get(zipFilePath); - inputStream = Files.newInputStream(filePath); - ArchiveStreamFactory archiveStreamFactory = new ArchiveStreamFactory(); - ArchiveInputStream archiveInputStream = archiveStreamFactory - .createArchiveInputStream(ArchiveStreamFactory.ZIP, inputStream); - ArchiveEntry archiveEntry = null; - while ((archiveEntry = archiveInputStream.getNextEntry()) != null) + // Read the script output + try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - Path path = Paths.get(extractDirectory, archiveEntry.getName()); - File file = path.toFile(); - if (archiveEntry.isDirectory()) - { - if (!file.isDirectory()) - { - file.mkdirs(); - } - } - else + String line; + while ((line = reader.readLine()) != null) { - File parent = file.getParentFile(); - if (!parent.isDirectory()) - { - parent.mkdirs(); - } - try (OutputStream outputStream = Files.newOutputStream(path)) + if (line.startsWith("ESP_IDF_VERSION=")) //$NON-NLS-1$ { - IOUtils.copy(archiveInputStream, outputStream); + espIdfVersion = line.split("=")[1]; //$NON-NLS-1$ + break; } } } - } - catch (Exception e) - { - Logger.log(e); - } - } - public static void extractTarGz(String tarFile, String outputDir) - { - Path pathInput = Paths.get(tarFile); - Path pathOutput = Paths.get(outputDir); - try - { - TarArchiveInputStream tararchiveinputstream = new TarArchiveInputStream( - new GzipCompressorInputStream(new BufferedInputStream(Files.newInputStream(pathInput)))); - - ArchiveEntry archiveentry = null; - while ((archiveentry = tararchiveinputstream.getNextEntry()) != null) - { - Path pathEntryOutput = pathOutput.resolve(archiveentry.getName()); - if (archiveentry.isDirectory()) - { - if (!Files.exists(pathEntryOutput)) - Files.createDirectories(pathEntryOutput); - } - else - { - Files.createDirectories(pathEntryOutput.getParent()); - Files.copy(tararchiveinputstream, pathEntryOutput, StandardCopyOption.REPLACE_EXISTING); - Runtime.getRuntime().exec("/bin/chmod 755 ".concat(pathEntryOutput.toString())); //$NON-NLS-1$ - } - - } - - tararchiveinputstream.close(); + process.waitFor(); } catch (Exception e) { Logger.log(e); } - } - - public static void extractTarXz(String tarFile, String outputDir) - { - Path pathOutput = Paths.get(outputDir); - Map symLinks = new HashMap<>(); - Map hardLinks = new HashMap<>(); - try - { - FileInputStream fileInputStream = new FileInputStream(tarFile); - BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); - XZInputStream xzInputStream = new XZInputStream(bufferedInputStream); - TarArchiveInputStream tararchiveinputstream = new TarArchiveInputStream(xzInputStream); - TarArchiveEntry archiveentry = null; - while ((archiveentry = tararchiveinputstream.getNextTarEntry()) != null) - { - Path pathEntryOutput = pathOutput.resolve(archiveentry.getName()); - if (archiveentry.isSymbolicLink()) - { - symLinks.put(pathEntryOutput, - pathOutput.resolve(archiveentry.getName()).getParent().resolve(archiveentry.getLinkName())); - continue; - } - else if (archiveentry.isLink()) - { - hardLinks.put(pathEntryOutput, - pathOutput.resolve(archiveentry.getLinkName())); - continue; - } - else if (archiveentry.isDirectory()) - { - if (!Files.exists(pathEntryOutput)) - Files.createDirectories(pathEntryOutput); - } - else - { - System.out.println(pathEntryOutput.toString() + " " + archiveentry.getSize()); //$NON-NLS-1$ - Files.copy(tararchiveinputstream, pathEntryOutput, StandardCopyOption.REPLACE_EXISTING); - Runtime.getRuntime().exec("/bin/chmod 755 ".concat(pathEntryOutput.toString())); //$NON-NLS-1$ - } - } - tararchiveinputstream.close(); - xzInputStream.close(); - fileInputStream.close(); - hardLinks.forEach(ToolsUtility::createHardLinks); - symLinks.forEach(ToolsUtility::createSymLinks); - } - catch (Exception e) - { - Logger.log(e); - } - } - - private static void createHardLinks(Path link, Path target) - { - try - { - Files.deleteIfExists(link); - Files.createLink(link, target); - } - catch (Exception e) - { - Logger.log(e); - } - } - - private static void createSymLinks(Path link, Path target) - { - try - { - Files.deleteIfExists(link); - Files.createSymbolicLink(link, target.toRealPath()); - } - catch (Exception e) - { - Logger.log(e); - } - } - public static String getReadableSizeMB(double size) - { - size /= 1024; // KB - size /= 1024; // MB - DecimalFormat df = new DecimalFormat("0.00"); //$NON-NLS-1$ - return String.valueOf(df.format(size)).concat(" MB"); //$NON-NLS-1$ + return espIdfVersion; } - - public static Map getAvailableToolVersions(ToolsVO toolsVo) + + public static List getExportScriptCommand(String activationScriptPath) { - Map availableVersions = new HashMap(); - File toolDirectory = new File( - ESPRESSIF_HOME_TOOLS_DIR.concat(FORWARD_SLASH).concat(toolsVo.getName()).concat(FORWARD_SLASH)); - if (toolDirectory.exists()) + List command = new ArrayList<>(); + if (Platform.getOS().equals(Platform.OS_WIN32)) { - for (File file : toolDirectory.listFiles()) - { - if (file.isDirectory()) - { - availableVersions.put(file.getName(), file.getAbsolutePath()); - } - } + command.add("powershell.exe"); //$NON-NLS-1$ + command.add("-ExecutionPolicy"); //$NON-NLS-1$ + command.add("Bypass"); //$NON-NLS-1$ + command.add("-File"); //$NON-NLS-1$ + command.add(activationScriptPath); + command.add("-e"); //$NON-NLS-1$ } - - return availableVersions; - } - - /** - * Gets the file checksum based on the provided message digest - * - * @param digest - * @param file - * @return - * @throws IOException - */ - public static String getFileChecksum(MessageDigest digest, File file) throws IOException - { - FileInputStream fis = new FileInputStream(file); - byte[] byteArray = new byte[1024]; - int bytesCount = 0; - while ((bytesCount = fis.read(byteArray)) != -1) + else if (Platform.getOS().equals(Platform.OS_LINUX)) { - digest.update(byteArray, 0, bytesCount); + command.add("/bin/bash"); //$NON-NLS-1$ + command.add(activationScriptPath); + command.add("-e"); //$NON-NLS-1$ } - ; - fis.close(); - byte[] bytes = digest.digest(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < bytes.length; i++) + else { - sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + command.add("/bin/zsh"); //$NON-NLS-1$ + command.add(activationScriptPath); + command.add("-e"); //$NON-NLS-1$ } - return sb.toString(); + return command; } - /** - * Gets the absolute path for the tool from the given path - * @param toolName tool to find absolute path - * @param path the path to variable to look into, if null System.getenv() will be used - * @return absolute path to the tool - */ - public static IPath findAbsoluteToolPath(String toolName, String path) + public static boolean isIdfInstalledActive(IdfInstalled idfInstalled) { - if (StringUtil.isEmpty(path)) - { - Map env = IDFUtil.getSystemEnv(); - if (env.containsKey(IDFEnvironmentVariables.PATH)) - path = env.get(IDFEnvironmentVariables.PATH); - else - path = env.get("Path"); //$NON-NLS-1$ - } - - SystemExecutableFinder systemExecutableFinder = new SystemExecutableFinder(new ToolsSystemWrapper(path)); - return systemExecutableFinder.find(toolName); + IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); + String espIdfIdEim = idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.ESP_IDF_EIM_ID); + return idfInstalled.getId().equals(espIdfIdEim); } } diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/EimJson.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/EimJson.java new file mode 100644 index 000000000..b6076d013 --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/EimJson.java @@ -0,0 +1,47 @@ +package com.espressif.idf.core.tools.vo; + +import java.util.Collections; +import java.util.List; + +import com.google.gson.annotations.Expose; + +public class EimJson +{ + @Expose + private String gitPath; + @Expose + private String idfSelectedId; + @Expose + private List idfInstalled = Collections.emptyList(); + + public String getGitPath() + { + return gitPath; + } + + public void setGitPath(String gitPath) + { + this.gitPath = gitPath; + } + + public String getIdfSelectedId() + { + return idfSelectedId; + } + + public void setIdfSelectedId(String idfSelectedId) + { + this.idfSelectedId = idfSelectedId; + } + + public List getIdfInstalled() + { + return idfInstalled; + } + + public void setIdfInstalled(List idfInstalled) + { + this.idfInstalled = idfInstalled; + } + +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/IDFToolSet.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/IDFToolSet.java deleted file mode 100644 index 50a750b54..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/IDFToolSet.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright 2024 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools.vo; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import org.eclipse.cdt.cmake.core.ICMakeToolChainFile; - -import com.espressif.idf.core.toolchain.ESPToolchain; -import com.google.gson.annotations.Expose; - -/** - * VO to hold the idf tools information that is read or exported to the configuration json - * - * @author Ali Azam Rana - * - */ -public class IDFToolSet implements Serializable -{ - private static final long serialVersionUID = -4899224940094139736L; - - @Expose - private int id; - - @Expose - private String idfLocation; - - @Expose - private String idfVersion; - - @Expose - private boolean active; - - @Expose - private String systemGitExecutablePath; - - @Expose - private String systemPythonExecutablePath; - - @Expose - private Map envVars; - - private List espStdToolChains; - private List espCmakeToolChainFiles; - private List launchTargets; - - public String getIdfLocation() - { - return idfLocation; - } - - public void setIdfLocation(String idfLocation) - { - this.idfLocation = idfLocation; - } - - public String getIdfVersion() - { - return idfVersion; - } - - public void setIdfVersion(String idfVersion) - { - this.idfVersion = idfVersion; - } - - public boolean isActive() - { - return active; - } - - public void setActive(boolean active) - { - this.active = active; - } - - public Map getEnvVars() - { - return envVars; - } - - public void setEnvVars(Map envVars) - { - this.envVars = envVars; - } - - public List getEspStdToolChains() - { - return espStdToolChains; - } - - public void setEspStdToolChains(List espStdToolChains) - { - this.espStdToolChains = espStdToolChains; - } - - public List getEspCmakeToolChainFiles() - { - return espCmakeToolChainFiles; - } - - public void setEspCmakeToolChainFiles(List espCmakeToolChainFiles) - { - this.espCmakeToolChainFiles = espCmakeToolChainFiles; - } - - public List getLaunchTargets() - { - return launchTargets; - } - - public void setLaunchTargets(List launchTargets) - { - this.launchTargets = launchTargets; - } - - public int getId() - { - return id; - } - - public void setId(int id) - { - this.id = id; - } - - @Override - public int hashCode() - { - return idfLocation.hashCode(); - } - - public String getSystemGitExecutablePath() - { - return systemGitExecutablePath; - } - - public void setSystemGitExecutablePath(String systemGitExecutablePath) - { - this.systemGitExecutablePath = systemGitExecutablePath; - } - - public String getSystemPythonExecutablePath() - { - return systemPythonExecutablePath; - } - - public void setSystemPythonExecutablePath(String systemPythonExecutablePath) - { - this.systemPythonExecutablePath = systemPythonExecutablePath; - } -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/IdfInstalled.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/IdfInstalled.java new file mode 100644 index 000000000..2e0d4ae9a --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/IdfInstalled.java @@ -0,0 +1,80 @@ +package com.espressif.idf.core.tools.vo; + +import com.google.gson.annotations.Expose; + +public class IdfInstalled +{ + @Expose + private String activationScript; + @Expose + private String id; + @Expose + private String idfToolsPath; + @Expose + private String name; + @Expose + private String path; + @Expose + private String python; + + public String getActivationScript() + { + return activationScript; + } + + public void setActivationScript(String activationScript) + { + this.activationScript = activationScript; + } + + public String getId() + { + return id; + } + + public void setId(String id) + { + this.id = id; + } + + public String getIdfToolsPath() + { + return idfToolsPath; + } + + public void setIdfToolsPath(String idfToolsPath) + { + this.idfToolsPath = idfToolsPath; + } + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public String getPath() + { + return path; + } + + public void setPath(String path) + { + this.path = path; + } + + public String getPython() + { + return python; + } + + public void setPython(String python) + { + this.python = python; + } + +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/ToolsVO.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/ToolsVO.java deleted file mode 100644 index 92ab5bf9e..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/ToolsVO.java +++ /dev/null @@ -1,259 +0,0 @@ -/******************************************************************************* - * Copyright 2021 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools.vo; - -import java.text.DecimalFormat; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import org.eclipse.core.runtime.Platform; - -import com.espressif.idf.core.tools.IToolsJsonKeys; -import com.espressif.idf.core.tools.JsonKey; - -/** - * Bean class for tools information from json - * - * @author Ali Azam Rana - * - */ -public class ToolsVO -{ - @JsonKey(key_name = IToolsJsonKeys.DESCRIPTION_KEY) - private String description; - - @JsonKey(key_name = IToolsJsonKeys.EXPORT_PATHS_KEY) - private List exportPaths; - - @JsonKey(key_name = IToolsJsonKeys.EXPORT_VARS_KEY) - private Map exportVars; - - @JsonKey(key_name = IToolsJsonKeys.INFO_URL_KEY) - private String infoUrl; - - @JsonKey(key_name = IToolsJsonKeys.INSTALL_KEY) - private String installType; - - @JsonKey(key_name = IToolsJsonKeys.LICENSE_KEY) - private String licesnse; - - @JsonKey(key_name = IToolsJsonKeys.NAME_KEY) - private String name; - - @JsonKey(key_name = IToolsJsonKeys.SUPPORTED_TARGETS_KEY) - private List supportedTargets; - - @JsonKey(key_name = IToolsJsonKeys.VERSION_CMD_KEY) - private List versionCmd; - - @JsonKey(key_name = IToolsJsonKeys.VERSION_REGEX) - private String versionRegex; - - @JsonKey(key_name = IToolsJsonKeys.VERSIONS_VO_KEY) - private List versionVOs; - - @JsonKey(key_name = IToolsJsonKeys.VERSION_KEY) - private String version; - - private boolean installed; - - private static final String MAC_OS = "mac"; //$NON-NLS-1$ - private static final String LINUX_OS = "linux"; //$NON-NLS-1$ - private static final String WIN_OS = "win"; //$NON-NLS-1$ - - public String getDescription() - { - return description; - } - - public void setDescription(String description) - { - this.description = description; - } - - public List getExportPaths() - { - return exportPaths; - } - - public void setExportPaths(List exportPaths) - { - this.exportPaths = exportPaths; - } - - public String getInfoUrl() - { - return infoUrl; - } - - public void setInfoUrl(String infoUrl) - { - this.infoUrl = infoUrl; - } - - public Map getExportVars() - { - return exportVars; - } - - public void setExportVars(Map exportVars) - { - this.exportVars = exportVars; - } - - public String getInstallType() - { - return installType; - } - - public void setInstallType(String installType) - { - this.installType = installType; - } - - public String getLicesnse() - { - return licesnse; - } - - public void setLicesnse(String licesnse) - { - this.licesnse = licesnse; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public List getSupportedTargets() - { - return supportedTargets; - } - - public void setSupportedTargets(List supportedTargets) - { - this.supportedTargets = supportedTargets; - } - - public List getVersionCmd() - { - return versionCmd; - } - - public void setVersionCmd(List versionCmd) - { - this.versionCmd = versionCmd; - } - - public String getVersion() - { - return version; - } - - public void setVersion(String version) - { - this.version = version; - } - - public List getVersionVO() - { - return versionVOs; - } - - public void setVersionVO(List versionVO) - { - this.versionVOs = versionVO; - } - - public double getSize() - { - double totalSize = 0; - String key = null; - if (Platform.getOS().equals(Platform.OS_WIN32)) - { - key = WIN_OS; - } - else if (Platform.getOS().equals(Platform.OS_LINUX)) - { - key = LINUX_OS; - } - else if (Platform.getOS().equals(Platform.OS_MACOSX)) - { - key = MAC_OS; - } - - for (VersionsVO versionVO : versionVOs) - { - totalSize += versionVO.getVersionOsMap().get(key).getSize(); - } - - return totalSize; - } - - public String getReadableSize() - { - double totalSize = getSize(); - totalSize /= 1024; // KB - totalSize /= 1024; // MB - DecimalFormat df = new DecimalFormat("0"); //$NON-NLS-1$ - return String.valueOf(df.format(totalSize)).concat(" MB"); //$NON-NLS-1$ - } - - public boolean isInstalled() - { - return installed; - } - - public void setInstalled(boolean installed) - { - this.installed = installed; - } - - public String getVersionRegex() - { - return versionRegex; - } - - public void setVersionRegex(String versionRegex) - { - this.versionRegex = versionRegex; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null || getClass() != obj.getClass()) - return false; - ToolsVO other = (ToolsVO) obj; - return Objects.equals(description, other.description) - && Objects.equals(exportPaths, other.exportPaths) - && Objects.equals(exportVars, other.exportVars) - && Objects.equals(infoUrl, other.infoUrl) - && Objects.equals(installType, other.installType) - && Objects.equals(licesnse, other.licesnse) - && Objects.equals(name, other.name) - && Objects.equals(supportedTargets, other.supportedTargets) - && Objects.equals(versionCmd, other.versionCmd) - && Objects.equals(versionRegex, other.versionRegex) - && Objects.equals(versionVOs, other.versionVOs) - && Objects.equals(version, other.version) - && installed == other.installed; - } - - @Override - public int hashCode() - { - return Objects.hash(description, exportPaths, exportVars, infoUrl, installType, licesnse, name, supportedTargets, versionCmd, versionRegex, versionVOs, version, installed); - } -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/VersionDetailsVO.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/VersionDetailsVO.java deleted file mode 100644 index a9a2122b0..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/VersionDetailsVO.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright 2021 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools.vo; - -import java.text.DecimalFormat; -import java.util.Objects; - -/** - * Version details vo for the versions class - * - * @author Ali Azam Rana - * - */ -public class VersionDetailsVO -{ - private String sha256; - - private double size; - - private String url; - - private boolean selected; - - public String getSha256() - { - return sha256; - } - - public void setSha256(String sha256) - { - this.sha256 = sha256; - } - - public double getSize() - { - return size; - } - - public void setSize(double size) - { - this.size = size; - } - - public String getUrl() - { - return url; - } - - public void setUrl(String url) - { - this.url = url; - } - - public String getReadableSize() - { - double totalSize = getSize(); - totalSize /= 1024; // KB - totalSize /= 1024; // MB - DecimalFormat df = new DecimalFormat("0"); - return String.valueOf(df.format(totalSize)).concat(" MB"); - } - - public boolean isSelected() - { - return selected; - } - - public void setSelected(boolean selected) - { - this.selected = selected; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null || getClass() != obj.getClass()) - return false; - VersionDetailsVO other = (VersionDetailsVO) obj; - return Double.compare(size, other.size) == 0 - && selected == other.selected - && Objects.equals(sha256, other.sha256) - && Objects.equals(url, other.url); - } - - @Override - public int hashCode() - { - return Objects.hash(sha256, size, url, selected); - } -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/VersionsVO.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/VersionsVO.java deleted file mode 100644 index ac871a78a..000000000 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/vo/VersionsVO.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright 2021 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.core.tools.vo; - -import java.util.Map; -import java.util.Objects; - -/** - * Versions class for versions information in tools json - * - * @author Ali Azam Rana - * - */ -public class VersionsVO -{ - private String name; - - private String status; - - private Map versionOsMap; - - private boolean isAvailable; - - private String availablePath; - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public String getStatus() - { - return status; - } - - public void setStatus(String status) - { - this.status = status; - } - - public Map getVersionOsMap() - { - return versionOsMap; - } - - public void setVersionOsMap(Map versionOsMap) - { - this.versionOsMap = versionOsMap; - } - - public boolean isAvailable() - { - return isAvailable; - } - - public void setAvailable(boolean isAvailable) - { - this.isAvailable = isAvailable; - } - - public String getAvailablePath() - { - return availablePath; - } - - public void setAvailablePath(String availablePath) - { - this.availablePath = availablePath; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null || getClass() != obj.getClass()) - return false; - VersionsVO other = (VersionsVO) obj; - return isAvailable == other.isAvailable - && Objects.equals(name, other.name) - && Objects.equals(status, other.status) - && Objects.equals(versionOsMap, other.versionOsMap) - && Objects.equals(availablePath, other.availablePath); - } - - @Override - public int hashCode() - { - return Objects.hash(name, status, versionOsMap, isAvailable, availablePath); - } -} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonChangeListener.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonChangeListener.java new file mode 100644 index 000000000..37d12f78d --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonChangeListener.java @@ -0,0 +1,17 @@ +/******************************************************************************* + * Copyright 2025 Espressif Systems (Shanghai) PTE LTD. All rights reserved. + * Use is subject to license terms. + *******************************************************************************/ +package com.espressif.idf.core.tools.watcher; + +import java.nio.file.Path; + +/** + * Classes that want to handle the eim_idf.json Changes must implement this listener + * @author Ali Azam Rana + * + */ +public interface EimJsonChangeListener +{ + void onJsonFileChanged(Path file); +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonStateChecker.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonStateChecker.java new file mode 100644 index 000000000..44232e9eb --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonStateChecker.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright 2025 Espressif Systems (Shanghai) PTE LTD. All rights reserved. + * Use is subject to license terms. + *******************************************************************************/ +package com.espressif.idf.core.tools.watcher; + +import java.io.File; + +import org.eclipse.core.runtime.Platform; +import org.osgi.service.prefs.Preferences; + +import com.espressif.idf.core.logging.Logger; +import com.espressif.idf.core.tools.EimConstants; + +/** + * Checks if eim_idf.json was changed while Eclipse was not running. Stores and compares last seen timestamp to file + * system's last modified. + * + * @author Ali Azam Rana + * + */ +public class EimJsonStateChecker +{ + private static final String LAST_MODIFIED_PREF_KEY = "lastEimJsonModified"; //$NON-NLS-1$ + + private final Preferences preferences; + + public EimJsonStateChecker(Preferences preferences) + { + this.preferences = preferences; + } + + public boolean wasModifiedSinceLastRun() + { + File jsonFile = new File(getEimJsonPath()); + if (!jsonFile.exists()) + { + return false; + } + + long lastModified = jsonFile.lastModified(); + long lastSeen = preferences.getLong(LAST_MODIFIED_PREF_KEY, 0L); + + if (lastSeen == 0L) + { + // First run ever, don't treat as changed + Logger.log("eim_idf.json detected, but no last seen timestamp — assuming first run."); //$NON-NLS-1$ + return false; + } + + return lastModified > lastSeen; + } + + public void updateLastSeenTimestamp() + { + File jsonFile = new File(getEimJsonPath()); + if (jsonFile.exists()) + { + preferences.putLong(LAST_MODIFIED_PREF_KEY, jsonFile.lastModified()); + } + } + + private String getEimJsonPath() + { + return Platform.getOS().equals(Platform.OS_WIN32) ? EimConstants.EIM_WIN_PATH : EimConstants.EIM_POSIX_PATH; + } +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonWatchService.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonWatchService.java new file mode 100644 index 000000000..b590e2500 --- /dev/null +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/tools/watcher/EimJsonWatchService.java @@ -0,0 +1,152 @@ +/******************************************************************************* + * Copyright 2025 Espressif Systems (Shanghai) PTE LTD. All rights reserved. + * Use is subject to license terms. + *******************************************************************************/ +package com.espressif.idf.core.tools.watcher; + +import java.io.IOException; +import java.nio.file.*; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.eclipse.core.runtime.Platform; + +import com.espressif.idf.core.logging.Logger; +import com.espressif.idf.core.tools.EimConstants; + +/** + * eim_idf.json watch service. The service will only watch for changes. Any handling must be done by the listeners to + * this service. + * + * @author Ali Azam Rana + */ +public class EimJsonWatchService extends Thread +{ + private final WatchService watchService; + private final Path watchDirectoryPath; + private final List eimJsonChangeListeners = new CopyOnWriteArrayList<>(); + private volatile boolean running = true; + + private EimJsonWatchService() throws IOException + { + String directoryPathString = Platform.getOS().equals(Platform.OS_WIN32) ? EimConstants.EIM_WIN_DIR + : EimConstants.EIM_POSIX_DIR; + + watchDirectoryPath = Paths.get(directoryPathString); + watchService = FileSystems.getDefault().newWatchService(); + watchDirectoryPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, + StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); + + Logger.log("Watcher added to the directory: " + directoryPathString); //$NON-NLS-1$ + setName("EimJsonWatchService"); //$NON-NLS-1$ + setDaemon(true); + start(); + } + + private static class Holder + { + private static EimJsonWatchService INSTANCE; + + static + { + try + { + INSTANCE = new EimJsonWatchService(); + } + catch (IOException e) + { + Logger.log("Failed to initialize EimJsonWatchService"); //$NON-NLS-1$ + Logger.log(e); + } + } + } + + public static EimJsonWatchService getInstance() + { + return Holder.INSTANCE; + } + + public void addEimJsonChangeListener(EimJsonChangeListener listener) + { + if (listener != null) + { + eimJsonChangeListeners.add(listener); + } + } + + public void removeAllListeners() + { + eimJsonChangeListeners.clear(); + } + + @Override + public void run() + { + while (running) + { + WatchKey key; + try + { + key = watchService.take(); + } + catch (InterruptedException e) + { + Logger.log("Watch Service Interrupted"); //$NON-NLS-1$ + Thread.currentThread().interrupt(); + break; + } + catch (ClosedWatchServiceException cwse) + { + break; + } + + for (WatchEvent event : key.pollEvents()) + { + if (event.kind() == StandardWatchEventKinds.OVERFLOW) + { + continue; + } + + Object context = event.context(); + if (context instanceof Path path && path.toString().equals(EimConstants.EIM_JSON)) + { + Path fullPath = watchDirectoryPath.resolve(path); + for (EimJsonChangeListener listener : eimJsonChangeListeners) + { + listener.onJsonFileChanged(fullPath); + } + } + } + + boolean valid = key.reset(); + if (!valid) + { + break; + } + } + + // clean up + try + { + watchService.close(); + } + catch (IOException e) + { + Logger.log("Failed to close WatchService"); //$NON-NLS-1$ + Logger.log(e); + } + } + + @Override + public void interrupt() + { + running = false; + super.interrupt(); + } + + public void shutdown() + { + running = false; + interrupt(); + } +} diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/util/EspToolCommands.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/util/EspToolCommands.java index 1de306634..f37405169 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/util/EspToolCommands.java +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/util/EspToolCommands.java @@ -26,7 +26,7 @@ public Process chipInformation(String port) throws Exception { destroyAnyChipInfoProcess(); ProcessBuilder processBuilder = new ProcessBuilder(getChipInfoCommand(port)); - processBuilder.environment().putAll(IDFUtil.getSystemEnv()); + processBuilder.environment().putAll(System.getenv()); chipInfoProcess = processBuilder.start(); return chipInfoProcess; } @@ -35,7 +35,7 @@ public Process eraseFlash(String port) throws Exception { destroyAnyChipInfoProcess(); ProcessBuilder processBuilder = new ProcessBuilder(getFlashEraseCommand(port)); - processBuilder.environment().putAll(IDFUtil.getSystemEnv()); + processBuilder.environment().putAll(System.getenv()); flashEraseProcess = processBuilder.start(); return flashEraseProcess; } @@ -44,7 +44,7 @@ public Process writeFlash(String port, String path, String offset) throws IOExce { destroyAnyChipInfoProcess(); ProcessBuilder processBuilder = new ProcessBuilder(getWriteFlashCommand(port, path, offset)); - processBuilder.environment().putAll(IDFUtil.getSystemEnv()); + processBuilder.environment().putAll(System.getenv()); writeFlashProcess = processBuilder.start(); return writeFlashProcess; } diff --git a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/util/IDFUtil.java b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/util/IDFUtil.java index 73a38153a..c583f78bf 100644 --- a/bundles/com.espressif.idf.core/src/com/espressif/idf/core/util/IDFUtil.java +++ b/bundles/com.espressif.idf.core/src/com/espressif/idf/core/util/IDFUtil.java @@ -43,7 +43,6 @@ import com.espressif.idf.core.IDFConstants; import com.espressif.idf.core.IDFCorePlugin; -import com.espressif.idf.core.IDFCorePreferenceConstants; import com.espressif.idf.core.IDFEnvironmentVariables; import com.espressif.idf.core.LaunchBarTargetConstants; import com.espressif.idf.core.ProcessBuilderFactory; @@ -210,6 +209,30 @@ public static String getIDFPythonEnvPath() return findCommandFromBuildEnvPath(IDFConstants.PYTHON_CMD); } + + public static String getIDFPythonEnvPath(String idfPyEnvPath) + { + idfPyEnvPath = idfPyEnvPath.strip(); + if (!StringUtil.isEmpty(idfPyEnvPath)) + { + + if (Platform.getOS().equals(Platform.OS_WIN32)) + { + idfPyEnvPath = idfPyEnvPath + "/" + "Scripts"; //$NON-NLS-1$ //$NON-NLS-2$ + } + else + { + idfPyEnvPath = idfPyEnvPath + "/" + "bin"; //$NON-NLS-1$ //$NON-NLS-2$ + } + java.nio.file.Path commandPath = findCommand(IDFConstants.PYTHON_CMD, idfPyEnvPath); + if (commandPath != null) + { + return commandPath.toFile().getAbsolutePath(); + } + } + return findCommandFromBuildEnvPath(IDFConstants.PYTHON_CMD); + + } public static boolean checkIfIdfSupportsSpaces() { @@ -776,7 +799,7 @@ public static String getGitExecutablePathFromSystem() arguments.add("whereis"); //$NON-NLS-1$ arguments.add("git"); //$NON-NLS-1$ - Map environment = new HashMap<>(getSystemEnv()); + Map environment = new HashMap<>(System.getenv()); IStatus status = processRunner.runInBackground(arguments, org.eclipse.core.runtime.Path.ROOT, environment); @@ -844,23 +867,7 @@ public static String resolveEnvVariable(String path) return resolvedPath.toString(); } - - public static Map getSystemEnv() - { - Map env = new HashMap(System.getenv()); - String idfToolsPath = Platform.getPreferencesService().getString(IDFCorePlugin.PLUGIN_ID, - IDFCorePreferenceConstants.IDF_TOOLS_PATH, IDFCorePreferenceConstants.IDF_TOOLS_PATH_DEFAULT, null); - env.put(IDFCorePreferenceConstants.IDF_TOOLS_PATH, idfToolsPath); - return env; - } - - public static String getIDFToolsPathFromPreferences() - { - String idfToolsPath = Platform.getPreferencesService().getString(IDFCorePlugin.PLUGIN_ID, - IDFCorePreferenceConstants.IDF_TOOLS_PATH, IDFCorePreferenceConstants.IDF_TOOLS_PATH_DEFAULT, null); - return idfToolsPath; - } - + public static void closeWelcomePage(IWorkbenchWindow activeww) { Display.getDefault().syncExec(() -> { diff --git a/bundles/com.espressif.idf.sdk.config.core/src/com/espressif/idf/sdk/config/core/server/JsonConfigServer.java b/bundles/com.espressif.idf.sdk.config.core/src/com/espressif/idf/sdk/config/core/server/JsonConfigServer.java index 4033fa16e..fa7f20468 100644 --- a/bundles/com.espressif.idf.sdk.config.core/src/com/espressif/idf/sdk/config/core/server/JsonConfigServer.java +++ b/bundles/com.espressif.idf.sdk.config.core/src/com/espressif/idf/sdk/config/core/server/JsonConfigServer.java @@ -10,10 +10,10 @@ import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; @@ -24,6 +24,7 @@ import com.espressif.idf.core.IDFConstants; import com.espressif.idf.core.IDFEnvironmentVariables; +import com.espressif.idf.core.ProcessBuilderFactory; import com.espressif.idf.core.logging.Logger; import com.espressif.idf.core.util.IDFUtil; import com.espressif.idf.core.util.StringUtil; @@ -92,69 +93,81 @@ public void removeListener(IMessageHandlerListener listener) public void start() throws IOException { IPath workingDir = project.getLocation(); - Map idfEnvMap = new IDFEnvironmentVariables().getSystemEnvMap(); - - // Disable buffering of output - idfEnvMap.put("PYTHONUNBUFFERED", "1"); //$NON-NLS-1$ //$NON-NLS-2$ - + Map env = new HashMap(System.getenv()); + + prepEnvMap(env); + List arguments = new ArrayList<>(); File idfPythonScriptFile = IDFUtil.getIDFPythonScriptFile(); if (!idfPythonScriptFile.exists()) { throw new FileNotFoundException("File Not found:" + idfPythonScriptFile); //$NON-NLS-1$ } - String pythonPath = IDFUtil.getIDFPythonEnvPath(); - - List arguments = Collections.emptyList(); try { - arguments = new ArrayList(Arrays.asList(pythonPath, idfPythonScriptFile.getAbsolutePath(), "-B", //$NON-NLS-1$ - IDFUtil.getBuildDir(project), "-DSDKCONFIG=".concat(file.getName()), IDFConstants.CONF_SERVER_CMD)); //$NON-NLS-1$ + String pythonPath = IDFUtil.getIDFPythonEnvPath(); + arguments.add(pythonPath); + arguments.add(idfPythonScriptFile.getAbsolutePath()); + arguments.add("-B"); //$NON-NLS-1$ + arguments.add(IDFUtil.getBuildDir(project)); + arguments.add("-DSDKCONFIG=".concat(file.getName())); //$NON-NLS-1$ + arguments.add(IDFConstants.CONF_SERVER_CMD); + Logger.log(arguments.toString()); + + ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); + + String oldSdkconfigValue = StringUtil.EMPTY; + oldSdkconfigValue = getCmakeCacheSdkconfigValue(); + + + process = processRunner.run(arguments, workingDir, env); + runnable = new JsonConfigServerRunnable(process, this, project, oldSdkconfigValue); + Thread t = new Thread(runnable); + t.start(); } - catch (CoreException e) + catch (Exception e) { Logger.log(e); } - Logger.log(arguments.toString()); - - ProcessBuilder processBuilder = new ProcessBuilder(arguments); - if (workingDir != null) - { - processBuilder.directory(workingDir.toFile()); - } - Map environment = processBuilder.environment(); - environment.putAll(idfEnvMap); - environment.put("IDF_CCACHE_ENABLE", "false"); - - Logger.log(environment.toString()); + } - String idfPath = environment.get("PATH"); //$NON-NLS-1$ - String processPath = environment.get("Path"); //$NON-NLS-1$ - if (!StringUtil.isEmpty(idfPath) && !StringUtil.isEmpty(processPath)) // if both exist! + private void prepEnvMap(Map env) + { + env.put("PYTHONUNBUFFERED", "1"); //$NON-NLS-1$ //$NON-NLS-2$ + env.put("IDF_CCACHE_ENABLE", "false"); //$NON-NLS-1$ //$NON-NLS-2$ + loadIdfPathWithSystemPath(env); + } + + private void loadIdfPathWithSystemPath(Map systemEnv) + { + IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); + String idfExportPath = idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.PATH); + String pathVar = "PATH"; // for Windows //$NON-NLS-1$ + String pathEntry = systemEnv.get(pathVar); // $NON-NLS-1$ + if (pathEntry == null) { - idfPath = idfPath.concat(";").concat(processPath); //$NON-NLS-1$ - environment.put("PATH", idfPath); //$NON-NLS-1$ - environment.remove("Path");//$NON-NLS-1$ + pathVar = "Path"; //$NON-NLS-1$ + pathEntry = systemEnv.get(pathVar); + if (pathEntry == null) // no idea + { + Logger.log(new Exception("No PATH found in the system environment variables")); //$NON-NLS-1$ + } } - Logger.log(environment.toString()); - - // redirect error stream to input stream - processBuilder.redirectErrorStream(true); - String oldSdkconfigValue = StringUtil.EMPTY; - try + if (!StringUtil.isEmpty(pathEntry)) { - oldSdkconfigValue = getCmakeCacheSdkconfigValue(); + idfExportPath = idfExportPath.replace("$PATH", pathEntry); // macOS //$NON-NLS-1$ + idfExportPath = idfExportPath.replace("%PATH%", pathEntry); // Windows //$NON-NLS-1$ } - catch (CoreException e) + + systemEnv.put(pathVar, idfExportPath); + for (Entry entry : idfEnvironmentVariables.getEnvMap().entrySet()) { - Logger.log(e); - } - process = processBuilder.start(); - runnable = new JsonConfigServerRunnable(process, this, project, oldSdkconfigValue); - Thread t = new Thread(runnable); - t.start(); + if (entry.getKey().equals(IDFEnvironmentVariables.PATH)) + continue; + systemEnv.put(entry.getKey(), entry.getValue()); + } } private String getCmakeCacheSdkconfigValue() throws CoreException diff --git a/bundles/com.espressif.idf.serial.monitor/src/com/espressif/idf/serial/monitor/core/IDFMonitor.java b/bundles/com.espressif.idf.serial.monitor/src/com/espressif/idf/serial/monitor/core/IDFMonitor.java index ce8f17126..2805b36d1 100644 --- a/bundles/com.espressif.idf.serial.monitor/src/com/espressif/idf/serial/monitor/core/IDFMonitor.java +++ b/bundles/com.espressif.idf.serial.monitor/src/com/espressif/idf/serial/monitor/core/IDFMonitor.java @@ -12,7 +12,6 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfiguration; @@ -20,14 +19,12 @@ import org.eclipse.embedcdt.debug.gdbjtag.core.DebugUtils; import com.espressif.idf.core.IDFConstants; -import com.espressif.idf.core.IDFCorePlugin; import com.espressif.idf.core.IDFEnvironmentVariables; import com.espressif.idf.core.logging.Logger; import com.espressif.idf.core.util.GenericJsonReader; import com.espressif.idf.core.util.IDFUtil; import com.espressif.idf.core.util.SDKConfigJsonReader; import com.espressif.idf.core.util.StringUtil; -import com.espressif.idf.ui.update.InstallToolsHandler; /** * @author Kondal Kolipaka @@ -146,10 +143,6 @@ private String getMonitorBaudRate() public Process start() throws Exception { - if (!dependenciesAreInstalled()) - { - throw new Exception("The WebSocket dependency is missing and cannot be installed automatically"); //$NON-NLS-1$ - } List arguments = commandArgsWithSocketServer(); // command to execute @@ -162,7 +155,7 @@ public Process start() throws Exception idfEnvMap.put("PYTHONUNBUFFERED", "1"); //$NON-NLS-1$ //$NON-NLS-2$ // Update with the CDT build environment variables - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); + Map environment = new HashMap<>(System.getenv()); environment.putAll(idfEnvMap); Logger.log(environment.toString()); @@ -189,18 +182,4 @@ public Process start() throws Exception LocalTerminal localTerminal = new LocalTerminal(arguments, workingDir.toFile(), environment); return localTerminal.connect(); } - - public boolean dependenciesAreInstalled() - { - InstallToolsHandler installToolsHandler = new InstallToolsHandler(); - IStatus status = installToolsHandler.handleWebSocketClientInstall(); - if (status == null || status.getSeverity() == IStatus.ERROR) - { - Logger.log(IDFCorePlugin.getPlugin(), IDFCorePlugin.errorStatus("Unable to get the process status.", null)); //$NON-NLS-1$ - return false; - } - - Logger.log(status.getMessage()); - return true; - } } diff --git a/bundles/com.espressif.idf.ui/OSGI-INF/l10n/bundle.properties b/bundles/com.espressif.idf.ui/OSGI-INF/l10n/bundle.properties index 7be5c883b..00178f0e3 100644 --- a/bundles/com.espressif.idf.ui/OSGI-INF/l10n/bundle.properties +++ b/bundles/com.espressif.idf.ui/OSGI-INF/l10n/bundle.properties @@ -62,7 +62,6 @@ command.name.delete = Delete command.name.13 = DFU command.label.11 = DFU command.tooltip.2 = DFU -command.name.updateEspIdfMaster = Update ESP-IDF master command.name.15 = Tools Installation Wizard (Preview) command.label.PartitionTableEditor = Partition Table Editor diff --git a/bundles/com.espressif.idf.ui/icons/tools/delete.png b/bundles/com.espressif.idf.ui/icons/tools/delete.png deleted file mode 100644 index 14de8ec9e..000000000 Binary files a/bundles/com.espressif.idf.ui/icons/tools/delete.png and /dev/null differ diff --git a/bundles/com.espressif.idf.ui/plugin.xml b/bundles/com.espressif.idf.ui/plugin.xml index 91315f5ae..cfd10a27a 100644 --- a/bundles/com.espressif.idf.ui/plugin.xml +++ b/bundles/com.espressif.idf.ui/plugin.xml @@ -65,11 +65,6 @@ - - - - - - - - - - @@ -565,11 +544,9 @@ - - - + class="com.espressif.idf.ui.EspressifGeneralStartup"/> + + * + */ +@SuppressWarnings("restriction") +public class EspressifGeneralStartup implements IStartup +{ + private static final String BUILDHINTS_ID = "com.espressif.idf.ui.views.buildhints"; + + private LaunchBarListener launchBarListener; + + @Override + public void earlyStartup() + { + hookDialogListeners(); + hookLaunchBarListeners(); + } + + private void hookDialogListeners() + { + OpenDialogListenerSupport.getSupport().addPropertyChangeListener(evt -> { + PopupDialog popupDialog = PopupDialog.valueOf(evt.getPropertyName()); + switch (popupDialog) + { + case LOW_PARTITION_SIZE: + openLowPartitionSizeDialog(evt); + break; + case AVAILABLE_HINTS: + openAvailableHintsDialog(evt); + break; + case DISABLE_LAUNCHABAR_EVENTS: + disableLaunchBarEvents(); + break; + case ENABLE_LAUNCHBAR_EVENTS: + enableLaunchBarEvents(); + break; + default: + break; + } + }); + } + + private void hookLaunchBarListeners() + { + launchBarListener = new LaunchBarListener(); + ResourcesPlugin.getWorkspace().addResourceChangeListener(new ResourceChangeListener(launchBarListener)); + + ILaunchBarManager launchBarManager = Activator.getService(ILaunchBarManager.class); + launchBarManager.addListener(launchBarListener); + } + + @SuppressWarnings("static-access") + private void disableLaunchBarEvents() + { + launchBarListener.setIgnoreTargetChange(true); + } + + @SuppressWarnings("static-access") + private void enableLaunchBarEvents() + { + launchBarListener.setIgnoreTargetChange(false); + } + + @SuppressWarnings("unchecked") + private void openAvailableHintsDialog(PropertyChangeEvent evt) + { + Display.getDefault().asyncExec(() -> { + List errorHintPairs = (List) evt.getNewValue(); + + if (errorHintPairs.isEmpty()) + { + updateBuildView(errorHintPairs); + return; + } + + try + { + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(BUILDHINTS_ID); + } + catch (PartInitException e) + { + Logger.log(e); + } + + updateBuildView(errorHintPairs); + }); + } + + private void updateBuildView(List errorHintPairs) + { + BuildView view = (BuildView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() + .findView(BUILDHINTS_ID); + if (view != null) + { + view.updateReHintsPairs(errorHintPairs); + } + } + + private void openLowPartitionSizeDialog(PropertyChangeEvent evt) + { + Display.getDefault().asyncExec(() -> { + Shell shell = Display.getDefault().getActiveShell(); + MessageLinkDialog.openWarning(shell, + Messages.IncreasePartitionSizeTitle, + MessageFormat.format(Messages.IncreasePartitionSizeMessage, + evt.getNewValue(), + evt.getOldValue(), + "https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/partition-tables.html?highlight=partitions%20csv#creating-custom-tables")); + }); + } +} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/InitializeToolsStartup.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/InitializeToolsStartup.java deleted file mode 100644 index a95f4793b..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/InitializeToolsStartup.java +++ /dev/null @@ -1,358 +0,0 @@ -/******************************************************************************* - * Copyright 2020 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui; - -import java.beans.PropertyChangeEvent; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.net.URL; -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; - -import org.eclipse.cdt.cmake.core.internal.Activator; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.launchbar.core.ILaunchBarManager; -import org.eclipse.osgi.service.datalocation.Location; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.MessageBox; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IStartup; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.osgi.service.prefs.BackingStoreException; -import org.osgi.service.prefs.Preferences; - -import com.espressif.idf.core.IDFCorePlugin; -import com.espressif.idf.core.IDFCorePreferenceConstants; -import com.espressif.idf.core.IDFEnvironmentVariables; -import com.espressif.idf.core.build.Messages; -import com.espressif.idf.core.build.ReHintPair; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.resources.OpenDialogListenerSupport; -import com.espressif.idf.core.resources.PopupDialog; -import com.espressif.idf.core.resources.ResourceChangeListener; -import com.espressif.idf.core.tools.vo.IDFToolSet; -import com.espressif.idf.core.util.IDFUtil; -import com.espressif.idf.ui.dialogs.BuildView; -import com.espressif.idf.ui.dialogs.MessageLinkDialog; -import com.espressif.idf.ui.tools.ToolsActivationJob; -import com.espressif.idf.ui.tools.ToolsActivationJobListener; -import com.espressif.idf.ui.tools.manager.pages.ESPIDFMainTablePage; - -@SuppressWarnings("restriction") -public class InitializeToolsStartup implements IStartup -{ - - private static final String BUILDHINTS_ID = "com.espressif.idf.ui.views.buildhints"; //$NON-NLS-1$ - - /** - * esp-idf.json is file created by the installer - */ - public static final String ESP_IDF_JSON_FILE = "esp_idf.json"; //$NON-NLS-1$ - - // Variables defined in the esp-idf.json file - private static final String GIT_PATH = "gitPath"; //$NON-NLS-1$ - private static final String IDF_TOOLS_PATH_KEY = "idfToolsPath"; //$NON-NLS-1$ - private static final String IDF_VERSIONS_ID = "idfSelectedId"; //$NON-NLS-1$ - private static final String IDF_INSTALLED_LIST_KEY = "idfInstalled"; //$NON-NLS-1$ - private static final String PYTHON_PATH = "python"; //$NON-NLS-1$ - private static final String IDF_PATH = "path"; //$NON-NLS-1$ - private static final String IS_INSTALLER_CONFIG_SET = "isInstallerConfigSet"; //$NON-NLS-1$ - private static final String DOC_URL = "\"https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/partition-tables.html?highlight=partitions%20csv#creating-custom-tables\""; //$NON-NLS-1$ - - private String newIdfPath; - private LaunchBarListener launchBarListener; - @Override - public void earlyStartup() - { - OpenDialogListenerSupport.getSupport().addPropertyChangeListener(evt -> { - PopupDialog popupDialog = PopupDialog.valueOf(evt.getPropertyName()); - switch (popupDialog) - { - case LOW_PARTITION_SIZE: - openLowPartitionSizeDialog(evt); - break; - case AVAILABLE_HINTS: - openAvailableHintsDialog(evt); - break; - case DISABLE_LAUNCHABAR_EVENTS: - disableLaunchBarEvents(evt); - break; - case ENABLE_LAUNCHBAR_EVENTS: - enableLaunchBarEvents(evt); - break; - default: - break; - } - }); - launchBarListener = new LaunchBarListener(); - ResourcesPlugin.getWorkspace().addResourceChangeListener(new ResourceChangeListener(launchBarListener)); - ILaunchBarManager launchBarManager = Activator.getService(ILaunchBarManager.class); - launchBarManager.addListener(launchBarListener); - - // Get the location of the eclipse root directory - Location installLocation = Platform.getInstallLocation(); - URL url = installLocation.getURL(); - Logger.log("Eclipse Install location::" + url); - File idf_json_file = new File(url.getPath() + File.separator + ESP_IDF_JSON_FILE); - if (!idf_json_file.exists()) - { - Logger.log(MessageFormat.format("esp-idf.json file doesn't exist at this location: '{0}'", url.getPath())); - return; - } - else if (isInstallerConfigSet()) - { - checkForUpdatedVersion(idf_json_file); - if (isInstallerConfigSet()) - { - Logger.log("Ignoring esp_idf.json settings as it was configured earilier and idf_path is similar."); - return; - } - - IDFEnvironmentVariables idfEnvMgr = new IDFEnvironmentVariables(); - Display.getDefault().syncExec(() -> { - Shell shell = new Shell(Display.getDefault()); - MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO); - messageBox.setButtonLabels(Map.of(SWT.YES, Messages.ToolsInitializationDifferentPathMessageBoxOptionYes, - SWT.NO, Messages.ToolsInitializationDifferentPathMessageBoxOptionNo)); - messageBox.setText(Messages.ToolsInitializationDifferentPathMessageBoxTitle); - messageBox.setMessage(MessageFormat.format(Messages.ToolsInitializationDifferentPathMessageBoxMessage, - newIdfPath, idfEnvMgr.getEnvValue(IDFEnvironmentVariables.IDF_PATH))); - int response = messageBox.open(); - if (response == SWT.NO) - { - IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); - updateEspIdfJsonFile(idf_json_file, - idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.IDF_PATH)); - Preferences prefs = getPreferences(); - prefs.putBoolean(IS_INSTALLER_CONFIG_SET, true); - try - { - prefs.flush(); - } - catch (BackingStoreException e) - { - Logger.log(e); - } - - return; - } - }); - } - - // read esp-idf.json file - JSONParser parser = new JSONParser(); - try - { - JSONObject jsonObj = (JSONObject) parser.parse(new FileReader(idf_json_file)); - String gitExecutablePath = (String) jsonObj.get(GIT_PATH); - String idfToolsPath = (String) jsonObj.get(IDF_TOOLS_PATH_KEY); - String idfVersionId = (String) jsonObj.get(IDF_VERSIONS_ID); - JSONObject list = (JSONObject) jsonObj.get(IDF_INSTALLED_LIST_KEY); - if (list != null) - { - // selected esp-idf version information - JSONObject selectedIDFInfo = (JSONObject) list.get(idfVersionId); - String idfPath = (String) selectedIDFInfo.get(IDF_PATH); - String pythonExecutablePath = (String) selectedIDFInfo.get(PYTHON_PATH); - IDFToolSet newToolSet = new IDFToolSet(); - newToolSet.setIdfLocation(idfPath); - newToolSet.setSystemGitExecutablePath(gitExecutablePath); - newToolSet.setSystemPythonExecutablePath(pythonExecutablePath); - newToolSet.setActive(true); - Preferences prefs = InstanceScope.INSTANCE.getNode(IDFCorePlugin.PLUGIN_ID); - prefs.put(IDFCorePreferenceConstants.IDF_TOOLS_PATH, idfToolsPath); - try - { - prefs.flush(); - } - catch (BackingStoreException e) - { - Logger.log(e); - } - ToolsActivationJob toolsActivationJob = new ToolsActivationJob(newToolSet, pythonExecutablePath, gitExecutablePath); - ToolsActivationJobListener toolsActivationJobListener = new ToolsActivationJobListener(ESPIDFMainTablePage.getInstance()); - toolsActivationJob.addJobChangeListener(toolsActivationJobListener); - toolsActivationJob.schedule(); - } - - // save state - Preferences prefs = getPreferences(); - prefs.putBoolean(IS_INSTALLER_CONFIG_SET, true); - try - { - prefs.flush(); - } - catch (BackingStoreException e) - { - Logger.log(e); - } - IDFUtil.updateEspressifPrefPageOpenocdPath(); - - } - catch ( - IOException - | ParseException e) - { - Logger.log(e); - } - } - - @SuppressWarnings("static-access") - private void disableLaunchBarEvents(PropertyChangeEvent evt) - { - launchBarListener.setIgnoreTargetChange(true); - } - - @SuppressWarnings("static-access") - private void enableLaunchBarEvents(PropertyChangeEvent evt) - { - launchBarListener.setIgnoreTargetChange(false); - } - - @SuppressWarnings("unchecked") - private void openAvailableHintsDialog(PropertyChangeEvent evt) - { - Display.getDefault().asyncExec(() -> { - List erroHintPairs = (List) evt.getNewValue(); - // if list is empty we don't want to change focus from the console output - if (erroHintPairs.isEmpty()) - { - updateValuesInBuildView(erroHintPairs); - return; - } - try - { - PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(BUILDHINTS_ID); - } - catch (PartInitException e) - { - Logger.log(e); - } - updateValuesInBuildView(erroHintPairs); - }); - - } - - private void updateValuesInBuildView(List erroHintPairs) - { - BuildView view = ((BuildView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() - .findView(BUILDHINTS_ID)); - if (view != null) - { - view.updateReHintsPairs(erroHintPairs); - } - } - - private void openLowPartitionSizeDialog(PropertyChangeEvent evt) - { - Display.getDefault() - .asyncExec(() -> MessageLinkDialog.openWarning(Display.getDefault().getActiveShell(), - Messages.IncreasePartitionSizeTitle, MessageFormat.format(Messages.IncreasePartitionSizeMessage, - evt.getNewValue(), evt.getOldValue(), DOC_URL))); - } - - @SuppressWarnings("unchecked") - private void updateEspIdfJsonFile(File idf_json_file, String newIdfPathToUpdate) - { - JSONParser parser = new JSONParser(); - JSONObject jsonObj = null; - try (FileReader reader = new FileReader(idf_json_file)) - { - jsonObj = (JSONObject) parser.parse(reader); - String idfVersionId = (String) jsonObj.get(IDF_VERSIONS_ID); - JSONObject list = (JSONObject) jsonObj.get(IDF_INSTALLED_LIST_KEY); - if (list == null) - { - return; - } - // selected esp-idf version information - JSONObject selectedIDFInfo = (JSONObject) list.get(idfVersionId); - selectedIDFInfo.put(IDF_PATH, newIdfPathToUpdate); - list.put(idfVersionId, selectedIDFInfo); - jsonObj.put(IDF_INSTALLED_LIST_KEY, list); - } - catch ( - IOException - | ParseException e) - { - Logger.log(e); - } - - if (jsonObj != null) - { - try (FileWriter fileWriter = new FileWriter(idf_json_file)) - { - fileWriter.write(jsonObj.toJSONString()); - fileWriter.flush(); - - } - catch (IOException e) - { - Logger.log(e); - } - } - - } - - private void checkForUpdatedVersion(File idf_json_file) - { - // read esp-idf.json file - JSONParser parser = new JSONParser(); - try (FileReader reader = new FileReader(idf_json_file)) - { - JSONObject jsonObj = (JSONObject) parser.parse(reader); - String idfVersionId = (String) jsonObj.get(IDF_VERSIONS_ID); - JSONObject list = (JSONObject) jsonObj.get(IDF_INSTALLED_LIST_KEY); - if (list == null) - { - return; - } - // selected esp-idf version information - JSONObject selectedIDFInfo = (JSONObject) list.get(idfVersionId); - String idfPath = (String) selectedIDFInfo.get(IDF_PATH); - IDFEnvironmentVariables idfEnvMgr = new IDFEnvironmentVariables(); - if (idfEnvMgr.getEnvValue(IDFEnvironmentVariables.IDF_PATH).equals(idfPath)) - return; - newIdfPath = idfPath; - Preferences prefs = getPreferences(); - prefs.putBoolean(IS_INSTALLER_CONFIG_SET, false); - try - { - prefs.flush(); - } - catch (BackingStoreException e) - { - Logger.log(e); - } - } - catch ( - IOException - | ParseException e) - { - Logger.log(e); - } - - } - - private Preferences getPreferences() - { - return InstanceScope.INSTANCE.getNode(UIPlugin.PLUGIN_ID); - } - - private boolean isInstallerConfigSet() - { - return getPreferences().getBoolean(IS_INSTALLER_CONFIG_SET, false); - } -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/dialogs/SbomCommandDialog.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/dialogs/SbomCommandDialog.java index d7445e758..0a27a578f 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/dialogs/SbomCommandDialog.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/dialogs/SbomCommandDialog.java @@ -283,7 +283,7 @@ private String buildProjectDescriptionPath() private void runEspIdfSbomCommand() { - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); + Map environment = new HashMap<>(System.getenv()); List arguments = new ArrayList<>(); final String pythonEnvPath = IDFUtil.getIDFPythonEnvPath(); arguments.add(pythonEnvPath); @@ -435,7 +435,7 @@ private boolean checkIfFileIsNotWritable(java.nio.file.Path pathToFile) private void installEspIdfSbom() { - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); + Map environment = new HashMap<>(System.getenv()); List arguments = new ArrayList<>(); final String pythonEnvPath = IDFUtil.getIDFPythonEnvPath(); arguments.add(pythonEnvPath); @@ -450,7 +450,7 @@ private void installEspIdfSbom() private boolean getEspIdfSbomInstalledStatus() { - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); + Map environment = new HashMap<>(System.getenv()); List arguments = new ArrayList<>(); final String pythonEnvPath = IDFUtil.getIDFPythonEnvPath(); arguments.add(pythonEnvPath); diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/handlers/NewProjectHandlerUtil.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/handlers/NewProjectHandlerUtil.java index 40a958223..2d7e76f25 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/handlers/NewProjectHandlerUtil.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/handlers/NewProjectHandlerUtil.java @@ -16,11 +16,11 @@ import com.espressif.idf.core.IDFEnvironmentVariables; import com.espressif.idf.core.logging.Logger; +import com.espressif.idf.core.tools.EimConstants; import com.espressif.idf.core.util.IDFUtil; import com.espressif.idf.core.util.StringUtil; import com.espressif.idf.ui.UIPlugin; import com.espressif.idf.ui.tools.ManageEspIdfVersionsHandler; -import com.espressif.idf.ui.update.InstallToolsHandler; public class NewProjectHandlerUtil { @@ -35,7 +35,7 @@ public static boolean installToolsCheck() String path = Optional.ofNullable(pathEnv).map(o -> o.getValue()).orElse(null); Preferences scopedPreferenceStore = InstanceScope.INSTANCE.getNode(UIPlugin.PLUGIN_ID); - boolean isToolsInstalled = scopedPreferenceStore.getBoolean(InstallToolsHandler.INSTALL_TOOLS_FLAG, false); + boolean isToolsInstalled = scopedPreferenceStore.getBoolean(EimConstants.INSTALL_TOOLS_FLAG, false); if (StringUtil.isEmpty(idfPath)) { diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/handlers/UpdateEspIdfHandler.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/handlers/UpdateEspIdfHandler.java deleted file mode 100644 index ddb74e7de..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/handlers/UpdateEspIdfHandler.java +++ /dev/null @@ -1,171 +0,0 @@ -/******************************************************************************* - * Copyright 2022 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.handlers; - -import java.io.File; -import java.io.IOException; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.SubmoduleInitCommand; -import org.eclipse.jgit.api.SubmoduleUpdateCommand; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.submodule.SubmoduleWalk; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; - -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.util.IDFUtil; -import com.espressif.idf.ui.install.GitProgressMonitor; -import com.espressif.idf.ui.update.InstallToolsHandler; - -public class UpdateEspIdfHandler extends AbstractHandler -{ - @Override - public Object execute(ExecutionEvent event) throws ExecutionException - { - - Job job = new Job(Messages.UpdateEspIdfCommand_JobMsg) - { - @Override - protected IStatus run(IProgressMonitor monitor) - { - GitProgressMonitor gitProgressMonitor = new GitProgressMonitor(monitor); - - try (Git git = Git.open(new File(IDFUtil.getIDFPath()))) - { - git.pull().setProgressMonitor(gitProgressMonitor).call(); - SubmoduleInitCommand initCommand = git.submoduleInit(); - SubmoduleUpdateCommand updateCommand = git.submoduleUpdate(); - addRecursivePaths(git.getRepository(), initCommand, updateCommand); - initCommand.call(); - updateCommand.setFetch(true); - updateCommand.setProgressMonitor(gitProgressMonitor).call(); - return Status.OK_STATUS; - } - catch ( - IOException - | GitAPIException e) - { - Logger.log(e); - return Status.error(e.getLocalizedMessage()); - } - } - - private void addRecursivePaths(Repository repo, SubmoduleInitCommand initCommand, - SubmoduleUpdateCommand updateCommand) throws IOException - { - if (repo == null) - return; - try (SubmoduleWalk generator = SubmoduleWalk.forIndex(repo)) - { - while (generator.next()) - { - // Add current submodule path - initCommand.addPath(generator.getPath()); - updateCommand.addPath(generator.getPath()); - - // Recursively add paths for each submodule repository - addRecursivePaths(generator.getRepository(), initCommand, updateCommand); - } - } - finally - { - repo.close(); - } - } - }; - - - MutexRule rule = new MutexRule(); - job.setUser(true); - - openProgressView(); - Job installToolsJob = new Job(Messages.UpdateEspIdfCommand_InstallToolsJobMsg) - { - - @Override - protected IStatus run(IProgressMonitor monitor) - { - suggestInstallTools(); - return Status.OK_STATUS; - } - - private void suggestInstallTools() - { - Display.getDefault().asyncExec(new Runnable() - { - @Override - public void run() - { - boolean isYes = MessageDialog.openQuestion(Display.getDefault().getActiveShell(), - Messages.UpdateEspIdfCommand_InstallToolsJobMsg, - Messages.UpdateEspIdfCommand_SuggestToOpenInstallToolsWizard); - if (isYes) - { - InstallToolsHandler installToolsHandler = new InstallToolsHandler(); - try - { - installToolsHandler.setCommandId("com.espressif.idf.ui.command.install"); //$NON-NLS-1$ - installToolsHandler.execute(null); - } - catch (ExecutionException e) - { - Logger.log(e); - } - } - } - }); - - } - - }; - job.setRule(rule); - installToolsJob.setRule(rule); - job.schedule(); - installToolsJob.schedule(); - return null; - } - - private void openProgressView() - { - try - { - PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() - .showView("org.eclipse.ui.views.ProgressView"); //$NON-NLS-1$ - } - catch (PartInitException e) - { - Logger.log(e); - } - - } - - public class MutexRule implements ISchedulingRule - { - @Override - public boolean isConflicting(ISchedulingRule rule) - { - return rule == this; - } - - @Override - public boolean contains(ISchedulingRule rule) - { - return rule == this; - } - } - -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/help/ProductInformationHandler.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/help/ProductInformationHandler.java index e7e988e15..afed00087 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/help/ProductInformationHandler.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/help/ProductInformationHandler.java @@ -131,7 +131,7 @@ private String getPythonExeVersion(String pythonExePath) List commands = new ArrayList<>(); commands.add(pythonExePath); commands.add("--version"); //$NON-NLS-1$ - return pythonExePath != null ? runCommand(commands, IDFUtil.getSystemEnv()) : null; + return pythonExePath != null ? runCommand(commands, System.getenv()) : null; } private String runCommand(List arguments, Map env) diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/GitRepositoryBuilder.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/GitRepositoryBuilder.java deleted file mode 100644 index 074f2ed09..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/GitRepositoryBuilder.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright 2020 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.install; - -import java.io.File; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jgit.api.Git; - -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.ui.tools.GitWizardRepProgressMonitor; - -/** - * @author Kondal Kolipaka - * - */ -public class GitRepositoryBuilder -{ - - private File repositoryDirectory; - private String activeBranch; - private String uri; - private IProgressMonitor monitor; - private boolean fromWizard; - private GitWizardRepProgressMonitor gitWizardRepProgressMonitor; - - public GitRepositoryBuilder(boolean fromWizard, GitWizardRepProgressMonitor gitWizardRepProgressMonitor) - { - this.fromWizard = fromWizard; - this.gitWizardRepProgressMonitor = gitWizardRepProgressMonitor; - } - - /** - * Location of the repository, or where the repository should be cloned. - * - * @param directory the directory - */ - public void repositoryDirectory(final File directory) - { - this.repositoryDirectory = directory; - } - - /** - * Active branch to checkout and use. - * - * @param value the value - */ - public void activeBranch(final String value) - { - this.activeBranch = value; - } - - public void repositoryClone() throws Exception - { - - Collection branchesToClone = new ArrayList<>(); - branchesToClone.add(getBranchPath(this.activeBranch)); - - GitProgressMonitor gitProgressMonitor = new GitProgressMonitor(monitor); - - // @formatter:off - Git git = Git.cloneRepository() - .setProgressMonitor(fromWizard ? gitWizardRepProgressMonitor : gitProgressMonitor) - .setCloneSubmodules(true) - .setURI(this.uri) - .setDirectory(this.repositoryDirectory) - .setBranchesToClone(branchesToClone) - .setBranch(getBranchPath(this.activeBranch)) - .setTimeout(300) - .call(); - - // @formatter:on - Logger.log(String.format(Messages.GitRepositoryBuilder_gitClone, git.toString())); - - // To release the lock on the file system resource - git.getRepository().close(); - - Logger.log(MessageFormat.format("ESP-IDF {0} cloning completed!", this.activeBranch)); //$NON-NLS-1$ - } - - private String getBranchPath(final String branchName) - { - return "refs/heads/" + branchName; //$NON-NLS-1$ - } - - public void repositoryURI(String uri) - { - this.uri = uri; - } - - public void setProgressMonitor(IProgressMonitor monitor) - { - this.monitor = monitor; - } -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/IDFDownloadPage.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/IDFDownloadPage.java deleted file mode 100644 index 085580162..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/IDFDownloadPage.java +++ /dev/null @@ -1,703 +0,0 @@ -/******************************************************************************* - * Copyright 2020 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.install; - -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.wizard.WizardPage; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.DirectoryDialog; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Link; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; - -import com.espressif.idf.core.IDFConstants; -import com.espressif.idf.core.IDFCorePlugin; -import com.espressif.idf.core.IDFVersion; -import com.espressif.idf.core.IDFVersionsReader; -import com.espressif.idf.core.ProcessBuilderFactory; -import com.espressif.idf.core.SystemExecutableFinder; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.util.IDFUtil; -import com.espressif.idf.core.util.StringUtil; -import com.espressif.idf.ui.UIPlugin; - -/** - * @author Kondal Kolipaka - * - */ -public class IDFDownloadPage extends WizardPage -{ - private static final int GIT_TOOL = 0; - private static final int PYTHON_TOOL = 1; - - private Combo versionCombo; - private Map versionsMap; - private Text directoryTxt; - private Button fileSystemBtn; - private Text existingIdfDirTxt; - private Button browseBtn; - - private Text gitText; - private Text pythonText; - - private String pythonExecutablePath; - private String gitExecutablePath; - private SystemExecutableFinder systemExecutableFinder; - - protected IDFDownloadPage(String pageName) - { - super(pageName); - setImageDescriptor(UIPlugin.getImageDescriptor(Messages.IDFDownloadPage_0)); - getPythonExecutablePath(); - } - - @Override - public void createControl(Composite parent) - { - Composite composite = new Composite(parent, SWT.NULL); - - initializeDialogUnits(parent); - - composite.setLayout(new GridLayout()); - composite.setLayoutData(new GridData(GridData.FILL_BOTH)); - - createExistingComposite(composite); - - createGitPythonComposite(composite); - - // esp-idf version selection group - Group versionGrp = new Group(composite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 3; - versionGrp.setLayout(layout); - versionGrp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - versionGrp.setText(Messages.IDFDownloadPage_DownloadIDF); - versionGrp.setFont(parent.getFont()); - - Label versionLbl = new Label(versionGrp, SWT.NONE); - versionLbl.setText(Messages.IDFDownloadPage_ChooseIDFVersion); - - versionCombo = new Combo(versionGrp, SWT.DROP_DOWN | SWT.READ_ONLY); - GridData gridData = new GridData(SWT.NONE, SWT.NONE, false, false, 2, 1); - gridData.widthHint = 250; - versionCombo.setLayoutData(gridData); - versionCombo.addSelectionListener(new SelectionAdapter() - { - @Override - public void widgetSelected(SelectionEvent e) - { - validate(); - } - }); - - versionsMap = new IDFVersionsReader().getVersionsMap(); - Set keySet = versionsMap.keySet(); - versionCombo.setItems(keySet.toArray(new String[keySet.size()])); - if (keySet.size() > 0) - { - versionCombo.select(0); - } - - createDownloadComposite(versionGrp); - createLinkArea(versionGrp); - - Label noteLbl = new Label(composite, SWT.NONE); - noteLbl.setText(Messages.IDFDownloadPage_Note); - - gridData = new GridData(SWT.LEFT, SWT.NONE, true, false, 1, 1); - gridData.verticalIndent = 10; - noteLbl.setLayoutData(gridData); - - setControl(composite); - setPageComplete(false); - } - - private void createGitPythonComposite(Composite parent) - { - Group gitPyGroup = new Group(parent, SWT.SHADOW_ETCHED_IN); - gitPyGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - final int numColumns = 3; - GridLayout gridLayout = new GridLayout(numColumns, false); - gitPyGroup.setLayout(gridLayout); - - Label gitLabel = new Label(gitPyGroup, SWT.NONE); - gitLabel.setText(Messages.GitLabel); - - gitText = new Text(gitPyGroup, SWT.SINGLE | SWT.BORDER); - gitText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - gitExecutablePath = IDFUtil.getGitExecutablePathFromSystem(); - - gitText.setText(gitExecutablePath); - gitText.addModifyListener(new ModifyTextValidationListener(GIT_TOOL)); - - Button gitBrowseButton = new Button(gitPyGroup, SWT.PUSH); - gitBrowseButton.setText(Messages.BrowseButton); - gitBrowseButton.addSelectionListener(new BrowseButtonSelectionAdapter(gitText, GIT_TOOL)); - - if (StringUtil.isEmpty(pythonExecutablePath)) - { - pythonExecutablePath = getPythonExecutablePath(); - } - - Label pythonLabel = new Label(gitPyGroup, SWT.NONE); - pythonLabel.setText(Messages.PythonLabel); - pythonText = new Text(gitPyGroup, SWT.SINGLE | SWT.BORDER); - pythonText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - pythonText.setText(pythonExecutablePath); - pythonText.addModifyListener(new ModifyTextValidationListener(PYTHON_TOOL)); - Button pythonBrowseButton = new Button(gitPyGroup, SWT.PUSH); - pythonBrowseButton.setText(Messages.BrowseButton); - pythonBrowseButton.addSelectionListener(new BrowseButtonSelectionAdapter(pythonText, PYTHON_TOOL)); - } - - private void createExistingComposite(Composite parent) - { - // File system selection - fileSystemBtn = new Button(parent, SWT.CHECK); - fileSystemBtn.setText(Messages.IDFDownloadPage_ChooseAnExistingIDF); - GridData gridData2 = new GridData(SWT.NONE, SWT.NONE, false, false, 1, 1); - gridData2.verticalIndent = 10; - fileSystemBtn.setLayoutData(gridData2); - - Group composite = new Group(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 3; - composite.setLayout(layout); - composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - composite.setFont(parent.getFont()); - - Label label = new Label(composite, SWT.NONE); - label.setText(Messages.IDFDownloadPage_ChooseDirIDF); - - existingIdfDirTxt = new Text(composite, SWT.BORDER); - existingIdfDirTxt.setEnabled(false); - GridData data = new GridData(); - data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - existingIdfDirTxt.setLayoutData(data); - existingIdfDirTxt.addModifyListener(new ModifyListener() - { - @Override - public void modifyText(ModifyEvent e) - { - validate(); - } - }); - - Button existingBrowseBtn = new Button(composite, SWT.PUSH); - existingBrowseBtn.setText(Messages.IDFDownloadPage_BrowseBtn); - existingBrowseBtn.setEnabled(false); - existingBrowseBtn.addSelectionListener(new SelectionAdapter() - { - @Override - public void widgetSelected(SelectionEvent event) - { - DirectoryDialog dlg = new DirectoryDialog(getShell()); - dlg.setFilterPath(existingIdfDirTxt.getText()); - dlg.setText(Messages.IDFDownloadPage_DirectoryDialogTxt); - dlg.setMessage(Messages.IDFDownloadPage_DirectoryDialogMsg); - - String dir = dlg.open(); - if (dir != null) - { - existingIdfDirTxt.setText(dir); - } - } - }); - - fileSystemBtn.addSelectionListener(new SelectionAdapter() - { - @Override - public void widgetSelected(SelectionEvent e) - { - if (fileSystemBtn.getSelection()) - { - existingIdfDirTxt.setEnabled(true); - existingBrowseBtn.setEnabled(true); - - versionCombo.setEnabled(false); - directoryTxt.setEnabled(false); - browseBtn.setEnabled(false); - - } - else - { - existingIdfDirTxt.setEnabled(false); - existingBrowseBtn.setEnabled(false); - - versionCombo.setEnabled(true); - directoryTxt.setEnabled(true); - browseBtn.setEnabled(true); - - } - validate(); - } - }); - - } - - private void createDownloadComposite(Composite composite) - { - Label descLbl = new Label(composite, SWT.NONE); - descLbl.setText(Messages.IDFDownloadPage_ChooseIDFDir); - - directoryTxt = new Text(composite, SWT.BORDER); - GridData data = new GridData(); - data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - directoryTxt.setLayoutData(data); - directoryTxt.setFocus(); - directoryTxt.addModifyListener(new ModifyListener() - { - @Override - public void modifyText(ModifyEvent e) - { - validate(); - } - }); - - browseBtn = new Button(composite, SWT.PUSH); - browseBtn.setText(Messages.IDFDownloadPage_BrowseBtnTxt); - browseBtn.addSelectionListener(new SelectionAdapter() - { - @Override - public void widgetSelected(SelectionEvent event) - { - DirectoryDialog dlg = new DirectoryDialog(getShell()); - dlg.setFilterPath(directoryTxt.getText()); - dlg.setText(Messages.IDFDownloadPage_DirectoryDialogText); - dlg.setMessage(Messages.IDFDownloadPage_DirectoryDialogMessage); - - String dir = dlg.open(); - if (dir != null) - { - directoryTxt.setText(dir); - } - } - }); - - } - - private String getPythonExecutablePath() - { - return IDFUtil.getPythonExecutable(); - } - - private void createLinkArea(Composite parent) - { - Link link = new Link(parent, SWT.NONE); - String message = Messages.IDFDownloadPage_VersionLinkMsg; - link.setText(message); - link.setSize(400, 100); - - GridData gridData = new GridData(SWT.NONE, SWT.NONE, false, false, 3, 1); - gridData.verticalIndent = 10; - link.setLayoutData(gridData); - - link.addSelectionListener(new SelectionAdapter() - { - @Override - public void widgetSelected(SelectionEvent e) - { - try - { - // Open default external browser - PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(e.text)); - } - catch (PartInitException ex) - { - ex.printStackTrace(); - } - catch (MalformedURLException ex) - { - ex.printStackTrace(); - } - } - }); - } - - private boolean validateGitAndPython() - { - if (systemExecutableFinder == null) - { - systemExecutableFinder = new SystemExecutableFinder(); - } - - if (StringUtil.isEmpty(pythonExecutablePath) || StringUtil.isEmpty(gitExecutablePath)) - { - setErrorMessage("Python & Git are Required"); - return false; - } - - - IPath pathGit = systemExecutableFinder.find(gitExecutablePath); - if (pathGit != null) - gitExecutablePath = pathGit.toOSString(); - - File file = new File(gitExecutablePath); - if (!file.exists() && !IDFUtil.isReparseTag(file)) - { - setErrorMessage("Git executable not found"); - return false; - } - - IPath pythonPath = systemExecutableFinder.find(pythonExecutablePath); - if (pythonPath != null) - { - pythonExecutablePath = pythonPath.toOSString(); - } - file = new File(pythonExecutablePath); - if (!file.exists() && !IDFUtil.isReparseTag(file)) - { - setErrorMessage("Python executable not found"); - return false; - } - - return true; - } - - private void validate() - { - if (fileSystemBtn.getSelection()) - { - String idfPath = existingIdfDirTxt.getText(); - if (StringUtil.isEmpty(idfPath)) - { - setPageComplete(false); - setErrorMessage("IDF Directory is Required"); - return; - } - - if (!new File(idfPath).exists()) - { - setErrorMessage(Messages.IDFDownloadPage_DirDoesnotExist+ idfPath); - setPageComplete(false); - return; - } - - String version = getIdfVersionUsingGit(idfPath); - - if (idfPath.contains(" ") && !StringUtil.isEmpty(version)) //$NON-NLS-1$ - { - boolean validVersion = isVersionGreaterOrEqual(version, "5.0.0"); //$NON-NLS-1$ - if (!validVersion) - { - setErrorMessage(Messages.IDFDownloadPage_VersionSpaceError); - setPageComplete(false); - return; - } - if (getErrorMessage() == null || getErrorMessage().equals(Messages.IDFDownloadPage_VersionSpaceError)) - { - setErrorMessage(null); - setPageComplete(true); - } - } - - String idfPyPath = idfPath + File.separator + IDFConstants.TOOLS_FOLDER + File.separator + IDFConstants.IDF_PYTHON_SCRIPT; - String idfToolsPyPth = idfPath + File.separator + IDFConstants.TOOLS_FOLDER + File.separator + IDFConstants.IDF_TOOLS_SCRIPT; - if (!new File (idfPyPath).exists() || !new File (idfToolsPyPth).exists()) - { - setErrorMessage(MessageFormat.format(Messages.IDFDownloadPage_CantfindProperEspIDFDirectory, idfPath)); - setPageComplete(false); - return; - } - if (validateGitAndPython()) - { - setPageComplete(true); - setErrorMessage(null); - setMessage(Messages.IDFDownloadPage_ClickOnFinish + idfPath); - } - else - { - setPageComplete(false); - } - } - else - { - setMessage(StringUtil.EMPTY); - setErrorMessage(null); - boolean supportSpaces = false; - if (versionCombo.getText().contentEquals("master")) //$NON-NLS-1$ - { - supportSpaces = true; - } - else - { - Pattern p = Pattern.compile("([0-9][.][0-9])"); //$NON-NLS-1$ - Matcher m = p.matcher(versionCombo.getText()); - supportSpaces = m.find() && Double.parseDouble(m.group(0)) >= 5.0; - } - if (StringUtil.isEmpty(directoryTxt.getText())) - { - setPageComplete(false); - return; - } - - if (!supportSpaces && directoryTxt.getText().contains(" ")) //$NON-NLS-1$ - { - setErrorMessage(Messages.IDFDownloadPage_VersionSpaceError); - setPageComplete(false); - return; - } - - if (validateGitAndPython()) - { - setPageComplete(true); - setErrorMessage(null); - setMessage(Messages.IDFDownloadPage_ClickFinishToDownload); - } - else - { - setPageComplete(false); - } - } - } - - private String getIdfVersionUsingGit(String idfPath) - { - if (!validateGitAndPython()) - return StringUtil.EMPTY; - - List commands = new ArrayList(); - commands.add(gitExecutablePath); - commands.add("describe"); //$NON-NLS-1$ - - ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); - try - { - Logger.log("Executing commads: " + commands.toString()); - Map environment = new HashMap<>(System.getenv()); - IStatus status = processRunner.runInBackground(commands, Path.fromOSString(idfPath), environment); - if (status == null) - { - Logger.log(IDFCorePlugin.getPlugin(), - IDFCorePlugin.errorStatus("Unable to get the process status.", null)); //$NON-NLS-1$ - return StringUtil.EMPTY; - } - String cmdOutput = status.getMessage(); - String version = StringUtil.EMPTY; - String patternString = "\\d+\\.\\d+\\.\\d+"; //$NON-NLS-1$ - Pattern pattern = Pattern.compile(patternString); - Matcher matcher = pattern.matcher(cmdOutput); - if (matcher.find()) - { - version = matcher.group(0); - } - - if(StringUtil.isEmpty(version)) - { - return StringUtil.EMPTY; - } - - return version; - } - catch (Exception e) - { - Logger.log(e); - } - - return StringUtil.EMPTY; - } - - private boolean isVersionGreaterOrEqual(String version, String minVersion) - { - // Define the regex pattern to match version numbers - String pattern = "\\d+\\.\\d+\\.\\d+"; //$NON-NLS-1$ - Pattern r = Pattern.compile(pattern); - - // Now create matcher object. - Matcher m = r.matcher(version); - Matcher mMin = r.matcher(minVersion); - - if (m.find() && mMin.find()) - { - String[] currentVersionParts = m.group(0).split("\\."); //$NON-NLS-1$ - String[] minVersionParts = mMin.group(0).split("\\."); //$NON-NLS-1$ - - int currentMajor = Integer.parseInt(currentVersionParts[0]); - int currentMinor = Integer.parseInt(currentVersionParts[1]); - int currentPatch = Integer.parseInt(currentVersionParts[2]); - - int minMajor = Integer.parseInt(minVersionParts[0]); - int minMinor = Integer.parseInt(minVersionParts[1]); - int minPatch = Integer.parseInt(minVersionParts[2]); - - if (currentMajor > minMajor) - { - return true; - } - else if (currentMajor == minMajor) - { - if (currentMinor > minMinor) - { - return true; - } - else if (currentMinor == minMinor) - { - return currentPatch >= minPatch; - } - } - } - - return false; - } - - - protected IDFVersion Version() - { - String versionTxt = versionCombo.getText(); - IDFVersion version = versionsMap.get(versionTxt); - return version; - } - - public String getDestinationLocation() - { - return directoryTxt.getText().trim(); - } - - public String getExistingIDFLocation() - { - return existingIdfDirTxt.getText().trim(); - } - - public boolean isConfigureExistingEnabled() - { - return fileSystemBtn.getSelection(); - } - - public String getPythonExePath() - { - return pythonExecutablePath; - } - - public String getGitExecutablePath() - { - return gitExecutablePath; - } - - private class BrowseButtonSelectionAdapter extends SelectionAdapter - { - private Text linkedText; - private int dialog; - private static final String GIT_FILE = "git"; //$NON-NLS-1$ - private static final String PYTHON_FILE = "python*"; //$NON-NLS-1$ - private static final String PYTHON_FILTERS = "Python Executables"; //$NON-NLS-1$ - private static final String WINDOWS_EXTENSION = ".exe"; //$NON-NLS-1$ - - private BrowseButtonSelectionAdapter(Text text, int dialog) - { - this.linkedText = text; - this.dialog = dialog; - } - - @Override - public void widgetSelected(SelectionEvent selectionEvent) - { - FileDialog dlg = null; - if (dialog == GIT_TOOL) - { - dlg = gitDialog(); - } - else - { - dlg = pythonDialog(); - } - - dlg.setText(Messages.FileSelectionDialogTitle); - String dir = dlg.open(); - if (!StringUtil.isEmpty(dir)) - { - linkedText.setText(dir); - } - } - - private FileDialog pythonDialog() - { - FileDialog dialog = new FileDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell()); - if (Platform.getOS().equals(Platform.OS_WIN32)) - { - dialog.setFilterNames(new String[] { PYTHON_FILTERS }); - dialog.setFilterExtensions(new String[] { PYTHON_FILE.concat(WINDOWS_EXTENSION) }); - } - else - { - dialog.setFilterNames(new String[] { PYTHON_FILTERS }); - dialog.setFilterExtensions(new String[] { PYTHON_FILE }); - } - return dialog; - } - - private FileDialog gitDialog() - { - FileDialog dialog = new FileDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell()); - if (Platform.getOS().equals(Platform.OS_WIN32)) - { - dialog.setFilterNames(new String[] { GIT_FILE.concat(WINDOWS_EXTENSION) }); - dialog.setFilterExtensions(new String[] { GIT_FILE.concat(WINDOWS_EXTENSION) }); - } - else - { - dialog.setFilterNames(new String[] { GIT_FILE }); - dialog.setFilterExtensions(new String[] { GIT_FILE }); - } - - return dialog; - } - } - - private class ModifyTextValidationListener implements ModifyListener - { - private int tool; - - private ModifyTextValidationListener(int tool) - { - this.tool = tool; - } - - @Override - public void modifyText(ModifyEvent e) - { - switch (tool) - { - case GIT_TOOL: - gitExecutablePath = gitText.getText(); - break; - case PYTHON_TOOL: - pythonExecutablePath = pythonText.getText(); - default: - break; - } - - validate(); - } - } -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/IDFNewToolsWizard.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/IDFNewToolsWizard.java deleted file mode 100644 index 6295948f7..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/IDFNewToolsWizard.java +++ /dev/null @@ -1,350 +0,0 @@ -/******************************************************************************* - * Copyright 2020 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.install; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.text.MessageFormat; -import java.util.List; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.IJobChangeEvent; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.core.runtime.jobs.JobChangeAdapter; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; - -import com.espressif.idf.core.IDFVersion; -import com.espressif.idf.core.ZipUtility; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.tools.ToolSetConfigurationManager; -import com.espressif.idf.core.tools.vo.IDFToolSet; -import com.espressif.idf.core.util.StringUtil; -import com.espressif.idf.ui.tools.ToolsActivationJob; -import com.espressif.idf.ui.tools.ToolsActivationJobListener; -import com.espressif.idf.ui.tools.ToolsInstallationJob; -import com.espressif.idf.ui.tools.manager.pages.ESPIDFMainTablePage; - -/** - * @author Kondal Kolipaka , Ali Azam Rana - * - */ -public class IDFNewToolsWizard extends Wizard -{ - private static final int BUFFER_SIZE = 4096; // $NON-NLS-1$ - private IDFDownloadPage downloadPage; - private ESPIDFMainTablePage espidfMainTablePage; - private ToolSetConfigurationManager toolSetConfigurationManager; - private ToolsInstallationJob toolsInstallationJob; - private String pythonPath; - private String gitPath; - - public IDFNewToolsWizard() - { - } - - public IDFNewToolsWizard(ESPIDFMainTablePage espidfMainTablePage) - { - this.espidfMainTablePage = espidfMainTablePage; - toolSetConfigurationManager = new ToolSetConfigurationManager(); - } - - @Override - public boolean performFinish() - { - IDFVersion version = downloadPage.Version(); - String destinationLocation = downloadPage.getDestinationLocation(); - boolean configureExistingEnabled = downloadPage.isConfigureExistingEnabled(); - pythonPath = downloadPage.getPythonExePath(); - gitPath = downloadPage.getGitExecutablePath(); - - if (configureExistingEnabled) - { - String localIdfLocation = downloadPage.getExistingIDFLocation(); - - toolsInstallationJob = new ToolsInstallationJob(pythonPath, gitPath, localIdfLocation); - toolsInstallationJob.addJobChangeListener(new ToolsInstallationJobChangeListener()); - toolsInstallationJob.schedule(); - - } - else - { - new File(destinationLocation).mkdirs(); - String url = version.getUrl(); - if (version.getName().equals("master") || version.getName().startsWith("release/")) //$NON-NLS-1$ //$NON-NLS-2$ - { - Job job = new Job(MessageFormat.format(Messages.IDFDownloadWizard_CloningJobMsg, version.getName())) - { - @Override - protected IStatus run(IProgressMonitor monitor) - { - String localIdfLocation = repositoryClone(version.getName(), url, destinationLocation, monitor); - toolsInstallationJob = new ToolsInstallationJob(pythonPath, gitPath, localIdfLocation); - toolsInstallationJob.addJobChangeListener(new ToolsInstallationJobChangeListener()); - toolsInstallationJob.schedule(); - return Status.OK_STATUS; - } - }; - - job.setUser(true); - job.schedule(); - } - else - { - Job job = new Job(MessageFormat.format(Messages.IDFDownloadWizard_DownloadingJobMsg, version.getName())) - { - @Override - protected IStatus run(IProgressMonitor monitor) - { - String localIdfLocation = download(monitor, url, destinationLocation); - toolsInstallationJob = new ToolsInstallationJob(pythonPath, gitPath, localIdfLocation); - toolsInstallationJob.addJobChangeListener(new ToolsInstallationJobChangeListener()); - toolsInstallationJob.schedule(); - return Status.OK_STATUS; - } - }; - - job.setUser(true); - job.schedule(); - - } - - // Show the progress in Progress View - openProgressView(); - } - - return true; - } - - private void openProgressView() - { - try - { - PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() - .showView("org.eclipse.ui.views.ProgressView"); //$NON-NLS-1$ - } - catch (PartInitException e) - { - Logger.log(e); - } - - } - - protected String download(IProgressMonitor monitor, String url, String destinationLocation) - { - try - { - String downloadFile = downloadFile(url, destinationLocation, monitor); - if (downloadFile != null) - { - unZipFile(downloadFile, destinationLocation); - new File(downloadFile).delete(); - - // extracts file name from URL - String folderName = new File(url).getName().replace(".zip", ""); //$NON-NLS-1$ //$NON-NLS-2$ - - return new File(destinationLocation, folderName).getAbsolutePath(); - } - } - catch (IOException e) - { - Logger.log(e); - showErrorMessage(e.getLocalizedMessage()); - } - - return StringUtil.EMPTY; - } - - protected String repositoryClone(String version, String url, String destinationLocation, IProgressMonitor monitor) - { - GitRepositoryBuilder gitBuilder = new GitRepositoryBuilder(false, null); - StringBuilder destinationLocationPath = new StringBuilder(); - destinationLocationPath.append(destinationLocation); - destinationLocationPath.append("/esp-idf-"); //$NON-NLS-1$ - if (version.startsWith("release/")) //$NON-NLS-1$ - { - destinationLocationPath.append(version.substring("release/".length())); //$NON-NLS-1$ - } - else - { - destinationLocationPath.append(version); - } - - gitBuilder.repositoryURI(url); - gitBuilder.repositoryDirectory(new File(destinationLocationPath.toString())); - gitBuilder.activeBranch(version); - gitBuilder.setProgressMonitor(monitor); - - try - { - gitBuilder.repositoryClone(); - return destinationLocationPath.toString(); - - } - catch (Exception e) - { - Logger.log(e); - showErrorMessage(e.getLocalizedMessage()); - } - - return StringUtil.EMPTY; - } - - private void unZipFile(String downloadFile, String destinationLocation) - { - new ZipUtility().decompress(new File(downloadFile), new File(destinationLocation)); - } - - private void showErrorMessage(String errorMessage) - { - Display.getDefault().asyncExec(new Runnable() - { - public void run() - { - MessageDialog.openError(Display.getDefault().getActiveShell(), Messages.IDFDownloadWizard_ErrorTitle, - errorMessage); - } - }); - } - - public void init(IWorkbench aWorkbench, IStructuredSelection currentSelection) - { - setNeedsProgressMonitor(true); - } - - @Override - public void addPages() - { - downloadPage = new IDFDownloadPage("Download page"); //$NON-NLS-1$ - addPage(downloadPage); - } - - protected String downloadFile(String fileURL, String saveDir, IProgressMonitor monitor) throws IOException - { - - String msg = MessageFormat.format(Messages.IDFDownloadWizard_DownloadingMessage, fileURL); - Logger.log(msg); - monitor.beginTask(msg, 100); - - URL url = new URL(fileURL); - HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); - int responseCode = httpConn.getResponseCode(); - - // always check HTTP response code first - if (responseCode == HttpURLConnection.HTTP_OK) - { - String fileName = ""; //$NON-NLS-1$ - String disposition = httpConn.getHeaderField("Content-Disposition"); //$NON-NLS-1$ - String contentType = httpConn.getContentType(); - int contentLength = httpConn.getContentLength(); - - if (disposition != null) - { - // extracts file name from header field - String identifier = "filename="; //$NON-NLS-1$ - int index = disposition.indexOf(identifier); - if (index > 0) - { - fileName = disposition.substring(index + identifier.length(), disposition.length()); - } - } - else - { - // extracts file name from URL - fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); //$NON-NLS-1$ - } - - Logger.log("Content-Type = " + contentType); //$NON-NLS-1$ - Logger.log("Content-Disposition = " + disposition); //$NON-NLS-1$ - Logger.log("Content-Length = " + contentLength); //$NON-NLS-1$ - Logger.log("fileName = " + fileName); //$NON-NLS-1$ - - // opens input stream from the HTTP connection - InputStream inputStream = httpConn.getInputStream(); - String saveFilePath = saveDir + File.separator + fileName; - - // opens an output stream to save into file - FileOutputStream outputStream = new FileOutputStream(saveFilePath); - - float downloaded = 0f; - int bytesRead = -1; - int noOfUnitedUpdated = 0; - byte[] buffer = new byte[BUFFER_SIZE]; - while ((bytesRead = inputStream.read(buffer)) != -1) - { - outputStream.write(buffer, 0, bytesRead); - downloaded = downloaded + BUFFER_SIZE; - int unitsDownloadedSofar = (int) ((downloaded / contentLength) * 100); - if (unitsDownloadedSofar > noOfUnitedUpdated) - { - int needToBeUpdated = unitsDownloadedSofar - noOfUnitedUpdated; - noOfUnitedUpdated = noOfUnitedUpdated + needToBeUpdated; - String taskName = MessageFormat.format(msg + "({0}/{1})", convertToMB(downloaded), //$NON-NLS-1$ - convertToMB(contentLength)); - monitor.setTaskName(taskName); - monitor.worked(needToBeUpdated); - } - if (monitor.isCanceled()) - { - Logger.log("File download cancelled"); //$NON-NLS-1$ - saveFilePath = null; - break; - } - } - - outputStream.close(); - inputStream.close(); - - return saveFilePath; - } - else - { - Logger.log("No file to download. Server replied HTTP code: " + responseCode); //$NON-NLS-1$ - } - httpConn.disconnect(); - return null; - } - - protected String convertToMB(float value) - { - return String.format("%.2f", (value / (1024 * 1024))) + " MB"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - - private class ToolsInstallationJobChangeListener extends JobChangeAdapter - { - @Override - public void done(IJobChangeEvent event) - { - List idfToolSets = toolSetConfigurationManager.getIdfToolSets(false); - Display.getDefault().asyncExec(() -> { - if (espidfMainTablePage != null) - { - espidfMainTablePage.refreshEditorUI(); - } - }); - - if (idfToolSets != null && idfToolSets.size() == 1) - { - ToolsActivationJob toolsActivationJob = new ToolsActivationJob(idfToolSets.get(0), pythonPath, gitPath); - ToolsActivationJobListener toolsActivationJobListener = new ToolsActivationJobListener(espidfMainTablePage); - toolsActivationJob.addJobChangeListener(toolsActivationJobListener); - toolsActivationJob.schedule(); - } - - } - } -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/Messages.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/Messages.java deleted file mode 100644 index cc53e5c79..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/Messages.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.espressif.idf.ui.install; - -import org.eclipse.osgi.util.NLS; - -public class Messages extends NLS -{ - private static final String BUNDLE_NAME = "com.espressif.idf.ui.install.messages"; //$NON-NLS-1$ - public static String GitRepositoryBuilder_gitClone; - public static String IDFDownloadPage_0; - public static String IDFDownloadPage_BrowseBtn; - public static String IDFDownloadPage_BrowseBtnTxt; - public static String IDFDownloadPage_CantfindProperEspIDFDirectory; - public static String IDFDownloadPage_CantFindRequirementsFile; - public static String IDFDownloadPage_ChooseAnExistingIDF; - public static String IDFDownloadPage_ChooseDirIDF; - public static String IDFDownloadPage_ChooseIDFDir; - public static String IDFDownloadPage_ChooseIDFVersion; - public static String IDFDownloadPage_ClickFinishToDownload; - public static String IDFDownloadPage_ClickOnFinish; - public static String IDFDownloadPage_DirDoesnotExist; - public static String IDFDownloadPage_DirectoryDialogMessage; - public static String IDFDownloadPage_DirectoryDialogMsg; - public static String IDFDownloadPage_DirectoryDialogText; - public static String IDFDownloadPage_DirectoryDialogTxt; - public static String IDFDownloadPage_VersionSpaceError; - public static String IDFDownloadPage_DownloadIDF; - public static String IDFDownloadPage_IDFBuildNotSupported; - public static String IDFDownloadPage_Note; - public static String IDFDownloadPage_VersionLinkMsg; - public static String IDFDownloadWizard_CloningCompletedMsg; - public static String IDFDownloadWizard_CloningJobMsg; - public static String IDFDownloadWizard_ConfigMessage; - public static String IDFDownloadWizard_DownloadCompleteMsg; - public static String IDFDownloadWizard_DownloadingJobMsg; - public static String IDFDownloadWizard_DownloadingMessage; - public static String IDFDownloadWizard_ErrorTitle; - public static String IDFDownloadWizard_MessageTitle; - public static String IDFDownloadWizard_AllowSpacesTitle; - public static String IDFDownloadWizard_AllowSpacesMsg; - - public static String BrowseButton; - public static String GitLabel; - public static String PythonLabel; - public static String FileSelectionDialogTitle; - static - { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() - { - } -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/messages.properties b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/messages.properties deleted file mode 100644 index 071dc26af..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/messages.properties +++ /dev/null @@ -1,35 +0,0 @@ -GitRepositoryBuilder_gitClone=git clone result: %s -IDFDownloadPage_0=icons/espressif_logo.png -IDFDownloadPage_BrowseBtn=Browse... -IDFDownloadPage_BrowseBtnTxt=Browse... -IDFDownloadPage_CantfindProperEspIDFDirectory=Can not find idf python scripts in {0} tools. Make sure to select valid ESP-IDF directory. -IDFDownloadPage_ChooseAnExistingIDF=Use an existing ESP-IDF directory from file system -IDFDownloadPage_ChooseDirIDF=Choose existing ESP-IDF directory: -IDFDownloadPage_ChooseIDFDir=Choose a directory to download ESP-IDF to: -IDFDownloadPage_ChooseIDFVersion=Please choose ESP-IDF version to download: -IDFDownloadPage_ClickFinishToDownload=Click on `Finish` to download -IDFDownloadPage_ClickOnFinish=Click on `Finish` to configure IDF_PATH with -IDFDownloadPage_DirDoesnotExist=Directory doesn''t exist: -IDFDownloadPage_VersionSpaceError=ESP-IDF build system support spaces in paths after v5.0. Please choose a different directory. -IDFDownloadPage_DirectoryDialogMessage=Choose Directory to download ESP-IDF -IDFDownloadPage_DirectoryDialogMsg=Select ESP-IDF Directory: -IDFDownloadPage_DirectoryDialogText=Choose Directory -IDFDownloadPage_DirectoryDialogTxt=ESP-IDF Directory: -IDFDownloadPage_DownloadIDF=Download ESP-IDF -IDFDownloadPage_IDFBuildNotSupported=ESP-IDF build system does not support spaces in paths. Please choose a different directory. -IDFDownloadPage_Note=Note: The newly configured ESP-IDF will set to IDF_PATH in the CDT Build environment (Preferences > C/C++ > Build > Environment) -IDFDownloadPage_VersionLinkMsg=For more information about ESP-IDF versions, see https://docs.espressif.com/projects/esp-idf/en/latest/versions.html -IDFDownloadWizard_CloningCompletedMsg=ESP-IDF {0} cloning completed\! This might require a new set of tools to be installed. Do you want to install them? -IDFDownloadWizard_CloningJobMsg=Cloning ESP-IDF {0}... -IDFDownloadWizard_ConfigMessage=IDF_PATH configured with {0}. This might require a new set of tools to be installed. Do you want to install them? -IDFDownloadWizard_DownloadCompleteMsg={0} download completed\! This might require a new set of tools to be installed. Do you want to install them? -IDFDownloadWizard_DownloadingJobMsg=Downloading ESP-IDF {0}... -IDFDownloadWizard_DownloadingMessage=Downloading {0}... -IDFDownloadWizard_ErrorTitle=Error -IDFDownloadWizard_MessageTitle=Message -IDFDownloadWizard_AllowSpacesTitle=Space detected! -IDFDownloadWizard_AllowSpacesMsg=Detected a whitespace character in path. Spaces in IDF_PATH and project paths are allowed in versions 5.0 and higher. By clicking "Yes", you confirm that your version supports spaces. -PythonLabel=Python: -BrowseButton=Browse -GitLabel=Git: -FileSelectionDialogTitle=Select tool executable file \ No newline at end of file diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/messages_zh.properties b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/messages_zh.properties deleted file mode 100644 index 86fd023cb..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/install/messages_zh.properties +++ /dev/null @@ -1,32 +0,0 @@ -GitRepositoryBuilder_gitClone=git \u514b\u9686\u7ed3\u679c\uff1a%s -IDFDownloadPage_0=icons/espressif_logo.png -IDFDownloadPage_BrowseBtn=\u6d4f\u89c8... -IDFDownloadPage_BrowseBtnTxt=\u6d4f\u89c8... -IDFDownloadPage_CantfindIDFpy={0} \u5de5\u5177\u4e2d\u627e\u4e0d\u5230 idf.py -IDFDownloadPage_CantFindRequirementsFile={0} \u4e2d\u627e\u4e0d\u5230 requirements.txt \u6587\u4ef6 -IDFDownloadPage_ChooseAnExistingIDF=\u4f7f\u7528\u6587\u4ef6\u7cfb\u7edf\u4e2d\u73b0\u6709\u7684 ESP-IDF \u76ee\u5f55 -IDFDownloadPage_ChooseDirIDF=\u9009\u62e9\u73b0\u6709\u7684 ESP-IDF \u76ee\u5f55\uff1a -IDFDownloadPage_ChooseIDFDir=\u9009\u62e9 ESP-IDF \u7684\u4e0b\u8f7d\u76ee\u5f55\uff1a -IDFDownloadPage_ChooseIDFVersion=\u8bf7\u9009\u62e9\u9700\u8981\u4e0b\u8f7d\u7684 ESP-IDF \u7248\u672c\uff1a -IDFDownloadPage_ClickFinishToDownload=\u5355\u51fb `\u5b8c\u6210` \u5f00\u59cb\u4e0b\u8f7d -IDFDownloadPage_ClickOnFinish=\u5355\u51fb `\u5b8c\u6210` \u914d\u7f6e IDF_PATH -IDFDownloadPage_DirDoesnotExist=\u76ee\u5f55\u4e0d\u5b58\u5728\uff1a -IDFDownloadPage_DirectoryDialogMessage=\u9009\u62e9 ESP-IDF \u7684\u4e0b\u8f7d\u76ee\u5f55\uff1a -IDFDownloadPage_DirectoryDialogMsg=\u9009\u62e9 ESP-IDF \u76ee\u5f55\uff1a -IDFDownloadPage_DirectoryDialogText=\u9009\u62e9\u76ee\u5f55\uff1a -IDFDownloadPage_DirectoryDialogTxt=ESP-IDF \u76ee\u5f55\uff1a -IDFDownloadPage_DownloadIDF=\u4e0b\u8f7d ESP-IDF -IDFDownloadPage_IDFBuildNotSupported=ESP-IDF \u6784\u5efa\u7cfb\u7edf\u4e0d\u652f\u6301\u8def\u5f84\u4e2d\u6709\u7a7a\u683c\u3002\u8bf7\u9009\u62e9\u4e00\u4e2a\u5176\u4ed6\u76ee\u5f55\u3002 -IDFDownloadPage_Note=\u6ce8\u610f\uff1a\u65b0\u914d\u7f6e\u7684 ESP-IDF \u5c06\u8bbe\u7f6e\u4e3a CDT \u6784\u5efa\u73af\u5883\u4e2d\u7684 IDF_PATH\uff08\u504f\u597d\u8bbe\u7f6e > C/C++ > \u6784\u5efa > \u73af\u5883\uff09 -IDFDownloadPage_VersionLinkMsg=\u6709\u5173 ESP-IDF \u7248\u672c\u7684\u66f4\u591a\u4fe1\u606f\uff0c\u8bf7\u53c2\u9605 https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/versions.html -IDFDownloadWizard_CloningCompletedMsg=ESP-IDF {0} \u514b\u9686\u5b8c\u6210\uff01\u8fd9\u53ef\u80fd\u9700\u8981\u5b89\u88c5\u4e00\u7ec4\u65b0\u7684\u5de5\u5177\u3002\u662f\u5426\u8981\u5b89\u88c5\u8fd9\u4e9b\u5de5\u5177\uff1f -IDFDownloadWizard_CloningJobMsg=\u514b\u9686 ESP-IDF {0}... -IDFDownloadWizard_ConfigMessage=IDF_PATH \u914d\u7f6e\u4e3a {0}\u3002\u8fd9\u53ef\u80fd\u9700\u8981\u5b89\u88c5\u4e00\u7ec4\u65b0\u7684\u5de5\u5177\u3002\u662f\u5426\u8981\u5b89\u88c5\u8fd9\u4e9b\u5de5\u5177\uff1f -IDFDownloadWizard_DownloadCompleteMsg={0} \u4e0b\u8f7d\u5b8c\u6210\uff01\u8fd9\u53ef\u80fd\u9700\u8981\u5b89\u88c5\u4e00\u7ec4\u65b0\u7684\u5de5\u5177\u3002\u662f\u5426\u8981\u5b89\u88c5\u8fd9\u4e9b\u5de5\u5177\uff1f -IDFDownloadWizard_DownloadingJobMsg=\u4e0b\u8f7d ESP-IDF {0}... -IDFDownloadWizard_DownloadingMessage=\u4e0b\u8f7d {0}... -IDFDownloadWizard_ErrorTitle=\u9519\u8bef -IDFDownloadWizard_MessageTitle=\u6d88\u606f -IDFDownloadWizard_AllowSpacesTitle=\u68c0\u6d4b\u5230\u7a7a\u683c\uff01 -IDFDownloadWizard_AllowSpacesMsg=\u68c0\u6d4b\u5230\u8def\u5f84\u4e2d\u5b58\u5728\u7a7a\u683c\u5b57\u7b26\u30025.0 \u53ca\u4ee5\u4e0a\u7248\u672c\u5141\u8bb8 IDF_PATH \u548c\u9879\u76ee\u8def\u5f84\u4e2d\u5b58\u5728\u7a7a\u683c\u3002\u5982\u5df2\u786e\u5b9a\u60a8\u7684\u7248\u672c\u53ef\u652f\u6301\u7a7a\u683c\uff0c\u8bf7\u5355\u51fb\u201c\u662f\u201d\u3002 - diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/preferences/EspresssifPreferencesPage.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/preferences/EspresssifPreferencesPage.java index 5913e4335..672424e22 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/preferences/EspresssifPreferencesPage.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/preferences/EspresssifPreferencesPage.java @@ -3,15 +3,12 @@ import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; @@ -22,7 +19,6 @@ import com.espressif.idf.core.IDFCorePlugin; import com.espressif.idf.core.IDFCorePreferenceConstants; import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.util.StringUtil; public class EspresssifPreferencesPage extends PreferencePage implements IWorkbenchPreferencePage { @@ -42,7 +38,6 @@ public class EspresssifPreferencesPage extends PreferencePage implements IWorkbe private Combo gitAssetsCombo; private Combo pythonWheelCombo; - private Text idfToolsPathText; private Button automateClangdFormatCreationBtn; public EspresssifPreferencesPage() @@ -80,8 +75,6 @@ protected Control createContents(Composite parent) addBuildSettings(mainComposite); - addToolsInstallationSettings(mainComposite); - addClangdSettings(mainComposite); return mainComposite; } @@ -100,73 +93,6 @@ private void addClangdSettings(Composite mainComposite) .setSelection(getPreferenceStore().getBoolean(IDFCorePreferenceConstants.AUTOMATE_CLANGD_FORMAT_FILE)); } - private void addToolsInstallationSettings(Composite mainComposite) - { - Group toolsInstallationGroup = new Group(mainComposite, SWT.SHADOW_ETCHED_IN); - toolsInstallationGroup.setText(Messages.EspressifPreferencesPage_ToolsInstallationGrpTxt); - toolsInstallationGroup.setLayout(new GridLayout(3, false)); - - Label githubAssetsLabel = new Label(toolsInstallationGroup, SWT.NONE); - githubAssetsLabel.setText(Messages.EspressifPreferencesPage_ToolsInstallationGitAssetUrlLabel); - gitAssetsCombo = new Combo(toolsInstallationGroup, SWT.DROP_DOWN | SWT.BORDER); - gitAssetsCombo.setItems(IDFCorePreferenceConstants.IDF_GITHUB_ASSETS_DEFAULT_GLOBAL, - IDFCorePreferenceConstants.IDF_GITHUB_ASSETS_DEFAULT_CHINA); - gitAssetsCombo.select(0); - - Label pythonWheelsLabel = new Label(toolsInstallationGroup, SWT.NONE); - pythonWheelsLabel.setText(Messages.EspressifPreferencesPage_ToolsInstallationPythonPyWheelUrlLabel); - pythonWheelCombo = new Combo(toolsInstallationGroup, SWT.DROP_DOWN | SWT.BORDER); - pythonWheelCombo.setItems(IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL_DEFAULT_GLOBAL, - IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL_DEFAULT_CHINA); - pythonWheelCombo.select(0); - - GridData gitTextGridData = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); - gitTextGridData.widthHint = 200; - GridData pythonTextGridData = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); - pythonTextGridData.widthHint = 200; - gitAssetsCombo.setLayoutData(gitTextGridData); - pythonWheelCombo.setLayoutData(pythonTextGridData); - - Label idfToolsPathLabel = new Label(toolsInstallationGroup, SWT.NONE); - idfToolsPathLabel.setText(Messages.EspressifPreferencesPage_EspIdfToolsInstallationDirectoryLabel); - idfToolsPathText = new Text(toolsInstallationGroup, SWT.SINGLE | SWT.NONE); - GridData idfToolsPathTextGridData = new GridData(SWT.FILL, SWT.CENTER, true, false); - idfToolsPathTextGridData.widthHint = 200; - idfToolsPathText.setLayoutData(idfToolsPathTextGridData); - // Add browse button - Button browseButtonIdfToolsPath = new Button(toolsInstallationGroup, SWT.PUSH); - browseButtonIdfToolsPath.setText(Messages.EspressifPreferencesPage_DirectorySelectionIDFToolsPathBrowseButton); - browseButtonIdfToolsPath.addSelectionListener(new SelectionAdapter() - { - @Override - public void widgetSelected(SelectionEvent e) - { - DirectoryDialog dialog = new DirectoryDialog(mainComposite.getShell()); - dialog.setText(Messages.EspressifPreferencesPage_DirectorySelectionIDFToolsPathTitle); - dialog.setMessage(Messages.EspressifPreferencesPage_DirectorySelectionIDFToolsPathMessage); - String dir = dialog.open(); - if (dir != null) - { - idfToolsPathText.setText(dir); - } - } - }); - - String idfToolsPath = getPreferenceStore().getString(IDFCorePreferenceConstants.IDF_TOOLS_PATH); - idfToolsPath = StringUtil.isEmpty(idfToolsPath) - ? getPreferenceStore().getDefaultString(IDFCorePreferenceConstants.IDF_TOOLS_PATH) - : idfToolsPath; - idfToolsPathText.setText(idfToolsPath); - - String gitUrl = getPreferenceStore().getString(IDFCorePreferenceConstants.IDF_GITHUB_ASSETS); - String pyWheelUrl = getPreferenceStore().getString(IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL); - gitUrl = StringUtil.isEmpty(gitUrl) ? gitAssetsCombo.getItem(0) : gitUrl; - pyWheelUrl = StringUtil.isEmpty(pyWheelUrl) ? pythonWheelCombo.getItem(0) : pyWheelUrl; - - gitAssetsCombo.setText(gitUrl); - pythonWheelCombo.setText(pyWheelUrl); - } - private void addBuildSettings(Composite mainComposite) { Group buildGroup = new Group(mainComposite, SWT.SHADOW_ETCHED_IN); @@ -267,12 +193,6 @@ public boolean performOk() IDFCorePlugin.ERROR_MARKER_LISTENER.initialMarkerCleanup(); } - getPreferenceStore().setValue(IDFCorePreferenceConstants.IDF_GITHUB_ASSETS, gitAssetsCombo.getText()); - - getPreferenceStore().setValue(IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL, pythonWheelCombo.getText()); - - getPreferenceStore().setValue(IDFCorePreferenceConstants.IDF_TOOLS_PATH, idfToolsPathText.getText()); - getPreferenceStore().setValue(IDFCorePreferenceConstants.AUTOMATE_CLANGD_FORMAT_FILE, automateClangdFormatCreationBtn.getSelection()); } @@ -300,7 +220,6 @@ protected void performDefaults() .setSelection(getPreferenceStore().getBoolean(IDFCorePreferenceConstants.AUTOMATE_CLANGD_FORMAT_FILE)); gitAssetsCombo.setText(gitAssetsCombo.getItem(0)); pythonWheelCombo.setText(pythonWheelCombo.getItem(0)); - idfToolsPathText.setText(getPreferenceStore().getDefaultString(IDFCorePreferenceConstants.IDF_TOOLS_PATH)); } private void initializeDefaults() @@ -314,13 +233,6 @@ private void initializeDefaults() IDFCorePreferenceConstants.AUTOMATE_BUILD_HINTS_DEFAULT_STATUS); getPreferenceStore().setDefault(IDFCorePreferenceConstants.HIDE_ERRORS_IDF_COMPONENTS, IDFCorePreferenceConstants.HIDE_ERRORS_IDF_COMPONENTS_DEFAULT_STATUS); - - getPreferenceStore().setDefault(IDFCorePreferenceConstants.IDF_GITHUB_ASSETS, - IDFCorePreferenceConstants.IDF_GITHUB_ASSETS_DEFAULT_GLOBAL); - getPreferenceStore().setDefault(IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL, - IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL_DEFAULT_GLOBAL); - getPreferenceStore().setDefault(IDFCorePreferenceConstants.IDF_TOOLS_PATH, - IDFCorePreferenceConstants.IDF_TOOLS_PATH_DEFAULT); getPreferenceStore().setDefault(IDFCorePreferenceConstants.AUTOMATE_CLANGD_FORMAT_FILE, IDFCorePreferenceConstants.AUTOMATE_CLANGD_FORMAT_FILE_DEFAULT); } diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/size/IDFSizeDataManager.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/size/IDFSizeDataManager.java index 7acb68185..a12e6d089 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/size/IDFSizeDataManager.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/size/IDFSizeDataManager.java @@ -205,7 +205,7 @@ protected IStatus runProcess(IFile file, List arguments) throws Exceptio ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); try { - return processRunner.runInBackground(arguments, Path.ROOT, IDFUtil.getSystemEnv()); + return processRunner.runInBackground(arguments, Path.ROOT, System.getenv()); } catch (Exception e1) { diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/EspressifToolStartup.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/EspressifToolStartup.java new file mode 100644 index 000000000..570521136 --- /dev/null +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/EspressifToolStartup.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright 2025 Espressif Systems (Shanghai) PTE LTD. All rights reserved. + * Use is subject to license terms. + *******************************************************************************/ +package com.espressif.idf.ui.tools; + +import java.text.MessageFormat; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.MessageBox; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IStartup; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.ide.IDE; +import org.osgi.service.prefs.Preferences; + +import com.espressif.idf.core.build.Messages; +import com.espressif.idf.core.logging.Logger; +import com.espressif.idf.core.tools.EimConstants; +import com.espressif.idf.core.tools.ToolInitializer; +import com.espressif.idf.core.tools.vo.EimJson; +import com.espressif.idf.core.tools.watcher.EimJsonStateChecker; +import com.espressif.idf.core.tools.watcher.EimJsonWatchService; +import com.espressif.idf.core.util.IDFUtil; +import com.espressif.idf.core.util.StringUtil; +import com.espressif.idf.ui.UIPlugin; +import com.espressif.idf.ui.dialogs.MessageLinkDialog; +import com.espressif.idf.ui.handlers.EclipseHandler; +import com.espressif.idf.ui.tools.manager.ESPIDFManagerEditor; +import com.espressif.idf.ui.tools.manager.EimEditorInput; +import com.espressif.idf.ui.tools.watcher.EimJsonUiChangeHandler; + +/** + * Startup class to handle the tools + * + * @author Ali Azam Rana + * + */ +public class EspressifToolStartup implements IStartup +{ + @Override + public void earlyStartup() + { + Preferences preferences = org.eclipse.core.runtime.preferences.InstanceScope.INSTANCE + .getNode(UIPlugin.PLUGIN_ID); + ToolInitializer toolInitializer = new ToolInitializer(preferences); + + if (!toolInitializer.isEimInstalled()) + { + notifyMissingTools(); + return; + } + + EimJson eimJson = toolInitializer.loadEimJson(); + if (eimJson == null) + { + return; + } + + if (!toolInitializer.isEspIdfSet()) + { + promptUserToOpenToolManager(eimJson); + } + + EimJsonStateChecker stateChecker = new EimJsonStateChecker(preferences); + if (stateChecker.wasModifiedSinceLastRun()) + { + showEimJsonStateChangeNotification(); + } + + stateChecker.updateLastSeenTimestamp(); + EimJsonWatchService.getInstance().addEimJsonChangeListener(new EimJsonUiChangeHandler(preferences)); + } + + private void showEimJsonStateChangeNotification() + { + Display.getDefault().asyncExec(() -> { + MessageDialog.openInformation(Display.getDefault().getActiveShell(), + com.espressif.idf.ui.tools.Messages.EimJsonChangedMsgTitle, + com.espressif.idf.ui.tools.Messages.EimJsonStateChangedMsgDetail); + }); + } + + private void notifyMissingTools() + { + Display.getDefault().asyncExec(() -> { + MessageLinkDialog.openWarning(Display.getDefault().getActiveShell(), + Messages.ToolsInitializationEimMissingMsgBoxTitle, + MessageFormat.format(Messages.ToolsInitializationEimMissingMsgBoxMessage, EimConstants.EIM_URL)); + }); + } + + private void promptUserToOpenToolManager(EimJson eimJson) + { + Display.getDefault().syncExec(() -> { + String testRunValue = System.getProperty("testRun"); + Logger.log("testRun: " + testRunValue); + + if (!StringUtil.isEmpty(testRunValue) && Boolean.parseBoolean(testRunValue)) + { + openEspIdfManager(eimJson); + return; + } + + Shell shell = Display.getDefault().getActiveShell(); + MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO); + messageBox.setText(Messages.NoActiveEspIdfInWorkspaceMsgTitle); + messageBox.setMessage(Messages.NoActiveEspIdfInWorkspaceMsg); + + if (messageBox.open() == SWT.YES) + { + openEspIdfManager(eimJson); + } + }); + } + + private void openEspIdfManager(EimJson eimJson) + { + IWorkbenchWindow window = EclipseHandler.getActiveWorkbenchWindow(); + IDFUtil.closeWelcomePage(window); + try + { + EimEditorInput input = new EimEditorInput(eimJson); + input.setFirstStartup(true); + IDE.openEditor(window.getActivePage(), input, ESPIDFManagerEditor.EDITOR_ID); + } + catch (PartInitException e) + { + Logger.log(e); + } + } +} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/GitWizardRepProgressMonitor.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/GitWizardRepProgressMonitor.java deleted file mode 100644 index d245dc821..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/GitWizardRepProgressMonitor.java +++ /dev/null @@ -1,138 +0,0 @@ -/******************************************************************************* - * Copyright 2022 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.tools; - -import java.text.MessageFormat; -import java.time.Duration; -import java.util.Queue; - -import org.eclipse.jgit.lib.BatchingProgressMonitor; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.ProgressBar; - -/** - * Git cloning progress report class to add updated messages to the passed queue of messages which can be then consumed - * by the initiator - * - * @author Ali Azam Rana - * - */ -public class GitWizardRepProgressMonitor extends BatchingProgressMonitor -{ - private Queue logMessages; - private boolean jobCancelled; - private ProgressBar progressBar; - private Display display; - - public GitWizardRepProgressMonitor(Queue logMessages, ProgressBar progressBar) - { - this.logMessages = logMessages; - this.progressBar = progressBar; - display = progressBar.getDisplay(); - } - - protected void onUpdate(String taskName, int workCurr) - { - onUpdate(taskName, workCurr, null); - } - - protected void onEndTask(String taskName, int workCurr) - { - onEndTask(taskName, workCurr, null); - } - - protected void onUpdate(String taskName, int workCurr, int workTotal, int percentDone) - { - onUpdate(taskName, workCurr, null); - } - - protected void onEndTask(String taskName, int workCurr, int workTotal, int percentDone) - { - onEndTask(taskName, workCurr, workTotal, percentDone, null); - } - - protected void onUpdate(String taskName, int workCurr, Duration duration) - { - updateProgressBar(workCurr); - setProgressBarVisibility(false); - logMessages.add(MessageFormat.format("{0} {1}", taskName, workCurr)); //$NON-NLS-1$ - } - - protected void onEndTask(String taskName, int workCurr, Duration duration) - { - updateProgressBar(workCurr); - logMessages.add(MessageFormat.format("Finished {0} {1}", taskName, workCurr)); //$NON-NLS-1$ - } - - protected void onUpdate(String taskName, int workCurr, int workTotal, int percentDone, Duration duration) - { - initializeMaxProgressbar(workTotal); - updateProgressBar(workCurr); - logMessages.add( - MessageFormat.format("{0} {1}, total {2} {3}% Completed", taskName, workCurr, workTotal, percentDone)); //$NON-NLS-1$ - } - - protected void onEndTask(String taskName, int workCurr, int workTotal, int percentDone, Duration duration) - { - initializeMaxProgressbar(workTotal); - updateProgressBar(workCurr); - setProgressBarVisibility(false); - logMessages.add(MessageFormat.format("Finished {0} {1}, total {2} {3}% Completed", taskName, workCurr, //$NON-NLS-1$ - workTotal, percentDone)); - } - - @Override - public boolean isCancelled() - { - if (jobCancelled) - { - logMessages.add("Cancelled by User"); //$NON-NLS-1$ - } - return jobCancelled; - } - - public void setJobCancelled(boolean jobCancelled) - { - this.jobCancelled = jobCancelled; - } - - private void initializeMaxProgressbar(int max) - { - display.asyncExec(new Runnable() - { - @Override - public void run() - { - progressBar.setVisible(true); - progressBar.setMaximum(max); - } - }); - } - - private void updateProgressBar(int updateValue) - { - display.asyncExec(new Runnable() - { - @Override - public void run() - { - progressBar.setSelection(updateValue); - } - }); - } - - private void setProgressBarVisibility(boolean visible) - { - display.asyncExec(new Runnable() - { - @Override - public void run() - { - progressBar.setVisible(visible); - } - }); - } - -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/LogMessagesThread.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/LogMessagesThread.java deleted file mode 100644 index 20e25273f..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/LogMessagesThread.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright 2022 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.tools; - -import java.util.Queue; - -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Text; - -import com.espressif.idf.core.logging.Logger; - -/** - * Thread for logging messages in a queue to the SWT Text - * - * @author Ali Azam Rana - * - */ -public class LogMessagesThread extends Thread -{ - private final Queue logMessages; - private boolean stopLogging; - private final Text logAreaText; - private Display display; - - public LogMessagesThread(Queue logMessages, Text logAreaText, Display display) - { - this.logMessages = logMessages; - this.logAreaText = logAreaText; - this.display = display; - } - - @Override - public void run() - { - while (!stopLogging) - { - try - { - Thread.sleep(50); - } - catch (InterruptedException e) - { - Logger.log(e); - } - if (logMessages.size() != 0) - { - String msg = logMessages.poll(); - showMessage(msg); - } - } - } - - private void showMessage(final String message) - { - if (display == null && logAreaText != null) - { - display = logAreaText.getDisplay(); - } - display.asyncExec(new Runnable() - { - public void run() - { - if (logAreaText.getText().length() != 0) - { - logAreaText.append(System.getProperty("line.separator")); //$NON-NLS-1$ - } - logAreaText.append(message); - } - }); - } - - public void setStopLogging(boolean stopLogging) - { - this.stopLogging = stopLogging; - } -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ManageEspIdfVersionsHandler.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ManageEspIdfVersionsHandler.java index ceb02b514..dc1dff888 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ManageEspIdfVersionsHandler.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ManageEspIdfVersionsHandler.java @@ -1,24 +1,27 @@ package com.espressif.idf.ui.tools; -import java.io.File; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.ArrayList; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.ide.IDE; -import org.eclipse.ui.part.FileEditorInput; +import com.espressif.idf.core.build.Messages; import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.tools.IToolsInstallationWizardConstants; +import com.espressif.idf.core.tools.EimConstants; +import com.espressif.idf.core.tools.EimIdfConfiguratinParser; +import com.espressif.idf.core.tools.vo.EimJson; +import com.espressif.idf.core.tools.vo.IdfInstalled; import com.espressif.idf.core.util.IDFUtil; +import com.espressif.idf.ui.dialogs.MessageLinkDialog; import com.espressif.idf.ui.handlers.EclipseHandler; import com.espressif.idf.ui.tools.manager.ESPIDFManagerEditor; +import com.espressif.idf.ui.tools.manager.EimEditorInput; public class ManageEspIdfVersionsHandler extends AbstractHandler { @@ -39,34 +42,45 @@ public void run() { IWorkbenchWindow activeww = EclipseHandler.getActiveWorkbenchWindow(); IDFUtil.closeWelcomePage(activeww); - + + EimJson eimJson = new EimJson(); + try { - File inputFile = new File(toolSetConfigFilePath()); - if (!inputFile.exists()) - { - inputFile.createNewFile(); - } + EimIdfConfiguratinParser eimIdfConfiguratinParser = new EimIdfConfiguratinParser(); + eimJson = eimIdfConfiguratinParser.getEimJson(true); + } + catch (IOException e) + { + Logger.log(e); + // Proceed with an empty EimJson object + } - IFile iFile = ResourcesPlugin.getWorkspace().getRoot() - .getFile(new Path(inputFile.getAbsolutePath())); - IDE.openEditor(activeww.getActivePage(), new FileEditorInput(iFile), ESPIDFManagerEditor.EDITOR_ID); + try + { + IDE.openEditor(activeww.getActivePage(), new EimEditorInput(eimJson), ESPIDFManagerEditor.EDITOR_ID, + true); } catch (Exception e) { Logger.log(e); } + + if (eimJson.getIdfInstalled().isEmpty()) + { + notifyIDFNotFound(); + } } }); } - - private String toolSetConfigFilePath() + + private void notifyIDFNotFound() { - IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation(); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(path.toOSString()); - stringBuilder.append(File.separatorChar); - stringBuilder.append(IToolsInstallationWizardConstants.TOOL_SET_CONFIG_FILE); - return stringBuilder.toString(); + Display.getDefault().asyncExec(() -> { + MessageLinkDialog.openWarning(Display.getDefault().getActiveShell(), + Messages.ToolsInitializationEimMissingMsgBoxTitle, + MessageFormat.format(Messages.ToolsInitializationEimMissingMsgBoxMessage, EimConstants.EIM_URL)); + + }); } } diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/Messages.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/Messages.java index 25f631a0f..5dbcf3f2b 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/Messages.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/Messages.java @@ -16,118 +16,19 @@ public class Messages extends NLS { private static final String BUNDLE_NAME = "com.espressif.idf.ui.tools.messages"; //$NON-NLS-1$ - public static String UrlDescriptionText; - public static String SizeDescriptionText; - public static String SupportedTargetsDescriptionText; - public static String ToolsManagerShellHeading; - public static String ToolsTreeNameCol; - public static String ToolsTreeSizeCol; - public static String ToolsTreeStatusCol; - public static String DescriptionText; - public static String InstallToolsText; - public static String DeleteToolsText; - public static String Installed; - public static String DownloadFileText; - public static String ExtractionTextMessage; - public static String InstallingToolMessage; - public static String UpdatingPathMessage; - public static String PreviousToolMessage; - public static String UpdateToolPathMessage; - public static String SystemPathMessage; - public static String ExtractionCompletedMessage; - public static String RemovedPathMessage; - public static String ManageToolsInstallationShell_mntmNewItem_text; - public static String ManageToolsInstallationShell_tltmCheckItem_text; - public static String ManageToolsInstallationShell_label_text; - public static String SelectRecommended; - public static String FilterLabel; - public static String ManageToolsInstallation; - public static String ManageToolsInstallationDescription; - public static String ToolsManagerWizard; - public static String InstallPreRquisitePage; - public static String InstallPreRquisitePage_lblLog_text; - public static String InstallToolsPreReqPageDescription; - public static String FileSelectionDialogTitle; - public static String DirectorySelectionDialogMessage; - public static String GitLabel; - public static String PythonLabel; - public static String BrowseButton; - public static String InstallEspIdfPage; - public static String InstallEspIdfPageDescription; - public static String InstallEspIdfPage_Existing; - public static String InstallEspIdfPage_btnNew_text; - public static String InstallEspIdfPage_lblEspidfPath_text; - public static String InstallEspIdfPage_lblEspidfVersion_text; - public static String InstallEspIdfPage_btnDownload_text; - public static String SelectPythonVersion; - public static String InstallEspIdfPage_lblDownloadDirectory_text; - public static String SelectDownloadDir; - public static String GitCloningJobMsg; - public static String CloningCompletedMsg; - public static String IDFDownloadWizard_DownloadingMessage; - public static String IDFDownloadWizard_DownloadCompleteMsg; - public static String IDFDownloadWizard_DecompressingMsg; - public static String IDFDownloadWizard_DecompressingCompleted; - public static String IDFDownloadWizard_UpdatingIDFPathMessage; - public static String BtnCancel; - public static String OperationCancelledByUser; - public static String InstallToolsHandler_CopyingOpenOCDRules; - public static String InstallToolsHandler_OpenOCDRulesCopied; - public static String InstallToolsHandler_OpenOCDRulesCopyError; - public static String InstallToolsHandler_OpenOCDRulesCopyPaths; - public static String InstallToolsHandler_OpenOCDRulesCopyWarning; - public static String InstallToolsHandler_OpenOCDRulesCopyWarningMessage; - public static String InstallToolsHandler_OpenOCDRulesNotCopied; - public static String AbstractToolsHandler_ExecutingMsg; - public static String ToolAreadyPresent; - public static String ForceDownload_ToolTip; - public static String ForceDownload; - public static String InstallToolsProgressShell_lblNewLabel_text; - public static String InstallToolsProgressShell_text_text; - public static String InstallToolsProgressShell_txtTxtinstalledtool_text; - public static String RemovingDirectoryMessage; - public static String RemoveToolMessageBox; - public static String RemoveToolMessageBoxTitle; - public static String SelectAllButton; - public static String DeselectAllButton; - public static String FilterTargets; - public static String Warning; - public static String DirectorySelectionDialog_IDFDirLabel; - public static String DirectorySelectionDialog_SelectIDFDirMessage; - public static String NotInstalled; - public static String Available; - public static String ShowAvailableVersionsOnly; - public static String ForceDownloadToolTip; - public static String RemoveToolMessageBoxFinish; - public static String SelectAllButtonToolTip; - public static String DeselectAllButtonToolTip; - public static String SelectRecommendedToolTip; - public static String FilterTargetBoxToolTip; - public static String ShowAvailableVersionsOnlyToolTip; - public static String DeleteToolsTextToolTip; - public static String MissingToolsValidationMessage_A; - public static String MissingToolsValidationMessage_B; - public static String MissingToolsValidationLink; - - public static String EspIdfEditorTitle; public static String EspIdfManagerVersionCol; public static String EspIdfManagerLocationCol; - public static String EspIdfManagerStateCol; public static String EspIdfManagerActivateCol; - public static String EspIdfManagerAddToolsBtn; - public static String EspIdfManagerRemoveAllBtn; - public static String EspIdfManagerDeleteBtn; - public static String EspIdfManagerMessageBoxDeleteConfirmMessage; - public static String EspIdfManagerMessageBoxDeleteConfirmMessageTitle; - public static String EspIdfManagerMessageBoxDeleteAllConfirmMessage; - public static String EspIdfManagerMessageBoxDeleteAllConfirmMessageTitle; - - public static String IDFDownloadHandler_ESPIDFConfiguration; - public static String IDFDownloadHandler_DownloadPage_Title; - public static String IDFDownloadHandler_DownloadPageMsg; + public static String EspIdfManagerNameCol; public static String EspIdfManagerReloadBtnToolTip; - public static String EspIdfManagerDeleteBtnToolTip; + public static String IDFGuideLinkLabel_Text; + + public static String IDFToolsHandler_ToolsManagerConsole; + + public static String EimJsonChangedMsgTitle; + public static String EimJsonChangedMsgDetail; + public static String EimJsonStateChangedMsgDetail; static { diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsActivationJobListener.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/SetupToolsJobListener.java similarity index 70% rename from bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsActivationJobListener.java rename to bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/SetupToolsJobListener.java index 438e5e510..c292171b3 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsActivationJobListener.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/SetupToolsJobListener.java @@ -4,6 +4,7 @@ *******************************************************************************/ package com.espressif.idf.ui.tools; +import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.core.runtime.preferences.InstanceScope; @@ -14,25 +15,28 @@ import com.espressif.idf.core.logging.Logger; import com.espressif.idf.core.resources.OpenDialogListenerSupport; import com.espressif.idf.core.resources.PopupDialog; +import com.espressif.idf.core.tools.EimConstants; +import com.espressif.idf.core.tools.SetupToolsInIde; import com.espressif.idf.ui.UIPlugin; import com.espressif.idf.ui.tools.manager.pages.ESPIDFMainTablePage; -import com.espressif.idf.ui.update.InstallToolsHandler; /** - * Listener for {@link ToolsActivationJob} + * Listener for {@link SetupToolsInIde} * @author Ali Azam Rana * */ -public class ToolsActivationJobListener extends JobChangeAdapter +public class SetupToolsJobListener extends JobChangeAdapter { private ESPIDFMainTablePage espidfMainTablePage; + private SetupToolsInIde setupToolsInIde; - public ToolsActivationJobListener(ESPIDFMainTablePage espidfMainTablePage) + public SetupToolsJobListener(ESPIDFMainTablePage espidfMainTablePage, SetupToolsInIde setupToolsInIde) { this.espidfMainTablePage = espidfMainTablePage; + this.setupToolsInIde = setupToolsInIde; } - public ToolsActivationJobListener() + public SetupToolsJobListener() { } @@ -46,23 +50,21 @@ public void aboutToRun(IJobChangeEvent event) @Override public void done(IJobChangeEvent event) { - Display.getDefault().asyncExec(() -> { - if (espidfMainTablePage != null) - { - espidfMainTablePage.refreshEditorUI(); - } - }); - OpenDialogListenerSupport.getSupport().firePropertyChange(PopupDialog.ENABLE_LAUNCHBAR_EVENTS.name(), null, - null); - Preferences scopedPreferenceStore = InstanceScope.INSTANCE.getNode(UIPlugin.PLUGIN_ID); + + if (event.getResult().getSeverity() != IStatus.OK) + { + // Rollback all the changes + setupToolsInIde.rollback(); + } + if (event.getResult().isOK()) { - scopedPreferenceStore.putBoolean(InstallToolsHandler.INSTALL_TOOLS_FLAG, true); + scopedPreferenceStore.putBoolean(EimConstants.INSTALL_TOOLS_FLAG, true); } else { - scopedPreferenceStore.putBoolean(InstallToolsHandler.INSTALL_TOOLS_FLAG, false); + scopedPreferenceStore.putBoolean(EimConstants.INSTALL_TOOLS_FLAG, false); } try @@ -73,5 +75,14 @@ public void done(IJobChangeEvent event) { Logger.log(e); } + + Display.getDefault().asyncExec(() -> { + if (espidfMainTablePage != null) + { + espidfMainTablePage.refreshEditorUI(); + } + }); + OpenDialogListenerSupport.getSupport().firePropertyChange(PopupDialog.ENABLE_LAUNCHBAR_EVENTS.name(), null, + null); } } diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsActivationJob.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsActivationJob.java deleted file mode 100644 index 63c0c994d..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsActivationJob.java +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* - * Copyright 2024 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.tools; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.List; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.MessageBox; -import org.osgi.service.prefs.BackingStoreException; -import org.osgi.service.prefs.Preferences; - -import com.espressif.idf.core.IDFEnvironmentVariables; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.toolchain.ESPToolChainManager; -import com.espressif.idf.core.tools.vo.IDFToolSet; -import com.espressif.idf.core.util.IDFUtil; -import com.espressif.idf.core.util.LspService; -import com.espressif.idf.core.util.StringUtil; -import com.espressif.idf.ui.UIPlugin; -import com.espressif.idf.ui.update.ExportIDFTools; -import com.espressif.idf.ui.update.Messages; - -/** - * Job to activate the provide {@link IDFToolSet} in the given ide environment - * - * @author Ali Azam Rana - * - */ -public class ToolsActivationJob extends ToolsJob -{ - public static final String INSTALL_TOOLS_FLAG = "INSTALL_TOOLS_FLAG"; //$NON-NLS-1$ - - public ToolsActivationJob(IDFToolSet idfToolSet, String pythonExecutablePath, String gitExecutablePath) - { - super("Tools Activation Job", null, null); - this.idfToolSet = idfToolSet; - } - - @Override - protected IStatus run(IProgressMonitor monitor) - { - if (idfToolSet == null) - { - return Status.error("IDF Tool Set Cannot be null"); - } - - // verify with export script to test if everything is okay with installation - - monitor.beginTask("Verifying if there are any changes to the installed tools", 5); - monitor.worked(1); - - ExportIDFTools exportIDFTools = new ExportIDFTools(); - IStatus status = exportIDFTools.getToolsExportOutputFromGivenIdfPath(idfToolSet.getSystemPythonExecutablePath(), - idfToolSet.getSystemGitExecutablePath(), console, errorConsoleStream, idfToolSet.getIdfLocation()); - if (status.getSeverity() == IStatus.ERROR) - { - return Status.error("INSTALL_AGAIN"); - } - monitor.worked(1); - - monitor.setTaskName("Exporting variables to eclipse"); - processExportCmdOutput(status.getMessage()); - setEnvVarsInEclipse(); - monitor.worked(1); - - monitor.setTaskName("Setting up toolchains and targets"); - setUpToolChainsAndTargets(); - monitor.worked(1); - - // post export operations like copying openocd rules may also need to setup with the python dependencies here as - // well like websocket-client - monitor.setTaskName(Messages.InstallToolsHandler_InstallingWebscoketMsg); - handleWebSocketClientInstall(); - monitor.worked(1); - - monitor.setTaskName("Setting OpenOCD rules"); - copyOpenOcdRules(); - monitor.worked(1); - - idfToolSet.setActive(true); - - toolSetConfigurationManager.export(idfToolSet); - console.println("Tools Activated"); - new LspService().updateClangdPath(); - Preferences scopedPreferenceStore = InstanceScope.INSTANCE.getNode(UIPlugin.PLUGIN_ID); - scopedPreferenceStore.putBoolean(INSTALL_TOOLS_FLAG, true); - try - { - scopedPreferenceStore.flush(); - } - catch (BackingStoreException e) - { - Logger.log(e); - } - - return Status.OK_STATUS; - } - - private void copyOpenOcdRules() - { - if (Platform.getOS().equals(Platform.OS_LINUX) - && !IDFUtil.getOpenOCDLocation().equalsIgnoreCase(StringUtil.EMPTY)) - { - console.println(Messages.InstallToolsHandler_CopyingOpenOCDRules); - // Copy the rules to the idf - StringBuilder pathToRules = new StringBuilder(); - pathToRules.append(IDFUtil.getOpenOCDLocation()); - pathToRules.append("/../share/openocd/contrib/60-openocd.rules"); //$NON-NLS-1$ - File rulesFile = new File(pathToRules.toString()); - if (rulesFile.exists()) - { - Path source = Paths.get(pathToRules.toString()); - Path target = Paths.get("/etc/udev/rules.d/60-openocd.rules"); //$NON-NLS-1$ - console.println(String.format(Messages.InstallToolsHandler_OpenOCDRulesCopyPaths, source.toString(), - target.toString())); - - Display.getDefault().syncExec(new Runnable() - { - @Override - public void run() - { - try - { - if (target.toFile().exists()) - { - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell(), - SWT.ICON_WARNING | SWT.YES | SWT.NO); - messageBox.setText(Messages.InstallToolsHandler_OpenOCDRulesCopyWarning); - messageBox.setMessage(Messages.InstallToolsHandler_OpenOCDRulesCopyWarningMessage); - int response = messageBox.open(); - if (response == SWT.YES) - { - Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); - } - else - { - console.println(Messages.InstallToolsHandler_OpenOCDRulesNotCopied); - return; - } - } - else - { - Files.copy(source, target); - } - - console.println(Messages.InstallToolsHandler_OpenOCDRulesCopied); - } - catch (IOException e) - { - Logger.log(e); - errorConsoleStream.println(Messages.InstallToolsHandler_OpenOCDRulesCopyError); - } - } - }); - } - } - } - - private void setUpToolChainsAndTargets() - { - IStatus status = loadTargetsAvailableFromIdfInCurrentToolSet(); - if (status.getSeverity() == IStatus.ERROR) - { - Logger.log("Unable to get IDF targets from current toolset"); - return; - } - - List targets = extractTargets(status.getMessage()); - ESPToolChainManager espToolChainManager = new ESPToolChainManager(); - espToolChainManager.removeLaunchTargetsNotPresent(targets); - espToolChainManager.removeCmakeToolChains(); - espToolChainManager.removeStdToolChains(); - espToolChainManager.configureToolChain(targets); - } - - private void setEnvVarsInEclipse() - { - if (idfToolSet == null) - throw new RuntimeException("Tools Cannot be null"); - - IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); - idfEnvironmentVariables.removeAllEnvVariables(); - idfToolSet.getEnvVars().forEach((key, value) -> { - if (value != null) - idfEnvironmentVariables.addEnvVariable(key, value); - }); - String path = replacePathVariable(idfToolSet.getEnvVars().get(IDFEnvironmentVariables.PATH)); - - idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.IDF_PATH, idfToolSet.getIdfLocation()); - idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.PATH, path); - idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.PYTHON_EXE_PATH, - idfToolSet.getSystemPythonExecutablePath()); - - idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.IDF_COMPONENT_MANAGER, "1"); - // IDF_MAINTAINER=1 to be able to build with the clang toolchain - idfEnvironmentVariables.addEnvVariable(IDFEnvironmentVariables.IDF_MAINTAINER, "1"); - IDFUtil.updateEspressifPrefPageOpenocdPath(); - } -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsInstallationJob.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsInstallationJob.java deleted file mode 100644 index 988624c55..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsInstallationJob.java +++ /dev/null @@ -1,163 +0,0 @@ -/******************************************************************************* - * Copyright 2024 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.tools; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.cdt.cmake.core.ICMakeToolChainFile; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.ui.console.MessageConsoleStream; - -import com.espressif.idf.core.IDFConstants; -import com.espressif.idf.core.IDFCorePlugin; -import com.espressif.idf.core.IDFEnvironmentVariables; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.toolchain.ESPToolChainManager; -import com.espressif.idf.core.toolchain.ESPToolchain; -import com.espressif.idf.core.tools.vo.IDFToolSet; -import com.espressif.idf.ui.update.ExportIDFTools; -import com.espressif.idf.ui.update.Messages; - -/** - * Class to install the dependencies and any - * given tools for an idf with given {@link IDFToolSet} - * @author Ali Azam Rana - * - */ -public class ToolsInstallationJob extends ToolsJob -{ - public ToolsInstallationJob(String pythonExecutablePath, String gitExecutablePath, String idfPath) - { - super(Messages.InstallToolsHandler_InstallingToolsMsg, pythonExecutablePath, gitExecutablePath); - this.idfPath = idfPath; - this.idfToolSet.setIdfLocation(idfPath); - this.idfToolSet.setSystemGitExecutablePath(gitExecutablePath); - this.idfToolSet.setSystemPythonExecutablePath(pythonExecutablePath); - } - - @Override - protected IStatus run(IProgressMonitor monitor) - { - monitor.beginTask(Messages.InstallToolsHandler_ItWilltakeTimeMsg, 5); - monitor.worked(1); - Logger.log("" - ); - IStatus status = handleToolsInstall(); - if (status.getSeverity() == IStatus.ERROR) - { - return status; - } - - monitor.worked(1); - monitor.setTaskName(Messages.InstallToolsHandler_InstallingPythonMsg); - status = handleToolsInstallPython(console); - if (status.getSeverity() == IStatus.ERROR) - { - return status; - } - - monitor.worked(1); - - monitor.setTaskName(Messages.InstallToolsHandler_ExportingPathsMsg); - ExportIDFTools exportIDFTools = new ExportIDFTools(); - status = exportIDFTools.getToolsExportOutputFromGivenIdfPath(pythonExecutablePath, gitExecutablePath, console, - errorConsoleStream, idfPath); - if (status.getSeverity() == IStatus.ERROR) - { - return status; - } - - Logger.log(status.getMessage()); - processExportCmdOutput(status.getMessage()); - - monitor.worked(1); - - monitor.setTaskName(Messages.InstallToolsHandler_AutoConfigureToolchain); - ESPToolChainManager espToolChainManager = new ESPToolChainManager(); - String pathToLookForToolChains = idfToolSet.getEnvVars().get(IDFEnvironmentVariables.PATH); - String idfPath = idfToolSet.getEnvVars().get(IDFEnvironmentVariables.IDF_PATH); - try - { - List espToolChains = espToolChainManager - .getStdToolChains(Arrays.asList(pathToLookForToolChains.split(File.pathSeparator)), idfPath); - idfToolSet.setEspStdToolChains(espToolChains); - List cMakeToolChainFiles = espToolChainManager.getCmakeToolChains(idfPath); - idfToolSet.setEspCmakeToolChainFiles(cMakeToolChainFiles); - } - catch (CoreException e) - { - Logger.log(e); - logToConsole("Error Getting Toolchains", errorConsoleStream); - return IDFCorePlugin.errorStatus("Error Getting Toolchains", null); //$NON-NLS-1$ - } - - monitor.setTaskName("Loading Available Targets in IDF"); - - status = loadTargetsAvailableFromIdfInCurrentToolSet(); - if (status.getSeverity() == IStatus.ERROR) - { - return status; - } - - idfToolSet.setLaunchTargets(extractTargets(status.getMessage())); - - monitor.worked(1); - - monitor.setTaskName(Messages.InstallToolsHandler_InstallingWebscoketMsg); - handleWebSocketClientInstall(); - monitor.worked(1); - - console.println(Messages.InstallToolsHandler_ToolsCompleted); - - console.println("Writing to the configuration file"); - idfToolSet.setId(idfToolSet.hashCode()); - - toolSetConfigurationManager.export(idfToolSet); - - console.println(Messages.ToolsInstallationJobCompletedMessage); - return Status.OK_STATUS; - } - - private void logToConsole(String message, MessageConsoleStream stream) - { - try - { - stream.write(message); - } - catch (IOException e) - { - Logger.log(e); - } - } - - protected IStatus handleToolsInstall() - { - // idf_tools.py install all - List arguments = new ArrayList(); - arguments.add(IDFConstants.TOOLS_INSTALL_CMD); - arguments.add(IDFConstants.TOOLS_INSTALL_ALL_CMD); - - console.println(Messages.InstallToolsHandler_InstallingToolsMsg); - console.println(Messages.InstallToolsHandler_ItWilltakeTimeMsg); - return runCommand(arguments, console); - } - - protected IStatus handleToolsInstallPython(MessageConsoleStream console) - { - List arguments; - // idf_tools.py install-python-env - arguments = new ArrayList(); - arguments.add(IDFConstants.TOOLS_INSTALL_PYTHON_CMD); - return runCommand(arguments, console); - } - -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsJob.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsJob.java deleted file mode 100644 index 5fec36a23..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/ToolsJob.java +++ /dev/null @@ -1,565 +0,0 @@ -/******************************************************************************* - * Copyright 2024 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.tools; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.osgi.util.NLS; -import org.eclipse.ui.console.MessageConsoleStream; - -import com.espressif.idf.core.IDFConstants; -import com.espressif.idf.core.IDFCorePlugin; -import com.espressif.idf.core.IDFCorePreferenceConstants; -import com.espressif.idf.core.IDFEnvironmentVariables; -import com.espressif.idf.core.ProcessBuilderFactory; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.tools.ToolSetConfigurationManager; -import com.espressif.idf.core.tools.vo.IDFToolSet; -import com.espressif.idf.core.util.IDFUtil; -import com.espressif.idf.core.util.StringUtil; -import com.espressif.idf.ui.IDFConsole; -import com.espressif.idf.ui.InputStreamConsoleThread; -import com.espressif.idf.ui.UIPlugin; -import com.espressif.idf.ui.update.Messages; - -/** - * Parent class for all tools related activity - * any common methods must be added here - * The class was created to save - * code and split the operation of installation and activation in two - * @author Ali Azam Rana - * - */ -public abstract class ToolsJob extends Job -{ - - protected IDFConsole idfConsole; - protected MessageConsoleStream console; - protected MessageConsoleStream errorConsoleStream; - protected String pythonExecutablePath; - protected String gitExecutablePath; - protected IDFToolSet idfToolSet; - protected ToolSetConfigurationManager toolSetConfigurationManager; - protected String idfPath; - - public ToolsJob(String name, String pythonExecutablePath, String gitExecutablePath) - { - super(name); - this.pythonExecutablePath = pythonExecutablePath; - this.gitExecutablePath = gitExecutablePath; - idfToolSet = new IDFToolSet(); - toolSetConfigurationManager = new ToolSetConfigurationManager(); - activateIDFConsoleView(); - } - - protected void processExportCmdOutput(final String exportCmdOp) - { - // process export command output - final String[] exportEntries = exportCmdOp.split("\n"); //$NON-NLS-1$ - for (String entry : exportEntries) - { - entry = entry.replaceAll("\\r", ""); //$NON-NLS-1$ //$NON-NLS-2$ - if (entry.startsWith("Error")) - { - try - { - errorConsoleStream.write(entry); - } - catch (IOException e) - { - Logger.log(e); - } - } - String[] keyValue = entry.split("="); //$NON-NLS-1$ - if (keyValue.length == 2) // 0 - key, 1 - value - { - final String msg = MessageFormat.format("Key: {0} Value: {1}", keyValue[0], keyValue[1]); //$NON-NLS-1$ - Logger.log(msg); - String key = keyValue[0]; - String value = keyValue[1]; - if (idfToolSet.getEnvVars() == null) - { - idfToolSet.setEnvVars(new HashMap()); - } - - idfToolSet.getEnvVars().put(key, value); - } - - } - - idfToolSet.getEnvVars().put(IDFEnvironmentVariables.IDF_COMPONENT_MANAGER, "1"); //$NON-NLS-1$ - // IDF_MAINTAINER=1 to be able to build with the clang toolchain - idfToolSet.getEnvVars().put(IDFEnvironmentVariables.IDF_MAINTAINER, "1"); //$NON-NLS-1$ - if (!StringUtil.isEmpty(idfPath)) - { - idfToolSet.getEnvVars().put(IDFEnvironmentVariables.IDF_PATH, idfPath); - idfToolSet.setIdfLocation(idfPath); - } - - IStatus status = getIdfVersionFromIdfPy(); - String cmdOutput = status.getMessage(); - Pattern pattern = Pattern.compile("v(\\d+\\.\\d+\\.\\d+)"); //$NON-NLS-1$ - Matcher matcher = pattern.matcher(cmdOutput.toLowerCase()); - if (matcher.find()) - { - idfToolSet.setIdfVersion(matcher.group(1)); - } - else - { - idfToolSet.setIdfVersion(idfToolSet.getEnvVars().computeIfAbsent(IDFEnvironmentVariables.ESP_IDF_VERSION, k -> StringUtil.EMPTY)); - } - idfToolSet.getEnvVars().put(IDFEnvironmentVariables.ESP_IDF_VERSION, idfToolSet.getIdfVersion()); - - } - - protected String replacePathVariable(String value) - { - // Get system PATH - Map systemEnv = new HashMap<>(IDFUtil.getSystemEnv()); - String pathEntry = systemEnv.get("PATH"); //$NON-NLS-1$ - if (pathEntry == null) - { - pathEntry = systemEnv.get("Path"); // for Windows //$NON-NLS-1$ - if (pathEntry == null) // no idea - { - Logger.log(new Exception("No PATH found in the system environment variables")); //$NON-NLS-1$ - } - } - - if (!StringUtil.isEmpty(pathEntry)) - { - value = value.replace("$PATH", pathEntry); // macOS //$NON-NLS-1$ - value = value.replace("%PATH%", pathEntry); // Windows //$NON-NLS-1$ - } - return value; - } - - protected IStatus loadTargetsAvailableFromIdfInCurrentToolSet() - { - List arguments = new ArrayList(); - arguments.add(IDFConstants.IDF_LIST_TARGETS_CMD); - return runCommandIdfPyInIdfEnv(arguments, console); - } - - protected List extractTargets(String input) - { - List targets = new ArrayList(); - Pattern pattern = Pattern.compile("^esp32.*", Pattern.MULTILINE); - Matcher matcher = pattern.matcher(input); - while (matcher.find()) - { - targets.add(matcher.group()); - } - return targets; - } - - protected IStatus handleWebSocketClientInstall() - { - String websocketClient = "websocket-client"; //$NON-NLS-1$ - // pip install websocket-client - List arguments = new ArrayList(); - final String pythonEnvPath = pythonVirtualExecutablePath(idfToolSet); - if (pythonEnvPath == null || !new File(pythonEnvPath).exists()) - { - console.println(String.format("%s executable not found. Unable to run `%s -m pip install websocket-client`", //$NON-NLS-1$ - IDFConstants.PYTHON_CMD, IDFConstants.PYTHON_CMD)); - return IDFCorePlugin.errorStatus( - String.format("%s executable not found. Unable to run `%s -m pip install websocket-client`", //$NON-NLS-1$ - IDFConstants.PYTHON_CMD, IDFConstants.PYTHON_CMD), - null); - } - arguments.add(pythonEnvPath); - arguments.add("-m"); //$NON-NLS-1$ - arguments.add("pip"); //$NON-NLS-1$ - arguments.add("list"); //$NON-NLS-1$ - - ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); - - try - { - String cmdMsg = "Executing " + getCommandString(arguments); //$NON-NLS-1$ - if (console != null) - { - console.println(cmdMsg); - } - Logger.log(cmdMsg); - - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); - Logger.log(environment.toString()); - - IStatus status = processRunner.runInBackground(arguments, org.eclipse.core.runtime.Path.ROOT, environment); - if (status == null) - { - Logger.log(IDFCorePlugin.getPlugin(), - IDFCorePlugin.errorStatus("Unable to get the process status.", null)); //$NON-NLS-1$ - if (errorConsoleStream != null) - { - errorConsoleStream.println("Unable to get the process status."); - } - return IDFCorePlugin.errorStatus("Unable to get the process status.", null); //$NON-NLS-1$ - } - - String cmdOutput = status.getMessage(); - if (cmdOutput.contains(websocketClient)) - { - return IDFCorePlugin.okStatus("websocket-client already installed", null); //$NON-NLS-1$ - } - - // websocket client not installed so installing it now. - arguments.remove(arguments.size() - 1); - arguments.add("install"); //$NON-NLS-1$ - arguments.add(websocketClient); - - status = processRunner.runInBackground(arguments, org.eclipse.core.runtime.Path.ROOT, environment); - if (status == null) - { - Logger.log(IDFCorePlugin.getPlugin(), - IDFCorePlugin.errorStatus("Unable to get the process status.", null)); //$NON-NLS-1$ - if (errorConsoleStream != null) - { - errorConsoleStream.println("Unable to get the process status."); - } - return IDFCorePlugin.errorStatus("Unable to get the process status.", null); //$NON-NLS-1$ - } - - if (console != null) - { - console.println(status.getMessage()); - } - - return status; - } - catch (Exception e1) - { - Logger.log(IDFCorePlugin.getPlugin(), e1); - if (errorConsoleStream != null) - { - errorConsoleStream.println(e1.getLocalizedMessage()); - } - return IDFCorePlugin.errorStatus(e1.getLocalizedMessage(), e1); // $NON-NLS-1$; - } - } - - protected String pythonVirtualExecutablePath(IDFToolSet idfToolSet) - { - String pythonVirtualPath = idfToolSet.getEnvVars().get(IDFEnvironmentVariables.IDF_PYTHON_ENV_PATH); - StringBuilder pythonVirtualExePath = new StringBuilder(); - pythonVirtualExePath.append(pythonVirtualPath); - pythonVirtualExePath.append("/"); //$NON-NLS-1$ - if (Platform.getOS().equals(Platform.OS_WIN32)) - { - pythonVirtualExePath.append("Scripts"); //$NON-NLS-1$ - pythonVirtualExePath.append("/"); //$NON-NLS-1$ - pythonVirtualExePath.append("python.exe"); //$NON-NLS-1$ - } - else - { - pythonVirtualExePath.append("bin"); //$NON-NLS-1$ - pythonVirtualExePath.append("/"); //$NON-NLS-1$ - pythonVirtualExePath.append("python"); //$NON-NLS-1$ - } - - - return pythonVirtualExePath.toString(); - } - - - private String getCommandString(List arguments) - { - StringBuilder builder = new StringBuilder(); - arguments.forEach(entry -> builder.append(entry + " ")); //$NON-NLS-1$ - - return builder.toString().trim(); - } - - protected void activateIDFConsoleView() - { - idfConsole = new IDFConsole(); - console = idfConsole.getConsoleStream(Messages.IDFToolsHandler_ToolsManagerConsole, null, false, true); - errorConsoleStream = idfConsole.getConsoleStream(Messages.IDFToolsHandler_ToolsManagerConsole, null, true, - true); - } - - protected IStatus getIdfVersionFromIdfPy() - { - List arguments = new ArrayList(); - arguments.add("--version"); - return runCommandIdfPyInIdfEnv(arguments, console); - } - - /** - * Append the git directory to the existing CDT build environment PATH variable - * - * @param path CDT build environment PATH - * @param gitExecutablePath - * @return PATH value with git appended - */ - protected String appendGitToPath(String path, String gitExecutablePath) - { - IPath gitPath = new Path(gitExecutablePath); - if (!gitPath.toFile().exists()) - { - Logger.log(NLS.bind("{0} doesn't exist", gitExecutablePath)); //$NON-NLS-1$ - return path; - } - - String gitDir = gitPath.removeLastSegments(1).toOSString(); // ../bin/git - if (!StringUtil.isEmpty(path) && !path.contains(gitDir)) // Git not found on the CDT build PATH environment - { - return path.concat(";").concat(gitDir); // append git path //$NON-NLS-1$ - } - return path; - } - - protected IStatus runCommandIdfPyInIdfEnv(List arguments, MessageConsoleStream console) - { - ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); - StringBuilder output = new StringBuilder(); - int waitCount = 10; - try - { - arguments.add(0, pythonVirtualExecutablePath(idfToolSet)); - arguments.add(1, IDFUtil.getIDFPythonScriptFile(idfToolSet.getIdfLocation()).getAbsolutePath()); - - String cmdMsg = Messages.AbstractToolsHandler_ExecutingMsg + " " + getCommandString(arguments); //$NON-NLS-1$ - console.println(cmdMsg); - Logger.log(cmdMsg); - - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); - Logger.log(environment.toString()); - environment.put("PYTHONUNBUFFERED", "1"); //$NON-NLS-1$ //$NON-NLS-2$ - loadIdfPathWithSystemPath(environment); - environment.remove(IDFEnvironmentVariables.IDF_PYTHON_ENV_PATH); - environment.remove(IDFEnvironmentVariables.ESP_IDF_VERSION); - environment.remove(IDFEnvironmentVariables.IDF_PATH); - environment.remove(IDFEnvironmentVariables.OPENOCD_SCRIPTS); - - if (gitExecutablePath != null) - { - addPathToEnvironmentPath(environment, gitExecutablePath); - } - Process process = processRunner.run(arguments, org.eclipse.core.runtime.Path.ROOT, environment); - BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); - String line; - while ((line = reader.readLine()) != null) - { - output.append(line).append(System.lineSeparator()); - } - - while (process.isAlive() && waitCount > 0) - { - try - { - Thread.sleep(300); - } - catch (InterruptedException e) - { - Logger.log(e); - } - waitCount--; - } - - if (waitCount == 0) - { - console.println("Process possibly stuck"); - Logger.log("Process possibly stuck"); - return Status.CANCEL_STATUS; - } - - IStatus status = new Status(process.exitValue() == 0 ? IStatus.OK : IStatus.ERROR, UIPlugin.PLUGIN_ID, - process.exitValue(), output.toString(), null); - if (status.getSeverity() == IStatus.ERROR) - { - errorConsoleStream.print( - status.getException() != null ? status.getException().getMessage() : status.getMessage()); - } - console.println(status.getMessage()); - console.println(); - - return status; - } - catch (Exception e1) - { - Logger.log(IDFCorePlugin.getPlugin(), e1); - return IDFCorePlugin.errorStatus(e1.getMessage(), e1); - } - } - - private void addPathToEnvironmentPath(Map environment, String gitExecutablePath) - { - IPath gitPath = new org.eclipse.core.runtime.Path(gitExecutablePath); - if (gitPath.toFile().exists()) - { - String gitDir = gitPath.removeLastSegments(1).toOSString(); - String path1 = environment.get("PATH"); //$NON-NLS-1$ - String path2 = environment.get("Path"); //$NON-NLS-1$ - if (!StringUtil.isEmpty(path1) && !path1.contains(gitDir)) // Git not found on the PATH environment - { - path1 = gitDir.concat(";").concat(path1); //$NON-NLS-1$ - environment.put("PATH", path1); //$NON-NLS-1$ - } - else if (!StringUtil.isEmpty(path2) && !path2.contains(gitDir)) // Git not found on the Path environment - { - path2 = gitDir.concat(";").concat(path2); //$NON-NLS-1$ - environment.put("Path", path2); //$NON-NLS-1$ - } - } - } - - private void loadIdfPathWithSystemPath(Map systemEnv) - { - String idfExportPath = idfToolSet.getEnvVars().get(IDFEnvironmentVariables.PATH); - String pathVar = "PATH"; // for Windows //$NON-NLS-1$ - String pathEntry = systemEnv.get(pathVar); // $NON-NLS-1$ - if (pathEntry == null) - { - pathVar = "Path"; //$NON-NLS-1$ - pathEntry = systemEnv.get(pathVar); - if (pathEntry == null) // no idea - { - Logger.log(new Exception("No PATH found in the system environment variables")); //$NON-NLS-1$ - } - } - - if (!StringUtil.isEmpty(pathEntry)) - { - idfExportPath = idfExportPath.replace("$PATH", pathEntry); // macOS //$NON-NLS-1$ - idfExportPath = idfExportPath.replace("%PATH%", pathEntry); // Windows //$NON-NLS-1$ - } - systemEnv.put(pathVar, idfExportPath); - for (Entry entry : idfToolSet.getEnvVars().entrySet()) - { - if (entry.getKey().equals(IDFEnvironmentVariables.PATH)) - continue; - - systemEnv.put(entry.getKey(), entry.getValue()); - } - } - - protected IStatus runCommand(List arguments, MessageConsoleStream console) - { - ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); - - try - { - // insert python.sh/exe path and idf_tools.py - arguments.add(0, pythonExecutablePath); - arguments.add(1, IDFUtil.getIDFToolsScriptFile(idfToolSet.getIdfLocation()).getAbsolutePath()); - - String cmdMsg = Messages.AbstractToolsHandler_ExecutingMsg + " " + getCommandString(arguments); //$NON-NLS-1$ - console.println(cmdMsg); - Logger.log(cmdMsg); - - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); - Logger.log(environment.toString()); - environment.put("PYTHONUNBUFFERED", "1"); //$NON-NLS-1$ //$NON-NLS-2$ - environment.put("IDF_GITHUB_ASSETS", //$NON-NLS-1$ - Platform.getPreferencesService().getString(IDFCorePlugin.PLUGIN_ID, - IDFCorePreferenceConstants.IDF_GITHUB_ASSETS, - IDFCorePreferenceConstants.IDF_GITHUB_ASSETS_DEFAULT_GLOBAL, null)); - - environment.put("PIP_EXTRA_INDEX_URL", //$NON-NLS-1$ - Platform.getPreferencesService().getString(IDFCorePlugin.PLUGIN_ID, - IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL, - IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL_DEFAULT_GLOBAL, null)); - - if (gitExecutablePath != null) - { - addPathToEnvironmentPath(environment, gitExecutablePath); - } - Process process = processRunner.run(arguments, org.eclipse.core.runtime.Path.ROOT, environment); - IStatus status = processData(process); - console.println(); - - return IDFCorePlugin.okStatus(status.getMessage(), null); - } - catch (Exception e1) - { - Logger.log(IDFCorePlugin.getPlugin(), e1); - return IDFCorePlugin.errorStatus(e1.getMessage(), e1); - } - } - - private IStatus processData(Process process) - { - - InputStream inputStream = process.getInputStream(); - InputStream errorStream = process.getErrorStream(); - - InputStreamConsoleThread readerThread = null; - InputStreamConsoleThread errorThread = null; - try - { - - readerThread = new InputStreamConsoleThread(inputStream, console); - errorThread = new InputStreamConsoleThread(errorStream, console); - - readerThread.start(); - errorThread.start(); - - // This will wait till the process is done. - int exitValue = process.waitFor(); - - readerThread.interrupt(); - errorThread.interrupt(); - readerThread.join(); - errorThread.join(); - - if (exitValue == 0) - { - return Status.OK_STATUS; - } - - return new Status(IStatus.ERROR, IDFCorePlugin.PLUGIN_ID, "Error"); //$NON-NLS-1$ - - } - catch (InterruptedException e) - { - try - { - if (readerThread != null) - { - readerThread.interrupt(); - } - if (errorThread != null) - { - errorThread.interrupt(); - } - if (readerThread != null) - { - readerThread.join(); - } - if (errorThread != null) - { - errorThread.join(); - } - } - catch (InterruptedException e1) - { - // ignore - } - return new Status(IStatus.ERROR, IDFCorePlugin.PLUGIN_ID, e.getMessage(), e); - } - } - -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/ESPIDFManagerEditor.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/ESPIDFManagerEditor.java index d727d615c..a004708fe 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/ESPIDFManagerEditor.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/ESPIDFManagerEditor.java @@ -53,8 +53,13 @@ public boolean isSaveAsAllowed() @Override public void createPartControl(Composite parent) { - ESPIDFMainTablePage espidfMainTablePage = ESPIDFMainTablePage.getInstance(); + ESPIDFMainTablePage espidfMainTablePage = ESPIDFMainTablePage + .getInstance(((EimEditorInput) getEditorInput()).getEimJson()); espidfMainTablePage.createPage(parent); + if (((EimEditorInput) getEditorInput()).isFirstStartup()) + { + espidfMainTablePage.setupInitialEspIdf(); + } } diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/EimEditorInput.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/EimEditorInput.java new file mode 100644 index 000000000..8b65e7539 --- /dev/null +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/EimEditorInput.java @@ -0,0 +1,93 @@ +package com.espressif.idf.ui.tools.manager; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IPersistableElement; + +import com.espressif.idf.core.tools.vo.EimJson; + +public class EimEditorInput implements IEditorInput +{ + private EimJson eimJson; + private boolean firstStartup; + private String FILE_NAME = "idf_eim.json"; //$NON-NLS-1$ + + public EimEditorInput(EimJson eimJson) + { + this.eimJson = eimJson; + } + + public EimJson getEimJson() + { + return eimJson; + } + + @Override + public T getAdapter(Class adapter) + { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean exists() + { + return true; + } + + @Override + public ImageDescriptor getImageDescriptor() + { + return null; + } + + @Override + public String getName() + { + return null; + } + + @Override + public IPersistableElement getPersistable() + { + return null; + } + + @Override + public String getToolTipText() + { + return null; + } + + public boolean isFirstStartup() + { + return firstStartup; + } + + public void setFirstStartup(boolean firstStartup) + { + this.firstStartup = firstStartup; + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) + { + return true; + } + if (obj == null || getClass() != obj.getClass()) + { + return false; + } + EimEditorInput that = (EimEditorInput) obj; + return FILE_NAME.equals(that.FILE_NAME); + } + + @Override + public int hashCode() + { + return FILE_NAME.hashCode(); + } + +} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/pages/ESPIDFMainTablePage.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/pages/ESPIDFMainTablePage.java index 76df9e544..3e27a4c43 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/pages/ESPIDFMainTablePage.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/manager/pages/ESPIDFMainTablePage.java @@ -4,9 +4,10 @@ *******************************************************************************/ package com.espressif.idf.ui.tools.manager.pages; -import java.text.MessageFormat; +import java.io.IOException; import java.util.List; +import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; @@ -16,7 +17,6 @@ import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerComparator; -import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.SelectionAdapter; @@ -30,18 +30,23 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.MessageBox; +import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; +import org.eclipse.ui.console.MessageConsoleStream; +import org.osgi.service.prefs.Preferences; -import com.espressif.idf.core.tools.ToolSetConfigurationManager; -import com.espressif.idf.core.tools.vo.IDFToolSet; -import com.espressif.idf.core.util.IDFUtil; +import com.espressif.idf.core.logging.Logger; +import com.espressif.idf.core.tools.EimConstants; +import com.espressif.idf.core.tools.EimIdfConfiguratinParser; +import com.espressif.idf.core.tools.SetupToolsInIde; +import com.espressif.idf.core.tools.util.ToolsUtility; +import com.espressif.idf.core.tools.vo.EimJson; +import com.espressif.idf.core.tools.vo.IdfInstalled; +import com.espressif.idf.ui.IDFConsole; import com.espressif.idf.ui.UIPlugin; -import com.espressif.idf.ui.install.IDFNewToolsWizard; import com.espressif.idf.ui.tools.Messages; -import com.espressif.idf.ui.tools.ToolsActivationJob; -import com.espressif.idf.ui.tools.ToolsActivationJobListener; +import com.espressif.idf.ui.tools.SetupToolsJobListener; /** * Main UI class for all listing and interacting with the tools @@ -52,18 +57,19 @@ public class ESPIDFMainTablePage { private Composite container; private TableViewer tableViewer; - private ToolSetConfigurationManager toolSetConfigurationManager; private ColumnViewerComparator comparator; private TableViewerColumn versionColumn; private TableViewerColumn locationColumn; private TableViewerColumn activateColumn; private TableViewerColumn removeColumn; + private TableViewerColumn nameColumn; + private TableColumnLayout tableColumnLayout; private Composite tableComposite; - private List idfToolSets; - private Button removeAllButton; + private List idfInstalledList; + private static EimJson eimJson; + private EimIdfConfiguratinParser eimIdfConfiguratinParser; - private static final String REMOVE_ICON = "icons/tools/delete.png"; //$NON-NLS-1$ private static final String RELOAD_ICON = "icons/tools/reload.png"; //$NON-NLS-1$ private static final String IDF_TOOL_SET_BTN_KEY = "IDFToolSet"; //$NON-NLS-1$ @@ -71,29 +77,67 @@ public class ESPIDFMainTablePage private ESPIDFMainTablePage() { + eimIdfConfiguratinParser = new EimIdfConfiguratinParser(); } - public static ESPIDFMainTablePage getInstance() + public static ESPIDFMainTablePage getInstance(EimJson eimJson) { if (espidfMainTablePage == null) { espidfMainTablePage = new ESPIDFMainTablePage(); } + ESPIDFMainTablePage.eimJson = eimJson; return espidfMainTablePage; } public Composite createPage(Composite composite) { - toolSetConfigurationManager = new ToolSetConfigurationManager(); - idfToolSets = toolSetConfigurationManager.getIdfToolSets(true); + idfInstalledList = eimJson != null ? eimJson.getIdfInstalled() : null; container = new Composite(composite, SWT.NONE); final int numColumns = 2; GridLayout gridLayout = new GridLayout(numColumns, false); container.setLayout(gridLayout); + createGuideLink(container); createIdfTable(container); return container; } + + private void createGuideLink(Composite composite) + { + Link guideLink = new Link(composite, SWT.WRAP); + guideLink.setText(Messages.IDFGuideLinkLabel_Text); + guideLink.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1)); + guideLink.addListener(SWT.Selection, e -> { + try + { + java.awt.Desktop.getDesktop().browse(new java.net.URI( + "https://dl.espressif.com/dl/esp-idf/support-periods.svg")); + } + catch (Exception ex) + { + Logger.log(ex); + } + }); + } + + public void setupInitialEspIdf() + { + if (idfInstalledList != null && idfInstalledList.size() == 1) + { + // activate the only available esp-idf first check if its not already active + Preferences scopedPreferenceStore = InstanceScope.INSTANCE.getNode(UIPlugin.PLUGIN_ID); + if (!scopedPreferenceStore.getBoolean(EimConstants.INSTALL_TOOLS_FLAG, false)) + { + SetupToolsInIde setupToolsInIde = new SetupToolsInIde(idfInstalledList.get(0), eimJson, + getConsoleStream(true), getConsoleStream(false)); + SetupToolsJobListener toolsActivationJobListener = new SetupToolsJobListener(ESPIDFMainTablePage.this, + setupToolsInIde); + setupToolsInIde.addJobChangeListener(toolsActivationJobListener); + setupToolsInIde.schedule(); + } + } + } public void refreshEditorUI() { @@ -126,23 +170,21 @@ public void refreshEditorUI() item.setData(EDITOR_KEY_LAST, null); } } - toolSetConfigurationManager.setReload(true); - idfToolSets = toolSetConfigurationManager.getIdfToolSets(true); + try + { + eimJson = eimIdfConfiguratinParser.getEimJson(true); + } + catch (IOException e) + { + Logger.log(e); + } + + idfInstalledList = eimJson.getIdfInstalled(); setupColumns(); - tableViewer.setInput(idfToolSets); + tableViewer.setInput(idfInstalledList); tableViewer.getControl().requestLayout(); tableViewer.refresh(); container.redraw(); - toolSetConfigurationManager.setReload(false); - - if (idfToolSets == null || idfToolSets.isEmpty()) - { - removeAllButton.setEnabled(false); - } - else - { - removeAllButton.setEnabled(true); - } } private Composite createIdfTable(Composite parent) @@ -173,7 +215,7 @@ private Composite createIdfTable(Composite parent) e.height = 30; }); - tableViewer.setInput(toolSetConfigurationManager.getIdfToolSets(true)); + tableViewer.setInput(idfInstalledList); table.layout(); // Composite for the "Add" button Composite buttonComposite = new Composite(idfToolsGroup, SWT.NONE); @@ -181,63 +223,6 @@ private Composite createIdfTable(Composite parent) buttonCompositeGridData.verticalAlignment = SWT.TOP; // Aligns the button composite at the top buttonComposite.setLayoutData(buttonCompositeGridData); buttonComposite.setLayout(new GridLayout(1, true)); - - // Creating the "Add" button - Button addButton = new Button(buttonComposite, SWT.PUSH); - addButton.setText(Messages.EspIdfManagerAddToolsBtn); - GridData addButtonGridData = new GridData(SWT.FILL, SWT.CENTER, true, false); - addButton.setLayoutData(addButtonGridData); - addButton.addSelectionListener(new SelectionAdapter() - { - @Override - public void widgetSelected(SelectionEvent e) - { - IDFNewToolsWizard wizard = new IDFNewToolsWizard(ESPIDFMainTablePage.this); - wizard.setWindowTitle(Messages.IDFDownloadHandler_ESPIDFConfiguration); - WizardDialog wizDialog = new WizardDialog(container.getShell(), wizard); - wizDialog.create(); - - wizDialog.setTitle(Messages.IDFDownloadHandler_DownloadPage_Title); - wizDialog.setMessage(Messages.IDFDownloadHandler_DownloadPageMsg); - wizDialog.getShell().setSize(Math.max(850, wizDialog.getShell().getSize().x), 550); - - wizDialog.open(); - } - }); - - removeAllButton = new Button(buttonComposite, SWT.PUSH); - removeAllButton.setText(Messages.EspIdfManagerRemoveAllBtn); - removeAllButton.addSelectionListener(new SelectionAdapter() - { - @Override - public void widgetSelected(SelectionEvent e) - { - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell(), - SWT.ICON_WARNING | SWT.YES | SWT.NO); - messageBox.setMessage(Messages.EspIdfManagerMessageBoxDeleteAllConfirmMessage); - messageBox.setText(Messages.EspIdfManagerMessageBoxDeleteAllConfirmMessageTitle); - int response = messageBox.open(); - if (response == SWT.YES) - { - for(IDFToolSet idfToolSet : idfToolSets) - { - toolSetConfigurationManager.delete(idfToolSet); - } - refreshEditorUI(); - } - } - }); - - GridData removeAllButtonGridData = new GridData(SWT.FILL, SWT.CENTER, true, false); - removeAllButton.setLayoutData(removeAllButtonGridData); - if (idfToolSets == null || idfToolSets.isEmpty()) - { - removeAllButton.setEnabled(false); - } - else - { - removeAllButton.setEnabled(true); - } return idfToolsGroup; } @@ -263,6 +248,11 @@ private void disposeColumns() { removeColumn.getColumn().dispose(); } + + if (nameColumn != null && nameColumn.getColumn() != null) + { + nameColumn.getColumn().dispose(); + } } private void setupColumns() @@ -280,6 +270,12 @@ private void setupColumns() versionColumn.setLabelProvider(new IdfManagerTableColumnLabelProvider()); setComparatorForCols(versionColumn, colIndex++); tableColumnLayout.setColumnData(versionColumn.getColumn(), new ColumnWeightData(3, 50, true)); + + nameColumn = new TableViewerColumn(tableViewer, SWT.NONE); + nameColumn.getColumn().setText(Messages.EspIdfManagerNameCol); + nameColumn.setLabelProvider(new IdfManagerTableColumnLabelProvider()); + setComparatorForCols(nameColumn, colIndex++); + tableColumnLayout.setColumnData(nameColumn.getColumn(), new ColumnWeightData(3, 50, true)); locationColumn = new TableViewerColumn(tableViewer, SWT.NONE); locationColumn.getColumn().setText(Messages.EspIdfManagerLocationCol); @@ -318,19 +314,6 @@ public void widgetSelected(SelectionEvent e) } - private void performDeleteOperation(IDFToolSet idfToolSet) - { - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell(), - SWT.ICON_WARNING | SWT.YES | SWT.NO); - messageBox.setMessage(MessageFormat.format(Messages.EspIdfManagerMessageBoxDeleteConfirmMessage, idfToolSet.getIdfVersion())); - messageBox.setText(Messages.EspIdfManagerMessageBoxDeleteConfirmMessageTitle); - int response = messageBox.open(); - if (response == SWT.YES) - { - toolSetConfigurationManager.delete(idfToolSet); - } - } - private class IdfManagerTableColumnLabelProvider extends ColumnLabelProvider { private Color activeBackgroundColor; @@ -344,10 +327,10 @@ private IdfManagerTableColumnLabelProvider() @Override public Color getBackground(Object element) { - if (element instanceof IDFToolSet) + if (element instanceof IdfInstalled) { - IDFToolSet idfToolSet = (IDFToolSet) element; - if (idfToolSet.isActive()) + IdfInstalled idfInstalled = (IdfInstalled) element; + if (ToolsUtility.isIdfInstalledActive(idfInstalled)) { // Return the green color for active rows return activeBackgroundColor; @@ -384,25 +367,34 @@ else if (isLastCol) private void updateDataIntoCells(ViewerCell cell) { - if ((!(cell.getElement() instanceof IDFToolSet)) && cell.getElement() == null) + if ((!(cell.getElement() instanceof IdfInstalled)) && cell.getElement() == null) return; - IDFToolSet idfToolSet = (IDFToolSet) cell.getElement(); + IdfInstalled idfInstalled = (IdfInstalled) cell.getElement(); switch (cell.getColumnIndex()) { case 0: break; case 1: - cell.setText(idfToolSet.getIdfVersion()); + cell.setText(getIdfVersion(idfInstalled)); break; case 2: - cell.setText(idfToolSet.getIdfLocation()); + cell.setText(idfInstalled.getName()); break; case 3: + cell.setText(idfInstalled.getPath()); + break; + case 4: break; } } + private String getIdfVersion(IdfInstalled idfInstalled) + { + String version = ToolsUtility.getIdfVersion(idfInstalled, eimJson.getGitPath()); + return version; + } + private void createButtonsForFirstCol(ViewerCell cell) { TableItem item = (TableItem) cell.getItem(); @@ -417,18 +409,17 @@ private void createButtonsForFirstCol(ViewerCell cell) Composite buttonComposite = new Composite(tableViewer.getTable(), SWT.NONE); buttonComposite.setLayout(new FillLayout()); item.setData(EDITOR_KEY, editor); - IDFToolSet idfToolSet = (IDFToolSet) cell.getElement(); + IdfInstalled idfInstalled = (IdfInstalled) cell.getElement(); Button setActiveButton = new Button(buttonComposite, SWT.RADIO); - setActiveButton.setSelection(idfToolSet.isActive()); - setActiveButton.setData(IDF_TOOL_SET_BTN_KEY, idfToolSet); + setActiveButton.setSelection(ToolsUtility.isIdfInstalledActive(idfInstalled)); + setActiveButton.setData(IDF_TOOL_SET_BTN_KEY, idfInstalled); setActiveButton.addListener(SWT.Selection, e -> { Button btn = (Button) e.widget; - ToolsActivationJob toolsActivationJob = new ToolsActivationJob((IDFToolSet) btn.getData(IDF_TOOL_SET_BTN_KEY), - null, null); - ToolsActivationJobListener toolsActivationJobListener = new ToolsActivationJobListener( - ESPIDFMainTablePage.this); - toolsActivationJob.addJobChangeListener(toolsActivationJobListener); - toolsActivationJob.schedule(); + SetupToolsInIde setupToolsInIde = new SetupToolsInIde(idfInstalled, eimJson, getConsoleStream(true), getConsoleStream(false)); + SetupToolsJobListener toolsActivationJobListener = new SetupToolsJobListener( + ESPIDFMainTablePage.this, setupToolsInIde); + setupToolsInIde.addJobChangeListener(toolsActivationJobListener); + setupToolsInIde.schedule(); btn.setEnabled(false); }); @@ -452,24 +443,25 @@ private void createButtonsForLastCol(ViewerCell cell) buttonComposite.setLayout(fillLayout); buttonComposite.redraw(); item.setData(EDITOR_KEY, editor); - IDFToolSet idfToolSet = (IDFToolSet) cell.getElement(); + IdfInstalled idfInstalled = (IdfInstalled) cell.getElement(); int buttonHeight = Math.min(cellBounds.height - 6, 30); - if (idfToolSet.isActive()) + if (ToolsUtility.isIdfInstalledActive(idfInstalled)) { Button reloadButton = new Button(buttonComposite, SWT.PUSH | SWT.FLAT); reloadButton.pack(); - reloadButton.setData(IDF_TOOL_SET_BTN_KEY, idfToolSet); + reloadButton.setData(IDF_TOOL_SET_BTN_KEY, idfInstalled); reloadButton.setImage(UIPlugin.getImage(RELOAD_ICON)); reloadButton.setToolTipText(Messages.EspIdfManagerReloadBtnToolTip); reloadButton.addListener(SWT.Selection, e -> { Button btn = (Button) e.widget; - IDFToolSet selectedToolSet = (IDFToolSet) btn.getData(IDF_TOOL_SET_BTN_KEY); - ToolsActivationJob toolsActivationJob = new ToolsActivationJob(selectedToolSet, IDFUtil.getPythonExecutable(), IDFUtil.getGitExecutablePathFromSystem()); - ToolsActivationJobListener toolsActivationJobListener = new ToolsActivationJobListener(ESPIDFMainTablePage.this); - toolsActivationJob.addJobChangeListener(toolsActivationJobListener); - toolsActivationJob.schedule(); + IdfInstalled selectedToolSet = (IdfInstalled) btn.getData(IDF_TOOL_SET_BTN_KEY); + SetupToolsInIde setupToolsInIde = new SetupToolsInIde(selectedToolSet, eimJson, getConsoleStream(true), getConsoleStream(false)); + SetupToolsJobListener toolsActivationJobListener = new SetupToolsJobListener( + ESPIDFMainTablePage.this, setupToolsInIde); + setupToolsInIde.addJobChangeListener(toolsActivationJobListener); + setupToolsInIde.schedule(); }); reloadButton.setSize(cellBounds.width, buttonHeight); @@ -477,26 +469,10 @@ private void createButtonsForLastCol(ViewerCell cell) reloadButton.redraw(); } - Button removeButton = new Button(buttonComposite, SWT.PUSH | SWT.FLAT); - removeButton.pack(); - removeButton.setData(IDF_TOOL_SET_BTN_KEY, idfToolSet); - removeButton.setImage(UIPlugin.getImage(REMOVE_ICON)); - removeButton.setToolTipText(Messages.EspIdfManagerDeleteBtnToolTip); - removeButton.addListener(SWT.Selection, e -> { - Button btn = (Button) e.widget; - IDFToolSet selectedToolSet = (IDFToolSet) btn.getData(IDF_TOOL_SET_BTN_KEY); - performDeleteOperation(selectedToolSet); - refreshEditorUI(); - }); - removeButton.setSize(cellBounds.width, buttonHeight); - removeButton.redraw(); - editor.grabHorizontal = true; editor.grabVertical = true; editor.horizontalAlignment = SWT.CENTER; editor.verticalAlignment = SWT.CENTER; - editor.minimumHeight = removeButton.getSize().y; - editor.minimumWidth = removeButton.getSize().x; editor.setEditor(buttonComposite, item, cell.getColumnIndex()); buttonComposite.layout(true, true); buttonComposite.redraw(); @@ -514,6 +490,12 @@ public void dispose() super.dispose(); } } + + private MessageConsoleStream getConsoleStream(boolean errorStream) + { + IDFConsole idfConsole = new IDFConsole(); + return idfConsole.getConsoleStream(Messages.IDFToolsHandler_ToolsManagerConsole, null, errorStream, true); + } private class ColumnViewerComparator extends ViewerComparator { @@ -545,20 +527,20 @@ public void setColumn(int column) @Override public int compare(Viewer viewer, Object e1, Object e2) { - IDFToolSet p1 = (IDFToolSet) e1; - IDFToolSet p2 = (IDFToolSet) e2; + IdfInstalled p1 = (IdfInstalled) e1; + IdfInstalled p2 = (IdfInstalled) e2; int rc = 0; switch (propertyIndex) { case 0: - rc = p1.getIdfVersion().compareTo(p2.getIdfVersion()); + rc = p1.getName().compareTo(p2.getName()); break; case 1: - rc = p1.getIdfLocation().compareTo(p2.getIdfLocation()); + rc = p1.getPath().compareTo(p2.getPath()); break; case 2: - Boolean p1State = p1.isActive(); - Boolean p2State = p2.isActive(); + Boolean p1State = ToolsUtility.isIdfInstalledActive(p1); + Boolean p2State = ToolsUtility.isIdfInstalledActive(p2); rc = p1State.compareTo(p2State); break; default: diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/messages.properties b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/messages.properties index 8d40d45dd..6a42ecb88 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/messages.properties +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/messages.properties @@ -1,132 +1,12 @@ -#Eclipse modern messages class -#Wed May 18 13:39:42 CEST 2022 -SizeDescriptionText=Size: -RemoveToolMessageBox=Do you want to delete the selected tools? -RemoveToolMessageBoxFinish=Do you want to continue or finish the changes? -SystemPathMessage=System Path: -ToolsTreeSizeCol=Size (MB) -FilterTargets=Filter Chips -UrlDescriptionText=URL: -ToolsTreeNameCol=Name -Available=Available -InstallPreRquisitePage=Install Prerequisites -ManageToolsInstallationDescription=Here you can install tools available with the selected IDF version -InstallEspIdfPage_lblEspidfPath_text=ESP-IDF Path: -ManageToolsInstallation=Tools Installation -InstallToolsText=Install Tools -InstallEspIdfPage_lblEspidfVersion_text=ESP-IDF Version: -InstallEspIdfPage_btnDownload_text=Download -Warning=Warning -ExtractionTextMessage=Extracting file: -PreviousToolMessage=Previous Tool Path: -DeselectAllButton=Deselect All -DeselectAllButtonToolTip=Deselect all tools -GitLabel=Git: -DirectorySelectionDialog_IDFDirLabel=ESP-IDF Directory: -ToolsManagerShellHeading=Manage Tools Installation -ToolsManagerWizard=Tools Installation Wizard -InstallEspIdfPage_Existing=Existing -InstallEspIdfPageDescription=Download ESP-IDF or select an existing version -ToolsTreeStatusCol=Status -SupportedTargetsDescriptionText=Supported Targets: -DownloadFileText=Downloading File: -SelectRecommended=Select Recommended -SelectRecommendedToolTip=Selects recommended tools only -DeleteToolsText=Delete Tools -DeleteToolsTextToolTip=Delete selected tools. Make sure not to delete the recommended tools for proper working -FileSelectionDialogTitle=Select tool executable file -DirectorySelectionDialog_SelectIDFDirMessage=Select ESP-IDF Directory: -FilterLabel=Type below to filter -Installed=Installed -DescriptionText=Description -ShowAvailableVersionsOnly=Show Available Versions Only -UpdateToolPathMessage=Updated Tool Path: -ManageToolsInstallationShell_mntmNewItem_text=New Item -ExtractionCompletedMessage=Extraction Completed -InstallEspIdfPage_btnNew_text=New -InstallEspIdfPage=Install ESP-IDF -ManageToolsInstallationShell_tltmCheckItem_text=Check Item -InstallEspIdfPage_lblDownloadDirectory_text=Download Directory: -NotInstalled=Not Installed -RemoveToolMessageBoxTitle=Confirmation -UpdatingPathMessage=Updating PATH -PythonLabel=Python: -InstallToolsPreReqPageDescription=Set path for the required tools here -DownloadProgressText=Download Progress: -InstallPreRquisitePage_lblLog_text=Log -BrowseButton=Browse -SelectPythonVersion=Select Python Version -SelectAllButton=Select All -SelectAllButtonToolTip=Select all tools -RemovedPathMessage=Removed Path: -InstallingToolMessage=Installing Tool: -SelectDownloadDir=Select the directory to download ESP-IDF Tools -GitCloningJobMsg=Cloning ESP-IDF {0}... -CloningCompletedMsg=Cloning completed... -IDFDownloadWizard_DownloadingMessage=Downloading {0}... -IDFDownloadWizard_DownloadCompleteMsg={0} download completed! -IDFDownloadWizard_DecompressingMsg=Extracting downloaded archive... -IDFDownloadWizard_DecompressingCompleted=Archive extracted! -IDFDownloadWizard_UpdatingIDFPathMessage=Updating IDF_PATH to: {0} -BtnCancel=Cancel -OperationCancelledByUser=Operation is cancelled by the user! -InstallToolsHandler_CopyingOpenOCDRules=Copying OpenOCD Rules -InstallToolsHandler_OpenOCDRulesCopied=Rules Copied to system -InstallToolsHandler_OpenOCDRulesNotCopied=Rules Not Copied to system -InstallToolsHandler_OpenOCDRulesCopyPaths=Copying File: %s to destination: %s -InstallToolsHandler_OpenOCDRulesCopyError=Unable to copy rules for OpenOCD to system directory, try running the eclipse with sudo command -InstallToolsHandler_OpenOCDRulesCopyWarning=Warning -InstallToolsHandler_OpenOCDRulesCopyWarningMessage=The rules file is already present in the /etc/udev/rules.d/ directory, Do you want to replace the file with the file from OpenOCD directory -AbstractToolsHandler_ExecutingMsg=Executing -ToolAreadyPresent=Tool already present in ESPRESSIF home directory. -ForceDownloadToolTip=Downloads the tools again even if they are already downloaded in ESPRESSIF home directory. -ForceDownload=Force Download -InstallToolsProgressShell_lblNewLabel_text=Tool Being Installed -ToolsTreeHeading=Tools Tree -DownloadFileText=Downloading File: -ExtractionTextMessage=Extracting file: -InstallingToolMessage=Installing Tool: -UpdatingPathMessage=Updating PATH -PreviousToolMessage=Previous Tool Path: -UpdateToolPathMessage=Updated Tool Path: -SystemPathMessage=System Path: -ExtractionCompletedMessage=Extraction Completed -RemovedPathMessage=Removed Path: -RemoveToolMessageBox=Do you want to delete the selected tools? -RemoveToolMessageBoxTitle=Confirmation -SelectAllButton=Select All -RemovedPathMessage=Removed Path: -InstallingToolMessage=Installing Tool: -SelectDownloadDir=Select the directory to download ESP-IDF Tools -GitCloningJobMsg=Cloning ESP-IDF {0}... -CloningCompletedMsg=Cloning completed... -IDFDownloadWizard_DownloadingMessage=Downloading {0}... -IDFDownloadWizard_DownloadCompleteMsg={0} download completed! -IDFDownloadWizard_DecompressingMsg=Extracting downloaded archive... -IDFDownloadWizard_DecompressingCompleted=Archive extracted! -IDFDownloadWizard_UpdatingIDFPathMessage=Updating IDF_PATH to: {0} -FilterTargetBoxToolTip=Filter the tools based on the target selection of ESP chips -ShowAvailableVersionsOnlyToolTip=Shows the versions that are available already and downloaded. The versions should be in the espressif home directory to be visible with this. -MissingToolsValidationMessage_A=Following required tools are missing: -MissingToolsValidationMessage_B=Please visit the Link to see configuration for these tools -MissingToolsValidationLink=https://github.com/espressif/idf-eclipse-plugin/blob/master/docs_readme/MissingToolsManualPathUpdateGuide.md - - EspIdfEditorTitle=ESP-IDF Manager EspIdfManagerVersionCol=ESP-IDF Version EspIdfManagerLocationCol=Location -EspIdfManagerStateCol=State EspIdfManagerActivateCol=Active -EspIdfManagerAddToolsBtn=Add ESP-IDF -EspIdfManagerRemoveAllBtn=Remove All -EspIdfManagerDeleteBtn=Delete -EspIdfManagerMessageBoxDeleteConfirmMessage=Do you want to remove the toolchain with ESP-IDF version: {0} -EspIdfManagerMessageBoxDeleteConfirmMessageTitle=Confirm Remove -EspIdfManagerMessageBoxDeleteAllConfirmMessage=Do you want to remove all ESP-IDF versions from IDE -EspIdfManagerMessageBoxDeleteAllConfirmMessageTitle=Remove All ESP-IDF Versions +EspIdfManagerNameCol=Name EspIdfManagerReloadBtnToolTip=Reload from disk -EspIdfManagerDeleteBtnToolTip=Delete ESP-IDF version from IDE - -IDFDownloadHandler_ESPIDFConfiguration=ESP-IDF Configuration -IDFDownloadHandler_DownloadPage_Title=Download or use ESP-IDF -IDFDownloadHandler_DownloadPageMsg=Please choose ESP-IDF version to download, or use an existing ESP-IDF copy \ No newline at end of file +IDFToolsHandler_ToolsManagerConsole=Espressif IDF Tools Console +IDFGuideLinkLabel_Text=Select the version of ESP-IDF you want to use. Click the radio button in Active column next to the version you want. For help in choosing the correct version, visit ESP-IDF Version Guide. +EimJsonChangedMsgTitle=ESP-IDF Installation Changed +EimJsonChangedMsgDetail=It looks like the ESP-IDF tools are modified. The Espressif IDE cannot guarantee the consistency. Kindly refresh the installation via ESP-IDF Manager. +EimJsonStateChangedMsgDetail=It looks like the ESP-IDF installation was modified since last start. The Espressif IDE cannot guarantee the consistency. Kindly refresh the installation via ESP-IDF Manager. + \ No newline at end of file diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/watcher/EimJsonUiChangeHandler.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/watcher/EimJsonUiChangeHandler.java new file mode 100644 index 000000000..aa0b6495f --- /dev/null +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tools/watcher/EimJsonUiChangeHandler.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright 2025 Espressif Systems (Shanghai) PTE LTD. All rights reserved. + * Use is subject to license terms. + *******************************************************************************/ +package com.espressif.idf.ui.tools.watcher; + +import java.nio.file.Path; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.widgets.Display; +import org.osgi.service.prefs.Preferences; + +import com.espressif.idf.core.tools.watcher.EimJsonChangeListener; +import com.espressif.idf.core.tools.watcher.EimJsonStateChecker; +import com.espressif.idf.ui.tools.Messages; + +/** + * eim_idf.json file ui change handler to notify user for changes. + * + * @author Ali Azam Rana + * + */ +public class EimJsonUiChangeHandler implements EimJsonChangeListener +{ + private Preferences preferences; + + public EimJsonUiChangeHandler(Preferences preferences) + { + this.preferences = preferences; + } + + @Override + public void onJsonFileChanged(Path file) + { + Display.getDefault().asyncExec(() -> { + MessageDialog.openWarning(Display.getDefault().getActiveShell(), Messages.EimJsonChangedMsgTitle, + Messages.EimJsonChangedMsgDetail); + }); + + EimJsonStateChecker checker = new EimJsonStateChecker(preferences); + checker.updateLastSeenTimestamp(); + } + +} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tracing/AppLvlTracingDialog.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tracing/AppLvlTracingDialog.java index b9ee9d677..1cd6fc8ad 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tracing/AppLvlTracingDialog.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/tracing/AppLvlTracingDialog.java @@ -298,7 +298,7 @@ private void runTraceCommand() try { List arguments = new ArrayList(Arrays.asList(parseCommandTxt.getText().split(" "))); //$NON-NLS-1$ - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); + Map environment = new HashMap<>(System.getenv()); IStatus status = processRunner.runInBackground(arguments, Path.ROOT, environment); if (status == null) { diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/AbstractToolsHandler.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/AbstractToolsHandler.java index bd46091a0..9a7a093e0 100644 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/AbstractToolsHandler.java +++ b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/AbstractToolsHandler.java @@ -16,7 +16,6 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.window.Window; @@ -24,7 +23,6 @@ import org.eclipse.ui.console.MessageConsoleStream; import com.espressif.idf.core.IDFCorePlugin; -import com.espressif.idf.core.IDFCorePreferenceConstants; import com.espressif.idf.core.IDFEnvironmentVariables; import com.espressif.idf.core.ProcessBuilderFactory; import com.espressif.idf.core.SystemExecutableFinder; @@ -143,20 +141,10 @@ protected IStatus runCommand(List arguments, MessageConsoleStream consol console.println(cmdMsg); Logger.log(cmdMsg); - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); + Map environment = new HashMap<>(System.getenv()); Logger.log(environment.toString()); environment.put("PYTHONUNBUFFERED", "1"); //$NON-NLS-1$ //$NON-NLS-2$ - environment.put("IDF_GITHUB_ASSETS", //$NON-NLS-1$ - Platform.getPreferencesService().getString(IDFCorePlugin.PLUGIN_ID, - IDFCorePreferenceConstants.IDF_GITHUB_ASSETS, - IDFCorePreferenceConstants.IDF_GITHUB_ASSETS_DEFAULT_GLOBAL, null)); - - environment.put("PIP_EXTRA_INDEX_URL", //$NON-NLS-1$ - Platform.getPreferencesService().getString(IDFCorePlugin.PLUGIN_ID, - IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL, - IDFCorePreferenceConstants.PIP_EXTRA_INDEX_URL_DEFAULT_GLOBAL, null)); - if (gitExecutablePath != null) { addGitToEnvironment(environment, gitExecutablePath); diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/ExportIDFTools.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/ExportIDFTools.java deleted file mode 100644 index 6a6b6a6eb..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/ExportIDFTools.java +++ /dev/null @@ -1,292 +0,0 @@ -/******************************************************************************* - * Copyright 2020 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.update; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.osgi.util.NLS; -import org.eclipse.ui.console.MessageConsoleStream; - -import com.espressif.idf.core.IDFConstants; -import com.espressif.idf.core.IDFCorePlugin; -import com.espressif.idf.core.IDFEnvironmentVariables; -import com.espressif.idf.core.ProcessBuilderFactory; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.util.IDFUtil; -import com.espressif.idf.core.util.StringUtil; - -/** - * @author Kondal Kolipaka - * - * Run /tools/idf_tools.py export command - * - */ -public class ExportIDFTools -{ - /** - * @param pythonExePath python executable full path - * @param gitExePath git executable full path - * @param console Console stream to write messages - * @param errorConsoleStream - */ - public IStatus runToolsExportAndProcessOutput(final String pythonExePath, final String gitExePath, final MessageConsoleStream console, MessageConsoleStream errorConsoleStream) - { - final List arguments = getExportCommand(pythonExePath); - - final String cmd = Messages.AbstractToolsHandler_ExecutingMsg + " " + getCommandString(arguments); //$NON-NLS-1$ - log(cmd, console); - - final Map environment = new HashMap<>(IDFUtil.getSystemEnv()); - if (gitExePath != null) - { - addGitToEnvironment(environment, gitExePath); - } - final ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); - try - { - final IStatus status = processRunner.runInBackground(arguments, Path.ROOT, environment); - if (status == null) - { - Logger.log(IDFCorePlugin.getPlugin(), IDFCorePlugin.errorStatus("Status can't be null", null)); //$NON-NLS-1$ - return IDFCorePlugin.errorStatus("Status can't be null", null); //$NON-NLS-1$ - } - - if (status.getSeverity() == IStatus.ERROR) - { - log(status.getException() != null ? status.getException().getMessage() : status.getMessage(), errorConsoleStream); - return status; - } - - // process export command output - final String exportCmdOp = status.getMessage(); - log(exportCmdOp, console); - processExportCmdOutput(exportCmdOp, gitExePath); - - return status; - } - catch (IOException e1) - { - Logger.log(IDFCorePlugin.getPlugin(), e1); - return IDFCorePlugin.errorStatus(e1.getMessage(), e1); - } - } - - public IStatus getToolsExportOutput(final String pythonExePath, final String gitExePath, final MessageConsoleStream console, MessageConsoleStream errorConsoleStream) - { - final List arguments = getExportCommand(pythonExePath); - - final String cmd = Messages.AbstractToolsHandler_ExecutingMsg + " " + getCommandString(arguments); //$NON-NLS-1$ - log(cmd, console); - - final Map environment = new HashMap<>(IDFUtil.getSystemEnv()); - if (gitExePath != null) - { - addGitToEnvironment(environment, gitExePath); - } - final ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); - try - { - final IStatus status = processRunner.runInBackground(arguments, Path.ROOT, environment); - if (status == null) - { - Logger.log(IDFCorePlugin.getPlugin(), IDFCorePlugin.errorStatus("Status can't be null", null)); //$NON-NLS-1$ - return IDFCorePlugin.errorStatus("Status can't be null", null); //$NON-NLS-1$ - } - - if (status.getSeverity() == IStatus.ERROR) - { - log(status.getException() != null ? status.getException().getMessage() : status.getMessage(), errorConsoleStream); - return status; - } - - return status; - } - catch (IOException e) - { - Logger.log(IDFCorePlugin.getPlugin(), e); - return IDFCorePlugin.errorStatus(e.getMessage(), e); - } - } - - public IStatus getToolsExportOutputFromGivenIdfPath(final String pythonExePath, final String gitExePath, - final MessageConsoleStream console, MessageConsoleStream errorConsoleStream, final String idfPath) - { - final List arguments = getExportCommandUsingGivenIdfPath(pythonExePath, idfPath); - - final String cmd = Messages.AbstractToolsHandler_ExecutingMsg + " " + getCommandString(arguments); //$NON-NLS-1$ - log(cmd, console); - - final Map environment = new HashMap<>(IDFUtil.getSystemEnv()); - if (gitExePath != null) - { - addGitToEnvironment(environment, gitExePath); - } - - final ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); - try - { - final IStatus status = processRunner.runInBackground(arguments, Path.ROOT, environment); - if (status == null) - { - Logger.log(IDFCorePlugin.getPlugin(), IDFCorePlugin.errorStatus("Status can't be null", null)); //$NON-NLS-1$ - return IDFCorePlugin.errorStatus("Status can't be null", null); //$NON-NLS-1$ - } - - if (status.getSeverity() == IStatus.ERROR) - { - log(status.getException() != null ? status.getException().getMessage() : status.getMessage(), errorConsoleStream); - return status; - } - - return status; - } - catch (IOException e) - { - Logger.log(IDFCorePlugin.getPlugin(), e); - return IDFCorePlugin.errorStatus(e.getMessage(), e); - } - } - - private List getExportCommandUsingGivenIdfPath(String pythonExePath, String idfPath) - { - final List arguments = new ArrayList<>(); - arguments.add(pythonExePath); - arguments.add(IDFUtil.getIDFToolsScriptFile(idfPath).getAbsolutePath()); - arguments.add(IDFConstants.TOOLS_EXPORT_CMD); - arguments.add(IDFConstants.TOOLS_EXPORT_CMD_FORMAT_VAL); - return arguments; - } - - private List getExportCommand(String pythonExePath) - { - final List arguments = new ArrayList<>(); - arguments.add(pythonExePath); - arguments.add(IDFUtil.getIDFToolsScriptFile().getAbsolutePath()); - arguments.add(IDFConstants.TOOLS_EXPORT_CMD); - arguments.add(IDFConstants.TOOLS_EXPORT_CMD_FORMAT_VAL); - return arguments; - } - - private void log(final String cmd, final MessageConsoleStream console) - { - Logger.log(cmd); - if (console != null) - { - console.println(cmd); - } - } - - private String getCommandString(final List arguments) - { - final StringBuilder builder = new StringBuilder(); - arguments.forEach(entry -> builder.append(entry + " ")); //$NON-NLS-1$ - - return builder.toString().trim(); - } - - private void processExportCmdOutput(final String exportCmdOp, final String gitExecutablePath) - { - // process export command output - final String[] exportEntries = exportCmdOp.split("\n"); //$NON-NLS-1$ - for (String entry : exportEntries) - { - entry = entry.replaceAll("\\r", ""); //$NON-NLS-1$ //$NON-NLS-2$ - String[] keyValue = entry.split("="); //$NON-NLS-1$ - if (keyValue.length == 2) // 0 - key, 1 - value - { - final String msg = MessageFormat.format("Key: {0} Value: {1}", keyValue[0], keyValue[1]); //$NON-NLS-1$ - Logger.log(msg); - - final IDFEnvironmentVariables idfEnvMgr = new IDFEnvironmentVariables(); - String key = keyValue[0]; - String value = keyValue[1]; - if (key.equals(IDFEnvironmentVariables.PATH)) - { - value = replacePathVariable(value); - value = appendGitToPath(value, gitExecutablePath); - } - - // add new or replace old entries - idfEnvMgr.addEnvVariable(key, value); - } - - } - } - - private String replacePathVariable(String value) - { - // Get system PATH - Map systemEnv = new HashMap<>(IDFUtil.getSystemEnv()); - String pathEntry = systemEnv.get("PATH"); //$NON-NLS-1$ - if (pathEntry == null) - { - pathEntry = systemEnv.get("Path"); // for Windows //$NON-NLS-1$ - if (pathEntry == null) // no idea - { - Logger.log(new Exception("No PATH found in the system environment variables")); //$NON-NLS-1$ - } - } - - if (!StringUtil.isEmpty(pathEntry)) - { - value = value.replace("$PATH", pathEntry); // macOS //$NON-NLS-1$ - value = value.replace("%PATH%", pathEntry); // Windows //$NON-NLS-1$ - } - return value; - } - - protected void addGitToEnvironment(Map envMap, String executablePath) - { - IPath gitPath = new Path(executablePath); - if (gitPath.toFile().exists()) - { - String gitDir = gitPath.removeLastSegments(1).toOSString(); - String path1 = envMap.get("PATH"); //$NON-NLS-1$ - String path2 = envMap.get("Path"); //$NON-NLS-1$ - if (!StringUtil.isEmpty(path1) && !path1.contains(gitDir)) // Git not found on the PATH environment - { - path1 = gitDir.concat(";").concat(path1); //$NON-NLS-1$ - envMap.put("PATH", path1); //$NON-NLS-1$ - } - else if (!StringUtil.isEmpty(path2) && !path2.contains(gitDir)) // Git not found on the Path environment - { - path2 = gitDir.concat(";").concat(path2); //$NON-NLS-1$ - envMap.put("Path", path2); //$NON-NLS-1$ - } - } - } - - /** - * Append the git directory to the existing CDT build environment PATH variable - * - * @param path CDT build environment PATH - * @param gitExecutablePath - * @return PATH value with git appended - */ - private String appendGitToPath(String path, String gitExecutablePath) - { - IPath gitPath = new Path(gitExecutablePath); - if (!gitPath.toFile().exists()) - { - Logger.log(NLS.bind("{0} doesn't exist", gitExecutablePath)); //$NON-NLS-1$ - return path; - } - - String gitDir = gitPath.removeLastSegments(1).toOSString(); // ../bin/git - if (!StringUtil.isEmpty(path) && !path.contains(gitDir)) // Git not found on the CDT build PATH environment - { - return path.concat(";").concat(gitDir); // append git path //$NON-NLS-1$ - } - return path; - } -} diff --git a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/InstallToolsHandler.java b/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/InstallToolsHandler.java deleted file mode 100644 index 15ec76edf..000000000 --- a/bundles/com.espressif.idf.ui/src/com/espressif/idf/ui/update/InstallToolsHandler.java +++ /dev/null @@ -1,382 +0,0 @@ -/******************************************************************************* - * Copyright 2018-2019 Espressif Systems (Shanghai) PTE LTD. All rights reserved. - * Use is subject to license terms. - *******************************************************************************/ -package com.espressif.idf.ui.update; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.IJobChangeEvent; -import org.eclipse.core.runtime.jobs.IJobChangeListener; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.MessageBox; -import org.eclipse.ui.console.MessageConsoleStream; -import org.osgi.service.prefs.BackingStoreException; -import org.osgi.service.prefs.Preferences; - -import com.espressif.idf.core.IDFConstants; -import com.espressif.idf.core.IDFCorePlugin; -import com.espressif.idf.core.IDFEnvironmentVariables; -import com.espressif.idf.core.ProcessBuilderFactory; -import com.espressif.idf.core.logging.Logger; -import com.espressif.idf.core.toolchain.ESPToolChainManager; -import com.espressif.idf.core.util.IDFUtil; -import com.espressif.idf.core.util.StringUtil; -import com.espressif.idf.ui.IDFConsole; -import com.espressif.idf.ui.UIPlugin; - -/** - * IDF Tools install command handler - * - * @author Kondal Kolipaka - * - */ -public class InstallToolsHandler extends AbstractToolsHandler -{ - public static final String INSTALL_TOOLS_FLAG = "INSTALL_TOOLS_FLAG"; //$NON-NLS-1$ - - @Override - protected void execute() - { - Job installToolsJob = new Job(Messages.InstallToolsHandler_InstallingToolsMsg) - { - @Override - protected IStatus run(IProgressMonitor monitor) - { - monitor.beginTask(Messages.InstallToolsHandler_ItWilltakeTimeMsg, 5); - monitor.worked(1); - - IStatus status = handleToolsInstall(); - if (status.getSeverity() == IStatus.ERROR) - { - return status; - } - - monitor.worked(1); - monitor.setTaskName(Messages.InstallToolsHandler_InstallingPythonMsg); - status = handleToolsInstallPython(console); - if (status.getSeverity() == IStatus.ERROR) - { - return status; - } - - monitor.worked(1); - - monitor.setTaskName(Messages.InstallToolsHandler_ExportingPathsMsg); - status = new ExportIDFTools().runToolsExportAndProcessOutput(pythonExecutablenPath, gitExecutablePath, console, - errorConsoleStream); - if (status.getSeverity() == IStatus.ERROR) - { - return status; - } - - monitor.worked(1); - console.println(Messages.InstallToolsHandler_ConfiguredBuildEnvVarMsg); - - monitor.setTaskName(Messages.InstallToolsHandler_AutoConfigureToolchain); - new ESPToolChainManager().configureToolChain(); - monitor.worked(1); - - configEnv(); - - monitor.setTaskName(Messages.InstallToolsHandler_InstallingWebscoketMsg); - handleWebSocketClientInstall(); - monitor.worked(1); - - copyOpenOcdRules(); - console.println(Messages.InstallToolsHandler_ConfiguredCMakeMsg); - - console.println(Messages.InstallToolsHandler_ToolsCompleted); - return Status.OK_STATUS; - } - }; - Preferences scopedPreferenceStore = InstanceScope.INSTANCE.getNode(UIPlugin.PLUGIN_ID); - scopedPreferenceStore.putBoolean(INSTALL_TOOLS_FLAG, true); - try - { - scopedPreferenceStore.flush(); - } - catch (BackingStoreException e) - { - Logger.log(e); - } - installToolsJob.addJobChangeListener(new ToolInstallListener()); - installToolsJob.schedule(); - } - - /** - * Configure all the required environment variables here - */ - protected void configEnv() - { - IDFEnvironmentVariables idfEnvMgr = new IDFEnvironmentVariables(); - - // Enable IDF_COMPONENT_MANAGER by default - idfEnvMgr.addEnvVariable(IDFEnvironmentVariables.IDF_COMPONENT_MANAGER, "1"); - // IDF_MAINTAINER=1 to be able to build with the clang toolchain - idfEnvMgr.addEnvVariable(IDFEnvironmentVariables.IDF_MAINTAINER, "1"); - - } - - private void copyOpenOcdRules() - { - if (Platform.getOS().equals(Platform.OS_LINUX) - && !IDFUtil.getOpenOCDLocation().equalsIgnoreCase(StringUtil.EMPTY)) - { - console.println(Messages.InstallToolsHandler_CopyingOpenOCDRules); - // Copy the rules to the idf - StringBuilder pathToRules = new StringBuilder(); - pathToRules.append(IDFUtil.getOpenOCDLocation()); - pathToRules.append("/../share/openocd/contrib/60-openocd.rules"); //$NON-NLS-1$ - File rulesFile = new File(pathToRules.toString()); - if (rulesFile.exists()) - { - Path source = Paths.get(pathToRules.toString()); - Path target = Paths.get("/etc/udev/rules.d/60-openocd.rules"); //$NON-NLS-1$ - console.println(String.format(Messages.InstallToolsHandler_OpenOCDRulesCopyPaths, source.toString(), - target.toString())); - - Display.getDefault().syncExec(new Runnable() - { - @Override - public void run() - { - try - { - if (target.toFile().exists()) - { - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell(), - SWT.ICON_WARNING | SWT.YES | SWT.NO); - messageBox.setText(Messages.InstallToolsHandler_OpenOCDRulesCopyWarning); - messageBox.setMessage(Messages.InstallToolsHandler_OpenOCDRulesCopyWarningMessage); - int response = messageBox.open(); - if (response == SWT.YES) - { - Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); - } - else - { - console.println(Messages.InstallToolsHandler_OpenOCDRulesNotCopied); - return; - } - } - else - { - Files.copy(source, target); - } - - console.println(Messages.InstallToolsHandler_OpenOCDRulesCopied); - } - catch (IOException e) - { - Logger.log(e); - errorConsoleStream.println(Messages.InstallToolsHandler_OpenOCDRulesCopyError); - } - } - }); - } - } - } - - protected IStatus handleToolsInstall() - { - // idf_tools.py install all - List arguments = new ArrayList(); - arguments.add(IDFConstants.TOOLS_INSTALL_CMD); - arguments.add(IDFConstants.TOOLS_INSTALL_ALL_CMD); - - console.println(Messages.InstallToolsHandler_InstallingToolsMsg); - console.println(Messages.InstallToolsHandler_ItWilltakeTimeMsg); - return runCommand(arguments, console); - } - - protected IStatus handleToolsInstallPython(MessageConsoleStream console) - { - List arguments; - // idf_tools.py install-python-env - arguments = new ArrayList(); - arguments.add(IDFConstants.TOOLS_INSTALL_PYTHON_CMD); - return runCommand(arguments, console); - } - - public IStatus handleWebSocketClientInstall() - { - String websocketClient = "websocket-client"; //$NON-NLS-1$ - // pip install websocket-client - List arguments = new ArrayList(); - final String pythonEnvPath = IDFUtil.getIDFPythonEnvPath(); - if (pythonEnvPath == null || !new File(pythonEnvPath).exists()) - { - console.println(String.format("%s executable not found. Unable to run `%s -m pip install websocket-client`", //$NON-NLS-1$ - IDFConstants.PYTHON_CMD, IDFConstants.PYTHON_CMD)); - return IDFCorePlugin.errorStatus( - String.format("%s executable not found. Unable to run `%s -m pip install websocket-client`", //$NON-NLS-1$ - IDFConstants.PYTHON_CMD, IDFConstants.PYTHON_CMD), - null); - } - arguments.add(pythonEnvPath); - arguments.add("-m"); //$NON-NLS-1$ - arguments.add("pip"); //$NON-NLS-1$ - arguments.add("list"); //$NON-NLS-1$ - - ProcessBuilderFactory processRunner = new ProcessBuilderFactory(); - - try - { - String cmdMsg = "Executing " + getCommandString(arguments); //$NON-NLS-1$ - if (console != null) - { - console.println(cmdMsg); - } - Logger.log(cmdMsg); - - Map environment = new HashMap<>(IDFUtil.getSystemEnv()); - Logger.log(environment.toString()); - - IStatus status = processRunner.runInBackground(arguments, org.eclipse.core.runtime.Path.ROOT, environment); - if (status == null) - { - Logger.log(IDFCorePlugin.getPlugin(), - IDFCorePlugin.errorStatus("Unable to get the process status.", null)); //$NON-NLS-1$ - if (errorConsoleStream != null) - { - errorConsoleStream.println("Unable to get the process status."); - } - return IDFCorePlugin.errorStatus("Unable to get the process status.", null); //$NON-NLS-1$ - } - - String cmdOutput = status.getMessage(); - if (cmdOutput.contains(websocketClient)) - { - return IDFCorePlugin.okStatus("websocket-client already installed", null); //$NON-NLS-1$ - } - - // websocket client not installed so installing it now. - arguments.remove(arguments.size() - 1); - arguments.add("install"); //$NON-NLS-1$ - arguments.add(websocketClient); - - status = processRunner.runInBackground(arguments, org.eclipse.core.runtime.Path.ROOT, environment); - if (status == null) - { - Logger.log(IDFCorePlugin.getPlugin(), - IDFCorePlugin.errorStatus("Unable to get the process status.", null)); //$NON-NLS-1$ - if (errorConsoleStream != null) - { - errorConsoleStream.println("Unable to get the process status."); - } - return IDFCorePlugin.errorStatus("Unable to get the process status.", null); //$NON-NLS-1$ - } - - if (console != null) - { - console.println(status.getMessage()); - } - - return status; - } - catch (Exception e1) - { - Logger.log(IDFCorePlugin.getPlugin(), e1); - if (errorConsoleStream != null) - { - errorConsoleStream.println(e1.getLocalizedMessage()); - } - return IDFCorePlugin.errorStatus(e1.getLocalizedMessage(), e1); // $NON-NLS-1$; - } - } - - private class ToolInstallListener implements IJobChangeListener - { - Map existingVarMap; - - @Override - public void aboutToRun(IJobChangeEvent event) - { - // clean the ESP_IDF_VERSION variable first, because it's not coming from older versions of the ESP-IDF - new IDFEnvironmentVariables().removeEnvVariable(IDFEnvironmentVariables.ESP_IDF_VERSION); - this.existingVarMap = loadExistingVars(); - } - - private Map loadExistingVars() - { - IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); - Map existingVarMap = new HashMap<>(); - existingVarMap.put(IDFEnvironmentVariables.IDF_COMPONENT_MANAGER, - idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.IDF_COMPONENT_MANAGER)); - existingVarMap.put(IDFEnvironmentVariables.IDF_PATH, - idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.IDF_PATH)); - existingVarMap.put(IDFEnvironmentVariables.IDF_PYTHON_ENV_PATH, - idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.IDF_PYTHON_ENV_PATH)); - existingVarMap.put(IDFEnvironmentVariables.OPENOCD_SCRIPTS, - idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.OPENOCD_SCRIPTS)); - existingVarMap.put(IDFEnvironmentVariables.PATH, - idfEnvironmentVariables.getEnvValue(IDFEnvironmentVariables.PATH)); - - return existingVarMap; - } - - @Override - public void awake(IJobChangeEvent event) - { - - } - - @Override - public void done(IJobChangeEvent event) - { - if (event.getResult().getSeverity() == IStatus.ERROR) - { - restoreOldVars(); - } - else - { - IDFUtil.updateEspressifPrefPageOpenocdPath(); - } - } - - private void restoreOldVars() - { - IDFEnvironmentVariables idfEnvironmentVariables = new IDFEnvironmentVariables(); - for (Entry varsEntry : existingVarMap.entrySet()) - { - idfEnvironmentVariables.addEnvVariable(varsEntry.getKey(), varsEntry.getValue()); - } - } - - @Override - public void running(IJobChangeEvent event) - { - - } - - @Override - public void scheduled(IJobChangeEvent event) - { - - } - - @Override - public void sleeping(IJobChangeEvent event) - { - - } - } -} diff --git a/tests/com.espressif.idf.ui.test/configs/default-test-linux.properties b/tests/com.espressif.idf.ui.test/configs/default-test-linux.properties index 4cef675fc..05338624f 100644 --- a/tests/com.espressif.idf.ui.test/configs/default-test-linux.properties +++ b/tests/com.espressif.idf.ui.test/configs/default-test-linux.properties @@ -7,7 +7,7 @@ default.project.copy.wait=7000 # Default paths for esp env configs (These may need to be updated as per Automation requirements and the env being used) #Github Actions Path -default.env.esp.idf.path=/opt/actions-runner/_work/idf-eclipse-plugin/idf-eclipse-plugin/dependencies/idf-tools +default.env.esp.idf.path=/opt/actions-runner/_work/idf-eclipse-plugin/idf-eclipse-plugin/dependencies/idf-tools/v5.3/esp-idf default.env.esp.git.path=git default.env.esp.python.version=3.9 default.env.esp.python.path=python3 diff --git a/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/executable/cases/project/NewEspressifIDFProjectSDKconfigTest.java b/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/executable/cases/project/NewEspressifIDFProjectSDKconfigTest.java index ff5fb9752..04201e45f 100644 --- a/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/executable/cases/project/NewEspressifIDFProjectSDKconfigTest.java +++ b/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/executable/cases/project/NewEspressifIDFProjectSDKconfigTest.java @@ -175,14 +175,14 @@ private static void whenSDKconfigFileOpenedUsingDoubleClick() throws IOException { bot.tree().getTreeItem(projectName).getNode("sdkconfig").doubleClick(); TestWidgetWaitUtility.waitWhileDialogIsVisible(bot, "Progress Information", 40000); - TestWidgetWaitUtility.waitForSDKConfigurationTab(bot, 5000); + TestWidgetWaitUtility.waitForSDKConfigurationTab(bot, 900000); } private static void whenSDKconfigFileOpenedUsingContextMenu() throws IOException { ProjectTestOperations.launchCommandUsingContextMenu(projectName, bot, "Menu Config"); TestWidgetWaitUtility.waitWhileDialogIsVisible(bot, "Progress Information", 40000); - TestWidgetWaitUtility.waitForSDKConfigurationTab(bot, 5000); + TestWidgetWaitUtility.waitForSDKConfigurationTab(bot, 900000); } private static void thenSDKconfigFileContentChecked() throws Exception diff --git a/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/executable/cases/project/NewEspressifIDFProjectTest.java b/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/executable/cases/project/NewEspressifIDFProjectTest.java index e23c76aaa..827fdeb47 100644 --- a/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/executable/cases/project/NewEspressifIDFProjectTest.java +++ b/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/executable/cases/project/NewEspressifIDFProjectTest.java @@ -119,55 +119,6 @@ public void givenNewProjectCreatedAndRenamedAfterThenProjectIsBuildSuccessfully( Fixture.thenConsoleShowsBuildSuccessful(); } -// @Test -// public void givenNewProjectCreatedDfuBuiltThenHasDfuBin() throws Exception -// { -// Fixture.givenNewEspressifIDFProjectIsSelected("EspressIf", "Espressif IDF Project"); -// Fixture.givenProjectNameIs("NewProjectTestDFU"); -// Fixture.whenNewProjectIsSelected(); -// Fixture.thenLaunchTargetIsSelectedFromLaunchTargets("esp32s2"); -// Fixture.turnOnDfu(); -// Fixture.whenProjectIsBuiltUsingContextMenu(); -// Fixture.thenProjectHasTheFile("dfu.bin", "/build"); -// Fixture.turnOffDfu(); -// } - - @Test - public void givenNewProjectCreatedThenInstallNewComponent() throws Exception - { - Fixture.givenNewEspressifIDFProjectIsSelected("EspressIf", "Espressif IDF Project"); - Fixture.givenProjectNameIs("NewProjectForInstallNewComponentTest"); - Fixture.whenNewProjectIsSelected(); - Fixture.whenProjectIsBuiltUsingContextMenu(); - Fixture.whenInstallNewComponentUsingContextMenu(); - Fixture.whenRefreshProject(); - Fixture.checkIfNewComponentIsInstalledUsingContextMenu(); - } - -// @Test -// public void givenNewProjectCreatedBuiltAndThenProjectCleanUsingContextMenu() throws Exception -// { -// Fixture.givenNewEspressifIDFProjectIsSelected("EspressIf", "Espressif IDF Project"); -// Fixture.givenProjectNameIs("NewProjectCleanTest"); -// Fixture.whenNewProjectIsSelected(); -// Fixture.whenProjectIsBuiltUsingContextMenu(); -// Fixture.whenProjectCleanUsingContextMenu(); -// Fixture.whenRefreshProject(); -// Fixture.checkIfProjectCleanedFilesInBuildFolder(); -// } - - @Test - public void givenNewProjectCreatedBuiltAndThenProjectFullCleanUsingContextMenu() throws Exception - { - Fixture.givenNewEspressifIDFProjectIsSelected("EspressIf", "Espressif IDF Project"); - Fixture.givenProjectNameIs("NewProjectFullCleanTest"); - Fixture.whenNewProjectIsSelected(); - Fixture.whenProjectIsBuiltUsingContextMenu(); - Fixture.whenProjectFullCleanUsingContextMenu(); - Fixture.whenRefreshProject(); - Fixture.checkIfProjectFullCleanedFilesInBuildFolder(); - } - @Test public void givenNewProjectCreatedBuiltAndThenProjectPythonCleanUsingContextMenu() throws Exception { diff --git a/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/operations/EnvSetupOperations.java b/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/operations/EnvSetupOperations.java index 27b673659..6bba6c0ee 100644 --- a/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/operations/EnvSetupOperations.java +++ b/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/operations/EnvSetupOperations.java @@ -3,6 +3,7 @@ import static org.eclipse.swtbot.eclipse.finder.matchers.WidgetMatcherFactory.withPartName; import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot; +import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; @@ -27,6 +28,17 @@ public static void setupEspressifEnv(SWTWorkbenchBot bot) throws Exception { view.close(); } + + SWTBotEditor espIdfManagerView = bot.editorByTitle("ESP-IDF Manager"); + espIdfManagerView.bot().radio(0).click(); + + SWTBotView consoleView = bot.viewById("org.eclipse.ui.console.ConsoleView"); + consoleView.show(); + consoleView.setFocus(); + TestWidgetWaitUtility.waitUntilViewContains(bot, "Tools Setup complete", consoleView, 99000000); + bot.cTabItem("ESP-IDF Manager").activate(); + bot.cTabItem("ESP-IDF Manager").close(); + bot.menu("Window").menu("Perspective").menu("Open Perspective").menu("Other...").click(); bot.table().select("C/C++"); bot.button("Open").click(); @@ -55,30 +67,6 @@ public static void setupEspressifEnv(SWTWorkbenchBot bot) throws Exception bot.text().setText("progress"); bot.button("Open").click(); bot.viewByTitle("Progress").show(); - - TestWidgetWaitUtility.waitForOperationsInProgressToFinishSync(bot); - bot.activeShell(); - - bot.menu("Espressif").menu("ESP-IDF Manager").click(); - bot.activeShell().activate(); - bot.button("Add ESP-IDF").click(); - SWTBotShell espIdfConfigShell = bot.shell("ESP-IDF Configuration"); - espIdfConfigShell.setFocus(); - espIdfConfigShell.bot().checkBox("Use an existing ESP-IDF directory from file system").click(); - espIdfConfigShell.bot().textWithLabel("Choose existing ESP-IDF directory:") - .setText(DefaultPropertyFetcher.getStringPropertyValue(ESP_IDF_PATH_PROPERTY, "")); - espIdfConfigShell.bot().textWithLabel("Git: ") - .setText(DefaultPropertyFetcher.getStringPropertyValue(GIT_PATH_PROPERTY, "")); - espIdfConfigShell.bot().textWithLabel("Python: ") - .setText(DefaultPropertyFetcher.getStringPropertyValue(PYTHON_PATH_PROPERTY, "")); - espIdfConfigShell.bot().button("Finish").click(); - - SWTBotView consoleView = bot.viewById("org.eclipse.ui.console.ConsoleView"); - consoleView.show(); - consoleView.setFocus(); - TestWidgetWaitUtility.waitUntilViewContains(bot, "Tools Activated", consoleView, 99000000); - bot.cTabItem("ESP-IDF Manager").activate(); - bot.cTabItem("ESP-IDF Manager").close(); SETUP = true; } diff --git a/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/operations/ProjectTestOperations.java b/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/operations/ProjectTestOperations.java index 5a9356335..e79fd7648 100644 --- a/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/operations/ProjectTestOperations.java +++ b/tests/com.espressif.idf.ui.test/src/com/espressif/idf/ui/test/operations/ProjectTestOperations.java @@ -579,7 +579,7 @@ public static void findInConsole(SWTWorkbenchBot bot, String consoleName, String SWTBotView consoleView = viewConsole(consoleName, bot); consoleView.show(); consoleView.setFocus(); - TestWidgetWaitUtility.waitUntilViewContains(bot, findText, consoleView, 3000); + TestWidgetWaitUtility.waitUntilViewContains(bot, findText, consoleView, 30000); } public static boolean checkShellContent(SWTWorkbenchBot bot, String shellName, String expectedText) diff --git a/tests/pom.xml b/tests/pom.xml index 965e0deaa..550801bd9 100644 --- a/tests/pom.xml +++ b/tests/pom.xml @@ -30,7 +30,7 @@ false org.eclipse.ui.ide.workbench - -Xms4096m -Xmx8192m + -Xms4096m -Xmx8192m -DtestRun=true ${skipTests} true ${testWorkspace}