diff --git a/images_plugin_dev_setup/SVG_Logo/splash.svg b/images_plugin_dev_setup/SVG_Logo/splash.svg index 22c2eb0e3..d624f2ffa 100644 --- a/images_plugin_dev_setup/SVG_Logo/splash.svg +++ b/images_plugin_dev_setup/SVG_Logo/splash.svg @@ -9,7 +9,7 @@ version="1.1" inkscape:version="1.3.2 (091e20e, 2023-11-25, custom)" sodipodi:docname="splash.svg" - inkscape:export-filename="..\..\..\..\..\..\test\splash.png" + inkscape:export-filename="..\..\..\..\Desktop\splash.jpg" inkscape:export-xdpi="96" inkscape:export-ydpi="96" xml:space="preserve" @@ -28,16 +28,16 @@ inkscape:pageopacity="1" inkscape:pageshadow="2" inkscape:zoom="1" - inkscape:cx="-262.5" + inkscape:cx="-345" inkscape:cy="-55.5" inkscape:document-units="px" inkscape:current-layer="layer4" showgrid="false" units="px" inkscape:window-width="1920" - inkscape:window-height="991" - inkscape:window-x="-9" - inkscape:window-y="-9" + inkscape:window-height="1009" + inkscape:window-x="-8" + inkscape:window-y="-8" inkscape:window-maximized="1" inkscape:snap-global="false" showguides="true" @@ -2678,7 +2678,7 @@ id="tspan4789" x="315.39621" y="212.03772" - style="font-size:25px;line-height:1.25">BerylliumBoron - - - - - - + + + + + + + + + + + diff --git a/io.sloeber.autoBuild.test/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.autoBuild.test/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..23fa13b17 --- /dev/null +++ b/io.sloeber.autoBuild.test/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,9 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=21 diff --git a/io.sloeber.autoBuild.test/META-INF/MANIFEST.MF b/io.sloeber.autoBuild.test/META-INF/MANIFEST.MF index 1166e9fdb..4f2c8325f 100644 --- a/io.sloeber.autoBuild.test/META-INF/MANIFEST.MF +++ b/io.sloeber.autoBuild.test/META-INF/MANIFEST.MF @@ -7,7 +7,6 @@ Require-Bundle: io.sloeber.autoBuild, junit-jupiter-api;bundle-version="5.0.0", junit-jupiter-params;bundle-version="5.0.0", org.eclipse.core.resources, - org.apache.log4j;bundle-version="1.2.24", org.eclipse.cdt.core;bundle-version="7.4.200", org.eclipse.osgi, org.eclipse.core.jobs, @@ -22,4 +21,4 @@ Require-Bundle: io.sloeber.autoBuild, junit-platform-engine;bundle-version="1.10.2", junit-platform-suite-api;bundle-version="1.10.2" Automatic-Module-Name: io.sloeber.autoBuild.test -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 diff --git a/io.sloeber.autoBuild.test/launch/AutoBuildRegression_linux_jantje.launch b/io.sloeber.autoBuild.test/launch/AutoBuildRegression_linux_jantje.launch new file mode 100644 index 000000000..5679f78c0 --- /dev/null +++ b/io.sloeber.autoBuild.test/launch/AutoBuildRegression_linux_jantje.launch @@ -0,0 +1,308 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/io.sloeber.autoBuild.test/src/io/sloeber/autoBuilld/investigate/CConfigurationDescriptionInvestigation.java b/io.sloeber.autoBuild.test/src/io/sloeber/autoBuilld/investigate/CConfigurationDescriptionInvestigation.java deleted file mode 100644 index 4895e1489..000000000 --- a/io.sloeber.autoBuild.test/src/io/sloeber/autoBuilld/investigate/CConfigurationDescriptionInvestigation.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.sloeber.autoBuilld.investigate; - -import static io.sloeber.autoBuild.helpers.Defaults.*; -import static org.junit.jupiter.api.Assertions.*; - -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; -import org.eclipse.cdt.core.settings.model.ICFolderDescription; -import org.eclipse.cdt.core.settings.model.ICProjectDescription; -import org.eclipse.cdt.internal.core.settings.model.CConfigurationDescription; -import org.eclipse.cdt.internal.core.settings.model.CConfigurationDescriptionCache; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceDescription; -import org.eclipse.core.resources.ResourcesPlugin; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import io.sloeber.autoBuild.api.AutoBuildProject; -import io.sloeber.autoBuild.buildTools.api.IBuildTools; -import io.sloeber.autoBuild.buildTools.api.IBuildToolsManager; -import io.sloeber.autoBuild.helpers.Shared; - -@SuppressWarnings({ "restriction", "nls", "static-method" }) -public class CConfigurationDescriptionInvestigation { - static int testCounter = 1; - - @BeforeAll - static void beforeAll() { - Shared.setDeleteProjects(false); - Shared.setCloseProjects(false); - // turn off auto building to make sure autobuild does not start a build behind our backs - final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - IWorkspaceDescription workspaceDesc = workspace.getDescription(); - workspaceDesc.setAutoBuilding(false); - } - - @Test - public void testConfigDescription() { - String projectName = "testConfigDescription"; - IBuildTools buildTools = IBuildToolsManager.getDefault().getAnyInstalledBuildTools(defaultProjectType); - IProject testProject = AutoBuildProject.createProject(projectName, defaultProjectType, defaultNatureID, cpp_exeCodeProvider, buildTools, false, null); - ICProjectDescription projectDesc = CoreModel.getDefault().getProjectDescription(testProject, true); - for (ICConfigurationDescription curConf : projectDesc.getConfigurations()) { - assertFalse( curConf instanceof CConfigurationDescriptionCache,"conf is readOnly class instance"); - assertTrue( curConf instanceof CConfigurationDescription,"conf is of a unknown class instance"); - ICFolderDescription orgDescription = curConf.getRootFolderDescription(); - curConf.setDescription("A nice description"); - ICFolderDescription newDescription = curConf.getRootFolderDescription(); - } - } - -} diff --git a/io.sloeber.autoBuild.ui/.classpath b/io.sloeber.autoBuild.ui/.classpath index 3628e3368..35386b94b 100644 --- a/io.sloeber.autoBuild.ui/.classpath +++ b/io.sloeber.autoBuild.ui/.classpath @@ -1,6 +1,6 @@ - + diff --git a/io.sloeber.autoBuild.ui/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.autoBuild.ui/.settings/org.eclipse.jdt.core.prefs index 62ef3488c..23fa13b17 100644 --- a/io.sloeber.autoBuild.ui/.settings/org.eclipse.jdt.core.prefs +++ b/io.sloeber.autoBuild.ui/.settings/org.eclipse.jdt.core.prefs @@ -1,9 +1,9 @@ eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=17 -org.eclipse.jdt.core.compiler.compliance=17 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=enabled -org.eclipse.jdt.core.compiler.source=17 +org.eclipse.jdt.core.compiler.source=21 diff --git a/io.sloeber.autoBuild.ui/META-INF/MANIFEST.MF b/io.sloeber.autoBuild.ui/META-INF/MANIFEST.MF index 00fec2362..60e7d1c63 100644 --- a/io.sloeber.autoBuild.ui/META-INF/MANIFEST.MF +++ b/io.sloeber.autoBuild.ui/META-INF/MANIFEST.MF @@ -17,7 +17,7 @@ Require-Bundle: org.eclipse.tools.templates.ui, org.eclipse.core.filesystem, io.sloeber.autoBuild;bundle-version="4.4.1", org.eclipse.tools.templates.core;bundle-version="2.0.0" -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Vendor: Sloeber.io Bundle-ActivationPolicy: lazy Bundle-Activator: io.sloeber.autoBuild.ui.internal.Activator diff --git a/io.sloeber.autoBuild.ui/build.properties b/io.sloeber.autoBuild.ui/build.properties index 0f364769b..b89543b23 100644 --- a/io.sloeber.autoBuild.ui/build.properties +++ b/io.sloeber.autoBuild.ui/build.properties @@ -5,5 +5,6 @@ bin.includes = .,\ plugin.properties,\ META-INF/,\ OSGI-INF/,\ - OSGI-INF/l10n/bundle.properties + OSGI-INF/l10n/bundle.properties,\ + icons/ jars.compile.order = . diff --git a/io.sloeber.autoBuild.ui/src/io/sloeber/autoBuild/ui/tabs/ToolSettingsTab.java b/io.sloeber.autoBuild.ui/src/io/sloeber/autoBuild/ui/tabs/ToolSettingsTab.java index 8b955e28a..09bd26406 100644 --- a/io.sloeber.autoBuild.ui/src/io/sloeber/autoBuild/ui/tabs/ToolSettingsTab.java +++ b/io.sloeber.autoBuild.ui/src/io/sloeber/autoBuild/ui/tabs/ToolSettingsTab.java @@ -216,7 +216,7 @@ public void controlResized(ControlEvent e) { } else { //the line below is only here for development so I know there will only be resources //TODO remove the line below after evaluation this never ever happens - System.err.println("Element should be resource " + pageElement); + System.err.println("Element should be resource " + pageElement); //$NON-NLS-1$ } setValues(); @@ -280,17 +280,6 @@ protected void updateTipText(String name, String tip) { tipText.update(); } - /* (non-Javadoc) - * Method resetTipText - * @since 7.0 - */ - private void resetTipText() { - if (tipText == null) { - return; - } - tipText.setText(Messages.ToolSettingsTab_0); - tipText.update(); - } /* (non-Javadoc) * Method displayOptionsForCategory @@ -411,7 +400,7 @@ public void modifyText(ModifyEvent e) { } } - Label label = stringField.getLabelControl(mySettingsPageContainer); + //Label label = stringField.getLabelControl(mySettingsPageContainer); Text text = stringField.getTextControl(mySettingsPageContainer); text.setText(optionValue); // if(pageHasToolTipBox) diff --git a/io.sloeber.autoBuild/.classpath b/io.sloeber.autoBuild/.classpath index 065ac06e1..e54fbc930 100644 --- a/io.sloeber.autoBuild/.classpath +++ b/io.sloeber.autoBuild/.classpath @@ -2,6 +2,6 @@ - + diff --git a/io.sloeber.autoBuild/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.autoBuild/.settings/org.eclipse.jdt.core.prefs index 62ef3488c..23fa13b17 100644 --- a/io.sloeber.autoBuild/.settings/org.eclipse.jdt.core.prefs +++ b/io.sloeber.autoBuild/.settings/org.eclipse.jdt.core.prefs @@ -1,9 +1,9 @@ eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=17 -org.eclipse.jdt.core.compiler.compliance=17 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=enabled -org.eclipse.jdt.core.compiler.source=17 +org.eclipse.jdt.core.compiler.source=21 diff --git a/io.sloeber.autoBuild/META-INF/MANIFEST.MF b/io.sloeber.autoBuild/META-INF/MANIFEST.MF index 3b583249f..341912e99 100644 --- a/io.sloeber.autoBuild/META-INF/MANIFEST.MF +++ b/io.sloeber.autoBuild/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: Sloeber auto Build Bundle-SymbolicName: io.sloeber.autoBuild;singleton:=true Bundle-Version: 5.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-ActivationPolicy: lazy Bundle-ClassPath: . Require-Bundle: org.eclipse.cdt.core;bundle-version="7.0.0", diff --git a/io.sloeber.autoBuild/build.properties b/io.sloeber.autoBuild/build.properties index 9bc5fc8ce..15072b461 100644 --- a/io.sloeber.autoBuild/build.properties +++ b/io.sloeber.autoBuild/build.properties @@ -10,6 +10,5 @@ bin.includes = .,\ icons/ jars.compile.order = . src.includes = schema/,\ - src/,\ template/,\ icons/ diff --git a/io.sloeber.autoBuild/plugin.xml b/io.sloeber.autoBuild/plugin.xml index fea1e11bf..169fce6c8 100644 --- a/io.sloeber.autoBuild/plugin.xml +++ b/io.sloeber.autoBuild/plugin.xml @@ -2072,7 +2072,7 @@ diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/api/AutoBuildCommon.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/api/AutoBuildCommon.java index c6af150d7..5980e8dc5 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/api/AutoBuildCommon.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/api/AutoBuildCommon.java @@ -368,7 +368,7 @@ static public String GetNiceFileName(IFolder buildPath, IFile path) { static public String GetNiceFileName(IPath buildPath, IPath filePath) { String ret; if (buildPath.isPrefixOf(filePath) || buildPath.removeLastSegments(3).isPrefixOf(filePath)) { - ret = filePath.makeRelativeTo(buildPath).toString(); + ret = filePath.makeRelativeTo(buildPath).toOSString(); } else { ret = filePath.toString(); } diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/api/IAutoBuildConfigurationDescription.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/api/IAutoBuildConfigurationDescription.java index 4531a5c58..812017332 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/api/IAutoBuildConfigurationDescription.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/api/IAutoBuildConfigurationDescription.java @@ -13,11 +13,14 @@ import org.eclipse.cdt.core.settings.model.CSourceEntry; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.cdt.core.settings.model.ICProjectDescription; +import org.eclipse.cdt.core.settings.model.ICProjectDescriptionManager; import org.eclipse.cdt.core.settings.model.ICSettingEntry; import org.eclipse.cdt.core.settings.model.ICSourceEntry; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IProgressMonitor; + import io.sloeber.autoBuild.buildTools.api.IBuildTools; import io.sloeber.autoBuild.buildTools.api.IBuildToolsManager.ToolFlavour; import io.sloeber.autoBuild.integration.AutoBuildConfigurationDescription; @@ -31,7 +34,8 @@ public interface IAutoBuildConfigurationDescription { public static IAutoBuildConfigurationDescription getActiveConfig(IProject project, boolean write) { CoreModel coreModel = CoreModel.getDefault(); - ICProjectDescription projectDescription = coreModel.getProjectDescription(project, write); + ICProjectDescription projectDescription =coreModel.getProjectDescriptionManager().getProjectDescription(project, ICProjectDescriptionManager.GET_IF_LOADDED); + //ICProjectDescription projectDescription = coreModel.getProjectDescription(project, write); return getActiveConfig(projectDescription); } @@ -49,7 +53,6 @@ public static IAutoBuildConfigurationDescription getConfig(ICConfigurationDescri return null; } AutoBuildConfigurationDescription ret = (AutoBuildConfigurationDescription) confDesc.getConfigurationData(); - // ret.setWritable(!confDesc.isReadOnly()); return ret; } @@ -453,5 +456,13 @@ public static ICSourceEntry[] getResolvedSourceEntries(IAutoBuildConfigurationDe */ public LinkedHashMap getPostbuildSteps(); + /*** + * delete the build folder + * Not actually deletes the build folder but all the members. + * + * @param monitor + */ + void deleteBuildFolder(IProgressMonitor monitor); + } diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/CDTBuildTools.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/CDTBuildTools.java index d0d001d61..ce5c929d0 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/CDTBuildTools.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/CDTBuildTools.java @@ -96,7 +96,7 @@ public String getPathExtension() { @Override public String getDiscoveryCommand(ToolType toolType) { - return getToolLocation().append( getCommand(toolType)).toString() + DISCOVERY_PARAMETERS; + return getToolLocation().append( getCommand(toolType)).toOSString() + DISCOVERY_PARAMETERS; } @Override diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/MinGW32ToolsProvider.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/MinGW32ToolsProvider.java index f43592da1..b35a7ead6 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/MinGW32ToolsProvider.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/MinGW32ToolsProvider.java @@ -36,7 +36,7 @@ private void findTools() { try { myMinGWHome = org.eclipse.cdt.internal.core.MinGW.getMinGWHome(); } - catch(@SuppressWarnings("unused") Exception e) { + catch( Exception e) { //ignore as this fails in maven build due to lack of gui and as such registry //is not available e.printStackTrace(); diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/MinGWBuildTools.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/MinGWBuildTools.java index a14f19b1d..34e94c64d 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/MinGWBuildTools.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/buildTools/internal/MinGWBuildTools.java @@ -92,7 +92,7 @@ public String getPathExtension() { @Override public String getDiscoveryCommand(ToolType toolType) { - return getToolLocation().append( getCommand(toolType)).toString() +DISCOVERY_PARAMETERS; + return getToolLocation().append( getCommand(toolType)).toOSString() +DISCOVERY_PARAMETERS; } @Override diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/core/Messages.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/core/Messages.java index 6e7fffddb..da0e8076f 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/core/Messages.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/core/Messages.java @@ -20,7 +20,6 @@ public class Messages extends NLS { public static String ManagedMakeBuilder_message_no_build; public static String ManagedMakeBuilder_message_error; public static String ManagedMakeBuilder_message_error_build; - // public static String ManagedMakeBuilder_message_error_refresh; public static String ManagedMakeBuilder_message_undefined_build_command; public static String ManagedMakeBuilder_message_finished; public static String ManagedMakeBuilder_message_cancelled; @@ -122,7 +121,6 @@ public class Messages extends NLS { public static String GeneratedMakefileBuilder_cleanSelectedFiles; public static String FolderInfo_4; public static String GnuLinkOutputNameProvider_0; - public static String CommonBuilder_1; public static String CommonBuilder_2; public static String CommonBuilder_6; public static String CommonBuilder_7; @@ -140,18 +138,22 @@ public class Messages extends NLS { public static String ResourceChangeHandler2_0; public static String ToolInfo_0; public static String ToolInfo_1; - public static String AbstractBuiltinSpecsDetector_AddScannerDiscoveryMarkers; public static String AbstractBuiltinSpecsDetector_ClearingMarkers; public static String AbstractBuiltinSpecsDetector_DiscoverBuiltInSettingsJobName; - public static String AbstractBuiltinSpecsDetector_RunningScannerDiscovery; - public static String AbstractBuiltinSpecsDetector_ScannerDiscoveryMarkerLocationPreferences; - public static String AbstractBuiltinSpecsDetector_ScannerDiscoveryMarkerLocationProperties; public static String AbstractBuiltinSpecsDetector_ScannerDiscoveryTaskTitle; public static String AbstractBuiltinSpecsDetector_SerializingResults; public static String ExternalBuilderName; public static String InternalBuilderName; public static String InternalBuildRunner_NoNeedToRun; + + public static String ScannerDiscoveryMarkerLocationPreferences; + + public static String ScannerDiscoveryMarkerLocationProperties; + + public static String AddScannerDiscoveryMarkers; + + public static String RunningScannerDiscovery; static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/core/messages.properties b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/core/messages.properties index 0e54f6ea3..f7ec54e3c 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/core/messages.properties +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/core/messages.properties @@ -150,7 +150,6 @@ CfgScannerConfigUtil_ErrorNotSupported=Only type {0} is supported in this method GeneratedMakefileBuilder_cleanSelectedFiles=Cleaning Selected Files FolderInfo_4=converter invocation failed GnuLinkOutputNameProvider_0=tool parent must be one of configuration, toolchain, or resource configuration -CommonBuilder_1=customized builder created for builder that does not support customization CommonBuilder_2=request for building non active configuration for the builder that does not support this CommonBuilder_6=Time consumed: {0} ms. \u0020 CommonBuilder_7=Info: Parallel threads used: {0} @@ -171,17 +170,16 @@ ToolInfo_0=conversion failure ToolInfo_1=the tool is removed #Language settings providers messages -AbstractBuiltinSpecsDetector_AddScannerDiscoveryMarkers=Adding Scanner Discovery markers +AddScannerDiscoveryMarkers=Adding Scanner Discovery markers AbstractBuiltinSpecsDetector_ClearingMarkers=Clearing markers for {0} AbstractBuiltinSpecsDetector_DiscoverBuiltInSettingsJobName=Discover compiler built-in language settings -AbstractBuiltinSpecsDetector_RunningScannerDiscovery=Running scanner discovery: {0} -AbstractBuiltinSpecsDetector_ScannerDiscoveryMarkerLocationPreferences=Preferences, C++/Build/Settings/Discovery, [{0}] options -AbstractBuiltinSpecsDetector_ScannerDiscoveryMarkerLocationProperties=Project Properties, C++ Preprocessor Include.../Providers, [{0}] options +RunningScannerDiscovery=Running scanner discovery: {0} +ScannerDiscoveryMarkerLocationPreferences=Preferences, C++/Build/Settings/Discovery, [{0}] options +ScannerDiscoveryMarkerLocationProperties=Project Properties, C++ Preprocessor Include.../Providers, [{0}] options AbstractBuiltinSpecsDetector_ScannerDiscoveryTaskTitle=CDT Scanner Discovery AbstractBuiltinSpecsDetector_SerializingResults=Serializing results - ExternalBuilderName=Make builder InternalBuilderName=Internal builder -InternalBuildRunner_NoNeedToRun=No need to run +InternalBuildRunner_NoNeedToRun=No need to run diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/internal/AutoBuildLanguageSettingsProvider.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/AutoBuildLanguageSettingsProvider.java similarity index 90% rename from io.sloeber.autoBuild/src/io/sloeber/autoBuild/internal/AutoBuildLanguageSettingsProvider.java rename to io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/AutoBuildLanguageSettingsProvider.java index d4cf99ea8..1c17bb1af 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/internal/AutoBuildLanguageSettingsProvider.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/AutoBuildLanguageSettingsProvider.java @@ -12,13 +12,14 @@ * Andrew Gvozdev - initial API and implementation *******************************************************************************/ -package io.sloeber.autoBuild.internal; +package io.sloeber.autoBuild.extensionPoint.providers; import static io.sloeber.autoBuild.helpers.api.AutoBuildConstants.*; import java.io.File; import java.io.IOException; import java.net.URL; +import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; @@ -65,7 +66,8 @@ import io.sloeber.autoBuild.api.AutoBuildCommon; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; import io.sloeber.autoBuild.core.Activator; -import io.sloeber.autoBuild.extensionPoint.providers.InternalBuildRunner; +import io.sloeber.autoBuild.core.Messages; +import io.sloeber.autoBuild.internal.AutoBuildRunnerHelper; import io.sloeber.autoBuild.schema.api.IOption; /** @@ -73,9 +75,10 @@ */ public class AutoBuildLanguageSettingsProvider extends AbstractExecutableExtensionBase implements ILanguageSettingsBroadcastingProvider { + private static final boolean LOG_TO_STD_OUT =false; - private static final String SCANNER_DISCOVERY_CONSOLE = "org.eclipse.cdt.managedbuilder.ScannerDiscoveryConsole"; //$NON-NLS-1$ - private static final String SCANNER_DISCOVERY_GLOBAL_CONSOLE = "org.eclipse.cdt.managedbuilder.ScannerDiscoveryGlobalConsole"; //$NON-NLS-1$ + private static final String SCANNER_DISCOVERY_CONSOLE = "io.Sloeber.autoBuild.ScannerDiscoveryConsole"; //$NON-NLS-1$ + private static final String SCANNER_DISCOVERY_GLOBAL_CONSOLE = "io.Sloeber.autoBuild.ScannerDiscoveryGlobalConsole"; //$NON-NLS-1$ private static final String DEFAULT_CONSOLE_ICON = "icons/obj16/inspect_sys.gif"; //$NON-NLS-1$ private static final String GMAKE_ERROR_PARSER_ID = "org.eclipse.cdt.core.GmakeErrorParser"; //$NON-NLS-1$ @@ -101,10 +104,10 @@ public void addMarker(IResource rc, int lineNumber, String errorDesc, int severi @Override public void addMarker(final ProblemMarkerInfo problemMarkerInfo) { final String providerId = getId(); + final String providerName=getName(); // Add markers in a job to avoid deadlocks Job markerJob = new Job( - // ManagedMakeMessages.getResourceString( - "AbstractBuiltinSpecsDetector.AddScannerDiscoveryMarkers") { //$NON-NLS-1$ + Messages.AddScannerDiscoveryMarkers) { @Override protected IStatus run(IProgressMonitor monitor) { // Avoid duplicates as different languages can generate identical errors @@ -133,14 +136,12 @@ protected IStatus run(IProgressMonitor monitor) { marker.setAttribute(SDMarkerGenerator.ATTR_PROVIDER, providerId); if (problemMarkerInfo.file instanceof IWorkspaceRoot) { - String msgPreferences = // ManagedMakeMessages.getFormattedString( - "AbstractBuiltinSpecsDetector.ScannerDiscoveryMarkerLocationPreferences"; - // , //$NON-NLS-1$ providerName); + String msgPreferences = MessageFormat.format( + Messages.ScannerDiscoveryMarkerLocationPreferences, providerName); marker.setAttribute(IMarker.LOCATION, msgPreferences); } else { - String msgProperties = // ManagedMakeMessages.getFormattedString( - "AbstractBuiltinSpecsDetector.ScannerDiscoveryMarkerLocationProperties"; - // //$NON-NLS-1$ providerName); + String msgProperties = MessageFormat.format( + Messages.ScannerDiscoveryMarkerLocationProperties, providerName); marker.setAttribute(IMarker.LOCATION, msgProperties); } } catch (CoreException e) { @@ -252,8 +253,9 @@ public List getSettingEntries(ICConfigurationDescription if (discoveryCommand == null || discoveryCommand.isBlank()) { return LanguageSettingsStorage.getPooledList(list); } + discoveryCommand=discoveryCommand.trim(); List cachedList=myDiscoveryCache.get(discoveryCommand); - if ( cachedList== null || cachedList.size()==0 ) { + if ( cachedList== null ) { myDiscoveryCache.put(discoveryCommand, runForLanguage(languageId, discoveryCommand, autoConf, autoConf.getProject(), new NullProgressMonitor())); } @@ -298,10 +300,8 @@ private List runForLanguage(String currentLanguageId, St try (AutoBuildRunnerHelper buildRunnerHelper = new AutoBuildRunnerHelper(currentProject);) { SubMonitor subMonitor = SubMonitor.convert(monitor, - // ManagedMakeMessages.getFormattedString( - "AbstractBuiltinSpecsDetector.RunningScannerDiscovery", //$NON-NLS-1$ - // getName()), - 100); + MessageFormat.format( + Messages.RunningScannerDiscovery, getName()), 100); IConsole console; if (isConsoleEnabled) { @@ -331,11 +331,12 @@ private List runForLanguage(String currentLanguageId, St buildRunnerHelper.prepareStreams(epm, parsers, console, subMonitor.split(TICKS_OUTPUT_PARSING)); - buildRunnerHelper.greeting(// ManagedMakeMessages - // .getFormattedString( - "AbstractBuiltinSpecsDetector.RunningScannerDiscovery"//$NON-NLS-1$ - // , getName()) + buildRunnerHelper.greeting(MessageFormat.format( + Messages.RunningScannerDiscovery , getName()) ); + if(LOG_TO_STD_OUT) { + System.out.println(currentCommandResolved); + } InternalBuildRunner.launchCommand(currentCommandResolved, autoConf, monitor, buildRunnerHelper); @@ -412,7 +413,9 @@ public void startup(ICConfigurationDescription cfgDescription, IWorkingDirectory @Override public boolean processLine(String line) { - // System.out.println(line); + if(LOG_TO_STD_OUT) { + System.out.println(line); + } for (Entry curMatcher : outputMatchers.entrySet()) { Pattern pat = curMatcher.getKey(); diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/AutoBuildMakeRule.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/AutoBuildMakeRule.java index f3f1ac5cc..4635860cc 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/AutoBuildMakeRule.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/AutoBuildMakeRule.java @@ -288,7 +288,7 @@ public String[] getRecipes(IFolder buildFolder, AutoBuildConfigurationDescriptio IFile file = project.getWorkspace().getRoot() .getFile(IPath.forPosix(curEntry.getValue())); includeFiles = includeFiles + WHITESPACE + DOUBLE_QUOTE + CMD_LINE_INCLUDE_FILE - + file.getLocation().toString() + DOUBLE_QUOTE; + + file.getLocation().toOSString() + DOUBLE_QUOTE; break; } case ICSettingEntry.INCLUDE_PATH: { @@ -296,11 +296,11 @@ public String[] getRecipes(IFolder buildFolder, AutoBuildConfigurationDescriptio .getFolder(IPath.forPosix(curEntry.getValue())).getLocation(); if(path==null) { //Log error to allow for investigation - Activator.log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, "No location found for "+curEntry.getValue())); + Activator.log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, "No location found for "+curEntry.getValue())); //$NON-NLS-1$ }else { includePath = includePath + WHITESPACE + DOUBLE_QUOTE + CMD_LINE_INCLUDE_FOLDER - + path.toString() + DOUBLE_QUOTE; + + path.toOSString() + DOUBLE_QUOTE; } break; } diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/BuildRunnerForMake.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/BuildRunnerForMake.java index 75216a1e4..454f973f6 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/BuildRunnerForMake.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/BuildRunnerForMake.java @@ -64,14 +64,8 @@ public class BuildRunnerForMake implements IBuildRunner { @Override public void invokeClean(int kind, IAutoBuildConfigurationDescription autoData, IMarkerGenerator markerGenerator, IConsole console, IProgressMonitor monitor) throws CoreException { - IFolder buildRoot = autoData.getBuildFolder(); - if(!buildRoot.exists()) { - return ; - } - //Do not delete the build folder as it may be in use with other processes (like discovery) - for(IResource curMember:buildRoot.members()) { - curMember.delete(true, monitor); - } + autoData.deleteBuildFolder(monitor); + //buildRoot.create(true, true, monitor); // for now I do not run make clean due to the fact rm -f is probably not on the system path //return invokeBuild(IncrementalProjectBuilder.CLEAN_BUILD, envp, autoData, markerGenerator, console, monitor); diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/CommonBuilder.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/CommonBuilder.java index fe65ccd55..803b63b32 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/CommonBuilder.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/CommonBuilder.java @@ -311,6 +311,8 @@ private static Set getConfigsToBuild(IProject cfgToBuild.add((AutoBuildConfigurationDescription) IAutoBuildConfigurationDescription .getActiveConfig(project, false)); } + //remove null configurations that may have been added + cfgToBuild.remove(null); return cfgToBuild; } diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/InternalBuildRunner.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/InternalBuildRunner.java index 3cbd65702..3f88bc866 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/InternalBuildRunner.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/InternalBuildRunner.java @@ -44,7 +44,6 @@ import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; @@ -86,16 +85,7 @@ private static void createFolder(IFolder folder, boolean force, boolean local, I @Override public void invokeClean(int kind, IAutoBuildConfigurationDescription autoData, IMarkerGenerator markerGenerator, IConsole console, IProgressMonitor monitor) throws CoreException { - IFolder buildRoot = autoData.getBuildFolder(); - if(!buildRoot.exists()) { - return ; - } - //Do not delete the build folder as it may be in use with other processes (like discovery) - for(IResource curMember:buildRoot.members()) { - curMember.delete(true, monitor); - } -// buildRoot.delete(true, monitor); -// buildRoot.create(true, true, monitor); + autoData.deleteBuildFolder(monitor); return ; } @@ -144,6 +134,7 @@ public boolean invokeBuild(int kind, String targetName, IAutoBuildConfigurationD epm.deferDeDuplication(); int sequenceID = -1; boolean lastSequenceID = true; + myHasBuildError = false; // Run preBuildStep if existing LinkedHashMap preBuildSteps = autoData.getPrebuildSteps(); @@ -156,13 +147,14 @@ public boolean invokeBuild(int kind, String targetName, IAutoBuildConfigurationD } buildRunnerHelper.toConsole(command); if (launchCommand(command, autoData, monitor, buildRunnerHelper) != 0) { + myHasBuildError = true; if (autoData.stopOnFirstBuildError()) { return false; } } } - myHasBuildError = false; + do { sequenceID++; lastSequenceID = true; @@ -227,35 +219,36 @@ public boolean invokeBuild(int kind, String targetName, IAutoBuildConfigurationD lastSequenceID = true; } } while (!(lastSequenceID || myHasBuildError)); - // Run postBuildStep if existing - LinkedHashMap postBuildSteps = autoData.getPostbuildSteps(); - for (Entry step:postBuildSteps.entrySet()) { - String announcement = step.getKey(); - String command = step.getValue(); + // Run postBuildStep if existing and no error + if (!myHasBuildError) { + LinkedHashMap postBuildSteps = autoData.getPostbuildSteps(); + for (Entry step : postBuildSteps.entrySet()) { + String announcement = step.getKey(); + String command = step.getValue(); - if (!announcement.isEmpty()) { - buildRunnerHelper.toConsole(announcement); - } - buildRunnerHelper.toConsole(command); - if (launchCommand(command, autoData, monitor, buildRunnerHelper) != 0) { - if (autoData.stopOnFirstBuildError()) { - return false; + if (!announcement.isEmpty()) { + buildRunnerHelper.toConsole(announcement); + } + buildRunnerHelper.toConsole(command); + if (launchCommand(command, autoData, monitor, buildRunnerHelper) != 0) { + if (autoData.stopOnFirstBuildError()) { + return false; + } } } - } - - String postBuildStep = autoData.getPostbuildStep(); - postBuildStep = resolve(postBuildStep, EMPTY_STRING, WHITESPACE, autoData); - if (!postBuildStep.isEmpty()) { - String announcement = autoData.getPostBuildAnouncement(); - if (!announcement.isEmpty()) { - buildRunnerHelper.toConsole(announcement); - } - buildRunnerHelper.toConsole(postBuildStep); - if (launchCommand(postBuildStep, autoData, monitor, buildRunnerHelper) != 0) { - return false; + String postBuildStep = autoData.getPostbuildStep(); + postBuildStep = resolve(postBuildStep, EMPTY_STRING, WHITESPACE, autoData); + if (!postBuildStep.isEmpty()) { + String announcement = autoData.getPostBuildAnouncement(); + if (!announcement.isEmpty()) { + buildRunnerHelper.toConsole(announcement); + } + buildRunnerHelper.toConsole(postBuildStep); + if (launchCommand(postBuildStep, autoData, monitor, buildRunnerHelper) != 0) { + return false; + } } } } diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/MakefileGenerator.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/MakefileGenerator.java index 08af9ed28..3c751d5d9 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/MakefileGenerator.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/extensionPoint/providers/MakefileGenerator.java @@ -6,6 +6,7 @@ import java.text.MessageFormat; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; @@ -309,29 +310,7 @@ protected StringBuffer topMakeGetRMCommand(Set myDependencyMacros) { return (buffer.append(NEWLINE)); } - protected String topMakeGetPreBuildStep() { - String prebuildStep = myAutoBuildConfData.getPrebuildStep(); - // JABA issue927 adding recipe.hooks.sketch.prebuild.NUMBER.pattern as cdt - // prebuild command if needed - // ICConfigurationDescription confDesc = - // ManagedBuildManager.getDescriptionForConfiguration(config); - // String sketchPrebuild = - // io.sloeber.core.common.Common.getBuildEnvironmentVariable(confDesc, - // "sloeber.prebuild", - // new String(), false); - String sketchPrebuild = getVariableValue("sloeber.prebuild", EMPTY_STRING, true, myAutoBuildConfData); //$NON-NLS-1$ - if (!sketchPrebuild.isEmpty()) { - if (!prebuildStep.isEmpty()) { - prebuildStep = prebuildStep + NEWLINE+TAB + sketchPrebuild; - } else { - prebuildStep = sketchPrebuild; - } - } - // end off JABA issue927 - // try to resolve the build macros in the prebuild step - prebuildStep = resolve(prebuildStep, EMPTY_STRING, WHITESPACE, myAutoBuildConfData); - return prebuildStep.trim(); - } + protected StringBuffer topMakeGetIncludeDependencies() { StringBuffer buffer = new StringBuffer(); @@ -339,22 +318,32 @@ protected StringBuffer topMakeGetIncludeDependencies() { // Add the comment for the "All" target buffer.append(COMMENT_START).append(MakefileGenerator_comment_build_alltarget).append(NEWLINE); - String prebuildStep = topMakeGetPreBuildStep(); - String postbuildStep = resolve(myAutoBuildConfData.getPostbuildStep(), EMPTY_STRING, WHITESPACE, - myAutoBuildConfData); - if (prebuildStep.isBlank() && postbuildStep.isBlank()) { + LinkedHashMap prebuildSteps = myAutoBuildConfData.getPrebuildSteps(); + LinkedHashMap postbuildSteps = myAutoBuildConfData.getPostbuildSteps(); + if (prebuildSteps.size()== 0 && postbuildSteps.size()==0) { buffer.append(TARGET_ALL).append(COLON).append(WHITESPACE).append(MAINBUILD).append(NEWLINE); } else { + // add prebuild announce data + String preannouncebuildStep = myAutoBuildConfData.getPreBuildAnouncement(); + if (preannouncebuildStep.length() > 0) { + buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(escapedEcho(preannouncebuildStep)); + } + // Add the prebuild recipes buffer.append(TARGET_ALL).append(COLON).append(NEWLINE); - if (!prebuildStep.isBlank()) { - buffer.append(TAB).append(MAKE).append(WHITESPACE).append(NO_PRINT_DIR).append(WHITESPACE) - .append(PREBUILD).append(NEWLINE); + for (String curRecipe : prebuildSteps.values()) { + buffer.append(TAB).append(WHITESPACE).append(curRecipe).append(NEWLINE); } + // Add the make all command buffer.append(TAB).append(MAKE).append(WHITESPACE).append(NO_PRINT_DIR).append(WHITESPACE).append(MAINBUILD) .append(NEWLINE); - if (!postbuildStep.isBlank()) { - buffer.append(TAB).append(MAKE).append(WHITESPACE).append(NO_PRINT_DIR).append(WHITESPACE) - .append(POSTBUILD).append(NEWLINE); + // add postbuild announce data + String postannouncebuildStep = myAutoBuildConfData.getPostBuildAnouncement(); + if (postannouncebuildStep.length() > 0) { + buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(escapedEcho(postannouncebuildStep)); + } + // Add the postbuild recipes + for (String curRecipe : postbuildSteps.values()) { + buffer.append(TAB).append(WHITESPACE).append(curRecipe).append(NEWLINE); } } @@ -396,31 +385,31 @@ protected StringBuffer topMakeGetTargets() { } buffer.append(NEWLINE).append(NEWLINE); - String prebuildStep = topMakeGetPreBuildStep(); - if (prebuildStep.length() > 0) { - - String preannouncebuildStep = myAutoBuildConfData.getPreBuildAnouncement(); - buffer.append(PREBUILD).append(COLON).append(NEWLINE); - if (preannouncebuildStep.length() > 0) { - buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(escapedEcho(preannouncebuildStep)); - } - buffer.append(TAB).append(DASH).append(prebuildStep).append(NEWLINE); - buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(ECHO_BLANK_LINE).append(NEWLINE); - } +// String prebuildStep = topMakeGetPreBuildStep(); +// if (prebuildStep.length() > 0) { +// +// String preannouncebuildStep = myAutoBuildConfData.getPreBuildAnouncement(); +// buffer.append(PREBUILD).append(COLON).append(NEWLINE); +// if (preannouncebuildStep.length() > 0) { +// buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(escapedEcho(preannouncebuildStep)); +// } +// buffer.append(TAB).append(DASH).append(prebuildStep).append(NEWLINE); +// buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(ECHO_BLANK_LINE).append(NEWLINE); +// } - String postbuildStep = myAutoBuildConfData.getPostbuildStep(); - postbuildStep = resolve(postbuildStep, EMPTY_STRING, WHITESPACE, myAutoBuildConfData); - postbuildStep = postbuildStep.trim(); - // Add the postbuild step, if specified - if (postbuildStep.length() > 0) { - String postannouncebuildStep = myAutoBuildConfData.getPostBuildAnouncement(); - buffer.append(POSTBUILD).append(COLON).append(NEWLINE); - if (postannouncebuildStep.length() > 0) { - buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(escapedEcho(postannouncebuildStep)); - } - buffer.append(TAB).append(DASH).append(postbuildStep).append(NEWLINE); - buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(ECHO_BLANK_LINE).append(NEWLINE); - } +// String postbuildStep = myAutoBuildConfData.getPostbuildStep(); +// postbuildStep = resolve(postbuildStep, EMPTY_STRING, WHITESPACE, myAutoBuildConfData); +// postbuildStep = postbuildStep.trim(); +// // Add the postbuild step, if specified +// if (postbuildStep.length() > 0) { +// String postannouncebuildStep = myAutoBuildConfData.getPostBuildAnouncement(); +// buffer.append(POSTBUILD).append(COLON).append(NEWLINE); +// if (postannouncebuildStep.length() > 0) { +// buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(escapedEcho(postannouncebuildStep)); +// } +// buffer.append(TAB).append(DASH).append(postbuildStep).append(NEWLINE); +// buffer.append(TAB).append(DASH).append(AT_SYMBOL).append(ECHO_BLANK_LINE).append(NEWLINE); +// } return buffer; } @@ -562,34 +551,10 @@ public StringBuffer getRecipesInMakeFileStyle(IAutoBuildMakeRule makeRule) { .append(escapedEcho(MakefileGenerator_message_start_file + WHITESPACE + OUT_MACRO)); buffer.append(TAB).append(AT_SYMBOL).append(escapedEcho(tool.getAnnouncement())); - // // JABA add sketch.prebuild and postbuild if needed - // //TOFIX this should not be here - // if ("sloeber.ino".equals(fileName)) { //$NON-NLS-1$ - // - // // String sketchPrebuild = - // io.sloeber.core.common.Common.getBuildEnvironmentVariable(confDesc, - // // "sloeber.sketch.prebuild", new String(), true); //$NON-NLS-1$ - // // String sketchPostBuild = - // io.sloeber.core.common.Common.getBuildEnvironmentVariable(confDesc, - // // "sloeber.sketch.postbuild", new String(), true); //$NON-NLS-1$ - // String sketchPrebuild = resolve("sloeber.sketch.prebuild", EMPTY_STRING, - // WHITESPACE, autoBuildConfData); - // String sketchPostBuild = resolve("sloeber.sketch.postbuild", EMPTY_STRING, - // WHITESPACE,autoBuildConfData); - // if (!sketchPrebuild.isEmpty()) { - // buffer.append(TAB).append(sketchPrebuild); - // } - // buffer.append(TAB).append(buildCmd).append(NEWLINE); - // if (!sketchPostBuild.isEmpty()) { - // buffer.append(TAB).append(sketchPostBuild); - // } - // } else { for (String resolvedCommand : makeRule.getRecipes(myBuildRoot, myAutoBuildConfData)) { buffer.append(TAB).append(resolvedCommand); buffer.append(NEWLINE); } - // } - // // end JABA add sketch.prebuild and postbuild if needed buffer.append(NEWLINE); buffer.append(TAB).append(AT_SYMBOL) diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/helpers/api/AutoBuildConstants.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/helpers/api/AutoBuildConstants.java index 439cf8a92..45556d073 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/helpers/api/AutoBuildConstants.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/helpers/api/AutoBuildConstants.java @@ -43,6 +43,7 @@ public class AutoBuildConstants { public static final String PROCENT = "%"; public static final String SLACH = "/"; public static final String BACKSLACH = "\\"; + public static final String PATH_SEPERATOR=isWindows?BACKSLACH:SLACH; public static final String FALSE = "FALSE"; public static final String TRUE = "TRUE"; public static final String COLON = ":"; diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/helpers/api/KeyValueTree.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/helpers/api/KeyValueTree.java index ce318b6b0..a2e059f3d 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/helpers/api/KeyValueTree.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/helpers/api/KeyValueTree.java @@ -8,8 +8,6 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.TreeMap; - import org.apache.commons.io.FileUtils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildConfigurationDescription.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildConfigurationDescription.java index 70fa7140b..8ea885d05 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildConfigurationDescription.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildConfigurationDescription.java @@ -33,8 +33,10 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; import org.osgi.framework.Bundle; import io.sloeber.autoBuild.api.AutoBuildCommon; @@ -52,7 +54,6 @@ import io.sloeber.autoBuild.schema.api.IOption; import io.sloeber.autoBuild.schema.api.IProjectType; import io.sloeber.autoBuild.schema.api.ITool; -import io.sloeber.autoBuild.schema.internal.Configuration; public class AutoBuildConfigurationDescription extends AutoBuildResourceData implements IAutoBuildConfigurationDescription { @@ -108,7 +109,7 @@ public class AutoBuildConfigurationDescription extends AutoBuildResourceData private boolean myIsWritable = false; private boolean myForceCleanBeforeBuild = false; - public AutoBuildConfigurationDescription(Configuration config, IProject project, IBuildTools buildTools, + public AutoBuildConfigurationDescription(IConfiguration config, IProject project, IBuildTools buildTools, String rootCodeFolder) { initializeResourceData(project, rootCodeFolder, myBuildFolderString); myBuildTools = buildTools; @@ -532,6 +533,10 @@ public void setGenerateMakeFilesAUtomatically(boolean generateMakeFilesAUtomatic @Override public void setBuildFolderString(String buildFolder) { + //TODO is this the correct place to delete the old folder + if(buildFolder.equals(myBuildFolderString)) { + return; + } checkIfWeCanWrite(); IFolder oldBuildFolder = getBuildFolder(); if (oldBuildFolder != null && oldBuildFolder.exists()) { @@ -1125,16 +1130,33 @@ public void forceCleanBeforeBuild() { myForceCleanBeforeBuild = true; } - public void forceFullBuildIfNeeded(IProgressMonitor monitor) throws CoreException { + public void forceFullBuildIfNeeded(IProgressMonitor monitor) { if (myForceCleanBeforeBuild) { myForceCleanBeforeBuild = false; - IFolder buildFolder = getBuildFolder(); - if (buildFolder != null && buildFolder.exists()) { - buildFolder.delete(true, monitor); - } - + deleteBuildFolder(monitor); } + } + + @Override + public void deleteBuildFolder(IProgressMonitor monitor) { + //Do not delete the build folder as it may be in use with other processes (like discovery) + IFolder buildFolder = getBuildFolder(); + if (buildFolder != null && buildFolder.exists()) { + try { + for(IResource curMember:buildFolder.members()) { + try { + curMember.delete(true, monitor); + } catch (CoreException e) { + Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, + "Failed to delete member "+curMember.getName(), e)); //$NON-NLS-1$ + } + + } + } catch (CoreException e) { + e.printStackTrace(); + } + } } private static String getSpecFile(String languageId) { diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildManager.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildManager.java index a58c441b8..4e8f9d114 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildManager.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildManager.java @@ -266,8 +266,8 @@ public static Set getProjectTypes(String extensionPointID, String IProjectType projectType = AutoBuildManager.getProjectType(extensionPointID, extensionID, element.getAttribute(ID), true); if (projectType == null) { - System.err.println("project not found: extensionPoint ID " + extensionPointID + " and extension ID " - + extensionID + " and " + ID); + System.err.println("project not found: extensionPoint ID " + extensionPointID + " and extension ID " //$NON-NLS-1$ //$NON-NLS-2$ + + extensionID + " and " + ID); //$NON-NLS-1$ } else { ret.add(projectType); } diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildProjectGenerator.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildProjectGenerator.java index 7ce673e24..7e857377b 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildProjectGenerator.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/integration/AutoBuildProjectGenerator.java @@ -2,6 +2,7 @@ package io.sloeber.autoBuild.integration; import java.net.URI; +import java.util.HashSet; import java.util.List; import org.eclipse.cdt.core.CCProjectNature; @@ -30,13 +31,11 @@ import org.eclipse.tools.templates.core.IGenerator; import io.sloeber.autoBuild.api.AutoBuildCommon; -import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; import io.sloeber.autoBuild.api.ICodeProvider; import io.sloeber.autoBuild.buildTools.api.IBuildTools; import io.sloeber.autoBuild.core.Activator; import io.sloeber.autoBuild.schema.api.IConfiguration; import io.sloeber.autoBuild.schema.api.IProjectType; -import io.sloeber.autoBuild.schema.internal.Configuration; public class AutoBuildProjectGenerator implements IGenerator { private URI myLocationURI = null; @@ -63,13 +62,57 @@ public void generate(IProgressMonitor monitor) throws CoreException { @Override public void run(IProgressMonitor internalMonitor) throws CoreException { + + ICProjectDescriptionManager mngr = CoreModel.getDefault().getProjectDescriptionManager(); + IProjectType autoBuildProjType = AutoBuildManager.getProjectType(myProjectType.getExtensionPointID(), + myProjectType.getExtensionID(), myProjectType.getId(), true); + if (autoBuildProjType == null) { + // project type not found can not continue + IStatus status = new Status(IStatus.ERROR, Activator.getId(), + "Did not find the projectType with " + myProjectType.getId() + " for extension ID " //$NON-NLS-1$ //$NON-NLS-2$ + + myProjectType.getExtensionID() + " in extensionpointID " //$NON-NLS-1$ + + myProjectType.getExtensionPointID()); + CoreException exception = new CoreException(status); + throw (exception); + } + HashSet configNames = new HashSet<>(); + myProject = root.getProject(myProjectName); + if (myProject.exists()) { + // Update the existing configurations + ICProjectDescription orgdesc = mngr.getProjectDescription(myProject, false); + for (ICConfigurationDescription curConfig : orgdesc.getConfigurations()) { + configNames.add(curConfig.getName()); + } + myLocationURI=myProject.getLocationURI(); + //CDT reads the .cproject file when setting the configuration for making the delta + //and old stuff stays in it causing problems + //ICProject cProject = CoreModel.getDefault().getCModel().getCProject(myProject.getName()); + IFile CdtDotFile = myProject.getFile(".cproject"); //$NON-NLS-1$ + if(CdtDotFile.exists()) { + CdtDotFile.delete(true, monitor); + } + myProject.close(monitor); + myProject.delete(false, true, monitor); + + } else { + // Create new configurations based on the model configurations from the + // plugin.xml + IConfiguration[] modelConfigs = autoBuildProjType.getConfigurations(); + for (IConfiguration iConfig : modelConfigs) { + configNames.add(iConfig.getName()); + } + } + + + IProjectDescription description = workspace.newProjectDescription(myProjectName); if (myLocationURI != null) { description.setLocationURI(myLocationURI); } - myProject = root.getProject(myProjectName); + myProject.create(description, monitor); myProject.open(monitor); + CProjectNature.addCNature(myProject, monitor); if (CCProjectNature.CC_NATURE_ID.equals(myNatureID)) { CCProjectNature.addCCNature(myProject, monitor); @@ -77,7 +120,7 @@ public void run(IProgressMonitor internalMonitor) throws CoreException { AutoBuildNature.addNature(myProject, monitor); IContainer srcFolder = myProject; - if (myCodeRootFolder!=null && !myCodeRootFolder.isBlank()) { + if (myCodeRootFolder != null && !myCodeRootFolder.isBlank()) { IFolder actualFolder = myProject.getFolder(myCodeRootFolder); srcFolder = actualFolder; if (!srcFolder.exists()) { @@ -90,48 +133,42 @@ public void run(IProgressMonitor internalMonitor) throws CoreException { myProject = CCorePlugin.getDefault().createCDTProject(description, myProject, monitor); - ICProjectDescriptionManager mngr = CoreModel.getDefault().getProjectDescriptionManager(); + ICProjectDescription des = mngr.createProjectDescription(myProject, false, true); - IProjectType sloeberProjType = AutoBuildManager.getProjectType(myProjectType.getExtensionPointID(), - myProjectType.getExtensionID(), myProjectType.getId(), true); - if (sloeberProjType == null) { - // project type not found can not continue - IStatus status = new Status(IStatus.ERROR, Activator.getId(), - "Did not find the projectType with " + myProjectType.getId() + " for extension ID " //$NON-NLS-1$ //$NON-NLS-2$ - + myProjectType.getExtensionID() + " in extensionpointID " //$NON-NLS-1$ - + myProjectType.getExtensionPointID()); - CoreException exception = new CoreException(status); - throw (exception); - } - IConfiguration[] modelConfigs = sloeberProjType.getConfigurations(); - for (IConfiguration iConfig : modelConfigs) { - Configuration config = (Configuration) iConfig; + IConfiguration defaultConfig = autoBuildProjType.getConfigurations()[0]; + + for (String curConfigName : configNames) { + IConfiguration config = autoBuildProjType.getConfiguration(curConfigName); + if (config == null) { + config = defaultConfig; + } AutoBuildConfigurationDescription data = new AutoBuildConfigurationDescription(config, myProject, myBuldTools, myCodeRootFolder); assert (data != null); + data.setBuilder(data.getBuilder(myBuilderID)); ICConfigurationDescription cdtCfgDes = des .createConfiguration(AutoBuildConfigurationDescriptionProvider.CFG_DATA_PROVIDER_ID, data); + cdtCfgDes.setName(curConfigName); data.setCdtConfigurationDescription(cdtCfgDes); - data.setBuilder(data.getBuilder(myBuilderID)); // Set the language Settings - String[] defaultIds = iConfig.getDefaultLanguageSettingsProviderIds().toArray(new String[0]); + String[] defaultIds = config.getDefaultLanguageSettingsProviderIds().toArray(new String[0]); List providers = LanguageSettingsManager .createLanguageSettingsProviders(defaultIds); ILanguageSettingsProvidersKeeper languageKeeper = (ILanguageSettingsProvidersKeeper) cdtCfgDes; if (cdtCfgDes instanceof ILanguageSettingsProvidersKeeper) { languageKeeper.setLanguageSettingProviders(providers); } + AutoBuildCommon.createFolder(data.getBuildFolder()); } if (!myNeedsMoreWork) { des.setCdtProjectCreated(); } + des.setActiveConfiguration(des.getConfigurations()[0]); + des.setDefaultSettingConfiguration(des.getConfigurations()[0]); mngr.setProjectDescription(myProject, des); - for(ICConfigurationDescription curConfig:des.getConfigurations()) { - IAutoBuildConfigurationDescription autodesc=IAutoBuildConfigurationDescription.getConfig(curConfig); - AutoBuildCommon.createFolder( autodesc.getBuildFolder()); - } + } }; try { diff --git a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/schema/internal/Tool.java b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/schema/internal/Tool.java index 46fb4c759..61574cf9a 100644 --- a/io.sloeber.autoBuild/src/io/sloeber/autoBuild/schema/internal/Tool.java +++ b/io.sloeber.autoBuild/src/io/sloeber/autoBuild/schema/internal/Tool.java @@ -562,7 +562,7 @@ public String[] getRecipes(IAutoBuildConfigurationDescription autoBuildConfData, IPath toolPath = buildTools.getToolLocation(); if (toolPath != null && !toolPath.toString().isBlank()) { //store the path - toolCommandVars.put(CMD_LINE_TOOL_PATH, toolPath.toString().trim() + SLACH); + toolCommandVars.put(CMD_LINE_TOOL_PATH, toolPath.toOSString().trim() + PATH_SEPERATOR); } Map toolVariables = buildTools.getToolVariables(); if (toolVariables != null && toolVariables.size() > 0) { diff --git a/io.sloeber.core.nl1/.classpath b/io.sloeber.core.nl1/.classpath new file mode 100644 index 000000000..06514e04e --- /dev/null +++ b/io.sloeber.core.nl1/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/io.sloeber.core.nl1/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.core.nl1/.settings/org.eclipse.jdt.core.prefs index 27705a035..502263510 100644 --- a/io.sloeber.core.nl1/.settings/org.eclipse.jdt.core.prefs +++ b/io.sloeber.core.nl1/.settings/org.eclipse.jdt.core.prefs @@ -1,9 +1,18 @@ eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=21 org.eclipse.jdt.core.formatter.align_assignment_statements_on_columns=false org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.align_variable_declarations_on_columns=false org.eclipse.jdt.core.formatter.align_with_spaces=false +org.eclipse.jdt.core.formatter.alignment_for_additive_operator=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -11,21 +20,24 @@ org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_c org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_bitwise_operator=16 org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 org.eclipse.jdt.core.formatter.alignment_for_compact_loops=16 org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 org.eclipse.jdt.core.formatter.alignment_for_enum_constants=16 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0 +org.eclipse.jdt.core.formatter.alignment_for_logical_operator=16 org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 org.eclipse.jdt.core.formatter.alignment_for_module_statements=16 org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_multiplicative_operator=16 org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_string_concatenation=16 org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 @@ -117,11 +129,12 @@ org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_additive_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_bitwise_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert @@ -152,6 +165,8 @@ org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_after_logical_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_multiplicative_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert @@ -176,13 +191,17 @@ org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_relational_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_shift_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_string_concatenation=insert org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_additive_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_bitwise_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert @@ -230,6 +249,8 @@ org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do no org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_before_logical_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_multiplicative_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert @@ -266,9 +287,12 @@ org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not inser org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_relational_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_shift_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_string_concatenation=insert org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert @@ -307,9 +331,13 @@ org.eclipse.jdt.core.formatter.tabulation.char=tab org.eclipse.jdt.core.formatter.tabulation.size=4 org.eclipse.jdt.core.formatter.use_on_off_tags=false org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_additive_operator=true org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_bitwise_operator=true org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true +org.eclipse.jdt.core.formatter.wrap_before_logical_operator=true +org.eclipse.jdt.core.formatter.wrap_before_multiplicative_operator=true org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_before_string_concatenation=true org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true org.eclipse.jdt.core.javaFormatter=org.eclipse.jdt.core.defaultJavaFormatter diff --git a/io.sloeber.core.nl1/META-INF/MANIFEST.MF b/io.sloeber.core.nl1/META-INF/MANIFEST.MF index 8aad12868..b8205fddb 100644 --- a/io.sloeber.core.nl1/META-INF/MANIFEST.MF +++ b/io.sloeber.core.nl1/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Sloeber core language pack Bundle-SymbolicName: io.sloeber.core.nl1;singleton:=true -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Version: 5.0.0.qualifier Fragment-Host: io.sloeber.core Bundle-Vendor: Sloeber.io diff --git a/io.sloeber.core/.classpath b/io.sloeber.core/.classpath index 17a441d04..478470af0 100644 --- a/io.sloeber.core/.classpath +++ b/io.sloeber.core/.classpath @@ -1,5 +1,7 @@ + + @@ -7,14 +9,11 @@ - - - - + diff --git a/io.sloeber.core/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.core/.settings/org.eclipse.jdt.core.prefs index 96d2364f2..24e173460 100644 --- a/io.sloeber.core/.settings/org.eclipse.jdt.core.prefs +++ b/io.sloeber.core/.settings/org.eclipse.jdt.core.prefs @@ -10,11 +10,11 @@ org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=17 -org.eclipse.jdt.core.compiler.compliance=17 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=enabled -org.eclipse.jdt.core.compiler.source=17 +org.eclipse.jdt.core.compiler.source=21 diff --git a/io.sloeber.core/META-INF/MANIFEST.MF b/io.sloeber.core/META-INF/MANIFEST.MF index 1fddc2e65..c2dc81a5a 100644 --- a/io.sloeber.core/META-INF/MANIFEST.MF +++ b/io.sloeber.core/META-INF/MANIFEST.MF @@ -3,12 +3,11 @@ Bundle-ManifestVersion: 2 Bundle-Name: Arduino eclipse plugin Bundle-SymbolicName: io.sloeber.core;singleton:=true Bundle-Version: 5.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Vendor: Sloeber.io Bundle-ActivationPolicy: lazy Bundle-Activator: io.sloeber.core.Activator Bundle-ClassPath: ., - lib/jsch-0.1.55.jar, lib/jssc-2.9.4.jar, lib/jmdns-3.5.7.jar Require-Bundle: @@ -28,16 +27,12 @@ Require-Bundle: org.eclipse.ui.intro, io.sloeber.autoBuild, org.eclipse.cdt.make.core, - org.apache.commons.lang3;bundle-version="3.14.0" + org.apache.commons.lang3;bundle-version="3.14.0", + com.jcraft.jsch Export-Package: cc.arduino.packages;x-internal:=true, cc.arduino.packages.discoverers;x-internal:=true, cc.arduino.packages.ssh;x-internal:=true, - com.jcraft.jsch, - com.jcraft.jsch.jce;uses:="com.jcraft.jsch", - com.jcraft.jsch.jcraft;uses:="com.jcraft.jsch", - com.jcraft.jsch.jgss;uses:="com.jcraft.jsch", - io.sloeber.core;x-friends:="io.sloeber.tests", - io.sloeber.core.Gson;uses:="com.google.gson,io.sloeber.core.api", + io.sloeber.arduinoFramework.api, io.sloeber.core.api; uses:="io.sloeber.core.common, org.eclipse.debug.core.model, @@ -48,20 +43,12 @@ Export-Package: cc.arduino.packages;x-internal:=true, org.eclipse.cdt.core.settings.model, org.eclipse.core.resources, io.sloeber.core.api.Json", - io.sloeber.core.api.Json;uses:="org.eclipse.core.runtime,com.google.gson,io.sloeber.core.api", - io.sloeber.core.builder;x-internal:=true, io.sloeber.core.common;x-friends:="io.sloeber.tests", io.sloeber.core.communication;x-internal:=true, io.sloeber.core.core;x-internal:=true, - io.sloeber.core.eclipseIntegrations;uses:="org.eclipse.core.variables", - io.sloeber.core.internal;x-friends:="io.sloeber.tests", - io.sloeber.core.listeners;x-internal:=true, - io.sloeber.core.managers;x-internal:=true, + io.sloeber.core.internal, io.sloeber.core.natures;x-internal:=true, io.sloeber.core.templates;x-internal:=true, - io.sloeber.core.toolchain;x-internal:=true, - io.sloeber.core.tools;x-friends:="io.sloeber.tests", - io.sloeber.core.tools.uploaders;x-internal:=true, io.sloeber.core.txt;x-friends:="io.sloeber.tests" Import-Package: io.sloeber.autoBuild.schema.api, org.apache.commons.io;version="2.13.0", diff --git a/io.sloeber.core/build.properties b/io.sloeber.core/build.properties index f43297fb8..8f7dd00fe 100644 --- a/io.sloeber.core/build.properties +++ b/io.sloeber.core/build.properties @@ -9,11 +9,11 @@ bin.includes = .,\ config/,\ OSGI-INF/,\ src/io/sloeber/core/templates/sketch.ino,\ - lib/jsch-0.1.55.jar,\ OSGI-INF/l10n/bundle.properties,\ + icons/,\ + launch/,\ lib/jssc-2.9.4.jar,\ lib/jmdns-3.5.7.jar,\ - icons/,\ - launch/ + introContent.xml jars.compile.order = . src.includes = icons/ diff --git a/io.sloeber.core/config/pre_processing_platform_default.txt b/io.sloeber.core/config/pre_processing_platform_default.txt index 6b47ace9d..b27b15804 100644 --- a/io.sloeber.core/config/pre_processing_platform_default.txt +++ b/io.sloeber.core/config/pre_processing_platform_default.txt @@ -1,7 +1,7 @@ #this file contains default/fallback/rescue values software=ARDUINO archive_file=arduino.ar -archive_file_path=${build.path}/${archive_file} +archive_file_path=${build.path}${PathDelimiter}${archive_file} ide_version=20302 serial.port=${com_port} diff --git a/io.sloeber.core/lib/jsch-0.1.55.jar b/io.sloeber.core/lib/jsch-0.1.55.jar deleted file mode 100644 index 1a64e71da..000000000 Binary files a/io.sloeber.core/lib/jsch-0.1.55.jar and /dev/null differ diff --git a/io.sloeber.core/plugin.xml b/io.sloeber.core/plugin.xml index 8309f00e1..563c4359d 100644 --- a/io.sloeber.core/plugin.xml +++ b/io.sloeber.core/plugin.xml @@ -240,7 +240,6 @@ name="%tool.archiver.name" toolType="o->ar"> diff --git a/io.sloeber.core/src/cc/arduino/packages/ssh/SSH.java b/io.sloeber.core/src/cc/arduino/packages/ssh/SSH.java index a40272329..f6d71d517 100644 --- a/io.sloeber.core/src/cc/arduino/packages/ssh/SSH.java +++ b/io.sloeber.core/src/cc/arduino/packages/ssh/SSH.java @@ -43,6 +43,7 @@ import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; +import io.sloeber.core.Activator; import io.sloeber.core.Messages; import io.sloeber.core.api.Common; import io.sloeber.core.api.Const; @@ -159,7 +160,7 @@ public void run() { } catch (IOException e) { // This is unlikely to happen, but log it nevertheless IStatus status = new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, Messages.command_io, e); - Common.log(status); + Activator.log(status); } finally { try { this.fReader.close(); diff --git a/io.sloeber.core/src/cc/arduino/packages/ssh/SSHPwdSetup.java b/io.sloeber.core/src/cc/arduino/packages/ssh/SSHPwdSetup.java index b76c126a3..b6f4251db 100644 --- a/io.sloeber.core/src/cc/arduino/packages/ssh/SSHPwdSetup.java +++ b/io.sloeber.core/src/cc/arduino/packages/ssh/SSHPwdSetup.java @@ -37,8 +37,8 @@ import com.jcraft.jsch.Session; import cc.arduino.packages.BoardPort; +import io.sloeber.core.Activator; import io.sloeber.core.Messages; -import io.sloeber.core.api.Common; import io.sloeber.core.api.Const; import io.sloeber.core.api.PasswordManager; @@ -58,7 +58,7 @@ public Session setup(BoardPort port, JSch jSch) throws JSchException { } else { // The user should set the password in the project // properties->arduino - Common.log( + Activator.log( new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, Messages.Upload_login_credentials_missing.replace(Messages.HOST_TAG, host))); return null; diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/ArduinoInstallable.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/ArduinoInstallable.java new file mode 100644 index 000000000..034288cdd --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/ArduinoInstallable.java @@ -0,0 +1,34 @@ +package io.sloeber.arduinoFramework.api; + +import org.eclipse.core.runtime.IPath; + +public abstract class ArduinoInstallable { + + protected String myArchiveFileName; + protected String myURL; + protected String myChecksum; + protected String mySize; + protected String myName; + + abstract public IPath getInstallPath(); + + public String getArchiveFileName() { + return myArchiveFileName; + } + + public String getUrl() { + return myURL; + } + + public String getChecksum() { + return myChecksum; + } + + public String getSize() { + return mySize; + } + + public String getName() { + return myName; + } +} diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/BoardDescription.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/BoardDescription.java new file mode 100644 index 000000000..72967b065 --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/BoardDescription.java @@ -0,0 +1,1259 @@ +package io.sloeber.arduinoFramework.api; + +import static io.sloeber.core.Messages.*; +import static io.sloeber.core.api.Common.*; +import static io.sloeber.core.api.Const.*; +import static io.sloeber.autoBuild.api.AutoBuildCommon.*; +import static io.sloeber.autoBuild.helpers.api.AutoBuildConstants.DOT; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import org.eclipse.cdt.core.parser.util.StringUtil; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.InstanceScope; + +import io.sloeber.arduinoFramework.internal.ArduinoPlatformTooldDependency; +import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; +import io.sloeber.autoBuild.helpers.api.KeyValueTree; +import io.sloeber.core.Activator; +import io.sloeber.core.Messages; +import io.sloeber.core.api.ConfigurationPreferences; +import io.sloeber.core.api.VersionNumber; +import io.sloeber.core.tools.KeyValue; +import io.sloeber.core.txt.BoardTxtFile; +import io.sloeber.core.txt.PlatformTxtFile; +import io.sloeber.core.txt.Programmers; +import io.sloeber.core.txt.TxtFile; + +public class BoardDescription { + private static final String FIRST_SLOEBER_LINE = "#Sloeber created file please do not modify V1.00.test 07 "; //$NON-NLS-1$ + private static final IEclipsePreferences myStorageNode = InstanceScope.INSTANCE.getNode(NODE_ARDUINO); + + /* + * This is the basic info contained in the descriptor + */ + private String myUploadPort = EMPTY; + private String myProgrammer = EMPTY; + private String myBoardID = EMPTY; + private Map myOptions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + private File myUserSelectedBoardsTxtFile; // this is the boards.txt file selected in the gui + private BoardTxtFile mySloeberBoardTxtFile; // this is the actual used and loaded sloeber.boards.txt file + + private String myBoardsCore = null; + private String myBoardsVariant = null; + private String myUploadTool = null; + + private IArduinoPlatformVersion myReferencedPlatformVariant = null; + private IArduinoPlatformVersion myReferencedPlatformCore = null; + private IArduinoPlatformVersion myReferencedPlatformUpload = null; + private String myJsonURL = null; + + private boolean myIsDirty = true; + + + @Override + public String toString() { + return getReferencingBoardsFile() + " \"" + getBoardName() + "\" " + getUploadPort(); //$NON-NLS-1$//$NON-NLS-2$ + } + + /** + * Compare 2 descriptors and return true is they are equal. This method detects + * - OS changes - project name changes - moves of workspace - changed runtine + * eclipse install + * + * @param obj + * @return true if equal otherwise false + */ + public boolean equals(BoardDescription otherBoardDescriptor) { + if (otherBoardDescriptor == null) { + return false; + } + if (!this.getUploadPort().equals(otherBoardDescriptor.getUploadPort())) { + return false; + } + if (!this.getProgrammer().equals(otherBoardDescriptor.getProgrammer())) { + return false; + } + return !needsRebuild(otherBoardDescriptor); + } + + /** + * compare 2 board descriptors and return true if replacing one board descriptor + * with the other implies that a rebuild is needed + * + * @param otherBoardDescriptor + * @return + */ + public boolean needsRebuild(BoardDescription otherBoardDescriptor) { + if (otherBoardDescriptor == null) { + return true; + } + if (!this.getBoardID().equals(otherBoardDescriptor.getBoardID())) { + return true; + } + String moddedReferencingBoardsFile = makePathVersionString(getReferencingBoardsFile()); + String moddedOtherReferencingBoardsFile = makePathVersionString( + otherBoardDescriptor.getReferencingBoardsFile()); + if (!moddedReferencingBoardsFile.equals(moddedOtherReferencingBoardsFile)) { + return true; + } + if (!this.getOptions().equals(otherBoardDescriptor.getOptions())) { + return true; + } + return false; + } + + /** + * after construction data needs to be derived from other data. This method + * derives all other data and puts it in fields + */ + private void calculateDerivedFields() { + + myReferencedPlatformCore = null; + myBoardsCore = null; + myReferencedPlatformVariant = null; + myBoardsVariant = null; + myReferencedPlatformUpload = null; + myUploadTool = null; + setDefaultOptions(); + // search in the board info + ParseSection(); + + } + + private void ParseSection() { + KeyValueTree rootData = mySloeberBoardTxtFile.getData(); + String boardID = getBoardID(); + KeyValueTree boardData = rootData.getChild(boardID); + + String core = boardData.getValue(BUILD + DOT + CORE); + String variant = boardData.getValue(BUILD + DOT + VARIANT); + String upload = boardData.getValue(UPLOAD + DOT + TOOL); + // also search the options + for (Entry curOption : this.myOptions.entrySet()) { + KeyValueTree curMenuData = boardData.getChild(MENU + DOT + curOption.getKey() + DOT + curOption.getValue()); + String coreOption = curMenuData.getValue(BUILD + DOT + CORE); + String variantOption = curMenuData.getValue(BUILD + DOT + VARIANT); + String uploadOption = curMenuData.getValue(UPLOAD + DOT + TOOL); + if (!coreOption.isEmpty()) { + core = coreOption; + } + if (!variantOption.isEmpty()) { + variant = variantOption; + } + if (!uploadOption.isEmpty()) { + upload = uploadOption; + } + } + String architecture = getArchitecture(); + if (core != null) { + String valueSplit[] = core.split(COLON); + if (valueSplit.length == 2) { + String refVendor = valueSplit[0]; + myBoardsCore = valueSplit[1]; + myReferencedPlatformCore = BoardsManager.getNewestInstalledPlatform(refVendor, architecture); + if (myReferencedPlatformCore == null) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Helpers_tool_reference_missing.replace(TOOL_TAG, core) + .replace(FILE_TAG, getReferencingBoardsFile().toString()) + .replace(BOARD_TAG, getBoardID()))); + return; + } + } else if (valueSplit.length == 4) { + String refVendor = valueSplit[0]; + String refArchitecture = valueSplit[1]; + VersionNumber refVersion = new VersionNumber(valueSplit[2]); + myBoardsCore = valueSplit[3]; + myReferencedPlatformCore = BoardsManager.getPlatform(refVendor, refArchitecture, refVersion); + if (myReferencedPlatformCore == null) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Helpers_tool_reference_missing.replace(TOOL_TAG, core) + .replace(FILE_TAG, getReferencingBoardsFile().toString()) + .replace(BOARD_TAG, getBoardID()))); + return; + } + } else { + this.myBoardsCore = core; + } + } + if (variant != null) { + String valueSplit[] = variant.split(COLON); + if (valueSplit.length == 2) { + String refVendor = valueSplit[0]; + myBoardsVariant = valueSplit[1]; + myReferencedPlatformVariant = BoardsManager.getNewestInstalledPlatform(refVendor, architecture); + if (myReferencedPlatformVariant == null) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Helpers_tool_reference_missing.replace(TOOL_TAG, variant) + .replace(FILE_TAG, getReferencingBoardsFile().toString()) + .replace(BOARD_TAG, getBoardID()))); + return; + } + } else if (valueSplit.length == 4) { + String refVendor = valueSplit[0]; + String refArchitecture = valueSplit[1]; + VersionNumber refVersion = new VersionNumber(valueSplit[2]); + myBoardsVariant = valueSplit[3]; + if ("*".equals(valueSplit[2])) { //$NON-NLS-1$ + myReferencedPlatformVariant = BoardsManager.getNewestInstalledPlatform(refVendor, refArchitecture); + } else { + myReferencedPlatformVariant = BoardsManager.getPlatform(refVendor, refArchitecture, refVersion); + } + if (myReferencedPlatformVariant == null) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Helpers_tool_reference_missing.replace(TOOL_TAG, variant) + .replace(FILE_TAG, getReferencingBoardsFile().toString()) + .replace(BOARD_TAG, getBoardID()))); + return; + } + } else { + myBoardsVariant = variant; + } + } + if (upload != null) { + String valueSplit[] = upload.split(COLON); + if (valueSplit.length == 2) { + String refVendor = valueSplit[0]; + myUploadTool = valueSplit[1]; + myReferencedPlatformUpload = BoardsManager.getNewestInstalledPlatform(refVendor, architecture); + if (myReferencedPlatformUpload == null) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Helpers_tool_reference_missing.replace(TOOL_TAG, upload) + .replace(FILE_TAG, getReferencingBoardsFile().toString()) + .replace(BOARD_TAG, getBoardID()))); + return; + } + } else if (valueSplit.length == 4) { + String refVendor = valueSplit[0]; + String refArchitecture = valueSplit[1]; + VersionNumber refVersion = new VersionNumber(valueSplit[2]); + myUploadTool = valueSplit[3]; + myReferencedPlatformUpload = BoardsManager.getPlatform(refVendor, refArchitecture, refVersion); + if (this.myReferencedPlatformUpload == null) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Helpers_tool_reference_missing.replace(TOOL_TAG, upload) + .replace(FILE_TAG, getReferencingBoardsFile().toString()) + .replace(BOARD_TAG, getBoardID()))); + return; + } + } else { + myUploadTool = upload; + } + } + } + + /** + * make a board descriptor for each board in the board.txt file with the default + * options + * + * @param boardFile + * @return a list of board descriptors + */ + public static List makeBoardDescriptors(File boardFile) { + BoardTxtFile txtFile = new BoardTxtFile(resolvePathEnvironmentString(boardFile)); + List boards = new ArrayList<>(); + List boardIDs = txtFile.getAllBoardIDs(); + for (String curboardID : boardIDs) { + Map boardSection = txtFile.getSection(curboardID); + if (boardSection != null) { + if (!"true".equalsIgnoreCase(boardSection.get("hide"))) { //$NON-NLS-1$ //$NON-NLS-2$ + boards.add(new BoardDescription(null,boardFile, curboardID, null)); + } + } + } + return boards; + } + + /** + * create a board descriptor + * + * @param boardsFile + * @param boardID + * @param options + * if null default options are taken + */ + public BoardDescription(String jsonURL,File boardsFile, String boardID, Map options) { + + File expandedBoardsFile = resolvePathEnvironmentString(boardsFile); + if (!expandedBoardsFile.exists()) { + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "BoardsFile " + boardsFile + " does not exist")); //$NON-NLS-1$//$NON-NLS-2$ + return; + } + if (jsonURL != null) { + myJsonURL = jsonURL; + } else { + myJsonURL = BoardsManager.getjsonURLFormBoardsFile(expandedBoardsFile); + } + myBoardID = boardID; + myUserSelectedBoardsTxtFile = boardsFile; + mySloeberBoardTxtFile = new BoardTxtFile(expandedBoardsFile); + setDefaultOptions(); + if (options != null) { + myOptions.putAll(options); + } + } + + public BoardDescription() { + myUserSelectedBoardsTxtFile = new File(myStorageNode.get(KEY_LAST_USED_BOARDS_FILE, EMPTY)); + if (!myUserSelectedBoardsTxtFile.exists()) { + + IArduinoPlatformVersion platform = BoardsManager.getNewestInstalledPlatform( VENDOR_ARDUINO, AVR); + if (platform == null) { + platform = BoardsManager.getAnyInstalledPlatform(); + } + myUserSelectedBoardsTxtFile = platform.getBoardsFile(); + mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); + myJsonURL= BoardsManager.getjsonURLFormBoardsFile(myUserSelectedBoardsTxtFile); + + if (mySloeberBoardTxtFile.getAllBoardIDs().contains(UNO)) { + myBoardID = UNO; + } else { + myBoardID = mySloeberBoardTxtFile.getAllBoardIDs().get(0); + } + setDefaultOptions(); + } else { + mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); + myBoardID = myStorageNode.get(KEY_LAST_USED_BOARD, EMPTY); + myUploadPort = myStorageNode.get(KEY_LAST_USED_UPLOAD_PORT, EMPTY); + myProgrammer = myStorageNode.get(KEY_LAST_USED_UPLOAD_PROTOCOL, EMPTY); + myJsonURL = myStorageNode.get(KEY_LAST_USED_JSON_URL, EMPTY); + myOptions = KeyValue.makeMap(myStorageNode.get(KEY_LAST_USED_BOARD_MENU_OPTIONS, EMPTY)); + } + + } + + + public BoardDescription(BoardDescription srcObject) { + myUserSelectedBoardsTxtFile = srcObject.myUserSelectedBoardsTxtFile; + mySloeberBoardTxtFile = srcObject.mySloeberBoardTxtFile; + myJsonURL = srcObject.myJsonURL; + myBoardID = srcObject.myBoardID; + myUploadPort = srcObject.myUploadPort; + myProgrammer = srcObject.myProgrammer; + myUploadTool = srcObject.myUploadTool; + myOptions.putAll(new TreeMap<>(srcObject.myOptions)); + + } + + public String getuploadTool() { + return this.myUploadTool; + } + + /* + * Sets default options as follows If no option is specified take the first one + * if a option is specified but the value is invalid take the first one + * + * this is so because I want to provide a list of options but if the options are + * incomplete or invalid this method still returns a complete and valid set. + */ + private void setDefaultOptions() { + Map allMenuIDs = this.mySloeberBoardTxtFile.getMenus(); + for (Map.Entry curMenuID : allMenuIDs.entrySet()) { + String providedMenuValue = this.myOptions.get(curMenuID.getKey()); + ArrayList menuOptions = this.mySloeberBoardTxtFile.getMenuItemIDsFromMenuID(curMenuID.getKey(), + getBoardID()); + if (menuOptions.size() > 0) { + if (providedMenuValue == null) { + + this.myOptions.put(curMenuID.getKey(), menuOptions.get(0)); + } else if (!menuOptions.contains(providedMenuValue)) { + this.myOptions.put(curMenuID.getKey(), menuOptions.get(0)); + } + } + } + } + + private void removeInvalidMenuIDs() { + Set allMenuIDs = this.mySloeberBoardTxtFile.getMenus().keySet(); + Set optionKey = new HashSet<>(myOptions.keySet()); + + for (String curOptionKey : optionKey) { + if (!allMenuIDs.contains(curOptionKey)) { + myOptions.remove(curOptionKey); + } + } + } + + /** + * Store the selections the user made so we can reuse them when creating a new + * project + */ + public void saveUserSelection() { + myStorageNode.put(KEY_LAST_USED_BOARDS_FILE, myUserSelectedBoardsTxtFile.toString()); + myStorageNode.put(KEY_LAST_USED_BOARD, myBoardID); + myStorageNode.put(KEY_LAST_USED_UPLOAD_PORT, myUploadPort); + myStorageNode.put(KEY_LAST_USED_UPLOAD_PROTOCOL, myProgrammer); + myStorageNode.put(KEY_LAST_USED_JSON_URL, myJsonURL); + myStorageNode.put(KEY_LAST_USED_BOARD_MENU_OPTIONS, KeyValue.makeString(myOptions)); + } + + /* + * Returns the architecture based on the myUserSelectedBoardsTxtFile file name + * Caters for the packages (with version number and for the old way if the boards + * file does not exists returns avr + */ + public String getArchitecture() { + if (myUserSelectedBoardsTxtFile == null) { + return AVR; + } + IPath platformFile = new Path(myUserSelectedBoardsTxtFile.toString().trim()); + int index = hardwareSegmentIndex(platformFile); + if (index < 0) { + return AVR; + } + return platformFile.segment(index + 3); + } + + /* + * Returns the vendor based on the myUserSelectedBoardsTxtFile file name + * Caters for the packages (with version number and for the old way if the boards + * file does not exists returns VENDOR_ARDUINO + */ + public String getVendor() { + if (myUserSelectedBoardsTxtFile == null) { + return VENDOR_ARDUINO; + } + IPath platformFile = new Path(myUserSelectedBoardsTxtFile.toString().trim()); + int index = hardwareSegmentIndex(platformFile); + if (index < 1) { + return VENDOR_ARDUINO; + } + return platformFile.segment(index + 1); + } + + /** + * return the segment that contains the name packages + * or -1 if no such segment is found + * @param platformFile + * @return + */ + private static int hardwareSegmentIndex(IPath platformFile) { + for (int i = 0; i < platformFile.segmentCount(); i++) { + if (PACKAGES_FOLDER_NAME.equals(platformFile.segment(i))) { + return i; + } + } + return -1; + + } + + public File getReferencingBoardsFile() { + return myUserSelectedBoardsTxtFile; + } + + public String getBoardName() { + return this.mySloeberBoardTxtFile.getNiceNameFromID(this.myBoardID); + } + + public String getUploadPort() { + return this.myUploadPort; + } + + /** + * return the actual adress en,coded in the upload port example uploadport com4 + * returns com4 uploadport = arduino.local at 199.25.25.1 returns arduino.local + * + * @return + */ + public String getActualUploadPort() { + return myUploadPort.split(" ")[0]; //$NON-NLS-1$ + } + + public String getProgrammer() { + return this.myProgrammer; + } + + /** + * Set the upload port like in the gui. The upload port can be a comport or a + * networkadress space and something else note that getuploadport returns the + * before space part of this method + * + * @param newUploadPort + */ + public void setUploadPort(String newUploadPort) { + this.myUploadPort = newUploadPort; + } + + public void setProgrammer(String newUploadProtocol) { + this.myProgrammer = newUploadProtocol; + } + + public void setBoardID(String boardID) { + if (!boardID.equals(this.myBoardID)) { + this.myBoardID = boardID; + setDirty(); + } + } + + private void setDirty() { + myIsDirty = true; + + } + + public void setBoardName(String boardName) { + String newBoardID = this.mySloeberBoardTxtFile.getIDFromNiceName(boardName); + if ((newBoardID == null || this.myBoardID.equals(newBoardID))) { + return; + } + this.myBoardID = newBoardID; + setDirty(); + + } + + public void setreferencingBoardsFile(File boardsFile) { + if (boardsFile == null) { + return;// ignore + } + + if (!myUserSelectedBoardsTxtFile.equals(boardsFile)) { + myUserSelectedBoardsTxtFile = boardsFile; + setDirty(); + } + + /* do not remove this for optimization as workaround changes will not be captured */ + mySloeberBoardTxtFile = new BoardTxtFile(resolvePathEnvironmentString(myUserSelectedBoardsTxtFile)); + + } + + /** + * seOptions add the options to the already existing options and removes the options + * with an invalid menuID + * The enuitemID is not verified and assumed correct. + * + */ + public void setOptions(Map options) { + if (options == null || options.size() == 0) { + return; + } + myOptions.putAll(options); + removeInvalidMenuIDs(); + setDirty(); + } + + /** + * Returns the options for this board This reflects the options selected through + * the menu functionality in the boards.txt + * + * @return a map of case insensitive ordered key value pairs + */ + public Map getOptions() { + // no update is needed as this field is only modified at construction or set + return this.myOptions; + } + + private void updateWhenDirty() { + if (myIsDirty) { + calculateDerivedFields(); + myIsDirty = false; + } + } + + public String getBoardID() { + // no update is needed as this field is only modified at construction or set + return this.myBoardID; + } + + public String[] getCompatibleBoards() { + return this.mySloeberBoardTxtFile.getAllSectionNames(); + } + + public String[] getUploadProtocols() { + + return Programmers.getUploadProtocols(this); + + } + + public String[] getMenuItemNamesFromMenuID(String menuID) { + return this.mySloeberBoardTxtFile.getMenuItemNamesFromMenuID(menuID, this.myBoardID); + } + + public String getMenuNameFromMenuID(String id) { + return this.mySloeberBoardTxtFile.getMenuNameFromID(id); + } + + public String getMenuItemNamedFromMenuItemID(String menuItemID, String menuID) { + return this.mySloeberBoardTxtFile.getMenuItemNameFromMenuItemID(this.myBoardID, menuID, menuItemID); + } + + public String getMenuItemIDFromMenuItemName(String menuItemName, String menuID) { + return this.mySloeberBoardTxtFile.getMenuItemIDFromMenuItemName(this.myBoardID, menuID, menuItemName); + } + + /** + * provide the actual path to the variant. Use this method if you want to know + * where the variant is + * + * @return the path to the variant; null if no variant is needed + */ + public IPath getActualVariantPath() { + updateWhenDirty(); + String boardVariant = getBoardVariant(); + if (boardVariant == null || boardVariant.isBlank()) { + return null; + } + if (myReferencedPlatformVariant == null) { + return new Path(myUserSelectedBoardsTxtFile.getParent().toString()).append(ARDUINO_VARIANTS_FOLDER_NAME) + .append(boardVariant); + } + return myReferencedPlatformVariant.getInstallPath().append(ARDUINO_VARIANTS_FOLDER_NAME).append(boardVariant); + } + + private String getBoardVariant() { + updateWhenDirty(); + return this.myBoardsVariant; + } + + public IPath getActualCoreCodePath() { + updateWhenDirty(); + if (myBoardsCore == null) { + return null; + } + IPath retPath = null; + if (myReferencedPlatformCore == null) { + retPath = getreferencingPlatformPath(); + } else { + retPath = myReferencedPlatformCore.getInstallPath(); + } + return retPath.append(CORES).append(myBoardsCore); + } + + public IPath getReferencedUploadPlatformPath() { + updateWhenDirty(); + if (myReferencedPlatformUpload != null) { + return myReferencedPlatformUpload.getInstallPath(); + } + return getreferencingPlatformPath(); + } + + public PlatformTxtFile getReferencingPlatformFile() { + updateWhenDirty(); + File platformFile = getreferencingPlatformPath().append(PLATFORM_FILE_NAME).toFile(); + if (platformFile != null && platformFile.exists()) { + return new PlatformTxtFile(platformFile); + } + return null; + } + + public Path getreferencingPlatformPath() { + try { + return new Path(myUserSelectedBoardsTxtFile.getParent()); + } catch (@SuppressWarnings("unused") Exception e) { + return new Path(EMPTY); + } + } + + public PlatformTxtFile getreferencedCorePlatformFile() { + updateWhenDirty(); + if (myReferencedPlatformCore == null) { + return null; + } + File platformFile = myReferencedPlatformCore.getInstallPath().append(PLATFORM_FILE_NAME).toFile(); + if (platformFile != null && platformFile.exists()) { + return new PlatformTxtFile(platformFile); + } + return null; + } + + public IPath getReferencedCoreLibraryPath() { + updateWhenDirty(); + if (myReferencedPlatformCore == null) { + return getReferencingLibraryPath(); + } + return this.myReferencedPlatformCore.getInstallPath().append(ARDUINO_LIBRARY_FOLDER_NAME); + } + + public IPath getReferencingLibraryPath() { + updateWhenDirty(); + return this.getreferencingPlatformPath().append(ARDUINO_LIBRARY_FOLDER_NAME); + } + + public String getUploadPatternKey() { + updateWhenDirty(); + String upLoadTool = getuploadTool(); + String networkPrefix = EMPTY; + if (isNetworkUpload()) { + networkPrefix = NETWORK_PREFIX; + } + return TOOLS + DOT + upLoadTool + DOT + UPLOAD + DOT + networkPrefix + PATTERN; + } + + public IPath getreferencedCoreHardwarePath() { + updateWhenDirty(); + if (myReferencedPlatformCore == null) { + return getreferencingPlatformPath(); + } + return myReferencedPlatformCore.getInstallPath(); + } + + /* + * get the latest installed arduino platform with the same architecture. This is + * the platform to use the programmers.txt if no other programmers.txt are + * found. + */ + public IPath getArduinoPlatformPath() { + updateWhenDirty(); + IArduinoPlatform platform = BoardsManager.getPlatform(VENDOR_ARDUINO, getArchitecture()); + if (platform == null) { + return null; + } + IArduinoPlatformVersion platformVersion = platform.getNewestInstalled(); + if (platformVersion == null) { + return null; + } + return platformVersion.getInstallPath(); + } + + /** + * If the upload port contains a space everything before the first space is + * considered to be a dns name or ip adress. + * + * @param mComPort + * @return null if no space in uploadport return dns name op ipadress + */ + public String getHost() { + String host = myUploadPort.split(" ")[0]; //$NON-NLS-1$ + if (host.equals(myUploadPort)) + return null; + return host; + } + + /** + * true if this board needs a networkUpload else false + * + * @return + */ + public boolean isNetworkUpload() { + return getHost() != null; + } + + + BoardDescription(TxtFile configFile, String prefix) { + + KeyValueTree tree = configFile.getData(); + KeyValueTree section = tree.getChild(prefix); + myProgrammer = section.getValue(KEY_SLOEBER_PROGRAMMER); + myBoardID = section.getValue(KEY_SLOEBER_BOARD_ID); + String board_txt = section.getValue(KEY_SLOEBER_BOARD_TXT); + myUploadPort = section.getValue(KEY_SLOEBER_UPLOAD_PORT); + KeyValueTree optionsTree = section.getChild(KEY_SLOEBER_MENU_SELECTION); + Map options = optionsTree.toKeyValues(EMPTY); + + KeyValueTree boardSection = tree.getChild(BOARD); + myJsonURL = boardSection.getValue(JSON_URL); + + myUserSelectedBoardsTxtFile = resolvePathEnvironmentString(new File(board_txt)); + mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); + setDefaultOptions(); + if (options != null) { + // Only add the valid options for this board to our options + myOptions.putAll(onlyKeepValidOptions(options)); + } + } + + /** + * create a BoardDescription based on the environment variables given + * + * @param envVars + */ + public BoardDescription(KeyValueTree keyValues) { + myProgrammer = keyValues.getValue(KEY_SLOEBER_PROGRAMMER); + myUploadPort = keyValues.getValue(KEY_SLOEBER_UPLOAD_PORT); + + KeyValueTree boardvalueTree = keyValues.getChild(KEY_BOARD); + myBoardID = boardvalueTree.getValue(KEY_SLOEBER_BOARD_ID); + String txtFile = boardvalueTree.getValue(KEY_SLOEBER_BOARD_TXT); + + KeyValueTree jSonvalueTree = keyValues.getChild(KEY_JSON); + myJsonURL = jSonvalueTree.getValue(KEY_JSON_URL); + + myUserSelectedBoardsTxtFile = resolvePathEnvironmentString(new File(txtFile)); + mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); + KeyValueTree options = keyValues.getChild(KEY_SLOEBER_MENU_SELECTION); + for (KeyValueTree curOption : options.getChildren().values()) { + myOptions.put(curOption.getKey(), curOption.getValue()); + } + +// int menuKeyLength = KEY_SLOEBER_MENU_SELECTION.length() + DOT.length(); +// for (Entry curEnvVar : envVars.entrySet()) { +// String key = curEnvVar.getKey(); +// String value = curEnvVar.getValue(); +// switch (key) { +// case KEY_SLOEBER_PROGRAMMER: +// myProgrammer = value; +// break; +// case KEY_SLOEBER_BOARD_ID: +// myBoardID = value; +// break; +// case KEY_SLOEBER_BOARD_TXT: +// myUserSelectedBoardsTxtFile = resolvePathEnvironmentString(new File(value)); +// mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); +// break; +// case KEY_SLOEBER_UPLOAD_PORT: +// myUploadPort = value; +// break; +// default: +// if (key.startsWith(KEY_SLOEBER_MENU_SELECTION + DOT)) { +// String cleanKey = key.substring(menuKeyLength); +// myOptions.put(cleanKey, value); +// } +// } +// } + } + + /** + * get the environment variables that need to be stored in the configuration + * files configuration files are files needed to setup the sloeber environment + * for instance when openiung a project or after import of a project in the + * workspace + * + * @return the minimum list of environment variables to recreate the project + */ + public void serialize(KeyValueTree keyValueTree) { + String board_txt = makePathVersionString(getReferencingBoardsFile()); + keyValueTree.addChild(KEY_SLOEBER_PROGRAMMER, myProgrammer); + keyValueTree.addChild(KEY_SLOEBER_UPLOAD_PORT, myUploadPort); + + KeyValueTree boardvalueTree = keyValueTree.addChild(KEY_BOARD); + boardvalueTree.addChild(KEY_SLOEBER_BOARD_ID, myBoardID); + boardvalueTree.addChild(KEY_SLOEBER_BOARD_TXT, board_txt); + + KeyValueTree jSonvalueTree = keyValueTree.addChild(KEY_JSON); + jSonvalueTree.addChild(KEY_JSON_URL, myJsonURL); + + KeyValueTree menuvalueTree = keyValueTree.addChild(KEY_SLOEBER_MENU_SELECTION); + for (Entry curOption : myOptions.entrySet()) { + menuvalueTree.addValue(curOption.getKey(), curOption.getValue()); + } + } + + private Map onlyKeepValidOptions(Map options) { + Map ret = new HashMap<>(); + + KeyValueTree tree = mySloeberBoardTxtFile.getData(); + KeyValueTree boardMenuSection = tree.getChild(myBoardID + DOT + MENU); + if (boardMenuSection != null) { + for (Entry curoption : options.entrySet()) { + String key = curoption.getKey(); + if (boardMenuSection.getChild(key).getKey() != null) { + ret.put(key, curoption.getValue()); + } + } + } + return ret; + } + + /** + * get the environment variables that need to be stored in version control + * + * @return the minimum list of environment variables to recreate the project + * from version control + */ + public Map getEnvVarsVersion(String prefix) { + Map allVars = new TreeMap<>(); + String board_txt = makePathVersionString(getReferencingBoardsFile()); + + allVars.put(prefix + KEY_SLOEBER_BOARD_ID, myBoardID); + allVars.put(prefix + KEY_SLOEBER_BOARD_TXT, board_txt); + + for (Entry curOption : myOptions.entrySet()) { + allVars.put(prefix + KEY_SLOEBER_MENU_SELECTION + DOT + curOption.getKey(), curOption.getValue()); + } + return allVars; + } + + /** + * This method creates environment variables based on the platform.txt and + * boards.txt. platform.txt is processed first and then boards.txt. This way + * boards.txt settings can overwrite common settings in platform.txt The + * environment variables are only valid for the project given as parameter The + * project properties are used to identify the boards.txt and platform.txt as + * well as the board id to select the settings in the board.txt file At the end + * also the path variable is set + * + * + * To be able to quickly fix boards.txt and platform.txt problems I also added a + * pre and post platform and boards files that are processed before and after + * the arduino delivered boards.txt file. + * + * @param project + * the project for which the environment variables are set + * @param arduinoProperties + * the info of the selected board to set the variables for + */ + public Map getEnvVars() { + updateWhenDirty(); + + TxtFile pluginPreProcessingPlatformTxt = new TxtFile(ConfigurationPreferences.getPreProcessingPlatformFile()); + TxtFile pluginPostProcessingPlatformTxt = new TxtFile(ConfigurationPreferences.getPostProcessingPlatformFile()); + BoardTxtFile pluginPreProcessingBoardsTxt = new BoardTxtFile( + ConfigurationPreferences.getPreProcessingBoardsFile()); + BoardTxtFile pluginPostProcessingBoardsTxt = new BoardTxtFile( + ConfigurationPreferences.getPostProcessingBoardsFile()); + + Map allVars = pluginPreProcessingPlatformTxt.getAllEnvironVars(EMPTY); + allVars.putAll(pluginPreProcessingBoardsTxt.getBoardEnvironVars(getBoardID())); + + String architecture = getArchitecture(); + IPath coreHardwarePath = getreferencedCoreHardwarePath(); + allVars.put(ENV_KEY_BUILD_ARCH, architecture.toUpperCase()); + allVars.put(ENV_KEY_RUNTIME_HARDWARE_PATH, getreferencingPlatformPath().removeLastSegments(1).toOSString()); + allVars.put(ENV_KEY_BUILD_SYSTEM_PATH, coreHardwarePath.append(SYSTEM).toOSString()); + allVars.put(ENV_KEY_RUNTIME_PLATFORM_PATH, getreferencingPlatformPath().toOSString()); + // ide_version is defined in pre_processing_platform_default.txt + allVars.put(ENV_KEY_RUNTIME_IDE_VERSION, makeEnvironmentVar("ide_version")); //$NON-NLS-1$ + allVars.put(ENV_KEY_RUNTIME_IDE_PATH, makeEnvironmentVar(SLOEBER_HOME)); + if (isWindows) { + allVars.put(ENV_KEY_RUNTIME_OS, "windows"); //$NON-NLS-1$ + } + if (isLinux) { + allVars.put(ENV_KEY_RUNTIME_OS, "linux"); //$NON-NLS-1$ + } + if (isMac) { + allVars.put(ENV_KEY_RUNTIME_OS, "macosx"); //$NON-NLS-1$ + } + allVars.put(ENV_KEY_ID, getBoardID()); + allVars.put(ENV_KEY_BUILD_FQBN, getBoardFQBN()); + + allVars.put(ENV_KEY_SERIAL_PORT, getActualUploadPort()); + allVars.put(ENV_KEY_SERIAL_DOT_PORT, getActualUploadPort()); + + allVars.put(ENV_KEY_SERIAL_PORT_FILE, getActualUploadPort().replace("/dev/", EMPTY)); //$NON-NLS-1$ + // if actual core path is osstring regression test issue555 willl fail teensy + // stuff + allVars.put(ENV_KEY_BUILD_ACTUAL_CORE_PATH, getActualCoreCodePath().toOSString()); + IPath variantPath = getActualVariantPath(); + if (variantPath != null) { + allVars.put(ENV_KEY_BUILD_VARIANT_PATH, variantPath.toOSString()); + } else {// teensy does not use variant + allVars.put(ENV_KEY_BUILD_VARIANT_PATH, EMPTY); + } + + PlatformTxtFile referencedPlatfromFile = getreferencedCorePlatformFile(); + // process the platform file referenced by the boards.txt + if (referencedPlatfromFile != null) { + allVars.putAll(referencedPlatfromFile.getAllEnvironVars()); + } + PlatformTxtFile referencingPlatfromFile = getReferencingPlatformFile(); + // process the platform file next to the selected boards.txt + if (referencingPlatfromFile != null) { + allVars.putAll(referencingPlatfromFile.getAllEnvironVars()); + } + + // put in the installed tools info + try { + allVars.putAll(getEnVarPlatformInfo()); + } catch (IOException e) { + // TODO Auto-generated catch block + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, Messages.BoardDescription_0, e)); + } + + // boards settings not coming from menu selections + allVars.putAll(mySloeberBoardTxtFile.getBoardEnvironVars(getBoardID())); + + // board settings from menu selections + Map options = getOptions(); + KeyValueTree rootData = mySloeberBoardTxtFile.getData(); + KeyValueTree menuData = rootData.getChild(getBoardID() + DOT + MENU); + for (Entry curOption : options.entrySet()) { + String menuID = curOption.getKey(); + String SelectedMenuItemID = curOption.getValue(); + KeyValueTree curSelectedMenuItem = menuData.getChild(menuID + DOT + SelectedMenuItemID); + allVars.putAll(curSelectedMenuItem.toKeyValues(EMPTY)); + } + + // This moved last. See github issue 1410 + Programmers localProgrammers[] = Programmers.fromBoards(this); + String programmer = getProgrammer(); + for (Programmers curProgrammer : localProgrammers) { + String programmerID = curProgrammer.getIDFromNiceName(programmer); + if (programmerID != null) { + allVars.putAll(curProgrammer.getAllEnvironVars(programmerID)); + } + } + + // add the stuff that comes with the plugin that is marked as post + allVars.putAll(pluginPostProcessingPlatformTxt.getAllEnvironVars(EMPTY)); + allVars.putAll(pluginPostProcessingBoardsTxt.getBoardEnvironVars(getBoardID())); + + // Do some coded post processing + allVars.putAll(getEnvVarsPostProcessing(allVars)); + return allVars; + + } + + private String getBoardFQBN() { + String fqbn = getVendor() + COLON + getArchitecture() + COLON + getBoardID(); + String options = EMPTY_STRING; + String prefix = COLON; + for (Entry curOption : myOptions.entrySet()) { + options = options + prefix + curOption.getKey() + EQUAL + curOption.getValue(); + prefix = COMMA; + } + return fqbn + options; + } + + private Map getEnVarPlatformInfo() throws IOException { + Map ret = new HashMap<>(); + + ret.putAll(getEnvVarPlatformFileTools(myReferencedPlatformUpload)); + ret.putAll(getEnvVarPlatformFileTools(myReferencedPlatformVariant)); + ret.putAll(getEnvVarPlatformFileTools(myReferencedPlatformCore)); + + BoardsManager.update(false);// This way we know the boardsmanager is started or we wait for the lock + IArduinoPlatformVersion latestArduinoPlatform = BoardsManager.getNewestInstalledPlatform(VENDOR_ARDUINO, + getArchitecture()); + ret.putAll(getEnvVarPlatformFileTools(latestArduinoPlatform)); + + IPath referencingPlatformPath = getreferencingPlatformPath(); + IArduinoPlatformVersion referencingPlatform = BoardsManager.getPlatform(referencingPlatformPath); + if (referencingPlatform == null) { + ret.putAll(getEnvVarPlatformFileTools(referencingPlatformPath.toFile())); + } else { + ret.putAll(getEnvVarPlatformFileTools(referencingPlatform)); + } + + if (myReferencedPlatformCore == null) { + // there is no referenced core so no need to do smart stuff + return ret; + } + + boolean jsonBasedPlatformManagement = !ConfigurationPreferences.getUseArduinoToolSelection(); + if (jsonBasedPlatformManagement) { + // overrule the Arduino IDE way of working and use the json refereced tools + ret.putAll(getEnvVarPlatformFileTools(referencingPlatform)); + return ret; + } + // standard arduino IDE way + ret.putAll(getEnvVarPlatformFileTools(myReferencedPlatformCore)); + return ret; + + } + + /** + * This method only returns environment variables with and without version + * number + * These are purely based on the tool dependencies + * + * @param platformVersion + * @return environment variables pointing to the tools used by the platform + * @throws IOException + */ + private Map getEnvVarPlatformFileTools(IArduinoPlatformVersion platformVersion) throws IOException { + if (platformVersion == null) { + Path path = new Path(myUserSelectedBoardsTxtFile.toString()); + File sloeberTxtFile = path.removeLastSegments(1).append(SLOEBER_TXT_FILE_NAME).toFile(); + return getEnvVarPlatformFileTools(sloeberTxtFile); + } + File sloeberTxtFile = platformVersion.getInstallPath().append(SLOEBER_TXT_FILE_NAME).toFile(); + deleteIfOutdated(sloeberTxtFile); + + if (!sloeberTxtFile.exists()) { + + String vars = FIRST_SLOEBER_LINE + NEWLINE; + for (ArduinoPlatformTooldDependency tool : platformVersion.getToolsDependencies()) { + IPath installPath = tool.getInstallPath(); + if (installPath.toFile().exists()) { + String value = installPath.toOSString(); + String keyString = ENV_KEY_RUNTIME_TOOLS + tool.getName() + tool.getVersion() + DOT_PATH; + vars = vars + NEWLINE + keyString + EQUAL + value; + keyString = ENV_KEY_RUNTIME_TOOLS + tool.getName() + '-' + tool.getVersion() + DOT_PATH; + vars = vars + NEWLINE + keyString + EQUAL + value; + keyString = ENV_KEY_RUNTIME_TOOLS + tool.getName() + DOT_PATH; + vars = vars + NEWLINE + keyString + EQUAL + value; + } + } + Files.write(sloeberTxtFile.toPath(), vars.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.CREATE); + } + + return getEnvVarPlatformFileTools(sloeberTxtFile); + } + + private static Map getEnvVarPlatformFileTools(File sloeberTxtFile) { + if (sloeberTxtFile == null || (!sloeberTxtFile.exists())) { + return new HashMap<>(); + } + TxtFile sloeberTxt = new TxtFile(sloeberTxtFile); + return sloeberTxt.getAllEnvironVars(EMPTY); + } + + /** + * If the sloeber.txt variant exists delete it if it is outdated + * + * @param tmpFile + */ + private static void deleteIfOutdated(File tmpFile) { + if (tmpFile.exists()) { + // delete if outdated + String firstLine = null; + try (BufferedReader Buff = new BufferedReader(new FileReader(tmpFile));) { + firstLine = Buff.readLine().trim(); + } catch (@SuppressWarnings("unused") Exception e) { + // ignore and delete the file + } + if (!FIRST_SLOEBER_LINE.trim().equals(firstLine)) { + tmpFile.delete(); + } + } + } + + /** + * Following post processing is done + * + * + * The handling of the upload variables is done differently in arduino + * than in Sloeber. This is taken care of here. for example the output of this + * input + * tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} + * is changed as if it were the output of this input + * tools.avrdude.upload.pattern="{tools.avrdude.cmd.path}" + * "-C{tools.avrdude.config.path}" {tools.avrdude.upload.verbose} + * + * if a programmer is selected different from default some extra actions + * are done here so no special code is needed to handle programmers + * + * The build path for the core is {build.path}/core/core in sloeber + * where it is {build.path}/core/ in arduino world and used to be {build.path}/ + * This only gives problems in the link command as sometimes there are hardcoded + * links to some sys files so ${build.path}/core/sys* ${build.path}/sys* is + * replaced with ${build.path}/core/core/sys* + * + * @param contribEnv + * @param confDesc + * @param boardsDescriptor + */ + private static Map getEnvVarsPostProcessing(Map vars) { + + Map extraVars = new HashMap<>(); + + ArrayList objcopyCommand = new ArrayList<>(); + for (Entry curVariable : vars.entrySet()) { + String name = curVariable.getKey(); + String value = curVariable.getValue(); + if (name.startsWith(RECIPE_OBJCOPY) && name.endsWith(".pattern") && !value.isEmpty()) { //$NON-NLS-1$ + objcopyCommand.add(makeEnvironmentVar(name)); + } + } + Collections.sort(objcopyCommand); + extraVars.put(SLOEBER_OBJCOPY, StringUtil.join(objcopyCommand, NEWLINE)); + + // add -relax for mega boards; the arduino ide way + String buildMCU = vars.get(ENV_KEY_BUILD_MCU); + if ("atmega2560".equalsIgnoreCase(buildMCU)) { //$NON-NLS-1$ + String c_elf_flags = vars.get(ENV_KEY_BUILD_COMPILER_C_ELF_FLAGS); + extraVars.put(ENV_KEY_BUILD_COMPILER_C_ELF_FLAGS, c_elf_flags + ",--relax"); //$NON-NLS-1$ + } + return extraVars; + } + + public LinkedHashMap getHookSteps(LinkedHashSet hookNames,IAutoBuildConfigurationDescription autoData) { + LinkedHashMap hookSteps = new LinkedHashMap<>(); + KeyValueTree keyValueTree = KeyValueTree.createRoot(); + + PlatformTxtFile referencedPlatfromFile = getreferencedCorePlatformFile(); + // process the platform file referenced by the boards.txt + if (referencedPlatfromFile != null) { + try { + keyValueTree.mergeFile(referencedPlatfromFile.getLoadedFile()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + PlatformTxtFile referencingPlatfromFile = getReferencingPlatformFile(); + // process the platform file next to the selected boards.txt + if (referencingPlatfromFile != null) { + try { + keyValueTree.mergeFile(referencingPlatfromFile.getLoadedFile()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + KeyValueTree hooks = keyValueTree.getChild(RECIPE).getChild(HOOKS); + for (String hookName : hookNames) { + hooks = hooks.getChild(hookName); + } + + // Try to find the nums from 1 to 10 in order + // that is 01 1 02 2 + + for (int hoookNum = 1; hoookNum < 10; hoookNum++) { + boolean exists = false; + for (int numDigits = 1; numDigits <= 2; numDigits++) { + String formatter = "%0" + Integer.toString(numDigits) + "d"; //$NON-NLS-1$ //$NON-NLS-2$ + String curKey = String.format(formatter, Integer.valueOf(hoookNum)); + KeyValueTree curHook = hooks.getChild(curKey).getChild(PATTERN); + if (curHook.getValue() != null) { + String cmd = resolve(curHook.getValue(), EMPTY_STRING, WHITESPACE, autoData); + hookSteps.put(curKey, cmd); + exists = true; + } + } + if (!exists) { + break; + } + } + return hookSteps; + } + + public boolean isValid() { + if (!myUserSelectedBoardsTxtFile.exists()) { + return false; + } + File boardsFile = mySloeberBoardTxtFile.getLoadedFile(); + if (boardsFile == null) { + return false; + } + return boardsFile.exists(); + } + + public void reloadTxtFile() { + mySloeberBoardTxtFile.reloadTxtFile(); + + } + + public Map getAllMenus() { + return mySloeberBoardTxtFile.getMenus(); + } + + public boolean isSSHUpload() { + if (!isNetworkUpload()) { + return false; + } + // This is a hardcoded fix. Not sure how to do better + return myBoardID.equals("yun"); //$NON-NLS-1$ + } + + public String getDefaultValueIDFromMenu(String menuID) { + return this.mySloeberBoardTxtFile.getDefaultValueIDFromMenu(getBoardID(), menuID); + } + + public String getDefaultValueNameFromMenu(String menuID) { + return this.mySloeberBoardTxtFile.getDefaultValueNameFromMenu(getBoardID(), menuID); + } + + public boolean isPrivate() { + return !sloeberHomePath.isPrefixOf(new Path(myUserSelectedBoardsTxtFile.toString())); + } +} diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/BoardsManager.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/BoardsManager.java new file mode 100644 index 000000000..bbf3e406b --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/BoardsManager.java @@ -0,0 +1,929 @@ +package io.sloeber.arduinoFramework.api; + +import static io.sloeber.core.Messages.*; +import static io.sloeber.core.api.Common.*; +import static io.sloeber.core.api.ConfigurationPreferences.*; +import static io.sloeber.core.api.Const.*; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.MultiStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Status; +import com.google.gson.Gson; + +import io.sloeber.arduinoFramework.internal.ArduinoPlatformPackageIndex; +import io.sloeber.arduinoFramework.internal.ArduinoPlatformTool; +import io.sloeber.arduinoFramework.internal.ArduinoPlatformToolVersion; +import io.sloeber.arduinoFramework.internal.ArduinoPlatformTooldDependency; +import io.sloeber.core.Activator; +import io.sloeber.core.Messages; +import io.sloeber.core.api.ConfigurationPreferences; +import io.sloeber.core.api.Defaults; +import io.sloeber.core.api.VersionNumber; +import io.sloeber.core.common.InstancePreferences; +import io.sloeber.core.managers.InstallProgress; +import io.sloeber.core.tools.MyMultiStatus; +import io.sloeber.core.tools.PackageManager; +import io.sloeber.core.txt.WorkAround; + +/** + * This class groups both boards installed by the hardware manager and boards + * installed locally. + * + * @author jantje + * + */ +public class BoardsManager { + private static final String THIRD_PARTY_URL_FILE = "sloeber_third_party_url.txt"; //$NON-NLS-1$ + + private static Set packageIndices = new HashSet<>(); + private static Set myPackageURLs = new HashSet<>(); + private static boolean myHasbeenLogged = false; + private static boolean envVarsNeedUpdating = true;// reset global variables at startup + + private static HashMap myWorkbenchEnvironmentVariables = new HashMap<>(); + + private static boolean myIsDirty = true; + + private static boolean myIsUpdating =false; + + static { + getPersistentPackageURLList(); + } + + public static boolean isReady() { + return !(myIsDirty || myIsUpdating || envVarsNeedUpdating); + } + + /** + * Gets the board description based on the information provided. If + * jsonFileName="local" the board is assumed not to be installed by the boards + * manager. Otherwise the boardsmanager is queried to find the board descriptor. + * In this case the latest installed board will be returned + * + * @param jsonURL equals to "local" or the name of the json file used by + * the boards manager to install the boards + * @param packageName if jsonFileName equals "local" the filename of the + * boards.txt containing the boards. otherwise the name of + * the package containing the board + * @param architectureID ignored if jsonFileName equals "local" otherwise the + * architecture name of the platform containing the board + * (this assumes the architecture is the unique id for the + * platform) + * @param boardID the id of the board in the boards.txt file + * @param options the options to specify the board (the menu named on the + * boards.txt file) or null for defaults + * @return The class BoardDescriptor or null + */ + static public BoardDescription getBoardDescription(String jsonURL, String packageName, String architectureID, + String boardID, Map options) { + if (LOCAL.equals(jsonURL)) { + return new BoardDescription(jsonURL,new File(packageName), boardID, options); + } + update(false); + return getNewestBoardIDFromBoardsManager(jsonURL, packageName, architectureID, boardID, options); + } + + static private BoardDescription getNewestBoardIDFromBoardsManager(String jsonURL, String packageName, + String architectureID, String boardID, Map options) { + + IArduinoPackage thePackage = getPackage(jsonURL, packageName); + if (thePackage == null) { + System.err.println("failed to find package:" + packageName); //$NON-NLS-1$ + return null; + } + IArduinoPlatform platform = thePackage.getPlatform(architectureID); + if (platform == null) { + System.err.println("failed to find architecture ID " + architectureID + " in package:" + packageName); //$NON-NLS-1$ //$NON-NLS-2$ + return null; + } + IArduinoPlatformVersion platformVersion = platform.getNewestVersion(); + java.io.File boardsFile = platformVersion.getBoardsFile(); + BoardDescription boardid = new BoardDescription(jsonURL,boardsFile, boardID, options); + + return boardid; + } + + public static void addPackageURLs(Collection packageUrlsToAdd) { + Set newList = new HashSet<>(); + newList.addAll(myPackageURLs); + newList.addAll(packageUrlsToAdd); + setPackageURLs(newList); +// HashSet originalJsonUrls = new HashSet<>(Arrays.asList(getJsonURLList())); +// packageUrlsToAdd.addAll(originalJsonUrls); +// +// setJsonURLs(packageUrlsToAdd); +// downloadJsons( forceDownload); +// readJsons(); + } + + public static void setPackageURLs(Collection packageUrls) { + Set orgList = new HashSet<>(); + orgList.addAll(myPackageURLs); + myPackageURLs.clear(); + myPackageURLs.addAll(packageUrls); + if (!orgList.equals(myPackageURLs)) { + myIsDirty = true; + + IPath myThirdPartyURLStoragePath = getThirdPartyURLStoragePath(); + try { + if (myThirdPartyURLStoragePath != null) { + Files.write(myThirdPartyURLStoragePath.toPath(), myPackageURLs, + Charset.forName(StandardCharsets.UTF_8.name())); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +// +// if (!isReady()) { +// Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); +// return; +// } +// setJsonURLs(packageUrls); +// downloadJsons( forceDownload); +// readJsons(); + } + + /** + * installs a subset of the latest platforms It skips the first + * platforms And stops at platforms. To install the 5 first latest + * platforms installsubsetOfLatestPlatforms(0,5) + * + * @param fromIndex the platforms at the start to skip + * @param toIndex the platforms after this platform are skipped + */ + public static void installsubsetOfLatestPlatforms(int fromIndex, int toIndex) { + String DEPRECATED = "DEPRECATED"; //$NON-NLS-1$ + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return; + } + + synchronized (packageIndices) { + int currPlatformIndex = 1; + NullProgressMonitor monitor = new NullProgressMonitor(); + List allPackages = getPackages(); + for (IArduinoPackage curPackage : allPackages) { + Collection latestPlatforms = curPackage.getPlatforms(); + for (IArduinoPlatform curPlatform : latestPlatforms) { + if (!curPlatform.getName().toUpperCase().contains(DEPRECATED)) { + if (currPlatformIndex > fromIndex) { + IArduinoPlatformVersion latestPlatformVersion = curPlatform.getNewestVersion(); + if (!latestPlatformVersion.getName().toUpperCase().contains(DEPRECATED)) { + install(latestPlatformVersion, monitor); + } else { + System.out.println("skipping platform " + latestPlatformVersion.toString()); //$NON-NLS-1$ + } + } + if (currPlatformIndex++ > toIndex) { + return; + } + } else { + System.out.println("skipping platform " + curPlatform.toString()); //$NON-NLS-1$ + } + } + } + } + } + + /** + * Install all the latest platforms Assumes there are less than 100000 platforms + */ + public static void installAllLatestPlatforms() { + installsubsetOfLatestPlatforms(0, 100000); + } + + public static void installLatestPlatform(String JasonName, String packagerName, String architectureName) { + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return; + } + internalInstallLatestPlatform( JasonName, packagerName, architectureName); + } + + private static void internalInstallLatestPlatform(String JasonName, String packagerName, String architectureName) { + synchronized (packageIndices) { + IArduinoPackage curPackage = getPackage(JasonName, packagerName); + if (curPackage != null) { + IArduinoPlatform curPlatform = curPackage.getPlatform(architectureName); + if (curPlatform != null) { + IArduinoPlatformVersion curPlatformVersion = curPlatform.getNewestVersion(); + if (curPlatformVersion != null) { + NullProgressMonitor monitor = new NullProgressMonitor(); + install(curPlatformVersion, monitor); + return; + } + } + } + } + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + "failed to find " + JasonName + " " + packagerName + " " + architectureName)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + private static IStatus install(IArduinoPlatformVersion platformVersion, IProgressMonitor monitor) { + boolean forceDownload = false; + // Check if we're installed already + if (platformVersion.isInstalled()) { + System.out.println("reusing platform " + platformVersion.toString()); //$NON-NLS-1$ + return Status.OK_STATUS; + } + + envVarsNeedUpdating = true; + + // Download platform archive + System.out.println("start installing platform " + platformVersion.toString()); //$NON-NLS-1$ + + MyMultiStatus mstatus = new MyMultiStatus("Failed to install " + platformVersion.getName()); //$NON-NLS-1$ + mstatus.addErrors(PackageManager.downloadAndInstall(platformVersion, forceDownload, monitor)); + if (!mstatus.isOK()) { + // no use installing tools when the boards failed installing + return mstatus; + } + + // keep a copy of the json file used at install + File packageFile = platformVersion.getParent().getParent().getPackageIndex().getJsonFile(); + File copyToFile = platformVersion.getInstallPath().append(packageFile.getName()).toFile(); + try { + Files.copy(packageFile.toPath(), copyToFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + e.printStackTrace(); + } + + IArduinoPackage referencingPkg = platformVersion.getParent().getParent(); + for (ArduinoPlatformTooldDependency toolDependency : platformVersion.getToolsDependencies()) { + ArduinoPlatformToolVersion tool = referencingPkg.getTool(toolDependency.getName(), + toolDependency.getVersion()); + if (tool == null) { + // this is a tool provided by another platform + // and the referencing platform does not specify the installable info + // This means the package file of the referencing platform needs to be provided + IArduinoPackage pkg = getPackageByProvider(toolDependency.getPackager()); + if (pkg != null) { + tool = pkg.getTool(toolDependency.getName(), toolDependency.getVersion()); + } + } + if (tool == null) { + mstatus.add(new Status(IStatus.ERROR, Activator.getId(), + Messages.Tool_no_valid_system.replace(Messages.KEY_TAG, toolDependency.getName()))); + } else if (!tool.isInstalled()) { + ArduinoInstallable installable = tool.getInstallable(); + if (installable != null) { + monitor.setTaskName(InstallProgress.getRandomMessage()); + mstatus.addErrors(PackageManager.downloadAndInstall(installable, forceDownload, monitor)); + } + } + } + + WorkAround.applyKnownWorkArounds(platformVersion); + + System.out.println("done installing platform " + platformVersion.toString()); //$NON-NLS-1$ + return mstatus; + } + + public static void addPrivateHardwarePath(String newHardwarePath) { + if (newHardwarePath == null) { + return; + } + String currentPaths[] = InstancePreferences.getPrivateHardwarePaths(); + String newPaths[] = new String[currentPaths.length + 1]; + for (int i = 0; i < currentPaths.length; i++) { + if (currentPaths[i].equals(newHardwarePath)) { + return; + } + newPaths[i] = currentPaths[i]; + } + newPaths[currentPaths.length] = newHardwarePath; + InstancePreferences.setPrivateHardwarePaths(newPaths); + } + + /** + * Searches for all boards.txt files from the hardware folders and the boards + * manager + * + * @return all the boards.txt files with full path and in a case insensitive + * order + */ + public static File[] getAllBoardsFiles() { + update(false); + String hardwareFolders[] = getHardwarePaths(); + + TreeSet boardFiles = new TreeSet<>(); + for (String CurFolder : hardwareFolders) { + searchFiles(new File(CurFolder), boardFiles, BOARDS_FILE_NAME, 6); + } + if (boardFiles.size() == 0) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Helpers_No_boards_txt_found.replace(FILE_TAG, String.join("\n", hardwareFolders)), null)); //$NON-NLS-1$ + return null; + } + return boardFiles.toArray(new File[boardFiles.size()]); + } + + private static void searchFiles(File folder, TreeSet Hardwarelists, String Filename, int depth) { + if (depth > 0) { + File[] a = folder.listFiles(); + if (a == null) { + if (!myHasbeenLogged) { + Activator.log(new Status(IStatus.INFO, CORE_PLUGIN_ID, + Helpers_Error_The_folder_is_empty.replace(FOLDER_TAG, folder.toString()), null)); + myHasbeenLogged = true; + } + return; + } + for (File f : a) { + if (f.isDirectory()) { + // ignore folders named tools + if (!f.getName().equals(TOOLS)) { + searchFiles(f, Hardwarelists, Filename, depth - 1); + } + } else if (f.getName().equals(Filename)) { + Hardwarelists.add(f); + } + } + } + } + + /** + * Gets all the folders that can contain hardware + * + * @return a list of all the folder locations that can contain hardware + */ + private static String[] getHardwarePaths() { + return (InstancePreferences.getPrivateHardwarePathsString() + File.pathSeparator + + ConfigurationPreferences.getInstallationPathPackages()).split(File.pathSeparator); + } + + public static IStatus updatePlatforms(List platformsToInstall, + List platformsToRemove, IProgressMonitor monitor, MultiStatus status) { + if (myIsDirty) { + status.add(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, null)); + return status; + } +// //TODO updating the jsons after selecting what to install seems dangerous to me; check to delete +// if (!ConfigurationPreferences.getUpdateJasonFilesFlag()) { +// downloadJsons( true); +// readJsons(); +// } + try { + synchronized (packageIndices) { + for (IArduinoPlatformVersion curPlatform : platformsToRemove) { + status.add(uninstall(curPlatform)); + } + for (IArduinoPlatformVersion curPlatform : platformsToInstall) { + status.add(install(curPlatform, monitor)); + } + } + } catch (@SuppressWarnings("unused") Exception e) { + // do nothing + } + return status; + } + + private static IStatus uninstall(IArduinoPlatformVersion curPlatform) { + if (!curPlatform.isInstalled()) { + return Status.OK_STATUS; + } + + IPath installFolder = curPlatform.getInstallPath(); + try { + deleteDirectory(installFolder); + envVarsNeedUpdating = true; + } catch (IOException e) { + return new Status(IStatus.ERROR, Activator.getId(), "Failed to remove folder" + installFolder.toOSString(), //$NON-NLS-1$ + e); + } + + return Status.OK_STATUS; + } + +// public static TreeMap getAllmenus() { +// update(false); +// TreeMap ret = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); +// File[] boardFiles = getAllBoardsFiles(); +// for (File curBoardFile : boardFiles) { +// BoardTxtFile txtFile = new BoardTxtFile(curBoardFile); +// ret.putAll(txtFile.getMenus()); +// } +// return ret; +// } + + public static void setPrivateHardwarePaths(String[] hardWarePaths) { + InstancePreferences.setPrivateHardwarePaths(hardWarePaths); + } + + public static String getPrivateHardwarePathsString() { + return InstancePreferences.getPrivateHardwarePathsString(); + } + + /** + * Download the json files from the internet If the file has already been + * downloaded it will only be downloaded again when forceDownload is true + * + * If the file exists and the download fails the original file will not be + * deleted. + * + * @param forceDownload if true all the json files will be replaced with new + * versions + */ + private static void downloadJsons(boolean forceDownload) { + String[] jsonUrls = getJsonURLList(); + for (String jsonUrl : jsonUrls) { + if (!jsonUrl.trim().isEmpty()) // skip empty lines + downloadJson(jsonUrl, forceDownload); + } + } + + private static void downloadJson(String jsonUrl, boolean forceDownload) { + File jsonFile = getLocalFileName(jsonUrl, true); + if (jsonFile == null) { + return; + } + File jsonTmpFile = new File(jsonFile.toString() + ".new"); //$NON-NLS-1$ + File jsonOldFile = new File(jsonFile.toString() + ".prev"); //$NON-NLS-1$ + if (!jsonFile.exists() || forceDownload) { + jsonFile.getParentFile().mkdirs(); + try { + if (jsonTmpFile.exists()) { + jsonTmpFile.delete(); + } + PackageManager.mySafeCopy(new URL(jsonUrl.trim()), jsonTmpFile, false); + if (jsonOldFile.exists()) { + jsonOldFile.delete(); + } + jsonFile.renameTo(jsonOldFile); + jsonTmpFile.renameTo(jsonFile); + } catch (IOException e) { + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "Unable to download " + jsonUrl, e)); //$NON-NLS-1$ + } + } + } + + /** + * This method takes all the json boards file urls and downloads them and parses + * them for usage in the boards manager + * + * @param url the url of the file to download and load + * @param forceDownload set true if you want to download the file even if it is + * already available locally + */ + private static void readJsons() { + LibraryManager.flushIndices(); + packageIndices.clear(); + + String[] jsonUrls = getJsonURLList(); + for (String jsonUrl : jsonUrls) { + if (!jsonUrl.isBlank()) {// skip empty lines + File jsonFile = getLocalFileName(jsonUrl, true); + if (jsonFile == null) { + return; + } + if (jsonFile.exists()) { + if (jsonFile.getName().toLowerCase().startsWith("package_")) { //$NON-NLS-1$ + loadPackageJson(jsonUrl, jsonFile); + } else if (jsonFile.getName().toLowerCase().startsWith("library_")) { //$NON-NLS-1$ + LibraryManager.loadJson(jsonFile); + } else { + Activator.log(new Status(IStatus.ERROR, Activator.getId(), + "json files should start with \"package_\" or \"library_\" " + jsonUrl //$NON-NLS-1$ + + " is ignored")); //$NON-NLS-1$ + } + } + } + } + } + + static private void loadPackageJson(String url, File jsonFile) { + try (Reader reader = new FileReader(jsonFile)) { + ArduinoPlatformPackageIndex index = new Gson().fromJson(reader, ArduinoPlatformPackageIndex.class); + index.setPackageFile(jsonFile); + index.setURL(url); + packageIndices.add(index); + } catch (Exception e) { + Activator.log(new Status(IStatus.ERROR, Activator.getId(), + Manager_Failed_to_parse.replace(FILE_TAG, jsonFile.getAbsolutePath()), e)); + jsonFile.delete();// Delete the file so it stops damaging + } + } + + /** + * convert a web url to a local file name. The local file name is the cache of + * the web + * + * @param url url of the file we want a local cache + * @return the file that represents the file that is the local cache. the file + * itself may not exists. If the url is malformed return null; + * @throws MalformedURLException + */ + private static File getLocalFileName(String url, boolean show_error) { + URL packageUrl; + try { + packageUrl = new URL(url.trim()); + } catch (MalformedURLException e) { + if (show_error) { + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "Malformed url " + url, e)); //$NON-NLS-1$ + } + return null; + } + if ("file".equals(packageUrl.getProtocol())) { //$NON-NLS-1$ + String tst = packageUrl.getFile(); + File file = new File(tst); + String localFileName = file.getName(); + java.nio.file.Path packagePath = Paths + .get(ConfigurationPreferences.getInstallationPath().append(localFileName).toString()); + return packagePath.toFile(); + } + String localFileName = Paths.get(packageUrl.getPath()).getFileName().toString(); + java.nio.file.Path packagePath = Paths + .get(ConfigurationPreferences.getInstallationPath().append(localFileName).toString()); + return packagePath.toFile(); + } + + public static String[] getDefaultJsonURLs() { + return Defaults.DEFAULT_JSON_URLS; + } + + public static String[] getJsonURLList() { + return myPackageURLs.toArray(new String[myPackageURLs.size()]); + } + + private static void getPersistentPackageURLList() { + myPackageURLs.clear(); + IPath myThirdPartyURLStoragePath = getThirdPartyURLStoragePath(); + try { + if (myThirdPartyURLStoragePath != null && myThirdPartyURLStoragePath.toFile().exists()) { + List thirdPartyURLs = Files.readAllLines(myThirdPartyURLStoragePath.toPath(), + Charset.forName(StandardCharsets.UTF_8.name())); + if (thirdPartyURLs.size() > 0) { + myPackageURLs.addAll(thirdPartyURLs); + return; + } + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // The new way of storing the thirdparty urls's failed + // try the Sloeber V3 way for downwards compatibility + String[] sloeberV4Storage = getString("Manager jsons", EMPTY_STRING).replace("\r", new String()).split("\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (sloeberV4Storage.length > 3) { + myPackageURLs.addAll(Arrays.asList(sloeberV4Storage)); + return; + } + // Everything failed; This is probably a new install; return the defaults; + myPackageURLs.addAll(Arrays.asList(Defaults.DEFAULT_JSON_URLS)); + + } + + private static IPath getThirdPartyURLStoragePath() { + return sloeberHomePath.append(SLOEBER_HOME_SUB_FOLDER).append(THIRD_PARTY_URL_FILE); + } + + public static void removeAllInstalledPlatforms() { + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return; + } + try { + synchronized (packageIndices) { + deleteDirectory(ConfigurationPreferences.getInstallationPathPackages()); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static IPath getInstallationPath() { + return ConfigurationPreferences.getInstallationPath(); + } + + /** + * If something has been installed or deinstalled update the global variables + * with references to the installed stuff this to support platforms that do not + * explicitly define tools or platform dependencies Like private hardware + */ + public static Map getEnvironmentVariables() { + update(false); + return myWorkbenchEnvironmentVariables; + } + + private static Map getEnvVarPlatformFileTools(IArduinoPlatformVersion platformVersion) { + HashMap vars = new HashMap<>(); + IArduinoPackage pkg = platformVersion.getParent().getParent(); + for (ArduinoPlatformTooldDependency tool : platformVersion.getToolsDependencies()) { + ArduinoPlatformTool theTool = pkg.getTool(tool.getName()); + if (theTool == null) { + System.err.println("Did not find " + tool.getName() + " in package with ID " + pkg.getID()); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + vars.putAll(theTool.getEnvVars(null)); + } + } + return vars; + } + + /** + * given a vendor and a architecture provide the newest installed platform + * version + * + * @param vendor + * @param architecture + * @return the found platformVersion or null if none found + */ + public static IArduinoPlatformVersion getNewestInstalledPlatform(String vendor, String architecture) { + IArduinoPlatform platform = getPlatform(vendor, architecture); + if (platform == null) { + return null; + } + return platform.getNewestInstalled(); + } + + // Below is what used to be the internal package manager class + + public static List getPackageIndices() { + update(false); + return new LinkedList<>(packageIndices); + } + +// public static List getPlatforms() { +// List platforms = new ArrayList<>(); +// for (IArduinoPlatformPackageIndex index : getPackageIndices()) { +// for (IArduinoPackage pkg : index.getPackages()) { +// platforms.addAll(pkg.getPlatforms()); +// } +// } +// return platforms; +// } + + public static IArduinoPlatform getPlatform( String vendor, String architecture) { + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return null; + } + for (IArduinoPlatformPackageIndex index : packageIndices) { + IArduinoPackage pkg = index.getPackage(vendor); + if (pkg != null) { + IArduinoPlatform platform = pkg.getPlatform(architecture); + if (platform != null) { + return platform; + } + } + } + return null; + } + + /** + * Given a platform.txt file find the platform in the platform manager + * + * @param platformTxt + * @return the found platform otherwise null + */ + public static IArduinoPlatformVersion getPlatform(IPath platformPath) { + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return null; + } + for (IArduinoPlatformPackageIndex index : packageIndices) { + for (IArduinoPackage pkg : index.getPackages()) { + for (IArduinoPlatform curPlatform : pkg.getPlatforms()) { + if (platformPath + .matchingFirstSegments(curPlatform.getInstallPath()) > (platformPath.segmentCount() - 2)) + + for (IArduinoPlatformVersion curPlatformVersion : curPlatform.getVersions()) { + if (curPlatformVersion.getInstallPath().equals(platformPath)) { + return curPlatformVersion; + } + } + } + } + } + return null; + } + +// static public List getInstalledPlatforms() { +// List platforms = new ArrayList<>(); +// for (IArduinoPlatformPackageIndex index : getPackageIndices()) { +// for (IArduinoPackage pkg : index.getPackages()) { +// platforms.addAll(pkg.getInstalledPlatforms()); +// } +// } +// return platforms; +// } + + /** + * Get any installed platform version This can be used in case of error + * conditions where any platform is better than null + * + * @return a platform or null if no platforms are installed + */ + static public IArduinoPlatformVersion getAnyInstalledPlatform() { + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return null; + } + for (IArduinoPlatformPackageIndex index : packageIndices) { + for (IArduinoPackage pkg : index.getPackages()) { + for (IArduinoPlatformVersion platformVersion : pkg.getInstalledPlatforms()) { + return platformVersion; + } + } + } + return null; + } + + static private boolean areThereInstalledBoards() { + for (IArduinoPlatformPackageIndex index : packageIndices) { + for (IArduinoPackage pkg : index.getPackages()) { + if (pkg.isInstalled()) { + return true; + } + } + } + return false; + } + + static public List getPackages() { + List packages = new ArrayList<>(); + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return packages; + } + + for (IArduinoPlatformPackageIndex index : packageIndices) { + packages.addAll(index.getPackages()); + } + + return packages; + } + + static private IArduinoPackage getPackage(String jasonURL, String packageName) { + for (IArduinoPlatformPackageIndex index : packageIndices) { + if (index.getJsonURL().equals(jasonURL)) { + return index.getPackage(packageName); + } + } + return null; + } + +// static public IArduinoPackage getPackage(String packageName) { +// for (IArduinoPlatformPackageIndex index : getPackageIndices()) { +// IArduinoPackage pkg = index.getPackage(packageName); +// if (pkg != null) { +// return pkg; +// } +// } +// return null; +// } + + /** + * Remove all packages that have a more recent version + */ + public static void onlyKeepLatestPlatforms() { + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return; + } + synchronized (packageIndices) { + List allPackages = getPackages(); + for (IArduinoPackage curPackage : allPackages) { + onlyKeepLatestPlatforms(curPackage); + } + } + } + + private static void onlyKeepLatestPlatforms(IArduinoPackage curPackage) { + for (IArduinoPlatform curplatform : curPackage.getPlatforms()) { + IArduinoPlatformVersion newestVersion = null; + for (IArduinoPlatformVersion curVersion : curplatform.getVersions()) { + if (curVersion.isInstalled()) { + if (newestVersion == null) { + newestVersion = curVersion; + } else { + if (newestVersion.getVersion().compareTo(curVersion.getVersion()) > 0) { + uninstall(curVersion); + } else { + uninstall(newestVersion); + } + } + } + } + } + } + + public static IArduinoPlatformVersion getPlatform( String vendor, String architecture, VersionNumber refVersion) { + IArduinoPlatform platform = getPlatform(vendor, architecture); + if (platform != null) { + return platform.getVersion(refVersion); + } + return null; + } + + public static IArduinoPackage getPackageByProvider(String packager) { + if (myIsDirty) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); + return null; + } + for (IArduinoPlatformPackageIndex index : packageIndices) { + for (IArduinoPackage pkg : index.getPackages()) { + if (packager.equals(pkg.getID())) { + return pkg; + } + } + } + return null; + } + + /** + * If there are changes to the package url's this method will process these + * changes + * + * If there are no boards installed this methoid will install the latest arduino + * avr boards + * + * @param reloadFromInternet if true the downloaded the package files will be + * replaced with a newer download (if download + * succeeded) + */ + public static void update(boolean reloadFromInternet) { + synchronized (packageIndices) { + myIsUpdating =true; + if (myIsDirty || reloadFromInternet) { + downloadJsons(reloadFromInternet); + readJsons(); + if(reloadFromInternet) { + ConfigurationPreferences.setLatestUpdateTime(Instant.now()); + } + + } + + if (!areThereInstalledBoards()) { + internalInstallLatestPlatform(Defaults.DEFAULT_INSTALL_JSON, Defaults.DEFAULT_INSTALL_MAINTAINER, + Defaults.DEFAULT_INSTALL_ARCHITECTURE); + } + + myIsDirty = false; + + if (envVarsNeedUpdating) { + myWorkbenchEnvironmentVariables.clear(); + IArduinoPlatformVersion latestAvrPlatform = getNewestInstalledPlatform(VENDOR_ARDUINO, AVR); + IArduinoPlatformVersion latestSamdPlatform = getNewestInstalledPlatform(VENDOR_ARDUINO, SAMD); + IArduinoPlatformVersion latestSamPlatform = getNewestInstalledPlatform(VENDOR_ARDUINO, SAM); + + if (latestSamdPlatform != null) { + myWorkbenchEnvironmentVariables.putAll(getEnvVarPlatformFileTools(latestSamdPlatform)); + } + if (latestSamPlatform != null) { + myWorkbenchEnvironmentVariables.putAll(getEnvVarPlatformFileTools(latestSamPlatform)); + } + if (latestAvrPlatform != null) { + myWorkbenchEnvironmentVariables.putAll(getEnvVarPlatformFileTools(latestAvrPlatform)); + } + envVarsNeedUpdating = false; + } + } + myIsUpdating=false; + } + + public static String getjsonURLFormBoardsFile(File boardsFile) { + File expandedBoardsFile = resolvePathEnvironmentString(boardsFile); + String ret=null; + for (IArduinoPlatformPackageIndex index : packageIndices) { + ret=index.getJsonURL(); + for (IArduinoPackage pkg : index.getPackages()) { + for (IArduinoPlatformVersion platformVersion : pkg.getInstalledPlatforms()) { + + if(platformVersion.getBoardsFile().equals(expandedBoardsFile)) { + return ret; + } + } + } + } + return ret; + } + +} diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibrary.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibrary.java new file mode 100644 index 000000000..c2f7c703e --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibrary.java @@ -0,0 +1,53 @@ +package io.sloeber.arduinoFramework.api; + +import java.util.Collection; +import java.util.List; + +import org.eclipse.core.runtime.IPath; + +import io.sloeber.core.api.VersionNumber; + +public abstract class IArduinoLibrary extends Node implements Comparable{ + + public abstract Collection getVersions(); + + public abstract String getAuthor(); + + public abstract String getMaintainer(); + + public abstract String getWebsite(); + + public abstract String getCategory(); + + public abstract List getArchitectures(); + + public abstract List getTypes(); + + /** + * Get the newest version of this library + * + * @return the newest version of this library + */ + public abstract IArduinoLibraryVersion getNewestVersion(); + + /** + * Get the version that is installed + * If no version is installed return NULL + * + * @return + */ + public abstract IArduinoLibraryVersion getInstalledVersion(); + + /** + * checks if a version of this library is installed. + * + * @return true if a version is installed. false in case no version is installed + */ + public abstract boolean isInstalled(); + + + public abstract IArduinoLibraryVersion getVersion(VersionNumber versionNumber); + + public abstract IPath getInstallPath(); + +} \ No newline at end of file diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibraryIndex.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibraryIndex.java new file mode 100644 index 000000000..fac54de7b --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibraryIndex.java @@ -0,0 +1,31 @@ +package io.sloeber.arduinoFramework.api; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; + + +public interface IArduinoLibraryIndex extends Comparable{ + + /** + * given a library name provide the library + * + * @param libraryName + * @return the library or null if not found + */ + IArduinoLibrary getLibrary(String libraryName); + + /** + * get all the latest versions of all the libraries provided that can be + * installed but are not yet installed To do so I find all latest libraries and + * I remove the once that are installed. + * + * @return + */ + Map getLatestInstallableLibraries(Set libNames); + + Collection getLibraries(); + + String getID(); + +} \ No newline at end of file diff --git a/io.sloeber.core/src/io/sloeber/core/api/IArduinoLibraryVersion.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibraryVersion.java similarity index 60% rename from io.sloeber.core/src/io/sloeber/core/api/IArduinoLibraryVersion.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibraryVersion.java index c91d08d7d..368e4df2c 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/IArduinoLibraryVersion.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoLibraryVersion.java @@ -1,8 +1,12 @@ -package io.sloeber.core.api; +package io.sloeber.arduinoFramework.api; + +import java.util.List; import org.eclipse.core.runtime.IPath; -public interface IArduinoLibraryVersion { +import io.sloeber.core.api.VersionNumber; + +public interface IArduinoLibraryVersion extends Comparable{ String getName(); @@ -39,5 +43,21 @@ public interface IArduinoLibraryVersion { public boolean equals(IArduinoLibraryVersion other); + IArduinoLibrary getLibrary(); + + VersionNumber getVersion(); + + boolean isInstalled(); + + List getArchitectures(); + + String getParagraph(); + + String getSentence(); + + String getMaintainer(); + + String getAuthor(); + } diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPackage.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPackage.java new file mode 100644 index 000000000..47dc56f5c --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPackage.java @@ -0,0 +1,67 @@ +package io.sloeber.arduinoFramework.api; + +import java.util.Collection; +import java.util.List; + +import org.eclipse.core.runtime.IPath; + +import io.sloeber.arduinoFramework.internal.ArduinoPlatformTool; +import io.sloeber.arduinoFramework.internal.ArduinoPlatformToolVersion; +import io.sloeber.core.api.VersionNumber; + +public interface IArduinoPackage extends Comparable{ + + IArduinoPlatformPackageIndex getPackageIndex(); + + String getMaintainer(); + + String getWebsiteURL(); + + String getEmail(); + + String getHelp(); + + Collection getPlatforms(); + + /** + * This method looks up the installed platforms So if you have 2 arduino avr + * platform versions installed you will get back 2. + * + * @return all the installed platforms + */ + List getInstalledPlatforms(); + + /** + * get tyhe platform based on the platform ID + * The platform ID is the architecture + * + * @param platformID + * @return return the platfiorm or null if not found + */ + IArduinoPlatform getPlatform(String platformID); + + Collection getTools(); + + ArduinoPlatformToolVersion getTool(String toolName, VersionNumber version); + + ArduinoPlatformTool getTool(String toolName); + + ArduinoPlatformToolVersion getNewestInstalled(String toolName); + + boolean isInstalled(); + + /** + * Is any version of the platform installed + * + * @param platformName + * @return if a platform with this name is installed + */ + boolean isAVersionOfThisPlatformInstalled(String platformName); + + String getID(); + + IPath getInstallPath(); + + String getName(); + +} \ No newline at end of file diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatform.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatform.java new file mode 100644 index 000000000..069682e0f --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatform.java @@ -0,0 +1,42 @@ +package io.sloeber.arduinoFramework.api; + +import java.util.Collection; + +import org.eclipse.core.runtime.IPath; + +import io.sloeber.core.api.VersionNumber; + +public interface IArduinoPlatform extends Comparable{ + + boolean isInstalled(); + + IPath getInstallPath(); + + /** + * Get the newest version of this platform + * + * @return the newest version of this platform + */ + IArduinoPlatformVersion getNewestVersion(); + + Collection getVersions(); + + IArduinoPlatformVersion getVersion(VersionNumber refVersion); + + /** + * return the installed version with the newest version number + * Null if no version is installed + * + * @return + */ + IArduinoPlatformVersion getNewestInstalled(); + + String getName(); + + String getArchitecture(); + + IArduinoPackage getParent(); + + String getID(); + +} \ No newline at end of file diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatformPackageIndex.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatformPackageIndex.java new file mode 100644 index 000000000..250c17262 --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatformPackageIndex.java @@ -0,0 +1,23 @@ +package io.sloeber.arduinoFramework.api; + +import java.io.File; +import java.util.List; + + +public interface IArduinoPlatformPackageIndex { + + List getPackages(); + + IArduinoPackage getPackage(String packageName); + + File getJsonFile(); + + boolean isInstalled(); + + String getID(); + + String getName(); + + String getJsonURL(); + +} \ No newline at end of file diff --git a/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatformVersion.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatformVersion.java new file mode 100644 index 000000000..3b84efc1a --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IArduinoPlatformVersion.java @@ -0,0 +1,34 @@ +package io.sloeber.arduinoFramework.api; + +import java.io.File; +import java.util.List; + +import io.sloeber.arduinoFramework.internal.ArduinoPlatformTooldDependency; +import io.sloeber.core.api.VersionNumber; + +public abstract class IArduinoPlatformVersion extends ArduinoInstallable implements Comparable{ + + public abstract IArduinoPlatform getParent(); + + public abstract String getArchitecture(); + + public abstract VersionNumber getVersion(); + + public abstract String getCategory(); + + public abstract List getToolsDependencies(); + + public abstract boolean isInstalled(); + + public abstract File getBoardsFile(); + + public abstract File getPlatformFile(); + + public abstract List getBoardNames(); + + public abstract String getID(); + + public abstract String getConcattenatedBoardNames(); + + +} \ No newline at end of file diff --git a/io.sloeber.core/src/io/sloeber/core/api/IExample.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IExample.java similarity index 88% rename from io.sloeber.core/src/io/sloeber/core/api/IExample.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/api/IExample.java index f38712c82..407256353 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/IExample.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/IExample.java @@ -1,4 +1,4 @@ -package io.sloeber.core.api; +package io.sloeber.arduinoFramework.api; import java.util.Collection; diff --git a/io.sloeber.core/src/io/sloeber/core/api/LibraryManager.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/LibraryManager.java similarity index 70% rename from io.sloeber.core/src/io/sloeber/core/api/LibraryManager.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/api/LibraryManager.java index 95ab3ad93..455cffb20 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/LibraryManager.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/LibraryManager.java @@ -1,4 +1,4 @@ -package io.sloeber.core.api; +package io.sloeber.arduinoFramework.api; import static io.sloeber.core.Messages.*; import static io.sloeber.core.api.Common.*; @@ -18,6 +18,7 @@ import java.util.TreeMap; import java.util.TreeSet; +import org.eclipse.core.resources.IFolder; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; @@ -28,14 +29,16 @@ import com.google.gson.Gson; +import io.sloeber.arduinoFramework.internal.ArduinoLibraryIndex; +import io.sloeber.arduinoFramework.internal.ArduinoLibraryVersion; import io.sloeber.core.Activator; -import io.sloeber.core.api.Json.ArduinoLibrary; -import io.sloeber.core.api.Json.ArduinoLibraryIndex; -import io.sloeber.core.api.Json.ArduinoLibraryVersion; +import io.sloeber.core.api.ConfigurationPreferences; +import io.sloeber.core.api.Defaults; +import io.sloeber.core.api.IInstallLibraryHandler; import io.sloeber.core.common.InstancePreferences; import io.sloeber.core.core.DefaultInstallHandler; import io.sloeber.core.internal.ArduinoHardwareLibrary; -import io.sloeber.core.internal.ArduinoPrivateLibraryVersion; +import io.sloeber.core.internal.ArduinoPrivateHardwareLibraryVersion; import io.sloeber.core.internal.Example; import io.sloeber.core.tools.FileModifiers; import io.sloeber.core.tools.PackageManager; @@ -55,10 +58,10 @@ public class LibraryManager { private static final Set IGNORE_FILES = new HashSet<>(Arrays.asList(DOT, DOT + DOT)); private static final Set CODE_EXTENSIONS = new HashSet<>(Arrays.asList("h", "cpp")); //$NON-NLS-1$ //$NON-NLS-2$ - static private List libraryIndices; + static private List libraryIndices; private static IInstallLibraryHandler myInstallLibraryHandler = new DefaultInstallHandler(); - static public List getLibraryIndices() { + static public List getLibraryIndices() { if (libraryIndices == null) { BoardsManager.getPackageIndices(); } @@ -84,19 +87,23 @@ public static String getPrivateLibraryPathsString() { return InstancePreferences.getPrivateLibraryPathsString(); } + public static String[] getPrivateLibraryPaths() { + return InstancePreferences.getPrivateLibraryPaths(); + } + public static void setPrivateLibraryPaths(String[] libraryPaths) { InstancePreferences.setPrivateLibraryPaths(libraryPaths); } public static void InstallDefaultLibraries(IProgressMonitor monitor) { - for (ArduinoLibraryIndex libindex : libraryIndices) { + for (IArduinoLibraryIndex libindex : libraryIndices) { for (String libraryName : Defaults.DEFAULT_INSTALLED_LIBRARIES) { - ArduinoLibrary toInstalLib = libindex.getLibrary(libraryName); + IArduinoLibrary toInstalLib = libindex.getLibrary(libraryName); if (toInstalLib != null) { - ArduinoLibraryVersion toInstalLibVersion = toInstalLib.getNewestVersion(); - ArduinoLibraryVersion instaledLibVersion = toInstalLib.getInstalledVersion(); + IArduinoLibraryVersion toInstalLibVersion = toInstalLib.getNewestVersion(); + IArduinoLibraryVersion instaledLibVersion = toInstalLib.getInstalledVersion(); if (toInstalLibVersion != null) { if (toInstalLibVersion != instaledLibVersion) { if (instaledLibVersion != null) { @@ -112,11 +119,11 @@ public static void InstallDefaultLibraries(IProgressMonitor monitor) { static public void loadJson(File jsonFile) { try (Reader reader = new FileReader(jsonFile)) { - ArduinoLibraryIndex index = new Gson().fromJson(reader, ArduinoLibraryIndex.class); - index.setJsonFile(jsonFile); + IArduinoLibraryIndex index = new Gson().fromJson(reader, ArduinoLibraryIndex.class); + ((ArduinoLibraryIndex)index).setJsonFile(jsonFile); libraryIndices.add(index); } catch (Exception e) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), + Activator.log(new Status(IStatus.ERROR, Activator.getId(), Manager_Failed_to_parse.replace(FILE_TAG, jsonFile.getAbsolutePath()), e)); jsonFile.delete();// Delete the file so it stops damaging } @@ -139,6 +146,7 @@ public static void installLibrary(String libName) { } } + public static IStatus install(IArduinoLibraryVersion inLib, IProgressMonitor monitor) { if (!(inLib instanceof ArduinoLibraryVersion)) { return Status.error("Trying to install a library that is not a installable library" + inLib.getName()); //$NON-NLS-1$ @@ -162,7 +170,7 @@ public static IStatus install(IArduinoLibraryVersion inLib, IProgressMonitor mon * @param monitor * @return Status.OK_STATUS if delete is successful otherwise IStatus.ERROR */ - public static IStatus unInstall(ArduinoLibraryVersion lib, IProgressMonitor monitor) { + public static IStatus unInstall(IArduinoLibraryVersion lib, IProgressMonitor monitor) { if (!lib.isInstalled()) { return Status.OK_STATUS; } @@ -171,7 +179,7 @@ public static IStatus unInstall(ArduinoLibraryVersion lib, IProgressMonitor moni deleteDirectory(lib.getInstallPath().removeLastSegments(1)); } catch (IOException e) { return new Status(IStatus.ERROR, Activator.getId(), - "Failed to remove folder" + lib.getInstallPath().toString(), //$NON-NLS-1$ + "Failed to remove folder" + lib.getInstallPath().toOSString(), //$NON-NLS-1$ e); } @@ -186,16 +194,16 @@ public static IStatus unInstall(ArduinoLibraryVersion lib, IProgressMonitor moni * @param category */ public static void installAllLatestLibraries() { - List libraryIndices1 = getLibraryIndices(); - for (ArduinoLibraryIndex libraryIndex : libraryIndices1) { - for (ArduinoLibrary curLib : libraryIndex.getLibraries()) { + List libraryIndices1 = getLibraryIndices(); + for (IArduinoLibraryIndex libraryIndex : libraryIndices1) { + for (IArduinoLibrary curLib : libraryIndex.getLibraries()) { String curLibName = curLib.getNodeName(); String[] skipArray = { "Base64", "Add others if needed" }; //$NON-NLS-1$ //$NON-NLS-2$ List skipList = Arrays.asList(skipArray); if (!skipList.contains(curLibName)) { - ArduinoLibraryVersion latestLibVersion = curLib.getNewestVersion(); + IArduinoLibraryVersion latestLibVersion = curLib.getNewestVersion(); if (!latestLibVersion.isInstalled()) { - ArduinoLibraryVersion installedLibVersion = curLib.getInstalledVersion(); + IArduinoLibraryVersion installedLibVersion = curLib.getInstalledVersion(); if (installedLibVersion != null) { unInstall(installedLibVersion, null); } @@ -221,7 +229,7 @@ public static void unInstallAllLibs() { public static Map getLatestInstallableLibraries(Set libnames) { Set remainingLibNames = new TreeSet<>(libnames); Map ret = new HashMap<>(); - for (ArduinoLibraryIndex libraryIndex : libraryIndices) { + for (IArduinoLibraryIndex libraryIndex : libraryIndices) { ret.putAll(libraryIndex.getLatestInstallableLibraries(remainingLibNames)); remainingLibNames.removeAll(ret.keySet()); } @@ -261,7 +269,7 @@ public static TreeMap getExamplesLibrary(BoardDescription boar Map installedLibs = getLibrariesAll(boardDescriptor); for (IArduinoLibraryVersion curLib : installedLibs.values()) { - examples.putAll(getExamplesFromFolder(curLib, curLib.getExamplePath().toFile(), 2)); + examples.putAll(getExamplesFromFolder(curLib, curLib.getExamplePath().toFile(), 3)); } return examples; @@ -320,17 +328,28 @@ public static TreeMap getExamplesFromIDE() { return examples; } - public static IStatus updateLibraries(Set toUnInstallLibs, - Set toInstallLibs, IProgressMonitor monitor, MultiStatus status) { - for (ArduinoLibraryVersion curLib : toUnInstallLibs) { + public static IStatus updateLibraries(Set toUnInstallLibs, + Set toInstallLibs, IProgressMonitor monitor, MultiStatus status) { + for (IArduinoLibraryVersion curLib : toUnInstallLibs) { status.add(unInstall(curLib, monitor)); } - for (ArduinoLibraryVersion curLib : toInstallLibs) { + for (IArduinoLibraryVersion curLib : toInstallLibs) { status.add(install(curLib, monitor)); } return status; } + /** + * A convenience (and downward compatibility method of + * getLibrariesAll(BoardDescription boardDescriptor, true) { + * + * @param confDesc can be null + * @return A map of FQN IArduinoLibraryVersion + */ + public static TreeMap getLibrariesAll(BoardDescription boardDescriptor) { + return getLibrariesAll( boardDescriptor, true); + } + /** * Given a sloeber configuration provide all the libraries that can be used by * this sketch This boils down to all libraries maintained by the Library @@ -338,36 +357,41 @@ public static IStatus updateLibraries(Set toUnInstallLibs * provided by the personal libraries * * @param confDesc can be null - * @return + * @return if keyIsFQN is true: A map of FQN IArduinoLibraryVersion + * if keyIsFQN is false: A map of location IArduinoLibraryVersion */ - public static TreeMap getLibrariesAll(BoardDescription boardDescriptor) { + public static TreeMap getLibrariesAll(BoardDescription boardDescriptor, boolean keyIsFQN) { TreeMap libraries = new TreeMap<>(); - libraries.putAll(getLibrariesdManaged()); - libraries.putAll(getLibrariesPrivate()); + libraries.putAll(getLibrariesdManaged(keyIsFQN)); + libraries.putAll(getLibrariesPrivate(keyIsFQN)); if (boardDescriptor != null) { - libraries.putAll(getLibrariesHarware(boardDescriptor)); + libraries.putAll(getLibrariesHarware(boardDescriptor,keyIsFQN)); } return libraries; } - private static Map getLibrariesdManaged() { + private static Map getLibrariesdManaged(boolean keyIsFQN) { Map ret = new HashMap<>(); - for (ArduinoLibraryIndex libindex : libraryIndices) { - for (ArduinoLibrary curLib : libindex.getLibraries()) { + for (IArduinoLibraryIndex libindex : libraryIndices) { + for (IArduinoLibrary curLib : libindex.getLibraries()) { IArduinoLibraryVersion instVersion = curLib.getInstalledVersion(); if (instVersion != null) { - ret.put(instVersion.getFQN().toPortableString(), instVersion); + if (keyIsFQN) { + ret.put(instVersion.getFQN().toPortableString(), instVersion); + } else { + ret.put(instVersion.getInstallPath().toPortableString(), instVersion); + } } } } return ret; } - private static Map getLibrariesPrivate() { + private static Map getLibrariesPrivate(boolean keyIsFQN) { Map ret = new HashMap<>(); String privateLibPaths[] = InstancePreferences.getPrivateLibraryPaths(); for (String curLibPath : privateLibPaths) { - ret.putAll(getLibrariesFromFolder(new Path(curLibPath), 2, false,true)); + ret.putAll(getLibrariesFromFolder(new Path(curLibPath), 2, false,true,keyIsFQN)); } return ret; @@ -377,12 +401,13 @@ private static Map getLibrariesPrivate() { * for a given folder return all subfolders * * @param ipath the folder you want the subfolders off + * @param keyIsFQN * @return The subfolders of the ipath folder. May contain empty values. This * method returns a key value pair of key equals foldername and value * equals full path. */ private static Map getLibrariesFromFolder(IPath ipath, int depth, - boolean isHardwareLib,boolean isPrivate) { + boolean isHardwareLib,boolean isPrivate, boolean keyIsFQN) { if (ConfigurationPreferences.getInstallationPathLibraries().isPrefixOf(ipath)) { System.err.println("The method findAllPrivateLibs should not be called on Library manager installed libs"); //$NON-NLS-1$ } @@ -401,13 +426,9 @@ private static Map getLibrariesFromFolder(IPath } String fileExt = (new Path(curChild)).getFileExtension(); if (LIBRARY_INDICATION_FILES.contains(curChild) || CODE_EXTENSIONS.contains(fileExt)) { - if (isHardwareLib) { - IArduinoLibraryVersion retVersion = new ArduinoHardwareLibrary(ipath); - ret.put(retVersion.getFQN().toPortableString(), retVersion); - } else { - IArduinoLibraryVersion retVersion = new ArduinoPrivateLibraryVersion(ipath); - ret.put(retVersion.getFQN().toPortableString(), retVersion); - } + IArduinoLibraryVersion retVersion = isHardwareLib?new ArduinoHardwareLibrary(ipath):new ArduinoPrivateHardwareLibraryVersion(ipath); + String key=keyIsFQN?retVersion.getFQN().toPortableString():retVersion.getInstallPath().toPortableString(); + ret.put(key, retVersion); return ret; } @@ -421,7 +442,7 @@ private static Map getLibrariesFromFolder(IPath IPath LibPath = ipath.append(curFolder); File LibPathFile = LibPath.toFile(); if (LibPathFile.isDirectory() && !LibPathFile.isHidden()) { - ret.putAll(getLibrariesFromFolder(LibPath, depth - 1, isHardwareLib,isPrivate)); + ret.putAll(getLibrariesFromFolder(LibPath, depth - 1, isHardwareLib,isPrivate,keyIsFQN)); } } return ret; @@ -431,23 +452,81 @@ private static Map getLibrariesFromFolder(IPath * Searches all the hardware dependent libraries of a project. If this is a * board referencing a core then the libraries of the referenced core are added * as well + * @param keyIsFQN * * @param project the project to find all hardware libraries for * @return all the library folder names. May contain empty values. */ - private static Map getLibrariesHarware(BoardDescription boardDescriptor) { + public static Map getLibrariesHarware(BoardDescription boardDescriptor, boolean keyIsFQN) { Map ret = new HashMap<>(); // first add the referenced IPath libPath = boardDescriptor.getReferencedCoreLibraryPath(); if (libPath != null) { - ret.putAll(getLibrariesFromFolder(libPath, 1, true,boardDescriptor.isPrivate())); + ret.putAll(getLibrariesFromFolder(libPath, 1, true,boardDescriptor.isPrivate(),keyIsFQN)); } // then add the referencing libPath = boardDescriptor.getReferencingLibraryPath(); if (libPath != null) { - ret.putAll(getLibrariesFromFolder(libPath, 1, true,boardDescriptor.isPrivate())); + ret.putAll(getLibrariesFromFolder(libPath, 1, true,boardDescriptor.isPrivate(),keyIsFQN)); } return ret; } + public static IArduinoLibraryVersion getLibraryVersionFromLocation(IFolder libFolder,BoardDescription boardDescriptor) { + if (boardDescriptor != null) { + IPath libPath=boardDescriptor.getReferencedCoreLibraryPath(); + if(libPath!=null && libPath.isPrefixOf(libFolder.getLocation())) { + return getLibrariesHarware(boardDescriptor,false).get(libFolder.getLocation().toPortableString()); + } + } + + if(ConfigurationPreferences.getInstallationPathLibraries().isPrefixOf(libFolder.getLocation())) { + return getLibrariesdManaged(false).get(libFolder.getLocation().toPortableString()); + } + + return getLibrariesPrivate(false).get(libFolder.getLocation().toPortableString()); + } + + public static IArduinoLibraryVersion getLibraryVersionFromFQN(String FQNLibName, BoardDescription boardDescriptor) { + String[] fqnParts = FQNLibName.split(SLACH); + if (fqnParts.length < 3) { + return null; + } + if (!SLOEBER_LIBRARY_FQN.equals(fqnParts[0])) { + // this is not a library + return null; + } + if (MANAGED.equals(fqnParts[1])) { + if (BOARD.equals(fqnParts[2])) { + if (boardDescriptor == null) { + return null; + } + return getLibrariesHarware(boardDescriptor,true).get(FQNLibName); + } + return getLibrariesdManaged(true).get(FQNLibName); + } + if (PRIVATE.equals(fqnParts[1])) { + return getLibrariesPrivate(true).get(FQNLibName); + } + return null; + } + + /** + * Remove a lib based on the name of the lib + * + * @param libName the name of the lib + * @return true if the lib has been removed or was not found + * false if the lib was found and the removal failed. + */ + public static boolean uninstallLibrary(String libName) { + Map installedLibs=getLibrariesAll(null); + IPath libFQN=ArduinoLibraryVersion.calculateFQN(libName); + IArduinoLibraryVersion libVersion = installedLibs.get(libFQN.toString()); + if(libVersion==null) { + return true; + + } + return unInstall(libVersion, new NullProgressMonitor()).isOK(); + } + } \ No newline at end of file diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/Node.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/Node.java similarity index 86% rename from io.sloeber.core/src/io/sloeber/core/api/Json/Node.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/api/Node.java index cfa59b309..0f751d806 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/Node.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/api/Node.java @@ -1,4 +1,4 @@ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.api; public abstract class Node { public boolean hasChildren() { diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibrary.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibrary.java similarity index 74% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibrary.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibrary.java index 8978a8f99..cadd31988 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibrary.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibrary.java @@ -1,9 +1,10 @@ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import java.util.Collection; import java.util.Collections; +import java.util.LinkedList; import java.util.List; import java.util.TreeMap; @@ -13,6 +14,9 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import io.sloeber.arduinoFramework.api.IArduinoLibrary; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.Node; import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.VersionNumber; @@ -23,7 +27,7 @@ * */ -public class ArduinoLibrary extends Node implements Comparable { +public class ArduinoLibrary extends IArduinoLibrary { private String name; private TreeMap versions = new TreeMap<>(Collections.reverseOrder()); @@ -50,15 +54,18 @@ protected void addVersion(JsonElement json) { versions.put(versionNumber, new ArduinoLibraryVersion(jsonObject, this)); } - public Collection getVersions() { - return versions.values(); + @Override + public Collection getVersions() { + return new LinkedList<>(versions.values()); } - public String getAuthor() { + @Override + public String getAuthor() { return getNewestVersion().getAuthor(); } - public String getMaintainer() { + @Override + public String getMaintainer() { return getNewestVersion().getMaintainer(); } @@ -70,19 +77,23 @@ public String getParagraph() { return getNewestVersion().getParagraph(); } - public String getWebsite() { + @Override + public String getWebsite() { return getNewestVersion().getWebsite(); } - public String getCategory() { + @Override + public String getCategory() { return getNewestVersion().getCategory(); } - public List getArchitectures() { + @Override + public List getArchitectures() { return getNewestVersion().getArchitectures(); } - public List getTypes() { + @Override + public List getTypes() { return getNewestVersion().getTypes(); } @@ -95,7 +106,8 @@ public String getUrl() { * * @return the newest version of this library */ - public ArduinoLibraryVersion getNewestVersion() { + @Override + public ArduinoLibraryVersion getNewestVersion() { return versions.firstEntry().getValue(); } @@ -105,7 +117,8 @@ public ArduinoLibraryVersion getNewestVersion() { * * @return */ - public ArduinoLibraryVersion getInstalledVersion() { + @Override + public ArduinoLibraryVersion getInstalledVersion() { for (ArduinoLibraryVersion curVersion : versions.values()) { if (curVersion.isInstalled()) { return curVersion; @@ -119,12 +132,13 @@ public ArduinoLibraryVersion getInstalledVersion() { * * @return true if a version is installed. false in case no version is installed */ - public boolean isInstalled() { + @Override + public boolean isInstalled() { return getInstalledVersion() != null; } @Override - public int compareTo(ArduinoLibrary other) { + public int compareTo(IArduinoLibrary other) { return getID().compareTo(other.getID()); } @@ -149,11 +163,13 @@ public String getID() { return name; } - public IPath getInstallPath() { + @Override + public IPath getInstallPath() { return ConfigurationPreferences.getInstallationPathLibraries().append(this.name.replace(' ', '_')); } - public ArduinoLibraryVersion getVersion(VersionNumber versionNumber) { + @Override + public ArduinoLibraryVersion getVersion(VersionNumber versionNumber) { return versions.get(versionNumber); } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibraryIndex.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibraryIndex.java similarity index 75% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibraryIndex.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibraryIndex.java index c9540ccc5..66a123793 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibraryIndex.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibraryIndex.java @@ -1,11 +1,12 @@ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import java.io.File; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashMap; +import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.TreeMap; @@ -17,6 +18,11 @@ import com.google.gson.JsonParseException; import com.google.gson.annotations.JsonAdapter; +import io.sloeber.arduinoFramework.api.IArduinoLibrary; +import io.sloeber.arduinoFramework.api.IArduinoLibraryIndex; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.Node; + /** * This class represents a json file that references libraries * @@ -25,7 +31,7 @@ */ @JsonAdapter(ArduinoLibraryIndex.class) public class ArduinoLibraryIndex extends Node - implements Comparable, JsonDeserializer { + implements JsonDeserializer, IArduinoLibraryIndex { private TreeMap libraries = new TreeMap<>(); private transient File jsonFile; @@ -35,11 +41,12 @@ public void setJsonFile(File packageFile) { /** * given a library name provide the library - * + * * @param libraryName * @return the library or null if not found */ - public ArduinoLibrary getLibrary(String libraryName) { + @Override + public IArduinoLibrary getLibrary(String libraryName) { return libraries.get(libraryName); } @@ -50,12 +57,13 @@ public ArduinoLibrary getLibrary(String libraryName) { * * @return */ - public Map getLatestInstallableLibraries(Set libNames) { - Map ret = new HashMap<>(); + @Override + public Map getLatestInstallableLibraries(Set libNames) { + Map ret = new HashMap<>(); if (libNames.isEmpty()) { return ret; } - for (ArduinoLibrary curLibrary : libraries.values()) { + for (IArduinoLibrary curLibrary : libraries.values()) { if (libNames.contains(curLibrary.getNodeName())) { if (!curLibrary.isInstalled()) { ret.put(curLibrary.getNodeName(), curLibrary.getNewestVersion()); @@ -111,12 +119,13 @@ public String getID() { } @Override - public int compareTo(ArduinoLibraryIndex o) { + public int compareTo(IArduinoLibraryIndex o) { return getID().compareTo(o.getID()); } - public Collection getLibraries() { - return libraries.values(); + @Override + public Collection getLibraries() { + return new LinkedList<> (libraries.values()); } } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibraryVersion.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibraryVersion.java similarity index 86% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibraryVersion.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibraryVersion.java index 82a176a18..1d7ca727b 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoLibraryVersion.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoLibraryVersion.java @@ -1,6 +1,6 @@ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import static io.sloeber.core.api.Const.*; import java.util.ArrayList; @@ -13,7 +13,9 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; -import io.sloeber.core.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IArduinoLibrary; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.Node; import io.sloeber.core.api.VersionNumber; /** @@ -23,7 +25,7 @@ * */ -public class ArduinoLibraryVersion extends Node implements IArduinoLibraryVersion, Comparable { +public class ArduinoLibraryVersion extends Node implements IArduinoLibraryVersion { private String name; private VersionNumber version; @@ -65,29 +67,34 @@ public ArduinoLibraryVersion(JsonElement json, ArduinoLibrary arduinoLibrary) { archiveFileName = getSafeString(jsonObject, "archiveFileName"); size = jsonObject.get("size").getAsInt(); checksum = getSafeString(jsonObject, "checksum"); - calculateFQN(); + myFQN=calculateFQN(getName()); } catch (Exception e) { throw new JsonParseException("failed to parse json " + e.getMessage(),e); } } + @Override public VersionNumber getVersion() { return version; } + @Override public String getAuthor() { return author; } + @Override public String getMaintainer() { return maintainer; } + @Override public String getSentence() { return sentence; } + @Override public String getParagraph() { return paragraph; } @@ -100,6 +107,7 @@ public String getCategory() { return category; } + @Override public List getArchitectures() { return architectures; } @@ -124,12 +132,13 @@ public String getChecksum() { return checksum; } + @Override public boolean isInstalled() { return getInstallPath().toFile().exists(); } @Override - public int compareTo(ArduinoLibraryVersion other) { + public int compareTo(IArduinoLibraryVersion other) { if (other == null) { return 1; } @@ -142,7 +151,8 @@ public int compareTo(ArduinoLibraryVersion other) { return version.toString().compareTo(other.getVersion().toString()); } - public ArduinoLibrary getLibrary() { + @Override + public IArduinoLibrary getLibrary() { return myParent; } @@ -195,9 +205,8 @@ public IPath getExamplePath() { return getInstallPath().append(EXAMPLES_FOLDER); } - private void calculateFQN() { - myFQN= Path.fromPortableString(SLOEBER_LIBRARY_FQN); - myFQN=myFQN.append(MANAGED).append(getName()); + static public IPath calculateFQN(String libName) { + return Path.fromPortableString(SLOEBER_LIBRARY_FQN).append(MANAGED).append(libName); } @Override diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPackage.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPackage.java similarity index 72% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPackage.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPackage.java index 962ddeceb..c2d97d652 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPackage.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPackage.java @@ -5,9 +5,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import java.util.Collection; import java.util.LinkedList; @@ -20,11 +20,14 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IArduinoPackage; +import io.sloeber.arduinoFramework.api.IArduinoPlatform; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; +import io.sloeber.arduinoFramework.api.Node; import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.VersionNumber; -public class ArduinoPackage extends Node implements Comparable { +public class ArduinoPackage extends Node implements IArduinoPackage { private String name; private String maintainer; @@ -75,7 +78,8 @@ public ArduinoPackage(JsonElement json, ArduinoPlatformPackageIndex packageIndex } } - public ArduinoPlatformPackageIndex getPackageIndex() { + @Override + public ArduinoPlatformPackageIndex getPackageIndex() { return myParent; } @@ -84,24 +88,29 @@ public String getNodeName() { return name; } - public String getMaintainer() { + @Override + public String getMaintainer() { return maintainer; } - public String getWebsiteURL() { + @Override + public String getWebsiteURL() { return websiteURL; } - public String getEmail() { + @Override + public String getEmail() { return email; } - public String getHelp() { + @Override + public String getHelp() { return helpOnline; } - public Collection getPlatforms() { - return platforms.values(); + @Override + public Collection getPlatforms() { + return new LinkedList<>( platforms.values()); } /** @@ -110,10 +119,11 @@ public Collection getPlatforms() { * * @return all the installed platforms */ - public List getInstalledPlatforms() { - List platformMap = new LinkedList<>(); + @Override + public List getInstalledPlatforms() { + List platformMap = new LinkedList<>(); for (ArduinoPlatform platform : platforms.values()) { - for (ArduinoPlatformVersion platformVersion : platform.getVersions()) { + for (IArduinoPlatformVersion platformVersion : platform.getVersions()) { if (platformVersion.isInstalled()) { platformMap.add(platformVersion); } @@ -129,15 +139,18 @@ public List getInstalledPlatforms() { * @param platformID * @return return the platfiorm or null if not found */ - public ArduinoPlatform getPlatform(String platformID) { + @Override + public IArduinoPlatform getPlatform(String platformID) { return platforms.get(platformID); } - public Collection getTools() { + @Override + public Collection getTools() { return tools.values(); } - public ArduinoPlatformToolVersion getTool(String toolName, VersionNumber version) { + @Override + public ArduinoPlatformToolVersion getTool(String toolName, VersionNumber version) { ArduinoPlatformTool tool = tools.get(toolName); if (tool == null) { return null; @@ -145,11 +158,13 @@ public ArduinoPlatformToolVersion getTool(String toolName, VersionNumber version return tool.getVersion(version); } - public ArduinoPlatformTool getTool(String toolName) { + @Override + public ArduinoPlatformTool getTool(String toolName) { return tools.get(toolName); } - public ArduinoPlatformToolVersion getNewestInstalled(String toolName) { + @Override + public ArduinoPlatformToolVersion getNewestInstalled(String toolName) { ArduinoPlatformTool tool = tools.get(toolName); if (tool == null) { return null; @@ -171,31 +186,15 @@ public int hashCode() { } @Override - public int compareTo(ArduinoPackage other) { - return this.name.compareTo(other.name); + public int compareTo(IArduinoPackage other) { + return this.name.compareTo(other.getName()); } - public void onlyKeepLatestPlatforms() { - for (ArduinoPlatform curplatform : platforms.values()) { - ArduinoPlatformVersion newestVersion = null; - for (ArduinoPlatformVersion curVersion : curplatform.getVersions()) { - if (curVersion.isInstalled()) { - if (newestVersion == null) { - newestVersion = curVersion; - } else { - if (newestVersion.getVersion().compareTo(curVersion.getVersion()) > 0) { - BoardsManager.uninstall(curVersion, null); - } else { - BoardsManager.uninstall(newestVersion, null); - } - } - } - } - } - } - public boolean isInstalled() { - for (ArduinoPlatform platform : platforms.values()) { + + @Override + public boolean isInstalled() { + for (IArduinoPlatform platform : platforms.values()) { if (platform.isInstalled()) { return true; } @@ -209,7 +208,8 @@ public boolean isInstalled() { * @param platformName * @return if a platform with this name is installed */ - public boolean isAVersionOfThisPlatformInstalled(String platformName) { + @Override + public boolean isAVersionOfThisPlatformInstalled(String platformName) { for (ArduinoPlatform platform : this.platforms.values()) { if (platform.getName().equals(platformName)) { if (platform.isInstalled()) { @@ -225,7 +225,8 @@ public String getID() { return name; } - public IPath getInstallPath() { + @Override + public IPath getInstallPath() { return ConfigurationPreferences.getInstallationPathPackages().append(getID()); } @@ -239,4 +240,9 @@ public Node getParent() { return myParent; } + @Override + public String getName() { + return name; + } + } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatform.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatform.java similarity index 67% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatform.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatform.java index b97a3a21d..867e6fad0 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatform.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatform.java @@ -5,13 +5,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import static io.sloeber.core.api.Const.*; import java.util.Collection; import java.util.Collections; +import java.util.LinkedList; import java.util.TreeMap; import org.eclipse.core.runtime.IPath; @@ -20,14 +21,17 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import io.sloeber.arduinoFramework.api.IArduinoPackage; +import io.sloeber.arduinoFramework.api.IArduinoPlatform; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; import io.sloeber.core.api.Const; import io.sloeber.core.api.VersionNumber; -public class ArduinoPlatform implements Comparable { +public class ArduinoPlatform implements IArduinoPlatform { private String name; private String architecture; - private TreeMap myVersions = new TreeMap<>(Collections.reverseOrder()); + private TreeMap myVersions = new TreeMap<>(Collections.reverseOrder()); private ArduinoPackage myParent; @@ -50,20 +54,24 @@ protected void addVersion(JsonElement json) { myVersions.put(version.getVersion(), version); } - public ArduinoPackage getParent() { + @Override + public IArduinoPackage getParent() { return this.myParent; } - public String getName() { + @Override + public String getName() { return this.name; } - public String getArchitecture() { + @Override + public String getArchitecture() { return architecture; } - public boolean isInstalled() { - for (ArduinoPlatformVersion curPlatformVersion : myVersions.values()) { + @Override + public boolean isInstalled() { + for (IArduinoPlatformVersion curPlatformVersion : myVersions.values()) { if (curPlatformVersion.isInstalled()) { return true; } @@ -71,16 +79,18 @@ public boolean isInstalled() { return false; } - public IPath getInstallPath() { + @Override + public IPath getInstallPath() { return myParent.getInstallPath().append(Const.ARDUINO_HARDWARE_FOLDER_NAME).append(getID()); } - public String getID() { + @Override + public String getID() { return architecture; } @Override - public int compareTo(ArduinoPlatform o) { + public int compareTo(IArduinoPlatform o) { return name.compareTo(o.getName()); } @@ -89,15 +99,18 @@ public int compareTo(ArduinoPlatform o) { * * @return the newest version of this platform */ - public ArduinoPlatformVersion getNewestVersion() { + @Override + public IArduinoPlatformVersion getNewestVersion() { return myVersions.firstEntry().getValue(); } - public Collection getVersions() { - return myVersions.values(); + @Override + public Collection getVersions() { + return new LinkedList<>(myVersions.values()); } - public ArduinoPlatformVersion getVersion(VersionNumber refVersion) { + @Override + public IArduinoPlatformVersion getVersion(VersionNumber refVersion) { return myVersions.get(refVersion); } @@ -107,8 +120,9 @@ public ArduinoPlatformVersion getVersion(VersionNumber refVersion) { * * @return */ - public ArduinoPlatformVersion getNewestInstalled() { - for (ArduinoPlatformVersion curVersion : myVersions.values()) { + @Override + public IArduinoPlatformVersion getNewestInstalled() { + for (IArduinoPlatformVersion curVersion : myVersions.values()) { if (curVersion.isInstalled()) { return curVersion; } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformPackageIndex.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformPackageIndex.java similarity index 76% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformPackageIndex.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformPackageIndex.java index df34bcdae..719d0f057 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformPackageIndex.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformPackageIndex.java @@ -5,11 +5,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import com.google.gson.JsonDeserializationContext; @@ -19,19 +20,27 @@ import com.google.gson.JsonParseException; import com.google.gson.annotations.JsonAdapter; +import io.sloeber.arduinoFramework.api.IArduinoPackage; +import io.sloeber.arduinoFramework.api.IArduinoPlatformPackageIndex; +import io.sloeber.arduinoFramework.api.Node; + @JsonAdapter(ArduinoPlatformPackageIndex.class) public class ArduinoPlatformPackageIndex extends Node - implements Comparable, JsonDeserializer { + implements Comparable, JsonDeserializer, IArduinoPlatformPackageIndex { private List myPackages = new ArrayList<>(); private transient File myJsonFile; - public List getPackages() { - return myPackages; + private String myURL; + + @Override + public List getPackages() { + return new LinkedList<>(myPackages); } - public ArduinoPackage getPackage(String packageName) { + @Override + public IArduinoPackage getPackage(String packageName) { for (ArduinoPackage pkg : myPackages) { if (pkg.getNodeName().equals(packageName)) { return pkg; @@ -44,7 +53,8 @@ public void setPackageFile(File packageFile) { myJsonFile = packageFile; } - public File getJsonFile() { + @Override + public File getJsonFile() { return myJsonFile; } @@ -76,8 +86,9 @@ public ArduinoPlatformPackageIndex deserialize(JsonElement json, Type arg1, Json } - public boolean isInstalled() { - for (ArduinoPackage pkg : myPackages) { + @Override + public boolean isInstalled() { + for (IArduinoPackage pkg : myPackages) { if (pkg.isInstalled()) { return true; } @@ -105,4 +116,19 @@ public int compareTo(ArduinoPlatformPackageIndex o) { return getID().compareTo(o.getID()); } + @Override + public String getName() { + return getNodeName(); + } + + @Override + public String getJsonURL() { + return myURL; + } + + public void setURL(String url) { + myURL=url; + + } + } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformTool.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformTool.java similarity index 93% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformTool.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformTool.java index c7bbfc249..7faae3d13 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformTool.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformTool.java @@ -5,9 +5,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import static io.sloeber.core.api.Const.*; import java.util.Collection; @@ -21,6 +21,8 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import io.sloeber.arduinoFramework.api.IArduinoPackage; +import io.sloeber.arduinoFramework.api.Node; import io.sloeber.core.api.VersionNumber; public class ArduinoPlatformTool extends Node { @@ -48,7 +50,7 @@ protected void addVersion(JsonElement json) { myVersions.put(version.getVersion(), version); } - public ArduinoPackage getPackage() { + public IArduinoPackage getPackage() { return myParentPackage; } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformToolVersion.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformToolVersion.java similarity index 88% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformToolVersion.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformToolVersion.java index 23467bb57..2bea7630c 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformToolVersion.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformToolVersion.java @@ -5,9 +5,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import static io.sloeber.core.api.Const.*; import java.util.ArrayList; @@ -20,6 +20,11 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import io.sloeber.arduinoFramework.api.ArduinoInstallable; +import io.sloeber.arduinoFramework.api.IArduinoPackage; +import io.sloeber.arduinoFramework.api.IArduinoPlatform; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; +import io.sloeber.arduinoFramework.api.Node; import io.sloeber.core.api.VersionNumber; public class ArduinoPlatformToolVersion extends Node { @@ -82,9 +87,9 @@ public IPath getInstallPath() { if (myInstallPath != null) { return myInstallPath; } - ArduinoPackage pkg = myParentTool.getPackage(); - for (ArduinoPlatform curPlatform : pkg.getPlatforms()) { - for (ArduinoPlatformVersion curplatformVersion : curPlatform.getVersions()) { + IArduinoPackage pkg = myParentTool.getPackage(); + for (IArduinoPlatform curPlatform : pkg.getPlatforms()) { + for (IArduinoPlatformVersion curplatformVersion : curPlatform.getVersions()) { for (ArduinoPlatformTooldDependency curTooldependency : curplatformVersion.getToolsDependencies()) { if (curTooldependency.getName().equals(myParentTool.getNodeName()) && curTooldependency.getVersion().compareTo(myVersion) == 0) { diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformTooldDependency.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformTooldDependency.java similarity index 78% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformTooldDependency.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformTooldDependency.java index 9d69a4a28..e335eda84 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformTooldDependency.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformTooldDependency.java @@ -1,6 +1,6 @@ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import static io.sloeber.core.api.Const.*; import org.eclipse.core.runtime.IPath; @@ -9,6 +9,7 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.VersionNumber; @@ -18,10 +19,10 @@ public class ArduinoPlatformTooldDependency { private String myPackager; private VersionNumber myVersion; - private transient ArduinoPlatformVersion myParentPlatform; + private transient IArduinoPlatformVersion myParentPlatform; @SuppressWarnings("nls") - public ArduinoPlatformTooldDependency(JsonElement json, ArduinoPlatformVersion arduinoPlatformVersion) { + public ArduinoPlatformTooldDependency(JsonElement json, IArduinoPlatformVersion arduinoPlatformVersion) { myParentPlatform = arduinoPlatformVersion; JsonObject jsonObject = json.getAsJsonObject(); try { diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformVersion.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformVersion.java similarity index 50% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformVersion.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformVersion.java index 7aed2b055..c69bbb8ee 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoPlatformVersion.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinoPlatformVersion.java @@ -5,14 +5,13 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import static io.sloeber.core.api.Const.*; import java.io.File; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.eclipse.core.runtime.IPath; @@ -21,16 +20,17 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; import io.sloeber.core.api.VersionNumber; -public class ArduinoPlatformVersion extends ArduinoInstallable implements Comparable { +public class ArduinoPlatformVersion extends IArduinoPlatformVersion { - private String architecture; - private VersionNumber version; - private String category; + private String myArchitecture; + private VersionNumber myVersion; + private String myCategory; - private List boards = new ArrayList<>(); - private List toolsDependencies = new ArrayList<>();; + private List myBoards = new ArrayList<>(); + private List myToolDependencies = new ArrayList<>(); private ArduinoPlatform myParent; @@ -40,20 +40,20 @@ public ArduinoPlatformVersion(JsonElement json, ArduinoPlatform parent) { JsonObject jsonObject = json.getAsJsonObject(); try { - name = getSafeString(jsonObject, "name"); - architecture = getSafeString(jsonObject, "architecture"); - version = getSafeVersion(jsonObject, "version"); - category = getSafeString(jsonObject, "category"); - url = getSafeString(jsonObject, "url"); - archiveFileName = getSafeString(jsonObject, "archiveFileName"); - checksum = getSafeString(jsonObject, "checksum"); - size = getSafeString(jsonObject, "size"); + myName = getSafeString(jsonObject, "name"); + myArchitecture = getSafeString(jsonObject, "architecture"); + myVersion = getSafeVersion(jsonObject, "version"); + myCategory = getSafeString(jsonObject, "category"); + myURL = getSafeString(jsonObject, "url"); + myArchiveFileName = getSafeString(jsonObject, "archiveFileName"); + myChecksum = getSafeString(jsonObject, "checksum"); + mySize = getSafeString(jsonObject, "size"); for (JsonElement curElement : jsonObject.get("boards").getAsJsonArray()) { - boards.add(getSafeString(curElement.getAsJsonObject(), "name")); + myBoards.add(getSafeString(curElement.getAsJsonObject(), "name")); } if (jsonObject.get("toolsDependencies") != null) { for (JsonElement curElement : jsonObject.get("toolsDependencies").getAsJsonArray()) { - toolsDependencies.add(new ArduinoPlatformTooldDependency(curElement, this)); + myToolDependencies.add(new ArduinoPlatformTooldDependency(curElement, this)); } } } catch (Exception e) { @@ -61,56 +61,59 @@ public ArduinoPlatformVersion(JsonElement json, ArduinoPlatform parent) { } } - public ArduinoPlatform getParent() { + @Override + public ArduinoPlatform getParent() { return myParent; } - public String getArchitecture() { - return architecture; + @Override + public String getArchitecture() { + return myArchitecture; } - public VersionNumber getVersion() { - return version; + @Override + public VersionNumber getVersion() { + return myVersion; } - public String getCategory() { - return category; + @Override + public String getCategory() { + return myCategory; } - public List getToolsDependencies() { - return toolsDependencies; + @Override + public List getToolsDependencies() { + return myToolDependencies; } - public boolean isInstalled() { + @Override + public boolean isInstalled() { return getBoardsFile().exists(); } - public File getBoardsFile() { + @Override + public File getBoardsFile() { return getInstallPath().append(BOARDS_FILE_NAME).toFile(); } - public File getPlatformFile() { + @Override + public File getPlatformFile() { return getInstallPath().append(PLATFORM_FILE_NAME).toFile(); } @Override public IPath getInstallPath() { - return getParent().getInstallPath().append(this.version.toString()); + return getParent().getInstallPath().append(this.myVersion.toString()); } - public List getIncludePath() { - IPath installPath = getInstallPath(); - return Arrays.asList(installPath.append("cores/{build.core}"), //$NON-NLS-1$ - installPath.append(ARDUINO_VARIANTS_FOLDER_NAME + "/{build.variant}")); //$NON-NLS-1$ - } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); + result = prime * result + ((this.myName == null) ? 0 : this.myName.hashCode()); result = prime * result + ((this.myParent == null) ? 0 : this.myParent.hashCode()); - result = prime * result + ((this.version == null) ? 0 : this.version.hashCode()); + result = prime * result + ((this.myVersion == null) ? 0 : this.myVersion.hashCode()); return result; } @@ -123,44 +126,47 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) return false; ArduinoPlatformVersion other = (ArduinoPlatformVersion) obj; - if (this.name == null) { - if (other.name != null) + if (this.myName == null) { + if (other.myName != null) return false; - } else if (!this.name.equals(other.name)) + } else if (!this.myName.equals(other.myName)) return false; if (this.myParent == null) { if (other.myParent != null) return false; } else if (!this.myParent.equals(other.myParent)) return false; - if (this.version == null) { - if (other.version != null) + if (this.myVersion == null) { + if (other.myVersion != null) return false; - } else if (!this.version.equals(other.version)) + } else if (!this.myVersion.equals(other.myVersion)) return false; return true; } - public List getBoardNames() { - return boards; + @Override + public List getBoardNames() { + return myBoards; } - public String getID() { - return version.toString(); + @Override + public String getID() { + return myVersion.toString(); } - public String getConcattenatedBoardNames() { + @Override + public String getConcattenatedBoardNames() { return String.join("\n", getBoardNames()); //$NON-NLS-1$ } @Override - public int compareTo(ArduinoPlatformVersion o) { - return name.compareTo(o.getName()); + public int compareTo(IArduinoPlatformVersion o) { + return myName.compareTo(o.getName()); } @Override public String toString() { - return name + SPACE + architecture + '(' + version + ')'; + return myName + SPACE + myArchitecture + '(' + myVersion + ')'; } } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinpPlatformToolSystem.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinpPlatformToolSystem.java similarity index 89% rename from io.sloeber.core/src/io/sloeber/core/api/Json/ArduinpPlatformToolSystem.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinpPlatformToolSystem.java index 58b675bff..92ac3feec 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinpPlatformToolSystem.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/ArduinpPlatformToolSystem.java @@ -5,9 +5,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ -package io.sloeber.core.api.Json; +package io.sloeber.arduinoFramework.internal; -import static io.sloeber.core.Gson.GsonConverter.*; +import static io.sloeber.arduinoFramework.internal.GsonConverter.*; import org.eclipse.core.runtime.IPath; @@ -15,6 +15,8 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import io.sloeber.arduinoFramework.api.ArduinoInstallable; + public class ArduinpPlatformToolSystem extends ArduinoInstallable { private transient ArduinoPlatformToolVersion myParent; @@ -27,10 +29,10 @@ public ArduinpPlatformToolSystem(JsonElement json, ArduinoPlatformToolVersion to try { host = getSafeString(jsonObject, "host"); - archiveFileName = getSafeString(jsonObject, "archiveFileName"); - url = getSafeString(jsonObject, "url"); - checksum = getSafeString(jsonObject, "checksum"); - size = getSafeString(jsonObject, "size"); + myArchiveFileName = getSafeString(jsonObject, "archiveFileName"); + myURL = getSafeString(jsonObject, "url"); + myChecksum = getSafeString(jsonObject, "checksum"); + mySize = getSafeString(jsonObject, "size"); } catch (Exception e) { throw new JsonParseException("failed to parse Tool json " + e.getMessage(),e); } diff --git a/io.sloeber.core/src/io/sloeber/core/Gson/GsonConverter.java b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/GsonConverter.java similarity index 93% rename from io.sloeber.core/src/io/sloeber/core/Gson/GsonConverter.java rename to io.sloeber.core/src/io/sloeber/arduinoFramework/internal/GsonConverter.java index 7f797bf60..af022007a 100644 --- a/io.sloeber.core/src/io/sloeber/core/Gson/GsonConverter.java +++ b/io.sloeber.core/src/io/sloeber/arduinoFramework/internal/GsonConverter.java @@ -1,4 +1,4 @@ -package io.sloeber.core.Gson; +package io.sloeber.arduinoFramework.internal; import com.google.gson.JsonElement; import com.google.gson.JsonObject; diff --git a/io.sloeber.core/src/io/sloeber/core/Activator.java b/io.sloeber.core/src/io/sloeber/core/Activator.java index afa7859e7..f9000e3c2 100644 --- a/io.sloeber.core/src/io/sloeber/core/Activator.java +++ b/io.sloeber.core/src/io/sloeber/core/Activator.java @@ -8,6 +8,8 @@ import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; +import java.time.Duration; +import java.time.Instant; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.model.CoreModel; @@ -29,16 +31,19 @@ import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; +import org.eclipse.ui.statushandlers.StatusManager; import org.osgi.framework.BundleContext; import org.osgi.service.prefs.BackingStoreException; import org.osgi.service.prefs.Preferences; import cc.arduino.packages.discoverers.SloeberNetworkDiscovery; -import io.sloeber.core.api.BoardsManager; -import io.sloeber.core.api.Common; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.ConfigurationPreferences; +import io.sloeber.core.api.Defaults; import io.sloeber.core.common.InstancePreferences; import io.sloeber.core.listeners.ConfigurationChangeListener; +import io.sloeber.core.listeners.IndexerController; import io.sloeber.core.listeners.IndexerListener; import io.sloeber.core.tools.PackageManager; @@ -168,7 +173,7 @@ private static void testKnownIssues() { if (!errorString.isEmpty()) { errorString += "\n\nSloeber might still function but if you get strange results you know where to look.\n"; errorString += "Do not create an issue if you see this!!!"; - Common.log(new Status(IStatus.ERROR, PLUGIN_ID, errorString)); + log(new Status(IStatus.ERROR, Activator.getId(), errorString)); } } @@ -190,8 +195,9 @@ private static void registerListeners() { CCorePlugin.getIndexManager().addIndexChangeListener(myindexerListener); CCorePlugin.getIndexManager().addIndexerStateListener(myindexerListener); CoreModel singCoreModel = CoreModel.getDefault(); + IndexerController.registerIndexerController(); - singCoreModel.addCProjectDescriptionListener(myConfigurationChangeListener,CProjectDescriptionEvent.ABOUT_TO_APPLY); + singCoreModel.addCProjectDescriptionListener(myConfigurationChangeListener,CProjectDescriptionEvent.ABOUT_TO_APPLY|CProjectDescriptionEvent.APPLIED); @@ -202,6 +208,7 @@ private static void unRegisterListeners() { CCorePlugin.getIndexManager().removeIndexChangeListener(myindexerListener); CoreModel singCoreModel = CoreModel.getDefault(); singCoreModel.removeCProjectDescriptionListener(myConfigurationChangeListener); + IndexerController.unRegisterIndexerController(); @@ -215,13 +222,12 @@ private static void initializeImportantVariables() { try { workspace.setDescription(workspaceDesc); } catch (CoreException e) { - Common.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, e.getMessage(), e)); + log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, e.getMessage(), e)); } // Make sure some important variables are being initialized InstancePreferences.setPrivateLibraryPaths(InstancePreferences.getPrivateLibraryPaths()); InstancePreferences.setPrivateHardwarePaths(InstancePreferences.getPrivateHardwarePaths()); InstancePreferences.setAutomaticallyImportLibraries(InstancePreferences.getAutomaticallyImportLibraries()); - BoardsManager.setJsonURLs(BoardsManager.getJsonURLs()); } private void runPluginCoreStartInstantiatorJob() { @@ -259,7 +265,7 @@ protected IStatus run(IProgressMonitor monitor) { installOtherStuff(); - BoardsManager.startup_Pluging(monitor); + startup_BoardsManager(monitor); monitor.setTaskName("Done!"); if (InstancePreferences.useBonjour()) { @@ -295,7 +301,7 @@ public void stop(BundleContext context) throws Exception { * the io.sloeber.core.managers and io.sloeber.core.managers.ui to work. */ public static String getId() { - return PLUGIN_ID; + return "io.sloeber.core"; } /** @@ -382,7 +388,7 @@ private static void addFileAssociations() { ctbin.addFileSpec("ino", IContentTypeSettings.FILE_EXTENSION_SPEC); ctbin.addFileSpec("pde", IContentTypeSettings.FILE_EXTENSION_SPEC); } catch (CoreException e) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), + log(new Status(IStatus.WARNING, Activator.getId(), "Failed to add *.ino and *.pde as file extensions.", e)); } @@ -405,6 +411,7 @@ private static void installOtherStuff() { if (localMakePath.append(MAKE_EXE).toFile().exists()) { if (!localMakePath.append(SH_EXE).toFile().exists()) { try { + //Sloeber needs the make that also contains sh.exe deleteDirectory(localMakePath); } catch (IOException e) { // should not happen @@ -414,16 +421,79 @@ private static void installOtherStuff() { } if (!localMakePath.append(MAKE_EXE).toFile().exists()) { IProgressMonitor monitor = new NullProgressMonitor(); - Common.log(PackageManager.downloadAndInstall(MAKE_URL, MAKE_ZIP, localMakePath, false, monitor)); + log(PackageManager.downloadAndInstall(MAKE_URL, MAKE_ZIP, localMakePath, false, monitor)); } // Install awk if needed IPath localAwkPath = ConfigurationPreferences.getAwkPath(); if (!localAwkPath.append(AWK_EXE).toFile().exists()) { IProgressMonitor monitor = new NullProgressMonitor(); - Common.log(PackageManager.downloadAndInstall(AWK_URL, AWK_ZIP, localAwkPath, false, monitor)); + log(PackageManager.downloadAndInstall(AWK_URL, AWK_ZIP, localAwkPath, false, monitor)); } } } + + /** + * Logs the status information if status is OK then nothing happens + * + * @param status + * the status information to log + */ + public static void log(IStatus status) { + switch (status.getSeverity()) { + case IStatus.OK: { + break; + } + case IStatus.ERROR: { + int style = StatusManager.LOG | StatusManager.SHOW | StatusManager.BLOCK; + StatusManager stMan = StatusManager.getManager(); + stMan.handle(status, style); + break; + } + case SLOEBER_STATUS_DEBUG: + // break;//remove break to add debugging + default: + Activator.getDefault().getLog().log(status); + } + } + + /** + * Loads all stuff needed and if this is the first time downloads the avr boards + * and needed tools + * + * @param monitor + */ + private static synchronized void startup_BoardsManager(IProgressMonitor monitor) { + //ConfigurationPreferences.getUpdateJasonFilesFlag(); + Instant currentTime=Instant.now(); + Instant latestUpdate= ConfigurationPreferences.getLatestJsonUpdateTime(); + Duration requestedDelay=ConfigurationPreferences.getJsonUpdateDelay(); + Instant nextUpdate=latestUpdate.plus(requestedDelay); + boolean needsUpdate = nextUpdate.isBefore(currentTime); + +// long latestUpdate= getLatestUpdateTime(); +// long requestedDelay=getUpdateDelay(); +// long currentTime= System.currentTimeMillis(); +// boolean needsUpdate = currentTime>(requestedDelay+latestUpdate); + if(needsUpdate) { + BoardsManager.update(true ); + }else { + BoardsManager.update(false ); + } + + if (!LibraryManager.libsAreInstalled()) { + LibraryManager.InstallDefaultLibraries(monitor); + } + IPath examplesPath = ConfigurationPreferences.getInstallationPathExamples(); + if (!examplesPath.toFile().exists()) {// examples are not installed + // Download arduino IDE example programs + Activator.log(PackageManager.downloadAndInstall(Defaults.EXAMPLES_URL, Defaults.EXAMPLE_PACKAGE, examplesPath, + false, monitor)); + } + + + } + + } diff --git a/io.sloeber.core/src/io/sloeber/core/Messages.java b/io.sloeber.core/src/io/sloeber/core/Messages.java index dc4651099..c3d9dce54 100644 --- a/io.sloeber.core/src/io/sloeber/core/Messages.java +++ b/io.sloeber.core/src/io/sloeber/core/Messages.java @@ -39,7 +39,8 @@ public class Messages extends NLS { public static String ArduinoSerial_unable_to_open_serial_port; public static String ArduinoSerial_Using_1200bps_touch; public static String ArduinoSerial_Using_comport; - public static String Boards_Failed_to_read_boards; + public static String BoardDescription_0; + public static String Boards_Failed_to_read_boards; public static String Boards_Get_menu_item_name_from_id_did_not_find; public static String Boards_menu_ID_not_found; public static String Boards_menu_name_not_found; @@ -108,15 +109,13 @@ public class Messages extends NLS { public static String CompileDescription_CustomDebugLevel; public static String CompileDescription_OptimizedForDebug; public static String CompileDescription_OptimizedForRelease; - public static String CompileDescription_SizeArduinoWay; - public static String CompileDescription_SizeAVRAlternative; - public static String CompileDescription_SizeCustom; - public static String CompileDescription_SizeRawResult; public static String CompileDescription_WarningsAll; public static String CompileDescription_WarningsCustom; public static String CompileDescription_WarningsDefault; public static String CompileDescription_WarningsMore; public static String CompileDescription_WarningsNone; + public static String SloeberConfiguration_Failed_Modify_config_rename; + public static String SloeberProject_Project_is_null; static { // initialize resource bundle diff --git a/io.sloeber.core/src/io/sloeber/core/api/BoardDescription.java b/io.sloeber.core/src/io/sloeber/core/api/BoardDescription.java deleted file mode 100644 index 039955cfe..000000000 --- a/io.sloeber.core/src/io/sloeber/core/api/BoardDescription.java +++ /dev/null @@ -1,1138 +0,0 @@ -package io.sloeber.core.api; - -import static io.sloeber.core.Messages.*; -import static io.sloeber.core.api.Common.*; -import static io.sloeber.core.api.Const.*; -import static io.sloeber.autoBuild.api.AutoBuildCommon.*; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; -import org.eclipse.cdt.core.parser.util.StringUtil; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.core.runtime.preferences.InstanceScope; - -import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; -import io.sloeber.autoBuild.helpers.api.KeyValueTree; -import io.sloeber.core.api.Json.ArduinoPlatform; -import io.sloeber.core.api.Json.ArduinoPlatformTooldDependency; -import io.sloeber.core.api.Json.ArduinoPlatformVersion; -import io.sloeber.core.tools.KeyValue; -import io.sloeber.core.txt.BoardTxtFile; -import io.sloeber.core.txt.PlatformTxtFile; -import io.sloeber.core.txt.Programmers; -import io.sloeber.core.txt.TxtFile; - -public class BoardDescription { - private static final IEclipsePreferences myStorageNode = InstanceScope.INSTANCE.getNode(NODE_ARDUINO); - - /* - * This is the basic info contained in the descriptor - */ - private String myUploadPort = EMPTY; - private String myProgrammer = EMPTY; - private String myBoardID = EMPTY; - private Map myOptions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - private File myUserSelectedBoardsTxtFile; //this is the boards.txt file selected in the gui - private BoardTxtFile mySloeberBoardTxtFile; // this is the actual used and loaded sloeber.boards.txt file - - private String myBoardsCore = null; - private String myBoardsVariant = null; - private String myUploadTool = null; - - private ArduinoPlatformVersion myReferencedPlatformVariant = null; - private ArduinoPlatformVersion myReferencedPlatformCore = null; - private ArduinoPlatformVersion myReferencedPlatformUpload = null; - - private boolean isDirty = true; - - @Override - public String toString() { - return getReferencingBoardsFile() + " \"" + getBoardName() + "\" " + getUploadPort(); //$NON-NLS-1$//$NON-NLS-2$ - } - - /** - * Compare 2 descriptors and return true is they are equal. This method detects - * - OS changes - project name changes - moves of workspace - changed runtine - * eclipse install - * - * @param obj - * @return true if equal otherwise false - */ - public boolean equals(BoardDescription otherBoardDescriptor) { - if (otherBoardDescriptor == null) { - return false; - } - if (!this.getUploadPort().equals(otherBoardDescriptor.getUploadPort())) { - return false; - } - if (!this.getProgrammer().equals(otherBoardDescriptor.getProgrammer())) { - return false; - } - return !needsRebuild(otherBoardDescriptor); - } - - /** - * compare 2 board descriptors and return true if replacing one board descriptor - * with the other implies that a rebuild is needed - * - * @param otherBoardDescriptor - * @return - */ - public boolean needsRebuild(BoardDescription otherBoardDescriptor) { - if (otherBoardDescriptor == null) { - return true; - } - if (!this.getBoardID().equals(otherBoardDescriptor.getBoardID())) { - return true; - } - String moddedReferencingBoardsFile = makePathVersionString(getReferencingBoardsFile()); - String moddedOtherReferencingBoardsFile = makePathVersionString( - otherBoardDescriptor.getReferencingBoardsFile()); - if (!moddedReferencingBoardsFile.equals(moddedOtherReferencingBoardsFile)) { - return true; - } - if (!this.getOptions().equals(otherBoardDescriptor.getOptions())) { - return true; - } - return false; - } - - /** - * after construction data needs to be derived from other data. This method - * derives all other data and puts it in fields - */ - private void calculateDerivedFields() { - - myReferencedPlatformCore = null; - myBoardsCore = null; - myReferencedPlatformVariant = null; - myBoardsVariant = null; - myReferencedPlatformUpload = null; - myUploadTool = null; - setDefaultOptions(); - // search in the board info - ParseSection(); - - } - - private void ParseSection() { - KeyValueTree rootData = mySloeberBoardTxtFile.getData(); - String boardID = getBoardID(); - KeyValueTree boardData = rootData.getChild(boardID); - - String core = boardData.getValue(BUILD + DOT + CORE); - String variant = boardData.getValue(BUILD + DOT + VARIANT); - String upload = boardData.getValue(UPLOAD + DOT + TOOL); - // also search the options - for (Entry curOption : this.myOptions.entrySet()) { - KeyValueTree curMenuData = boardData.getChild(MENU + DOT + curOption.getKey() + DOT + curOption.getValue()); - String coreOption = curMenuData.getValue(BUILD + DOT + CORE); - String variantOption = curMenuData.getValue(BUILD + DOT + VARIANT); - String uploadOption = curMenuData.getValue(UPLOAD + DOT + TOOL); - if (!coreOption.isEmpty()) { - core = coreOption; - } - if (!variantOption.isEmpty()) { - variant = variantOption; - } - if (!uploadOption.isEmpty()) { - upload = uploadOption; - } - } - String architecture = getArchitecture(); - if (core != null) { - String valueSplit[] = core.split(COLON); - if (valueSplit.length == 2) { - String refVendor = valueSplit[0]; - myBoardsCore = valueSplit[1]; - myReferencedPlatformCore = BoardsManager.getNewestInstalledPlatform(refVendor, architecture); - if (myReferencedPlatformCore == null) { - Common.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, - Helpers_tool_reference_missing.replace(TOOL_TAG, core) - .replace(FILE_TAG, getReferencingBoardsFile().toString()) - .replace(BOARD_TAG, getBoardID()))); - return; - } - } else if (valueSplit.length == 4) { - String refVendor = valueSplit[0]; - String refArchitecture = valueSplit[1]; - VersionNumber refVersion = new VersionNumber(valueSplit[2]); - myBoardsCore = valueSplit[3]; - myReferencedPlatformCore = BoardsManager.getPlatform(refVendor, refArchitecture, refVersion); - if (myReferencedPlatformCore == null) { - Common.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, - Helpers_tool_reference_missing.replace(TOOL_TAG, core) - .replace(FILE_TAG, getReferencingBoardsFile().toString()) - .replace(BOARD_TAG, getBoardID()))); - return; - } - } else { - this.myBoardsCore = core; - } - } - if (variant != null) { - String valueSplit[] = variant.split(COLON); - if (valueSplit.length == 2) { - String refVendor = valueSplit[0]; - myBoardsVariant = valueSplit[1]; - myReferencedPlatformVariant = BoardsManager.getNewestInstalledPlatform(refVendor, architecture); - if (myReferencedPlatformVariant == null) { - Common.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, - Helpers_tool_reference_missing.replace(TOOL_TAG, variant) - .replace(FILE_TAG, getReferencingBoardsFile().toString()) - .replace(BOARD_TAG, getBoardID()))); - return; - } - } else if (valueSplit.length == 4) { - String refVendor = valueSplit[0]; - String refArchitecture = valueSplit[1]; - VersionNumber refVersion = new VersionNumber(valueSplit[2]); - myBoardsVariant = valueSplit[3]; - if ("*".equals(valueSplit[2])) { //$NON-NLS-1$ - myReferencedPlatformVariant = BoardsManager.getNewestInstalledPlatform(refVendor, refArchitecture); - } else { - myReferencedPlatformVariant = BoardsManager.getPlatform(refVendor, refArchitecture, refVersion); - } - if (myReferencedPlatformVariant == null) { - Common.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, - Helpers_tool_reference_missing.replace(TOOL_TAG, variant) - .replace(FILE_TAG, getReferencingBoardsFile().toString()) - .replace(BOARD_TAG, getBoardID()))); - return; - } - } else { - myBoardsVariant = variant; - } - } - if (upload != null) { - String valueSplit[] = upload.split(COLON); - if (valueSplit.length == 2) { - String refVendor = valueSplit[0]; - myUploadTool = valueSplit[1]; - myReferencedPlatformUpload = BoardsManager.getNewestInstalledPlatform(refVendor, architecture); - if (myReferencedPlatformUpload == null) { - Common.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, - Helpers_tool_reference_missing.replace(TOOL_TAG, upload) - .replace(FILE_TAG, getReferencingBoardsFile().toString()) - .replace(BOARD_TAG, getBoardID()))); - return; - } - } else if (valueSplit.length == 4) { - String refVendor = valueSplit[0]; - String refArchitecture = valueSplit[1]; - VersionNumber refVersion = new VersionNumber(valueSplit[2]); - myUploadTool = valueSplit[3]; - myReferencedPlatformUpload = BoardsManager.getPlatform(refVendor, refArchitecture, refVersion); - if (this.myReferencedPlatformUpload == null) { - Common.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, - Helpers_tool_reference_missing.replace(TOOL_TAG, upload) - .replace(FILE_TAG, getReferencingBoardsFile().toString()) - .replace(BOARD_TAG, getBoardID()))); - return; - } - } else { - myUploadTool = upload; - } - } - } - - /** - * make a board descriptor for each board in the board.txt file with the default - * options - * - * @param boardFile - * @return a list of board descriptors - */ - public static List makeBoardDescriptors(File boardFile) { - BoardTxtFile txtFile = new BoardTxtFile(resolvePathEnvironmentString(boardFile)); - List boards = new ArrayList<>(); - List boardIDs = txtFile.getAllBoardIDs(); - for (String curboardID : boardIDs) { - Map boardSection = txtFile.getSection(curboardID); - if (boardSection != null) { - if (!"true".equalsIgnoreCase(boardSection.get("hide"))) { //$NON-NLS-1$ //$NON-NLS-2$ - boards.add(new BoardDescription(boardFile, curboardID, null)); - } - } - } - return boards; - } - - /** - * create a board descriptor - * - * @param boardsFile - * @param boardID - * @param options - * if null default options are taken - */ - BoardDescription(File boardsFile, String boardID, Map options) { - myBoardID = boardID; - myUserSelectedBoardsTxtFile = boardsFile; - mySloeberBoardTxtFile = new BoardTxtFile(resolvePathEnvironmentString(myUserSelectedBoardsTxtFile)); - setDefaultOptions(); - if (options != null) { - myOptions.putAll(options); - } - } - - public BoardDescription() { - myUserSelectedBoardsTxtFile = new File(myStorageNode.get(KEY_LAST_USED_BOARDS_FILE, EMPTY)); - if (!myUserSelectedBoardsTxtFile.exists()) { - - ArduinoPlatformVersion platform = BoardsManager.getNewestInstalledPlatform(VENDOR_ARDUINO, AVR); - if (platform == null) { - List platforms = BoardsManager.getInstalledPlatforms(); - //If you crash on the next line no platform have been installed - platform = platforms.get(0); - } - myUserSelectedBoardsTxtFile = platform.getBoardsFile(); - mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); - - if (mySloeberBoardTxtFile.getAllBoardIDs().contains(UNO)) { - myBoardID = UNO; - } else { - myBoardID = mySloeberBoardTxtFile.getAllBoardIDs().get(0); - } - } else { - mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); - myBoardID = myStorageNode.get(KEY_LAST_USED_BOARD, EMPTY); - myUploadPort = myStorageNode.get(KEY_LAST_USED_UPLOAD_PORT, EMPTY); - myProgrammer = myStorageNode.get(KEY_LAST_USED_UPLOAD_PROTOCOL, EMPTY); - myOptions = KeyValue.makeMap(myStorageNode.get(KEY_LAST_USED_BOARD_MENU_OPTIONS, EMPTY)); - } - - } - - public BoardDescription(BoardDescription srcObject) { - myUserSelectedBoardsTxtFile = srcObject.myUserSelectedBoardsTxtFile; - mySloeberBoardTxtFile = srcObject.mySloeberBoardTxtFile; - myBoardID = srcObject.myBoardID; - myUploadPort = srcObject.myUploadPort; - myProgrammer = srcObject.myProgrammer; - myUploadTool = srcObject.myUploadTool; - myOptions.putAll( new TreeMap<>(srcObject.myOptions)); - - } - - public String getuploadTool() { - return this.myUploadTool; - } - - /* - * Sets default options as follows If no option is specified take the first one - * if a option is specified but the value is invalid take the first one - * - * this is so because I want to provide a list of options but if the options are - * incomplete or invalid this method still returns a complete and valid set. - */ - private void setDefaultOptions() { - Map allMenuIDs = this.mySloeberBoardTxtFile.getMenus(); - for (Map.Entry curMenuID : allMenuIDs.entrySet()) { - String providedMenuValue = this.myOptions.get(curMenuID.getKey()); - ArrayList menuOptions = this.mySloeberBoardTxtFile.getMenuItemIDsFromMenuID(curMenuID.getKey(), - getBoardID()); - if (menuOptions.size() > 0) { - if (providedMenuValue == null) { - - this.myOptions.put(curMenuID.getKey(), menuOptions.get(0)); - } else if (!menuOptions.contains(providedMenuValue)) { - this.myOptions.put(curMenuID.getKey(), menuOptions.get(0)); - } - } - } - } - - private void removeInvalidMenuIDs() { - Set allMenuIDs = this.mySloeberBoardTxtFile.getMenus().keySet(); - Set optionKey=new HashSet<>(myOptions.keySet()); - - for ( String curOptionKey : optionKey) { - if(!allMenuIDs.contains(curOptionKey)) { - myOptions.remove(curOptionKey); - } - } - } - - /** - * Store the selections the user made so we can reuse them when creating a new - * project - */ - public void saveUserSelection() { - myStorageNode.put(KEY_LAST_USED_BOARDS_FILE, getReferencingBoardsFile().toString()); - myStorageNode.put(KEY_LAST_USED_BOARD, this.myBoardID); - myStorageNode.put(KEY_LAST_USED_UPLOAD_PORT, this.myUploadPort); - myStorageNode.put(KEY_LAST_USED_UPLOAD_PROTOCOL, this.myProgrammer); - myStorageNode.put(KEY_LAST_USED_BOARD_MENU_OPTIONS, KeyValue.makeString(this.myOptions)); - } - - public String getArchitecture() { - return mySloeberBoardTxtFile.getArchitecture(); - } - - public String getVendor() { - return mySloeberBoardTxtFile.getVendor(); - } - - public File getReferencingBoardsFile() { - return myUserSelectedBoardsTxtFile; - } - - public String getBoardName() { - return this.mySloeberBoardTxtFile.getNiceNameFromID(this.myBoardID); - } - - public String getUploadPort() { - return this.myUploadPort; - } - - /** - * return the actual adress en,coded in the upload port example uploadport com4 - * returns com4 uploadport = arduino.local at 199.25.25.1 returns arduino.local - * - * @return - */ - public String getActualUploadPort() { - return myUploadPort.split(" ")[0]; //$NON-NLS-1$ - } - - public String getProgrammer() { - return this.myProgrammer; - } - - /** - * Set the upload port like in the gui. The upload port can be a comport or a - * networkadress space and something else note that getuploadport returns the - * before space part of this method - * - * @param newUploadPort - */ - public void setUploadPort(String newUploadPort) { - this.myUploadPort = newUploadPort; - } - - public void setProgrammer(String newUploadProtocol) { - this.myProgrammer = newUploadProtocol; - } - - public void setBoardID(String boardID) { - if (!boardID.equals(this.myBoardID)) { - this.myBoardID = boardID; - setDirty(); - } - } - - private void setDirty() { - isDirty = true; - - } - - public void setBoardName(String boardName) { - String newBoardID = this.mySloeberBoardTxtFile.getIDFromNiceName(boardName); - if ((newBoardID == null || this.myBoardID.equals(newBoardID))) { - return; - } - this.myBoardID = newBoardID; - setDirty(); - - } - - public void setreferencingBoardsFile(File boardsFile) { - if (boardsFile == null) { - return;// ignore - } - - if (!myUserSelectedBoardsTxtFile.equals(boardsFile)) { - myUserSelectedBoardsTxtFile = boardsFile; - setDirty(); - } - - /* do not remove this for optimization as workaround changes will not be captured */ - mySloeberBoardTxtFile = new BoardTxtFile(resolvePathEnvironmentString(myUserSelectedBoardsTxtFile)); - - } - /** - * seOptions add the options to the already existing options and removes the options - * with an invalid menuID - * The enuitemID is not verified and assumed correct. - * - */ - public void setOptions(Map options) { - if (options == null || options.size()==0) { - return; - } - myOptions.putAll(options); - removeInvalidMenuIDs(); - setDirty(); - } - - /** - * Returns the options for this board This reflects the options selected through - * the menu functionality in the boards.txt - * - * @return a map of case insensitive ordered key value pairs - */ - public Map getOptions() { - // no update is needed as this field is only modified at construction or set - return this.myOptions; - } - - private void updateWhenDirty() { - if (isDirty) { - calculateDerivedFields(); - isDirty = false; - } - } - - public String getBoardID() { - // no update is needed as this field is only modified at construction or set - return this.myBoardID; - } - - public String[] getCompatibleBoards() { - return this.mySloeberBoardTxtFile.getAllSectionNames(); - } - - public String[] getUploadProtocols() { - - return Programmers.getUploadProtocols(this); - - } - - public String[] getMenuItemNamesFromMenuID(String menuID) { - return this.mySloeberBoardTxtFile.getMenuItemNamesFromMenuID(menuID, this.myBoardID); - } - - - public String getMenuNameFromMenuID(String id) { - return this.mySloeberBoardTxtFile.getMenuNameFromID(id); - } - - public String getMenuItemNamedFromMenuItemID(String menuItemID, String menuID) { - return this.mySloeberBoardTxtFile.getMenuItemNameFromMenuItemID(this.myBoardID, menuID, menuItemID); - } - - public String getMenuItemIDFromMenuItemName(String menuItemName, String menuID) { - return this.mySloeberBoardTxtFile.getMenuItemIDFromMenuItemName(this.myBoardID, menuID, menuItemName); - } - - /** - * provide the actual path to the variant. Use this method if you want to know - * where the variant is - * - * @return the path to the variant; null if no variant is needed - */ - public IPath getActualVariantPath() { - updateWhenDirty(); - String boardVariant = getBoardVariant(); - if (boardVariant == null || boardVariant.isBlank()) { - return null; - } - if (myReferencedPlatformVariant == null) { - return new Path(myUserSelectedBoardsTxtFile.getParent().toString()).append(ARDUINO_VARIANTS_FOLDER_NAME) - .append(boardVariant); - } - return myReferencedPlatformVariant.getInstallPath().append(ARDUINO_VARIANTS_FOLDER_NAME).append(boardVariant); - } - - private String getBoardVariant() { - updateWhenDirty(); - return this.myBoardsVariant; - } - - public IPath getActualCoreCodePath() { - updateWhenDirty(); - if (myBoardsCore == null) { - return null; - } - IPath retPath = null; - if (myReferencedPlatformCore == null) { - retPath = getreferencingPlatformPath(); - } else { - retPath = myReferencedPlatformCore.getInstallPath(); - } - return retPath.append(CORES).append(myBoardsCore); - } - - public IPath getReferencedUploadPlatformPath() { - updateWhenDirty(); - if (myReferencedPlatformUpload != null) { - return myReferencedPlatformUpload.getInstallPath(); - } - return getreferencingPlatformPath(); - } - - public PlatformTxtFile getReferencingPlatformFile() { - updateWhenDirty(); - File platformFile = getreferencingPlatformPath().append(PLATFORM_FILE_NAME).toFile(); - if (platformFile != null && platformFile.exists()) { - return new PlatformTxtFile(platformFile); - } - return null; - } - - public Path getreferencingPlatformPath() { - try { - return new Path(myUserSelectedBoardsTxtFile.getParent()); - } catch (@SuppressWarnings("unused") Exception e) { - return new Path(EMPTY); - } - } - - public PlatformTxtFile getreferencedCorePlatformFile() { - updateWhenDirty(); - if (myReferencedPlatformCore == null) { - return null; - } - File platformFile = myReferencedPlatformCore.getInstallPath().append(PLATFORM_FILE_NAME).toFile(); - if (platformFile != null && platformFile.exists()) { - return new PlatformTxtFile(platformFile); - } - return null; - } - - public IPath getReferencedCoreLibraryPath() { - updateWhenDirty(); - if (myReferencedPlatformCore == null) { - return null; - } - return this.myReferencedPlatformCore.getInstallPath().append(ARDUINO_LIBRARY_FOLDER_NAME); - } - - public IPath getReferencingLibraryPath() { - updateWhenDirty(); - return this.getreferencingPlatformPath().append(ARDUINO_LIBRARY_FOLDER_NAME); - } - - public String getUploadPatternKey() { - updateWhenDirty(); - String upLoadTool = getuploadTool(); - String networkPrefix = EMPTY; - if (isNetworkUpload()) { - networkPrefix = NETWORK_PREFIX; - } - return TOOLS + DOT + upLoadTool + DOT + UPLOAD + DOT + networkPrefix + PATTERN; - } - - public IPath getreferencedCoreHardwarePath() { - updateWhenDirty(); - if (myReferencedPlatformCore == null) { - return getreferencingPlatformPath(); - } - return myReferencedPlatformCore.getInstallPath(); - } - - /* - * get the latest installed arduino platform with the same architecture. This is - * the platform to use the programmers.txt if no other programmers.txt are - * found. - */ - public IPath getArduinoPlatformPath() { - updateWhenDirty(); - ArduinoPlatform platform = BoardsManager.getPlatform(VENDOR_ARDUINO, getArchitecture()); - if (platform == null) { - return null; - } - ArduinoPlatformVersion platformVersion = platform.getNewestInstalled(); - if (platformVersion == null) { - return null; - } - return platformVersion.getInstallPath(); - } - - /** - * If the upload port contains a space everything before the first space is - * considered to be a dns name or ip adress. - * - * @param mComPort - * @return null if no space in uploadport return dns name op ipadress - */ - public String getHost() { - String host = myUploadPort.split(" ")[0]; //$NON-NLS-1$ - if (host.equals(myUploadPort)) - return null; - return host; - } - - /** - * true if this board needs a networkUpload else false - * - * @return - */ - public boolean isNetworkUpload() { - return getHost() != null; - } - - protected BoardDescription(File boardsFile, String boardID) { - myBoardID = boardID; - myUserSelectedBoardsTxtFile = boardsFile; - mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); - setDefaultOptions(); - calculateDerivedFields(); - } - - BoardDescription(TxtFile configFile, String prefix) { - - KeyValueTree tree = configFile.getData(); - KeyValueTree section = tree.getChild(prefix); - myProgrammer = section.getValue(KEY_SLOEBER_PROGRAMMER); - myBoardID = section.getValue(KEY_SLOEBER_BOARD_ID); - String board_txt = section.getValue(KEY_SLOEBER_BOARD_TXT); - myUploadPort = section.getValue(KEY_SLOEBER_UPLOAD_PORT); - KeyValueTree optionsTree = section.getChild(KEY_SLOEBER_MENU_SELECTION); - Map options = optionsTree.toKeyValues(EMPTY); - - myUserSelectedBoardsTxtFile = resolvePathEnvironmentString(new File(board_txt)); - mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); - setDefaultOptions(); - if (options != null) { - // Only add the valid options for this board to our options - myOptions.putAll(onlyKeepValidOptions(options)); - } - } - - /** - * create a BoardDescription based on the environment variables given - * - * @param envVars - */ - public BoardDescription(Map envVars) { - int menuKeyLength = KEY_SLOEBER_MENU_SELECTION.length() + DOT.length(); - for (Entry curEnvVar : envVars.entrySet()) { - String key = curEnvVar.getKey(); - String value = curEnvVar.getValue(); - switch (key) { - case KEY_SLOEBER_PROGRAMMER: - myProgrammer = value; - break; - case KEY_SLOEBER_BOARD_ID: - myBoardID = value; - break; - case KEY_SLOEBER_BOARD_TXT: - myUserSelectedBoardsTxtFile = resolvePathEnvironmentString(new File(value)); - mySloeberBoardTxtFile = new BoardTxtFile(myUserSelectedBoardsTxtFile); - break; - case KEY_SLOEBER_UPLOAD_PORT: - myUploadPort = value; - break; - default: - if (key.startsWith(KEY_SLOEBER_MENU_SELECTION + DOT)) { - String cleanKey = key.substring(menuKeyLength); - myOptions.put(cleanKey, value); - } - } - } - } - - /** - * get the environment variables that need to be stored in the configuration - * files configuration files are files needed to setup the sloeber environment - * for instance when openiung a project or after import of a project in the - * workspace - * - * @return the minimum list of environment variables to recreate the project - */ - public Map getEnvVarsConfig() { - Map allVars = new TreeMap<>(); - String board_txt = makePathVersionString(getReferencingBoardsFile()); - - allVars.put(KEY_SLOEBER_PROGRAMMER, myProgrammer); - allVars.put(KEY_SLOEBER_BOARD_ID, myBoardID); - allVars.put(KEY_SLOEBER_BOARD_TXT, board_txt); - allVars.put(KEY_SLOEBER_UPLOAD_PORT, myUploadPort); - - for (Entry curOption : myOptions.entrySet()) { - allVars.put(KEY_SLOEBER_MENU_SELECTION + DOT + curOption.getKey(), curOption.getValue()); - } - return allVars; - } - - private Map onlyKeepValidOptions(Map options) { - Map ret = new HashMap<>(); - - KeyValueTree tree = mySloeberBoardTxtFile.getData(); - KeyValueTree boardMenuSection = tree.getChild(myBoardID + DOT + MENU); - if (boardMenuSection != null) { - for (Entry curoption : options.entrySet()) { - String key = curoption.getKey(); - if (boardMenuSection.getChild(key).getKey() != null) { - ret.put(key, curoption.getValue()); - } - } - } - return ret; - } - - /** - * get the environment variables that need to be stored in version control - * - * @return the minimum list of environment variables to recreate the project - * from version control - */ - public Map getEnvVarsVersion(String prefix) { - Map allVars = new TreeMap<>(); - String board_txt = makePathVersionString(getReferencingBoardsFile()); - - allVars.put(prefix + KEY_SLOEBER_BOARD_ID, myBoardID); - allVars.put(prefix + KEY_SLOEBER_BOARD_TXT, board_txt); - - for (Entry curOption : myOptions.entrySet()) { - allVars.put(prefix + KEY_SLOEBER_MENU_SELECTION + DOT + curOption.getKey(), curOption.getValue()); - } - return allVars; - } - - /** - * This method creates environment variables based on the platform.txt and - * boards.txt. platform.txt is processed first and then boards.txt. This way - * boards.txt settings can overwrite common settings in platform.txt The - * environment variables are only valid for the project given as parameter The - * project properties are used to identify the boards.txt and platform.txt as - * well as the board id to select the settings in the board.txt file At the end - * also the path variable is set - * - * - * To be able to quickly fix boards.txt and platform.txt problems I also added a - * pre and post platform and boards files that are processed before and after - * the arduino delivered boards.txt file. - * - * @param project - * the project for which the environment variables are set - * @param arduinoProperties - * the info of the selected board to set the variables for - */ - public Map getEnvVars() { - updateWhenDirty(); - - TxtFile pluginPreProcessingPlatformTxt = new TxtFile(ConfigurationPreferences.getPreProcessingPlatformFile()); - TxtFile pluginPostProcessingPlatformTxt = new TxtFile(ConfigurationPreferences.getPostProcessingPlatformFile()); - BoardTxtFile pluginPreProcessingBoardsTxt = new BoardTxtFile( - ConfigurationPreferences.getPreProcessingBoardsFile()); - BoardTxtFile pluginPostProcessingBoardsTxt = new BoardTxtFile( - ConfigurationPreferences.getPostProcessingBoardsFile()); - - Map allVars = pluginPreProcessingPlatformTxt.getAllEnvironVars(EMPTY); - allVars.putAll(pluginPreProcessingBoardsTxt.getBoardEnvironVars(getBoardID())); - - String architecture = getArchitecture(); - IPath coreHardwarePath = getreferencedCoreHardwarePath(); - allVars.put(ENV_KEY_BUILD_ARCH, architecture.toUpperCase()); - allVars.put(ENV_KEY_RUNTIME_HARDWARE_PATH, getreferencingPlatformPath().removeLastSegments(1).toOSString()); - allVars.put(ENV_KEY_BUILD_SYSTEM_PATH, coreHardwarePath.append(SYSTEM).toOSString()); - allVars.put(ENV_KEY_RUNTIME_PLATFORM_PATH, getreferencingPlatformPath().toOSString()); - //ide_version is defined in pre_processing_platform_default.txt - allVars.put(ENV_KEY_RUNTIME_IDE_VERSION, makeEnvironmentVar("ide_version")); //$NON-NLS-1$ - allVars.put(ENV_KEY_RUNTIME_IDE_PATH, makeEnvironmentVar(SLOEBER_HOME)); - if(isWindows) { - allVars.put(ENV_KEY_RUNTIME_OS, "windows"); //$NON-NLS-1$ - } - if(isLinux) { - allVars.put(ENV_KEY_RUNTIME_OS, "linux"); //$NON-NLS-1$ - } - if(isMac) { - allVars.put(ENV_KEY_RUNTIME_OS, "macosx"); //$NON-NLS-1$ - } - allVars.put(ENV_KEY_ID,getBoardID()); - allVars.put(ENV_KEY_BUILD_FQBN,getBoardFQBN()); - - allVars.put(ENV_KEY_SERIAL_PORT, getActualUploadPort()); - allVars.put(ENV_KEY_SERIAL_DOT_PORT, getActualUploadPort()); - - allVars.put(ENV_KEY_SERIAL_PORT_FILE, getActualUploadPort().replace("/dev/", EMPTY)); //$NON-NLS-1$ - // if actual core path is osstring regression test issue555 willl fail teensy - // stuff - allVars.put(ENV_KEY_BUILD_ACTUAL_CORE_PATH, getActualCoreCodePath().toString()); - IPath variantPath = getActualVariantPath(); - if (variantPath != null) { - allVars.put(ENV_KEY_BUILD_VARIANT_PATH, variantPath.toOSString()); - } else {// teensy does not use variant - allVars.put(ENV_KEY_BUILD_VARIANT_PATH, EMPTY); - } - - PlatformTxtFile referencedPlatfromFile = getreferencedCorePlatformFile(); - // process the platform file referenced by the boards.txt - if (referencedPlatfromFile != null) { - allVars.putAll(referencedPlatfromFile.getAllEnvironVars()); - } - PlatformTxtFile referencingPlatfromFile = getReferencingPlatformFile(); - // process the platform file next to the selected boards.txt - if (referencingPlatfromFile != null) { - allVars.putAll(referencingPlatfromFile.getAllEnvironVars()); - } - - // put in the installed tools info - allVars.putAll(getEnVarPlatformInfo()); - - // boards settings not coming from menu selections - allVars.putAll(mySloeberBoardTxtFile.getBoardEnvironVars(getBoardID())); - - // board settings from menu selections - Map options = getOptions(); - KeyValueTree rootData = mySloeberBoardTxtFile.getData(); - KeyValueTree menuData = rootData.getChild(getBoardID() + DOT + MENU); - for (Entry curOption : options.entrySet()) { - String menuID = curOption.getKey(); - String SelectedMenuItemID = curOption.getValue(); - KeyValueTree curSelectedMenuItem = menuData.getChild(menuID + DOT + SelectedMenuItemID); - allVars.putAll(curSelectedMenuItem.toKeyValues(EMPTY)); - } - - //This moved last. See github issue 1410 - Programmers localProgrammers[] = Programmers.fromBoards(this); - String programmer = getProgrammer(); - for (Programmers curProgrammer : localProgrammers) { - String programmerID = curProgrammer.getIDFromNiceName(programmer); - if (programmerID != null) { - allVars.putAll(curProgrammer.getAllEnvironVars(programmerID)); - } - } - - // add the stuff that comes with the plugin that is marked as post - allVars.putAll(pluginPostProcessingPlatformTxt.getAllEnvironVars(EMPTY)); - allVars.putAll(pluginPostProcessingBoardsTxt.getBoardEnvironVars(getBoardID())); - - // Do some coded post processing - allVars.putAll(getEnvVarsPostProcessing(allVars)); - return allVars; - - } - - private String getBoardFQBN() { - String fqbn=getVendor()+COLON+getArchitecture()+COLON+getBoardID(); - String options=EMPTY_STRING; - String prefix=COLON; - for(Entry curOption:myOptions.entrySet()){ - options=options+prefix+curOption.getKey()+EQUAL+curOption.getValue(); - prefix=COMMA; - } - return fqbn+options; - } - - private Map getEnVarPlatformInfo() { - Map ret = new HashMap<>(); - - if (myReferencedPlatformUpload != null) { - ret.putAll(getEnvVarPlatformFileTools(myReferencedPlatformUpload)); - } - if (myReferencedPlatformVariant != null) { - ret.putAll(getEnvVarPlatformFileTools(myReferencedPlatformVariant)); - } - - if (myReferencedPlatformCore != null) { - ret.putAll(getEnvVarPlatformFileTools(myReferencedPlatformCore)); - } - - IPath referencingPlatformPath = getreferencingPlatformPath(); - ArduinoPlatformVersion referencingPlatform = BoardsManager.getPlatform(referencingPlatformPath); - - if (referencingPlatform == null) { - // This is the case for private hardware - //there is no need to specify tool path as they do not use them - return ret; - } - ArduinoPlatformVersion latestArduinoPlatform = BoardsManager.getNewestInstalledPlatform(Const.VENDOR_ARDUINO, - referencingPlatform.getArchitecture()); - if (latestArduinoPlatform != null) { - ret.putAll(getEnvVarPlatformFileTools(latestArduinoPlatform)); - } - - if (myReferencedPlatformCore == null) { - //there is no referenced core so no need to do smart stuff - ret.putAll(getEnvVarPlatformFileTools(referencingPlatform)); - return ret; - } - - boolean jsonBasedPlatformManagement = !Preferences.getUseArduinoToolSelection(); - if (jsonBasedPlatformManagement) { - // overrule the Arduino IDE way of working and use the json refereced tools - ret.putAll(getEnvVarPlatformFileTools(referencingPlatform)); - return ret; - } - // standard arduino IDE way - ret.putAll(getEnvVarPlatformFileTools(referencingPlatform)); - ret.putAll(getEnvVarPlatformFileTools(myReferencedPlatformCore)); - return ret; - - } - - /** - * This method only returns environment variables with and without version - * number - * These are purely based on the tool dependencies - * - * @param platformVersion - * @return environment variables pointing to the tools used by the platform - */ - private static Map getEnvVarPlatformFileTools(ArduinoPlatformVersion platformVersion) { - HashMap vars = new HashMap<>(); - for (ArduinoPlatformTooldDependency tool : platformVersion.getToolsDependencies()) { - IPath installPath = tool.getInstallPath(); - if (installPath.toFile().exists()) { - String value = installPath.toOSString(); - String keyString = ENV_KEY_RUNTIME_TOOLS + tool.getName() + tool.getVersion() + DOT_PATH; - vars.put(keyString, value); - keyString = ENV_KEY_RUNTIME_TOOLS + tool.getName() + '-' + tool.getVersion() + DOT_PATH; - vars.put(keyString, value); - keyString = ENV_KEY_RUNTIME_TOOLS + tool.getName() + DOT_PATH; - vars.put(keyString, value); - } - } - return vars; - } - - /** - * Following post processing is done - * - * - * The handling of the upload variables is done differently in arduino - * than in Sloeber. This is taken care of here. for example the output of this - * input - * tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} - * is changed as if it were the output of this input - * tools.avrdude.upload.pattern="{tools.avrdude.cmd.path}" - * "-C{tools.avrdude.config.path}" {tools.avrdude.upload.verbose} - * - * if a programmer is selected different from default some extra actions - * are done here so no special code is needed to handle programmers - * - * The build path for the core is {build.path}/core/core in sloeber - * where it is {build.path}/core/ in arduino world and used to be {build.path}/ - * This only gives problems in the link command as sometimes there are hardcoded - * links to some sys files so ${build.path}/core/sys* ${build.path}/sys* is - * replaced with ${build.path}/core/core/sys* - * - * @param contribEnv - * @param confDesc - * @param boardsDescriptor - */ - private static Map getEnvVarsPostProcessing(Map vars) { - - Map extraVars = new HashMap<>(); - - ArrayList objcopyCommand = new ArrayList<>(); - for (Entry curVariable : vars.entrySet()) { - String name = curVariable.getKey(); - String value = curVariable.getValue(); - if (name.startsWith(RECIPE_OBJCOPY) && name.endsWith(".pattern") && !value.isEmpty()) { //$NON-NLS-1$ - objcopyCommand.add(makeEnvironmentVar(name)); - } - } - Collections.sort(objcopyCommand); - extraVars.put(SLOEBER_OBJCOPY, StringUtil.join(objcopyCommand, NEWLINE)); - - // add -relax for mega boards; the arduino ide way - String buildMCU = vars.get(ENV_KEY_BUILD_MCU); - if ("atmega2560".equalsIgnoreCase(buildMCU)) { //$NON-NLS-1$ - String c_elf_flags = vars.get(ENV_KEY_BUILD_COMPILER_C_ELF_FLAGS); - extraVars.put(ENV_KEY_BUILD_COMPILER_C_ELF_FLAGS, c_elf_flags + ",--relax"); //$NON-NLS-1$ - } - return extraVars; - } - - public LinkedHashMap getHookSteps(LinkedHashSet hookNames,IAutoBuildConfigurationDescription autoData) { - LinkedHashMap hookSteps = new LinkedHashMap<>(); - KeyValueTree keyValueTree = KeyValueTree.createRoot(); - - PlatformTxtFile referencedPlatfromFile = getreferencedCorePlatformFile(); - // process the platform file referenced by the boards.txt - if (referencedPlatfromFile != null) { - try { - keyValueTree.mergeFile(referencedPlatfromFile.getLoadedFile()); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - PlatformTxtFile referencingPlatfromFile = getReferencingPlatformFile(); - // process the platform file next to the selected boards.txt - if (referencingPlatfromFile != null) { - try { - keyValueTree.mergeFile(referencingPlatfromFile.getLoadedFile()); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - KeyValueTree hooks = keyValueTree.getChild(RECIPE).getChild(HOOKS); - for(String hookName:hookNames) { - hooks=hooks.getChild(hookName); - } - - // Try to find the nums from 1 to 10 in order - // that is 01 1 02 2 - - for (int hoookNum = 1; hoookNum < 10; hoookNum++) { - boolean exists=false; - for (int numDigits = 1; numDigits <= 2; numDigits++) { - String formatter = "%0" + Integer.toString(numDigits) + "d"; //$NON-NLS-1$ //$NON-NLS-2$ - String curKey = String.format(formatter, Integer.valueOf(hoookNum)); - KeyValueTree curHook = hooks.getChild(curKey).getChild(PATTERN); - if (curHook.getValue() != null) { - String cmd=resolve(curHook.getValue(), EMPTY_STRING, WHITESPACE, autoData); - hookSteps.put(curKey, cmd); - exists=true; - } - } - if(!exists) { - break; - } - } - return hookSteps; - } - - public boolean isValid() { - if (!myUserSelectedBoardsTxtFile.exists()) { - return false; - } - File boardsFile = mySloeberBoardTxtFile.getLoadedFile(); - if (boardsFile == null) { - return false; - } - return boardsFile.exists(); - } - - public void reloadTxtFile() { - mySloeberBoardTxtFile.reloadTxtFile(); - - } - - public Map getAllMenus() { - return mySloeberBoardTxtFile.getMenus(); - } - - public boolean isSSHUpload() { - if (!isNetworkUpload()) { - return false; - } - // This is a hardcoded fix. Not sure how to do better - return myBoardID.equals("yun"); //$NON-NLS-1$ - } - - - public String getDefaultValueIDFromMenu(String menuID) { - return this.mySloeberBoardTxtFile.getDefaultValueIDFromMenu(getBoardID(),menuID); - } - public String getDefaultValueNameFromMenu(String menuID) { - return this.mySloeberBoardTxtFile.getDefaultValueNameFromMenu(getBoardID(),menuID); - } - - public boolean isPrivate() { - return ! sloeberHomePath.isPrefixOf( new Path(myUserSelectedBoardsTxtFile.toString())); - } -} diff --git a/io.sloeber.core/src/io/sloeber/core/api/BoardsManager.java b/io.sloeber.core/src/io/sloeber/core/api/BoardsManager.java deleted file mode 100644 index 638807179..000000000 --- a/io.sloeber.core/src/io/sloeber/core/api/BoardsManager.java +++ /dev/null @@ -1,899 +0,0 @@ -package io.sloeber.core.api; - -import static io.sloeber.core.Messages.*; -import static io.sloeber.core.api.Common.*; -import static io.sloeber.core.api.ConfigurationPreferences.*; -import static io.sloeber.core.api.Const.*; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.Reader; -import java.net.MalformedURLException; -import java.net.URL; -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.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.eclipse.cdt.core.parser.util.StringUtil; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Status; -import org.eclipse.ui.statushandlers.StatusManager; - -import com.google.gson.Gson; - -import io.sloeber.core.Activator; -import io.sloeber.core.Messages; -import io.sloeber.core.api.Json.ArduinoInstallable; -import io.sloeber.core.api.Json.ArduinoPackage; -import io.sloeber.core.api.Json.ArduinoPlatform; -import io.sloeber.core.api.Json.ArduinoPlatformPackageIndex; -import io.sloeber.core.api.Json.ArduinoPlatformTool; -import io.sloeber.core.api.Json.ArduinoPlatformToolVersion; -import io.sloeber.core.api.Json.ArduinoPlatformTooldDependency; -import io.sloeber.core.api.Json.ArduinoPlatformVersion; -import io.sloeber.core.common.InstancePreferences; -import io.sloeber.core.managers.InstallProgress; -import io.sloeber.core.tools.MyMultiStatus; -import io.sloeber.core.tools.PackageManager; -import io.sloeber.core.txt.BoardTxtFile; -import io.sloeber.core.txt.WorkAround; - -/** - * This class groups both boards installed by the hardware manager and boards - * installed locally. - * - * @author jantje - * - */ -public class BoardsManager { - private static String stringSplitter = "\n";//$NON-NLS-1$ - private static final String KEY_MANAGER_JSON_URLS_V3 = "Arduino Manager board Urls"; //$NON-NLS-1$ - private static final String KEY_MANAGER_ARDUINO_LIBRARY_JSON_URL = "https://downloads.arduino.cc/libraries/library_index.json"; //$NON-NLS-1$ - private static final String KEY_MANAGER_JSON_URLS = "Manager jsons"; //$NON-NLS-1$ - private static final String DEFAULT_JSON_URLS = "https://downloads.arduino.cc/packages/package_index.json\n" //$NON-NLS-1$ - + "https://raw.githubusercontent.com/jantje/hardware/master/package_jantje_index.json\n" //$NON-NLS-1$ - + "https://raw.githubusercontent.com/jantje/ArduinoLibraries/master/library_jantje_index.json\n" //$NON-NLS-1$ - + "https://arduino.esp8266.com/stable/package_esp8266com_index.json\n" //$NON-NLS-1$ - + "https://www.pjrc.com/teensy/package_teensy_index.json\n" //$NON-NLS-1$ - + KEY_MANAGER_ARDUINO_LIBRARY_JSON_URL; - - protected static List packageIndices; - private static boolean myHasbeenLogged = false; - private static boolean envVarsNeedUpdating = true;// reset global variables at startup - - private static HashMap myWorkbenchEnvironmentVariables = new HashMap<>(); - - /** - * Gets the board description based on the information provided. If - * jsonFileName="local" the board is assumed not to be installed by the boards - * manager. Otherwise the boardsmanager is queried to find the board descriptor. - * In this case the latest installed board will be returned - * - * @param jsonFileName - * equals to "local" or the name of the json file used by the boards - * manager to install the boards - * @param packageName - * if jsonFileName equals "local" the filename of the boards.txt - * containing the boards. otherwise the name of the package - * containing the board - * @param architectureID - * ignored if jsonFileName equals "local" otherwise the architecture - * name of the platform containing the board (this assumes the - * architecture is the unique id for the platform) - * @param boardID - * the id of the board in the boards.txt file - * @param options - * the options to specify the board (the menu named on the boards.txt - * file) or null for defaults - * @return The class BoardDescriptor or null - */ - static public BoardDescription getBoardDescription(String jsonFileName, String packageName, String architectureID, - String boardID, Map options) { - if (LOCAL.equals(jsonFileName)) { - return new BoardDescription(new File(packageName), boardID, options); - } - return getNewestBoardIDFromBoardsManager(jsonFileName, packageName, architectureID, boardID, options); - } - - static private BoardDescription getNewestBoardIDFromBoardsManager(String jsonFileName, String packageName, - String architectureID, String boardID, Map options) { - - ArduinoPackage thePackage = getPackage(jsonFileName, packageName); - if (thePackage == null) { - System.err.println("failed to find package:" + packageName); //$NON-NLS-1$ - return null; - } - ArduinoPlatform platform = thePackage.getPlatform(architectureID); - if (platform == null) { - System.err.println("failed to find architecture ID " + architectureID + " in package:" + packageName); //$NON-NLS-1$ //$NON-NLS-2$ - return null; - } - ArduinoPlatformVersion platformVersion = platform.getNewestVersion(); - java.io.File boardsFile = platformVersion.getBoardsFile(); - BoardDescription boardid = new BoardDescription(boardsFile, boardID, options); - - return boardid; - } - - public static void addPackageURLs(HashSet packageUrlsToAdd, boolean forceDownload) { - HashSet originalJsonUrls = new HashSet<>(Arrays.asList(getJsonURLList())); - packageUrlsToAdd.addAll(originalJsonUrls); - - setJsonURLs(packageUrlsToAdd); - loadJsons(forceDownload); - } - - public static void setPackageURLs(HashSet packageUrls, boolean forceDownload) { - if (!isReady()) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); - return; - } - setJsonURLs(packageUrls); - loadJsons(forceDownload); - } - - /** - * installs a subset of the latest platforms It skips the first - * platforms And stops at platforms. To install the 5 first latest - * platforms installsubsetOfLatestPlatforms(0,5) - * - * @param fromIndex - * the platforms at the start to skip - * @param toIndex - * the platforms after this platform are skipped - */ - public static void installsubsetOfLatestPlatforms(int fromIndex, int toIndex) { - String DEPRECATED = "DEPRECATED"; //$NON-NLS-1$ - if (!isReady()) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); - return; - } - envVarsNeedUpdating = true; - int currPlatformIndex = 1; - NullProgressMonitor monitor = new NullProgressMonitor(); - List allPackages = getPackages(); - for (ArduinoPackage curPackage : allPackages) { - Collection latestPlatforms = curPackage.getPlatforms(); - for (ArduinoPlatform curPlatform : latestPlatforms) { - if (!curPlatform.getName().toUpperCase().contains(DEPRECATED)) { - if (currPlatformIndex > fromIndex) { - ArduinoPlatformVersion latestPlatformVersion = curPlatform.getNewestVersion(); - if (!latestPlatformVersion.getName().toUpperCase().contains(DEPRECATED)) { - install(latestPlatformVersion, monitor); - } else { - System.out.println("skipping platform " + latestPlatformVersion.toString()); //$NON-NLS-1$ - } - } - if (currPlatformIndex++ > toIndex) { - return; - } - } else { - System.out.println("skipping platform " + curPlatform.toString()); //$NON-NLS-1$ - } - } - } - } - - /** - * Install all the latest platforms Assumes there are less than 100000 platforms - */ - public static void installAllLatestPlatforms() { - installsubsetOfLatestPlatforms(0, 100000); - } - - public static void installLatestPlatform(String JasonName, String packageName, String architectureName) { - if (!isReady()) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); - return; - } - envVarsNeedUpdating = true; - ArduinoPackage curPackage = getPackage(JasonName, packageName); - if (curPackage != null) { - ArduinoPlatform curPlatform = curPackage.getPlatform(architectureName); - if (curPlatform != null) { - ArduinoPlatformVersion curPlatformVersion = curPlatform.getNewestVersion(); - if (curPlatformVersion != null) { - NullProgressMonitor monitor = new NullProgressMonitor(); - install(curPlatformVersion, monitor); - return; - } - } - } - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, - "failed to find " + JasonName + " " + packageName + " " + architectureName)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - private static IStatus install(ArduinoPlatformVersion platformVersion, IProgressMonitor monitor) { - boolean forceDownload = false; - // String name = platformVersion.getName(); - // String architecture = platformVersion.getArchitecture(); - // String version = platformVersion.getVersion().toString(); - // Check if we're installed already - if (platformVersion.isInstalled()) { - System.out.println("reusing platform " + platformVersion.toString()); //$NON-NLS-1$ - return Status.OK_STATUS; - } - - // Download platform archive - System.out.println("start installing platform " + platformVersion.toString()); //$NON-NLS-1$ - - MyMultiStatus mstatus = new MyMultiStatus("Failed to install " + platformVersion.getName()); //$NON-NLS-1$ - mstatus.addErrors(PackageManager.downloadAndInstall(platformVersion, forceDownload, monitor)); - if (!mstatus.isOK()) { - // no use installing tools when the boards failed installing - return mstatus; - } - - //keep a copy of the json file used at install - File packageFile = platformVersion.getParent().getParent().getPackageIndex().getJsonFile(); - File copyToFile = platformVersion.getInstallPath().append(packageFile.getName()).toFile(); - try { - Files.copy(packageFile.toPath(), copyToFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - e.printStackTrace(); - } - - ArduinoPackage referencingPkg = platformVersion.getParent().getParent(); - for (ArduinoPlatformTooldDependency toolDependency : platformVersion.getToolsDependencies()) { - ArduinoPlatformToolVersion tool = referencingPkg.getTool(toolDependency.getName(), - toolDependency.getVersion()); - if (tool == null) { - //this is a tool provided by another platform - //and the referencing platform does not specify the installable info - //This means the package file of the referencing platform needs to be provided - ArduinoPackage pkg = getPackageByProvider(toolDependency.getPackager()); - if (pkg != null) { - tool = pkg.getTool(toolDependency.getName(), toolDependency.getVersion()); - } - } - if (tool == null) { - mstatus.add(new Status(IStatus.ERROR, Activator.getId(), - Messages.Tool_no_valid_system.replace(Messages.KEY_TAG, toolDependency.getName()))); - } else if (!tool.isInstalled()) { - ArduinoInstallable installable = tool.getInstallable(); - if (installable != null) { - monitor.setTaskName(InstallProgress.getRandomMessage()); - mstatus.addErrors(PackageManager.downloadAndInstall(installable, forceDownload, monitor)); - } - } - } - - WorkAround.applyKnownWorkArounds(platformVersion); - - System.out.println("done installing platform " + platformVersion.toString()); //$NON-NLS-1$ - return mstatus; - } - - public static void addPrivateHardwarePath(String newHardwarePath) { - if (newHardwarePath == null) { - return; - } - String currentPaths[] = InstancePreferences.getPrivateHardwarePaths(); - String newPaths[] = new String[currentPaths.length + 1]; - for (int i = 0; i < currentPaths.length; i++) { - if (currentPaths[i].equals(newHardwarePath)) { - return; - } - newPaths[i] = currentPaths[i]; - } - newPaths[currentPaths.length] = newHardwarePath; - InstancePreferences.setPrivateHardwarePaths(newPaths); - } - - /** - * Searches for all boards.txt files from the hardware folders and the boards - * manager - * - * @return all the boards.txt files with full path and in a case insensitive - * order - */ - public static File[] getAllBoardsFiles() { - String hardwareFolders[] = getHardwarePaths(); - - TreeSet boardFiles = new TreeSet<>(); - for (String CurFolder : hardwareFolders) { - searchFiles(new File(CurFolder), boardFiles, Const.BOARDS_FILE_NAME, 6); - } - if (boardFiles.size() == 0) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, - Helpers_No_boards_txt_found.replace(FILE_TAG, String.join("\n", hardwareFolders)), null)); //$NON-NLS-1$ - return null; - } - return boardFiles.toArray(new File[boardFiles.size()]); - } - - private static void searchFiles(File folder, TreeSet Hardwarelists, String Filename, int depth) { - if (depth > 0) { - File[] a = folder.listFiles(); - if (a == null) { - if (!myHasbeenLogged) { - Common.log(new Status(IStatus.INFO, Const.CORE_PLUGIN_ID, - Helpers_Error_The_folder_is_empty.replace(FOLDER_TAG, folder.toString()), null)); - myHasbeenLogged = true; - } - return; - } - for (File f : a) { - if (f.isDirectory()) { - searchFiles(f, Hardwarelists, Filename, depth - 1); - } else if (f.getName().equals(Filename)) { - Hardwarelists.add(f); - } - } - } - } - - /** - * Gets all the folders that can contain hardware - * - * @return a list of all the folder locations that can contain hardware - */ - private static String[] getHardwarePaths() { - return (InstancePreferences.getPrivateHardwarePathsString() + File.pathSeparator - + ConfigurationPreferences.getInstallationPathPackages()).split(File.pathSeparator); - } - - public static IStatus updatePlatforms(List platformsToInstall, - List platformsToRemove, IProgressMonitor monitor, MultiStatus status) { - if (!isReady()) { - status.add(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, null)); - return status; - } - //TODO updating the jsons after selecting what to install seems dangerous to me; check to delete - if (!ConfigurationPreferences.getUpdateJasonFilesFlag()) { - loadJsons(true); - } - envVarsNeedUpdating = true; - try { - myIsReady = false; - for (ArduinoPlatformVersion curPlatform : platformsToRemove) { - status.add(uninstall(curPlatform, monitor)); - } - for (ArduinoPlatformVersion curPlatform : platformsToInstall) { - status.add(install(curPlatform, monitor)); - } - - } catch (@SuppressWarnings("unused") Exception e) { - // do nothing - } - myIsReady = true; - SloeberProject.reloadTxtFile(); - return status; - } - - public static IStatus uninstall(ArduinoPlatformVersion curPlatform, IProgressMonitor monitor) { - if (!curPlatform.isInstalled()) { - return Status.OK_STATUS; - } - - IPath installFolder = curPlatform.getInstallPath(); - try { - deleteDirectory(installFolder); - } catch (IOException e) { - return new Status(IStatus.ERROR, Activator.getId(), "Failed to remove folder" + installFolder.toString(), //$NON-NLS-1$ - e); - } - - return Status.OK_STATUS; - } - - public static TreeMap getAllmenus() { - TreeMap ret = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - File[] boardFiles = getAllBoardsFiles(); - for (File curBoardFile : boardFiles) { - BoardTxtFile txtFile = new BoardTxtFile(curBoardFile); - ret.putAll(txtFile.getMenus()); - } - return ret; - } - - public static void setPrivateHardwarePaths(String[] hardWarePaths) { - if (!isReady()) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); - return; - } - InstancePreferences.setPrivateHardwarePaths(hardWarePaths); - } - - public static String getPrivateHardwarePathsString() { - return InstancePreferences.getPrivateHardwarePathsString(); - } - - protected static synchronized void loadJsons(boolean forceDownload) { - packageIndices = new ArrayList<>(); - LibraryManager.flushIndices(); - - String[] jsonUrls = getJsonURLList(); - for (String jsonUrl : jsonUrls) { - if (!jsonUrl.trim().isEmpty()) // skip empty lines - loadJson(jsonUrl, forceDownload); - } - //sorting here so things look good in the gui - Collections.sort(packageIndices); - } - - /** - * This method takes a json boards file url and downloads it and parses it for - * usage in the boards manager - * - * @param url - * the url of the file to download and load - * @param forceDownload - * set true if you want to download the file even if it is already - * available locally - */ - static private void loadJson(String url, boolean forceDownload) { - File jsonFile = getLocalFileName(url, true); - if (jsonFile == null) { - return; - } - if (!jsonFile.exists() || forceDownload) { - jsonFile.getParentFile().mkdirs(); - try { - PackageManager.mySafeCopy(new URL(url.trim()), jsonFile, false); - } catch (IOException e) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), "Unable to download " + url, e)); //$NON-NLS-1$ - } - } - if (jsonFile.exists()) { - if (jsonFile.getName().toLowerCase().startsWith("package_")) { //$NON-NLS-1$ - loadPackage(jsonFile); - } else if (jsonFile.getName().toLowerCase().startsWith("library_")) { //$NON-NLS-1$ - LibraryManager.loadJson(jsonFile); - } else { - Common.log(new Status(IStatus.ERROR, Activator.getId(), - "json files should start with \"package_\" or \"library_\" " + url + " is ignored")); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - - static private void loadPackage(File jsonFile) { - try (Reader reader = new FileReader(jsonFile)) { - ArduinoPlatformPackageIndex index = new Gson().fromJson(reader, ArduinoPlatformPackageIndex.class); - index.setPackageFile(jsonFile); - packageIndices.add(index); - } catch (Exception e) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), - Manager_Failed_to_parse.replace(FILE_TAG, jsonFile.getAbsolutePath()), e)); - jsonFile.delete();// Delete the file so it stops damaging - } - } - - /** - * convert a web url to a local file name. The local file name is the cache of - * the web - * - * @param url - * url of the file we want a local cache - * @return the file that represents the file that is the local cache. the file - * itself may not exists. If the url is malformed return null; - * @throws MalformedURLException - */ - protected static File getLocalFileName(String url, boolean show_error) { - URL packageUrl; - try { - packageUrl = new URL(url.trim()); - } catch (MalformedURLException e) { - if (show_error) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), "Malformed url " + url, e)); //$NON-NLS-1$ - } - return null; - } - if ("file".equals(packageUrl.getProtocol())) { //$NON-NLS-1$ - String tst = packageUrl.getFile(); - File file = new File(tst); - String localFileName = file.getName(); - java.nio.file.Path packagePath = Paths - .get(ConfigurationPreferences.getInstallationPath().append(localFileName).toString()); - return packagePath.toFile(); - } - String localFileName = Paths.get(packageUrl.getPath()).getFileName().toString(); - java.nio.file.Path packagePath = Paths - .get(ConfigurationPreferences.getInstallationPath().append(localFileName).toString()); - return packagePath.toFile(); - } - - public static String getDefaultJsonURLs() { - return DEFAULT_JSON_URLS; - } - - public static String getJsonUrlsKey() { - return KEY_MANAGER_JSON_URLS; - } - - public static void setJsonURLs(String urls) { - setString(KEY_MANAGER_JSON_URLS, urls); - } - - private static void saveJsonURLs(String urls[]) { - setString(KEY_MANAGER_JSON_URLS, StringUtil.join(urls, stringSplitter)); - } - - public static void setJsonURLs(HashSet urls) { - setString(KEY_MANAGER_JSON_URLS, StringUtil.join(urls, stringSplitter)); - } - - public static String[] getJsonURLList() { - return getJsonURLs().replace("\r", new String()).split(stringSplitter); //$NON-NLS-1$ - } - - public static String getJsonURLs() { - // I added some code here to get easier from V3 to V4 - // the library json url is now managed as the boards url's so it also - // needs to be added to the json url's - // this is doen in the default but people who have installed other - // boards or do not move to the default (which is by default) - // wil not see libraries - // to fix this I changed the storage name and if the new storage name is - // empty I read the ol one and add the lib - String ret = getString(KEY_MANAGER_JSON_URLS, DEFAULT_JSON_URLS); - if (DEFAULT_JSON_URLS.equals(ret)) { - ret = getString(KEY_MANAGER_JSON_URLS_V3, DEFAULT_JSON_URLS); - if (!DEFAULT_JSON_URLS.equals(ret)) { - ret += System.lineSeparator() + KEY_MANAGER_ARDUINO_LIBRARY_JSON_URL; - setString(KEY_MANAGER_JSON_URLS, ret); - removeKey(KEY_MANAGER_JSON_URLS_V3); - } - } - return ret; - } - - /** - * Completely replace the list with jsons with a new list - * - * @param newJsonUrls - */ - public static void setJsonURLs(String[] newJsonUrls) { - if (!isReady()) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); - return; - } - - String curJsons[] = getJsonURLList(); - HashSet origJsons = new HashSet<>(Arrays.asList(curJsons)); - HashSet currentSelectedJsons = new HashSet<>(Arrays.asList(newJsonUrls)); - origJsons.removeAll(currentSelectedJsons); - // remove the files from disk which were in the old lst but not in the - // new one - for (String curJson : origJsons) { - try { - File localFile = getLocalFileName(curJson, false); - if (localFile.exists()) { - localFile.delete(); - } - } catch (@SuppressWarnings("unused") Exception e) { - // ignore - } - } - // save to configurationsettings before calling LoadIndices - saveJsonURLs(newJsonUrls); - // reload the indices (this will remove all potential remaining - // references - // existing files do not need to be refreshed as they have been - // refreshed at startup - // new files will be added - loadJsons(false); - } - - public static void removeAllInstalledPlatforms() { - if (!isReady()) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); - return; - } - try { - deleteDirectory(ConfigurationPreferences.getInstallationPathPackages()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static IPath getInstallationPath() { - return ConfigurationPreferences.getInstallationPath(); - } - - /** - * If something has been installed or deinstalled update the global variables - * with references to the installed stuff this to support platforms that do not - * explicitly define tools or platform dependencies Like private hardware - */ - public static Map getEnvironmentVariables() { - if (!envVarsNeedUpdating) { - return myWorkbenchEnvironmentVariables; - } - myWorkbenchEnvironmentVariables.clear(); - ArduinoPlatformVersion latestAvrPlatform = getNewestInstalledPlatform(Const.VENDOR_ARDUINO, Const.AVR); - ArduinoPlatformVersion latestSamdPlatform = getNewestInstalledPlatform(Const.VENDOR_ARDUINO, Const.SAMD); - ArduinoPlatformVersion latestSamPlatform = getNewestInstalledPlatform(Const.VENDOR_ARDUINO, Const.SAM); - - if (latestSamdPlatform != null) { - myWorkbenchEnvironmentVariables.putAll(getEnvVarPlatformFileTools(latestSamdPlatform)); - } - if (latestSamPlatform != null) { - myWorkbenchEnvironmentVariables.putAll(getEnvVarPlatformFileTools(latestSamPlatform)); - } - if (latestAvrPlatform != null) { - myWorkbenchEnvironmentVariables.putAll(getEnvVarPlatformFileTools(latestAvrPlatform)); - } - envVarsNeedUpdating = false; - return myWorkbenchEnvironmentVariables; - } - - private static Map getEnvVarPlatformFileTools(ArduinoPlatformVersion platformVersion) { - HashMap vars = new HashMap<>(); - ArduinoPackage pkg = platformVersion.getParent().getParent(); - for (ArduinoPlatformTooldDependency tool : platformVersion.getToolsDependencies()) { - ArduinoPlatformTool theTool = pkg.getTool(tool.getName()); - if (theTool == null) { - System.err.println("Did not find " + tool.getName() + " in package with ID " + pkg.getID()); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - vars.putAll(theTool.getEnvVars(null)); - } - } - return vars; - } - - /** - * given a vendor and a architecture provide the newest installed platform - * version - * - * @param vendor - * @param architecture - * @return the found platformVersion or null if none found - */ - public static ArduinoPlatformVersion getNewestInstalledPlatform(String vendor, String architecture) { - ArduinoPlatform platform = getPlatform(vendor, architecture); - if (platform == null) { - return null; - } - return platform.getNewestInstalled(); - } - - //Below is what used to be the internal package manager class - - private static boolean myIsReady = false; - - public static boolean isReady() { - return myIsReady; - } - - /** - * Loads all stuff needed and if this is the first time downloads the avr boards - * and needed tools - * - * @param monitor - */ - public static synchronized void startup_Pluging(IProgressMonitor monitor) { - loadJsons(ConfigurationPreferences.getUpdateJasonFilesFlag()); - - if (!LibraryManager.libsAreInstalled()) { - LibraryManager.InstallDefaultLibraries(monitor); - } - IPath examplesPath = ConfigurationPreferences.getInstallationPathExamples(); - if (!examplesPath.toFile().exists()) {// examples are not installed - // Download arduino IDE example programs - Common.log(PackageManager.downloadAndInstall(Defaults.EXAMPLES_URL, Defaults.EXAMPLE_PACKAGE, examplesPath, - false, monitor)); - } - if (!areThereInstalledBoards()) { - - IStatus status = null; - - // if successfully installed the examples: add the boards - ArduinoPlatform platform = getPlatform(Defaults.DEFAULT_INSTALL_MAINTAINER, - Defaults.DEFAULT_INSTALL_ARCHITECTURE); - //we failed to find arduino avr platform. Take the fiorst one - if (platform == null) { - try { - platform = getPlatforms().get(0); - } catch (@SuppressWarnings("unused") Exception e) { - //no need to do anything - } - } - if (platform == null) { - status = new Status(IStatus.ERROR, Activator.getId(), Messages.No_Platform_available); - } else { - status = install(platform.getNewestVersion(), monitor); - } - - if (!status.isOK()) { - StatusManager stMan = StatusManager.getManager(); - stMan.handle(status, StatusManager.LOG | StatusManager.SHOW | StatusManager.BLOCK); - } - - } - myIsReady = true; - - } - - synchronized static public List getPackageIndices() { - if (packageIndices == null) { - loadJsons(false); - } - return packageIndices; - } - - public static List getPlatforms() { - List platforms = new ArrayList<>(); - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - for (ArduinoPackage pkg : index.getPackages()) { - platforms.addAll(pkg.getPlatforms()); - } - } - return platforms; - } - - public static ArduinoPlatform getPlatform(String vendor, String architecture) { - - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - ArduinoPackage pkg = index.getPackage(vendor); - if (pkg != null) { - ArduinoPlatform platform = pkg.getPlatform(architecture); - if (platform != null) { - return platform; - } - } - } - return null; - } - - /** - * Given a platform.txt file find the platform in the platform manager - * - * @param platformTxt - * @return the found platform otherwise null - */ - public static ArduinoPlatformVersion getPlatform(IPath platformPath) { - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - for (ArduinoPackage pkg : index.getPackages()) { - for (ArduinoPlatform curPlatform : pkg.getPlatforms()) { - if (platformPath - .matchingFirstSegments(curPlatform.getInstallPath()) > (platformPath.segmentCount() - 2)) - - for (ArduinoPlatformVersion curPlatformVersion : curPlatform.getVersions()) { - if (curPlatformVersion.getInstallPath().equals(platformPath)) { - return curPlatformVersion; - } - } - } - } - } - return null; - } - - static public List getInstalledPlatforms() { - List platforms = new ArrayList<>(); - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - for (ArduinoPackage pkg : index.getPackages()) { - - platforms.addAll(pkg.getInstalledPlatforms()); - - } - } - return platforms; - } - - static public boolean areThereInstalledBoards() { - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - for (ArduinoPackage pkg : index.getPackages()) { - if (pkg.isInstalled()) { - return true; - } - } - } - return false; - } - - static public List getPackages() { - List packages = new ArrayList<>(); - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - packages.addAll(index.getPackages()); - } - - return packages; - } - - static public ArduinoPackage getPackage(String JasonName, String packageName) { - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - if (index.getJsonFile().getName().equals(JasonName)) { - return index.getPackage(packageName); - } - } - return null; - } - - static public ArduinoPackage getPackage(String packageName) { - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - ArduinoPackage pkg = index.getPackage(packageName); - if (pkg != null) { - return pkg; - } - } - return null; - } - - /** - * This method removes the json files from disk and removes memory references to - * these files or their content - * - * @param packageUrlsToRemove - */ - public static void removePackageURLs(Set packageUrlsToRemove) { - if (!isReady()) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); - return; - } - // remove the files from memory - Set activeUrls = new HashSet<>(Arrays.asList(getJsonURLList())); - - activeUrls.removeAll(packageUrlsToRemove); - - setJsonURLs(activeUrls.toArray((String[]) null)); - - // remove the files from disk - for (String curJson : packageUrlsToRemove) { - File localFile = getLocalFileName(curJson, true); - if (localFile != null) { - if (localFile.exists()) { - localFile.delete(); - } - } - } - - // reload the indices (this will remove all potential remaining - // references - // existing files do not need to be refreshed as they have been - // refreshed at startup - loadJsons(false); - - } - - /** - * Remove all packages that have a more recent version - */ - public static void onlyKeepLatestPlatforms() { - if (!isReady()) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, BoardsManagerIsBussy, new Exception())); - return; - } - List allPackages = getPackages(); - for (ArduinoPackage curPackage : allPackages) { - curPackage.onlyKeepLatestPlatforms(); - } - } - - public static ArduinoPlatformVersion getPlatform(String vendor, String architecture, VersionNumber refVersion) { - ArduinoPlatform platform = getPlatform(vendor, architecture); - if (platform != null) { - return platform.getVersion(refVersion); - } - return null; - } - - public static ArduinoPackage getPackageByProvider(String packager) { - for (ArduinoPlatformPackageIndex index : getPackageIndices()) { - for (ArduinoPackage pkg : index.getPackages()) { - if (packager.equals(pkg.getID())) { - return pkg; - } - } - } - return null; - } - -} diff --git a/io.sloeber.core/src/io/sloeber/core/api/CodeDescription.java b/io.sloeber.core/src/io/sloeber/core/api/CodeDescription.java index 95269e09d..509944e6f 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/CodeDescription.java +++ b/io.sloeber.core/src/io/sloeber/core/api/CodeDescription.java @@ -1,6 +1,5 @@ package io.sloeber.core.api; -import static io.sloeber.core.api.Common.*; import static io.sloeber.core.api.Const.*; import java.io.File; @@ -25,6 +24,10 @@ import org.eclipse.core.runtime.Status; import org.osgi.framework.Bundle; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IExample; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.autoBuild.api.ICodeProvider; import io.sloeber.core.Activator; import io.sloeber.core.common.InstancePreferences; @@ -48,8 +51,8 @@ public enum CodeTypes { static private final String DEFAULT_SKETCH_BASE = "sketch"; //$NON-NLS-1$ public static final String INO= "ino"; //$NON-NLS-1$ public static final String CPP= "cpp"; //$NON-NLS-1$ - public static final String DEFAULT_SKETCH_INO = DEFAULT_SKETCH_BASE + DOT+INO; - public static final String DEFAULT_SKETCH_CPP = DEFAULT_SKETCH_BASE + DOT+CPP; + public static final String DEFAULT_SKETCH_INO = DEFAULT_SKETCH_BASE + DOT+INO; + public static final String DEFAULT_SKETCH_CPP = DEFAULT_SKETCH_BASE + DOT+CPP; public static final String DEFAULT_SKETCH_H = DEFAULT_SKETCH_BASE + DOT+'h'; // // template Sketch information @@ -328,7 +331,7 @@ public boolean createFiles(IContainer scrContainer, IProgressMonitor monitor) { IPath folderName = myTemPlateFoldername; String files[] = folderName.toFile().list(); if (files == null) { - log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, "No files found in template folder :" + folderName, + Activator.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, "No files found in template folder :" + folderName, null)); } else { for (String file : files) { @@ -350,7 +353,7 @@ public boolean createFiles(IContainer scrContainer, IProgressMonitor monitor) { replacers);) { Helpers.addFileToProject(scrContainer.getFile(IPath.fromOSString(renamedFile)), theFileStream, monitor, false); } catch (IOException e) { - log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, "Failed to add template file :" + sourceFile.toString(), e)); } @@ -366,10 +369,10 @@ public boolean createFiles(IContainer scrContainer, IProgressMonitor monitor) { if (myMakeLinks) { if(scrContainer instanceof IFolder) { IFolder folder=(IFolder)scrContainer; - Helpers.linkDirectory( curPath, folder); + Helpers.LinkFolderToFolder( curPath, folder); } else { - log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, "Can not create links to project root")); } } else { diff --git a/io.sloeber.core/src/io/sloeber/core/api/Common.java b/io.sloeber.core/src/io/sloeber/core/api/Common.java index dc92f61fd..c44fcb2de 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Common.java +++ b/io.sloeber.core/src/io/sloeber/core/api/Common.java @@ -11,6 +11,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; +import java.util.stream.Stream; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; @@ -22,8 +23,6 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; -import org.eclipse.ui.statushandlers.StatusManager; - import io.sloeber.autoBuild.api.AutoBuildCommon; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; import io.sloeber.core.Activator; @@ -32,7 +31,7 @@ public class Common { public final static String sloeberHome = getSloeberHome(); public final static IPath sloeberHomePath = new org.eclipse.core.runtime.Path(sloeberHome); - public final static String sloeberHomePathToString = sloeberHomePath.toString(); + public final static String sloeberHomePathToString = sloeberHomePath.toOSString(); private static String getSloeberHome() { @@ -51,7 +50,7 @@ private static String getSloeberHome() { } catch (URISyntaxException e) { // this should not happen // but it seems a space in the path makes it happen - Common.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, "Eclipse fails to provide its own installation folder :-(. \nThis is known to happen when you have a space ! # or other wierd characters in your eclipse installation path", //$NON-NLS-1$ e)); } @@ -111,42 +110,27 @@ private static String getSloeberHome() { * allowed in Unix filenames, see Note 1 > greater than used to redirect output, * allowed in Unix filenames, see Note 1 . period or dot * + * + * Though { " & + @ } ; are allowed according to the above info they do confuse cmd + * commands so I also remove them + * + * multiple underscores are also concatenated to 1 underscore + * * @param name * the string that needs to be checked * @return a name safe to create files or folders */ public static String makeNameCompileSafe(String name) { - char[] badChars = { ' ', '/', '.', ':', '\\', '(', ')', '*', '?', '%', '|', '<', '>', ',', '-', '#' }; + char[] badChars = { ' ', '/', '.', ':', '\\', '(', ')', '*', '?', '%', '|', '<', '>', ',', '-', '#', '"', '&' ,'+' ,'@', ';' }; String ret = name.trim(); for (char curchar : badChars) { ret = ret.replace(curchar, '_'); } + ret = ret.replace("__", "_"); //$NON-NLS-1$ //$NON-NLS-2$ return ret; } - /** - * Logs the status information if status is OK then nothing happens - * - * @param status - * the status information to log - */ - public static void log(IStatus status) { - switch (status.getSeverity()) { - case IStatus.OK: { - break; - } - case IStatus.ERROR: { - int style = StatusManager.LOG | StatusManager.SHOW | StatusManager.BLOCK; - StatusManager stMan = StatusManager.getManager(); - stMan.handle(status, style); - break; - } - case SLOEBER_STATUS_DEBUG: - // break;//remove break to add debugging - default: - Activator.getDefault().getLog().log(status); - } - } + /** * @@ -197,8 +181,8 @@ static public String getBuildEnvironmentVariable(ISloeberConfiguration sloeberCo static public String getBuildEnvironmentVariable(ISloeberConfiguration sloeberConf, String envName, String defaultvalue, boolean expanded) { if (sloeberConf != null) { - IAutoBuildConfigurationDescription autoDesc= sloeberConf.getAutoBuildDesc(); - return AutoBuildCommon.getVariableValue(envName, defaultvalue, expanded, autoDesc); + IAutoBuildConfigurationDescription autoDesc= sloeberConf.getAutoBuildDesc(); + return AutoBuildCommon.getVariableValue(envName, defaultvalue, expanded, autoDesc); // IEnvironmentVariableManager envManager = CCorePlugin.getDefault().getBuildEnvironmentManager(); // try { // ICConfigurationDescription configurationDescription = sloeberConf.getAutoBuildDesc() @@ -233,9 +217,9 @@ public static IPath getWorkspaceRoot() { * @return modified string or the original */ public static String makePathVersionString(File file) { - if(sloeberHomePath.isPrefixOf(IPath.fromFile(file))) { - return SLOEBER_HOME_VAR+SLACH+IPath.fromFile(file) .makeRelativeTo(sloeberHomePath).toString(); - } + if(sloeberHomePath.isPrefixOf(IPath.fromFile(file))) { + return SLOEBER_HOME_VAR+SLACH+IPath.fromFile(file).makeRelativeTo(sloeberHomePath).toString(); + } return file.toString(); } @@ -249,9 +233,9 @@ public static File resolvePathEnvironmentString(File file) { String retString = file.getPath(); if (retString.startsWith(SLOEBER_HOME_VAR)) { - retString=retString.replace(SLOEBER_HOME_VAR, EMPTY_STRING); - return sloeberHomePath.append(retString).toFile(); - //.replace(SLOEBER_HOME_VAR, sloeberHomePathToString); + retString=retString.replace(SLOEBER_HOME_VAR, EMPTY_STRING); + return sloeberHomePath.append(retString).toFile(); + //.replace(SLOEBER_HOME_VAR, sloeberHomePathToString); } return new File(retString); } @@ -272,7 +256,9 @@ public static void deleteDirectory(org.eclipse.core.runtime.IPath directory) thr } public static void deleteDirectory(Path directory) throws IOException { - Files.walk(directory).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + try( Stream stream = Files.walk(directory)){ + stream.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } } /** diff --git a/io.sloeber.core/src/io/sloeber/core/api/CompileDescription.java b/io.sloeber.core/src/io/sloeber/core/api/CompileDescription.java index d4d1cb661..449d36050 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/CompileDescription.java +++ b/io.sloeber.core/src/io/sloeber/core/api/CompileDescription.java @@ -15,484 +15,460 @@ public class CompileDescription { - public enum DebugLevels { + public enum DebugLevels { OPTIMIZED_FOR_DEBUG, OPTIMIZED_FOR_RELEASE, CUSTOM; - @Override + @Override public String toString() { - switch (this) { - case OPTIMIZED_FOR_DEBUG: - return Messages.CompileDescription_OptimizedForDebug; - case OPTIMIZED_FOR_RELEASE: - return Messages.CompileDescription_OptimizedForRelease; - case CUSTOM: - return Messages.CompileDescription_CustomDebugLevel; + switch (this) { + case OPTIMIZED_FOR_DEBUG: + return Messages.CompileDescription_OptimizedForDebug; + case OPTIMIZED_FOR_RELEASE: + return Messages.CompileDescription_OptimizedForRelease; + case CUSTOM: + return Messages.CompileDescription_CustomDebugLevel; default: break; - } + } return super.toString(); } - private String myCustomDebugLevel = EMPTY; - /** - * Set the custom command but only if the warning level is CUSTOM - * + private String myCustomDebugLevel = EMPTY; + + /** + * Set the custom command but only if the warning level is CUSTOM + * * @param customCommand * the command that needs to be used - */ - public void setCustomDebugLevel(String customDebugLevel) { - if (this == CUSTOM) { - myCustomDebugLevel = customDebugLevel; - } - } - - public void setCustomDebugLevel(String customDebugLevel, boolean force) { - if (force) { - myCustomDebugLevel = customDebugLevel; - } else { - setCustomDebugLevel(customDebugLevel); - } - - } - - public String getCustomDebugLevel() { - return myCustomDebugLevel; - } - - /** - * Get the string that should be put in the environment variable that places the - * warning part in the command string This is a non expanded string for Arduino - * IDE supported options This is what the user typed in the GUI in the CUSTOM - * case - * - * @return - */ - public String getEnvValue() { - switch (this) { - case OPTIMIZED_FOR_DEBUG: - return "${compiler.optimization_flags.debug}"; //$NON-NLS-1$ - case OPTIMIZED_FOR_RELEASE: - return "${compiler.optimization_flags.release}"; //$NON-NLS-1$ - case CUSTOM: - return myCustomDebugLevel; + */ + public void setCustomDebugLevel(String customDebugLevel) { + if (this == CUSTOM) { + myCustomDebugLevel = customDebugLevel; + } + } + + public void setCustomDebugLevel(String customDebugLevel, boolean force) { + if (force) { + myCustomDebugLevel = customDebugLevel; + } else { + setCustomDebugLevel(customDebugLevel); + } + + } + + public String getCustomDebugLevel() { + return myCustomDebugLevel; + } + + /** + * Get the string that should be put in the environment variable that places the + * warning part in the command string This is a non expanded string for Arduino + * IDE supported options This is what the user typed in the GUI in the CUSTOM + * case + * + * @return + */ + public String getEnvValue() { + switch (this) { + case OPTIMIZED_FOR_DEBUG: + return "${compiler.optimization_flags.debug}"; //$NON-NLS-1$ + case OPTIMIZED_FOR_RELEASE: + return "${compiler.optimization_flags.release}"; //$NON-NLS-1$ + case CUSTOM: + return myCustomDebugLevel; default: return "${compiler.optimization_flags.release}"; //$NON-NLS-1$ - } - - } + } - } + } + } - public enum WarningLevels { + public enum WarningLevels { @SuppressWarnings("hiding") ALL, MORE, DEFAULT, NONE, CUSTOM; - @Override + @Override public String toString() { - switch (this) { - case MORE: - return Messages.CompileDescription_WarningsMore; - case ALL: - return Messages.CompileDescription_WarningsAll; - case CUSTOM: - return Messages.CompileDescription_WarningsCustom; - case DEFAULT: - return Messages.CompileDescription_WarningsDefault; - case NONE: - return Messages.CompileDescription_WarningsNone; + switch (this) { + case MORE: + return Messages.CompileDescription_WarningsMore; + case ALL: + return Messages.CompileDescription_WarningsAll; + case CUSTOM: + return Messages.CompileDescription_WarningsCustom; + case DEFAULT: + return Messages.CompileDescription_WarningsDefault; + case NONE: + return Messages.CompileDescription_WarningsNone; default: break; - } + } return super.toString(); } private String myCustomWarningLevel = EMPTY; - /** - * Set the custom command but only if the warning level is CUSTOM - * + /** + * Set the custom command but only if the warning level is CUSTOM + * * @param customCommand * the command that needs to be used - */ - public void setCustomWarningLevel(String customWarningLevel) { - if (this == CUSTOM) { - myCustomWarningLevel = customWarningLevel; - } - } - - public void setCustomWarningLevel(String customWarningLevel, boolean force) { - if (force) { - myCustomWarningLevel = customWarningLevel; - } else { - setCustomWarningLevel(customWarningLevel); - } - - } - - public String getCustomWarningLevel() { - return myCustomWarningLevel; - } - - /** - * Get the string that should be put in the environment variable that places the - * warning part in the command string This is a non expanded string for Arduino - * IDE supported options This is what the user typed in the GUI in the CUSTOM - * case - * - * @return - */ - public String getEnvValue() { - switch (this) { - case MORE: - return "${compiler.warning_flags.more}"; //$NON-NLS-1$ - case ALL: - return "${compiler.warning_flags.all}"; //$NON-NLS-1$ - case CUSTOM: - return myCustomWarningLevel; - case DEFAULT: - return "${compiler.warning_flags.default}";//$NON-NLS-1$ - case NONE: - return "${compiler.warning_flags.none}"; //$NON-NLS-1$ + */ + public void setCustomWarningLevel(String customWarningLevel) { + if (this == CUSTOM) { + myCustomWarningLevel = customWarningLevel; + } + } + + public void setCustomWarningLevel(String customWarningLevel, boolean force) { + if (force) { + myCustomWarningLevel = customWarningLevel; + } else { + setCustomWarningLevel(customWarningLevel); + } + + } + + public String getCustomWarningLevel() { + return myCustomWarningLevel; + } + + /** + * Get the string that should be put in the environment variable that places the + * warning part in the command string This is a non expanded string for Arduino + * IDE supported options This is what the user typed in the GUI in the CUSTOM + * case + * + * @return + */ + public String getEnvValue() { + switch (this) { + case MORE: + return "${compiler.warning_flags.more}"; //$NON-NLS-1$ + case ALL: + return "${compiler.warning_flags.all}"; //$NON-NLS-1$ + case CUSTOM: + return myCustomWarningLevel; + case DEFAULT: + return "${compiler.warning_flags.default}";//$NON-NLS-1$ + case NONE: + return "${compiler.warning_flags.none}"; //$NON-NLS-1$ default: break; - } - return "${compiler.warning_flags.all}"; //$NON-NLS-1$ - } + } + return "${compiler.warning_flags.all}"; //$NON-NLS-1$ + } + + } - } + public enum SizeCommands { - public enum SizeCommands { + ARDUINO_WAY, AVR_ALTERNATIVE, RAW_RESULT, CUSTOM; - ARDUINO_WAY, AVR_ALTERNATIVE, RAW_RESULT, CUSTOM; - @Override + + + + @Override public String toString() { - switch (this) { - case ARDUINO_WAY: - return Messages.CompileDescription_SizeArduinoWay; - case AVR_ALTERNATIVE: - return Messages.CompileDescription_SizeAVRAlternative; - case RAW_RESULT: - return Messages.CompileDescription_SizeRawResult; - case CUSTOM: - return Messages.CompileDescription_SizeCustom; + return toString (this); + } + + public static String toString(SizeCommands value) { + + switch (value) { + case ARDUINO_WAY: + return "Arduino Way"; //$NON-NLS-1$ + case AVR_ALTERNATIVE: + return "AVR Alternative"; //$NON-NLS-1$ + case RAW_RESULT: + return "Raw result"; //$NON-NLS-1$ + case CUSTOM: + return "Custom"; //$NON-NLS-1$ default: break; - } - return super.toString(); + } + try { + return value.toString(); + } catch (@SuppressWarnings("unused") Exception e) { + // ignore exception + } + return "Arduino Way"; //$NON-NLS-1$ } + public static SizeCommands valueOf(String name, SizeCommands defaultValue) { + if (name.equals(toString(ARDUINO_WAY))) { + return ARDUINO_WAY; + } + if (name.equals(toString(AVR_ALTERNATIVE))) { + return AVR_ALTERNATIVE; + } + if (name.equals(toString(RAW_RESULT))) { + return RAW_RESULT; + } + if (name.equals(toString(CUSTOM))) { + return CUSTOM; + } + return defaultValue; + } + + + private String myCustomSizeCommand = EMPTY; - /** - * Set the custom command but only if the warning level is CUSTOM - * + /** + * Set the custom command but only if the warning level is CUSTOM + * * @param customCommand * the command that needs to be used - */ - public void setCustomSizeCommand(String customWarningLevel) { - if (this == CUSTOM) { - myCustomSizeCommand = customWarningLevel; - } - } - - public void setCustomSizeCommand(String customWarningLevel, boolean force) { - if (force) { - myCustomSizeCommand = customWarningLevel; - } else { - setCustomSizeCommand(customWarningLevel); - } - - } - - public String getCustomSizeCommand() { - return myCustomSizeCommand; - } - - /** - * Get the string that should be put in the environment variable that places the - * warning part in the command string This is a non expanded string for Arduino - * IDE supported options This is what the user typed in the GUI in the CUSTOM - * case - * - * @return - */ - public String getEnvValue() { - switch (this) { - case ARDUINO_WAY: - if(isWindows) { - return "wsl -- ${sloeber.size_command.awk}"; //$NON-NLS-1$ - } - return "${sloeber.size_command.awk}"; //$NON-NLS-1$ - case AVR_ALTERNATIVE: - return "${sloeber.size_command.avr}"; //$NON-NLS-1$ - case RAW_RESULT: - return "${recipe.size.pattern}"; //$NON-NLS-1$ - case CUSTOM: - return myCustomSizeCommand; + */ + public void setCustomSizeCommand(String customWarningLevel) { + if (this == CUSTOM) { + myCustomSizeCommand = customWarningLevel; + } + } + + public void setCustomSizeCommand(String customWarningLevel, boolean force) { + if (force) { + myCustomSizeCommand = customWarningLevel; + } else { + setCustomSizeCommand(customWarningLevel); + } + + } + + public String getCustomSizeCommand() { + return myCustomSizeCommand; + } + + /** + * Get the string that should be put in the environment variable that places the + * warning part in the command string This is a non expanded string for Arduino + * IDE supported options This is what the user typed in the GUI in the CUSTOM + * case + * + * @return + */ + public String getEnvValue() { + switch (this) { + case ARDUINO_WAY: + return Common.makeEnvironmentVar(ENV_KEY_BUILD_PATH) + SLACH + ARDUINO_SIZE; + case AVR_ALTERNATIVE: + return "${sloeber.size_command.avr}"; //$NON-NLS-1$ + case RAW_RESULT: + return "${recipe.size.pattern}"; //$NON-NLS-1$ + case CUSTOM: + return myCustomSizeCommand; default: break; - } - return "${recipe.size.pattern}"; //$NON-NLS-1$ - } - } - - private WarningLevels myWarningLevel = WarningLevels.ALL; - private SizeCommands mySizeCommand = SizeCommands.RAW_RESULT; - private DebugLevels myDebugLevel = DebugLevels.OPTIMIZED_FOR_RELEASE; - - private boolean myEnableParallelBuild = false; - private String my_CPP_CompileOptions = new String(); - private String my_C_CompileOptions = new String(); - private String my_C_andCPP_CompileOptions = new String(); - private String my_Assembly_CompileOptions = new String(); - private String my_Archive_CompileOptions = new String(); - private String my_Link_CompileOptions = new String(); - private String my_All_CompileOptions = new String(); - - private static final String ENV_KEY_WARNING_LEVEL = "compiler.warning_flags"; //$NON-NLS-1$ - private static final String ENV_KEY_DEBUG_LEVEL = "compiler.optimization_flags"; //$NON-NLS-1$ - - - private static final String SLOEBER_ADDITIONAL_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.compile"; //$NON-NLS-1$ - private static final String SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.c.compile"; //$NON-NLS-1$ - private static final String SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.cpp.compile"; //$NON-NLS-1$ - private static final String SLOEBER_WARNING_LEVEL = ENV_KEY_SLOEBER_START + "warning_level"; //$NON-NLS-1$ - private static final String SLOEBER_SIZE_TYPE = ENV_KEY_SLOEBER_START + "size.type"; //$NON-NLS-1$ - private static final String SLOEBER_SIZE_CUSTOM = ENV_KEY_SLOEBER_START + "size.custom"; //$NON-NLS-1$ - - private static final String SLOEBER_WARNING_LEVEL_CUSTOM = SLOEBER_WARNING_LEVEL + DOT + "custom"; //$NON-NLS-1$ - private static final String SLOEBER_DEBUG_LEVEL = ENV_KEY_SLOEBER_START + "debug_level"; //$NON-NLS-1$ - private static final String SLOEBER_DEBUG_LEVEL_CUSTOM = SLOEBER_DEBUG_LEVEL + DOT + "custom"; //$NON-NLS-1$ - - // private static final String SLOEBER_SIZE_COMMAND = ENV_KEY_SLOEBER_START + - // "alt_size_command"; //$NON-NLS-1$ - private static final String SLOEBER_SIZE_SWITCH = ENV_KEY_SLOEBER_START + "size.switch"; //$NON-NLS-1$ - private static final String SLOEBER_ASSEMBLY_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.assembly"; //$NON-NLS-1$ - private static final String SLOEBER_ARCHIVE_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.archive"; //$NON-NLS-1$ - private static final String SLOEBER_LINK_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.link"; //$NON-NLS-1$ - private static final String SLOEBER_ALL_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.all"; //$NON-NLS-1$ - - public WarningLevels getWarningLevel() { - return myWarningLevel; - } - - public void setWarningLevel(WarningLevels warningLevel) { - myWarningLevel = warningLevel; - } - - public DebugLevels getDebugLevel() { - return myDebugLevel; - } - - public void setDebugLevel(DebugLevels debugLevel) { - myDebugLevel = debugLevel; - } - - - public boolean isParallelBuildEnabled() { - return myEnableParallelBuild; - } - - public void setEnableParallelBuild(boolean parrallelBuild) { - this.myEnableParallelBuild = parrallelBuild; - } - - public void setSizeCommand(SizeCommands sizeCommand) { - this.mySizeCommand = sizeCommand; - } - - public SizeCommands getSizeCommand() { - return mySizeCommand; - } - - public String get_CPP_CompileOptions() { - return this.my_CPP_CompileOptions; - } - - public void set_CPP_CompileOptions(String new_CPP_CompileOptions) { - this.my_CPP_CompileOptions = new_CPP_CompileOptions; - } - - public String get_C_CompileOptions() { - return this.my_C_CompileOptions; - } - - public void set_C_CompileOptions(String new_C_CompileOptions) { - this.my_C_CompileOptions = new_C_CompileOptions; - } - - public String get_C_andCPP_CompileOptions() { - return this.my_C_andCPP_CompileOptions; - } - - public void set_C_andCPP_CompileOptions(String new_C_andCPP_CompileOptions) { - this.my_C_andCPP_CompileOptions = new_C_andCPP_CompileOptions; - } - - public String get_Assembly_CompileOptions() { - return this.my_Assembly_CompileOptions; - } - - public void set_Assembly_CompileOptions(String my_Assembly_CompileOptions) { - this.my_Assembly_CompileOptions = my_Assembly_CompileOptions; - } - - public String get_Archive_CompileOptions() { - return this.my_Archive_CompileOptions; - } - - public void set_Archive_CompileOptions(String my_Archive_CompileOptions) { - this.my_Archive_CompileOptions = my_Archive_CompileOptions; - } - - public String get_Link_CompileOptions() { - return this.my_Link_CompileOptions; - } - - public void set_Link_CompileOptions(String my_Link_CompileOptions) { - this.my_Link_CompileOptions = my_Link_CompileOptions; - } - - public String get_All_CompileOptions() { - return this.my_All_CompileOptions; - } - - public void set_All_CompileOptions(String my_All_CompileOptions) { - this.my_All_CompileOptions = my_All_CompileOptions; - } - - /** - * save the compilation options in this configuration description. - * + } + return "${recipe.size.pattern}"; //$NON-NLS-1$ + } + } + + private WarningLevels myWarningLevel = WarningLevels.ALL; + private SizeCommands mySizeCommand = SizeCommands.RAW_RESULT; + private DebugLevels myDebugLevel = DebugLevels.OPTIMIZED_FOR_RELEASE; + + private boolean myEnableParallelBuild = false; + private String my_CPP_CompileOptions = new String(); + private String my_C_CompileOptions = new String(); + private String my_C_andCPP_CompileOptions = new String(); + private String my_Assembly_CompileOptions = new String(); + private String my_Archive_CompileOptions = new String(); + private String my_Link_CompileOptions = new String(); + private String my_All_CompileOptions = new String(); + + private static final String ENV_KEY_WARNING_LEVEL = "compiler.warning_flags"; //$NON-NLS-1$ + private static final String ENV_KEY_DEBUG_LEVEL = "compiler.optimization_flags"; //$NON-NLS-1$ + + private static final String SLOEBER_ADDITIONAL_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.compile"; //$NON-NLS-1$ + private static final String SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.c.compile"; //$NON-NLS-1$ + private static final String SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.cpp.compile"; //$NON-NLS-1$ + private static final String SLOEBER_WARNING_LEVEL = ENV_KEY_SLOEBER_START + "warning_level"; //$NON-NLS-1$ + private static final String SLOEBER_SIZE_TYPE = ENV_KEY_SLOEBER_START + "size.type"; //$NON-NLS-1$ + private static final String SLOEBER_SIZE_CUSTOM = ENV_KEY_SLOEBER_START + "size.custom"; //$NON-NLS-1$ + + private static final String SLOEBER_WARNING_LEVEL_CUSTOM = SLOEBER_WARNING_LEVEL + DOT + "custom"; //$NON-NLS-1$ + private static final String SLOEBER_DEBUG_LEVEL = ENV_KEY_SLOEBER_START + "debug_level"; //$NON-NLS-1$ + private static final String SLOEBER_DEBUG_LEVEL_CUSTOM = SLOEBER_DEBUG_LEVEL + DOT + "custom"; //$NON-NLS-1$ + + // private static final String SLOEBER_SIZE_COMMAND = ENV_KEY_SLOEBER_START + + // "alt_size_command"; //$NON-NLS-1$ + private static final String SLOEBER_SIZE_SWITCH = ENV_KEY_SLOEBER_START + "size.switch"; //$NON-NLS-1$ + private static final String SLOEBER_ASSEMBLY_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.assembly"; //$NON-NLS-1$ + private static final String SLOEBER_ARCHIVE_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.archive"; //$NON-NLS-1$ + private static final String SLOEBER_LINK_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.link"; //$NON-NLS-1$ + private static final String SLOEBER_ALL_COMPILE_OPTIONS = ENV_KEY_SLOEBER_START + "extra.all"; //$NON-NLS-1$ + + public WarningLevels getWarningLevel() { + return myWarningLevel; + } + + public void setWarningLevel(WarningLevels warningLevel) { + myWarningLevel = warningLevel; + } + + public DebugLevels getDebugLevel() { + return myDebugLevel; + } + + public void setDebugLevel(DebugLevels debugLevel) { + myDebugLevel = debugLevel; + } + + public boolean isParallelBuildEnabled() { + return myEnableParallelBuild; + } + + public void setEnableParallelBuild(boolean parrallelBuild) { + this.myEnableParallelBuild = parrallelBuild; + } + + public void setSizeCommand(SizeCommands sizeCommand) { + this.mySizeCommand = sizeCommand; + } + + public SizeCommands getSizeCommand() { + return mySizeCommand; + } + + public String get_CPP_CompileOptions() { + return this.my_CPP_CompileOptions; + } + + public void set_CPP_CompileOptions(String new_CPP_CompileOptions) { + this.my_CPP_CompileOptions = new_CPP_CompileOptions; + } + + public String get_C_CompileOptions() { + return this.my_C_CompileOptions; + } + + public void set_C_CompileOptions(String new_C_CompileOptions) { + this.my_C_CompileOptions = new_C_CompileOptions; + } + + public String get_C_andCPP_CompileOptions() { + return this.my_C_andCPP_CompileOptions; + } + + public void set_C_andCPP_CompileOptions(String new_C_andCPP_CompileOptions) { + this.my_C_andCPP_CompileOptions = new_C_andCPP_CompileOptions; + } + + public String get_Assembly_CompileOptions() { + return this.my_Assembly_CompileOptions; + } + + public void set_Assembly_CompileOptions(String my_Assembly_CompileOptions) { + this.my_Assembly_CompileOptions = my_Assembly_CompileOptions; + } + + public String get_Archive_CompileOptions() { + return this.my_Archive_CompileOptions; + } + + public void set_Archive_CompileOptions(String my_Archive_CompileOptions) { + this.my_Archive_CompileOptions = my_Archive_CompileOptions; + } + + public String get_Link_CompileOptions() { + return this.my_Link_CompileOptions; + } + + public void set_Link_CompileOptions(String my_Link_CompileOptions) { + this.my_Link_CompileOptions = my_Link_CompileOptions; + } + + public String get_All_CompileOptions() { + return this.my_All_CompileOptions; + } + + public void set_All_CompileOptions(String my_All_CompileOptions) { + this.my_All_CompileOptions = my_All_CompileOptions; + } + + /** + * save the compilation options in this configuration description. + * * @param configuration * must be a valid configuration description - */ - public Map getEnvVars() { - Map ret = new HashMap<>(); - ret.put(SLOEBER_ADDITIONAL_COMPILE_OPTIONS, this.my_C_andCPP_CompileOptions); - ret.put(SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS, this.my_CPP_CompileOptions); - ret.put(SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS, this.my_C_CompileOptions); - ret.put(SLOEBER_ASSEMBLY_COMPILE_OPTIONS, this.my_Assembly_CompileOptions); - ret.put(SLOEBER_ARCHIVE_COMPILE_OPTIONS, this.my_Archive_CompileOptions); - ret.put(SLOEBER_LINK_COMPILE_OPTIONS, this.my_Link_CompileOptions); - ret.put(SLOEBER_ALL_COMPILE_OPTIONS, this.my_All_CompileOptions); - ret.put(ENV_KEY_WARNING_LEVEL, myWarningLevel.getEnvValue()); - ret.put(ENV_KEY_DEBUG_LEVEL, myDebugLevel.getEnvValue()); - ret.put(SLOEBER_SIZE_SWITCH, mySizeCommand.getEnvValue()); - - return ret; - } - - /** - * Given the compile options you currently have and the ones provided Is a - * rebuild needed if you switch from one to another - * - * @param otherOptions - * @return true if a rebuild is needed otherwise false - */ - - public boolean needsRebuild(CompileDescription otherOptions) { - // ignore myWarningLevel (as changing the warning level does not hurt - // ignore myAlternativeSizeCommand (as this is run anyways) - if (otherOptions == null) { - return true; - } - //When the debuglevel is changed it is best to do a full rebuild - if(!myDebugLevel.getEnvValue().equals(otherOptions.myDebugLevel.getEnvValue())) { - return true; - } - return !equalCompileOptions(otherOptions); - } - - /** - * get the environment variables that need to be stored in the configuration - * files configuration files are files needed to setup the sloeber environment - * for instance when opening a project or after import of a project in the - * workspace - * - * @return the minimum list of environment variables to recreate the project - */ - public Map getEnvVarsConfig() { - Map ret = new HashMap<>(); - ret.put(SLOEBER_ADDITIONAL_COMPILE_OPTIONS, this.my_C_andCPP_CompileOptions); - ret.put(SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS, this.my_CPP_CompileOptions); - ret.put(SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS, this.my_C_CompileOptions); - ret.put(SLOEBER_ASSEMBLY_COMPILE_OPTIONS, this.my_Assembly_CompileOptions); - ret.put(SLOEBER_ARCHIVE_COMPILE_OPTIONS, this.my_Archive_CompileOptions); - ret.put(SLOEBER_LINK_COMPILE_OPTIONS, this.my_Link_CompileOptions); - ret.put(SLOEBER_ALL_COMPILE_OPTIONS, this.my_All_CompileOptions); - ret.put(SLOEBER_WARNING_LEVEL, myWarningLevel.name()); - ret.put(SLOEBER_WARNING_LEVEL_CUSTOM, myWarningLevel.myCustomWarningLevel); - ret.put(SLOEBER_DEBUG_LEVEL, myDebugLevel.name()); - ret.put(SLOEBER_DEBUG_LEVEL_CUSTOM, myDebugLevel.myCustomDebugLevel); - ret.put(SLOEBER_SIZE_TYPE, mySizeCommand.name()); - ret.put(SLOEBER_SIZE_CUSTOM, mySizeCommand.myCustomSizeCommand); - - return ret; - } - - /** - * Recreate the compile options based on the configuration environment variables - * given - * - * @param envVars - */ - public CompileDescription(Map envVars) { - String warningLevel = WarningLevels.ALL.name(); - String customWarningLevel = EMPTY; - String debugLevel = DebugLevels.OPTIMIZED_FOR_RELEASE.name(); - String customDebugLevel = EMPTY; - String sizeCommand = SizeCommands.RAW_RESULT.toString(); - String customSizeCommand = EMPTY; - for (Entry curEnvVar : envVars.entrySet()) { - String key = curEnvVar.getKey(); - String value = curEnvVar.getValue(); - switch (key) { - case SLOEBER_ADDITIONAL_COMPILE_OPTIONS: - my_C_andCPP_CompileOptions = value; - break; - case SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS: - my_CPP_CompileOptions = value; - break; - case SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS: - my_C_CompileOptions = value; - break; - case SLOEBER_ASSEMBLY_COMPILE_OPTIONS: - my_Assembly_CompileOptions = value; - break; - case SLOEBER_ARCHIVE_COMPILE_OPTIONS: - my_Archive_CompileOptions = value; - break; - case SLOEBER_LINK_COMPILE_OPTIONS: - my_Link_CompileOptions = value; - break; - case SLOEBER_ALL_COMPILE_OPTIONS: - my_All_CompileOptions = value; - break; - case SLOEBER_WARNING_LEVEL: - warningLevel = value; - break; - case SLOEBER_WARNING_LEVEL_CUSTOM: - customWarningLevel = value; - break; - case SLOEBER_DEBUG_LEVEL: - debugLevel = value; - break; - case SLOEBER_DEBUG_LEVEL_CUSTOM: - customDebugLevel = value; - break; - case SLOEBER_SIZE_TYPE: - sizeCommand = value; - break; - case SLOEBER_SIZE_CUSTOM: - customSizeCommand = value; - break; - default: - break; - } + */ + public Map getEnvVars() { + Map ret = new HashMap<>(); + ret.put(SLOEBER_ADDITIONAL_COMPILE_OPTIONS, this.my_C_andCPP_CompileOptions); + ret.put(SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS, this.my_CPP_CompileOptions); + ret.put(SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS, this.my_C_CompileOptions); + ret.put(SLOEBER_ASSEMBLY_COMPILE_OPTIONS, this.my_Assembly_CompileOptions); + ret.put(SLOEBER_ARCHIVE_COMPILE_OPTIONS, this.my_Archive_CompileOptions); + ret.put(SLOEBER_LINK_COMPILE_OPTIONS, this.my_Link_CompileOptions); + ret.put(SLOEBER_ALL_COMPILE_OPTIONS, this.my_All_CompileOptions); + ret.put(ENV_KEY_WARNING_LEVEL, myWarningLevel.getEnvValue()); + ret.put(ENV_KEY_DEBUG_LEVEL, myDebugLevel.getEnvValue()); + ret.put(SLOEBER_SIZE_SWITCH, mySizeCommand.getEnvValue()); + + return ret; + } + + /** + * Given the compile options you currently have and the ones provided Is a + * rebuild needed if you switch from one to another + * + * @param otherOptions + * @return true if a rebuild is needed otherwise false + */ + + public boolean needsRebuild(CompileDescription otherOptions) { + // ignore myWarningLevel (as changing the warning level does not hurt + // ignore myAlternativeSizeCommand (as this is run anyways) + if (otherOptions == null) { + return true; + } + // When the debuglevel is changed it is best to do a full rebuild + if (!myDebugLevel.getEnvValue().equals(otherOptions.myDebugLevel.getEnvValue())) { + return true; + } + return !equalCompileOptions(otherOptions); + } + + /** + * get the environment variables that need to be stored in the configuration + * files configuration files are files needed to setup the sloeber environment + * for instance when opening a project or after import of a project in the + * workspace + * + * @return the minimum list of environment variables to recreate the project + */ + public void serialize(KeyValueTree keyValueTree) { + Map ret = getEnvVarsVersion(); + for (Entry curvalue : ret.entrySet()) { + keyValueTree.addChild(curvalue.getKey(), curvalue.getValue()); } + } + + /** + * Recreate the compile options based on the configuration environment variables + * given + * + * @param envVars + */ + public CompileDescription(KeyValueTree keyValues) { + my_C_andCPP_CompileOptions = keyValues.getValue(SLOEBER_ADDITIONAL_COMPILE_OPTIONS); + my_CPP_CompileOptions = keyValues.getValue(SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS); + my_C_CompileOptions = keyValues.getValue(SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS); + my_Assembly_CompileOptions = keyValues.getValue(SLOEBER_ASSEMBLY_COMPILE_OPTIONS); + my_Archive_CompileOptions = keyValues.getValue(SLOEBER_ARCHIVE_COMPILE_OPTIONS); + my_Link_CompileOptions = keyValues.getValue(SLOEBER_LINK_COMPILE_OPTIONS); + my_All_CompileOptions = keyValues.getValue(SLOEBER_ALL_COMPILE_OPTIONS); + String warningLevel = keyValues.getValue(SLOEBER_WARNING_LEVEL); + String customWarningLevel = keyValues.getValue(SLOEBER_WARNING_LEVEL_CUSTOM); + String debugLevel = keyValues.getValue(SLOEBER_DEBUG_LEVEL); + String customDebugLevel = keyValues.getValue(SLOEBER_DEBUG_LEVEL_CUSTOM); + String sizeCommand = keyValues.getValue(SLOEBER_SIZE_TYPE); + String customSizeCommand = keyValues.getValue(SLOEBER_SIZE_CUSTOM); + try { myWarningLevel = WarningLevels.valueOf(warningLevel); myWarningLevel.setCustomWarningLevel(customWarningLevel, true); @@ -503,96 +479,111 @@ public CompileDescription(Map envVars) { mySizeCommand = SizeCommands.valueOf(sizeCommand); mySizeCommand.setCustomSizeCommand(customSizeCommand, true); } catch (Exception e) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), "Deserialisation error", e)); //$NON-NLS-1$ + Activator.log(new Status(IStatus.WARNING, Activator.getId(), "Deserialisation error", e)); //$NON-NLS-1$ } - } - - public Map getEnvVarsVersion() { - return getEnvVarsConfig(); - } - - public CompileDescription(TxtFile configFile, String prefix) { - - KeyValueTree tree = configFile.getData(); - KeyValueTree section = tree.getChild(prefix); - - my_C_andCPP_CompileOptions = section.getValue(SLOEBER_ADDITIONAL_COMPILE_OPTIONS); - my_CPP_CompileOptions = section.getValue(SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS); - my_C_CompileOptions = section.getValue(SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS); - my_Assembly_CompileOptions = section.getValue(SLOEBER_ASSEMBLY_COMPILE_OPTIONS); - my_Archive_CompileOptions = section.getValue(SLOEBER_ARCHIVE_COMPILE_OPTIONS); - my_Link_CompileOptions = section.getValue(SLOEBER_LINK_COMPILE_OPTIONS); - my_All_CompileOptions = section.getValue(SLOEBER_ALL_COMPILE_OPTIONS); - - try { - myWarningLevel = WarningLevels.valueOf(section.getValue(SLOEBER_WARNING_LEVEL)); - myWarningLevel.setCustomWarningLevel(section.getValue(SLOEBER_WARNING_LEVEL_CUSTOM)); - } catch (@SuppressWarnings("unused") Exception e) { - // ignore as this will be default - } - try { - myDebugLevel = DebugLevels.valueOf(section.getValue(SLOEBER_DEBUG_LEVEL)); - myDebugLevel.setCustomDebugLevel(section.getValue(SLOEBER_DEBUG_LEVEL_CUSTOM)); - } catch (@SuppressWarnings("unused") Exception e) { - // ignore as this will be default - } - try { - mySizeCommand = SizeCommands.valueOf(section.getValue(SLOEBER_SIZE_TYPE)); - mySizeCommand.setCustomSizeCommand(section.getValue(SLOEBER_SIZE_CUSTOM)); - } catch (@SuppressWarnings("unused") Exception e) { - // ignore as this will be default - } - - } - - public CompileDescription() { - // no need to do anything - // this will create default compile options - // note that the Parallel build option is implemented at the ui level - // therefore this is not set here but in the ui before project creation - } - - public CompileDescription(CompileDescription compileDescription) { - myWarningLevel = compileDescription.myWarningLevel; - myDebugLevel = compileDescription.myDebugLevel; - mySizeCommand = compileDescription.mySizeCommand; - myEnableParallelBuild = compileDescription.myEnableParallelBuild; - my_CPP_CompileOptions = compileDescription.my_CPP_CompileOptions; - my_C_CompileOptions = compileDescription.my_C_CompileOptions; - my_C_andCPP_CompileOptions = compileDescription.my_C_andCPP_CompileOptions; - my_Assembly_CompileOptions = compileDescription.my_Assembly_CompileOptions; - my_Archive_CompileOptions = compileDescription.my_Archive_CompileOptions; - my_Link_CompileOptions = compileDescription.my_Link_CompileOptions; - my_All_CompileOptions = compileDescription.my_All_CompileOptions; - } - - /** - * Compares 2 compile descriptors - * - * @param other - * @return true if the 2 are equal else false - */ - public boolean equals(CompileDescription other) { - return myWarningLevel.getEnvValue().equals(other.myWarningLevel.getEnvValue()) - && myDebugLevel.getEnvValue().equals(other.myDebugLevel.getEnvValue()) + } + + public Map getEnvVarsVersion() { + Map ret = new HashMap<>(); + ret.put(SLOEBER_ADDITIONAL_COMPILE_OPTIONS, this.my_C_andCPP_CompileOptions); + ret.put(SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS, this.my_CPP_CompileOptions); + ret.put(SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS, this.my_C_CompileOptions); + ret.put(SLOEBER_ASSEMBLY_COMPILE_OPTIONS, this.my_Assembly_CompileOptions); + ret.put(SLOEBER_ARCHIVE_COMPILE_OPTIONS, this.my_Archive_CompileOptions); + ret.put(SLOEBER_LINK_COMPILE_OPTIONS, this.my_Link_CompileOptions); + ret.put(SLOEBER_ALL_COMPILE_OPTIONS, this.my_All_CompileOptions); + ret.put(SLOEBER_WARNING_LEVEL, myWarningLevel.name()); + ret.put(SLOEBER_WARNING_LEVEL_CUSTOM, myWarningLevel.myCustomWarningLevel); + ret.put(SLOEBER_DEBUG_LEVEL, myDebugLevel.name()); + ret.put(SLOEBER_DEBUG_LEVEL_CUSTOM, myDebugLevel.myCustomDebugLevel); + ret.put(SLOEBER_SIZE_TYPE, mySizeCommand.name()); + ret.put(SLOEBER_SIZE_CUSTOM, mySizeCommand.myCustomSizeCommand); + + return ret; + } + + public CompileDescription(TxtFile configFile, String prefix) { + + KeyValueTree tree = configFile.getData(); + KeyValueTree section = tree.getChild(prefix); + + my_C_andCPP_CompileOptions = section.getValue(SLOEBER_ADDITIONAL_COMPILE_OPTIONS); + my_CPP_CompileOptions = section.getValue(SLOEBER_ADDITIONAL_CPP_COMPILE_OPTIONS); + my_C_CompileOptions = section.getValue(SLOEBER_ADDITIONAL_C_COMPILE_OPTIONS); + my_Assembly_CompileOptions = section.getValue(SLOEBER_ASSEMBLY_COMPILE_OPTIONS); + my_Archive_CompileOptions = section.getValue(SLOEBER_ARCHIVE_COMPILE_OPTIONS); + my_Link_CompileOptions = section.getValue(SLOEBER_LINK_COMPILE_OPTIONS); + my_All_CompileOptions = section.getValue(SLOEBER_ALL_COMPILE_OPTIONS); + + try { + myWarningLevel = WarningLevels.valueOf(section.getValue(SLOEBER_WARNING_LEVEL)); + myWarningLevel.setCustomWarningLevel(section.getValue(SLOEBER_WARNING_LEVEL_CUSTOM)); + } catch (@SuppressWarnings("unused") Exception e) { + // ignore as this will be default + } + try { + myDebugLevel = DebugLevels.valueOf(section.getValue(SLOEBER_DEBUG_LEVEL)); + myDebugLevel.setCustomDebugLevel(section.getValue(SLOEBER_DEBUG_LEVEL_CUSTOM)); + } catch (@SuppressWarnings("unused") Exception e) { + // ignore as this will be default + } + try { + mySizeCommand = SizeCommands.valueOf(section.getValue(SLOEBER_SIZE_TYPE)); + mySizeCommand.setCustomSizeCommand(section.getValue(SLOEBER_SIZE_CUSTOM)); + } catch (@SuppressWarnings("unused") Exception e) { + // ignore as this will be default + } + + } + + public CompileDescription() { + // no need to do anything + // this will create default compile options + // note that the Parallel build option is implemented at the ui level + // therefore this is not set here but in the ui before project creation + } + + public CompileDescription(CompileDescription compileDescription) { + myWarningLevel = compileDescription.myWarningLevel; + myDebugLevel = compileDescription.myDebugLevel; + mySizeCommand = compileDescription.mySizeCommand; + myEnableParallelBuild = compileDescription.myEnableParallelBuild; + my_CPP_CompileOptions = compileDescription.my_CPP_CompileOptions; + my_C_CompileOptions = compileDescription.my_C_CompileOptions; + my_C_andCPP_CompileOptions = compileDescription.my_C_andCPP_CompileOptions; + my_Assembly_CompileOptions = compileDescription.my_Assembly_CompileOptions; + my_Archive_CompileOptions = compileDescription.my_Archive_CompileOptions; + my_Link_CompileOptions = compileDescription.my_Link_CompileOptions; + my_All_CompileOptions = compileDescription.my_All_CompileOptions; + } + + /** + * Compares 2 compile descriptors + * + * @param other + * @return true if the 2 are equal else false + */ + public boolean equals(CompileDescription other) { + return myWarningLevel.getEnvValue().equals(other.myWarningLevel.getEnvValue()) + && myDebugLevel.getEnvValue().equals(other.myDebugLevel.getEnvValue()) && mySizeCommand.getEnvValue().equals(other.mySizeCommand.getEnvValue()) && equalCompileOptions(other); - } - - /** - * Compares the compile options of 2 compile descriptors - * - * @param other - * @return true if the 2 have equal compile options else false - */ - private boolean equalCompileOptions(CompileDescription other) { - return (my_CPP_CompileOptions.equals(other.my_CPP_CompileOptions)) - && (my_C_CompileOptions.equals(other.my_C_CompileOptions)) - && (my_C_andCPP_CompileOptions.equals(other.my_C_andCPP_CompileOptions)) - && (my_Assembly_CompileOptions.equals(other.my_Assembly_CompileOptions)) - && (my_Archive_CompileOptions.equals(other.my_Archive_CompileOptions)) - && (my_Link_CompileOptions.equals(other.my_Link_CompileOptions)) - && (my_All_CompileOptions.equals(other.my_All_CompileOptions)); - } + } + + /** + * Compares the compile options of 2 compile descriptors + * + * @param other + * @return true if the 2 have equal compile options else false + */ + private boolean equalCompileOptions(CompileDescription other) { + return (my_CPP_CompileOptions.equals(other.my_CPP_CompileOptions)) + && (my_C_CompileOptions.equals(other.my_C_CompileOptions)) + && (my_C_andCPP_CompileOptions.equals(other.my_C_andCPP_CompileOptions)) + && (my_Assembly_CompileOptions.equals(other.my_Assembly_CompileOptions)) + && (my_Archive_CompileOptions.equals(other.my_Archive_CompileOptions)) + && (my_Link_CompileOptions.equals(other.my_Link_CompileOptions)) + && (my_All_CompileOptions.equals(other.my_All_CompileOptions)); + } } diff --git a/io.sloeber.core/src/io/sloeber/core/api/ConfigurationPreferences.java b/io.sloeber.core/src/io/sloeber/core/api/ConfigurationPreferences.java index dd7110ca3..7e399de6a 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/ConfigurationPreferences.java +++ b/io.sloeber.core/src/io/sloeber/core/api/ConfigurationPreferences.java @@ -3,13 +3,20 @@ import static io.sloeber.core.api.Const.*; import java.io.File; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import org.eclipse.cdt.core.parser.util.StringUtil; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.preferences.ConfigurationScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.osgi.service.prefs.BackingStoreException; +import cc.arduino.packages.discoverers.SloeberNetworkDiscovery; +import io.sloeber.core.common.InstancePreferences; + /** * Items on the Configuration level are linked to the ConfigurationScope * (=eclipse install base). @@ -26,10 +33,86 @@ public class ConfigurationPreferences { private static final String PRE_PROCESSING_BOARDS_TXT = "pre_processing_boards.txt"; //$NON-NLS-1$ private static final String POST_PROCESSING_BOARDS_TXT = "post_processing_boards.txt"; //$NON-NLS-1$ - private static final String KEY_UPDATE_JASONS = "Update jsons files"; //$NON-NLS-1$ + private static final String KEY_LATEST_JSON_UPDATE_TIME ="latest time the json files were updated";//$NON-NLS-1$ + private static final String KEY_JSON_UPDATE_DELAY="Duration between json file updates";//$NON-NLS-1$ + + private static String stringSplitter = "\n";//$NON-NLS-1$ + private static final String KEY_DISCONNECT_SERIAL_TAGETS = "Target names that require serial disconnect to run";//$NON-NLS-1$ + + public static void setAutoImportLibraries(boolean booleanValue) { + InstancePreferences.setAutomaticallyImportLibraries(booleanValue); + + } + + public static void setPragmaOnceHeaders(boolean booleanValue) { + InstancePreferences.setPragmaOnceHeaders(booleanValue); + + } + + public static boolean getPragmaOnceHeaders() { + return InstancePreferences.getPragmaOnceHeaders(); + } + + public static boolean getAutoImportLibraries() { + return InstancePreferences.getAutomaticallyImportLibraries(); + } + + public static void setUseArduinoToolSelection(boolean booleanValue) { + InstancePreferences.setUseArduinoToolSelection(booleanValue); + + } + + public static boolean getUseArduinoToolSelection() { + return InstancePreferences.getUseArduinoToolSelection(); + } + +// public static void setUpdateJsonFiles(boolean flag) { +// ConfigurationPreferences.setUpdateJasonFilesFlag(flag); +// } +// public static boolean getUpdateJsonFiles() { +// return ConfigurationPreferences.getUpdateJasonFilesFlag(); +// } + + /** + *wrapper for ConfigurationPreferences.useBonjour(); + */ + public static boolean useBonjour() { + return InstancePreferences.useBonjour(); + } + + /** + *wrapper for ConfigurationPreferences.setUseBonjour(newFlag); + */ + public static void setUseBonjour(boolean newFlag) { + InstancePreferences.setUseBonjour(newFlag); + if(newFlag) { + SloeberNetworkDiscovery.start(); + }else { + SloeberNetworkDiscovery.stop(); + } + } + + + + public static String[] getDisconnectSerialTargetsList() { + return getDisconnectSerialTargets().split(stringSplitter); + } + + public static String getDisconnectSerialTargets() { + return getString(KEY_DISCONNECT_SERIAL_TAGETS, Defaults.getDefaultDisconnectSerialTargets()).replace("\r", EMPTY);//$NON-NLS-1$ + } - // preference nodes - private static final String PACKAGES_FOLDER_NAME = "packages"; //$NON-NLS-1$ + public static void setDisconnectSerialTargets(String targets) { + setString(KEY_DISCONNECT_SERIAL_TAGETS, targets); + } + + public static void setDisconnectSerialTargets(String targets[]) { + setString(KEY_DISCONNECT_SERIAL_TAGETS, StringUtil.join(targets, stringSplitter)); + } + + public static void setDisconnectSerialTargets(HashSet targets) { + setString(KEY_DISCONNECT_SERIAL_TAGETS, StringUtil.join(targets, stringSplitter)); + } public static void removeKey(String key) { IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO); @@ -41,14 +124,20 @@ public static String getString(String key, String defaultValue) { return myScope.get(key, defaultValue); } - private static boolean getBoolean(String key, boolean defaultValue) { + + private static Instant getInstant(String key, Instant defaultValue) { IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO); - return myScope.getBoolean(key, defaultValue); + long ret = myScope.getLong(key, 0); + if(ret==0) { + setInstant( key, defaultValue); + return defaultValue; + } + return Instant.ofEpochSecond(ret); } - private static void setBoolean(String key, boolean value) { + private static void setInstant(String key, Instant value) { IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO); - myScope.putBoolean(key, value); + myScope.putLong(key, value.getEpochSecond()); try { myScope.flush(); } catch (BackingStoreException e) { @@ -71,7 +160,7 @@ public static void setString(String key, String value) { } public static IPath getInstallationPath() { - return Common.sloeberHomePath.append("arduinoPlugin"); //$NON-NLS-1$ + return Common.sloeberHomePath.append(SLOEBER_HOME_SUB_FOLDER); } public static IPath getInstallationPathLibraries() { @@ -117,20 +206,65 @@ public static File getPostProcessingBoardsFile() { } public static Path getMakePath() { - return new Path(getInstallationPath().append("tools/make").toString()); //$NON-NLS-1$ + return new Path(getInstallationPath().append("tools/make").toOSString()); //$NON-NLS-1$ } public static IPath getAwkPath() { - return new Path(getInstallationPath().append("tools/awk").toString()); //$NON-NLS-1$ + return new Path(getInstallationPath().append("tools/awk").toOSString()); //$NON-NLS-1$ + } + + public static Instant getLatestJsonUpdateTime() { + return getInstant(KEY_LATEST_JSON_UPDATE_TIME, Instant.now()); + } + + public static void setLatestUpdateTime(Instant currentTime) { + setInstant(KEY_LATEST_JSON_UPDATE_TIME,currentTime); + + } + + public static Duration getJsonUpdateDelay() { + return getDuration(KEY_JSON_UPDATE_DELAY,Defaults.getJsonUpdateDuration()); } - public static boolean getUpdateJasonFilesFlag() { - return getBoolean(KEY_UPDATE_JASONS, Defaults.updateJsonFiles); + public static void setJsonUpdateDelay(Duration jsunUpdateDuration) { + setDuration(KEY_JSON_UPDATE_DELAY,jsunUpdateDuration); } - public static void setUpdateJasonFilesFlag(boolean newFlag) { - setBoolean(KEY_UPDATE_JASONS, newFlag); + private static void setDuration(String key, Duration value) { + IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO); + myScope.putLong(key, value.toDays()); + try { + myScope.flush(); + } catch (BackingStoreException e) { + e.printStackTrace(); + } + } + + private static Duration getDuration(String key, Duration defaultValue) { + IEclipsePreferences myScope = ConfigurationScope.INSTANCE.getNode(NODE_ARDUINO); + long ret = myScope.getLong(key, 0); + if(ret==0) { + return defaultValue; + } + return Duration.ofDays(ret); + } + + /** + * Allow the library manager to download and install libraries based on include directive in the source code. + * + * @param selection true if you want to install libraries based on their usage else false + */ + public static void setInstallLibraries(boolean selection) { + InstancePreferences.setInstallLibraries(selection); + } + + /** + * + * @return true when libraries can be downloaded and installed when referenced in the code. + */ + public static boolean getInstallLibraries() { + return InstancePreferences.getInstallLibraries(); } } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Const.java b/io.sloeber.core/src/io/sloeber/core/api/Const.java index 34fe564c2..c95258338 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Const.java +++ b/io.sloeber.core/src/io/sloeber/core/api/Const.java @@ -46,6 +46,8 @@ public class Const extends AutoBuildConstants { public static final String PRIVATE = "private"; public static final String MANAGED = "Managed"; public static final String BOARD = "Board"; + public static final String JSON_NAME = "json"; + public static final String JSON_URL = "json_url"; public static final String NETWORK = "network"; @@ -64,13 +66,14 @@ public class Const extends AutoBuildConstants { public static final String PROTOCOL = "protocol"; public static final String VENDOR = "VENDOR"; public static final String VENDOR_ARDUINO = ARDUINO; + public static final String PACKAGES_FOLDER_NAME = "packages"; // arduino txt pre and suffix public static final String NETWORK_PREFIX = "network_"; public static final String REMOTE_SUFFIX = "_remote"; // General stuff - public static final String PLUGIN_ID = "io.sloeber.core"; + //public static final String PLUGIN_ID = "io.sloeber.core"; public static final String CORE_PLUGIN_ID = "io.sloeber.arduino.core"; public static final String SLOEBER_NATURE_ID = "io.sloeber.arduinonature"; public static final String KEY_LAST_USED_EXAMPLES = "Last used Examples"; @@ -79,6 +82,7 @@ public class Const extends AutoBuildConstants { public static final String LOCAL = "local"; // Folder and file Information + public static final String SLOEBER_HOME_SUB_FOLDER ="arduinoPlugin"; public static final String ARDUINO_HARDWARE_FOLDER_NAME = HARDWARE; public static final String ARDUINO_CODE_FOLDER_NAME = CORE; public static final String ARDUINO_VARIANTS_FOLDER_NAME = VARIANTS; @@ -95,6 +99,7 @@ public class Const extends AutoBuildConstants { public static final String SLOEBER_PROJECT = ".sproject"; public static final String LIBRARY_PROPERTIES = "library.properties"; public static final String LIBRARY_DOT_A_LINKAGE = "dot_a_linkage"; + public static final String SLOEBER_TXT_FILE_NAME="sloeber.txt"; // Environment variable stuff public static final String ENV_KEY_SLOEBER_START = "sloeber" + DOT; @@ -158,6 +163,9 @@ public class Const extends AutoBuildConstants { public static final String KEY_LAST_USED_BOARD = "Last used Board"; //$NON-NLS-1$ public static final String KEY_LAST_USED_UPLOAD_PORT = "Last Used Upload port"; //$NON-NLS-1$ public static final String KEY_LAST_USED_UPLOAD_PROTOCOL = "last Used upload Protocol"; //$NON-NLS-1$ + public static final String KEY_LAST_USED_JSON_FILENAME = "last Used json filename"; //$NON-NLS-1$ + public static final String KEY_LAST_USED_JSON_URL = "last Used json URL"; //$NON-NLS-1$ + public static final String KEY_LAST_USED_BOARDS_FILE = "Last used Boards file"; //$NON-NLS-1$ public static final String KEY_LAST_USED_BOARD_MENU_OPTIONS = "last used Board custom option selections"; //$NON-NLS-1$ public static final String ENV_KEY_SERIAL_PORT = "serial_port"; //$NON-NLS-1$ @@ -181,13 +189,20 @@ public class Const extends AutoBuildConstants { // stuff to store last used board public static final String KEY_SLOEBER_PROGRAMMER = "PROGRAMMER.NAME"; //$NON-NLS-1$ - public static final String KEY_SLOEBER_BOARD_TXT = "BOARD.TXT"; //$NON-NLS-1$ - public static final String KEY_SLOEBER_BOARD_ID = "BOARD.ID"; //$NON-NLS-1$ public static final String KEY_SLOEBER_UPLOAD_PORT = "UPLOAD.PORT"; //$NON-NLS-1$ - public static final String KEY_SLOEBER_MENU_SELECTION = "BOARD.MENU"; //$NON-NLS-1$ + public static final String KEY_BOARD = "BOARD"; //$NON-NLS-1$ + + public static final String KEY_SLOEBER_BOARD_TXT = "TXT"; //$NON-NLS-1$ + public static final String KEY_SLOEBER_BOARD_ID = "ID"; //$NON-NLS-1$ + public static final String KEY_SLOEBER_MENU_SELECTION = "MENU"; //$NON-NLS-1$ + + public static final String KEY_JSON="JSON";//$NON-NLS-1$ + public static final String KEY_JSON_FILENAME="FILE";//$NON-NLS-1$ + public static final String KEY_JSON_URL="URL";//$NON-NLS-1$ public static final String RELEASE = "Release"; + public static final String ARDUINO_SIZE = "arduino-size.cmd"; public static final short PLOTTER_START_DATA = (short) 0xCDAB;// This is the diff --git a/io.sloeber.core/src/io/sloeber/core/api/Defaults.java b/io.sloeber.core/src/io/sloeber/core/api/Defaults.java index 82a383df7..2d33a731d 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Defaults.java +++ b/io.sloeber.core/src/io/sloeber/core/api/Defaults.java @@ -1,27 +1,42 @@ package io.sloeber.core.api; -import static io.sloeber.core.api.Common.*; import static io.sloeber.core.api.Const.*; +import java.time.Duration; + import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; @SuppressWarnings("nls") public class Defaults { + public static final String DEFAULT_INSTALL_JSON = "https://downloads.arduino.cc/packages/package_index.json"; + public static final String JANTJE_BOARD_JSON_URL = "https://raw.githubusercontent.com/jantje/hardware/master/package_jantje_index.json"; + public static final String DEFAULT_INSTALL_ARCHITECTURE = "avr"; + public static final String DEFAULT_INSTALL_MAINTAINER = "arduino"; + private static final String DEFAULT_DISCONNECT_SERIAL_TARGETS = "BurnBootLoader\nuploadWithBuild\nuploadWithoutBuild\nuploadWithProgrammerWithBuild\nuploadWithProgrammerWithoutBuild"; //$NON-NLS-1$ + + public static final String[] DEFAULT_JSON_URLS = {DEFAULT_INSTALL_JSON, + JANTJE_BOARD_JSON_URL, + "https://raw.githubusercontent.com/jantje/ArduinoLibraries/master/library_jantje_index.json", + "https://arduino.esp8266.com/stable/package_esp8266com_index.json", + "https://www.pjrc.com/teensy/package_teensy_index.json", + "https://downloads.arduino.cc/libraries/library_index.json"}; + + + public static final String EXAMPLE_PACKAGE = "examples_Arduino_1_8_10.zip"; public static final String EXAMPLES_URL = "https://github.com/Sloeber/arduino-eclipse-plugin/releases/download/V4_3_2/" + EXAMPLE_PACKAGE; - public static final String DEFAULT_INSTALL_ARCHITECTURE = "avr"; - public static final String DEFAULT_INSTALL_MAINTAINER = "arduino"; + public static final String[] DEFAULT_INSTALLED_LIBRARIES = new String[] { "Ethernet", "Firmata", "GSM", "Keyboard", "LiquidCrystal", "Mouse", "SD", "Servo", "Stepper", "TFT", "WiFi", "CapacitiveSensor" }; public static final String DEFAULT = "Default"; - public static final boolean updateJsonFiles = true; public static final boolean useBonjour = true; public static final boolean autoInstallLibraries = true; public static final boolean useArduinoToolSelection = true; + public static final boolean INSTALL_LIBRARIES =false; //Install libraries on usage /** * Arduino has the default libraries in the user home directory in subfolder @@ -35,7 +50,7 @@ public static String getPrivateLibraryPath() { if (isMac || isWindows) { homPath = homPath.append("Documents"); } - return homPath.append("Arduino").append(ARDUINO_LIBRARY_FOLDER_NAME).toString(); + return homPath.append("Arduino").append(ARDUINO_LIBRARY_FOLDER_NAME).toOSString(); } public static String getPrivateHardwarePath() { @@ -43,7 +58,15 @@ public static String getPrivateHardwarePath() { if (isMac || isWindows) { homPath = homPath.append("Documents"); } - return homPath.append("Arduino").append(ARDUINO_HARDWARE_FOLDER_NAME).toString(); + return homPath.append("Arduino").append(ARDUINO_HARDWARE_FOLDER_NAME).toOSString(); } + public static String getDefaultDisconnectSerialTargets() { + return DEFAULT_DISCONNECT_SERIAL_TARGETS; + } + + public static Duration getJsonUpdateDuration() { + return Duration.ofDays(7); + } + } diff --git a/io.sloeber.core/src/io/sloeber/core/api/IInstallLibraryHandler.java b/io.sloeber.core/src/io/sloeber/core/api/IInstallLibraryHandler.java index edca8e28e..36496593d 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/IInstallLibraryHandler.java +++ b/io.sloeber.core/src/io/sloeber/core/api/IInstallLibraryHandler.java @@ -2,6 +2,8 @@ import java.util.Map; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; + /** * this interface is to allow the ui to handle the automatic installation * of libraries. diff --git a/io.sloeber.core/src/io/sloeber/core/api/ISloeberConfiguration.java b/io.sloeber.core/src/io/sloeber/core/api/ISloeberConfiguration.java index 9d1a7bc44..13680e444 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/ISloeberConfiguration.java +++ b/io.sloeber.core/src/io/sloeber/core/api/ISloeberConfiguration.java @@ -12,9 +12,12 @@ import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; import io.sloeber.autoBuild.integration.AutoBuildConfigurationDescription; import io.sloeber.core.Activator; @@ -46,7 +49,7 @@ public static ISloeberConfiguration getConfig(ICConfigurationDescription config) CConfigurationData buildSettings = config.getConfigurationData(); if (!(buildSettings instanceof AutoBuildConfigurationDescription)) { //this should not happen as we just created a autoBuild project - Common.log(new Status(SLOEBER_STATUS_DEBUG, Activator.getId(), + Activator.log(new Status(SLOEBER_STATUS_DEBUG, Activator.getId(), "\"Auto build created a project that does not seem to be a autobuild project :-s : " //$NON-NLS-1$ + config.getProjectDescription().getName())); return null; @@ -58,7 +61,7 @@ public static ISloeberConfiguration getConfig(IAutoBuildConfigurationDescription return (ISloeberConfiguration) autoBuildConfig.getAutoBuildConfigurationExtensionDescription(); } - IFolder getArduinoCodeFolder(); + IFolder getArduinoConfigurationFolder(); IFolder getArduinoCoreFolder(); @@ -113,12 +116,29 @@ public static ISloeberConfiguration getConfig(IAutoBuildConfigurationDescription public Set getIncludeFolders(); + /** + * Add libraries to the configurations + * Some libraries contain subfolders that need to be ignoreed. + * Therefore the configuration description may change. + * + * @param librariesToAdd + * @return true if when cCorePlugin.setProjectDescription needs to be called + */ public boolean addLibraries(Collection librariesToAdd); public boolean removeLibraries(Collection librariesToRemove); + /** + * Implements the action under Menu->Sloeber->Re attache libraries + * This method validates the attached libraries + * 1) Links to hardware libraries that point to a hardware different than the one used in + * the boardDescription of this configuration are replaced by versions from + * this boardDescription and if none is found are removed. + * 2) Links to non existing libraries are removed + */ void reAttachLibraries(); - Map getUsedLibraries(); + Map getUsedLibraries(); void setLibraries(Set selectedLibraries); + IFolder getArduinoRootFolder(); } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoInstallable.java b/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoInstallable.java deleted file mode 100644 index 75204b032..000000000 --- a/io.sloeber.core/src/io/sloeber/core/api/Json/ArduinoInstallable.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.sloeber.core.api.Json; - -import org.eclipse.core.runtime.IPath; - -public abstract class ArduinoInstallable { - - protected String archiveFileName; - protected String url; - protected String checksum; - protected String size; - protected String name; - - abstract public IPath getInstallPath(); - - public String getArchiveFileName() { - return archiveFileName; - } - - public String getUrl() { - return url; - } - - public String getChecksum() { - return checksum; - } - - public String getSize() { - return size; - } - - public String getName() { - return name; - } -} diff --git a/io.sloeber.core/src/io/sloeber/core/api/LaunchConfiguration.java b/io.sloeber.core/src/io/sloeber/core/api/LaunchConfiguration.java index f1b8db470..4f0287886 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/LaunchConfiguration.java +++ b/io.sloeber.core/src/io/sloeber/core/api/LaunchConfiguration.java @@ -9,7 +9,6 @@ import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.model.ILaunchConfigurationDelegate; -@SuppressWarnings("unused") public class LaunchConfiguration implements ILaunchConfigurationDelegate { /** diff --git a/io.sloeber.core/src/io/sloeber/core/api/OtherDescription.java b/io.sloeber.core/src/io/sloeber/core/api/OtherDescription.java index acdbf4e4b..69ab7ed41 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/OtherDescription.java +++ b/io.sloeber.core/src/io/sloeber/core/api/OtherDescription.java @@ -2,7 +2,6 @@ import java.util.Map; import java.util.TreeMap; -import java.util.Map.Entry; import io.sloeber.autoBuild.helpers.api.KeyValueTree; import io.sloeber.core.txt.TxtFile; @@ -34,12 +33,8 @@ public Map getEnvVars() { return allVars; } - public Map getEnvVarsConfig() { - Map allVars = new TreeMap<>(); - - allVars.put(KEY_SLOEBER_IS_VERSION_CONTROLLED, Boolean.valueOf(myIsVersionControlled).toString()); - - return allVars; + public void serialize(KeyValueTree keyValueTree) { + keyValueTree.addChild(KEY_SLOEBER_IS_VERSION_CONTROLLED, Boolean.valueOf(myIsVersionControlled).toString()); } /** @@ -47,22 +42,14 @@ public Map getEnvVarsConfig() { * * @param envVars */ - public OtherDescription(Map envVars) { - for (Entry curEnvVar : envVars.entrySet()) { - String key = curEnvVar.getKey(); - String value = curEnvVar.getValue(); - switch (key) { - case KEY_SLOEBER_IS_VERSION_CONTROLLED: - myIsVersionControlled = Boolean.parseBoolean(value); - break; - default: - break; - } - } + public OtherDescription(KeyValueTree keyValues) { + myIsVersionControlled = Boolean.parseBoolean(keyValues.getValue(KEY_SLOEBER_IS_VERSION_CONTROLLED)); } public Map getEnvVarsVersion() { - return getEnvVarsConfig(); + Map allVars = new TreeMap<>(); + allVars.put(KEY_SLOEBER_IS_VERSION_CONTROLLED, Boolean.valueOf(myIsVersionControlled).toString()); + return allVars; } public boolean IsVersionControlled() { diff --git a/io.sloeber.core/src/io/sloeber/core/api/PasswordManager.java b/io.sloeber.core/src/io/sloeber/core/api/PasswordManager.java index 07ae5dc3d..468bbe4d1 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/PasswordManager.java +++ b/io.sloeber.core/src/io/sloeber/core/api/PasswordManager.java @@ -6,6 +6,8 @@ import org.eclipse.equinox.security.storage.SecurePreferencesFactory; import org.eclipse.equinox.security.storage.StorageException; +import io.sloeber.autoBuild.helpers.api.AutoBuildConstants; +import io.sloeber.core.Activator; import io.sloeber.core.Messages; public class PasswordManager { @@ -56,7 +58,7 @@ public boolean setHost(String host) { } } catch (StorageException e) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "Set a password on the project properties->Sloeber page", e)); //$NON-NLS-1$ } @@ -94,7 +96,7 @@ static public void setPwd(String host, String login, String pwd) { node.put(Messages.security_password, pwd, false); } catch (StorageException e) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "failed to set login info", e)); //$NON-NLS-1$ + Activator.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "failed to set login info", e)); //$NON-NLS-1$ } } @@ -112,7 +114,7 @@ public static void ErasePassword(String host) { private static String ConvertHostToNodeName(String host) { - return "ssh/" + host.replace(Const.DOT, Const.SLACH); //$NON-NLS-1$ + return "ssh/" + host.replace(AutoBuildConstants.DOT, AutoBuildConstants.SLACH); //$NON-NLS-1$ } } diff --git a/io.sloeber.core/src/io/sloeber/core/api/Preferences.java b/io.sloeber.core/src/io/sloeber/core/api/Preferences.java deleted file mode 100644 index 6603fcd63..000000000 --- a/io.sloeber.core/src/io/sloeber/core/api/Preferences.java +++ /dev/null @@ -1,101 +0,0 @@ -package io.sloeber.core.api; - -import static io.sloeber.core.api.ConfigurationPreferences.*; -import static io.sloeber.core.api.Const.*; - -import java.util.HashSet; - -import org.eclipse.cdt.core.parser.util.StringUtil; - -import cc.arduino.packages.discoverers.SloeberNetworkDiscovery; -import io.sloeber.core.common.InstancePreferences; - -/** - * This is a wrapper class to make internal configuration settings externally available - * There should not be any logic in this class only redirections to internal methods - * @author jan - * - */ -public class Preferences { - private static String stringSplitter = "\n";//$NON-NLS-1$ - private static final String KEY_DISCONNECT_SERIAL_TAGETS = "Target names that require serial disconnect to run";//$NON-NLS-1$ - private static final String DEFAULT_DISCONNECT_SERIAL_TARGETS = "BurnBootLoader\nuploadWithBuild\nuploadWithoutBuild\nuploadWithProgrammerWithBuild\nuploadWithProgrammerWithoutBuild"; //$NON-NLS-1$ - - public static void setAutoImportLibraries(boolean booleanValue) { - InstancePreferences.setAutomaticallyImportLibraries(booleanValue); - - } - - public static void setPragmaOnceHeaders(boolean booleanValue) { - InstancePreferences.setPragmaOnceHeaders(booleanValue); - - } - - public static boolean getPragmaOnceHeaders() { - return InstancePreferences.getPragmaOnceHeaders(); - } - - public static boolean getAutoImportLibraries() { - return InstancePreferences.getAutomaticallyImportLibraries(); - } - - public static void setUseArduinoToolSelection(boolean booleanValue) { - InstancePreferences.setUseArduinoToolSelection(booleanValue); - - } - - public static boolean getUseArduinoToolSelection() { - return InstancePreferences.getUseArduinoToolSelection(); - } - - public static void setUpdateJsonFiles(boolean flag) { - ConfigurationPreferences.setUpdateJasonFilesFlag(flag); - } - public static boolean getUpdateJsonFiles() { - return ConfigurationPreferences.getUpdateJasonFilesFlag(); - } - - /** - *wrapper for ConfigurationPreferences.useBonjour(); - */ - public static boolean useBonjour() { - return InstancePreferences.useBonjour(); - } - - /** - *wrapper for ConfigurationPreferences.setUseBonjour(newFlag); - */ - public static void setUseBonjour(boolean newFlag) { - InstancePreferences.setUseBonjour(newFlag); - if(newFlag) { - SloeberNetworkDiscovery.start(); - }else { - SloeberNetworkDiscovery.stop(); - } - } - - public static String getDefaultDisconnectSerialTargets() { - return DEFAULT_DISCONNECT_SERIAL_TARGETS; - } - - public static String[] getDisconnectSerialTargetsList() { - return getDisconnectSerialTargets().split(stringSplitter); - } - - public static String getDisconnectSerialTargets() { - return getString(KEY_DISCONNECT_SERIAL_TAGETS, DEFAULT_DISCONNECT_SERIAL_TARGETS).replace("\r", EMPTY);//$NON-NLS-1$ - } - - public static void setDisconnectSerialTargets(String targets) { - setString(KEY_DISCONNECT_SERIAL_TAGETS, targets); - } - - public static void setDisconnectSerialTargets(String targets[]) { - setString(KEY_DISCONNECT_SERIAL_TAGETS, StringUtil.join(targets, stringSplitter)); - } - - public static void setDisconnectSerialTargets(HashSet targets) { - setString(KEY_DISCONNECT_SERIAL_TAGETS, StringUtil.join(targets, stringSplitter)); - } - -} diff --git a/io.sloeber.core/src/io/sloeber/core/api/Serial.java b/io.sloeber.core/src/io/sloeber/core/api/Serial.java index 3be832ae0..daf38e775 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/Serial.java +++ b/io.sloeber.core/src/io/sloeber/core/api/Serial.java @@ -43,6 +43,7 @@ import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceRegistration; +import io.sloeber.core.Activator; import io.sloeber.core.common.InstancePreferences; import jssc.SerialPort; import jssc.SerialPortEvent; @@ -117,7 +118,7 @@ public Serial(String iname, int irate, char iparity, int idatabits, float istopb * something slightly more intelligent to do. */ public static void errorMessage(String where, Throwable e) { - Common.log(new Status(IStatus.WARNING, Const.CORE_PLUGIN_ID, "Error inside Serial. " + where, e)); //$NON-NLS-1$ + Activator.log(new Status(IStatus.WARNING, Const.CORE_PLUGIN_ID, "Error inside Serial. " + where, e)); //$NON-NLS-1$ } @@ -151,7 +152,7 @@ public static List list() { } return new ArrayList<>(Arrays.asList(portNames)); } catch (Exception e) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "There is a config problem on your system.\nFor more detail see https://github.com/jantje/arduino-eclipse-plugin/issues/252", //$NON-NLS-1$ e)); List ret = new ArrayList<>(); @@ -194,16 +195,16 @@ public void connect(int maxTries) { // handle exception if (++count == maxTries) { if (SerialPortException.TYPE_PORT_BUSY.equals(e.getExceptionType())) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "Serial port " + this.portName //$NON-NLS-1$ + Activator.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "Serial port " + this.portName //$NON-NLS-1$ + " already in use. Try quiting any programs that may be using it", //$NON-NLS-1$ e)); } else if (SerialPortException.TYPE_PORT_NOT_FOUND.equals(e.getExceptionType())) { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "Serial port " //$NON-NLS-1$ + Activator.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "Serial port " //$NON-NLS-1$ + this.portName + " not found. Did you select the right one from the project properties -> Sloeber?", //$NON-NLS-1$ e)); } else { - Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "Error opening serial port " + this.portName, e)); //$NON-NLS-1$ } return; @@ -211,7 +212,7 @@ public void connect(int maxTries) { try { Thread.sleep(200); } catch (InterruptedException e1) { - Common.log(new Status(IStatus.WARNING, Const.CORE_PLUGIN_ID, "Sleep failed", e1)); //$NON-NLS-1$ + Activator.log(new Status(IStatus.WARNING, Const.CORE_PLUGIN_ID, "Sleep failed", e1)); //$NON-NLS-1$ } } // If an exception was thrown, delete port variable diff --git a/io.sloeber.core/src/io/sloeber/core/api/SloeberProject.java b/io.sloeber.core/src/io/sloeber/core/api/SloeberProject.java index dbafa93b2..5033918e9 100644 --- a/io.sloeber.core/src/io/sloeber/core/api/SloeberProject.java +++ b/io.sloeber.core/src/io/sloeber/core/api/SloeberProject.java @@ -2,15 +2,14 @@ import static io.sloeber.core.api.Const.*; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.File; import java.net.URI; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; -import java.util.stream.Collectors; +import java.util.TreeMap; import org.eclipse.cdt.core.CCProjectNature; import org.eclipse.cdt.core.CCorePlugin; @@ -19,8 +18,9 @@ import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.cdt.core.settings.model.ICSettingEntry; import org.eclipse.cdt.core.settings.model.ICSourceEntry; -import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; @@ -30,144 +30,338 @@ 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.Status; import org.eclipse.core.runtime.SubMonitor; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.LibraryManager; +import io.sloeber.arduinoFramework.internal.ArduinoLibraryVersion; import io.sloeber.autoBuild.api.AutoBuildProject; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; import io.sloeber.autoBuild.buildTools.api.IBuildTools; import io.sloeber.autoBuild.buildTools.api.IBuildToolsManager; +import io.sloeber.autoBuild.helpers.api.KeyValueTree; import io.sloeber.autoBuild.integration.AutoBuildConfigurationDescription; import io.sloeber.autoBuild.integration.AutoBuildManager; +import io.sloeber.autoBuild.schema.api.IConfiguration; import io.sloeber.autoBuild.schema.api.IProjectType; import io.sloeber.core.Activator; +import io.sloeber.core.Messages; +import io.sloeber.core.api.CompileDescription.SizeCommands; +import io.sloeber.core.internal.ArduinoHardwareLibrary; +import io.sloeber.core.internal.ArduinoPrivateHardwareLibraryVersion; import io.sloeber.core.internal.SloeberConfiguration; +import io.sloeber.core.listeners.IndexerController; import io.sloeber.core.natures.SloeberNature; +import io.sloeber.core.txt.TxtFile; public class SloeberProject extends Common { public static String LATEST_EXTENSION_POINT_ID = "io.sloeber.autoBuild.buildDefinitions"; //$NON-NLS-1$ public static String LATEST_EXTENSION_ID = "io.sloeber.builddef"; //$NON-NLS-1$ public static String PROJECT_ID = "io.sloeber.core.sketch"; //$NON-NLS-1$ private static String SLOEBER_BUILD_TOOL_PROVIDER_ID = "io.sloeber.core.arduino.ToolProvider"; //$NON-NLS-1$ - private static String SOURCE_ENTRY_FILTER_ALL="/**"; //$NON-NLS-1$ + private static String SOURCE_ENTRY_FILTER_ALL = "/**"; //$NON-NLS-1$ - /** - * convenient method to create project - * - * @param proj1Name - * @param object - * @param proj1BoardDesc - * @param codeDesc - * @param proj1CompileDesc - * @param otherDesc - * @param nullProgressMonitor - * @return - */ public static void convertToArduinoProject(IProject project, IProgressMonitor monitor) { - // if (project == null) { - // return; - // } - // final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // IWorkspaceRoot root = workspace.getRoot(); - // ICoreRunnable runnable = new ICoreRunnable() { - // @Override - // public void run(IProgressMonitor internalMonitor) throws CoreException { - // IndexerController.doNotIndex(project); - // - // try { - // - // // create a sloeber project - // SloeberProject sloeberProject = new SloeberProject(project); - // CCorePlugin cCorePlugin = CCorePlugin.getDefault(); - // ICProjectDescription prjCDesc = cCorePlugin.getProjectDescription(project, - // true); - // upgradeArduinoProject(sloeberProject, prjCDesc); - // if (!sloeberProject.readConfigFromFiles()) { - // sloeberProject.setBoardDescription(RELEASE, new BoardDescription(), false); - // sloeberProject.setCompileDescription(RELEASE, new CompileDescription()); - // sloeberProject.setOtherDescription(RELEASE, new OtherDescription()); - // // we failed to read from disk so we set up some values - // // faking the stuff is in memory - // - // } - // String configName = - // sloeberProject.myBoardDescriptions.keySet().iterator().next(); - // BoardDescription boardDescriptor = - // sloeberProject.getBoardDescription(configName, true); - // - // // Add the arduino code folders - // List addToIncludePath = Helpers.addArduinoCodeToProject(project, - // boardDescriptor); - // - // // make the eclipse project a cdt project - // CCorePlugin.getDefault().createCProject(null, project, new - // NullProgressMonitor(), - // ManagedBuilderCorePlugin.MANAGED_MAKE_PROJECT_ID); - // - // // add the required natures - // AutoBuildNature.addNature(project, internalMonitor); - // - // // make the cdt project a managed build project - // IProjectType sloeberProjType = - // AutoBuildManager.getProjectType("io.sloeber.core.sketch"); //$NON-NLS-1$ - // ManagedBuildManager.createBuildInfo(project); - // IManagedProject newProject = - // ManagedBuildManager.createManagedProject(project, sloeberProjType); - // ManagedBuildManager.setNewProjectVersion(project); - // // Copy over the Sloeber configs - // IConfiguration defaultConfig = null; - // IConfiguration[] configs = sloeberProjType.getConfigurations(); - // for (int i = 0; i < configs.length; ++i) { - // IConfiguration curConfig = newProject.createConfiguration(configs[i], - // sloeberProjType.getId() + "." + i); //$NON-NLS-1$ - // curConfig.setArtifactName(newProject.getDefaultArtifactName()); - // // Make the first configuration the default - // if (i == 0) { - // defaultConfig = curConfig; - // } - // } - // - // ManagedBuildManager.setDefaultConfiguration(project, defaultConfig); - // - // ICConfigurationDescription activeConfig = prjCDesc.getActiveConfiguration(); - // - // for (String curConfigName : sloeberProject.myBoardDescriptions.keySet()) { - // ICConfigurationDescription curConfigDesc = - // prjCDesc.getConfigurationByName(curConfigName); - // if (curConfigDesc == null) { - // String id = CDataUtil.genId(null); - // curConfigDesc = prjCDesc.createConfiguration(id, curConfigName, - // activeConfig); - // } - // Helpers.addIncludeFolder(curConfigDesc, addToIncludePath, true); - // - // String curConfigKey = getConfigKey(curConfigDesc); - // sloeberProject.myEnvironmentVariables.put(curConfigKey, - // sloeberProject.getEnvVars(curConfigKey)); - // - // } - // sloeberProject.createSloeberConfigFiles(); - // SubMonitor refreshMonitor = SubMonitor.convert(internalMonitor, 3); - // project.refreshLocal(IResource.DEPTH_INFINITE, refreshMonitor); - // cCorePlugin.setProjectDescription(project, prjCDesc, true, null); - // - // } catch (Exception e) { - // Common.log(new Status(IStatus.INFO, io.sloeber.core.Activator.getId(), - // "Project conversion failed: ", e)); //$NON-NLS-1$ - // } - // - // IndexerController.index(project); - // } - // - // }; - // - // try { - // workspace.run(runnable, root, IWorkspace.AVOID_UPDATE, monitor); - // } catch (Exception e) { - // Common.log(new Status(IStatus.INFO, io.sloeber.core.Activator.getId(), - // "Project conversion failed: ", e)); //$NON-NLS-1$ - // } + if (project == null) { + Activator.log(new Status(IStatus.ERROR, Activator.getId(), + Messages.SloeberProject_Project_is_null)); + return; + } + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + IWorkspaceRoot root = workspace.getRoot(); + ICoreRunnable runnable = new ICoreRunnable() { + @Override + public void run(IProgressMonitor internalMonitor) throws CoreException { + //remove managed build nature if it exists + String managedBuildNature="org.eclipse.cdt.managedbuilder.core.managedBuildNature"; //$NON-NLS-1$ + String ScannerConfigNature="org.eclipse.cdt.managedbuilder.core.ScannerConfigNature"; //$NON-NLS-1$ + if(project.hasNature(managedBuildNature) || project.hasNature(ScannerConfigNature)) { + + IProjectDescription description = project.getDescription(); + Set curNatures = new HashSet<>(Arrays.asList(description.getNatureIds())); + curNatures.remove(managedBuildNature); + curNatures.remove(ScannerConfigNature); + description.setNatureIds(curNatures.toArray(new String[curNatures.size()])); + project.setDescription(description, monitor); + } + IFolder OldCoreFolder =project.getFolder("core"); //$NON-NLS-1$ + if(OldCoreFolder.exists()) { + OldCoreFolder.delete(true, monitor); + } + + + File sloeberDotFile = project.getFile(".sproject").getLocation().toFile(); //$NON-NLS-1$ + File sloeberCfgFile = project.getFile(SLOEBER_CFG).getLocation().toFile(); + TxtFile oldSloeberInfo = null; + if (sloeberDotFile.exists() && sloeberCfgFile.exists()) { + oldSloeberInfo = new TxtFile(sloeberDotFile); + oldSloeberInfo.mergeFile(sloeberCfgFile); + } else { + if (sloeberDotFile.exists()) { + oldSloeberInfo = new TxtFile(sloeberDotFile); + } + if (sloeberCfgFile.exists()) { + oldSloeberInfo = new TxtFile(sloeberCfgFile); + } + } + + CCorePlugin cCorePlugin = CCorePlugin.getDefault(); + ICProjectDescription oldPrjCDesc = cCorePlugin.getProjectDescription(project, false); + Set cfgNames=new HashSet<>(); + for (ICConfigurationDescription curConfig : oldPrjCDesc.getConfigurations()) { + cfgNames.add( curConfig.getName()); + } + + + KeyValueTree oldConfigs=null; + if (oldSloeberInfo != null) { + oldConfigs = oldSloeberInfo.getData().getChild("Config"); //$NON-NLS-1$ + for (String curTree : oldConfigs.getChildren().keySet()) { + cfgNames.add(curTree); + } + } + + String builderName = AutoBuildProject.INTERNAL_BUILDER_ID; + IBuildTools buildTools = IBuildToolsManager.getDefault().getBuildTools(SLOEBER_BUILD_TOOL_PROVIDER_ID, + null); + IProjectType projectType = AutoBuildManager.getProjectType(LATEST_EXTENSION_POINT_ID, + LATEST_EXTENSION_ID, PROJECT_ID, true); + CodeDescription codeProvider = CodeDescription.createNone(); + AutoBuildProject.createProject(project.getName(), null, projectType, builderName, + CCProjectNature.CC_NATURE_ID, codeProvider, buildTools, true, internalMonitor); + + SloeberNature.addNature(project, internalMonitor); + ICProjectDescription prjCDesc = cCorePlugin.getProjectDescription(project, true); + + // Get the libraries used + Set libNames = new HashSet<>(); + IFolder libFolder = project.getFolder("libraries"); //$NON-NLS-1$ + if (libFolder.exists()) { + for (IResource curResource : libFolder.members()) { + if (curResource instanceof IFolder) { + IFolder curFolder = (IFolder) curResource; + libNames.add(curFolder.getName()); + } + } + } + + + IConfiguration defaultConfig = projectType.getConfigurations()[0]; + for(String cfgName:cfgNames) { + KeyValueTree oldConfig=null; + if (oldConfigs != null) { + oldConfig = oldConfigs.getChild(cfgName); + } + + IConfiguration config = projectType.getConfiguration(cfgName); + if (config == null) { + config = defaultConfig; + } + ICConfigurationDescription curConfig = prjCDesc.getConfigurationByName(cfgName); + AutoBuildConfigurationDescription autoConf=null; + if (curConfig == null) { + // config does not exists so create it + autoConf = new AutoBuildConfigurationDescription(config, + project, buildTools, null); + autoConf.setName(cfgName); + curConfig = prjCDesc.createConfiguration(AutoBuildProject.INTERNAL_BUILDER_ID, autoConf); + autoConf.setCdtConfigurationDescription(curConfig); + }else { + autoConf = (AutoBuildConfigurationDescription) IAutoBuildConfigurationDescription.getConfig(curConfig); + } + + ICSourceEntry newSourceEntries[] = new ICSourceEntry[2]; + // old Sloeber project so the code is in the root of the project for sure + // as we are at the root + // exclude bin folder and arduino folder + IPath excludes[] = new IPath[2]; + excludes[0] = autoConf.getBuildFolder().getProjectRelativePath().removeLastSegments(1) + .append(SOURCE_ENTRY_FILTER_ALL); + excludes[1] = project.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getProjectRelativePath() + .append(SOURCE_ENTRY_FILTER_ALL); + newSourceEntries[0] = new CSourceEntry(project.getFullPath(), excludes, ICSettingEntry.RESOLVED); + IPath excludes2[] = new IPath[10]; + excludes2[0] = IPath.fromOSString("**/*.ino"); //$NON-NLS-1$ + excludes2[1] = IPath.fromOSString("libraries/?*/**/doc*/**"); //$NON-NLS-1$ + excludes2[2] = IPath.fromOSString("libraries/?*/**/?xamples/**"); //$NON-NLS-1$ + excludes2[3] = IPath.fromOSString("libraries/?*/**/?xtras/**"); //$NON-NLS-1$ + excludes2[4] = IPath.fromOSString("libraries/?*/**/test*/**"); //$NON-NLS-1$ + excludes2[5] = IPath.fromOSString("libraries/?*/**/third-party/**"); //$NON-NLS-1$ + excludes2[6] = IPath.fromOSString("libraries/**/._*"); //$NON-NLS-1$ + excludes2[7] = IPath.fromOSString("libraries/?*/lib/**"); //$NON-NLS-1$ + excludes2[8] = IPath.fromOSString("libraries/?*/utility/*/*"); //$NON-NLS-1$ + excludes2[9] = IPath.fromOSString("libraries/?*/Applications/**"); //$NON-NLS-1$ + + /* + * CDT currently causes issues with ${ConfigName] + * https://github.com/eclipse-cdt/cdt/issues/870 IPath arduinoRoot = + * newProjectHandle.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getFullPath().append( + * CONFIG_NAME_VARIABLE); + */ + IPath arduinoRoot = project.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getFullPath() + .append(cfgName); + newSourceEntries[1] = new CSourceEntry(arduinoRoot, excludes2, ICSettingEntry.NONE); + curConfig.setSourceEntries(newSourceEntries); + + //Get the Sloeber information from the original project (and if nothing found use defaults) + BoardDescription boardDescriptor = getBoardDescription(oldConfig); + CompileDescription compileDescriptor = getCompileDescription(oldConfig); + OtherDescription otherDesc = getOtherDescription(oldConfig); + + //Set the Sloeber configuration based on to the old project + autoConf.setIsParallelBuild(compileDescriptor.isParallelBuildEnabled()); + SloeberConfiguration sloeberConfiguration = new SloeberConfiguration(boardDescriptor, otherDesc, + compileDescriptor); + + + + //Save the sloeber configuration in the autoBuild configuration + autoConf.setAutoBuildConfigurationExtensionDescription(sloeberConfiguration); + + // Add the libraries + TreeMap availableLibs = LibraryManager + .getLibrariesAll(boardDescriptor); + // find the libs we can add + Set toInstallLibs = new HashSet<>(); + for (String curLibName : libNames) { + IPath boardLibFQN = ArduinoHardwareLibrary.calculateFQN(curLibName); + IArduinoLibraryVersion foundLib = availableLibs.get(boardLibFQN.toString()); + if (foundLib != null) { + toInstallLibs.add(foundLib); + continue; + } + + IPath managedLibFQN = ArduinoLibraryVersion.calculateFQN(curLibName); + foundLib = availableLibs.get(managedLibFQN.toString()); + if (foundLib != null) { + toInstallLibs.add(foundLib); + continue; + } + + IPath privateLibFQN = ArduinoPrivateHardwareLibraryVersion.calculateFQN(curLibName); + foundLib = availableLibs.get(privateLibFQN.toString()); + if (foundLib != null) { + toInstallLibs.add(foundLib); + continue; + } + + } + toInstallLibs.remove(null); + sloeberConfiguration.addLibraries(toInstallLibs); + } + + SubMonitor refreshMonitor = SubMonitor.convert(internalMonitor, 3); + project.open(refreshMonitor); + project.refreshLocal(IResource.DEPTH_INFINITE, refreshMonitor); + prjCDesc.setActiveConfiguration(prjCDesc.getConfigurations()[0]); + prjCDesc.setCdtProjectCreated(); + + cCorePlugin.setProjectDescription(project, prjCDesc, true, SubMonitor.convert(internalMonitor, 1)); +// project.close(monitor); +// project.open(monitor); + + Activator.log(new Status(SLOEBER_STATUS_DEBUG, Activator.getId(), + "internal creation of project is done: " + project.getName())); //$NON-NLS-1$ + } + }; + try + + { + IndexerController.doNotIndex(project); + workspace.run(runnable, root, IWorkspace.AVOID_UPDATE, monitor); + } catch (Exception e) { + Activator.log(new Status(IStatus.ERROR, io.sloeber.core.Activator.getId(), + "Project creation failed: " + project.getName(), e)); //$NON-NLS-1$ + } + IndexerController.index(project); + monitor.done(); + } + + private static OtherDescription getOtherDescription(KeyValueTree config) { + OtherDescription ret =new OtherDescription(); + if (config == null) { + return ret; + } + ret.setVersionControlled(Boolean.valueOf(config.getValue("other.IS_VERSION_CONTROLLED")).booleanValue()); //$NON-NLS-1$ + return ret; + } + + private static CompileDescription getCompileDescription(KeyValueTree oldConfig) { + CompileDescription ret = new CompileDescription(); + if (oldConfig == null) { + return ret; + } + KeyValueTree compileConfig=oldConfig.getChild("compile").getChild("sloeber"); //$NON-NLS-1$ //$NON-NLS-2$ + if (compileConfig == null) { + return ret; + } + + KeyValueTree extraConfig=compileConfig.getChild("extra"); //$NON-NLS-1$ + ret.set_All_CompileOptions(extraConfig.getValue("all")); //$NON-NLS-1$ + ret.set_Archive_CompileOptions(extraConfig.getValue("archive")); //$NON-NLS-1$ + ret.set_Assembly_CompileOptions(extraConfig.getValue("assembly")); //$NON-NLS-1$ + ret.set_C_CompileOptions(extraConfig.getValue("c.compile")); //$NON-NLS-1$ + ret.set_CPP_CompileOptions(extraConfig.getValue("cpp.compile")); //$NON-NLS-1$ + ret.set_Link_CompileOptions(extraConfig.getValue("link")); //$NON-NLS-1$ + ret.set_C_andCPP_CompileOptions(extraConfig.getValue("compile")); //$NON-NLS-1$ + ret.setSizeCommand(SizeCommands.valueOf(extraConfig.getValue("compile.sloeber.size.type"),SizeCommands.ARDUINO_WAY)); //$NON-NLS-1$ + +// ret.setSizeCommand(extraConfig.getValue("compile")); //$NON-NLS-1$ +// +// +// Config.Release.compile.sloeber.size.custom= +// Config.Release.compile.sloeber.size.type=RAW_RESULT +// Config.Release.compile.sloeber.warning_level=NONE +// Config.Release.compile.sloeber.warning_level.custom= + + return ret; + } + + private static BoardDescription getBoardDescription(KeyValueTree oldConfig) { + if (oldConfig == null) { + return new BoardDescription(); + } + String boardsFileString=oldConfig.getValue("board.BOARD.TXT"); //$NON-NLS-1$ + String boardID=oldConfig.getValue("board.BOARD.ID"); //$NON-NLS-1$ + + if(boardsFileString.isBlank() || boardID.isBlank()) { + return new BoardDescription(); + } + Path readBoardsFilePath=new Path(boardsFileString); + IPath foundBoardsFilePath=null; + String[] segments =readBoardsFilePath.segments(); + for(String curSegment:segments) { + + if(foundBoardsFilePath!=null) { + foundBoardsFilePath=foundBoardsFilePath.append(curSegment); + }else { + if(SLOEBER_HOME_SUB_FOLDER.equals( curSegment)) { + foundBoardsFilePath=new Path(sloeberHome).append(curSegment); + } + } + } + if (foundBoardsFilePath == null || (!foundBoardsFilePath.toFile().exists()) ) { + return new BoardDescription(); + } + + + KeyValueTree optionsHolder=oldConfig.getChild("board.BOARD.MENU"); //$NON-NLS-1$ + + Map options=new HashMap<>(); + for(KeyValueTree curOption:optionsHolder.getChildren().values()) { + options.put(curOption.getKey(), curOption.getValue()); + } + File boardsFile=foundBoardsFilePath.toFile();// new File(boardsFileString); + + BoardDescription ret= new BoardDescription( null,boardsFile, boardID, options); + String uploadPort=oldConfig.getValue("board.UPLOAD.PORT"); //$NON-NLS-1$ + ret.setUploadPort(uploadPort); + + return ret; } /** @@ -184,31 +378,32 @@ public static void convertToArduinoProject(IProject project, IProgressMonitor mo */ public static IProject createArduinoProject(String projectName, URI projectURI, BoardDescription boardDescriptor, CodeDescription codeDesc, CompileDescription compileDescriptor, IProgressMonitor monitor) { - return createArduinoProject(projectName, projectURI, boardDescriptor, codeDesc, compileDescriptor, - null,null, monitor); + return createArduinoProject(projectName, projectURI, boardDescriptor, codeDesc, compileDescriptor, null, null, + monitor); } - public static IProject createArduinoProject(String projectName, URI projectURI, BoardDescription boardDescriptor, - CodeDescription codeDesc, CompileDescription compileDescriptor,String builderName, + public static IProject createArduinoProject(String projectName, URI projectURI, BoardDescription boardDescriptor, + CodeDescription codeDesc, CompileDescription compileDescriptor, String builderName, IProgressMonitor monitor) { - return createArduinoProject(projectName, projectURI, boardDescriptor, codeDesc, compileDescriptor, - null,builderName, monitor); + return createArduinoProject(projectName, projectURI, boardDescriptor, codeDesc, compileDescriptor, null, + builderName, monitor); } - public static IProject createArduinoProject(String projectName, URI projectURI, BoardDescription boardDescriptor, + + public static IProject createArduinoProject(String projectName, URI projectURI, BoardDescription boardDescriptor, CodeDescription codeDesc, CompileDescription compileDescriptor, OtherDescription otherDesc, IProgressMonitor monitor) { - return createArduinoProject(projectName, projectURI, boardDescriptor, codeDesc, compileDescriptor, - otherDesc,null, monitor); + return createArduinoProject(projectName, projectURI, boardDescriptor, codeDesc, compileDescriptor, otherDesc, + null, monitor); } /* * Method to create a project based on the board */ - public static IProject createArduinoProject(String projectName, URI projectURI, BoardDescription boardDescriptor, - CodeDescription codeDesc, CompileDescription compileDescriptor, OtherDescription inOtherDesc,String inBuilderName, - IProgressMonitor monitor) { - OtherDescription otherDesc=inOtherDesc==null?new OtherDescription():inOtherDesc; - String builderName=inBuilderName==null?AutoBuildProject.INTERNAL_BUILDER_ID:inBuilderName; + public static IProject createArduinoProject(String projectName, URI projectURI, BoardDescription boardDescriptor, + CodeDescription codeDesc, CompileDescription compileDescriptor, OtherDescription inOtherDesc, + String inBuilderName, IProgressMonitor monitor) { + OtherDescription otherDesc = inOtherDesc == null ? new OtherDescription() : inOtherDesc; + String builderName = inBuilderName == null ? AutoBuildProject.INTERNAL_BUILDER_ID : inBuilderName; String realProjectName = makeNameCompileSafe(projectName); @@ -221,11 +416,11 @@ public void run(IProgressMonitor internalMonitor) throws CoreException { // IndexerController.doNotIndex(newProjectHandle); IBuildTools buildTools = IBuildToolsManager.getDefault().getBuildTools(SLOEBER_BUILD_TOOL_PROVIDER_ID, - realProjectName); + null); IProjectType projectType = AutoBuildManager.getProjectType(LATEST_EXTENSION_POINT_ID, LATEST_EXTENSION_ID, PROJECT_ID, true); - newProjectHandle = AutoBuildProject.createProject(realProjectName, projectURI, projectType, - builderName ,CCProjectNature.CC_NATURE_ID, codeDesc, buildTools, true, internalMonitor); + newProjectHandle = AutoBuildProject.createProject(realProjectName, projectURI, projectType, builderName, + CCProjectNature.CC_NATURE_ID, codeDesc, buildTools, true, internalMonitor); String rootCodeFolder = codeDesc.getCodeFolder(); // Add the sketch code @@ -238,43 +433,51 @@ public void run(IProgressMonitor internalMonitor) throws CoreException { for (ICConfigurationDescription curConfig : prjCDesc.getConfigurations()) { - IAutoBuildConfigurationDescription autoConf = IAutoBuildConfigurationDescription.getConfig( curConfig); + IAutoBuildConfigurationDescription autoConf = IAutoBuildConfigurationDescription + .getConfig(curConfig); ICSourceEntry newSourceEntries[] = new ICSourceEntry[2]; if (rootCodeFolder == null || rootCodeFolder.isBlank()) { // as we are at the root // exclude bin folder and arduino folder IPath excludes[] = new IPath[2]; - excludes[0] = autoConf.getBuildFolder().getProjectRelativePath().removeLastSegments(1).append(SOURCE_ENTRY_FILTER_ALL); - excludes[1] = newProjectHandle.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getProjectRelativePath().append(SOURCE_ENTRY_FILTER_ALL); - newSourceEntries[0] = new CSourceEntry(newProjectHandle.getFullPath(), excludes, ICSettingEntry.RESOLVED); + excludes[0] = autoConf.getBuildFolder().getProjectRelativePath().removeLastSegments(1) + .append(SOURCE_ENTRY_FILTER_ALL); + excludes[1] = newProjectHandle.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getProjectRelativePath() + .append(SOURCE_ENTRY_FILTER_ALL); + newSourceEntries[0] = new CSourceEntry(newProjectHandle.getFullPath(), excludes, + ICSettingEntry.RESOLVED); } else { // no need to exclude any folder as we have a dedicated code folder - IPath path=newProjectHandle.getFolder(rootCodeFolder).getFullPath(); + IPath path = newProjectHandle.getFolder(rootCodeFolder).getFullPath(); newSourceEntries[0] = new CSourceEntry(path, null, ICSettingEntry.RESOLVED); } - IPath excludes[] = new IPath[8]; - excludes[0] = IPath.fromOSString("**/*.ino"); //$NON-NLS-1$ - excludes[1] = IPath.fromOSString("libraries/?*/**/doc*/**"); //$NON-NLS-1$ - excludes[2] = IPath.fromOSString("libraries/?*/**/?xamples/**"); //$NON-NLS-1$ - excludes[3] = IPath.fromOSString("libraries/?*/**/?xtras/**"); //$NON-NLS-1$ - excludes[4] = IPath.fromOSString("libraries/?*/**/test*/**"); //$NON-NLS-1$ - excludes[5] = IPath.fromOSString("libraries/?*/**/third-party/**"); //$NON-NLS-1$ - excludes[6] = IPath.fromOSString("libraries/**/._*"); //$NON-NLS-1$ - excludes[7] = IPath.fromOSString("libraries/?*/utility/*/*"); //$NON-NLS-1$ + IPath excludes2[] = new IPath[10]; + excludes2[0] = IPath.fromOSString("**/*.ino"); //$NON-NLS-1$ + excludes2[1] = IPath.fromOSString("libraries/?*/**/doc*/**"); //$NON-NLS-1$ + excludes2[2] = IPath.fromOSString("libraries/?*/**/?xamples/**"); //$NON-NLS-1$ + excludes2[3] = IPath.fromOSString("libraries/?*/**/?xtras/**"); //$NON-NLS-1$ + excludes2[4] = IPath.fromOSString("libraries/?*/**/test*/**"); //$NON-NLS-1$ + excludes2[5] = IPath.fromOSString("libraries/?*/**/third-party/**"); //$NON-NLS-1$ + excludes2[6] = IPath.fromOSString("libraries/**/._*"); //$NON-NLS-1$ + excludes2[7] = IPath.fromOSString("libraries/?*/lib/**"); //$NON-NLS-1$ + excludes2[8] = IPath.fromOSString("libraries/?*/utility/*/*"); //$NON-NLS-1$ + excludes2[9] = IPath.fromOSString("libraries/?*/Applications/**"); //$NON-NLS-1$ /* * CDT currently causes issues with ${ConfigName] - * https://github.com/eclipse-cdt/cdt/issues/870 - * IPath arduinoRoot = newProjectHandle.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getFullPath().append(CONFIG_NAME_VARIABLE); - */ - IPath arduinoRoot = newProjectHandle.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getFullPath().append(curConfig.getName()); - newSourceEntries[1] = new CSourceEntry(arduinoRoot, excludes, ICSettingEntry.NONE); + * https://github.com/eclipse-cdt/cdt/issues/870 IPath arduinoRoot = + * newProjectHandle.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getFullPath().append( + * CONFIG_NAME_VARIABLE); + */ + IPath arduinoRoot = newProjectHandle.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getFullPath() + .append(curConfig.getName()); + newSourceEntries[1] = new CSourceEntry(arduinoRoot, excludes2, ICSettingEntry.NONE); curConfig.setSourceEntries(newSourceEntries); IAutoBuildConfigurationDescription iAutoBuildConfig = IAutoBuildConfigurationDescription .getConfig(curConfig); if (!(iAutoBuildConfig instanceof AutoBuildConfigurationDescription)) { // this should not happen as we just created a autoBuild project - Common.log(new Status(SLOEBER_STATUS_DEBUG, Activator.getId(), + Activator.log(new Status(SLOEBER_STATUS_DEBUG, Activator.getId(), "\"Auto build created a project that does not seem to be a autobuild project :-s : " //$NON-NLS-1$ + realProjectName)); continue; @@ -294,426 +497,20 @@ public void run(IProgressMonitor internalMonitor) throws CoreException { cCorePlugin.setProjectDescription(newProjectHandle, prjCDesc, true, SubMonitor.convert(internalMonitor, 1)); - Common.log(new Status(SLOEBER_STATUS_DEBUG, Activator.getId(), + Activator.log(new Status(SLOEBER_STATUS_DEBUG, Activator.getId(), "internal creation of project is done: " + realProjectName)); //$NON-NLS-1$ // IndexerController.index(newProjectHandle); } }; - try - - { + try { workspace.run(runnable, root, IWorkspace.AVOID_UPDATE, monitor); } catch (Exception e) { - Common.log(new Status(IStatus.INFO, io.sloeber.core.Activator.getId(), + Activator.log(new Status(IStatus.INFO, io.sloeber.core.Activator.getId(), "Project creation failed: " + realProjectName, e)); //$NON-NLS-1$ } monitor.done(); return root.getProject(realProjectName); } - // private HashMap getEnvVars(String configKey) { - // BoardDescription boardDescription = myBoardDescriptions.get(configKey); - // CompileDescription compileOptions = myCompileDescriptions.get(configKey); - // OtherDescription otherOptions = myOtherDescriptions.get(configKey); - // - // HashMap allVars = new HashMap<>(); - // - // allVars.put(ENV_KEY_BUILD_SOURCE_PATH, myProject.getLocation().toOSString()); - // allVars.put(ENV_KEY_BUILD_PATH, - // myProject.getLocation().append(configKey).toOSString()); - // - // if (boardDescription != null) { - // allVars.putAll(boardDescription.getEnvVars()); - // } - // if (compileOptions != null) { - // allVars.putAll(compileOptions.getEnvVars()); - // } - // if (otherOptions != null) { - // allVars.putAll(otherOptions.getEnvVars()); - // } - // // set the paths - // String pathDelimiter = makeEnvironmentVar("PathDelimiter"); //$NON-NLS-1$ - // if (Common.isWindows) { - // allVars.put(SLOEBER_MAKE_LOCATION, - // ConfigurationPreferences.getMakePath().addTrailingSeparator().toOSString()); - // allVars.put(SLOEBER_AWK_LOCATION, - // ConfigurationPreferences.getAwkPath().addTrailingSeparator().toOSString()); - // - // String systemroot = makeEnvironmentVar("SystemRoot"); //$NON-NLS-1$ - // allVars.put("PATH", //$NON-NLS-1$ - // makeEnvironmentVar(ENV_KEY_COMPILER_PATH) + pathDelimiter - // + makeEnvironmentVar(ENV_KEY_BUILD_GENERIC_PATH) + pathDelimiter + systemroot - // + "\\system32" //$NON-NLS-1$ - // + pathDelimiter + systemroot + pathDelimiter + systemroot + - // "\\system32\\Wbem" //$NON-NLS-1$ - // + pathDelimiter + makeEnvironmentVar("sloeber_path_extension")); - // //$NON-NLS-1$ - // } else { - // allVars.put("PATH", makeEnvironmentVar(ENV_KEY_COMPILER_PATH) + pathDelimiter - // //$NON-NLS-1$ - // + makeEnvironmentVar(ENV_KEY_BUILD_GENERIC_PATH) + pathDelimiter + - // makeEnvironmentVar("PATH")); //$NON-NLS-1$ - // } - // - // return allVars; - // } - - /** - * Read the sloeber configuration file and setup the project - * - * @return true if the files exist - */ - // private boolean readConfigFromFiles() { - // IFile file = getConfigLocalFile(); - // IFile versionFile = getConfigVersionFile(); - // if (!(file.exists() || versionFile.exists())) { - // // no sloeber files found - // return false; - // } - // if (file.exists()) { - // myCfgFile = new TxtFile(file.getLocation().toFile()); - // if (versionFile.exists()) { - // myCfgFile.mergeFile(versionFile.getLocation().toFile()); - // } - // } else { - // myCfgFile = new TxtFile(versionFile.getLocation().toFile()); - // } - // - // KeyValueTree allFileConfigs = myCfgFile.getData().getChild(CONFIG); - // for (Entry curChild : - // allFileConfigs.getChildren().entrySet()) { - // String curConfName = curChild.getKey(); - // BoardDescription boardDesc = new BoardDescription(myCfgFile, - // getBoardPrefix(curConfName)); - // CompileDescription compileDescription = new CompileDescription(myCfgFile, - // getCompilePrefix(curConfName)); - // OtherDescription otherDesc = new OtherDescription(myCfgFile, - // getOtherPrefix(curConfName)); - // String curConfKey = curConfName; - // myBoardDescriptions.put(curConfKey, boardDesc); - // myCompileDescriptions.put(curConfKey, compileDescription); - // myOtherDescriptions.put(curConfKey, otherDesc); - // } - // return true; - // } - - /** - * return the list of configNames known by Sloeber not known by CDT - * - * @param prjCDesc - * @return a list of sloeber known configurationNames unknown to CDT - */ - // private List newConfigsNeededInCDT(ICProjectDescription prjCDesc) { - // List ret = new LinkedList<>(); - // for (String curConfName : myBoardDescriptions.keySet()) { - // ICConfigurationDescription curConfDesc = - // prjCDesc.getConfigurationByName(curConfName); - // if (curConfDesc == null) { - // ret.add(curConfName); - // } - // } - // return ret; - // - // } - -// /** -// * create the cdt configurations from the list -// * -// * @param configs -// * @param prjCDesc -// * @return true if at least one config was created (basically only false if -// * configs is empty oe error conditions) -// */ -// private static boolean createNeededCDTConfigs(List configs, ICProjectDescription prjCDesc) { -// boolean ret = false; -// for (String curConfName : configs) { -// try { -// String id = CDataUtil.genId(null); -// prjCDesc.createConfiguration(id, curConfName, prjCDesc.getActiveConfiguration()); -// ret = true; -// } catch (Exception e) { -// // ignore as we will try again later -// e.printStackTrace(); -// } -// } -// return ret; -// } - - /** - * This methods creates/updates 2 files in the workspace. Together these files - * contain the Sloeber project configuration info The info is split into 2 files - * because you probably do not want to add all the info to a version control - * tool. - * - * sloeber.cfg is the file you can add to a version control .sproject is the - * file with settings you do not want to add to version control - * - * @param project the project to store the data for - */ - // private void createSloeberConfigFiles() { - // - // final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // if (workspace.isTreeLocked()) { - // // we cant save now do it later - // return; - // } - // - // Map configVars = new TreeMap<>(); - // Map versionVars = new TreeMap<>(); - // - // for (String configKey : myBoardDescriptions.keySet()) { - // BoardDescription boardDescription = myBoardDescriptions.get(configKey); - // CompileDescription compileDescription = myCompileDescriptions.get(configKey); - // OtherDescription otherDescription = myOtherDescriptions.get(configKey); - // - // String boardPrefix = getBoardPrefix(configKey); - // String compPrefix = getCompilePrefix(configKey); - // String otherPrefix = getOtherPrefix(configKey); - // - // configVars.putAll(boardDescription.getEnvVarsConfig(boardPrefix)); - // configVars.putAll(compileDescription.getEnvVarsConfig(compPrefix)); - // configVars.putAll(otherDescription.getEnvVarsConfig(otherPrefix)); - // - // if (otherDescription.IsVersionControlled()) { - // versionVars.putAll(boardDescription.getEnvVarsVersion(boardPrefix)); - // versionVars.putAll(compileDescription.getEnvVarsVersion(compPrefix)); - // versionVars.putAll(otherDescription.getEnvVarsVersion(otherPrefix)); - // } - // } - // - // try { - // storeConfigurationFile(getConfigVersionFile(), versionVars); - // storeConfigurationFile(getConfigLocalFile(), configVars); - // } catch (Exception e) { - // Common.log(new Status(IStatus.ERROR, io.sloeber.core.Activator.getId(), - // "failed to save the sloeber config files", e)); //$NON-NLS-1$ - // } - // - // } - - private static void storeConfigurationFile(IFile file, Map vars) throws Exception { - String content = EMPTY; - for (Entry curLine : vars.entrySet()) { - content += curLine.getKey() + '=' + curLine.getValue() + '\n'; - } - - if (file.exists()) { - // if the filecontent hasn't changed=>do nothing - try (InputStream inputStream = file.getContents();) { - String fileContent = new BufferedReader(new InputStreamReader(inputStream)).lines() - .collect(Collectors.joining("\n")); - -// Path filePath = Path.of(file.getLocation().toOSString()); -// String fileContent = Files.readString(filePath); - if (content.equals(fileContent)) { - return; - } - } - file.delete(true, null); - } - - if (!file.exists() && (!content.isBlank())) { - ByteArrayInputStream stream = new ByteArrayInputStream(content.getBytes()); - file.create(stream, true, null); - } - - } - - // /** - // * get the Arduino project description based on a project description - // * - // * @param project - // * @return the sloeber project or null if this is not a sloeber project - // */ - // public static SloeberProject getSloeberProject(IProject project) { - // - // if (project.isOpen() && project.getLocation().toFile().exists()) { - // if (Sketch.isSketch(project)) { - // Object sessionProperty = null; - // try { - // sessionProperty = project.getSessionProperty(sloeberQualifiedName); - // if (null != sessionProperty) { - // SloeberProject sloeberProject = (SloeberProject) sessionProperty; - // if (sloeberProject.isInMemory()) { - // IndexerController.index(project); - // } - // return sloeberProject; - // } - // } catch (CoreException e) { - // e.printStackTrace(); - // } - // return new SloeberProject(project); - // } - // } - // return null; - // } - -// private static String getBoardPrefix(String confDescName) { -// return CONFIG_DOT + confDescName + DOT + "board."; //$NON-NLS-1$ -// } -// -// private static String getCompilePrefix(String confDescName) { -// return CONFIG_DOT + confDescName + DOT + "compile."; //$NON-NLS-1$ -// } -// -// private static String getOtherPrefix(String confDescName) { -// return CONFIG_DOT + confDescName + DOT + "other."; //$NON-NLS-1$ -// } -// -// /* -// * Get the file that Sloeber maintains and that is meant to be stored in version control -// */ -// private IFile getConfigVersionFile() { -// return Sketch.getConfigVersionFile(myProject); -// } -// -// /* -// * Get the sloeber configuration file -// */ -// private IFile getConfigLocalFile() { -// return Sketch.getConfigLocalFile(myProject); -// } - - public void configChangeAboutToApply(ICProjectDescription newProjDesc, ICProjectDescription oldProjDesc) { - // ICConfigurationDescription newActiveConfig = - // newProjDesc.getActiveConfiguration(); - // ICConfigurationDescription oldActiveConfig = - // oldProjDesc.getActiveConfiguration(); - // - // //handle configuration name changes and new configs - // for (ICConfigurationDescription curConfig : newProjDesc.getConfigurations()) - // { - // String curConfigKey = getConfigKey(curConfig); - // ICConfigurationDescription oldConfig = - // oldProjDesc.getConfigurationById(curConfig.getId()); - // if (oldConfig == null) { - // //this is a new config - // myIsDirty = true; - // - // BoardDescription brdDesc = myBoardDescriptions.get(curConfigKey); - // if (brdDesc == null) { - // // This new configuration has not been created in project properties - // // I don't know how to get the "copied from" configuration - // // trying to get something somewhere - // // read: only copy configurations in project properties - // String copyConfKey = getConfigKey(oldActiveConfig); - // brdDesc = myBoardDescriptions.get(copyConfKey); - // if (brdDesc == null) { - // copyConfKey = getConfigKey(oldActiveConfig); - // brdDesc = myBoardDescriptions.get(copyConfKey); - // } - // BoardDescription boardDescription = new - // BoardDescription(myBoardDescriptions.get(copyConfKey)); - // myBoardDescriptions.put(curConfigKey, boardDescription); - // - // CompileDescription compileDescription = new CompileDescription( - // myCompileDescriptions.get(copyConfKey)); - // myCompileDescriptions.put(curConfigKey, compileDescription); - // - // OtherDescription otherDescription = new - // OtherDescription(myOtherDescriptions.get(copyConfKey)); - // myOtherDescriptions.put(curConfigKey, otherDescription); - // } - // - // } else { - // - // String oldConfigKey = getConfigKey(oldConfig); - // if (!oldConfigKey.equals(curConfigKey)) { - // //this is a rename - // myIsDirty = true; - // Helpers.deleteBuildFolder(myProject, oldConfig.getName()); - // BoardDescription boardDesc = myBoardDescriptions.get(oldConfigKey); - // myBoardDescriptions.remove(oldConfigKey); - // myBoardDescriptions.put(curConfigKey, boardDesc); - // - // CompileDescription compDesc = myCompileDescriptions.get(oldConfigKey); - // myCompileDescriptions.remove(oldConfigKey); - // myCompileDescriptions.put(curConfigKey, compDesc); - // - // OtherDescription otherDesc = myOtherDescriptions.get(oldConfigKey); - // myOtherDescriptions.remove(oldConfigKey); - // myOtherDescriptions.put(curConfigKey, otherDesc); - // - // } - // - // } - // } - // - // //delete all the deleted configs - // for (ICConfigurationDescription curConfig : oldProjDesc.getConfigurations()) - // { - // String curConfigKey = getConfigKey(curConfig); - // ICConfigurationDescription newConfig = - // newProjDesc.getConfigurationById(curConfig.getId()); - // if (newConfig == null) { - // //this is a deleted config - // myIsDirty = true; - // myBoardDescriptions.remove(curConfigKey); - // myCompileDescriptions.remove(curConfigKey); - // myOtherDescriptions.remove(curConfigKey); - // } - // } - // - // configure(newProjDesc, true); - - } - - /** - * Call this method when the sloeber.cfg file changed - * - */ - public void sloeberCfgChanged() { - // //CCorePlugin cCorePlugin = CCorePlugin.getDefault(); - // //ICProjectDescription projDesc = - // cCorePlugin.getProjectDescription(myProject, true); - // ///ICConfigurationDescription activeConfig = - // projDesc.getActiveConfiguration(); - // configure(); - // //all configs may have changed so only deleting the active config does not - // make sense - // //Helpers.deleteBuildFolder(myProject, activeConfig.getName()); - // - // //This code is only triggered when sloeber.cfg changed so no need to set the - // active config - // //projDescNeedsSaving = projDescNeedsSaving || setActiveConfig(activeConfig); - // // if (projDescNeedsSaving) { - // // try { - // // cCorePlugin.setProjectDescription(myProject, projDesc); - // // } catch (CoreException e) { - // // e.printStackTrace(); - // // } - // // } - - } - - /** - * When a board has been installed it may be that a boardDescription needs to - * reload the txt file - */ - public static void reloadTxtFile() { - // final IWorkspaceRoot workspaceRoot = - // ResourcesPlugin.getWorkspace().getRoot(); - // for (IProject curProject : workspaceRoot.getProjects()) { - // if (curProject.isOpen()) { - // SloeberProject sloeberProject = new - // SloeberProject(curProject);//getSloeberProject(curProject); - // if (sloeberProject != null) { - // sloeberProject.internalReloadTxtFile(); - // } - // } - // } - } - - /** - * When a board has been installed it may be that a boardDescription needs to - * reload the txt file - */ - // private void internalReloadTxtFile() { - // for (BoardDescription curBoardDescription : myBoardDescriptions.values()) { - // curBoardDescription.reloadTxtFile(); - // } - // - // } - } diff --git a/io.sloeber.core/src/io/sloeber/core/builder/SloeberBuilderExtension.java b/io.sloeber.core/src/io/sloeber/core/builder/SloeberBuilderExtension.java index 5cf655f51..835b4e0fd 100644 --- a/io.sloeber.core/src/io/sloeber/core/builder/SloeberBuilderExtension.java +++ b/io.sloeber.core/src/io/sloeber/core/builder/SloeberBuilderExtension.java @@ -16,6 +16,7 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; +import io.sloeber.arduinoFramework.api.BoardDescription; import io.sloeber.autoBuild.api.AutoBuildBuilderExtension; import io.sloeber.autoBuild.api.AutoBuildProject; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; @@ -25,7 +26,6 @@ import io.sloeber.autoBuild.integration.AutoBuildConfigurationDescription; import io.sloeber.autoBuild.schema.api.IBuilder; import io.sloeber.core.Messages; -import io.sloeber.core.api.BoardDescription; import io.sloeber.core.api.Common; import io.sloeber.core.internal.SloeberConfiguration; import io.sloeber.core.tools.Helpers; @@ -69,9 +69,14 @@ public void beforeAddingSourceRules(IAutoBuildMakeRules makeRules, makeRules.getSourceFilesToBuild().add(sloeberInoCppFile); } generateAwkFile(autoBuildConfData); + generateArduinoSizeCommandFile(autoBuildConfData); + super.beforeAddingSourceRules(makeRules, autoBuildConfData); } + + + @Override public boolean invokeBuild(IBuilder builder, int kind, String targetName, IAutoBuildConfigurationDescription autoData, IMarkerGenerator markerGenerator, IConsole console, IProgressMonitor monitor) throws CoreException { @@ -122,6 +127,30 @@ public SloeberBuilderExtension() { // Nothing to do here } + + @SuppressWarnings("nls") + private static void generateArduinoSizeCommandFile(IAutoBuildConfigurationDescription autoBuildConfData) { + IFile sizeCommandIFile = autoBuildConfData.getBuildFolder().getFile(ARDUINO_SIZE ); + SloeberConfiguration confDesc = SloeberConfiguration.getFromAutoBuildConfDesc(autoBuildConfData); + + File sizeCommandFile = sizeCommandIFile.getLocation().toFile(); + String content = Common.getBuildEnvironmentVariable(confDesc, "sloeber.size_command.awk", EMPTY); + + try { + if (sizeCommandFile.exists()) { + String curContent = FileUtils.readFileToString(sizeCommandFile, Charset.defaultCharset()); + if (!curContent.equals(content)) { + sizeCommandFile.delete(); + } + } + if (!sizeCommandFile.exists()) { + FileUtils.write(sizeCommandFile, content, Charset.defaultCharset()); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + @SuppressWarnings("nls") private static void generateAwkFile(IAutoBuildConfigurationDescription autoBuildConfData) { IFile sizeAwkFile1 = autoBuildConfData.getBuildFolder().getFile("size.awk"); @@ -144,7 +173,15 @@ private static void generateAwkFile(IAutoBuildConfigurationDescription autoBuild awkContent += "\"}"; try { - FileUtils.write(sizeAwkFile, awkContent, Charset.defaultCharset()); + if (sizeAwkFile.exists()) { + String curContent = FileUtils.readFileToString(sizeAwkFile, Charset.defaultCharset()); + if (!curContent.equals(awkContent)) { + sizeAwkFile.delete(); + } + } + if (!sizeAwkFile.exists()) { + FileUtils.write(sizeAwkFile, awkContent, Charset.defaultCharset()); + } } catch (IOException e) { e.printStackTrace(); } diff --git a/io.sloeber.core/src/io/sloeber/core/common/InstancePreferences.java b/io.sloeber.core/src/io/sloeber/core/common/InstancePreferences.java index 55b59a48c..329509276 100644 --- a/io.sloeber.core/src/io/sloeber/core/common/InstancePreferences.java +++ b/io.sloeber.core/src/io/sloeber/core/common/InstancePreferences.java @@ -10,7 +10,7 @@ import org.eclipse.core.runtime.preferences.InstanceScope; import org.osgi.service.prefs.BackingStoreException; -import io.sloeber.core.api.Common; +import io.sloeber.core.Activator; import io.sloeber.core.api.Defaults; /** @@ -28,6 +28,7 @@ public class InstancePreferences { private static final String KEY_PRAGMA_ONCE_HEADER = "add pragma once to headers"; //$NON-NLS-1$ private static final String KEY_USE_ARDUINO_TOOLS_SELECTION_ALGORITHM="Use the algoritm to find the toolchain like Arduino IDE"; //$NON-NLS-1$ private static final String KEY_USE_BONJOUR="use bonjour service to find devices"; //$NON-NLS-1$ + private static final String KEY_INSTALL_LIBRARIES= "download and install libraries on usage"; //$NON-NLS-1$ /** * Give back the user option if the libraries need to be added or not @@ -60,7 +61,7 @@ public static void setGlobalValue(String key, String value) { try { myScope.flush(); } catch (BackingStoreException e) { - Common.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, "failed to set global variable of type string " + key,e)); //$NON-NLS-1$ } } @@ -73,7 +74,7 @@ private static void setValue(String key, boolean value) { try { myScope.flush(); } catch (BackingStoreException e) { - Common.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, "failed to set global variable of type boolean " + key,e)); //$NON-NLS-1$ } } @@ -141,4 +142,12 @@ public static boolean useBonjour() { public static void setUseBonjour(boolean newFlag) { setValue(KEY_USE_BONJOUR, newFlag); } + + public static void setInstallLibraries(boolean selection) { + setValue(KEY_INSTALL_LIBRARIES, selection); + } + + public static boolean getInstallLibraries() { + return getBoolean(KEY_INSTALL_LIBRARIES, Defaults.INSTALL_LIBRARIES); + } } diff --git a/io.sloeber.core/src/io/sloeber/core/communication/ArduinoSerial.java b/io.sloeber.core/src/io/sloeber/core/communication/ArduinoSerial.java index 6fc2b2e8d..a111d46a5 100644 --- a/io.sloeber.core/src/io/sloeber/core/communication/ArduinoSerial.java +++ b/io.sloeber.core/src/io/sloeber/core/communication/ArduinoSerial.java @@ -11,7 +11,8 @@ import org.eclipse.core.runtime.Status; import org.eclipse.ui.console.MessageConsoleStream; -import io.sloeber.core.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.core.Activator; import io.sloeber.core.api.ISloeberConfiguration; import io.sloeber.core.api.Serial; @@ -43,7 +44,7 @@ public static boolean reset_Arduino_by_baud_rate(String comPort, int baudRate, l serialPort.dispose(); Thread.sleep(openTime); } catch (Exception e) { - log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, ArduinoSerial_unable_to_open_serial_port.replace(PORT_TAG, comPort), e)); return false; } diff --git a/io.sloeber.core/src/io/sloeber/core/core/DefaultInstallHandler.java b/io.sloeber.core/src/io/sloeber/core/core/DefaultInstallHandler.java index e08b8a30b..687b3edf1 100644 --- a/io.sloeber.core/src/io/sloeber/core/core/DefaultInstallHandler.java +++ b/io.sloeber.core/src/io/sloeber/core/core/DefaultInstallHandler.java @@ -2,7 +2,7 @@ import java.util.Map; -import io.sloeber.core.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; import io.sloeber.core.api.IInstallLibraryHandler; public class DefaultInstallHandler implements IInstallLibraryHandler { diff --git a/io.sloeber.core/src/io/sloeber/core/eclipseIntegrations/CDT_EnvironmentVariableResolver.java b/io.sloeber.core/src/io/sloeber/core/eclipseIntegrations/CDT_EnvironmentVariableResolver.java index 19c818425..9b8eb2c78 100644 --- a/io.sloeber.core/src/io/sloeber/core/eclipseIntegrations/CDT_EnvironmentVariableResolver.java +++ b/io.sloeber.core/src/io/sloeber/core/eclipseIntegrations/CDT_EnvironmentVariableResolver.java @@ -1,7 +1,5 @@ package io.sloeber.core.eclipseIntegrations; -import static io.sloeber.core.api.Const.*; - import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.envvar.IEnvironmentVariableManager; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; @@ -18,6 +16,7 @@ import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; +import io.sloeber.core.Activator; import io.sloeber.core.Messages; public class CDT_EnvironmentVariableResolver implements IDynamicVariableResolver { @@ -29,7 +28,7 @@ public String resolveValue(IDynamicVariable variable, String varName) throws Cor return getBuildEnvironmentVariable(confDesc, varName); } catch ( Exception e) { - Status iStatus = new Status(IStatus.ERROR, PLUGIN_ID, Messages.projectNotFoundInGUI,e); + Status iStatus = new Status(IStatus.ERROR, Activator.getId(), Messages.projectNotFoundInGUI,e); throw new CoreException(iStatus); } } diff --git a/io.sloeber.core/src/io/sloeber/core/internal/ArduinoHardwareLibrary.java b/io.sloeber.core/src/io/sloeber/core/internal/ArduinoHardwareLibrary.java index ed8f2a21a..12ce9efb1 100644 --- a/io.sloeber.core/src/io/sloeber/core/internal/ArduinoHardwareLibrary.java +++ b/io.sloeber.core/src/io/sloeber/core/internal/ArduinoHardwareLibrary.java @@ -2,12 +2,16 @@ import static io.sloeber.core.api.Const.*; +import java.util.List; + import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; -import io.sloeber.core.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.IArduinoLibrary; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; import io.sloeber.core.api.Common; -import io.sloeber.core.api.IArduinoLibraryVersion; +import io.sloeber.core.api.VersionNumber; public class ArduinoHardwareLibrary implements IArduinoLibraryVersion { private IPath myInstallPath; @@ -17,7 +21,7 @@ public class ArduinoHardwareLibrary implements IArduinoLibraryVersion { public ArduinoHardwareLibrary(IPath installPath) { myInstallPath = installPath; myName = myInstallPath.lastSegment(); - calculateFQN(); + myFQN=calculateFQN(getName()); } public ArduinoHardwareLibrary(String curSaveString, BoardDescription boardDesc) { @@ -27,7 +31,7 @@ public ArduinoHardwareLibrary(String curSaveString, BoardDescription boardDesc) if(!myInstallPath.toFile().exists()) { myInstallPath=boardDesc.getReferencedCoreLibraryPath().append(myName); } - calculateFQN(); + myFQN=calculateFQN(getName()); } @Override @@ -60,9 +64,8 @@ public IPath getExamplePath() { } - private void calculateFQN() { - myFQN= Path.fromPortableString(SLOEBER_LIBRARY_FQN); - myFQN= myFQN.append(BOARD).append(getName()); + public static IPath calculateFQN(String libName) { + return Path.fromPortableString(SLOEBER_LIBRARY_FQN).append(BOARD).append(libName); } @Override @@ -80,4 +83,50 @@ public boolean equals(IArduinoLibraryVersion other) { return myFQN.equals(other.getFQN()); } + @Override + public int compareTo(IArduinoLibraryVersion o) { + return 0; + } + + @Override + public IArduinoLibrary getLibrary() { + return null; + } + + @Override + public VersionNumber getVersion() { + return null; + } + + @Override + public boolean isInstalled() { + return true; + } + + @Override + public List getArchitectures() { + return null; + } + + @Override + public String getParagraph() { + return EMPTY_STRING; + } + + @Override + public String getSentence() { + return EMPTY_STRING; + } + + @Override + public String getMaintainer() { + return "Maintainer is board provider"; //$NON-NLS-1$ + } + + @Override + public String getAuthor() { + // TODO Auto-generated method stub + return "Author is board provider"; //$NON-NLS-1$ + } + } diff --git a/io.sloeber.core/src/io/sloeber/core/internal/ArduinoPrivateLibraryVersion.java b/io.sloeber.core/src/io/sloeber/core/internal/ArduinoPrivateHardwareLibraryVersion.java similarity index 53% rename from io.sloeber.core/src/io/sloeber/core/internal/ArduinoPrivateLibraryVersion.java rename to io.sloeber.core/src/io/sloeber/core/internal/ArduinoPrivateHardwareLibraryVersion.java index 6c4ff16fe..dc7a40997 100644 --- a/io.sloeber.core/src/io/sloeber/core/internal/ArduinoPrivateLibraryVersion.java +++ b/io.sloeber.core/src/io/sloeber/core/internal/ArduinoPrivateHardwareLibraryVersion.java @@ -2,27 +2,31 @@ import static io.sloeber.core.api.Const.*; +import java.util.List; + import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; -import io.sloeber.core.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IArduinoLibrary; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.core.api.VersionNumber; import io.sloeber.core.common.InstancePreferences; -public class ArduinoPrivateLibraryVersion implements IArduinoLibraryVersion { +public class ArduinoPrivateHardwareLibraryVersion implements IArduinoLibraryVersion { private IPath myInstallPath; private String myName; private IPath myFQN; - public ArduinoPrivateLibraryVersion(IPath installPath) { + public ArduinoPrivateHardwareLibraryVersion(IPath installPath) { myInstallPath = installPath; myName = myInstallPath.lastSegment(); - calcFQN(); + myFQN= calculateFQN(getName()); } - public ArduinoPrivateLibraryVersion(String curSaveString) { + public ArduinoPrivateHardwareLibraryVersion(String curSaveString) { String[] parts=curSaveString.split(SEMI_COLON); myName=parts[parts.length-1]; - calcFQN(); + myFQN= calculateFQN(getName()); String privateLibPaths[] = InstancePreferences.getPrivateLibraryPaths(); for (String curLibPath : privateLibPaths) { Path curPrivPath=new Path(curLibPath); @@ -63,9 +67,8 @@ public IPath getExamplePath() { return getInstallPath().append(EXAMPLES_FOLDER); } - private void calcFQN() { - myFQN= Path.fromPortableString(SLOEBER_LIBRARY_FQN); - myFQN= myFQN.append(PRIVATE).append(getName()); + static public IPath calculateFQN(String libName) { + return Path.fromPortableString(SLOEBER_LIBRARY_FQN).append(PRIVATE).append(libName); } @Override @@ -83,4 +86,49 @@ public boolean equals(IArduinoLibraryVersion other) { return myFQN.equals(other.getFQN()); } + @Override + public int compareTo(IArduinoLibraryVersion o) { + return 0; + } + + @Override + public IArduinoLibrary getLibrary() { + return null; + } + + @Override + public VersionNumber getVersion() { + return null; + } + + @Override + public boolean isInstalled() { + return true; + } + + @Override + public List getArchitectures() { + return null; + } + + @Override + public String getParagraph() { + return EMPTY_STRING; + } + + @Override + public String getSentence() { + return EMPTY_STRING; + } + + @Override + public String getMaintainer() { + return "unknown maintainer (private lib)"; //$NON-NLS-1$ + } + + @Override + public String getAuthor() { + return "unknown author (private lib)"; //$NON-NLS-1$ + } + } diff --git a/io.sloeber.core/src/io/sloeber/core/internal/Example.java b/io.sloeber.core/src/io/sloeber/core/internal/Example.java index 45b95554f..ba0e8c090 100644 --- a/io.sloeber.core/src/io/sloeber/core/internal/Example.java +++ b/io.sloeber.core/src/io/sloeber/core/internal/Example.java @@ -9,9 +9,9 @@ import java.util.HashMap; import java.util.Map; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IExample; import io.sloeber.core.api.ConfigurationPreferences; -import io.sloeber.core.api.IArduinoLibraryVersion; -import io.sloeber.core.api.IExample; public class Example implements IExample { protected IPath myFQN; @@ -45,7 +45,7 @@ private void calculateFQN() { } } else { for (IArduinoLibraryVersion myLib : myLibs.values()) { - myFQN = myLib.getFQN().append(getName()); + myFQN = myLib.getFQN().append( myExampleLocation.makeRelativeTo(myLib.getExamplePath())); } } } diff --git a/io.sloeber.core/src/io/sloeber/core/internal/SloeberConfiguration.java b/io.sloeber.core/src/io/sloeber/core/internal/SloeberConfiguration.java index d61d969b3..8e76dc6ef 100644 --- a/io.sloeber.core/src/io/sloeber/core/internal/SloeberConfiguration.java +++ b/io.sloeber.core/src/io/sloeber/core/internal/SloeberConfiguration.java @@ -1,19 +1,23 @@ package io.sloeber.core.internal; +import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import static io.sloeber.core.api.Common.*; import static io.sloeber.core.api.Const.*; +import org.eclipse.cdt.core.settings.model.CSourceEntry; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.cdt.core.settings.model.ICSourceEntry; import org.eclipse.cdt.core.settings.model.extension.CConfigurationData; +import org.eclipse.cdt.core.settings.model.util.CDataUtil; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; @@ -25,9 +29,13 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.autoBuild.api.AutoBuildConfigurationExtensionDescription; import io.sloeber.autoBuild.api.AutoBuildProject; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; @@ -35,10 +43,8 @@ import io.sloeber.autoBuild.integration.AutoBuildConfigurationDescription; import io.sloeber.core.Activator; import io.sloeber.core.Messages; -import io.sloeber.core.api.BoardDescription; import io.sloeber.core.api.CompileDescription; import io.sloeber.core.api.ConfigurationPreferences; -import io.sloeber.core.api.IArduinoLibraryVersion; import io.sloeber.core.api.ISloeberConfiguration; import io.sloeber.core.api.OtherDescription; import io.sloeber.core.tools.Helpers; @@ -49,27 +55,27 @@ public class SloeberConfiguration extends AutoBuildConfigurationExtensionDescrip private BoardDescription myBoardDescription; private OtherDescription myOtherDesc; private CompileDescription myCompileDescription; - private Map myLibraries = new HashMap<>(); + // a map of foldername library + private Map myLibraries = new HashMap<>(); // operational data private boolean myMemoryIsDirty = true; // derived data private Map myEnvironmentVariables = new HashMap<>(); + public static SloeberConfiguration getFromAutoBuildConfDesc(IAutoBuildConfigurationDescription autoBuildConfData) { return (SloeberConfiguration) autoBuildConfData.getAutoBuildConfigurationExtensionDescription(); } public static SloeberConfiguration getConfig(ICConfigurationDescription cConfigDesc) { - CConfigurationData confData=cConfigDesc.getConfigurationData(); - if(confData instanceof IAutoBuildConfigurationDescription) { + CConfigurationData confData = cConfigDesc.getConfigurationData(); + if (confData instanceof IAutoBuildConfigurationDescription) { return (SloeberConfiguration) ((IAutoBuildConfigurationDescription)confData).getAutoBuildConfigurationExtensionDescription(); } return null; } - - /** * copy constructor This constructor must be implemented for each derived class * of AutoBuildConfigurationExtensionDescription or you will get run time errors @@ -89,7 +95,7 @@ public SloeberConfiguration(AutoBuildConfigurationDescription owner, setBoardDescription(src.getBoardDescription()); setOtherDescription(src.getOtherDescription()); setCompileDescription(src.getCompileDescription()); - myLibraries = src.myLibraries; + myLibraries = src.getLibrariesFromLinks(); } public SloeberConfiguration(BoardDescription boardDesc, OtherDescription otherDesc, @@ -99,8 +105,6 @@ public SloeberConfiguration(BoardDescription boardDesc, OtherDescription otherDe setCompileDescription(compileDescriptor); } - - @Override public BoardDescription getBoardDescription() { return new BoardDescription(myBoardDescription); @@ -141,22 +145,18 @@ public void copyData(AutoBuildConfigurationExtensionDescription from) { } @Override - public void serialize(KeyValueTree keyValuePairs) { - Map envVars = myBoardDescription.getEnvVarsConfig(); - envVars.putAll(myOtherDesc.getEnvVarsConfig()); - envVars.putAll(myCompileDescription.getEnvVarsConfig()); - for (Entry curEnvVar : envVars.entrySet()) { - keyValuePairs.addValue( curEnvVar.getKey() , curEnvVar.getValue() ); - } + public void serialize(KeyValueTree serialize) { + myBoardDescription.serialize(serialize); + myOtherDesc.serialize(serialize); + myCompileDescription.serialize(serialize); configureWhenDirty(); } public SloeberConfiguration(IAutoBuildConfigurationDescription autoCfgDescription, KeyValueTree keyValues) { setAutoBuildDescription(autoCfgDescription); - Map envVars =keyValues.toKeyValues(false); - myBoardDescription = new BoardDescription(envVars); - myOtherDesc = new OtherDescription(envVars); - myCompileDescription = new CompileDescription(envVars); + myBoardDescription = new BoardDescription(keyValues); + myOtherDesc = new OtherDescription(keyValues); + myCompileDescription = new CompileDescription(keyValues); myMemoryIsDirty = true; // configure(); Seems I can not do the config here } @@ -167,25 +167,30 @@ public IProject getProject() { } @Override - public IFolder getArduinoCodeFolder() { - String cdtConfDescName = getAutoBuildDescription().getCdtConfigurationDescription().getName(); + public IFolder getArduinoRootFolder() { IProject project = getProject(); - return project.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getFolder(cdtConfDescName); + return project.getFolder(SLOEBER_ARDUINO_FOLDER_NAME); + } + + @Override + public IFolder getArduinoConfigurationFolder() { + String cdtConfDescName = getCDTConfName(); + return getArduinoRootFolder().getFolder(cdtConfDescName); } @Override public IFolder getArduinoCoreFolder() { - return getArduinoCodeFolder().getFolder(SLOEBER_CODE_FOLDER_NAME); + return getArduinoConfigurationFolder().getFolder(SLOEBER_CODE_FOLDER_NAME); } @Override public IFolder getArduinoVariantFolder() { - return getArduinoCodeFolder().getFolder(SLOEBER_VARIANT_FOLDER_NAME); + return getArduinoConfigurationFolder().getFolder(SLOEBER_VARIANT_FOLDER_NAME); } @Override public IFolder getArduinoLibraryFolder() { - return getArduinoCodeFolder().getFolder(SLOEBER_LIBRARY_FOLDER_NAME); + return getArduinoConfigurationFolder().getFolder(SLOEBER_LIBRARY_FOLDER_NAME); } @Override @@ -202,19 +207,23 @@ private void configureWhenDirty() { } - private void LinkToCore() { + /* Update the links to the Arduino stuff + * Return true if the project needs a refresh + */ + private boolean LinkToCore() { if (!ResourcesPlugin.getWorkspace().isTreeLocked()) { if (projectNeedsUpdate()) { updateArduinoCodeLinks(); + return true; } } + return false; } - private boolean projectNeedsUpdate() { IPath corePath = myBoardDescription.getActualCoreCodePath(); IFolder coreFolder = getArduinoCoreFolder(); - if (! corePath.equals(coreFolder.getLocation())) { + if (!corePath.equals(coreFolder.getLocation())) { // System.out.println("projectNeedsUpdate core Folder mismatch"); // System.out.println("corefolder "+coreFolder.getLocation()); // System.out.println("corePath "+corePath); @@ -222,7 +231,7 @@ private boolean projectNeedsUpdate() { } IFolder arduinoVariantFolder = getArduinoVariantFolder(); IPath variantPath = myBoardDescription.getActualVariantPath(); - if(variantPath==null) { + if (variantPath == null) { return arduinoVariantFolder.exists(); } if ((!variantPath.toFile().exists()) && (arduinoVariantFolder.exists())) { @@ -239,69 +248,88 @@ private boolean projectNeedsUpdate() { return false; } - - /** * get the environment variables that do not reliy on variable expansion to get the value. * @return true when data was missing */ private boolean getEnvVarsNonExpanding() { - myEnvironmentVariables.clear(); + myEnvironmentVariables.clear(); - myEnvironmentVariables.put(ENV_KEY_BUILD_PATH, - getProject().getFolder(getAutoBuildDescription().getBuildFolderString()).getLocation().toOSString()); + myEnvironmentVariables.put(ENV_KEY_BUILD_PATH, + getProject().getFolder(getAutoBuildDescription().getBuildFolderString()).getLocation().toOSString()); - myEnvironmentVariables.put(ENV_KEY_BUILD_SOURCE_PATH,getCodeLocation().toOSString()); + myEnvironmentVariables.put(ENV_KEY_BUILD_SOURCE_PATH, getCodeLocation().toOSString()); // myEnvironmentVariables.put(ENV_KEY_BUILD_PATH, // getAutoBuildDescription().getBuildFolder().getLocation().toOSString()); - if (myBoardDescription != null) { - myEnvironmentVariables.putAll(myBoardDescription.getEnvVars()); - } - if (myCompileDescription != null) { - myEnvironmentVariables.putAll(myCompileDescription.getEnvVars()); - } - if (myOtherDesc != null) { - myEnvironmentVariables.putAll(myOtherDesc.getEnvVars()); - } - // set the paths - String pathDelimiter = makeEnvironmentVar("PathDelimiter"); //$NON-NLS-1$ - if (isWindows) { - myEnvironmentVariables.put(SLOEBER_MAKE_LOCATION, - ConfigurationPreferences.getMakePath().addTrailingSeparator().toOSString()); - myEnvironmentVariables.put(SLOEBER_AWK_LOCATION, - ConfigurationPreferences.getAwkPath().addTrailingSeparator().toOSString()); - - String systemroot = makeEnvironmentVar("SystemRoot"); //$NON-NLS-1$ - myEnvironmentVariables.put("PATH", //$NON-NLS-1$ - makeEnvironmentVar(ENV_KEY_COMPILER_PATH) + pathDelimiter + if (myBoardDescription != null) { + myEnvironmentVariables.putAll(myBoardDescription.getEnvVars()); + } + if (myCompileDescription != null) { + myEnvironmentVariables.putAll(myCompileDescription.getEnvVars()); + } + if (myOtherDesc != null) { + myEnvironmentVariables.putAll(myOtherDesc.getEnvVars()); + } + // set the paths + String pathDelimiter = makeEnvironmentVar("PathDelimiter"); //$NON-NLS-1$ + if (isWindows) { + myEnvironmentVariables.put(SLOEBER_MAKE_LOCATION, + ConfigurationPreferences.getMakePath().addTrailingSeparator().toOSString()); + myEnvironmentVariables.put(SLOEBER_AWK_LOCATION, + ConfigurationPreferences.getAwkPath().addTrailingSeparator().toOSString()); + + String systemroot = makeEnvironmentVar("SystemRoot"); //$NON-NLS-1$ + myEnvironmentVariables.put("PATH", //$NON-NLS-1$ + makeEnvironmentVar(ENV_KEY_COMPILER_PATH) + pathDelimiter + makeEnvironmentVar(ENV_KEY_BUILD_GENERIC_PATH) + pathDelimiter + systemroot + "\\system32" //$NON-NLS-1$ - + pathDelimiter + systemroot + pathDelimiter + systemroot + "\\system32\\Wbem" //$NON-NLS-1$ - + pathDelimiter + makeEnvironmentVar("sloeber_path_extension")); //$NON-NLS-1$ - } else { - myEnvironmentVariables.put("PATH", makeEnvironmentVar(ENV_KEY_COMPILER_PATH) + pathDelimiter //$NON-NLS-1$ - + makeEnvironmentVar(ENV_KEY_BUILD_GENERIC_PATH) + pathDelimiter + makeEnvironmentVar("PATH")); //$NON-NLS-1$ - } - return (myBoardDescription == null) || (myCompileDescription == null)|| (myOtherDesc == null); + + pathDelimiter + systemroot + pathDelimiter + systemroot + "\\system32\\Wbem" //$NON-NLS-1$ + + pathDelimiter + makeEnvironmentVar("sloeber_path_extension")); //$NON-NLS-1$ + } else { + myEnvironmentVariables.put("PATH", makeEnvironmentVar(ENV_KEY_COMPILER_PATH) + pathDelimiter //$NON-NLS-1$ + + makeEnvironmentVar(ENV_KEY_BUILD_GENERIC_PATH) + pathDelimiter + makeEnvironmentVar("PATH")); //$NON-NLS-1$ + } + return (myBoardDescription == null) || (myCompileDescription == null) || (myOtherDesc == null); } private IPath getCodeLocation() { IProject project = getProject(); - IPath arduinoPath=project.getFolder(SLOEBER_ARDUINO_FOLDER_NAME).getFullPath(); + IPath arduinoPath = getArduinoRootFolder().getFullPath(); ICSourceEntry[] sourceEntries = getAutoBuildDesc().getCdtConfigurationDescription().getSourceEntries(); for (ICSourceEntry curEntry : sourceEntries) { - IPath entryPath=curEntry.getFullPath(); - if (arduinoPath.isPrefixOf( entryPath)) { - //this is the arduino code folder: ignore + IPath entryPath = curEntry.getFullPath(); + if (arduinoPath.isPrefixOf(entryPath)) { + // this is the arduino code folder: ignore continue; } - //Just pick the first none arduino one as there should only be one - return curEntry.getLocation(); + // Just pick the first none arduino one as there should only be one + return getLocation(curEntry); } return project.getLocation(); } + /** + * workaround code because ICSourceEntry.getLocation returns null if the + * resolved flag is not set moreover the resolved flag is not set when adding a + * source location via the gui Therefore one can not convert from root to src + * based projects because the manually added src is not marked as resolved This + * code is the same as ICSourceEntry.getLocation except for it assumes the + * resolved flag is set + * + * @param entry + * @return + */ + private static IPath getLocation(ICSourceEntry entry) { + if (!entry.isValueWorkspacePath()) + return new Path(entry.getValue()); + IPath path = new Path(entry.getValue()); + IResource rc = ResourcesPlugin.getWorkspace().getRoot().findMember(path); + if (rc != null) + return rc.getLocation(); + return null; + } + /** * get the text for the decorator * @@ -435,17 +463,24 @@ public IAutoBuildConfigurationDescription getAutoBuildDesc() { * */ private void updateArduinoCodeLinks() { - IPath corePath = myBoardDescription.getActualCoreCodePath(); + IFolder arduinoVariantFolder = getArduinoVariantFolder(); + IFolder arduinoCodeFolder = getArduinoCoreFolder(); + NullProgressMonitor monitor = new NullProgressMonitor(); + try { + arduinoVariantFolder.delete(true, monitor); + arduinoCodeFolder.delete(true, monitor); + } catch (CoreException e) { + // ignore exception + e.printStackTrace(); + } + IPath corePath = myBoardDescription.getActualCoreCodePath(); if (corePath != null) { - Helpers.LinkFolderToFolder(corePath, getArduinoCoreFolder()); - IPath variantPath = myBoardDescription.getActualVariantPath(); - if ((variantPath == null) || (!variantPath.toFile().exists())) { - // remove the existing link - Helpers.removeCodeFolder(arduinoVariantFolder); - } else { - Helpers.LinkFolderToFolder(variantPath, arduinoVariantFolder); - } + Helpers.LinkFolderToFolder(corePath, arduinoCodeFolder); + } + IPath variantPath = myBoardDescription.getActualVariantPath(); + if (variantPath != null) { + Helpers.LinkFolderToFolder(variantPath, arduinoVariantFolder); } } @@ -453,9 +488,9 @@ private void updateArduinoCodeLinks() { public Set getIncludeFolders() { Set ret = new HashSet<>(); ret.add(getArduinoCoreFolder()); - if (myBoardDescription.getActualVariantPath() != null) { - ret.add(getArduinoVariantFolder()); - } + if (myBoardDescription.getActualVariantPath() != null) { + ret.add(getArduinoVariantFolder()); + } try { if (getArduinoLibraryFolder().exists()) { for (IResource curMember : getArduinoLibraryFolder().members()) { @@ -476,17 +511,143 @@ public Set getIncludeFolders() { return ret; } + /** + * Get all the libraries that are linked to on disk + * + * @return + * @throws CoreException + */ + private Map getLibrariesFromLinks() { + Map ret = new HashMap<>(); + IFolder libFolder = getArduinoLibraryFolder(); + if (!libFolder.exists()) { + return ret; + } + try { + for (IResource curResource : libFolder.members()) { + if (curResource instanceof IFolder) { + IFolder curFolder = (IFolder) curResource; + IArduinoLibraryVersion curLib=null; + for(IArduinoLibraryVersion curknowLib: myLibraries.values()) { + if(curknowLib.getName().equals(curFolder.getName())){ + curLib=curknowLib; + continue; + } + } + if (curLib != null) { + // We know the lib so it is ok + ret.put(curLib.getFQN(), curLib); + continue; + } + + curLib = LibraryManager.getLibraryVersionFromLocation(curFolder, getBoardDescription()); + if (curLib != null) { + ret.put(curLib.getFQN(), curLib); + } + } + } + } catch (CoreException e) { + e.printStackTrace(); + ret.putAll(myLibraries); + } + return ret; + } + + /** + * remove the links from the libraries on disk + * + */ + private void removeLibraryLinks() { + IProgressMonitor monitor = new NullProgressMonitor(); + IFolder libFolder = getArduinoLibraryFolder(); + for (IArduinoLibraryVersion curLib : myLibraries.values()) { + IFolder curLibFolder = libFolder.getFolder(curLib.getName()); + if (curLibFolder.exists()) { + try { + curLibFolder.delete(true, monitor); + } catch (CoreException e) { + // ignore exception + e.printStackTrace(); + } + } + } + } + + /** + * remove the links from the libraries on disk + * + */ + private void linkLibrariesToFolder() { + IFolder libFolder = getArduinoLibraryFolder(); + for (IArduinoLibraryVersion curLib : myLibraries.values()) { + IFolder curLibFolder = libFolder.getFolder(curLib.getName()); + Helpers.LinkFolderToFolder(curLib.getInstallPath(), curLibFolder); + } + } + + /** + * For libraries of with FQN Libraries/hardware/X make sure that the location + * point to a valid location of the given boardDescriptor + */ + private void upDateHardwareLibraries() { + // make sure the libraries that link to hardware are the correct ones + BoardDescription boardDesc = getBoardDescription(); + IPath referenceLibPath = boardDesc.getReferencedCoreLibraryPath(); + IPath referencingLibPath = boardDesc.getReferencingLibraryPath(); + if (referencingLibPath == null) { + referencingLibPath = referenceLibPath; + } + Set hardwareLibsFQN = new HashSet<>(); + for (IArduinoLibraryVersion curLib : myLibraries.values()) { + if (curLib.isHardwareLib()) { + IPath libPath = curLib.getInstallPath(); + if (referencingLibPath.isPrefixOf(libPath) || referenceLibPath.isPrefixOf(libPath)) { + // the hardware lib is ok + continue; + } + // The hardware lib is for a different hardware. + // add it to the lists to reattach + hardwareLibsFQN.add(curLib.getFQN()); + } + } + if (!hardwareLibsFQN.isEmpty()) { + Map boardLibs = LibraryManager.getLibrariesHarware(boardDesc,true); + for (IPath curReplaceLibFQN : hardwareLibsFQN) { + IArduinoLibraryVersion newLib = boardLibs.get(curReplaceLibFQN.toPortableString()); + if (newLib != null) { + // a library with the same name was found so use this one + myLibraries.put(newLib.getFQN(), newLib); + } else { + // no new library was found remove the old lib + myLibraries.remove(curReplaceLibFQN); + } + } + } + } + @Override public void reAttachLibraries() { + upDateHardwareLibraries(); + IProgressMonitor monitor = new NullProgressMonitor(); IFolder libFolder = getArduinoLibraryFolder(); // Remove all existing lib folders that are not known or are linking to the // wrong lib try { + if (!libFolder.exists()) { + libFolder.create(true, true, new NullProgressMonitor()); + } for (IResource curResource : libFolder.members()) { if (curResource instanceof IFolder) { IFolder curFolder = (IFolder) curResource; - IArduinoLibraryVersion curLib = myLibraries.get(curFolder.getName()); + + IArduinoLibraryVersion curLib =null; + for(IArduinoLibraryVersion curknowLib: myLibraries.values()) { + if(curknowLib.getName().equals(curFolder.getName())){ + curLib=curknowLib; + } + } + if ((curLib == null) || (!curLib.getInstallPath().equals(curFolder.getLocation()))) { try { curFolder.delete(true, monitor); @@ -510,34 +671,72 @@ public void reAttachLibraries() { } @Override - public Map getUsedLibraries() { + public Map getUsedLibraries() { + myLibraries = getLibrariesFromLinks(); return new HashMap<>(myLibraries); } @Override public boolean addLibraries(Collection librartiesToAdd) { - boolean ret = false; + if (librartiesToAdd == null || librartiesToAdd.isEmpty()) { + return false; + } + List foldersToRemoveFromBuildPath = new LinkedList<>(); IFolder libFolder = getArduinoLibraryFolder(); + ICConfigurationDescription confdesc = getAutoBuildDesc().getCdtConfigurationDescription(); + ICSourceEntry[] sourceEntries = confdesc.getSourceEntries(); for (IArduinoLibraryVersion curLib : librartiesToAdd) { if (curLib == null) { continue; } - Helpers.LinkFolderToFolder(curLib.getInstallPath(), libFolder.getFolder(curLib.getName())); - myLibraries.put(curLib.getName(), curLib); - ret = true; + IFolder newLibFolder = libFolder.getFolder(curLib.getName()); + Helpers.LinkFolderToFolder(curLib.getInstallPath(), newLibFolder); + myLibraries.put(curLib.getFQN(), curLib); + + // exclude bad folders + File[] subFolders; + subFolders = curLib.getInstallPath().toFile().listFiles(); + + for (File subFolder : subFolders) { + if (subFolder.isFile()) { + continue; + } + String curName = subFolder.getName(); + if ("src".equals(curName)) { //$NON-NLS-1$ + continue; + } + IFolder curFolder = newLibFolder.getFolder(curName); + if (CDataUtil.isExcluded(curFolder.getFullPath(), sourceEntries)) { + continue; + } + foldersToRemoveFromBuildPath.add(curFolder); + } } - return ret; + if (foldersToRemoveFromBuildPath.isEmpty()) { + return false; + } + try { + for (IResource subFolder : foldersToRemoveFromBuildPath) { + sourceEntries = CDataUtil.setExcluded(subFolder.getFullPath(), true, true, sourceEntries); + } + confdesc.setSourceEntries(sourceEntries); + } catch (CoreException e) { + // ignore error + e.printStackTrace(); + } + return true; } + @Override public boolean removeLibraries(Collection librariesToRemove) { boolean ret = false; IProgressMonitor monitor = new NullProgressMonitor(); IFolder libFolder = getArduinoLibraryFolder(); for (IArduinoLibraryVersion curLib : librariesToRemove) { - if (myLibraries.containsKey(curLib.getName())) { + if (myLibraries.containsKey(curLib.getFQN())) { ret = true; - myLibraries.remove(curLib.getName()); + myLibraries.remove(curLib.getFQN()); try { libFolder.getFolder(curLib.getName()).delete(true, monitor); } catch (CoreException e) { @@ -557,26 +756,24 @@ public void setLibraries(Set selectedLibraries) { @Override public Set getTeamDefaultExclusionKeys(String name) { - Set ret=new HashSet<>(); - ret.add(name+DOT+KEY_SLOEBER_UPLOAD_PORT); + Set ret = new HashSet<>(); + ret.add(name + DOT + KEY_SLOEBER_UPLOAD_PORT); return ret; } @Override public boolean equals(AutoBuildConfigurationExtensionDescription base) { - if(!(base instanceof SloeberConfiguration)) { + if (!(base instanceof SloeberConfiguration)) { return false; } - SloeberConfiguration other=(SloeberConfiguration)base; + SloeberConfiguration other = (SloeberConfiguration) base; if( myBoardDescription.equals(other.myBoardDescription) && myOtherDesc.equals(other.myOtherDesc) && myCompileDescription.equals(other.myCompileDescription) && myLibraries.size()==other.myLibraries.size()) { - for(Entry curLib:myLibraries.entrySet()) { - String key=curLib.getKey(); - IArduinoLibraryVersion localValue=curLib.getValue(); - IArduinoLibraryVersion otherValue=other.myLibraries.get(key); - if(!localValue.equals(otherValue)) { + for ( IArduinoLibraryVersion localValue : myLibraries.values()) { + IArduinoLibraryVersion otherValue = other.myLibraries.get(localValue.getFQN()); + if (!localValue.equals(otherValue)) { return false; } } @@ -587,25 +784,110 @@ public boolean equals(AutoBuildConfigurationExtensionDescription base) { @Override public LinkedHashMap getPrebuildSteps() { - LinkedHashMap ret=new LinkedHashMap<>(); - LinkedHashSet hookNamess=new LinkedHashSet<>(); + LinkedHashMap ret = new LinkedHashMap<>(); + LinkedHashSet hookNamess = new LinkedHashSet<>(); hookNamess.add("prebuild"); //$NON-NLS-1$ - ret.putAll(myBoardDescription.getHookSteps(hookNamess,getAutoBuildDescription())); + ret.putAll(myBoardDescription.getHookSteps(hookNamess, getAutoBuildDescription())); return ret; } @Override public LinkedHashMap getPostbuildSteps() { - LinkedHashMap ret=new LinkedHashMap<>(); - LinkedHashSet hookNamess=new LinkedHashSet<>(); + LinkedHashMap ret = new LinkedHashMap<>(); + LinkedHashSet hookNamess = new LinkedHashSet<>(); hookNamess.add("postbuild"); //$NON-NLS-1$ - ret.putAll(myBoardDescription.getHookSteps(hookNamess,getAutoBuildDescription())); + ret.putAll(myBoardDescription.getHookSteps(hookNamess, getAutoBuildDescription())); return ret; } - public void apply() { - configureWhenDirty() ; + /** + * Because SloeberConfiguration are copied and can be changed at all times + * but there is only 1 disk representation of each config + * we can not update the disk + * at the time the SloeberConfiguration is changed + * + * When a configuration becomes "the active" configuration this method will + * create/update the necessary resources on disk. + * This apply is when this configuration is new. + */ + public void aboutToApplyConfigChange() { +// try { +// myLibraries =getLibrariesFromLinks(); +// } catch (CoreException e) { +// // ignore exception +// e.printStackTrace(); +// } + if (updateSourceEntries()) { + // the config has been renamed; + // remove the library links + removeLibraryLinks(); + } + configureWhenDirty(); + + } + + public void appliedConfigChange() { LinkToCore(); + upDateHardwareLibraries(); + linkLibrariesToFolder(); + } + + /** + * Look at the source entries to see whether this is a rename + * If it is a rename update the source entries and update the arduino/[configName] + * + * return true if the config has been renamed otherwise false + */ + private boolean updateSourceEntries() { + + IFolder curArduinoConfigurationfolder = getArduinoConfigurationFolder(); + IFolder oldArduinoConfigurationfolder = null; + + // update the source entries + + ICSourceEntry[] orgSourceEntries = getAutoBuildDesc().getCdtConfigurationDescription().getSourceEntries(); + ICSourceEntry[] newSourceEntries = new ICSourceEntry[orgSourceEntries.length]; + for (int curItem = 0; curItem < orgSourceEntries.length; curItem++) { + ICSourceEntry curEntry = orgSourceEntries[curItem]; + if (curArduinoConfigurationfolder.getFullPath().equals(curEntry.getFullPath())) { + newSourceEntries[curItem] = orgSourceEntries[curItem]; + continue; + } + if (getArduinoRootFolder().getFullPath().isPrefixOf(curEntry.getFullPath())) { + oldArduinoConfigurationfolder = getProject().getFolder(curEntry.getFullPath().removeFirstSegments(1)); + newSourceEntries[curItem]=new CSourceEntry(curArduinoConfigurationfolder, curEntry.getExclusionPatterns(), curEntry.getFlags()); + } else { + newSourceEntries[curItem] = orgSourceEntries[curItem]; + } + } + if (oldArduinoConfigurationfolder == null) { + return false; + } + try { + if (oldArduinoConfigurationfolder.exists()) { + NullProgressMonitor monitor = new NullProgressMonitor(); + IFolder deleteFolder = oldArduinoConfigurationfolder.getFolder(SLOEBER_VARIANT_FOLDER_NAME); + if (deleteFolder.exists()) { + deleteFolder.delete(true, monitor); + } + deleteFolder = oldArduinoConfigurationfolder.getFolder(SLOEBER_CODE_FOLDER_NAME); + if (deleteFolder.exists()) { + deleteFolder.delete(true, monitor); + } + if (oldArduinoConfigurationfolder.exists()) { + oldArduinoConfigurationfolder.delete(true, monitor); + } + } + getAutoBuildDesc().getCdtConfigurationDescription().setSourceEntries(newSourceEntries); + + } catch (Exception e) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, Messages.SloeberConfiguration_Failed_Modify_config_rename, e)); + } + return true; + } + + private String getCDTConfName() { + return getAutoBuildDescription().getCdtConfigurationDescription().getName(); } } diff --git a/io.sloeber.core/src/io/sloeber/core/listeners/ConfigurationChangeListener.java b/io.sloeber.core/src/io/sloeber/core/listeners/ConfigurationChangeListener.java index 9f0a486e0..883e5e9f1 100644 --- a/io.sloeber.core/src/io/sloeber/core/listeners/ConfigurationChangeListener.java +++ b/io.sloeber.core/src/io/sloeber/core/listeners/ConfigurationChangeListener.java @@ -13,17 +13,27 @@ public void handleEvent(CProjectDescriptionEvent event) { switch (event.getEventType()) { case CProjectDescriptionEvent.ABOUT_TO_APPLY: { + ICProjectDescription newProjDesc = event.getNewCProjectDescription(); + for(ICConfigurationDescription curConfig:newProjDesc.getConfigurations()) { + SloeberConfiguration sloeberConfig=SloeberConfiguration.getConfig(curConfig); + if(sloeberConfig==null) { + return; + } + sloeberConfig.aboutToApplyConfigChange(); + } + break; + } + case CProjectDescriptionEvent.APPLIED: { ICProjectDescription newProjDesc = event.getNewCProjectDescription(); for(ICConfigurationDescription curConfig:newProjDesc.getConfigurations()) { SloeberConfiguration sloeberConfig=SloeberConfiguration.getConfig(curConfig); if(sloeberConfig==null) { return; } - sloeberConfig.apply(); + sloeberConfig.appliedConfigChange(); } - - break; - } + break; + } default: { // should not happen @@ -31,4 +41,5 @@ public void handleEvent(CProjectDescriptionEvent event) { } } + } diff --git a/io.sloeber.core/src/io/sloeber/core/listeners/IndexerController.java b/io.sloeber.core/src/io/sloeber/core/listeners/IndexerController.java new file mode 100644 index 000000000..43b697b7e --- /dev/null +++ b/io.sloeber.core/src/io/sloeber/core/listeners/IndexerController.java @@ -0,0 +1,88 @@ +package io.sloeber.core.listeners; + +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.cdt.core.CCorePlugin; +import org.eclipse.cdt.core.index.IndexerSetupParticipant; +import org.eclipse.cdt.core.model.CoreModel; +import org.eclipse.cdt.core.model.ICProject; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; + +import io.sloeber.core.Activator; +import io.sloeber.core.natures.SloeberNature; + +public class IndexerController extends IndexerSetupParticipant { + private static Set doNotIndexProjects = new HashSet<>(); + private static Set indexingPosponedProjects = new HashSet<>(); + private static IndexerController myIndexController = null; + private static final String managedBuildNature="org.eclipse.cdt.managedbuilder.core.managedBuildNature"; //$NON-NLS-1$ + + @Override + public boolean postponeIndexerSetup(ICProject cProject) { + IProject project = cProject.getProject(); + String projectName=project.getName(); + boolean ret=false; + if( doNotIndexProjects.contains(projectName)) { + ret=true; + }else { + try { + if(project.hasNature(SloeberNature.NATURE_ID) &&project.hasNature(managedBuildNature)) { + ret=true; + } + } catch (CoreException e) { + e.printStackTrace(); + ret = false; + } + } + if (ret) { + Activator.log(new Status(IStatus.INFO, Activator.getId(), "pospone index " + projectName)); //$NON-NLS-1$ + indexingPosponedProjects.add(projectName); + } /* else { + Common.log(new Status(Const.SLOEBER_STATUS_DEBUG, Activator.getId(), + "do not pospone index " + project.getName())); //$NON-NLS-1$ + }*/ + return ret; + } + + static public boolean isPosponed(String projectName) { + return doNotIndexProjects.contains(projectName); + } + + public static void doNotIndex(IProject project) { + String projectName=project.getName(); + Activator.log(new Status(IStatus.INFO, Activator.getId(), "Do not index " + projectName)); //$NON-NLS-1$ + doNotIndexProjects.add(projectName); + } + + public static void index(IProject project) { + String projectName=project.getName(); + if (doNotIndexProjects.remove(projectName)) { + Activator.log(new Status(IStatus.INFO, Activator.getId(), "index " + projectName)); //$NON-NLS-1$ + } + if (indexingPosponedProjects.contains(projectName)) { + indexingPosponedProjects.remove(projectName); + ICProject cProject = CoreModel.getDefault().getCModel().getCProject(projectName); + myIndexController.notifyIndexerSetup(cProject); + } + } + + public static void registerIndexerController() { + if (myIndexController == null) { + myIndexController = new IndexerController(); + CCorePlugin.getIndexManager().addIndexerSetupParticipant(myIndexController); + } + } + + public static void unRegisterIndexerController() { + if (myIndexController != null) { + CCorePlugin.getIndexManager().removeIndexerSetupParticipant(myIndexController); + myIndexController=null; + } + + } + +} diff --git a/io.sloeber.core/src/io/sloeber/core/listeners/IndexerListener.java b/io.sloeber.core/src/io/sloeber/core/listeners/IndexerListener.java index 0a97a89c8..f55950bf9 100644 --- a/io.sloeber.core/src/io/sloeber/core/listeners/IndexerListener.java +++ b/io.sloeber.core/src/io/sloeber/core/listeners/IndexerListener.java @@ -23,6 +23,7 @@ import org.eclipse.cdt.core.index.IIndexerStateListener; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; +import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; @@ -31,41 +32,33 @@ import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.Activator; import io.sloeber.core.Messages; -import io.sloeber.core.api.Common; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.Const; -import io.sloeber.core.api.IArduinoLibraryVersion; import io.sloeber.core.api.IInstallLibraryHandler; import io.sloeber.core.api.ISloeberConfiguration; -import io.sloeber.core.api.LibraryManager; import io.sloeber.core.common.InstancePreferences; public class IndexerListener implements IIndexChangeListener, IIndexerStateListener { - private static Set newChangedProjects = new HashSet<>(); + private static Set newChangedProjects = new HashSet<>(); private static Map myIncludeHeaderReplacement; @Override public void indexChanged(IIndexChangeEvent event) { if (!InstancePreferences.getAutomaticallyImportLibraries()) { + //The automagically adding of libraries has been disabled newChangedProjects.clear(); return; } IProject project = event.getAffectedProject().getProject(); - ISloeberConfiguration sloeberConfDesc = ISloeberConfiguration.getActiveConfig(project); -// if (IndexerController.isPosponed(project)) { -// // Do not update libraries if project is in creation -// return; -// } - if (sloeberConfDesc == null) { - return; - } - if (!newChangedProjects.contains(sloeberConfDesc)) { - Common.log(new Status(Const.SLOEBER_STATUS_DEBUG, Activator.getId(), - "Index of project changed :" + project.getName())); //$NON-NLS-1$ - newChangedProjects.add(sloeberConfDesc); + if(project!=null) { + newChangedProjects.add(project); } + } @Override @@ -73,26 +66,33 @@ public void indexChanged(IIndexerStateEvent event) { if (event.indexerIsIdle()) { if (!newChangedProjects.isEmpty()) { - Set curChangedProjects = new HashSet<>(newChangedProjects); + CCorePlugin cCorePlugin = CCorePlugin.getDefault(); + Set curChangedProjects = new HashSet<>(newChangedProjects); newChangedProjects.clear(); - for (ISloeberConfiguration sloeberConfDesc : curChangedProjects) { - String projectName = sloeberConfDesc.getProject().getName(); + for (IProject curProject : curChangedProjects) { + ICProjectDescription projectDescription =cCorePlugin.getProjectDescription(curProject, true); + + ISloeberConfiguration sloeberConfDesc = ISloeberConfiguration.getActiveConfig(projectDescription); + if (sloeberConfDesc == null) { + return; + } try { - Common.log(new Status(Const.SLOEBER_STATUS_DEBUG, Activator.getId(), - "Looking for libraries for project :" + projectName)); //$NON-NLS-1$ - checkLibraries(sloeberConfDesc); + Activator.log(new Status(Const.SLOEBER_STATUS_DEBUG, Activator.getId(), + "Looking for libraries for project :" + curProject.getName())); //$NON-NLS-1$ + if (checkLibraries(sloeberConfDesc)) { + cCorePlugin.setProjectDescription(curProject,projectDescription); + } } catch (Exception e) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), Messages.Failed_To_Add_Libraries, e)); + Activator.log(new Status(IStatus.WARNING, Activator.getId(), Messages.Failed_To_Add_Libraries, e)); } - Common.log(new Status(Const.SLOEBER_STATUS_DEBUG, Activator.getId(), - "libraries added for project " + projectName)); //$NON-NLS-1$ + Activator.log(new Status(Const.SLOEBER_STATUS_DEBUG, Activator.getId(), + "libraries added for project " + curProject.getName())); //$NON-NLS-1$ } } } } - private static void checkLibraries(ISloeberConfiguration SloeberCfg) { - Map alreadyAddedLibs = SloeberCfg.getUsedLibraries(); + private static boolean checkLibraries(ISloeberConfiguration SloeberCfg) { Set UnresolvedIncludedHeaders = getUnresolvedProjectIncludes(SloeberCfg.getProject()); // remove pgmspace as it gives a problem UnresolvedIncludedHeaders.remove("pgmspace"); //$NON-NLS-1$ @@ -101,17 +101,17 @@ private static void checkLibraries(ISloeberConfiguration SloeberCfg) { } //The line below is for cases where libs have been excluded from the build - for(String curLib:alreadyAddedLibs.keySet()) { - IFolder libFolder =SloeberCfg.getArduinoLibraryFolder().getFolder(curLib); + for(IArduinoLibraryVersion curLib:SloeberCfg.getUsedLibraries().values()) { + IFolder libFolder =SloeberCfg.getArduinoLibraryFolder().getFolder(curLib.getName()); if(libFolder.exists()) { - UnresolvedIncludedHeaders.remove(curLib); + UnresolvedIncludedHeaders.remove(curLib.getName()); }else { - UnresolvedIncludedHeaders.add(curLib); + UnresolvedIncludedHeaders.add(curLib.getName()); } } if (UnresolvedIncludedHeaders.isEmpty()) { - return; + return false; } for (Map.Entry entry : getIncludeHeaderReplacement().entrySet()) { @@ -125,7 +125,7 @@ private static void checkLibraries(ISloeberConfiguration SloeberCfg) { //Check wether we need to download and install libraries IInstallLibraryHandler installHandler = LibraryManager.getInstallLibraryHandler(); - if (installHandler.autoInstall()) { + if (ConfigurationPreferences.getInstallLibraries() && installHandler.autoInstall()) { // Check if there are libraries that are not found in // the installed libraries Set uninstalledIncludedHeaders = new TreeSet<>(UnresolvedIncludedHeaders); @@ -160,13 +160,15 @@ private static void checkLibraries(ISloeberConfiguration SloeberCfg) { toInstallLibString=toInstallLibString+SPACE+curlib.getFQN(); } } + boolean ret =false; if (!toInstallLibs.isEmpty()) { // there are possible libraries to add - Common.log(new Status(IStatus.INFO, CORE_PLUGIN_ID, "list of libraries to add to project " //$NON-NLS-1$ + Activator.log(new Status(IStatus.INFO, CORE_PLUGIN_ID, "list of libraries to add to project " //$NON-NLS-1$ + SloeberCfg.getProject().getName() + COLON + SPACE + toInstallLibString)); - SloeberCfg.addLibraries(toInstallLibs); + ret=ret||SloeberCfg.addLibraries(toInstallLibs); } + return ret; } private static Set getUnresolvedProjectIncludes(IProject iProject) { diff --git a/io.sloeber.core/src/io/sloeber/core/messages.properties b/io.sloeber.core/src/io/sloeber/core/messages.properties index 44fdf5913..0f3c98cfd 100644 --- a/io.sloeber.core/src/io/sloeber/core/messages.properties +++ b/io.sloeber.core/src/io/sloeber/core/messages.properties @@ -12,6 +12,7 @@ ArduinoSerial_reset_failed=reset using 1200bps touch failed ArduinoSerial_unable_to_open_serial_port=Unable to open Serial port "{PORT}" ArduinoSerial_Using_1200bps_touch=Forcing reset using 1200bps open/close on port : "{PORT}" ArduinoSerial_Using_comport=Using port "{PORT}" from now onwards +BoardDescription_0=failed to get platform paths Boards_Failed_to_read_boards=Failed to read arduino boards file "{FILE}"!! Boards_Get_menu_item_name_from_id_did_not_find=getMenuItemNameFromMenuItemID did not find menu item with ID "{MENUITEMID}" menu ID "{MENUID}" for board "{BOARDID}" Boards_menu_ID_not_found=menu ID "{ID}" not found @@ -81,13 +82,10 @@ sizeReportData=Global variables use "arduino_data" bytes ("int(arduino_data/maxi CompileDescription_CustomDebugLevel=Custom debug level CompileDescription_OptimizedForDebug=Optimized for debug CompileDescription_OptimizedForRelease=Optimized for release -CompileDescription_SizeArduinoWay=Arduino Way -CompileDescription_SizeAVRAlternative=AVR Alternative -CompileDescription_SizeCustom=Custom -CompileDescription_SizeRawResult=Raw result CompileDescription_WarningsAll=All CompileDescription_WarningsCustom=Custom CompileDescription_WarningsDefault=Default CompileDescription_WarningsMore=More CompileDescription_WarningsNone=None - +SloeberConfiguration_Failed_Modify_config_rename=Failed to modify configuration for rename +SloeberProject_Project_is_null=The provided project is null. Sloeber can not upgrade. diff --git a/io.sloeber.core/src/io/sloeber/core/toolchain/ArduinoLanguageProvider.java b/io.sloeber.core/src/io/sloeber/core/toolchain/ArduinoLanguageProvider.java index 668b1ca50..ec5c25be7 100644 --- a/io.sloeber.core/src/io/sloeber/core/toolchain/ArduinoLanguageProvider.java +++ b/io.sloeber.core/src/io/sloeber/core/toolchain/ArduinoLanguageProvider.java @@ -10,10 +10,12 @@ import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.cdt.core.settings.model.ICLanguageSettingEntry; import org.eclipse.cdt.core.settings.model.ICSettingEntry; +import org.eclipse.cdt.core.settings.model.ICSourceEntry; import org.eclipse.cdt.core.settings.model.util.CDataUtil; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; +import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; import io.sloeber.core.api.ISloeberConfiguration; public class ArduinoLanguageProvider implements ILanguageSettingsProvider { @@ -35,10 +37,23 @@ public List getSettingEntries(ICConfigurationDescription return null; } List ret = new LinkedList<>(); - ISloeberConfiguration autoConfDesc= ISloeberConfiguration.getConfig(cfgDescription); + IAutoBuildConfigurationDescription autoBuildConfData=IAutoBuildConfigurationDescription.getConfig(cfgDescription); + if(autoBuildConfData==null) { + return null; + } + ISloeberConfiguration autoConfDesc= ISloeberConfiguration.getConfig(autoBuildConfData); + if(autoConfDesc==null) { + return null; + } + ICSourceEntry[] mySrcEntries = IAutoBuildConfigurationDescription.getResolvedSourceEntries(autoBuildConfData); Set includeFolders = autoConfDesc.getIncludeFolders(); int flags = ICSettingEntry.READONLY | ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.RESOLVED; for(IFolder curFolder:includeFolders) { + boolean isExcluded = mySrcEntries == null ? false + : CDataUtil.isExcluded(curFolder.getProjectRelativePath(), mySrcEntries); + if (isExcluded) { + continue; + } ret.add(CDataUtil.getPooledEntry(new CIncludePathEntry(curFolder, flags))); } return LanguageSettingsStorage.getPooledList(ret); diff --git a/io.sloeber.core/src/io/sloeber/core/toolchain/SloeberConfigurationVariableSupplier.java b/io.sloeber.core/src/io/sloeber/core/toolchain/SloeberConfigurationVariableSupplier.java index 7ce411486..b0fac2d30 100644 --- a/io.sloeber.core/src/io/sloeber/core/toolchain/SloeberConfigurationVariableSupplier.java +++ b/io.sloeber.core/src/io/sloeber/core/toolchain/SloeberConfigurationVariableSupplier.java @@ -7,8 +7,9 @@ import org.eclipse.cdt.core.envvar.EnvironmentVariable; import org.eclipse.cdt.core.envvar.IEnvironmentVariable; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; + +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.autoBuild.api.IEnvironmentVariableProvider; -import io.sloeber.core.api.BoardsManager; import io.sloeber.core.api.ISloeberConfiguration; public class SloeberConfigurationVariableSupplier implements IEnvironmentVariableProvider { diff --git a/io.sloeber.core/src/io/sloeber/core/tools/ExternalCommandLauncher.java b/io.sloeber.core/src/io/sloeber/core/tools/ExternalCommandLauncher.java index 40235f442..db056eace 100644 --- a/io.sloeber.core/src/io/sloeber/core/tools/ExternalCommandLauncher.java +++ b/io.sloeber.core/src/io/sloeber/core/tools/ExternalCommandLauncher.java @@ -29,6 +29,7 @@ import org.eclipse.core.runtime.Status; import org.eclipse.ui.console.MessageConsoleStream; +import io.sloeber.core.Activator; import io.sloeber.core.Messages; import io.sloeber.core.api.Common; import io.sloeber.core.api.Const; @@ -120,7 +121,7 @@ public void run() { } catch (IOException e) { // This is unlikely to happen, but log it nevertheless IStatus status = new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, Messages.command_io, e); - Common.log(status); + Activator.log(status); } finally { try { this.fReader.close(); diff --git a/io.sloeber.core/src/io/sloeber/core/tools/FileModifiers.java b/io.sloeber.core/src/io/sloeber/core/tools/FileModifiers.java index 93ffa5caa..54d3ac868 100644 --- a/io.sloeber.core/src/io/sloeber/core/tools/FileModifiers.java +++ b/io.sloeber.core/src/io/sloeber/core/tools/FileModifiers.java @@ -17,7 +17,6 @@ import org.eclipse.core.runtime.Status; import io.sloeber.core.Activator; -import io.sloeber.core.api.Common; import io.sloeber.core.common.InstancePreferences; public class FileModifiers { @@ -37,12 +36,12 @@ public static void appendString(File input, String addString) throws IOException try { String fileString = Files.readString(pathFile,StandardCharsets.UTF_8) + addString; Files.write(pathFile, fileString.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); - }catch(IOException e) { - String fileString = Files.readString(pathFile,Charset.forName("Cp1252")) + addString; + }catch(@SuppressWarnings("unused") IOException e) { + String fileString = Files.readString(pathFile,Charset.forName("Cp1252")) + addString; //$NON-NLS-1$ Files.write(pathFile, fileString.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); - + } - + } /** @@ -118,7 +117,7 @@ public static void replaceInFile(File file, boolean regex, String find, String r Files.write(pathFile, textFromFile.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } catch (IOException e) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), + Activator.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to replace " + find + " with " + replace + " in file " + file.toString(), e)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } diff --git a/io.sloeber.core/src/io/sloeber/core/tools/Helpers.java b/io.sloeber.core/src/io/sloeber/core/tools/Helpers.java index bc2b29326..1283b9a17 100644 --- a/io.sloeber.core/src/io/sloeber/core/tools/Helpers.java +++ b/io.sloeber.core/src/io/sloeber/core/tools/Helpers.java @@ -1,9 +1,7 @@ package io.sloeber.core.tools; -import static io.sloeber.core.api.Common.*; import static io.sloeber.core.api.Const.*; -import java.io.File; import java.io.InputStream; import java.net.URI; import org.eclipse.cdt.core.CCorePlugin; @@ -24,6 +22,7 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.IConsole; @@ -31,6 +30,7 @@ import org.eclipse.ui.console.MessageConsole; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; +import io.sloeber.core.Activator; import io.sloeber.core.Messages; /** @@ -41,176 +41,110 @@ */ public class Helpers { - private static final String FILE = Messages.FILE_TAG; - private static final String FOLDER = Messages.FOLDER_TAG; - - private static boolean myHasBeenLogged = false; - - /** - * This method is the internal working class that adds the provided include - * paths to the configuration for all languages. - * - * @param configurationDescription - * The configuration description of the project to add it to - * @param IncludePath - * The path to add to the include folders - * @param isWorkspacePath - * is this path in the workspace - * - * @return true if the configuration description has changed - * (setprojectdescription is needed to make the changes effective) - */ -// public static boolean addIncludeFolder(ICConfigurationDescription configurationDescription, -// List IncludePaths, boolean isWorkspacePath) { -// -// boolean confDesckMustBeSet = false; -// if (IncludePaths == null) { -// return false; -// } -// ICLanguageSetting[] languageSettings = configurationDescription.getRootFolderDescription() -// .getLanguageSettings(); -// int pathSetting = ICSettingEntry.VALUE_WORKSPACE_PATH; -// if (!isWorkspacePath) { -// pathSetting = 0; -// } -// -// // Add include path to all languages -// for (int idx = 0; idx < languageSettings.length; idx++) { -// ICLanguageSetting lang = languageSettings[idx]; -// String LangID = lang.getLanguageId(); -// if (LangID != null) { -// if (LangID.startsWith("org.eclipse.cdt.")) { //$NON-NLS-1$ -// ICLanguageSettingEntry[] OrgIncludeEntries = lang.getSettingEntries(ICSettingEntry.INCLUDE_PATH); -// HashSet toAddPaths = new HashSet<>(IncludePaths); -// for (ICLanguageSettingEntry curLangSetting : OrgIncludeEntries) { -// CIncludePathEntry curIncludePathEntry = (CIncludePathEntry) curLangSetting; -// toAddPaths.remove(curIncludePathEntry.getFullPath()); -// } -// if (!toAddPaths.isEmpty()) { -// confDesckMustBeSet = true; -// ICLanguageSettingEntry[] IncludeEntries = new ICLanguageSettingEntry[OrgIncludeEntries.length -// + toAddPaths.size()]; -// System.arraycopy(OrgIncludeEntries, 0, IncludeEntries, 0, OrgIncludeEntries.length); -// int startPointer = OrgIncludeEntries.length; -// for (IPath curPath : toAddPaths) { -// IncludeEntries[startPointer++] = new CIncludePathEntry(curPath, pathSetting); -// } -// lang.setSettingEntries(ICSettingEntry.INCLUDE_PATH, IncludeEntries); -// } -// } -// } -// } -// return confDesckMustBeSet; -// } - - /** - * Removes include folders that are not valid. This method does not save the - * configurationDescription description - * - * @param configurationDescription - * a writable project description the configuration that is checked - * @return true is a include path has been removed. False if the include path - * remains unchanged. If true the projectdescription must be set - */ - public static boolean removeInvalidIncludeFolders(ICConfigurationDescription configurationDescription) { - // find all languages - ICFolderDescription folderDescription = configurationDescription.getRootFolderDescription(); - ICLanguageSetting[] languageSettings = folderDescription.getLanguageSettings(); - boolean hasChange = false; - // Add include path to all languages - for (int idx = 0; idx < languageSettings.length; idx++) { - ICLanguageSetting lang = languageSettings[idx]; - String LangID = lang.getLanguageId(); - if (LangID != null) { - if (LangID.startsWith("org.eclipse.cdt.")) { //$NON-NLS-1$ - ICLanguageSettingEntry[] OrgIncludeEntries = lang.getSettingEntries(ICSettingEntry.INCLUDE_PATH); - ICLanguageSettingEntry[] OrgIncludeEntriesFull = lang - .getResolvedSettingEntries(ICSettingEntry.INCLUDE_PATH); - int copiedEntry = 0; - for (int curEntry = 0; curEntry < OrgIncludeEntries.length; curEntry++) { - IPath cusPath = ((CIncludePathEntry) OrgIncludeEntriesFull[curEntry]).getFullPath(); - if ((ResourcesPlugin.getWorkspace().getRoot().exists(cusPath)) - || (((CIncludePathEntry) OrgIncludeEntries[curEntry]).isBuiltIn())) { - OrgIncludeEntries[copiedEntry++] = OrgIncludeEntries[curEntry]; - } else { - log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, "Removed invalid include path" + cusPath, //$NON-NLS-1$ - null)); - } - } - if (copiedEntry != OrgIncludeEntries.length) // do not save - // if nothing - // has changed - { - ICLanguageSettingEntry[] IncludeEntries = new ICLanguageSettingEntry[copiedEntry]; - System.arraycopy(OrgIncludeEntries, 0, IncludeEntries, 0, copiedEntry); - lang.setSettingEntries(ICSettingEntry.INCLUDE_PATH, IncludeEntries); - hasChange = true; - - } - } - } - } - return hasChange; - } - - /** - * Creates a folder and links the folder to an existing folder Parent folders of - * the target folder are created if needed. In case this method fails an error - * is logged. - * - * @param project - * the project the newly created folder will belong to - * @param projectFolder - * the folder name relative to the project - * @param source - * the fully qualified name of the folder to link to - */ - public static void LinkFolderToFolder(IPath source, IFolder projectFolder) { - IProject project = projectFolder.getProject(); - - // create target parent folder and grandparents - IPath ParentFolders = projectFolder.getProjectRelativePath().removeLastSegments(1); - for (int curfolder = ParentFolders.segmentCount() - 1; curfolder >= 0; curfolder--) { - try { - createNewFolder(project.getFolder(ParentFolders.removeLastSegments(curfolder)), null); - } catch (@SuppressWarnings("unused") CoreException e) { - // ignore this error as the parent - // folders may have been created yet - } - } + private static final String FOLDER = Messages.FOLDER_TAG; + + /** + * Removes include folders that are not valid. This method does not save the + * configurationDescription description + * + * @param configurationDescription a writable project description the + * configuration that is checked + * @return true is a include path has been removed. False if the include path + * remains unchanged. If true the projectdescription must be set + */ + public static boolean removeInvalidIncludeFolders(ICConfigurationDescription configurationDescription) { + // find all languages + ICFolderDescription folderDescription = configurationDescription.getRootFolderDescription(); + ICLanguageSetting[] languageSettings = folderDescription.getLanguageSettings(); + boolean hasChange = false; + // Add include path to all languages + for (int idx = 0; idx < languageSettings.length; idx++) { + ICLanguageSetting lang = languageSettings[idx]; + String LangID = lang.getLanguageId(); + if (LangID != null) { + if (LangID.startsWith("org.eclipse.cdt.")) { //$NON-NLS-1$ + ICLanguageSettingEntry[] OrgIncludeEntries = lang.getSettingEntries(ICSettingEntry.INCLUDE_PATH); + ICLanguageSettingEntry[] OrgIncludeEntriesFull = lang + .getResolvedSettingEntries(ICSettingEntry.INCLUDE_PATH); + int copiedEntry = 0; + for (int curEntry = 0; curEntry < OrgIncludeEntries.length; curEntry++) { + IPath cusPath = ((CIncludePathEntry) OrgIncludeEntriesFull[curEntry]).getFullPath(); + if ((ResourcesPlugin.getWorkspace().getRoot().exists(cusPath)) + || (((CIncludePathEntry) OrgIncludeEntries[curEntry]).isBuiltIn())) { + OrgIncludeEntries[copiedEntry++] = OrgIncludeEntries[curEntry]; + } else { + Activator.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, + "Removed invalid include path" + cusPath, //$NON-NLS-1$ + null)); + } + } + if (copiedEntry != OrgIncludeEntries.length) // do not save + // if nothing + // has changed + { + ICLanguageSettingEntry[] IncludeEntries = new ICLanguageSettingEntry[copiedEntry]; + System.arraycopy(OrgIncludeEntries, 0, IncludeEntries, 0, copiedEntry); + lang.setSettingEntries(ICSettingEntry.INCLUDE_PATH, IncludeEntries); + hasChange = true; + + } + } + } + } + return hasChange; + } - // create the actual link - try { - createNewFolder(projectFolder, source); - } catch (CoreException e) { - log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, - Messages.Helpers_Create_folder_failed.replace(FOLDER, projectFolder.toString()), e)); - } - } + /** + * Creates a folder and links the folder to an existing folder Parent folders of + * the target folder are created if needed. In case this method fails an error + * is logged. + * + * @param project the project the newly created folder will belong to + * @param projectFolder the folder name relative to the project + * @param source the fully qualified name of the folder to link to + */ + public static void LinkFolderToFolder(IPath source, IFolder projectFolder) { + IProject project = projectFolder.getProject(); + + // create target parent folder and grandparents + IPath ParentFolders = projectFolder.getProjectRelativePath().removeLastSegments(1); + for (int curfolder = ParentFolders.segmentCount() - 1; curfolder >= 0; curfolder--) { + try { + createNewFolder(project.getFolder(ParentFolders.removeLastSegments(curfolder)), null); + } catch (@SuppressWarnings("unused") CoreException e) { + // ignore this error as the parent + // folders may have been created yet + } + } + // create the actual link + try { + createNewFolder(projectFolder, source); + } catch (CoreException e) { + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Messages.Helpers_Create_folder_failed.replace(FOLDER, projectFolder.toString()), e)); + } + } - public static void removeCodeFolder(IFolder deleteFolder) { - if (deleteFolder.exists()) { - try { - deleteFolder.delete(true, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } - } + public static void removeCodeFolder(IFolder deleteFolder) { + if (deleteFolder.exists()) { + try { + deleteFolder.delete(true, null); + } catch (CoreException e) { + e.printStackTrace(); + } + } + } - /** - * This method adds the content of a content stream to a file If the file - * already exist the file remains untouched - * - * @param file - * The file to create - * @param contentStream - * The stream to put in the file - * @param monitor - * A monitor to show progress - * @throws CoreException - */ + /** + * This method adds the content of a content stream to a file If the file + * already exist the file remains untouched + * + * @param file The file to create + * @param contentStream The stream to put in the file + * @param monitor A monitor to show progress + * @throws CoreException + */ public static IFile addFileToProject(IFile file, InputStream contentStream, IProgressMonitor monitor, boolean overwrite) throws CoreException { file.refreshLocal(IResource.DEPTH_INFINITE, monitor); @@ -223,8 +157,7 @@ public static IFile addFileToProject(IFile file, InputStream contentStream, IPro if (!file.exists() && (contentStream != null)) { IPath filePath = file.getProjectRelativePath(); - for (int curSegment = 0;curSegment < (filePath.segmentCount()-1);curSegment++) - { + for (int curSegment = 0; curSegment < (filePath.segmentCount() - 1); curSegment++) { IFolder curFolder = file.getProject().getFolder(filePath.segment(curSegment)); if (!curFolder.exists()) { curFolder.create(true, false, monitor); @@ -235,99 +168,56 @@ public static IFile addFileToProject(IFile file, InputStream contentStream, IPro return file; } - public static MessageConsole findConsole(String name) { - ConsolePlugin plugin = ConsolePlugin.getDefault(); - IConsoleManager conMan = plugin.getConsoleManager(); - IConsole[] existing = conMan.getConsoles(); - for (int i = 0; i < existing.length; i++) - if (name.equals(existing[i].getName())) - return (MessageConsole) existing[i]; - // no console found, so create a new one - MessageConsole myConsole = new MessageConsole(name, null); - conMan.addConsoles(new IConsole[] { myConsole }); - return myConsole; - } - - /** - * Creates a new folder resource as a link or local - * - * @param newFolder - * the new folder to create (can contain subfolders) - * @param linklocation - * if null a local folder is created using newFolderName if not null - * a link folder is created with the name newFolderName and pointing - * to linklocation - * - * @return nothing - * @throws CoreException - */ - public static void createNewFolder(IFolder newFolder, IPath linklocation) throws CoreException { - if (linklocation != null) { - URI relativeLinklocation = newFolder.getProject().getPathVariableManager() - .convertToRelative(URIUtil.toURI(linklocation), false, null); - newFolder.createLink(relativeLinklocation, IResource.REPLACE | IResource.ALLOW_MISSING_LOCAL, null); - } else { - newFolder.create(0, false, null); - } - - } - - /** - * Set the project to force a rebuild. This method is called after the arduino - * settings have been updated. Note the only way I found I could get this to - * work is by deleting the build folder - * - * @param project - */ - public static void deleteBuildFolder(IProject project, String cfgName) { - ICProjectDescription cdtProjectDescription = CCorePlugin.getDefault().getProjectDescription(project, false); - ICConfigurationDescription cdtConfigurationDescription = cdtProjectDescription.getConfigurationByName(cfgName); - IAutoBuildConfigurationDescription autoData = IAutoBuildConfigurationDescription - .getConfig(cdtConfigurationDescription); - - IFolder buildFolder = autoData.getBuildFolder(); - if (buildFolder.exists()) { - try { - buildFolder.delete(true, null); - } catch (CoreException e) { - log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, - Messages.Helpers_delete_folder_failed.replace(FOLDER, cfgName), e)); - } - } - } + public static MessageConsole findConsole(String name) { + ConsolePlugin plugin = ConsolePlugin.getDefault(); + IConsoleManager conMan = plugin.getConsoleManager(); + IConsole[] existing = conMan.getConsoles(); + for (int i = 0; i < existing.length; i++) + if (name.equals(existing[i].getName())) + return (MessageConsole) existing[i]; + // no console found, so create a new one + MessageConsole myConsole = new MessageConsole(name, null); + conMan.addConsoles(new IConsole[] { myConsole }); + return myConsole; + } - /** - * creates links to the root files and folders of the source location - * - * @param source - * the location where the files are that need to be linked to - * @param target - * the location where the links are to be created - */ - public static void linkDirectory(IPath source, IFolder target) { + /** + * Creates a new folder resource as a link or local + * + * @param newFolder the new folder to create (can contain subfolders) + * @param linklocation if null a local folder is created using newFolderName if + * not null a link folder is created with the name + * newFolderName and pointing to linklocation + * + * @return nothing + * @throws CoreException + */ + public static void createNewFolder(IFolder newFolder, IPath linklocation) throws CoreException { + if (linklocation != null) { + URI relativeLinklocation = newFolder.getProject().getPathVariableManager() + .convertToRelative(URIUtil.toURI(linklocation), false, null); + newFolder.createLink(relativeLinklocation, + IResource.REPLACE | IResource.ALLOW_MISSING_LOCAL | IResource.BACKGROUND_REFRESH, null); + } else { + newFolder.create(0, false, null); + } - File[] sourceFiles = source.toFile().listFiles(); - if (sourceFiles == null) { - if (!myHasBeenLogged) { - log(new Status(IStatus.INFO, CORE_PLUGIN_ID, - Messages.Helpers_error_link_folder_is_empty.replace(FILE, source.toOSString()), null)); - myHasBeenLogged = true; - } - return; - } - for (File curFile : sourceFiles) { - if (curFile.isDirectory()) { - LinkFolderToFolder(source.append(curFile.getName()), target.getFolder(curFile.getName())); - } else { - try { - target.getFile(curFile.getName()).createLink(source.append(curFile.getName()), - IResource.REPLACE | IResource.ALLOW_MISSING_LOCAL, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } - } + } - } + /** + * Set the project to force a rebuild. This method is called after the arduino + * settings have been updated. Note the only way I found I could get this to + * work is by deleting the build folder + * + * @param project + */ + public static void deleteBuildFolder(IProject project, String cfgName) { + ICProjectDescription cdtProjectDescription = CCorePlugin.getDefault().getProjectDescription(project, false); + ICConfigurationDescription cdtConfigurationDescription = cdtProjectDescription.getConfigurationByName(cfgName); + IAutoBuildConfigurationDescription autoData = IAutoBuildConfigurationDescription + .getConfig(cdtConfigurationDescription); + + autoData.deleteBuildFolder(new NullProgressMonitor()); + } } diff --git a/io.sloeber.core/src/io/sloeber/core/tools/Libraries.java b/io.sloeber.core/src/io/sloeber/core/tools/Libraries.java index 3caad74db..307e3ffee 100644 --- a/io.sloeber.core/src/io/sloeber/core/tools/Libraries.java +++ b/io.sloeber.core/src/io/sloeber/core/tools/Libraries.java @@ -14,7 +14,7 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; -import io.sloeber.core.api.Common; +import io.sloeber.core.Activator; import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.VersionNumber; @@ -45,7 +45,7 @@ public static Map findAllArduinoManagerLibraries() { if (versions != null) { switch (versions.length) { case 0:// A empty lib folder is hanging around - Common.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, EmptyLibFolder.replace(LIB_TAG, curLib))); Lib_root.toFile().delete(); break; @@ -58,7 +58,7 @@ public static Map findAllArduinoManagerLibraries() { // latest int highestVersion = getHighestVersion(versions); ret.put(curLib, Lib_root.append(versions[highestVersion])); - Common.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.WARNING, CORE_PLUGIN_ID, MultipleVersionsOfLib.replace(LIB_TAG, curLib))); } @@ -109,7 +109,7 @@ public static boolean removeLibrariesFromProject(IProject project, ICConfigurati final IFolder folderHandle = project.getFolder(WORKSPACE_LIB_FOLDER + CurItem); folderHandle.delete(true, null); } catch (CoreException e) { - Common.log( + Activator.log( new Status(IStatus.ERROR, CORE_PLUGIN_ID, failed_to_remove_lib.replace(LIB_TAG, CurItem), e)); } } diff --git a/io.sloeber.core/src/io/sloeber/core/tools/PackageManager.java b/io.sloeber.core/src/io/sloeber/core/tools/PackageManager.java index fcfb9e03d..bbd3823b2 100644 --- a/io.sloeber.core/src/io/sloeber/core/tools/PackageManager.java +++ b/io.sloeber.core/src/io/sloeber/core/tools/PackageManager.java @@ -1,7 +1,6 @@ package io.sloeber.core.tools; import static io.sloeber.core.api.Const.*; -import static io.sloeber.core.api.Common.*; import static java.nio.file.StandardCopyOption.*; import java.io.File; @@ -29,11 +28,10 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; +import io.sloeber.arduinoFramework.api.ArduinoInstallable; import io.sloeber.core.Activator; import io.sloeber.core.Messages; -import io.sloeber.core.api.Common; import io.sloeber.core.api.ConfigurationPreferences; -import io.sloeber.core.api.Json.ArduinoInstallable; public class PackageManager { private static final String FILE = Messages.FILE_TAG; @@ -420,14 +418,14 @@ private static void myCopy(URL url, File localFile, boolean report_error, int re return; } if (report_error) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), + Activator.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url + " error code is: " + status, null)); } throw new IOException("Failed to download url " + url + " error code is: " + status); } catch (Exception e) { if (report_error) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e)); + Activator.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e)); } throw e; diff --git a/io.sloeber.core/src/io/sloeber/core/tools/Stream.java b/io.sloeber.core/src/io/sloeber/core/tools/Stream.java index c6ea4025a..6089feb17 100644 --- a/io.sloeber.core/src/io/sloeber/core/tools/Stream.java +++ b/io.sloeber.core/src/io/sloeber/core/tools/Stream.java @@ -14,7 +14,6 @@ import org.eclipse.core.runtime.Status; import io.sloeber.core.Activator; -import io.sloeber.core.api.Common; /** * the Stream class is used to read the board.txt file @@ -43,7 +42,7 @@ public static InputStream openContentStream(String Resource, boolean isFile,Map< input = Stream.class.getResourceAsStream(Resource); } if (input == null) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "openContentStream: resource " + Resource + " not found.\nThe file will not be processed!")); //$NON-NLS-1$ //$NON-NLS-2$ return null; } @@ -71,7 +70,7 @@ public static InputStream openContentStream(String Resource, boolean isFile,Map< } input = null; IStatus status = new Status(IStatus.ERROR, "NewFileWizard", IStatus.OK, ioe.getLocalizedMessage(), ioe); //$NON-NLS-1$ - Common.log(status); + Activator.log(status); throw new CoreException(status); } finally { if (input != null) { diff --git a/io.sloeber.core/src/io/sloeber/core/tools/uploaders/UploadSketchWrapper.java b/io.sloeber.core/src/io/sloeber/core/tools/uploaders/UploadSketchWrapper.java index 1b16f06cf..9a3698cd1 100644 --- a/io.sloeber.core/src/io/sloeber/core/tools/uploaders/UploadSketchWrapper.java +++ b/io.sloeber.core/src/io/sloeber/core/tools/uploaders/UploadSketchWrapper.java @@ -41,8 +41,9 @@ import cc.arduino.packages.ssh.SSHClientSetupChainRing; import cc.arduino.packages.ssh.SSHConfigFileSetup; import cc.arduino.packages.ssh.SSHPwdSetup; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.core.Activator; import io.sloeber.core.Messages; -import io.sloeber.core.api.BoardDescription; import io.sloeber.core.api.ISloeberConfiguration; import io.sloeber.core.api.PasswordManager; import io.sloeber.core.api.Serial; @@ -169,7 +170,7 @@ public void run() { theComPortIsPaused = SerialManager.pauseSerialMonitor(myProvidedUploadPort); } catch (Exception e) { ret = new Status(IStatus.WARNING, CORE_PLUGIN_ID, Upload_Error_com_port, e); - log(ret); + Activator.log(ret); } if (!actualUpload(monitor, highLevelStream, outStream, errStream)) { @@ -180,7 +181,7 @@ public void run() { } catch (Exception e) { String error = Upload_failed_upload_file.replace(FILE_TAG, projectName); - log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, error, e)); + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, error, e)); } finally { try { if (theComPortIsPaused) { @@ -202,7 +203,7 @@ public void run() { } } catch (Exception e) { ret = new Status(IStatus.WARNING, CORE_PLUGIN_ID, Messages.Upload_Error_serial_monitor_restart, e); - log(ret); + Activator.log(ret); } } monitor.done(); @@ -233,7 +234,7 @@ private boolean actualUpload(IProgressMonitor monitor, MessageConsoleStream high String command = getBuildEnvironmentVariable(mySloeberConf, uploadRecipoeKey, EMPTY); if (command.isEmpty()) { - log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, uploadRecipoeKey + " : not found in the platform.txt file")); //$NON-NLS-1$ highStream.println(uploader_Failed_to_get_upload_recipe); return false; @@ -252,7 +253,7 @@ private boolean actualUpload(IProgressMonitor monitor, MessageConsoleStream high if (cmdLauncher.launch(monitor, highStream, outStream, errStream) < 0) return false; } catch (IOException e) { - log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, Upload_failed, e)); + Activator.log(new Status(IStatus.ERROR, CORE_PLUGIN_ID, Upload_failed, e)); return false; } } diff --git a/io.sloeber.core/src/io/sloeber/core/txt/Programmers.java b/io.sloeber.core/src/io/sloeber/core/txt/Programmers.java index e3e537145..6bc0adbfb 100644 --- a/io.sloeber.core/src/io/sloeber/core/txt/Programmers.java +++ b/io.sloeber.core/src/io/sloeber/core/txt/Programmers.java @@ -7,7 +7,7 @@ import org.eclipse.core.runtime.IPath; -import io.sloeber.core.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardDescription; public class Programmers extends BoardTxtFile { private static final String programmersFileName1 = "programmers.txt";//$NON-NLS-1$ diff --git a/io.sloeber.core/src/io/sloeber/core/txt/TxtFile.java b/io.sloeber.core/src/io/sloeber/core/txt/TxtFile.java index 139558953..8f0f7a0ae 100644 --- a/io.sloeber.core/src/io/sloeber/core/txt/TxtFile.java +++ b/io.sloeber.core/src/io/sloeber/core/txt/TxtFile.java @@ -12,13 +12,11 @@ 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.core.runtime.Status; import io.sloeber.autoBuild.helpers.api.KeyValueTree; -import io.sloeber.core.api.Common; +import io.sloeber.core.Activator; import io.sloeber.core.api.Const; /** @@ -72,7 +70,7 @@ public void mergeFile(File boardsFileName) { } } } catch (Exception e) { - Common.log(new Status(IStatus.WARNING, Const.CORE_PLUGIN_ID, + Activator.log(new Status(IStatus.WARNING, Const.CORE_PLUGIN_ID, Boards_Failed_to_read_boards.replace(FILE_TAG, boardsFileName.getName()), e)); } } @@ -119,43 +117,7 @@ public String getNiceNameFromID(String myBoardID) { return myData.getValue(myBoardID + DOT + NAME); } - /* - * Returns the architecture based on the platform file name Caters for the - * packages (with version number and for the old way if the boards file does not - * exists returns avr - */ - public String getArchitecture() { - - IPath platformFile = new Path(this.mLoadedTxtFile.toString().trim()); - String architecture = platformFile.removeLastSegments(1).lastSegment(); - if (architecture == null) {// for error conditions - architecture = AVR; - } - if (architecture.contains(DOT)) { // This is a version number so - // package - architecture = platformFile.removeLastSegments(2).lastSegment(); - } - return architecture; - } - /* - * Returns the architecture based on the platform file name Caters for the - * packages (with version number and for the old way if the boards file does not - * exists returns avr - */ - public String getVendor() { - - IPath platformFile = new Path(this.mLoadedTxtFile.toString().trim()); - String vendor = platformFile.removeLastSegments(2).lastSegment(); - if (vendor == null) {// for error conditions - vendor = "NotFound"; //$NON-NLS-1$ - } - if (vendor.contains(DOT)) { // This is a version number so - // package - vendor = platformFile.removeLastSegments(3).lastSegment(); - } - return vendor; - } /** * Given a nice name look for the ID The assumption is that the txt file diff --git a/io.sloeber.core/src/io/sloeber/core/txt/WorkAround.java b/io.sloeber.core/src/io/sloeber/core/txt/WorkAround.java index 5f8a543c3..8e98caf93 100644 --- a/io.sloeber.core/src/io/sloeber/core/txt/WorkAround.java +++ b/io.sloeber.core/src/io/sloeber/core/txt/WorkAround.java @@ -20,10 +20,9 @@ import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; import io.sloeber.core.Activator; -import io.sloeber.core.api.Common; import io.sloeber.core.api.VersionNumber; -import io.sloeber.core.api.Json.ArduinoPlatformVersion; import io.sloeber.core.tools.FileModifiers; /** @@ -45,7 +44,7 @@ public class WorkAround { // Each time this class is touched consider changing the String below to enforce // updates - private static final String FIRST_SLOEBER_WORKAROUND_LINE = "#Sloeber created TXT file V3.00.test 24 "; + private static final String FIRST_SLOEBER_WORKAROUND_LINE = "#Sloeber created TXT file V3.00.test 38 "; private static Map USB_replacers; @@ -53,6 +52,8 @@ public class WorkAround { { USB_replacers = new TreeMap<>(); + if (isWindows) { + USB_replacers.put(" '-DUSB_MANUFACTURER={build.usb_manufacturer}' ", " \"-DUSB_MANUFACTURER={build.usb_manufacturer}\" "); USB_replacers.put(" '-DUSB_MANUFACTURER=\"{build.usb_manufacturer}\"' ", @@ -67,6 +68,25 @@ public class WorkAround { USB_replacers.put(" '-DUSB_SERIAL=\"{build.usb_serial}\"' ", " \"-DUSB_SERIAL=\\\"{build.usb_serial}\\\"\" "); USB_replacers.put(" '-DUSB_SERIAL={build.usb_serial}' ", " \"-DUSB_SERIAL={build.usb_serial}\" "); + USB_replacers.put("-DARDUINO_HOST_OS=\"{runtime.os}\" ", "\"-DARDUINO_HOST_OS=\\\"{runtime.os}\\\"\" "); + USB_replacers.put(" -DARDUINO_VARIANT=\"{build.variant}\" ", " \"-DARDUINO_VARIANT=\\\"{build.variant}\\\"\" "); + USB_replacers.put(" -DARDUINO_FQBN=\"{build.fqbn}\" ", " \"-DARDUINO_FQBN=\\\"{build.fqbn}\\\"\" "); + + }else { + USB_replacers.put(" -DUSB_MANUFACTURER=\"{build.usb_manufacturer}\" ", + " '-DUSB_MANUFACTURER=\"{build.usb_manufacturer}\"' "); + USB_replacers.put(" -DUSB_PRODUCT=\"{build.usb_product}\" "," '-DUSB_PRODUCT=\"{build.usb_product}\"' "); + USB_replacers.put(" -DARDUINO_BOARD=\"{build.board}\" ", " '-DARDUINO_BOARD=\"{build.board}\"' "); + USB_replacers.put(" -DUSB_SERIAL=\"{build.usb_serial}\" ", " '-DUSB_SERIAL=\"{build.usb_serial}\"' "); + + //esp32 has + //extraflags=-DARDUINO_HOST_OS= + //so no space in search + USB_replacers.put("-DARDUINO_HOST_OS=\"{runtime.os}\" ", "'-DARDUINO_HOST_OS=\"{runtime.os}\"' "); + USB_replacers.put(" -DARDUINO_VARIANT=\"{build.variant}\" ", " '-DARDUINO_VARIANT=\"{build.variant}\"' "); + USB_replacers.put(" -DARDUINO_FQBN=\"{build.fqbn}\" ", " '-DARDUINO_FQBN=\"{build.fqbn}\"' "); + + } } @@ -77,7 +97,7 @@ public class WorkAround { * * @param arduinoPlatformVersion */ - static public void applyKnownWorkArounds(ArduinoPlatformVersion arduinoPlatformVersion) { + static public void applyKnownWorkArounds(IArduinoPlatformVersion arduinoPlatformVersion) { /* * for STM32 V1.8 and later #include "SrcWrapper.h" to Arduino.h remove the @@ -122,7 +142,7 @@ static File MakeBoardsSloeberTxt(File requestedFileToWorkAround) { String inFile = requestedFileToWorkAround.toString(); String actualFileToLoad = inFile.replace(BOARDS_FILE_NAME, "boards.sloeber.txt"); if (inFile.equals(actualFileToLoad)) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "Boards.txt file is not recognized " + requestedFileToWorkAround.toString())); return requestedFileToWorkAround; } @@ -144,7 +164,7 @@ static File MakeBoardsSloeberTxt(File requestedFileToWorkAround) { Files.write(boardsSloeberTXT.toPath(), boardsTXT.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } catch (IOException e) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), + Activator.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to apply work arounds to " + requestedFileToWorkAround.toString(), e)); return requestedFileToWorkAround; } @@ -159,10 +179,12 @@ public static String boardsApplyWorkArounds(String inBoardsTXT) { boardsTXT = boardsTXT.replace("\n", " \n"); boardsTXT = solveOSStuff(boardsTXT); - // replace FI circuitplay32u4cat.build.usb_manufacturer="Adafruit" - // with circuitplay32u4cat.build.usb_manufacturer=\"Adafruit\" - boardsTXT = boardsTXT.replaceAll("(\\S+\\.build\\.usb\\S+)=\\\"(.+)\\\"", - "$1=\\\\\"$2\\\\\""); + if (isWindows) { + // replace FI circuitplay32u4cat.build.usb_manufacturer="Adafruit" + // with circuitplay32u4cat.build.usb_manufacturer=\"Adafruit\" + boardsTXT = boardsTXT.replaceAll("(\\S+\\.build\\.usb\\S+)=\\\"(.+)\\\"", + "$1=\\\\\"$2\\\\\""); + } // quoting fixes for embedutils // ['\"]?(-DMBEDTLS_\S+)=\\?"(mbedtls\S+?)\\?\"["']? \"$1=\\\"$2\\\"\" @@ -196,7 +218,7 @@ static File MakePlatformSloeberTXT(File requestedFileToWorkAround) { String inFile = requestedFileToWorkAround.toString(); String actualFileToLoad = inFile.replace(PLATFORM_FILE_NAME, "platform.sloeber.txt"); if (inFile.equals(actualFileToLoad)) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "platform.txt file is not recognized " + requestedFileToWorkAround.toString())); return requestedFileToWorkAround; } @@ -219,7 +241,7 @@ static File MakePlatformSloeberTXT(File requestedFileToWorkAround) { Files.write(platformSloeberTXT.toPath(), platformTXT.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } catch (IOException e) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), + Activator.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to apply work arounds to " + requestedFileToWorkAround.toString(), e)); return requestedFileToWorkAround; } @@ -242,6 +264,7 @@ public static String platformApplyWorkArounds(String inPlatformTxt, File request platformTXT = platformTXT.replaceAll("(?m)^(\\S*)\\s*=", "$1="); // remove -MMD (the dependency generation parameter platformTXT = platformTXT.replaceAll(" -MMD ", " "); + // add a space at the end of the line platformTXT = platformTXT.replace("\n", " \n"); platformTXT = solveOSStuff(platformTXT); @@ -297,6 +320,11 @@ private static String platformApplyCustomWorkArounds(String inPlatformTxt) { platformTXT = platformTXT.replace(" \"@{build.opt.fqfn}\"", ""); platformTXT = platformTXT.replace("\"@{build.opt.fqfn}\"", ""); + //for leonardo on windows + if(isWindows) { + platformTXT = platformTXT.replace("build.usb_manufacturer=\"Unknown\"", "build.usb_manufacturer=\\\"Unknown\\\""); + } + return platformTXT; } @@ -351,9 +379,9 @@ private static String platformApplyStandardWorkArounds(String inPlatformTxt) { changed = changed + "{sloeber.extra.compile} {sloeber.extra.c.compile} {sloeber.extra.all}"; String codan = changed.replace(RECIPE_C_to_O, RECIPE_C_O_CODAN); codan = codan.replace(" -o ", " "); - codan = codan.replace(" {FLAGS} ", " "); + //codan = codan.replace(" {FLAGS} ", " "); codan = codan.replace(" {OUTPUT} ", " "); - codan = codan.replace(" {compiler.cpreprocessor.flags} ", " "); + //codan = codan.replace(" {compiler.cpreprocessor.flags} ", " "); codan = codan.replace(" {INPUTS} ", DISCOVERY_PARAMETERS.replace("${", "{") + BLANK); platformTXT = platformTXT.replace(origRecipe, changed + NEWLINE + codan); @@ -368,9 +396,9 @@ private static String platformApplyStandardWorkArounds(String inPlatformTxt) { changed = changed + "{sloeber.extra.compile} {sloeber.extra.cpp.compile} {sloeber.extra.all}"; String codan = changed.replace(RECIPE_CPP_to_O, RECIPE_CPP_O_CODAN); codan = codan.replace(" -o ", " "); - codan = codan.replace(" {FLAGS} ", " "); + //codan = codan.replace(" {FLAGS} ", " "); codan = codan.replace(" {OUTPUT} ", " "); - codan = codan.replace(" {compiler.cpreprocessor.flags} ", " "); + //codan = codan.replace(" {compiler.cpreprocessor.flags} ", " "); codan = codan.replace(" {INPUTS} ", DISCOVERY_PARAMETERS.replace("${", "{") + BLANK); platformTXT = platformTXT.replace(origRecipe, changed + NEWLINE + codan); @@ -403,7 +431,7 @@ private static String platformApplyStandardWorkArounds(String inPlatformTxt) { // the fix below seems no longer needed but is still on august 2021 // Arduino treats core differently so we need to change the location of directly // referenced files this manifests only in the combine recipe - String changed = origRecipe.replaceAll("(\\{build\\.path})(/core)?/sys", "$1/core/core/sys") + " "; + String changed = origRecipe.replaceAll("(\\{build\\.path})(/core)?/sys", "$1/"+SLOEBER_ARDUINO_FOLDER_NAME+SLACH+"{ConfigName}/core/sys") + " "; changed = changed.replace(" \"{build.path}/{archive_file}\" ", " {ARCHIVES} "); changed = changed.replace(" \"{archive_file_path}\" ", " {ARCHIVES} "); @@ -549,7 +577,7 @@ private static String solveOSStuff(String inpuText) { Otherosses.add(WINDOWSKEY); Otherosses.add(LINUXKEY); } else { - Common.log(new Status(IStatus.ERROR, Activator.getId(), "Failed to recognize the os you are using")); + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "Failed to recognize the os you are using")); return inpuText; } @@ -566,7 +594,7 @@ private static String solveOSStuff(String inpuText) { while (null != neededOSLine) { int keyIndex = neededOSLine.indexOf(thisOSKey); if (keyIndex < 0) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), "Error processing txt file: " + neededOSLine)); + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "Error processing txt file: " + neededOSLine)); neededOSLine = null; } else { String genericKey = neededOSLine.substring(0, keyIndex) + EQUAL; @@ -604,7 +632,7 @@ public static File MakeProgrammersSloeberTXT(File requestedFileToWorkAround) { String inFile = requestedFileToWorkAround.toString(); String actualFileToLoad = inFile.replace("programmers.txt", "programmers.sloeber.txt"); if (inFile.equals(actualFileToLoad)) { - Common.log(new Status(IStatus.ERROR, Activator.getId(), + Activator.log(new Status(IStatus.ERROR, Activator.getId(), "programmers.txt file is not recognized " + requestedFileToWorkAround.toString())); return requestedFileToWorkAround; } @@ -626,7 +654,7 @@ public static File MakeProgrammersSloeberTXT(File requestedFileToWorkAround) { Files.write(actualProgrammersTXT.toPath(), programmersTXT.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } catch (IOException e) { - Common.log(new Status(IStatus.WARNING, Activator.getId(), + Activator.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to apply work arounds to " + requestedFileToWorkAround.toString(), e)); return requestedFileToWorkAround; } diff --git a/io.sloeber.parent/pom.xml b/io.sloeber.parent/pom.xml index c5a184aba..f4a2e305e 100644 --- a/io.sloeber.parent/pom.xml +++ b/io.sloeber.parent/pom.xml @@ -9,7 +9,7 @@ pom - 4.0.8 + 4.0.9 ${project.build.directory}/repo diff --git a/io.sloeber.product.sdk/.classpath b/io.sloeber.product.sdk/.classpath index 3f74547ab..7eb7ec57d 100644 --- a/io.sloeber.product.sdk/.classpath +++ b/io.sloeber.product.sdk/.classpath @@ -1,6 +1,6 @@ - + diff --git a/io.sloeber.product.sdk/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.product.sdk/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..23fa13b17 --- /dev/null +++ b/io.sloeber.product.sdk/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,9 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=21 diff --git a/io.sloeber.product.sdk/META-INF/MANIFEST.MF b/io.sloeber.product.sdk/META-INF/MANIFEST.MF index bc8976496..442109a8c 100644 --- a/io.sloeber.product.sdk/META-INF/MANIFEST.MF +++ b/io.sloeber.product.sdk/META-INF/MANIFEST.MF @@ -3,6 +3,6 @@ Bundle-ManifestVersion: 2 Bundle-Name: Sloeber SDK Bundle-SymbolicName: io.sloeber.product.sdk;singleton:=true Bundle-Version: 5.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Vendor: baeyens.it Automatic-Module-Name: io.sloeber.product.sdk diff --git a/io.sloeber.product.sdk/sdk.product b/io.sloeber.product.sdk/sdk.product index d5acd2821..b7f45cc48 100644 --- a/io.sloeber.product.sdk/sdk.product +++ b/io.sloeber.product.sdk/sdk.product @@ -25,10 +25,10 @@ https://github.com/sloeber/arduino-eclipse-plugin/graphs/contributors --launcher.defaultAction openFile --launcher.appendVmargs - -Dorg.eclipse.update.reconcile=false --Dlog4j.configuration=log4j/log4j.xml --Xms256m --Xmx2048m + -Dorg.eclipse.update.reconcile=false +-Dlog4j.configuration=log4j/log4j.xml +-Xms256m +-Xmx2048m --add-modules=ALL-SYSTEM -XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts @@ -209,7 +209,6 @@ United States, other countries, or both. - @@ -239,7 +238,6 @@ United States, other countries, or both. - @@ -250,7 +248,6 @@ United States, other countries, or both. - diff --git a/io.sloeber.product/.classpath b/io.sloeber.product/.classpath index 1da84188f..87aa5a7bc 100644 --- a/io.sloeber.product/.classpath +++ b/io.sloeber.product/.classpath @@ -1,7 +1,7 @@ - + diff --git a/io.sloeber.product/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.product/.settings/org.eclipse.jdt.core.prefs index 62ef3488c..23fa13b17 100644 --- a/io.sloeber.product/.settings/org.eclipse.jdt.core.prefs +++ b/io.sloeber.product/.settings/org.eclipse.jdt.core.prefs @@ -1,9 +1,9 @@ eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=17 -org.eclipse.jdt.core.compiler.compliance=17 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=enabled -org.eclipse.jdt.core.compiler.source=17 +org.eclipse.jdt.core.compiler.source=21 diff --git a/io.sloeber.product/META-INF/MANIFEST.MF b/io.sloeber.product/META-INF/MANIFEST.MF index 9b1cb6b5f..946240015 100644 --- a/io.sloeber.product/META-INF/MANIFEST.MF +++ b/io.sloeber.product/META-INF/MANIFEST.MF @@ -4,6 +4,6 @@ Bundle-Name: Sloeber product Bundle-SymbolicName: io.sloeber.product;singleton:=true Bundle-Version: 5.0.0.qualifier Require-Bundle: io.sloeber.ui;bundle-version="5.0.0" -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Vendor: baeyens.it Automatic-Module-Name: io.sloeber.product diff --git a/io.sloeber.product/introContent.xml b/io.sloeber.product/introContent.xml deleted file mode 100644 index d379c164a..000000000 --- a/io.sloeber.product/introContent.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/io.sloeber.product/sloeber.product b/io.sloeber.product/sloeber.product index a9fd3c9df..25c5632d7 100644 --- a/io.sloeber.product/sloeber.product +++ b/io.sloeber.product/sloeber.product @@ -22,14 +22,14 @@ https://github.com/sloeber/arduino-eclipse-plugin/graphs/contributors - --launcher.defaultAction openFile + -perspective (io.sloeber.product.perspective) +--launcher.defaultAction openFile --launcher.appendVmargs ---perspective io.sloeber.product.perspective - -Dorg.eclipse.update.reconcile=false --Dlog4j.configuration=log4j/log4j.xml --Xms256m --Xmx4g + -Dorg.eclipse.update.reconcile=false +-Dlog4j.configuration=log4j/log4j.xml +-Xms256m +-Xmx4g --add-modules=ALL-SYSTEM -XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts @@ -219,10 +219,8 @@ United States, other countries, or both. - - @@ -248,7 +246,6 @@ United States, other countries, or both. - diff --git a/io.sloeber.product/sloeber.target b/io.sloeber.product/sloeber.target index dd75021ef..08d2e6cc7 100644 --- a/io.sloeber.product/sloeber.target +++ b/io.sloeber.product/sloeber.target @@ -2,7 +2,7 @@ - + @@ -22,7 +22,6 @@ - @@ -38,18 +37,20 @@ + + - + - + - + @@ -63,7 +64,7 @@ - + @@ -75,25 +76,37 @@ com.github.luben zstd-jni - 1.5.6-3 + 1.5.6-8 jar com.google.code.gson gson - 2.10.1 + 2.11.0 jar commons-io commons-io - 2.15.0 + 2.18.0 jar org.apache.commons commons-compress - 1.26.1 + 1.27.1 + jar + + + org.apache.logging.log4j + log4j-api + 2.19.0 + jar + + + org.apache.logging.log4j + log4j-core + 2.19.0 jar diff --git a/io.sloeber.tests/.classpath b/io.sloeber.tests/.classpath index b672bb973..5ac61f02c 100644 --- a/io.sloeber.tests/.classpath +++ b/io.sloeber.tests/.classpath @@ -1,6 +1,6 @@ - + @@ -11,6 +11,7 @@ + diff --git a/io.sloeber.tests/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.tests/.settings/org.eclipse.jdt.core.prefs index f78f7f772..96641ff8b 100644 --- a/io.sloeber.tests/.settings/org.eclipse.jdt.core.prefs +++ b/io.sloeber.tests/.settings/org.eclipse.jdt.core.prefs @@ -1,10 +1,10 @@ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=17 -org.eclipse.jdt.core.compiler.compliance=17 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=enabled -org.eclipse.jdt.core.compiler.source=17 +org.eclipse.jdt.core.compiler.source=21 diff --git a/io.sloeber.tests/BuildTests Sloeber Load packages.launch b/io.sloeber.tests/BuildTests Sloeber Load packages.launch new file mode 100644 index 000000000..b57e331f3 --- /dev/null +++ b/io.sloeber.tests/BuildTests Sloeber Load packages.launch @@ -0,0 +1,314 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/io.sloeber.tests/BuildTests Sloeber.launch b/io.sloeber.tests/BuildTests Sloeber.launch index 74a98e717..2d9159267 100644 --- a/io.sloeber.tests/BuildTests Sloeber.launch +++ b/io.sloeber.tests/BuildTests Sloeber.launch @@ -2,8 +2,9 @@ - - + + + @@ -11,10 +12,7 @@ - - - - + @@ -33,7 +31,7 @@ - + @@ -49,8 +47,8 @@ - - + + @@ -59,12 +57,13 @@ - + + + - @@ -86,18 +85,21 @@ + + - - + + + + - - - + + @@ -106,11 +108,11 @@ - + - - + + @@ -128,12 +130,9 @@ - - - @@ -156,7 +155,7 @@ - + @@ -184,16 +183,16 @@ - + - + - - + + - + @@ -201,34 +200,33 @@ - - - - - + + + + - - + + - + - - + + - + - + @@ -236,7 +234,7 @@ - + @@ -255,7 +253,7 @@ - + @@ -268,13 +266,13 @@ - + - + @@ -298,11 +296,10 @@ - + - - + diff --git a/io.sloeber.tests/BuildTests Sloeber_linux_jantje.launch b/io.sloeber.tests/BuildTests Sloeber_linux_jantje.launch new file mode 100644 index 000000000..ddb09d71e --- /dev/null +++ b/io.sloeber.tests/BuildTests Sloeber_linux_jantje.launch @@ -0,0 +1,309 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/io.sloeber.tests/META-INF/MANIFEST.MF b/io.sloeber.tests/META-INF/MANIFEST.MF index fea1aaa52..27aee41b1 100644 --- a/io.sloeber.tests/META-INF/MANIFEST.MF +++ b/io.sloeber.tests/META-INF/MANIFEST.MF @@ -3,30 +3,28 @@ Bundle-ManifestVersion: 2 Bundle-Name: Sloeber Tests Bundle-SymbolicName: io.sloeber.tests;singleton:=true Bundle-Version: 5.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Vendor: Sloeber.io -Require-Bundle: io.sloeber.core, - io.sloeber.ui, - org.eclipse.cdt.core, - org.eclipse.core.runtime, +Require-Bundle: org.eclipse.core.runtime, org.eclipse.core.resources, - junit-jupiter-params;bundle-version="5.10.2", - junit-jupiter-api;bundle-version="5.10.2", - org.apache.log4j, org.eclipse.swt, + org.eclipse.cdt.core, io.sloeber.autoBuild, - org.opentest4j, - junit-platform-suite-api + io.sloeber.core, + io.sloeber.ui, + junit-platform-suite-api, + junit-jupiter-params, + junit-jupiter-api, + org.apache.commons.commons-io, + org.apache.logging.log4j.api;bundle-version="2.19.0", + org.apache.logging.log4j.core;bundle-version="2.19.0" Bundle-ActivationPolicy: lazy Import-Package: io.sloeber.ui, io.sloeber.ui.monitor, io.sloeber.autoBuild.api, org.apache.commons.io Automatic-Module-Name: io.sloeber.tests -Export-Package: io.sloeber.core;x-internal:=true, - io.sloeber.junit;x-internal:=true, - io.sloeber.providers;x-internal:=true, - templates.CreateAndCompileTest;x-internal:=true, +Export-Package: templates.CreateAndCompileTest;x-internal:=true, templates.are_defines_found;x-internal:=true, templates.basic.ino;x-internal:=true, templates.defines_and_includes;x-internal:=true, diff --git a/io.sloeber.tests/pom.xml b/io.sloeber.tests/pom.xml index 94bb08cc4..ab8868a7a 100644 --- a/io.sloeber.tests/pom.xml +++ b/io.sloeber.tests/pom.xml @@ -13,9 +13,9 @@ - junit - junit - 4.13.1 + org.junit.jupiter + junit-jupiter-engine + 5.9.2 test diff --git a/io.sloeber.tests/src/io/sloeber/core/BuildTests.java b/io.sloeber.tests/src/io/sloeber/core/BuildTests.java index 28facd445..7f022d57d 100644 --- a/io.sloeber.tests/src/io/sloeber/core/BuildTests.java +++ b/io.sloeber.tests/src/io/sloeber/core/BuildTests.java @@ -2,7 +2,7 @@ - +import static io.sloeber.core.api.Const.*; import java.io.File; import java.util.Arrays; import java.util.Collection; @@ -15,6 +15,8 @@ import java.util.TreeMap; import java.util.stream.Stream; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import org.apache.commons.io.FileUtils; @@ -25,8 +27,10 @@ import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.cdt.internal.core.pdom.indexer.IndexerPreferences; import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; @@ -40,19 +44,19 @@ import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.*; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IExample; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; import io.sloeber.core.api.CodeDescription; import io.sloeber.core.api.CompileDescription; -import io.sloeber.core.api.IExample; import io.sloeber.core.api.CompileDescription.SizeCommands; import io.sloeber.core.api.CompileDescription.WarningLevels; -import io.sloeber.core.api.IArduinoLibraryVersion; import io.sloeber.core.api.ISloeberConfiguration; -import io.sloeber.core.api.LibraryManager; import io.sloeber.core.api.OtherDescription; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.SloeberProject; import io.sloeber.providers.Arduino; import io.sloeber.providers.ESP32; @@ -62,732 +66,843 @@ @SuppressWarnings({ "nls", "static-method", "null", "restriction" }) public class BuildTests { - private static final boolean reinstall_boards_and_libraries = false; - private final static String AUTOBUILD_CFG = ".autoBuildProject"; - private static final String HIDlibName = "HID-Project"; - - /* - * In new new installations (of the Sloeber development environment) the - * installer job will trigger downloads These must have finished before we can - * start testing - */ - @BeforeAll - public static void beforeClass() throws Exception { - Shared.waitForBoardsManager(); - Shared.setDeleteProjects(false); - Preferences.setUseBonjour(false); - installAdditionalBoards(); - installAdditionalLibs(); - } - - @BeforeEach - public void beforeTest() { - //make sure the fail message is cleaned before the tests is started - Shared.getLastFailMessage(); - } - - private static void installAdditionalLibs() { - LibraryManager.installLibrary(HIDlibName); - - } - - public static void installAdditionalBoards() throws Exception { - - String[] packageUrlsToAdd = { ESP8266.packageURL, ESP32.packageURL, - "http://talk2arduino.wisen.com.au/master/package_talk2.wisen.com_index.json" }; - BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd)), false); - Shared.waitForBoardsManager(); - if (reinstall_boards_and_libraries) { - BoardsManager.removeAllInstalledPlatforms(); - } - // make sure the needed boards are available - - ESP8266.installLatest(); - ESP32.installLatest(); - Arduino.installLatestAVRBoards(); - Teensy.installLatest(); - Arduino.installLatestSamDBoards(); - LibraryManager.installLibrary("RTCZero"); - - } - - /** - * make sure when switching between a board with variant file and without the - * build still succeeds - * - * @throws CoreException - */ - @Test - public void issue555() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - BoardDescription teensyBoardid = Teensy.Teensy3_1().getBoardDescriptor(); - - IProject theTestProject = null; - CodeDescription codeDescriptor = CodeDescription.createDefaultIno(); - String projectName = "issue555"; - NullProgressMonitor monitor = new NullProgressMonitor(); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - new CompileDescription(), monitor); - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - assertNull(Shared.hasBuildErrors(theTestProject)); - - CCorePlugin cCorePlugin = CCorePlugin.getDefault(); - ICProjectDescription cProjectDescription = cCorePlugin.getProjectDescription(theTestProject); - ICConfigurationDescription activeCfg = cProjectDescription.getActiveConfiguration(); - ISloeberConfiguration sloeberConf = ISloeberConfiguration.getConfig(activeCfg); - sloeberConf.setBoardDescription(teensyBoardid); - cCorePlugin.setProjectDescription(theTestProject, cProjectDescription); - - if (sloeberConf.getArduinoVariantFolder().exists()) { - fail("variant folder exists"); - } - - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - if (Shared.hasBuildErrors(theTestProject) != null) { - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - assertNull(Shared.hasBuildErrors(theTestProject)); - } - } - - /** - * support void loop{}; - * - * @throws Exception - */ - @Test - public void issue687() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - String projectName = "issue687"; - IPath templateFolder = Shared.getTemplateFolder(projectName); - CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - new CompileDescription(), new NullProgressMonitor()); - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); - assertNull(Shared.hasBuildErrors(theTestProject)); - } - - - - /** - * Test multiple ino's - */ - @Test - public void multipleINOs() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - String projectName = "multipleInos"; - IPath templateFolder = Shared.getTemplateFolder(projectName); - CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - new CompileDescription(), new NullProgressMonitor()); - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); - assertNull(Shared.hasBuildErrors(theTestProject)); - } - - - - - - @Test - public void create_CPP_based_Sloeber_Project() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - String projectName = "createCPPProject"; - - CodeDescription codeDescriptor = CodeDescription.createDefaultCPP(); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - new CompileDescription(), new NullProgressMonitor()); - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); - assertNull(Shared.hasBuildErrors(theTestProject)); - - } - - @Test - public void createDefaultInoProject() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - String projectName = "createDefaultInoProject"; - - CodeDescription codeDescriptor = CodeDescription.createDefaultIno(); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - new CompileDescription(), new NullProgressMonitor()); - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); - assertNull(Shared.hasBuildErrors(theTestProject)); - } - - /** - * support void loop{}; - * - * @throws Exception - */ - @Test - public void issue1047_Board_Names_Can_Be_used_as_Strings() throws Exception { - MCUBoard unoBoard = ESP8266.nodeMCU(); - - String projectName = "issue1047_Board_Names_Can_Be_used_as_Strings"; - IPath templateFolder = Shared.getTemplateFolder(projectName); - CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); - IProject theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoard.getBoardDescriptor(), - codeDescriptor, new CompileDescription(), new NullProgressMonitor()); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); - assertNull(Shared.hasBuildErrors(theTestProject)); - - } - - /** - * This test will fail if the arduino compile option are not taken into account - * To do sa a bunch of defines are added to the command line and the code checks - * whether these defines are set properly - * - * @throws Exception - */ - @Test - public void are_jantjes_options_taken_into_account() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - String projectName = "are_defines_found"; - IPath templateFolder = Shared.getTemplateFolder(projectName); - CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); - - NullProgressMonitor monitor = new NullProgressMonitor(); - CompileDescription compileOptions = new CompileDescription(); - compileOptions.set_C_andCPP_CompileOptions("-DTEST_C_CPP"); - compileOptions.set_C_CompileOptions("-DTEST_C"); - compileOptions.set_CPP_CompileOptions("-DTEST_CPP"); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - compileOptions, new NullProgressMonitor()); - - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - assertNull(Shared.hasBuildErrors(theTestProject)); - } - - /** - * If a .ino file is including a include using extern C is this handled properly - * by the ino to cpp parser - * - * @throws Exception - */ - @Test - public void is_extern_C_taken_into_account() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - String projectName = "externc"; - IPath templateFolder = Shared.getTemplateFolder(projectName); - CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); - - NullProgressMonitor monitor = new NullProgressMonitor(); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - new CompileDescription(), new NullProgressMonitor()); - - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - assertNull(Shared.hasBuildErrors(theTestProject)); - } - - /** - * If a .ino file is defining defines before including a include this should be - * handled properly by the ino to cpp parser - * - * @throws Exception - */ - @Test - public void are_defines_before_includes_taken_into_account() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - String projectName = "defines_and_includes"; - IPath templateFolder = Shared.getTemplateFolder(projectName); - CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); - - NullProgressMonitor monitor = new NullProgressMonitor(); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - new CompileDescription(), new NullProgressMonitor()); - - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - assertNull(Shared.hasBuildErrors(theTestProject)); - - } - - /** - * Does Sloeber still compile after a configuration renamen - * - * @throws Exception - */ - @Test - public void rename_Configuration() throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - String projectName = "rename_Configuration"; - - CodeDescription codeDescriptor = CodeDescription.createDefaultIno(); - - NullProgressMonitor monitor = new NullProgressMonitor(); - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - new CompileDescription(), new NullProgressMonitor()); - - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - assertNull( Shared.hasBuildErrors(theTestProject),"Failed to compile the project before config rename"); - - CCorePlugin cCorePlugin = CCorePlugin.getDefault(); - ICProjectDescription prjCDesc = cCorePlugin.getProjectDescription(theTestProject); - ICConfigurationDescription activeConfig = prjCDesc.getActiveConfiguration(); - activeConfig.setName("renamedConfig"); - cCorePlugin.setProjectDescription(theTestProject, prjCDesc); - - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - assertNull(Shared.hasBuildErrors(theTestProject),"Failed to compile the project after config rename" ); - } - - // /** - // * Does Sloeber still compile after a project rename - // * - // * @throws Exception - // */ - // @Test - // public void rename_Project() throws Exception { - // BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - // - // IProject theTestProject = null; - // String projectName = "rename_project"; - // String projectNameRenamed = "renamed_project"; - // - // CodeDescription codeDescriptor = CodeDescription.createDefaultIno(); - // - // NullProgressMonitor monitor = new NullProgressMonitor(); - // theTestProject = SloeberProject.createArduinoProject(projectName, null, - // unoBoardid, codeDescriptor, - // new CompileDescription(), new NullProgressMonitor()); - // - // Shared.waitForAllJobsToFinish(); // for the indexer - // theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - // if (Shared.hasBuildErrors(theTestProject)) { - // fail("Failed to compile the project before project rename"); - // } - // theTestProject.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor); - // - // CCorePlugin cCorePlugin = CCorePlugin.getDefault(); - // ICProjectDescription prjCDesc = - // cCorePlugin.getProjectDescription(theTestProject); - // - // IProjectDescription descr = theTestProject.getDescription(); - // descr.ren(projectNameRenamed); - // theTestProject.setDescription(descr, null); - // - // Shared.waitForAllJobsToFinish(); // for the indexer - // theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - // if (Shared.hasBuildErrors(theTestProject)) { - // fail("Failed to compile the project after project rename"); - // } - // } - - /** - * open and close a project should keep the compileDescription and - * BoardDescriotion - * - * @throws Exception - */ - @ParameterizedTest - @MethodSource("openAndClosePreservesSettingsValueCmd") - public void openAndClosePreservesSettings(String projectName, CodeDescription codeDescriptor) throws Exception { - BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); - - IProject theTestProject = null; - - CompileDescription inCompileDescription = getBunkersCompileDescription(); - - theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, - inCompileDescription, new NullProgressMonitor()); - - Shared.waitForIndexer(theTestProject); - // also do a build - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, null); - assertNull(Shared.hasBuildErrors(theTestProject),"Failed to compile the project before close: " + projectName); - - // also do a clean - theTestProject.build(IncrementalProjectBuilder.CLEAN_BUILD, null); - - // Read the data we want to test - ISloeberConfiguration sloeberConf = ISloeberConfiguration.getActiveConfig(theTestProject); - BoardDescription createdBoardDesc = sloeberConf.getBoardDescription(); - CompileDescription createdCompileDesc = sloeberConf.getCompileDescription(); - - // close and reopen the project - theTestProject.close(null); - // just wait a while - Thread.sleep(1000); - theTestProject.open(null); - Shared.waitForIndexer(theTestProject); - - // read the data we want to test - sloeberConf = ISloeberConfiguration.getActiveConfig(theTestProject); - if (sloeberConf == null) { - fail("failed to open and close project"); - } - BoardDescription reopenedBoardDesc = sloeberConf.getBoardDescription(); - CompileDescription reopenedCompileDesc = sloeberConf.getCompileDescription(); - - // check the data is equal - boolean createBoardsDiff = !unoBoardid.equals(createdBoardDesc); - boolean createCompileDiff = !inCompileDescription.equals(createdCompileDesc); - boolean openBoardsDiff = !reopenedBoardDesc.equals(createdBoardDesc); - boolean openCompileDiff = !reopenedCompileDesc.equals(createdCompileDesc); - - if (createBoardsDiff || createCompileDiff) { - fail("Created project does not match creation parameters."); - } - if (openBoardsDiff || openCompileDiff) { - fail("Opened project does not match closed project parameters."); - } - - // also do a build - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, null); - assertNull(Shared.hasBuildErrors(theTestProject),"Failed to compile the project after open: " + projectName); - - } - - /** - * open and close a project should keep the compileDescription and - * BoardDescriotion - * - * @throws Exception - */ - - @Test - public void openModAndCloseUsesSavedSettings() throws Exception { - CodeDescription codeDesc = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); - - String proj1Name = "openModAndClose1"; - BoardDescription proj1BoardDesc = Arduino.uno().getBoardDescriptor(); - OtherDescription otherDesc = new OtherDescription(); - otherDesc.setVersionControlled(true); - CompileDescription proj1CompileDesc = getBunkersCompileDescription(); - IProject proj1 = SloeberProject.createArduinoProject(proj1Name, null, proj1BoardDesc, codeDesc, - proj1CompileDesc, otherDesc, new NullProgressMonitor()); - - String proj2Name = "openModAndClose2"; - BoardDescription proj2BoardDesc = Arduino.mega2560Board().getBoardDescriptor(); - CompileDescription proj2CompileDesc = new CompileDescription(); - IProject proj2 = SloeberProject.createArduinoProject(proj2Name, null, proj2BoardDesc, codeDesc, - proj2CompileDesc, new NullProgressMonitor()); - - // Read the data we want to test - ISloeberConfiguration sloeberConf = ISloeberConfiguration.getActiveConfig(proj1); - BoardDescription proj1CreatedBoardDesc = sloeberConf.getBoardDescription(); - CompileDescription proj1CreatedCompileDesc = sloeberConf.getCompileDescription(); - - ISloeberConfiguration sloeberConf2 = ISloeberConfiguration.getActiveConfig(proj2); - BoardDescription proj2CreatedBoardDesc = sloeberConf2.getBoardDescription(); - CompileDescription proj2CreatedCompileDesc = sloeberConf2.getCompileDescription(); - - // get the filenames to copy - IFile file = proj1.getFile(AUTOBUILD_CFG); - File proj1SloeberFile = file.getLocation().toFile(); - - file = proj2.getFile(AUTOBUILD_CFG); - File proj2SloeberFile = file.getLocation().toFile(); - - // close and reopen the project - proj2.close(null); - // just wait a while - Thread.sleep(1000); - - // copy from proj1 to proj2 - FileUtils.copyFile(proj1SloeberFile, proj2SloeberFile); - - // reopen the project - proj2.open(null); - Shared.waitForIndexer(proj2); - - // reread project 2 - ISloeberConfiguration sloebercfg2 = ISloeberConfiguration.getActiveConfig(proj2); - if (sloebercfg2 == null) { - fail("failed to load the sloeber configuration"); - } - BoardDescription proj2OpenedBoardDesc = sloebercfg2.getBoardDescription(); - CompileDescription proj2OpenedCompileDesc = sloebercfg2.getCompileDescription(); - - // check the setup was done correctly - if (!proj1BoardDesc.equals(proj1CreatedBoardDesc)) { - fail("Project 1 not created properly."); - } - if (!proj2BoardDesc.equals(proj2CreatedBoardDesc)) { - fail("Project 2 not created properly."); - } - if (!proj1CompileDesc.equals(proj1CreatedCompileDesc)) { - fail("Project 1 not created properly."); - } - if (!proj2CompileDesc.equals(proj2CreatedCompileDesc)) { - fail("Project 2 not created properly."); - } - - // check wether the file modification was taken into account - if (!proj1BoardDesc.equals(proj2OpenedBoardDesc)) { - fail("Project 2 not created properly."); - } - if (!proj1CompileDesc.equals(proj2OpenedCompileDesc)) { - fail("Project 2 not created properly."); - } - - } - - @Test - public void createProjectWithURI() throws Exception { - CodeDescription codeDesc = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); - - String proj1Name = "projectWithURI"; - String codeFolderName = "locationWithURI"; - BoardDescription proj1BoardDesc = Arduino.uno().getBoardDescriptor(); - OtherDescription otherDesc = new OtherDescription(); - CompileDescription proj1CompileDesc = getBunkersCompileDescription(); - final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - IPath projectFolder = workspace.getRoot().getLocation().removeLastSegments(1).append(codeFolderName); - URI uri = projectFolder.toFile().toURI(); - // workspace.getRoot().getFolder(Path.fromOSString(codeFolderName)).getLocationURI(); - IProject theTestProject = SloeberProject.createArduinoProject(proj1Name, uri, proj1BoardDesc, codeDesc, - proj1CompileDesc, otherDesc, new NullProgressMonitor()); - - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, null); - assertNull(Shared.hasBuildErrors(theTestProject), - "Failed to compile the project: " + Shared.hasBuildErrors(theTestProject)); - String fileLocation = projectFolder.append("src").append(proj1Name + ".cpp").toString(); - - IFile cppFile = theTestProject.getFolder("src").getFile(proj1Name + ".cpp"); - assertTrue( cppFile.exists(),"File not in correct location"); - assertEquals( cppFile.getLocation().toString(), fileLocation,"File not in correct location"); - - } - - static CompileDescription getBunkersCompileDescription() { - CompileDescription inCompileDescription = new CompileDescription(); - - inCompileDescription.set_All_CompileOptions("-Deen=1"); - inCompileDescription.set_Archive_CompileOptions("-Dtwee=2"); - inCompileDescription.set_Assembly_CompileOptions("-Drie=3"); - inCompileDescription.set_C_andCPP_CompileOptions("-Dvier=4"); - inCompileDescription.set_C_CompileOptions("-Dvijf=5"); - inCompileDescription.set_Link_CompileOptions("-Dzes=6"); - inCompileDescription.set_CPP_CompileOptions("-Dzeven=7"); - inCompileDescription.setSizeCommand(SizeCommands.ARDUINO_WAY); - inCompileDescription.setEnableParallelBuild(true); - inCompileDescription.setWarningLevel(WarningLevels.NONE); - return inCompileDescription; - } - - /** - * check to see whether upload recipe key is correct for a couple of boards that - * have failed in the past - * - * @throws Exception - */ - @Test - public void uploadPattern() throws Exception { - BoardDescription boardDescriptor = Arduino.uno().getBoardDescriptor(); - String recipeKey = boardDescriptor.getUploadPatternKey(); - assertEquals( "tools.avrdude.upload.pattern", recipeKey,"uno upload recipe key is wrong"); - boardDescriptor = ESP32.esp32().getBoardDescriptor(); - boardDescriptor.setUploadPort("host 10.10.10.10"); - recipeKey = boardDescriptor.getUploadPatternKey(); - assertEquals( "tools.esptool_py.upload.network_pattern", recipeKey,"ESP OTA upload recipe key is wrong"); - - } - - public static Stream testDifferentSourceFoldersData() throws Exception { - List ret = new LinkedList<>(); - OtherDescription otherDesc = new OtherDescription(); - CompileDescription projCompileDesc = new CompileDescription(); - - MCUBoard unoboard = Arduino.uno(); - CodeDescription codeDescriptor1 = CodeDescription.createDefaultCPP(); - codeDescriptor1.setCodeFolder(null); - String projectName1 = Shared.getProjectName(codeDescriptor1, unoboard); - ret.add(Arguments.of(projectName1, codeDescriptor1, unoboard, otherDesc, projCompileDesc)); - - CodeDescription codeDescriptor2 = CodeDescription.createDefaultCPP(); - codeDescriptor2.setCodeFolder("src"); - String projectName2 = Shared.getProjectName(codeDescriptor2, unoboard); - ret.add(Arguments.of(projectName2, codeDescriptor2, unoboard, otherDesc, projCompileDesc)); - - CodeDescription codeDescriptor3 = CodeDescription.createDefaultCPP(); - codeDescriptor3.setCodeFolder("SRC"); - String projectName3 = Shared.getProjectName(codeDescriptor3, unoboard); - ret.add(Arguments.of(projectName3, codeDescriptor3, unoboard, otherDesc, projCompileDesc)); - - CodeDescription codeDescriptor4 = CodeDescription.createDefaultCPP(); - codeDescriptor4.setCodeFolder("blabla"); - String projectName4 = Shared.getProjectName(codeDescriptor4, unoboard); - ret.add(Arguments.of(projectName4, codeDescriptor4, unoboard, otherDesc, projCompileDesc)); - - return ret.stream(); - - } - - @ParameterizedTest - @MethodSource("testDifferentSourceFoldersData") - public void testDifferentSourceFolders(String projectName, CodeDescription codeDescriptor, MCUBoard board, - OtherDescription otherDesc, CompileDescription proj1CompileDesc) throws Exception { - - BoardDescription proj1BoardDesc = board.getBoardDescriptor(); - IProject theTestProject = SloeberProject.createArduinoProject(projectName, null, proj1BoardDesc, codeDescriptor, - proj1CompileDesc, otherDesc, new NullProgressMonitor()); - - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, null); - assertNull( Shared.hasBuildErrors(theTestProject),"Failed to compile " + projectName); - - String srcFolder = codeDescriptor.getCodeFolder(); - IFile cppFile = null; - if (srcFolder == null) { - cppFile = theTestProject.getFile(projectName + ".cpp"); - } else { - cppFile = theTestProject.getFolder(srcFolder).getFile(projectName + ".cpp"); - } - assertTrue( cppFile.exists(),"Source File not in right location " + projectName); - } - - /** - * Test wether a platform json redirect is handled properly - * https://github.com/jantje/arduino-eclipse-plugin/issues/393 - * - * @throws Exception - */ - @Test - public void redirectedJson() throws Exception { - // this board references to arduino avr so install that one to - Arduino.installLatestAVRBoards(); - BoardsManager.installLatestPlatform("package_talk2.wisen.com_index.json", "Talk2", "avr"); - Map options = new HashMap<>(); - options.put("mhz", "16MHz"); - BoardDescription boardid = BoardsManager.getBoardDescription("package_talk2.wisen.com_index.json", "Talk2", - "avr", "whispernode", options); - if (boardid == null) { - fail("redirect Json "); - return; - } - assertNull(Shared.buildAndVerify("redirect_json", boardid, CodeDescription.createDefaultIno(), - new CompileDescription())); - } - - @Test - public void issue1126LibArchiver() throws Exception { - - MCUBoard leonardoBoard = Arduino.leonardo(); - Map examples = LibraryManager.getExamplesAll(null); - CompileDescription compileDesc = new CompileDescription(); - compileDesc.setEnableParallelBuild(true); - IArduinoLibraryVersion lib = null; - IExample example = null; - for (IExample curExample : examples.values()) { - Collection curLibs = curExample.getArduinoLibraries(); - if (curLibs.size() == 0) { - continue; - } - for (IArduinoLibraryVersion curLib : curLibs) { - if (curLib.getName().equals(HIDlibName)) { - example = curExample; - lib = curLib; - break; - } - } - } - assertNotNull( lib,"HID Lib \"" + HIDlibName + "\" Not found"); - - Set testExamples = new HashSet<>(); - testExamples.add(example); - CodeDescription codeDescriptor = CodeDescription.createExample(false, testExamples); - NullProgressMonitor monitor = new NullProgressMonitor(); - - IProject theTestProject = SloeberProject.createArduinoProject("issue1126LibArchiver", null, - leonardoBoard.getBoardDescriptor(), codeDescriptor, compileDesc, null, null, monitor); - - IndexerPreferences.setScope(theTestProject, IndexerPreferences.SCOPE_PROJECT_PRIVATE); - IndexerPreferences.set(theTestProject, IndexerPreferences.KEY_INCLUDE_HEURISTICS, Boolean.FALSE.toString()); - ICProject icProject = CoreModel.getDefault().create(theTestProject); - CCorePlugin.getIndexManager().reindex(icProject); - - Shared.waitForIndexer(theTestProject); - Thread.sleep(1000);//just make sure the libs can get added - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - IAutoBuildConfigurationDescription autoDesc = IAutoBuildConfigurationDescription.getActiveConfig(theTestProject, - false); - IFile libArchive = autoDesc.getBuildFolder().getFile(HIDlibName + ".ar"); - if(!libArchive.exists()) { - Thread.sleep(1000);//just make sure the libs can get added - Shared.waitForIndexer(theTestProject); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - } - assertTrue( libArchive.exists(),"Archive " + libArchive.toString() + " does not exists"); - - } - - static Stream openAndClosePreservesSettingsValueCmd() throws Exception { - CodeDescription codeDescriptordefaultCPPRoot = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); - CodeDescription codeDescriptordefaultCPPSrc = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); - CodeDescription codeDescriptordefaultCPXX = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); - - codeDescriptordefaultCPPRoot.setCodeFolder(null); - codeDescriptordefaultCPPSrc.setCodeFolder("src"); - codeDescriptordefaultCPXX.setCodeFolder("XX"); - - List ret = new LinkedList<>(); - ret.add(Arguments.of(Shared.getCounterName("openAndCloseRoot"), codeDescriptordefaultCPPRoot)); - ret.add(Arguments.of(Shared.getCounterName("openAndCloseSrc"), codeDescriptordefaultCPPSrc)); - ret.add(Arguments.of(Shared.getCounterName("openAndCloseXX"), codeDescriptordefaultCPXX)); - - return ret.stream(); - } - - public static Stream NightlyBoardPatronTestData() throws Exception { - Preferences.setUseArduinoToolSelection(true); - CompileDescription compileOptions = new CompileDescription(); - MCUBoard zeroBoard = Arduino.zeroProgrammingPort(); - - List ret = new LinkedList<>(); - TreeMap examples = LibraryManager.getExamplesLibrary(null); - for (Map.Entry curexample : examples.entrySet()) { - String fqn = curexample.getKey().trim(); - IExample example = curexample.getValue(); - IPath examplePath = example.getCodeLocation(); - if (fqn.contains("RTCZero")) { - Example SloeberExample = new Example(fqn, examplePath); - - ret.add(Arguments.of(Shared.getCounterName(SloeberExample.calcLibName() + ":" + example.getName()), - zeroBoard, SloeberExample, compileOptions)); - } - } - return ret.stream(); - } - - @ParameterizedTest - @MethodSource("NightlyBoardPatronTestData") - public void NightlyBoardPatron(String name, MCUBoard boardID, Example example, CompileDescription compileOptions) - throws Exception { - Shared.getLastFailMessage(); - Set examples = new HashSet<>(); - examples.add(example); - CodeDescription codeDescriptor = CodeDescription.createExample(false, examples); - - BoardDescription boardDescriptor = boardID.getBoardDescriptor(); - boardDescriptor.setOptions(boardID.getBoardOptions(example)); - assertNull( - Shared.buildAndVerifyAllBuilders(name, boardID.getBoardDescriptor(), codeDescriptor, compileOptions)); - - } - + private static final boolean reinstall_boards_and_libraries = false; + private final static String AUTOBUILD_CFG = ".autoBuildProject"; + private static final String HIDlibName = "HID-Project"; + private static final String packageURL= "http://talk2arduino.wisen.com.au/master/package_talk2.wisen.com_index.json"; + + /* + * In new new installations (of the Sloeber development environment) the + * installer job will trigger downloads These must have finished before we can + * start testing + */ + @BeforeAll + public static void beforeClass() throws Exception { + Shared.waitForBoardsManager(); + Shared.setDeleteProjects(false); + ConfigurationPreferences.setUseBonjour(false); + installAdditionalBoards(); + installAdditionalLibs(); + } + + @BeforeEach + public void beforeTest() { + //make sure the fail message is cleaned before the tests is started + Shared.getLastFailMessage(); + } + + private static void installAdditionalLibs() { + LibraryManager.installLibrary(HIDlibName); + + } + + public static void installAdditionalBoards() throws Exception { + + String[] packageUrlsToAdd = { ESP8266.packageURL, ESP32.packageURL,packageURL}; + BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd))); + BoardsManager.update(false); + Shared.waitForBoardsManager(); + if (reinstall_boards_and_libraries) { + BoardsManager.removeAllInstalledPlatforms(); + } + // make sure the needed boards are available + + ESP8266.installLatest(); + ESP32.installLatest(); + Arduino.installLatestAVRBoards(); + Teensy.installLatest(); + Arduino.installLatestSamDBoards(); + LibraryManager.installLibrary("RTCZero"); + BoardsManager.update(false); + Shared.waitForBoardsManager(); + + } + + /** + * make sure when switching between a board with variant file and without the + * build still succeeds + * + * @throws CoreException + */ + @Test + public void issue555() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + BoardDescription teensyBoardid = Teensy.Teensy3_1().getBoardDescriptor(); + + IProject theTestProject = null; + CodeDescription codeDescriptor = CodeDescription.createDefaultIno(); + String projectName = "issue555"; + NullProgressMonitor monitor = new NullProgressMonitor(); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), monitor); + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + assertNull(Shared.hasBuildErrors(theTestProject)); + + CCorePlugin cCorePlugin = CCorePlugin.getDefault(); + ICProjectDescription cProjectDescription = cCorePlugin.getProjectDescription(theTestProject); + ICConfigurationDescription activeCfg = cProjectDescription.getActiveConfiguration(); + ISloeberConfiguration sloeberConf = ISloeberConfiguration.getConfig(activeCfg); + sloeberConf.setBoardDescription(teensyBoardid); + cCorePlugin.setProjectDescription(theTestProject, cProjectDescription); + + if (sloeberConf.getArduinoVariantFolder().exists()) { + fail("variant folder exists"); + } + + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + if (Shared.hasBuildErrors(theTestProject) != null) { + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + assertNull(Shared.hasBuildErrors(theTestProject)); + } + } + + /** + * support void loop{}; + * + * @throws Exception + */ + @Test + public void issue687() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + String projectName = "issue687"; + IPath templateFolder = Shared.getTemplateFolder(projectName); + CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), new NullProgressMonitor()); + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); + assertNull(Shared.hasBuildErrors(theTestProject)); + } + + + + /** + * Test multiple ino's + */ + @Test + public void multipleINOs() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + String projectName = "multipleInos"; + IPath templateFolder = Shared.getTemplateFolder(projectName); + CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), new NullProgressMonitor()); + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); + assertNull(Shared.hasBuildErrors(theTestProject)); + } + + + + + + @Test + public void create_CPP_based_Sloeber_Project() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + String projectName = "createCPPProject"; + + CodeDescription codeDescriptor = CodeDescription.createDefaultCPP(); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), new NullProgressMonitor()); + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); + assertNull(Shared.hasBuildErrors(theTestProject)); + + } + + @Test + public void createDefaultInoProject() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + String projectName = "createDefaultInoProject"; + + CodeDescription codeDescriptor = CodeDescription.createDefaultIno(); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), new NullProgressMonitor()); + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); + assertNull(Shared.hasBuildErrors(theTestProject)); + } + + /** + * support void loop{}; + * + * @throws Exception + */ + @ParameterizedTest + @MethodSource("issue1047_Board_Names_Can_Be_used_as_StringsData") + public void issue1047_Board_Names_Can_Be_used_as_Strings(String projectName, MCUBoard board) throws Exception { + + IPath templateFolder = Shared.getTemplateFolder("issue1047_Board_Names_Can_Be_used_as_Strings"); + CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); + IProject theTestProject = SloeberProject.createArduinoProject(projectName, null, board.getBoardDescriptor(), + codeDescriptor, new CompileDescription(), new NullProgressMonitor()); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); + assertNull(Shared.hasBuildErrors(theTestProject)); + } + + public static Stream issue1047_Board_Names_Can_Be_used_as_StringsData() throws Exception { + List ret = new LinkedList<>(); + ret.add(Arguments.of("issue1047_Leonardo_Board_Names_Can_Be_used_as_Strings", Arduino.leonardo())); + ret.add(Arguments.of("issue1047_Zero_Board_Names_Can_Be_used_as_Strings", Arduino.zeroNatviePort())); + ret.add(Arguments.of("issue1047_ESP32S3_Board_Names_Can_Be_used_as_Strings", ESP32.ESP32S3())); + return ret.stream(); + } + + /** + * This test will fail if the arduino compile option are not taken into account + * To do sa a bunch of defines are added to the command line and the code checks + * whether these defines are set properly + * + * @throws Exception + */ + @Test + public void are_jantjes_options_taken_into_account() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + String projectName = "are_defines_found"; + IPath templateFolder = Shared.getTemplateFolder(projectName); + CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); + + NullProgressMonitor monitor = new NullProgressMonitor(); + CompileDescription compileOptions = new CompileDescription(); + compileOptions.set_C_andCPP_CompileOptions("-DTEST_C_CPP"); + compileOptions.set_C_CompileOptions("-DTEST_C"); + compileOptions.set_CPP_CompileOptions("-DTEST_CPP"); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + compileOptions, new NullProgressMonitor()); + + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + assertNull(Shared.hasBuildErrors(theTestProject)); + } + + /** + * If a .ino file is including a include using extern C is this handled properly + * by the ino to cpp parser + * + * @throws Exception + */ + @Test + public void is_extern_C_taken_into_account() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + String projectName = "externc"; + IPath templateFolder = Shared.getTemplateFolder(projectName); + CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); + + NullProgressMonitor monitor = new NullProgressMonitor(); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), new NullProgressMonitor()); + + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + assertNull(Shared.hasBuildErrors(theTestProject)); + } + + /** + * If a .ino file is defining defines before including a include this should be + * handled properly by the ino to cpp parser + * + * @throws Exception + */ + @Test + public void are_defines_before_includes_taken_into_account() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + String projectName = "defines_and_includes"; + IPath templateFolder = Shared.getTemplateFolder(projectName); + CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); + + NullProgressMonitor monitor = new NullProgressMonitor(); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), new NullProgressMonitor()); + + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + assertNull(Shared.hasBuildErrors(theTestProject)); + + } + + /** + * Does Sloeber still compile after a configuration renamen + * + * @throws Exception + */ + @Test + public void rename_Configuration() throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + String projectName = "rename_Configuration"; + + CodeDescription codeDescriptor = CodeDescription.createDefaultIno(); + + NullProgressMonitor monitor = new NullProgressMonitor(); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), new NullProgressMonitor()); + + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + assertNull( Shared.hasBuildErrors(theTestProject),"Failed to compile the project before config rename"); + + CCorePlugin cCorePlugin = CCorePlugin.getDefault(); + ICProjectDescription prjCDesc = cCorePlugin.getProjectDescription(theTestProject); + ICConfigurationDescription activeConfig = prjCDesc.getActiveConfiguration(); + activeConfig.setName("renamedConfig"); + cCorePlugin.setProjectDescription(theTestProject, prjCDesc); + + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + assertNull(Shared.hasBuildErrors(theTestProject),"Failed to compile the project after config rename" ); + } + + // /** + // * Does Sloeber still compile after a project rename + // * + // * @throws Exception + // */ + // @Test + // public void rename_Project() throws Exception { + // BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + // + // IProject theTestProject = null; + // String projectName = "rename_project"; + // String projectNameRenamed = "renamed_project"; + // + // CodeDescription codeDescriptor = CodeDescription.createDefaultIno(); + // + // NullProgressMonitor monitor = new NullProgressMonitor(); + // theTestProject = SloeberProject.createArduinoProject(projectName, null, + // unoBoardid, codeDescriptor, + // new CompileDescription(), new NullProgressMonitor()); + // + // Shared.waitForAllJobsToFinish(); // for the indexer + // theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + // if (Shared.hasBuildErrors(theTestProject)) { + // fail("Failed to compile the project before project rename"); + // } + // theTestProject.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor); + // + // CCorePlugin cCorePlugin = CCorePlugin.getDefault(); + // ICProjectDescription prjCDesc = + // cCorePlugin.getProjectDescription(theTestProject); + // + // IProjectDescription descr = theTestProject.getDescription(); + // descr.ren(projectNameRenamed); + // theTestProject.setDescription(descr, null); + // + // Shared.waitForAllJobsToFinish(); // for the indexer + // theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + // if (Shared.hasBuildErrors(theTestProject)) { + // fail("Failed to compile the project after project rename"); + // } + // } + + /** + * open and close a project should keep the compileDescription and + * BoardDescriotion + * + * @throws Exception + */ + @ParameterizedTest + @MethodSource("openAndClosePreservesSettingsValueCmd") + public void openAndClosePreservesSettings(String projectName, CodeDescription codeDescriptor) throws Exception { + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + + IProject theTestProject = null; + + CompileDescription inCompileDescription = getBunkersCompileDescription(); + + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + inCompileDescription, new NullProgressMonitor()); + + Shared.waitForIndexer(theTestProject); + // also do a build + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, null); + assertNull(Shared.hasBuildErrors(theTestProject),"Failed to compile the project before close: " + projectName); + + // also do a clean + theTestProject.build(IncrementalProjectBuilder.CLEAN_BUILD, null); + + // Read the data we want to test + ISloeberConfiguration sloeberConf = ISloeberConfiguration.getActiveConfig(theTestProject); + BoardDescription createdBoardDesc = sloeberConf.getBoardDescription(); + CompileDescription createdCompileDesc = sloeberConf.getCompileDescription(); + + // close and reopen the project + theTestProject.close(null); + // just wait a while + Thread.sleep(1000); + theTestProject.open(null); + Shared.waitForIndexer(theTestProject); + + // read the data we want to test + sloeberConf = ISloeberConfiguration.getActiveConfig(theTestProject); + if (sloeberConf == null) { + fail("failed to open and close project"); + } + BoardDescription reopenedBoardDesc = sloeberConf.getBoardDescription(); + CompileDescription reopenedCompileDesc = sloeberConf.getCompileDescription(); + + // check the data is equal + boolean createBoardsDiff = !unoBoardid.equals(createdBoardDesc); + boolean createCompileDiff = !inCompileDescription.equals(createdCompileDesc); + boolean openBoardsDiff = !reopenedBoardDesc.equals(createdBoardDesc); + boolean openCompileDiff = !reopenedCompileDesc.equals(createdCompileDesc); + + if (createBoardsDiff || createCompileDiff) { + fail("Created project does not match creation parameters."); + } + if (openBoardsDiff || openCompileDiff) { + fail("Opened project does not match closed project parameters."); + } + + // also do a build + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, null); + assertNull(Shared.hasBuildErrors(theTestProject),"Failed to compile the project after open: " + projectName); + + } + + /** + * open and close a project should keep the compileDescription and + * BoardDescriotion + * + * @throws Exception + */ + + @Test + public void openModAndCloseUsesSavedSettings() throws Exception { + CodeDescription codeDesc = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); + + String proj1Name = "openModAndClose1"; + BoardDescription proj1BoardDesc = Arduino.uno().getBoardDescriptor(); + OtherDescription otherDesc = new OtherDescription(); + otherDesc.setVersionControlled(true); + CompileDescription proj1CompileDesc = getBunkersCompileDescription(); + IProject proj1 = SloeberProject.createArduinoProject(proj1Name, null, proj1BoardDesc, codeDesc, + proj1CompileDesc, otherDesc, new NullProgressMonitor()); + + String proj2Name = "openModAndClose2"; + BoardDescription proj2BoardDesc = Arduino.mega2560Board().getBoardDescriptor(); + CompileDescription proj2CompileDesc = new CompileDescription(); + IProject proj2 = SloeberProject.createArduinoProject(proj2Name, null, proj2BoardDesc, codeDesc, + proj2CompileDesc, new NullProgressMonitor()); + + // Read the data we want to test + ISloeberConfiguration sloeberConf = ISloeberConfiguration.getActiveConfig(proj1); + BoardDescription proj1CreatedBoardDesc = sloeberConf.getBoardDescription(); + CompileDescription proj1CreatedCompileDesc = sloeberConf.getCompileDescription(); + + ISloeberConfiguration sloeberConf2 = ISloeberConfiguration.getActiveConfig(proj2); + BoardDescription proj2CreatedBoardDesc = sloeberConf2.getBoardDescription(); + CompileDescription proj2CreatedCompileDesc = sloeberConf2.getCompileDescription(); + + // get the filenames to copy + IFile file = proj1.getFile(AUTOBUILD_CFG); + File proj1SloeberFile = file.getLocation().toFile(); + + file = proj2.getFile(AUTOBUILD_CFG); + File proj2SloeberFile = file.getLocation().toFile(); + + // close and reopen the project + proj2.close(null); + // just wait a while + Thread.sleep(1000); + + // copy from proj1 to proj2 + FileUtils.copyFile(proj1SloeberFile, proj2SloeberFile); + + // reopen the project + proj2.open(null); + Shared.waitForIndexer(proj2); + + // reread project 2 + ISloeberConfiguration sloebercfg2 = ISloeberConfiguration.getActiveConfig(proj2); + if (sloebercfg2 == null) { + fail("failed to load the sloeber configuration"); + } + BoardDescription proj2OpenedBoardDesc = sloebercfg2.getBoardDescription(); + CompileDescription proj2OpenedCompileDesc = sloebercfg2.getCompileDescription(); + + // check the setup was done correctly + if (!proj1BoardDesc.equals(proj1CreatedBoardDesc)) { + fail("Project 1 not created properly."); + } + if (!proj2BoardDesc.equals(proj2CreatedBoardDesc)) { + fail("Project 2 not created properly."); + } + if (!proj1CompileDesc.equals(proj1CreatedCompileDesc)) { + fail("Project 1 not created properly."); + } + if (!proj2CompileDesc.equals(proj2CreatedCompileDesc)) { + fail("Project 2 not created properly."); + } + + // check wether the file modification was taken into account + if (!proj1BoardDesc.equals(proj2OpenedBoardDesc)) { + fail("Project 2 not created properly."); + } + if (!proj1CompileDesc.equals(proj2OpenedCompileDesc)) { + fail("Project 2 not created properly."); + } + + } + + @Test + public void createProjectWithURI() throws Exception { + CodeDescription codeDesc = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); + + String proj1Name = "projectWithURI"; + String codeFolderName = "locationWithURI"; + BoardDescription proj1BoardDesc = Arduino.uno().getBoardDescriptor(); + OtherDescription otherDesc = new OtherDescription(); + CompileDescription proj1CompileDesc = getBunkersCompileDescription(); + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + IPath projectFolder = workspace.getRoot().getLocation().removeLastSegments(1).append(codeFolderName); + URI uri = projectFolder.toFile().toURI(); + // workspace.getRoot().getFolder(Path.fromOSString(codeFolderName)).getLocationURI(); + IProject theTestProject = SloeberProject.createArduinoProject(proj1Name, uri, proj1BoardDesc, codeDesc, + proj1CompileDesc, otherDesc, new NullProgressMonitor()); + + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, null); + assertNull(Shared.hasBuildErrors(theTestProject), + "Failed to compile the project: " + Shared.hasBuildErrors(theTestProject)); + String fileLocation = projectFolder.append("src").append(proj1Name + ".cpp").toString(); + + IFile cppFile = theTestProject.getFolder("src").getFile(proj1Name + ".cpp"); + assertTrue( cppFile.exists(),"File not in correct location"); + assertEquals( cppFile.getLocation().toString(), fileLocation,"File not in correct location"); + + } + + static CompileDescription getBunkersCompileDescription() { + CompileDescription inCompileDescription = new CompileDescription(); + + inCompileDescription.set_All_CompileOptions("-Deen=1"); + inCompileDescription.set_Archive_CompileOptions("-Dtwee=2"); + inCompileDescription.set_Assembly_CompileOptions("-Drie=3"); + inCompileDescription.set_C_andCPP_CompileOptions("-Dvier=4"); + inCompileDescription.set_C_CompileOptions("-Dvijf=5"); + inCompileDescription.set_Link_CompileOptions("-Dzes=6"); + inCompileDescription.set_CPP_CompileOptions("-Dzeven=7"); + inCompileDescription.setSizeCommand(SizeCommands.ARDUINO_WAY); + inCompileDescription.setEnableParallelBuild(true); + inCompileDescription.setWarningLevel(WarningLevels.NONE); + return inCompileDescription; + } + + /** + * check to see whether upload recipe key is correct for a couple of boards that + * have failed in the past + * + * @throws Exception + */ + @Test + public void uploadPattern() throws Exception { + BoardDescription boardDescriptor = Arduino.uno().getBoardDescriptor(); + String recipeKey = boardDescriptor.getUploadPatternKey(); + assertEquals( "tools.avrdude.upload.pattern", recipeKey,"uno upload recipe key is wrong"); + boardDescriptor = ESP32.esp32().getBoardDescriptor(); + boardDescriptor.setUploadPort("host 10.10.10.10"); + recipeKey = boardDescriptor.getUploadPatternKey(); + assertEquals( "tools.esptool_py.upload.network_pattern", recipeKey,"ESP OTA upload recipe key is wrong "); + + } + + public static Stream testDifferentSourceFoldersData() throws Exception { + List ret = new LinkedList<>(); + OtherDescription otherDesc = new OtherDescription(); + CompileDescription projCompileDesc = new CompileDescription(); + + MCUBoard unoboard = Arduino.uno(); + CodeDescription codeDescriptor1 = CodeDescription.createDefaultCPP(); + codeDescriptor1.setCodeFolder(null); + String projectName1 = Shared.getProjectName(codeDescriptor1, unoboard); + ret.add(Arguments.of(projectName1, codeDescriptor1, unoboard, otherDesc, projCompileDesc)); + + CodeDescription codeDescriptor2 = CodeDescription.createDefaultCPP(); + codeDescriptor2.setCodeFolder("src"); + String projectName2 = Shared.getProjectName(codeDescriptor2, unoboard); + ret.add(Arguments.of(projectName2, codeDescriptor2, unoboard, otherDesc, projCompileDesc)); + + CodeDescription codeDescriptor3 = CodeDescription.createDefaultCPP(); + codeDescriptor3.setCodeFolder("SRC"); + String projectName3 = Shared.getProjectName(codeDescriptor3, unoboard); + ret.add(Arguments.of(projectName3, codeDescriptor3, unoboard, otherDesc, projCompileDesc)); + + CodeDescription codeDescriptor4 = CodeDescription.createDefaultCPP(); + codeDescriptor4.setCodeFolder("blabla"); + String projectName4 = Shared.getProjectName(codeDescriptor4, unoboard); + ret.add(Arguments.of(projectName4, codeDescriptor4, unoboard, otherDesc, projCompileDesc)); + + return ret.stream(); + + } + + @ParameterizedTest + @MethodSource("testDifferentSourceFoldersData") + public void testDifferentSourceFolders(String projectName, CodeDescription codeDescriptor, MCUBoard board, + OtherDescription otherDesc, CompileDescription proj1CompileDesc) throws Exception { + + BoardDescription proj1BoardDesc = board.getBoardDescriptor(); + IProject theTestProject = SloeberProject.createArduinoProject(projectName, null, proj1BoardDesc, codeDescriptor, + proj1CompileDesc, otherDesc, new NullProgressMonitor()); + + Shared.waitForIndexer(theTestProject); + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, null); + assertNull( Shared.hasBuildErrors(theTestProject),"Failed to compile " + projectName); + + String srcFolder = codeDescriptor.getCodeFolder(); + IFile cppFile = null; + if (srcFolder == null) { + cppFile = theTestProject.getFile(projectName + ".cpp"); + } else { + cppFile = theTestProject.getFolder(srcFolder).getFile(projectName + ".cpp"); + } + assertTrue( cppFile.exists(),"Source File not in right location " + projectName); + } + + /** + * Test wether a platform json redirect is handled properly + * https://github.com/jantje/arduino-eclipse-plugin/issues/393 + * + * @throws Exception + */ + @Test + public void redirectedJson() throws Exception { + // this board references to arduino avr so install that one to + Arduino.installLatestAVRBoards(); + BoardsManager.installLatestPlatform(packageURL, "Talk2", "avr"); + Map options = new HashMap<>(); + options.put("mhz", "16MHz"); + BoardDescription boardid = BoardsManager.getBoardDescription(packageURL, "Talk2", + "avr", "whispernode", options); + if (boardid == null) { + fail("redirect Json "); + return; + } + assertNull(Shared.buildAndVerify("redirect_json", boardid, CodeDescription.createDefaultIno(), + new CompileDescription())); + } + + @Test + public void issue1126LibArchiver() throws Exception { + + MCUBoard leonardoBoard = Arduino.leonardo(); + Map examples = LibraryManager.getExamplesAll(null); + CompileDescription compileDesc = new CompileDescription(); + compileDesc.setEnableParallelBuild(true); + IArduinoLibraryVersion lib = null; + IExample example = null; + for (IExample curExample : examples.values()) { + Collection curLibs = curExample.getArduinoLibraries(); + if (curLibs.size() == 0) { + continue; + } + for (IArduinoLibraryVersion curLib : curLibs) { + if (curLib.getName().equals(HIDlibName)) { + example = curExample; + lib = curLib; + break; + } + } + if(example!=null) { + break; + } + } + assertNotNull( lib,"HID Lib \"" + HIDlibName + "\" Not found"); + + Set testExamples = new HashSet<>(); + testExamples.add(example); + CodeDescription codeDescriptor = CodeDescription.createExample(false, testExamples); + NullProgressMonitor monitor = new NullProgressMonitor(); + + IProject theTestProject = SloeberProject.createArduinoProject("issue1126LibArchiver", null, + leonardoBoard.getBoardDescriptor(), codeDescriptor, compileDesc, null, null, monitor); + + IndexerPreferences.setScope(theTestProject, IndexerPreferences.SCOPE_PROJECT_PRIVATE); + IndexerPreferences.set(theTestProject, IndexerPreferences.KEY_INCLUDE_HEURISTICS, Boolean.FALSE.toString()); + ICProject icProject = CoreModel.getDefault().create(theTestProject); + CCorePlugin.getIndexManager().reindex(icProject); + + IAutoBuildConfigurationDescription autoDesc = IAutoBuildConfigurationDescription.getActiveConfig(theTestProject, + false); + IFile libArchive = autoDesc.getBuildFolder().getFile(HIDlibName + ".ar"); + int tries=1; + while (!(libArchive.exists() || (tries++>4))) { + Thread.sleep(1000);//just make sure the libs can get added + Shared.waitForIndexer(theTestProject); + Thread.sleep(1000);//just make sure the libs can get added + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); + } + assertTrue( libArchive.exists(),"Archive " + libArchive.toString() + " does not exists"); + + } + + static Stream openAndClosePreservesSettingsValueCmd() throws Exception { + CodeDescription codeDescriptordefaultCPPRoot = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); + CodeDescription codeDescriptordefaultCPPSrc = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); + CodeDescription codeDescriptordefaultCPXX = new CodeDescription(CodeDescription.CodeTypes.defaultCPP); + + codeDescriptordefaultCPPRoot.setCodeFolder(null); + codeDescriptordefaultCPPSrc.setCodeFolder("src"); + codeDescriptordefaultCPXX.setCodeFolder("XX"); + + List ret = new LinkedList<>(); + ret.add(Arguments.of(Shared.getCounterName("openAndCloseRoot"), codeDescriptordefaultCPPRoot)); + ret.add(Arguments.of(Shared.getCounterName("openAndCloseSrc"), codeDescriptordefaultCPPSrc)); + ret.add(Arguments.of(Shared.getCounterName("openAndCloseXX"), codeDescriptordefaultCPXX)); + + return ret.stream(); + } + + public static Stream NightlyBoardPatronTestData() throws Exception { + ConfigurationPreferences.setUseArduinoToolSelection(true); + CompileDescription compileOptions = new CompileDescription(); + MCUBoard zeroBoard = Arduino.zeroProgrammingPort(); + + List ret = new LinkedList<>(); + TreeMap examples = LibraryManager.getExamplesLibrary(null); + for (Map.Entry curexample : examples.entrySet()) { + String fqn = curexample.getKey().trim(); + IExample example = curexample.getValue(); + IPath examplePath = example.getCodeLocation(); + if (fqn.contains("RTCZero")) { + Example SloeberExample = new Example(fqn, examplePath); + + ret.add(Arguments.of(Shared.getCounterName(SloeberExample.calcLibName() + ":" + example.getName()), + zeroBoard, SloeberExample, compileOptions)); + } + } + return ret.stream(); + } + + @ParameterizedTest + @MethodSource("NightlyBoardPatronTestData") + public void NightlyBoardPatron(String name, MCUBoard boardID, Example example, CompileDescription compileOptions) + throws Exception { + Shared.getLastFailMessage(); + Set examples = new HashSet<>(); + examples.add(example); + CodeDescription codeDescriptor = CodeDescription.createExample(false, examples); + + BoardDescription boardDescriptor = boardID.getBoardDescriptor(); + boardDescriptor.setOptions(boardID.getBoardOptions(example)); + assertNull( + Shared.buildAndVerifyAllBuilders(name, boardID.getBoardDescriptor(), codeDescriptor, compileOptions)); + + } + + + /** + * Use private lib from the workspace. + * Close project + * open project + * Is the lib still there (as does project still build) + * + * @throws Exception + */ + @Test + public void issue1723() throws Exception { + final String projectName = "private_lib"; + final String privateLibFolderName = "an_private_lib"; + final String privateLibName = "a_private_lib"; + final String libHeaderContent=("int aFunction();")+System.lineSeparator(); + String libCodeContent=("#include \""+privateLibName+".h\"")+System.lineSeparator(); + libCodeContent=libCodeContent+("int aFunction(){")+System.lineSeparator(); + libCodeContent=libCodeContent+("}")+System.lineSeparator(); + String libRefContent=("#include \""+privateLibName+".h\"")+System.lineSeparator(); + libRefContent=libRefContent+("int aRefFunction(){")+System.lineSeparator(); + libRefContent=libRefContent+("aFunction();")+System.lineSeparator(); + libRefContent=libRefContent+("}")+System.lineSeparator(); + + + //create a basic arduino project + BoardDescription unoBoardid = Arduino.uno().getBoardDescriptor(); + IProject theTestProject = null; + + IPath templateFolder = Shared.getTemplateFolder("CreateAndCompileTest"); + CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); + theTestProject = SloeberProject.createArduinoProject(projectName, null, unoBoardid, codeDescriptor, + new CompileDescription(), new NullProgressMonitor()); + Shared.waitForIndexer(theTestProject); + + //create a private library project + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + IWorkspaceRoot root = workspace.getRoot(); + IProject theLibProject= root.getProject("PrivateLibs"); + theLibProject.create(new NullProgressMonitor()); + theLibProject.open(new NullProgressMonitor()); + IFolder libFolder = theLibProject.getFolder(privateLibFolderName); + libFolder.create(true, true, new NullProgressMonitor()); + IFile libHeaderFile=libFolder.getFile(privateLibName+".h"); + IFile libSourceFile=libFolder.getFile(privateLibName+".cpp"); + + Files.write(libHeaderFile.getLocation().toPath(), libHeaderContent.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.CREATE); + Files.write(libSourceFile.getLocation().toPath(), libCodeContent.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.CREATE); + + + //build project (should work) + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); + assertNull(Shared.hasBuildErrors(theTestProject),"Created Project does not build."); + + + //Add code to project that uses private lib + IFolder srcFolder = theTestProject.getFolder("src"); + IFile referingFile=srcFolder.getFile("privateLibUser.cpp"); + Files.write(referingFile.getLocation().toPath(), libRefContent.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.CREATE); + + //build project (should fail) + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); + assertNotNull(Shared.hasBuildErrors(theTestProject),"Lib should be missing; build should fail."); + + + //add private libs project to the sloeber preferences private libs + List privateLibList= new LinkedList<>(); + privateLibList.add(theLibProject.getLocation().toOSString()); + privateLibList.addAll( Arrays.asList( LibraryManager.getPrivateLibraryPaths())); + LibraryManager.setPrivateLibraryPaths(privateLibList.toArray(new String[privateLibList.size()])); + + + + //add the private lib to the project + IArduinoLibraryVersion privateArduinoLib=LibraryManager.getLibraryVersionFromFQN(SLOEBER_LIBRARY_FQN+SLACH+PRIVATE+SLACH+libFolder.getName(), null); + Collection myPrivateLibs =new LinkedList<>(); + myPrivateLibs.add(privateArduinoLib); + + ISloeberConfiguration sloeberConf=ISloeberConfiguration.getActiveConfig(theTestProject, true); + sloeberConf.addLibraries(myPrivateLibs); + + //build project (should work) + theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); + assertNull(Shared.hasBuildErrors(theTestProject),"lib added build should succeed"); + + //open and close the project to clear the cache + theTestProject.close(null); + // just wait a while + Thread.sleep(1000); + + theTestProject.open(new NullProgressMonitor()); + + //There should be 1 lib in the project + sloeberConf=ISloeberConfiguration.getActiveConfig(theTestProject, true); + Map usedLibs=sloeberConf.getUsedLibraries(); + assertEquals(1,usedLibs.size(),"Private Lib not found"); + + } } diff --git a/io.sloeber.tests/src/io/sloeber/core/BuildTests_not_on_github.java b/io.sloeber.tests/src/io/sloeber/core/BuildTests_not_on_github.java new file mode 100644 index 000000000..841490711 --- /dev/null +++ b/io.sloeber.tests/src/io/sloeber/core/BuildTests_not_on_github.java @@ -0,0 +1,82 @@ +package io.sloeber.core; + + + + +import org.eclipse.cdt.core.CCorePlugin; +import org.eclipse.cdt.core.model.CoreModel; +import org.eclipse.cdt.core.model.ICProject; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IncrementalProjectBuilder; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +import io.sloeber.arduinoFramework.api.LibraryManager; +import io.sloeber.core.api.CodeDescription; +import io.sloeber.core.api.CompileDescription; +import io.sloeber.core.api.ConfigurationPreferences; +import io.sloeber.core.api.SloeberProject; +import io.sloeber.providers.Arduino; +import io.sloeber.providers.MCUBoard; + +@SuppressWarnings({ "nls", "static-method"}) +public class BuildTests_not_on_github { + + /* + * In new new installations (of the Sloeber development environment) the + * installer job will trigger downloads These must have finished before we can + * start testing + */ + @BeforeAll + public static void beforeClass() throws Exception { + Shared.waitForBoardsManager(); + Shared.setDeleteProjects(false); + ConfigurationPreferences.setUseBonjour(false); + } + + + @Test + public void onlyInstallLibraryWhenAllowed() throws Exception { + String libName="SD"; + + //set option not to install lib + ConfigurationPreferences.setInstallLibraries(false); + + //uninstall lib + LibraryManager.uninstallLibrary( libName); + + // create a project that uses a the lib + String testName = "onlyInstallLibraryWhenAllowed"; + IProgressMonitor monitor=new NullProgressMonitor(); + IPath templateFolder = Shared.getTemplateFolder(testName); + CodeDescription codeDescriptor = CodeDescription.createCustomTemplate(templateFolder); + MCUBoard unoboard = Arduino.uno(); + IProject theTestProject = SloeberProject.createArduinoProject(testName, null, unoboard.getBoardDescriptor(), codeDescriptor, + new CompileDescription(), monitor); + //wait for indexer and so on + Shared.waitForAllJobsToFinish(); + + + //Building the project should fail + assertNotNull( Shared.buildAndVerify(theTestProject,3,IncrementalProjectBuilder.FULL_BUILD ,monitor),"Sloeber wrongly installed lib "+libName); + + //set option to install libs + ConfigurationPreferences.setInstallLibraries(true); + + //trigger the indexer + ICProject cTestProject = CoreModel.getDefault().getCModel().getCProject(theTestProject.getName()); + CCorePlugin.getIndexManager().reindex(cTestProject); + Thread.sleep(5000); + Shared.waitForIndexer(theTestProject); + + //build should not fail + assertNull( Shared.buildAndVerify(theTestProject,3,IncrementalProjectBuilder.FULL_BUILD ,monitor),"Sloeber dit not install lib "+libName); + + + + } +} diff --git a/io.sloeber.tests/src/io/sloeber/core/CompileAndUpload.java b/io.sloeber.tests/src/io/sloeber/core/CompileAndUpload.java index 0358d0948..e09de5db5 100644 --- a/io.sloeber.tests/src/io/sloeber/core/CompileAndUpload.java +++ b/io.sloeber.tests/src/io/sloeber/core/CompileAndUpload.java @@ -34,12 +34,12 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.core.api.CodeDescription; import io.sloeber.core.api.CompileDescription; import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.ISloeberConfiguration; -import io.sloeber.core.api.BoardsManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.Sketch; import io.sloeber.core.api.SloeberProject; import io.sloeber.providers.Arduino; @@ -98,9 +98,9 @@ static Stream uploadBourds() throws Exception { public static void installAdditionalBoards() { - Preferences.setUseBonjour(false); + ConfigurationPreferences.setUseBonjour(false); String[] packageUrlsToAdd = { ESP32.packageURL, ESP8266.packageURL }; - BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd)), true); + BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd))); if (reinstall_boards_and_libraries) { BoardsManager.removeAllInstalledPlatforms(); diff --git a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesOnAVRHardwareTest.java b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesOnAVRHardwareTest.java index c6bbaee32..3f57db784 100644 --- a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesOnAVRHardwareTest.java +++ b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesOnAVRHardwareTest.java @@ -26,11 +26,12 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; + +import io.sloeber.arduinoFramework.api.IExample; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.CodeDescription; import io.sloeber.core.api.CompileDescription; -import io.sloeber.core.api.IExample; -import io.sloeber.core.api.LibraryManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.providers.Arduino; import io.sloeber.providers.MCUBoard; @@ -45,7 +46,7 @@ public static void setup() throws Exception { Shared.waitForBoardsManager(); Shared.setUseParralBuildProjects(Boolean.TRUE); Shared.waitForAllJobsToFinish(); - Preferences.setUseBonjour(false); + ConfigurationPreferences.setUseBonjour(false); } @@ -82,7 +83,7 @@ public static Stream avrHardwareData() throws Exception { } - private static boolean skipExample(Example example) { + private static boolean skipExample(IExample example) { // skip Teensy stuff on Arduino hardware // Teensy is so mutch more advanced that most arduino avr hardware can not // handle it diff --git a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesOnTeensyTest.java b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesOnTeensyTest.java index d73c27900..b6b49ba4c 100644 --- a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesOnTeensyTest.java +++ b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesOnTeensyTest.java @@ -30,12 +30,12 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import io.sloeber.core.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.IExample; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.CodeDescription; import io.sloeber.core.api.CompileDescription; -import io.sloeber.core.api.IExample; -import io.sloeber.core.api.LibraryManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.providers.MCUBoard; import io.sloeber.providers.Teensy; @@ -55,7 +55,7 @@ public static void setup() throws Exception { //Shared.setDefaultBuilder(AutoBuildProject.MAKE_BUILDER_ID); Shared.waitForAllJobsToFinish(); - Preferences.setUseBonjour(false); + ConfigurationPreferences.setUseBonjour(false); } diff --git a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesonJantjesBoardsTest.java b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesonJantjesBoardsTest.java index cc6e184ac..4c86d1ea6 100644 --- a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesonJantjesBoardsTest.java +++ b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileArduinoIDEExamplesonJantjesBoardsTest.java @@ -18,12 +18,12 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IExample; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.CodeDescription; -import io.sloeber.core.api.IExample; -import io.sloeber.core.api.LibraryManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.providers.Jantje; import io.sloeber.providers.MCUBoard; @@ -35,10 +35,10 @@ public class CreateAndCompileArduinoIDEExamplesonJantjesBoardsTest { private static int mySkipAtStart = 0; @BeforeAll public static void setup() throws Exception { - Preferences.setUseBonjour(false); + ConfigurationPreferences.setUseBonjour(false); Shared.waitForAllJobsToFinish(); String[] packageUrlsToAdd = { Jantje.additionalJsonURL }; - BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd)), true); + BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd))); Jantje.installLatestLocalDebugBoards(); Shared.waitForAllJobsToFinish(); diff --git a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileDefaultInoOnAllBoardsTest.java b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileDefaultInoOnAllBoardsTest.java index 88416f838..facadf647 100644 --- a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileDefaultInoOnAllBoardsTest.java +++ b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileDefaultInoOnAllBoardsTest.java @@ -12,16 +12,19 @@ import java.util.List; import java.util.stream.Stream; +import org.eclipse.cdt.core.CCorePlugin; +import org.eclipse.cdt.core.dom.IPDOMManager; import org.eclipse.core.runtime.IPath; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.CodeDescription; -import io.sloeber.core.api.LibraryManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; @SuppressWarnings({"nls","static-method"}) public class CreateAndCompileDefaultInoOnAllBoardsTest { @@ -33,10 +36,30 @@ public class CreateAndCompileDefaultInoOnAllBoardsTest { private static final boolean closeFailedProjects = false; private static int myTotalFails = 0; - private static int maxFails = 50; - private static int mySkipTestsAtStart = 0; + private static final int maxFails = 50; + private static final int mySkipTestsAtStart = 0; + + @BeforeAll + static public void beforeAll() throws Exception { + Shared.setCloseFailedProjects(closeFailedProjects); + // make sure all plugin installation is done + Shared.waitForAllJobsToFinish(); + Shared.setUseParralBuildProjects(Boolean.TRUE); + CCorePlugin.getIndexManager().setDefaultIndexerId( IPDOMManager.ID_NO_INDEXER ); + // build the Arduino way + ConfigurationPreferences.setUseArduinoToolSelection(true); + ConfigurationPreferences.setUseBonjour(false); + installAdditionalBoards(); + } private static final String[] packageUrlsToIgnoreonAllOSes = { + + //This package contains an additional avr folder for the tiny. + //This should work. Bug=Sloeber starts from disk not from boardsmanager + //therefore doesn't find the json file + //this test excludes the other hardwares but I can't be bothered + "http://www.leonardomiliani.com/repository/package_leonardomiliani.com_index.json", + // There is a newer version "https://raw.githubusercontent.com/ElektorLabs/arduino/master/package_elektor-labs.com_ide-1.6.5_index.json", // Third party url implies this is outdated (it also doesn't work) @@ -69,18 +92,26 @@ public class CreateAndCompileDefaultInoOnAllBoardsTest { // confirmed 2020 03 09 version 25 12 17 "https://raw.githubusercontent.com/avandalen/SAM15x15/master/package_avdweb_nl_index.json", - //no longer supported causes issues with USB_MANUFACTOR + //no longer supported "https://raw.githubusercontent.com/mikaelpatel/Cosa/master/package_cosa_index.json", + "https://engimusing.github.io/arduinoIDE/package_engimusing_modules_index.json", //Seems no longer supported json file download fails "https://raw.githubusercontent.com/MaximIntegratedMicros/arduino-collateral/master/package_maxim_index.json", - + //another fail to download json "https://www.mattairtech.com/software/arduino/package_MattairTech_index.json", + //malformed json file (confirmed by arduino IDE + "https://raw.githubusercontent.com/DFRobot/DFRobotDuinoBoard/master/package_dfrobot_index.json", + "https://raw.githubusercontent.com/DFRobot/DFRobotDuinoBoard/master/package_dfrobot_iot_mainboard.json", + // uses busybox on windows so command line issues and on Linux the all in one // archive build fails - "https://github.com/tenbaht/sduino/raw/master/package_sduino_stm8_index.json", }; + "https://github.com/tenbaht/sduino/raw/master/package_sduino_stm8_index.json", + + //moved to diferent place + "https://dl.espressif.com/dl/package_esp32_index.json",}; private static final String[] packageUrlsToIgnoreonWindows = { // following packages did not work in the arduino ide on windows at last test // confirmed 220 03 09 was version 1.0 @@ -107,8 +138,8 @@ public class CreateAndCompileDefaultInoOnAllBoardsTest { // confirmed 2020 03 09 version 4.0.0 "SmartEverything Bee (Native USB Port)", - // issue #1152 (confirmed 2020 03 07 ) - "Engimusing EFM32WG840", "Engimusing EFM32WG842", "Engimusing EFM32WG842F64", + // confirmed 2024 08 23 not to work in arduino IDE + "Kitten Syringe nRF52833 (NSFW)", "D-duino-32", // confirmed 2020 03 09 "SparkFun Blynk Board", // (confirmed 2020 03 07 ) @@ -128,6 +159,8 @@ public class CreateAndCompileDefaultInoOnAllBoardsTest { "Generic STM32F103Z series",// confirmed failing in arduino IDE 2020 05 30 "Arduino Nano ESP32",// requires recipe.hooks.core.prebuild and recipe.hooks.core.postbuild + "Snō",//fails in arduino ide 2024 11 22 + "OpenXLR8 - Snō",//fails in arduino ide 2024 11 22 }; private static final String[] boardsToIgnoreOnWindows = { @@ -271,18 +304,13 @@ public class CreateAndCompileDefaultInoOnAllBoardsTest { }; public static Stream allBoards() throws Exception { - Shared.setCloseFailedProjects(closeFailedProjects); - // make sure all plugin installation is done - Shared.waitForAllJobsToFinish(); - // build the Arduino way - Preferences.setUseArduinoToolSelection(true); - Preferences.setUseBonjour(false); - installAdditionalBoards(); + List boards = new ArrayList<>(); for (File curBoardFile : BoardsManager.getAllBoardsFiles()) { System.out.println("Adding boards of " + curBoardFile.toString()); - boards.addAll(BoardDescription.makeBoardDescriptors(curBoardFile)); + boards.addAll(BoardDescription.makeBoardDescriptors(curBoardFile)); + } HashSet boardsToIgnoreList = new HashSet<>(Arrays.asList(boardsToIgnoreOnAllOses)); @@ -330,7 +358,8 @@ public static void installAdditionalBoards() throws Exception { if (isMac) { toAddList.removeAll(Arrays.asList(packageUrlsToIgnoreOnMac)); } - BoardsManager.setPackageURLs(toAddList, true); + BoardsManager.addPackageURLs(toAddList); + if (!skipPlatformInstallation) { BoardsManager.installAllLatestPlatforms(); @@ -341,6 +370,7 @@ public static void installAdditionalBoards() throws Exception { if (apply_known_work_Arounds) { Shared.applyKnownWorkArounds(); } + BoardsManager.update(false); Shared.waitForAllJobsToFinish(); } diff --git a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileExamplesTest.java b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileExamplesTest.java index 1014f82ba..c3e99af32 100644 --- a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileExamplesTest.java +++ b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileExamplesTest.java @@ -15,13 +15,14 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import io.sloeber.core.api.BoardDescription; + +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IExample; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.CodeDescription; import io.sloeber.core.api.CompileDescription; -import io.sloeber.core.api.IExample; -import io.sloeber.core.api.LibraryManager; -import io.sloeber.core.api.BoardsManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.providers.Adafruit; import io.sloeber.providers.Arduino; import io.sloeber.providers.ESP8266; @@ -38,7 +39,7 @@ public class CreateAndCompileExamplesTest { public static Stream examples() throws Exception { installAdditionalBoards(); Shared.waitForAllJobsToFinish(); - Preferences.setUseBonjour(false); + ConfigurationPreferences.setUseBonjour(false); MCUBoard myBoards[] = { Arduino.leonardo(), Arduino.uno(), @@ -80,7 +81,7 @@ public static Stream examples() throws Exception { public static void installAdditionalBoards() { String[] packageUrlsToAdd = { ESP8266.packageURL, Adafruit.packageURL }; - BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd)), true); + BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd))); if (reinstall_boards_and_examples) { BoardsManager.installAllLatestPlatforms(); BoardsManager.onlyKeepLatestPlatforms(); diff --git a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileLibraryExamplesTest.java b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileLibraryExamplesTest.java index 7589f96e3..8956e1d89 100644 --- a/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileLibraryExamplesTest.java +++ b/io.sloeber.tests/src/io/sloeber/core/CreateAndCompileLibraryExamplesTest.java @@ -16,12 +16,13 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import io.sloeber.core.api.BoardDescription; + +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IExample; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.CodeDescription; -import io.sloeber.core.api.IExample; -import io.sloeber.core.api.LibraryManager; -import io.sloeber.core.api.BoardsManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.providers.Adafruit; import io.sloeber.providers.Arduino; import io.sloeber.providers.ESP32; @@ -38,8 +39,8 @@ public class CreateAndCompileLibraryExamplesTest { private int myTotalFails = 0; public static Stream CreateAndCompileLibraryExamplesTestData() throws Exception { - Preferences.setUseBonjour(false); - Preferences.setUseArduinoToolSelection(true); + ConfigurationPreferences.setUseBonjour(false); + ConfigurationPreferences.setUseArduinoToolSelection(true); Shared.waitForAllJobsToFinish(); installMyStuff(); @@ -81,7 +82,7 @@ public static void installMyStuff() { public static void installAdditionalBoards() { String[] packageUrlsToAdd = { ESP8266.packageURL, Adafruit.packageURL, ESP32.packageURL }; - BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd)), reinstall_boards_and_examples); + BoardsManager.addPackageURLs(new HashSet<>(Arrays.asList(packageUrlsToAdd))); if (reinstall_boards_and_examples) { BoardsManager.installAllLatestPlatforms(); BoardsManager.onlyKeepLatestPlatforms(); diff --git a/io.sloeber.tests/src/io/sloeber/core/Example.java b/io.sloeber.tests/src/io/sloeber/core/Example.java index 21ca55f12..8fcc66acc 100644 --- a/io.sloeber.tests/src/io/sloeber/core/Example.java +++ b/io.sloeber.tests/src/io/sloeber/core/Example.java @@ -11,7 +11,7 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; -import io.sloeber.core.api.LibraryManager; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.providers.ESP32; import io.sloeber.providers.MCUBoard; import io.sloeber.providers.Teensy; diff --git a/io.sloeber.tests/src/io/sloeber/core/Shared.java b/io.sloeber.tests/src/io/sloeber/core/Shared.java index 28b42075c..bacfa7954 100644 --- a/io.sloeber.tests/src/io/sloeber/core/Shared.java +++ b/io.sloeber.tests/src/io/sloeber/core/Shared.java @@ -31,6 +31,7 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; @@ -40,15 +41,15 @@ import static io.sloeber.core.api.Const.*; import static org.junit.jupiter.api.Assertions.fail; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IExample; import io.sloeber.autoBuild.api.AutoBuildProject; import io.sloeber.autoBuild.api.IAutoBuildConfigurationDescription; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; import io.sloeber.core.api.CodeDescription; import io.sloeber.core.api.CompileDescription; import io.sloeber.core.api.ConfigurationPreferences; -import io.sloeber.core.api.IArduinoLibraryVersion; -import io.sloeber.core.api.IExample; import io.sloeber.core.api.SloeberProject; import io.sloeber.providers.MCUBoard; @@ -132,6 +133,8 @@ public static void waitForIndexer(IProject iProject) throws Exception { if(count%10==0) { System.out.println("Waiting for indexer"); } + icProject = CoreModel.getDefault().create(iProject); + index = CCorePlugin.getIndexManager().getIndex(icProject); } } @@ -197,7 +200,7 @@ public static String buildAndVerify(BoardDescription boardDescriptor, CodeDescri public static String buildAndVerify(BoardDescription boardDescriptor, CodeDescription codeDescriptor, CompileDescription compileOptions) throws Exception { - String projectName = getCounterName(boardDescriptor.getBoardID()); + String projectName = getCounterName(boardDescriptor); IExample example = codeDescriptor.getLinkedExample(); if (example != null) { Collection lib = example.getArduinoLibraries(); @@ -248,7 +251,7 @@ public static String buildAndVerifyGivenBuilders(String projectName, BoardDescri } // clean so we will get a full build for this buider theTestProject.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor); - + // set the builder CoreModel coreModel = CoreModel.getDefault(); ICProjectDescription projectDescription = coreModel.getProjectDescription(theTestProject, true); @@ -256,24 +259,10 @@ public static String buildAndVerifyGivenBuilders(String projectName, BoardDescri .getActiveConfig(projectDescription); autoDesc.setBuilder(curBuilder); coreModel.setProjectDescription(theTestProject, projectDescription); - - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - - if (hasBuildErrors(theTestProject)!=null) { - Shared.waitForAllJobsToFinish(); - Thread.sleep(2000); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - if (hasBuildErrors(theTestProject)!=null) { - Shared.waitForAllJobsToFinish(); - Thread.sleep(2000); - theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor); - String buildError=hasBuildErrors(theTestProject); - if (buildError!=null) { - myLastFailMessage = myLastFailMessage + NEWLINE +buildError+ NEWLINE+ "Failed to compile the project:" + projectName - + " with builder " + curBuilder; - } - } - } + + buildAndVerify(theTestProject,3,IncrementalProjectBuilder.FULL_BUILD, monitor); + + } if (!myLastFailMessage.isBlank()) { @@ -293,6 +282,26 @@ public static String buildAndVerifyGivenBuilders(String projectName, BoardDescri return null; } + static String buildAndVerify(IProject theTestProject, int maxTries, int buildType, IProgressMonitor monitor) throws Exception { + int curTry = 0; + String buildError=null; + while (curTry++ < maxTries) { + theTestProject.build(buildType, monitor); + Shared.waitForAllJobsToFinish(); + Thread.sleep(2000); + buildError = hasBuildErrors(theTestProject); + if (buildError == null) { + return buildError; + } + } + IAutoBuildConfigurationDescription autoDesc = IAutoBuildConfigurationDescription + .getActiveConfig(theTestProject,false); + String builder=autoDesc.getBuilder().getId(); + myLastFailMessage = myLastFailMessage + NEWLINE + buildError + NEWLINE + "Failed to compile the project:" + + theTestProject.getName() + " with builder " + builder; + return buildError; + } + /* * For some boards that do not run out of the box we know how to fix it. This * code fixes these things @@ -334,6 +343,11 @@ public static String getCounterName(String name) { return getCounterName("%05d_%s", name); } + public static String getCounterName( BoardDescription boardDescriptor) { + return String.format("%05d_%s_%s", Integer.valueOf(myTestCounter++), boardDescriptor.getVendor(),boardDescriptor.getBoardName()); + } + + public static String getCounterName(String format, String name) { return String.format(format, Integer.valueOf(myTestCounter++), name); } diff --git a/io.sloeber.tests/src/io/sloeber/core/UpgradeTest.java b/io.sloeber.tests/src/io/sloeber/core/UpgradeTest.java index 560731512..276b7d0ec 100644 --- a/io.sloeber.tests/src/io/sloeber/core/UpgradeTest.java +++ b/io.sloeber.tests/src/io/sloeber/core/UpgradeTest.java @@ -10,7 +10,7 @@ import static org.junit.jupiter.api.Assertions.*; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.core.api.SloeberProject; import io.sloeber.providers.Arduino; @@ -34,7 +34,7 @@ public class UpgradeTest { @BeforeAll public static void setup() { // stop bonjour as it clutters the console log - Preferences.setUseBonjour(false); + ConfigurationPreferences.setUseBonjour(false); Shared.waitForAllJobsToFinish(); // TOFIX: this will have to change into a specific version // or we will have to add the install based on stored data diff --git a/io.sloeber.tests/src/io/sloeber/core/releaseTesting_takes_very_long.java b/io.sloeber.tests/src/io/sloeber/core/releaseTesting_takes_very_long.java index 205a656bb..25a6e30c5 100644 --- a/io.sloeber.tests/src/io/sloeber/core/releaseTesting_takes_very_long.java +++ b/io.sloeber.tests/src/io/sloeber/core/releaseTesting_takes_very_long.java @@ -1,7 +1,6 @@ package io.sloeber.core; -import io.sloeber.core.api.Preferences; import org.junit.jupiter.api.BeforeAll; import org.junit.platform.suite.api.SelectClasses; @@ -9,6 +8,8 @@ import org.junit.platform.suite.api.Suite; import org.junit.platform.suite.api.SuiteDisplayName; +import io.sloeber.core.api.ConfigurationPreferences; + @SuiteDisplayName("Sloeber Nightly suite") @SelectClasses ({ @@ -26,7 +27,7 @@ public class releaseTesting_takes_very_long { @BeforeAll public static void setUp() { - Preferences.setUseBonjour(false); + ConfigurationPreferences.setUseBonjour(false); Shared.setDeleteProjects(true); } } diff --git a/io.sloeber.tests/src/io/sloeber/providers/Adafruit.java b/io.sloeber.tests/src/io/sloeber/providers/Adafruit.java index 409bb63da..b6afdf844 100644 --- a/io.sloeber.tests/src/io/sloeber/providers/Adafruit.java +++ b/io.sloeber.tests/src/io/sloeber/providers/Adafruit.java @@ -3,8 +3,8 @@ import static org.junit.jupiter.api.Assertions.fail; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; @SuppressWarnings("nls") public class Adafruit extends MCUBoard { @@ -18,7 +18,7 @@ public class Adafruit extends MCUBoard { public Adafruit(String architectureID, String boardName) { - myBoardDescriptor = BoardsManager.getBoardDescription("package_adafruit_index.json", "adafruit", architectureID, + myBoardDescriptor = BoardsManager.getBoardDescription(packageURL, "adafruit", architectureID, boardName, null); if (myBoardDescriptor == null) { fail(boardName + " Board not found"); diff --git a/io.sloeber.tests/src/io/sloeber/providers/Arduino.java b/io.sloeber.tests/src/io/sloeber/providers/Arduino.java index c15105349..4957ea1f2 100644 --- a/io.sloeber.tests/src/io/sloeber/providers/Arduino.java +++ b/io.sloeber.tests/src/io/sloeber/providers/Arduino.java @@ -8,15 +8,17 @@ import java.util.Map; import java.util.TreeMap; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; -import io.sloeber.core.api.Json.ArduinoPackage; -import io.sloeber.core.api.Json.ArduinoPlatform; -import io.sloeber.core.api.Json.ArduinoPlatformVersion; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IArduinoPackage; +import io.sloeber.arduinoFramework.api.IArduinoPlatform; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; +import io.sloeber.core.api.Defaults; @SuppressWarnings("nls") public class Arduino extends MCUBoard { + private static final String packageURL= Defaults.DEFAULT_INSTALL_JSON; private static final String providerArduino = "arduino"; private static final String providerIntel = "Intel"; private static final String AVRArchitectureName = "avr"; @@ -25,7 +27,6 @@ public class Arduino extends MCUBoard { private static final String NFRArchitectureName = "nrf52"; private static final String MBEDArchitectureName = "mbed"; private static final String intelCurieArchitectureName = "arc32"; - private static final String jsonFileName = "package_index.json"; public static final String circuitplay32ID = "circuitplay32u4cat"; public static final String unoID = "uno"; @@ -116,7 +117,7 @@ public static MCUBoard arduino_101() { } private Arduino(String providerName, String architectureName, String boardID) { - this.myBoardDescriptor = BoardsManager.getBoardDescription(jsonFileName, providerName, architectureName, + this.myBoardDescriptor = BoardsManager.getBoardDescription(packageURL, providerName, architectureName, boardID, null); if (this.myBoardDescriptor == null) { fail(boardID + " Board not found"); @@ -264,19 +265,19 @@ private static List supportKeyboardList() { } public static void installLatestAVRBoards() { - BoardsManager.installLatestPlatform(jsonFileName, providerArduino, AVRArchitectureName); + BoardsManager.installLatestPlatform(packageURL, providerArduino, AVRArchitectureName); } public static void installLatestSamDBoards() { - BoardsManager.installLatestPlatform(jsonFileName, providerArduino, SAMDArchitectureName); + BoardsManager.installLatestPlatform(packageURL, providerArduino, SAMDArchitectureName); } public static void installLatestSamBoards() { - BoardsManager.installLatestPlatform(jsonFileName, providerArduino, SAMArchitectureName); + BoardsManager.installLatestPlatform(packageURL, providerArduino, SAMArchitectureName); } public static void installLatestIntellCurieBoards() { - BoardsManager.installLatestPlatform(jsonFileName, providerIntel, intelCurieArchitectureName); + BoardsManager.installLatestPlatform(packageURL, providerIntel, intelCurieArchitectureName); } public static List getAllBoards() { @@ -289,10 +290,10 @@ public static List getAllAvrBoards() { private static List getAllmBedBoardNames() { List ret = new LinkedList<>(); - ArduinoPackage arduinoPkg = BoardsManager.getPackageByProvider(providerArduino); - for (ArduinoPlatform curPlatform : arduinoPkg.getPlatforms()) { + IArduinoPackage arduinoPkg = BoardsManager.getPackageByProvider(providerArduino); + for (IArduinoPlatform curPlatform : arduinoPkg.getPlatforms()) { if (curPlatform.getArchitecture().equals(MBEDArchitectureName)) { - ArduinoPlatformVersion curPlatformVersion = curPlatform.getNewestInstalled(); + IArduinoPlatformVersion curPlatformVersion = curPlatform.getNewestInstalled(); if (curPlatformVersion != null) { List boardDescriptions = BoardDescription .makeBoardDescriptors(curPlatformVersion.getBoardsFile()); diff --git a/io.sloeber.tests/src/io/sloeber/providers/ESP32.java b/io.sloeber.tests/src/io/sloeber/providers/ESP32.java index 74ef5c1dc..eb1ae57d1 100644 --- a/io.sloeber.tests/src/io/sloeber/providers/ESP32.java +++ b/io.sloeber.tests/src/io/sloeber/providers/ESP32.java @@ -6,15 +6,14 @@ import java.util.Map; import java.util.TreeMap; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; @SuppressWarnings("nls") public class ESP32 extends MCUBoard { private static final String provider = "esp32"; private static final String architectureName = "esp32"; - private static final String jsonFileName = "package_esp32_index.json"; - public static final String packageURL = "https://dl.espressif.com/dl/package_esp32_index.json"; + public static final String packageURL = "https://espressif.github.io/arduino-esp32/package_esp32_index.json"; public static final String esp32ID = "esp32"; public static MCUBoard esp32() { @@ -28,7 +27,7 @@ public static MCUBoard esp32() { } public ESP32(String boardName, Map options) { - myBoardDescriptor = BoardsManager.getBoardDescription(jsonFileName, provider, architectureName, boardName, + myBoardDescriptor = BoardsManager.getBoardDescription(packageURL, provider, architectureName, boardName, options); if (myBoardDescriptor == null) { fail(boardName + " Board not found"); @@ -36,6 +35,16 @@ public ESP32(String boardName, Map options) { setAttributes(); } + private ESP32(String providerName, String architectureName, String boardID) { + this.myBoardDescriptor = BoardsManager.getBoardDescription(packageURL, providerName, architectureName, + boardID, null); + if (this.myBoardDescriptor == null) { + fail(boardID + " Board not found"); + } + this.myBoardDescriptor.setUploadPort("none"); + setAttributes(); + } + public ESP32(BoardDescription boardDesc) { myBoardDescriptor = boardDesc; myBoardDescriptor.setUploadPort("none"); @@ -43,7 +52,7 @@ public ESP32(BoardDescription boardDesc) { } public static void installLatest() { - BoardsManager.installLatestPlatform(jsonFileName, provider, architectureName); + BoardsManager.installLatestPlatform(packageURL, provider, architectureName); } @Override @@ -58,4 +67,8 @@ public MCUBoard createMCUBoard(BoardDescription boardDesc) { return new ESP32(boardDesc); } + public static Object ESP32S3() { + return new ESP32(provider, architectureName, "esp32s3"); + } + } \ No newline at end of file diff --git a/io.sloeber.tests/src/io/sloeber/providers/ESP8266.java b/io.sloeber.tests/src/io/sloeber/providers/ESP8266.java index fdc42fb01..92f52435b 100644 --- a/io.sloeber.tests/src/io/sloeber/providers/ESP8266.java +++ b/io.sloeber.tests/src/io/sloeber/providers/ESP8266.java @@ -6,14 +6,13 @@ import java.util.Map; import java.util.TreeMap; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; @SuppressWarnings("nls") public class ESP8266 extends MCUBoard { private static final String provider = "esp8266"; private static final String architectureName = "esp8266"; - private static final String jsonFileName = "package_esp8266com_index.json"; public static final String packageURL = "https://arduino.esp8266.com/stable/package_esp8266com_index.json"; public static MCUBoard wemosD1() { @@ -33,7 +32,7 @@ public static MCUBoard ESPressoLite() { } public ESP8266(String boardName, Map options) { - myBoardDescriptor = BoardsManager.getBoardDescription(jsonFileName, provider, architectureName, boardName, + myBoardDescriptor = BoardsManager.getBoardDescription(packageURL, provider, architectureName, boardName, options); if (this.myBoardDescriptor == null) { fail(boardName + " Board not found"); @@ -48,7 +47,7 @@ public ESP8266(BoardDescription boardDesc) { } public static void installLatest() { - BoardsManager.installLatestPlatform(jsonFileName, provider, architectureName); + BoardsManager.installLatestPlatform(packageURL, provider, architectureName); } @Override diff --git a/io.sloeber.tests/src/io/sloeber/providers/Jantje.java b/io.sloeber.tests/src/io/sloeber/providers/Jantje.java index 53086e413..010a276b5 100644 --- a/io.sloeber.tests/src/io/sloeber/providers/Jantje.java +++ b/io.sloeber.tests/src/io/sloeber/providers/Jantje.java @@ -7,8 +7,9 @@ import java.util.Map; import java.util.TreeMap; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.core.api.Defaults; @SuppressWarnings("nls") public class Jantje extends MCUBoard { @@ -16,7 +17,7 @@ public class Jantje extends MCUBoard { private static final String provider = "Jantje"; private static final String packageName = "Jantje"; private static final String localDebugArchitectureName = "pc"; - private static final String jsonFileName = "package_jantje_index.json"; + private static final String packageURL = Defaults.JANTJE_BOARD_JSON_URL; // the below json url is need as esp8266 is a referenced platform public static final String additionalJsonURL = "https://arduino.esp8266.com/stable/package_esp8266com_index.json"; @@ -43,7 +44,7 @@ public static MCUBoard uno() { public Jantje(String boardName) { Map options = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); options.put("type", "debug"); - myBoardDescriptor = BoardsManager.getBoardDescription(jsonFileName, packageName, localDebugArchitectureName, + myBoardDescriptor = BoardsManager.getBoardDescription(packageURL, packageName, localDebugArchitectureName, boardName, options); if (myBoardDescriptor == null) { fail(boardName + " Board not found"); @@ -52,7 +53,7 @@ public Jantje(String boardName) { } public static void installLatestLocalDebugBoards() { - BoardsManager.installLatestPlatform(jsonFileName, provider, localDebugArchitectureName); + BoardsManager.installLatestPlatform(packageURL, provider, localDebugArchitectureName); } @Override diff --git a/io.sloeber.tests/src/io/sloeber/providers/MCUBoard.java b/io.sloeber.tests/src/io/sloeber/providers/MCUBoard.java index 9f6c5d6ca..d4bf1b0e9 100644 --- a/io.sloeber.tests/src/io/sloeber/providers/MCUBoard.java +++ b/io.sloeber.tests/src/io/sloeber/providers/MCUBoard.java @@ -5,13 +5,13 @@ import java.util.Map; import java.util.TreeMap; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IArduinoPackage; +import io.sloeber.arduinoFramework.api.IArduinoPlatform; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; import io.sloeber.core.AttributesBoard; import io.sloeber.core.Example; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; -import io.sloeber.core.api.Json.ArduinoPackage; -import io.sloeber.core.api.Json.ArduinoPlatform; -import io.sloeber.core.api.Json.ArduinoPlatformVersion; @SuppressWarnings("nls") public abstract class MCUBoard { @@ -47,12 +47,12 @@ public static List getAllBoards(String provider, MCUBoard board) { public static List getAllBoards(String provider, String architecture, MCUBoard board) { List ret = new LinkedList<>(); ret.add(board);//make the board provided the first in the list - ArduinoPackage arduinoPkg = BoardsManager.getPackageByProvider(provider); - for (ArduinoPlatform curPlatform : arduinoPkg.getPlatforms()) { + IArduinoPackage arduinoPkg = BoardsManager.getPackageByProvider(provider); + for (IArduinoPlatform curPlatform : arduinoPkg.getPlatforms()) { if(architecture!=null && !architecture.equals( curPlatform.getArchitecture())) { continue; } - ArduinoPlatformVersion curPlatformVersion = curPlatform.getNewestInstalled(); + IArduinoPlatformVersion curPlatformVersion = curPlatform.getNewestInstalled(); if (curPlatformVersion != null) { List boardDescriptions = BoardDescription .makeBoardDescriptors(curPlatformVersion.getBoardsFile()); diff --git a/io.sloeber.tests/src/io/sloeber/providers/Teensy.java b/io.sloeber.tests/src/io/sloeber/providers/Teensy.java index 5d2c3c0d1..77e2950f8 100644 --- a/io.sloeber.tests/src/io/sloeber/providers/Teensy.java +++ b/io.sloeber.tests/src/io/sloeber/providers/Teensy.java @@ -4,10 +4,10 @@ import java.util.Map; import java.util.TreeMap; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.core.AttributesCode; import io.sloeber.core.Example; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; @SuppressWarnings("nls") public class Teensy extends MCUBoard { @@ -21,7 +21,6 @@ public class Teensy extends MCUBoard { public final static String Teensy_LC_ID = "teensyLC"; public final static String TEENSY_PLATFORM_ID = "avr"; public final static String TEENSY_PROVIDER= "teensy"; - private static final String jsonFileName = "package_teensy_index.json"; public static final String packageURL = "https://www.pjrc.com/teensy/package_teensy_index.json"; public static MCUBoard Teensy_LC() { @@ -71,7 +70,7 @@ private Teensy(String boardID) { default: break; } - myBoardDescriptor = BoardsManager.getBoardDescription(jsonFileName, TEENSY_PROVIDER, TEENSY_PLATFORM_ID,boardID,options); + myBoardDescriptor = BoardsManager.getBoardDescription(packageURL, TEENSY_PROVIDER, TEENSY_PLATFORM_ID,boardID,options); setUploadPort("none"); setAttributes(); @@ -140,7 +139,7 @@ protected void setAttributes() { } public static void installLatest() { - BoardsManager.installLatestPlatform(jsonFileName, TEENSY_PROVIDER, TEENSY_PLATFORM_ID); + BoardsManager.installLatestPlatform(packageURL, TEENSY_PROVIDER, TEENSY_PLATFORM_ID); } public static List getAllBoards() { diff --git a/io.sloeber.tests/src/templates/CreateAndCompileTest/sketch.cpp b/io.sloeber.tests/src/templates/CreateAndCompileTest/sketch.cpp index e6efe49af..c4cc46880 100644 --- a/io.sloeber.tests/src/templates/CreateAndCompileTest/sketch.cpp +++ b/io.sloeber.tests/src/templates/CreateAndCompileTest/sketch.cpp @@ -1,15 +1,21 @@ #include "Arduino.h" #ifdef ARDUINO_BOARD -char mychar1[] = ARDUINO_BOARD; +char mychar[] = ARDUINO_BOARD; #endif - #ifdef USB_MANUFACTURER char mychar2[] = USB_MANUFACTURER; #endif #ifdef USB_PRODUCT char mychar3[] = USB_PRODUCT; #endif +#ifdef ARDUINO_HOST_OS +char mychar4[] = ARDUINO_HOST_OS; +#endif +#ifdef ARDUINO_VARIANT +char mychar5[] = ARDUINO_VARIANT; +#endif + diff --git a/io.sloeber.tests/src/templates/issue1047_Board_Names_Can_Be_used_as_Strings/sketch.ino b/io.sloeber.tests/src/templates/issue1047_Board_Names_Can_Be_used_as_Strings/sketch.ino index e8388bfc6..e5829620c 100644 --- a/io.sloeber.tests/src/templates/issue1047_Board_Names_Can_Be_used_as_Strings/sketch.ino +++ b/io.sloeber.tests/src/templates/issue1047_Board_Names_Can_Be_used_as_Strings/sketch.ino @@ -1,14 +1,21 @@ #include "Arduino.h" +#ifdef ARDUINO_BOARD char mychar[] = ARDUINO_BOARD; - - +#endif #ifdef USB_MANUFACTURER char mychar2[] = USB_MANUFACTURER; #endif #ifdef USB_PRODUCT char mychar3[] = USB_PRODUCT; #endif +#ifdef ARDUINO_HOST_OS +char mychar4[] = ARDUINO_HOST_OS; +#endif +#ifdef ARDUINO_VARIANT +char mychar5[] = ARDUINO_VARIANT; +#endif + diff --git a/io.sloeber.tests/src/templates/onlyInstallLibraryWhenAllowed/sketch.ino b/io.sloeber.tests/src/templates/onlyInstallLibraryWhenAllowed/sketch.ino new file mode 100644 index 000000000..69256a313 --- /dev/null +++ b/io.sloeber.tests/src/templates/onlyInstallLibraryWhenAllowed/sketch.ino @@ -0,0 +1,14 @@ +#include "Arduino.h" +#include "SD.h" +//The setup function is called once at startup of the sketch +void setup() +{ +// Add your initialization code here +} + +// The loop function is called in an endless loop +void loop() +{ +//Add your repeated code here +} + diff --git a/io.sloeber.ui.nl1/META-INF/MANIFEST.MF b/io.sloeber.ui.nl1/META-INF/MANIFEST.MF index a7b2ac39e..9e7c4ed0a 100644 --- a/io.sloeber.ui.nl1/META-INF/MANIFEST.MF +++ b/io.sloeber.ui.nl1/META-INF/MANIFEST.MF @@ -4,5 +4,5 @@ Bundle-Name: Sloeber ui language pack Bundle-SymbolicName: io.sloeber.ui.nl1;singleton:=true Bundle-Version: 5.0.0.qualifier Fragment-Host: io.sloeber.ui;bundle-version="5.0.0" -Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Vendor: baeyens.it diff --git a/io.sloeber.ui/.classpath b/io.sloeber.ui/.classpath index 390c47790..de9ab79cd 100644 --- a/io.sloeber.ui/.classpath +++ b/io.sloeber.ui/.classpath @@ -1,7 +1,7 @@ - + diff --git a/io.sloeber.ui/.settings/org.eclipse.jdt.core.prefs b/io.sloeber.ui/.settings/org.eclipse.jdt.core.prefs index 27705a035..502263510 100644 --- a/io.sloeber.ui/.settings/org.eclipse.jdt.core.prefs +++ b/io.sloeber.ui/.settings/org.eclipse.jdt.core.prefs @@ -1,9 +1,18 @@ eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=21 +org.eclipse.jdt.core.compiler.compliance=21 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=21 org.eclipse.jdt.core.formatter.align_assignment_statements_on_columns=false org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.align_variable_declarations_on_columns=false org.eclipse.jdt.core.formatter.align_with_spaces=false +org.eclipse.jdt.core.formatter.alignment_for_additive_operator=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -11,21 +20,24 @@ org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_c org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_bitwise_operator=16 org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 org.eclipse.jdt.core.formatter.alignment_for_compact_loops=16 org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 org.eclipse.jdt.core.formatter.alignment_for_enum_constants=16 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0 +org.eclipse.jdt.core.formatter.alignment_for_logical_operator=16 org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 org.eclipse.jdt.core.formatter.alignment_for_module_statements=16 org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_multiplicative_operator=16 org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_string_concatenation=16 org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 @@ -117,11 +129,12 @@ org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_additive_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_bitwise_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert @@ -152,6 +165,8 @@ org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_after_logical_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_multiplicative_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert @@ -176,13 +191,17 @@ org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_relational_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_shift_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_string_concatenation=insert org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_additive_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_bitwise_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert @@ -230,6 +249,8 @@ org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do no org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_before_logical_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_multiplicative_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert @@ -266,9 +287,12 @@ org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not inser org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_relational_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_shift_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_string_concatenation=insert org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert @@ -307,9 +331,13 @@ org.eclipse.jdt.core.formatter.tabulation.char=tab org.eclipse.jdt.core.formatter.tabulation.size=4 org.eclipse.jdt.core.formatter.use_on_off_tags=false org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_additive_operator=true org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_bitwise_operator=true org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true +org.eclipse.jdt.core.formatter.wrap_before_logical_operator=true +org.eclipse.jdt.core.formatter.wrap_before_multiplicative_operator=true org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_before_string_concatenation=true org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true org.eclipse.jdt.core.javaFormatter=org.eclipse.jdt.core.defaultJavaFormatter diff --git a/io.sloeber.ui/META-INF/MANIFEST.MF b/io.sloeber.ui/META-INF/MANIFEST.MF index d29f92d66..ea6296b80 100644 --- a/io.sloeber.ui/META-INF/MANIFEST.MF +++ b/io.sloeber.ui/META-INF/MANIFEST.MF @@ -16,8 +16,9 @@ Require-Bundle: org.eclipse.ui, org.apache.commons.commons-io, io.sloeber.autoBuild, org.eclipse.jface, - io.sloeber.autoBuild.ui -Bundle-RequiredExecutionEnvironment: JavaSE-17 + io.sloeber.autoBuild.ui, + org.eclipse.swt +Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-ActivationPolicy: lazy Bundle-Vendor: Sloeber.io Export-Package: io.sloeber.ui.monitor;x-friends:="io.sloeber.tests", diff --git a/io.sloeber.ui/splash.bmp b/io.sloeber.ui/splash.bmp index 69755764b..3d31586d0 100644 Binary files a/io.sloeber.ui/splash.bmp and b/io.sloeber.ui/splash.bmp differ diff --git a/io.sloeber.ui/src/io/sloeber/ui/Activator.java b/io.sloeber.ui/src/io/sloeber/ui/Activator.java index 34c33118f..646365b2c 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/Activator.java +++ b/io.sloeber.ui/src/io/sloeber/ui/Activator.java @@ -9,7 +9,7 @@ import org.eclipse.ui.statushandlers.StatusManager; import org.osgi.framework.BundleContext; -import io.sloeber.core.api.LibraryManager; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.ui.helpers.MyPreferences; import io.sloeber.ui.listeners.MyLibraryInstallHandler; import io.sloeber.ui.listeners.ProjectExplorerListener; diff --git a/io.sloeber.ui/src/io/sloeber/ui/Import_Libraries_Page.java b/io.sloeber.ui/src/io/sloeber/ui/Import_Libraries_Page.java index d4eb75a91..d3155433e 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/Import_Libraries_Page.java +++ b/io.sloeber.ui/src/io/sloeber/ui/Import_Libraries_Page.java @@ -11,6 +11,7 @@ import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.swt.SWT; @@ -21,9 +22,9 @@ import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.dialogs.WizardResourceImportPage; -import io.sloeber.core.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.ISloeberConfiguration; -import io.sloeber.core.api.LibraryManager; public class Import_Libraries_Page extends WizardResourceImportPage { @@ -65,13 +66,17 @@ public void createControl(Composite parent) { } class ItemSorter { - public static ISloeberConfiguration sloeberCfg; - public TreeMap myItems = new TreeMap<>(); - public IArduinoLibraryVersion myLib = null; + private TreeMap myItems = new TreeMap<>(); + private IArduinoLibraryVersion myLib = null; + private static Map myCurrentInstalledLibs =null; ItemSorter() { } + static void SetSloeberConfiguration(ISloeberConfiguration sloeberCfg) { + myCurrentInstalledLibs = sloeberCfg.getUsedLibraries(); + } + public void createChildren(TreeItem curItem) { for (Entry curentry : myItems.entrySet()) { String key = curentry.getKey(); @@ -83,7 +88,7 @@ public void createChildren(TreeItem curItem) { if (myLib == null) { curItem.setGrayed(true); }else { - boolean isSelected = sloeberCfg.getUsedLibraries().get(myLib.getName()) != null; + boolean isSelected = myCurrentInstalledLibs.get(myLib.getFQN()) != null; curItem.setChecked(isSelected); curItem.setData(myLib); if (isSelected) { @@ -127,7 +132,7 @@ protected void createSourceGroup(Composite parent) { // sort the items ItemSorter sortedItems = new ItemSorter(); - ItemSorter.sloeberCfg = sloeberCfg; + ItemSorter.SetSloeberConfiguration(sloeberCfg); for (IArduinoLibraryVersion curlib : allLibraries.values()) { String keys[] = curlib.getBreadCrumbs(); diff --git a/io.sloeber.ui/src/io/sloeber/ui/JsonMultiLineTextFieldEditor.java b/io.sloeber.ui/src/io/sloeber/ui/JsonMultiLineTextFieldEditor.java new file mode 100644 index 000000000..a0e63a879 --- /dev/null +++ b/io.sloeber.ui/src/io/sloeber/ui/JsonMultiLineTextFieldEditor.java @@ -0,0 +1,51 @@ +package io.sloeber.ui; + +import org.eclipse.cdt.core.parser.util.StringUtil; +import org.eclipse.cdt.ui.newui.MultiLineTextFieldEditor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Text; + + +/** + * A class to change MultiLineTextFieldEditor so it puts the label on top of the + * text field and the text field expands bot horizontal and verical + * Note I needed a FLAT parent FieldEditorPreferencePage (GRID did not work) + * public ThirdPartyHardwareSelectionPage() { + * super(org.eclipse.jface.preference.FieldEditorPreferencePage.FLAT); + */ +public class JsonMultiLineTextFieldEditor extends MultiLineTextFieldEditor{ + + public JsonMultiLineTextFieldEditor(String name, String labelText, int width, int strategy, Composite parent) { + super( name, labelText, width,strategy, parent); + } + + /** + * I want 1 column + */ + @Override + public int getNumberOfControls() { + return 1; + } + + + /** + * I want a GridData that has horizontal fill + */ + @Override + protected void doFillIntoGrid(Composite parent, int numColumns) { + super.doFillIntoGrid( parent, numColumns) ; + + Text textField = getTextControl(parent); + textField.setLayoutData( new GridData(SWT.FILL,SWT.BEGINNING,true,false)); + + } + + public void setText(String[] text) { + String actualText=StringUtil.join(text, System.lineSeparator()); + getPreferenceStore().setValue(getPreferenceName(), actualText); + setStringValue(actualText ); + } + +} diff --git a/io.sloeber.ui/src/io/sloeber/ui/Messages.java b/io.sloeber.ui/src/io/sloeber/ui/Messages.java index 319c18827..6ae513224 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/Messages.java +++ b/io.sloeber.ui/src/io/sloeber/ui/Messages.java @@ -66,7 +66,29 @@ public class Messages extends NLS { public static String packageTooltip; public static String PlatformSelectionPage_hide_third_party_url; - public static String platformSelectionTip; + public static String PreferencePage_centuries; + + public static String PreferencePage_days; + + public static String PreferencePage_Internal_Behaviour_Group_Title; + + public static String PreferencePage_json_Download_date; + + public static String PreferencePage_months; + + public static String PreferencePage_Network_Group_Title; + + public static String PreferencePage_UI_Behaviour_Group_Title; + + public static String PreferencePage_Update_json_files_now; + + public static String PreferencePage_update_interval; + + public static String PreferencePage_weeks; + + public static String PreferencePage_years; + + public static String platformSelectionTip; public static String pleaseWaitForInstallerJob; public static String plotterViewChannel; public static String plotterViewConnectedTo; diff --git a/io.sloeber.ui/src/io/sloeber/ui/MultiLineTextFieldEditor.java b/io.sloeber.ui/src/io/sloeber/ui/MultiLineTextFieldEditor.java deleted file mode 100644 index 1f3026449..000000000 --- a/io.sloeber.ui/src/io/sloeber/ui/MultiLineTextFieldEditor.java +++ /dev/null @@ -1,381 +0,0 @@ -package io.sloeber.ui; - -/******************************************************************************* - * Copyright (c) 2004 BitMethods Inc and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * BitMethods Inc - Initial API and implementation - *******************************************************************************/ - -import org.eclipse.jface.preference.FieldEditor; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; - -/** - * MultiLineTextFieldEditor. Field editor that is same as string field editor - * but will have the multi line text field for user input. - */ -public class MultiLineTextFieldEditor extends FieldEditor { - - /** - * Text limit constant (value -1) indicating unlimited text - * limit and width. - */ - public static int UNLIMITED = -1; - - /** - * Cached valid state. - */ - private boolean isValid; - - /** - * Old text value. - */ - private String oldValue; - private String compTitle; - private Label title; - - /** - * The text field, or null if none. - */ - protected Text textField; - - /** - * Text limit of text field in characters; initially unlimited. - */ - private int textLimit = UNLIMITED; - - /** - * Indicates whether the empty string is legal; true by - * default. - */ - private boolean emptyStringAllowed = true; - - /** - * Creates a new string field editor - */ - protected MultiLineTextFieldEditor() { - } - - /** - * Creates a string field editor. Use the method setTextLimit - * to limit the text. - * - * @param name - * the name of the preference this field editor works on - * @param labelText - * the label text of the field editor - * @param width - * the width of the text input field in characters, or - * UNLIMITED for no limit - * @param parent - * the parent of the field editor's control - * @since 2.0 - */ - public MultiLineTextFieldEditor(String name, String labelText, Composite parent) { - init(name, labelText); - this.isValid = false; - createControl(parent); - } - - /** - * Adjusts the horizontal span of this field editor's basic controls - *

- * Subclasses must implement this method to adjust the horizontal span of - * controls so they appear correct in the given number of columns. - *

- *

- * The number of columns will always be equal to or greater than the value - * returned by this editor's getNumberOfControls method. - * - * @param numColumns - * the number of columns - */ - @Override - protected void adjustForNumColumns(int numColumns) { - GridData gd = (GridData) this.textField.getLayoutData(); - // grab all the space we can - gd.horizontalSpan = numColumns; - gd.grabExcessHorizontalSpace = true; - gd.grabExcessVerticalSpace = true; - } - - /** - * Checks whether the text input field contains a valid value or not. - * - * @return true if the field value is valid, and - * false if invalid - */ - protected boolean checkState() { - String txt = this.textField.getText(); - - if (txt == null) - return false; - - return (txt.trim().length() > 0) || this.emptyStringAllowed; - } - - /** - * Fills this field editor's basic controls into the given parent. - *

- * The string field implementation of this FieldEditor - * framework method contributes the text field. Subclasses may override but - * must call super.doFillIntoGrid. - *

- */ - @Override - protected void doFillIntoGrid(Composite parent, int numColumns) { - - this.title = new Label(parent, SWT.UP); - this.title.setFont(parent.getFont()); - this.compTitle = getLabelText(); - this.title.setText(this.compTitle); - this.title.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); - - this.textField = getTextControl(parent); - GridData gd = new GridData(GridData.FILL_BOTH); - this.textField.setLayoutData(gd); - - } - - /** - * Initializes this field editor with the preference value from the - * preference store. - *

- * Subclasses must implement this method to properly initialize the field - * editor. - *

- */ - @Override - protected void doLoad() { - if (this.textField != null) { - String value = getPreferenceStore().getString(getPreferenceName()); - this.textField.setText(value); - this.oldValue = value; - } - } - - /** - * Initializes this field editor with the default preference value from the - * preference store. - *

- * Subclasses must implement this method to properly initialize the field - * editor. - *

- */ - @Override - protected void doLoadDefault() { - if (this.textField != null) { - String value = getPreferenceStore().getDefaultString(getPreferenceName()); - this.textField.setText(value); - } - valueChanged(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.FieldEditor#doStore() - */ - @Override - protected void doStore() { - getPreferenceStore().setValue(getPreferenceName(), this.textField.getText()); - } - - /** - * Returns the field editor's value. - * - * @return the current value - */ - public String getStringValue() { - if (this.textField != null) - return this.textField.getText(); - return getPreferenceStore().getString(getPreferenceName()); - } - - /** - * Returns this field editor's text control. - * - * @param parent - * the parent - * @return the text control, or null if no text field is - * created yet - */ - protected Text getTextControl() { - return this.textField; - } - - /** - * Returns this field editor's text control. - *

- * The control is created if it does not yet exist - *

- * - * @param parent - * the parent - * @return the text control - */ - public Text getTextControl(Composite parent) { - if (this.textField == null) { - this.textField = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER | SWT.WRAP); - this.textField.setFont(parent.getFont()); - - this.textField.addDisposeListener(new DisposeListener() { - - @Override - public void widgetDisposed(DisposeEvent event) { - MultiLineTextFieldEditor.this.textField = null; - } - - }); - - if (this.textLimit > 0) { // Only set limits above 0 - see SWT spec - this.textField.setTextLimit(this.textLimit); - } - } else { - checkParent(this.textField, parent); - } - return this.textField; - } - - /** - * Returns whether an empty string is a valid value. - * - * @return true if an empty string is a valid value, and - * false if an empty string is invalid - * @see #setEmptyStringAllowed - */ - - public boolean isEmptyStringAllowed() { - return this.emptyStringAllowed; - } - - /** - * Returns whether this field editor contains a valid value. - *

- * The default implementation of this framework method returns - * true. Subclasses wishing to perform validation should - * override both this method and refreshValidState. - *

- * - * @return true if the field value is valid, and - * false if invalid - * @see #refreshValidState - */ - @Override - public boolean isValid() { - return this.isValid; - } - - /** - * Refreshes this field editor's valid state after a value change and fires - * an IS_VALID property change event if warranted. - *

- * The default implementation of this framework method does nothing. - * Subclasses wishing to perform validation should override both this method - * and isValid. - *

- * - * @see #isValid - */ - @Override - protected void refreshValidState() { - this.isValid = checkState(); - } - - /** - * Sets whether the empty string is a valid value or not. - * - * @param b - * true if the empty string is allowed, and - * false if it is considered invalid - */ - public void setEmptyStringAllowed(boolean b) { - this.emptyStringAllowed = b; - } - - /** - * Sets the focus to this field editor. - *

- * The default implementation of this framework method does nothing. - * Subclasses may reimplement. - *

- */ - @Override - public void setFocus() { - if (this.textField != null) { - this.textField.setFocus(); - } - } - - /** - * Sets this field editor's value. - * - * @param value - * the new value, or null meaning the empty string - */ - public void setStringValue(String value) { - String safeValue = value; - if (value == null) - safeValue = ""; //$NON-NLS-1$ - if (this.textField != null) { - - this.oldValue = this.textField.getText(); - if (!this.oldValue.equals(safeValue)) { - this.textField.setText(safeValue); - valueChanged(); - } - } - } - - /** - * Sets this text field's text limit. - * - * @param limit - * the limit on the number of character in the text input field, - * or UNLIMITED for no limit - */ - public void setTextLimit(int limit) { - this.textLimit = limit; - if (this.textField != null) - this.textField.setTextLimit(limit); - } - - /** - * Informs this field editor's listener, if it has one, about a change to - * the value (VALUE property) provided that the old and new - * values are different. - *

- * This hook is not called when the text is initialized (or reset - * to the default value) from the preference store. - *

- */ - protected void valueChanged() { - setPresentsDefaultValue(false); - boolean oldState = this.isValid; - refreshValidState(); - - if (this.isValid != oldState) - fireStateChanged(IS_VALID, oldState, this.isValid); - - String newValue = this.textField.getText(); - if (!newValue.equals(this.oldValue)) { - fireValueChanged(VALUE, this.oldValue, newValue); - this.oldValue = newValue; - } - } - - @Override - public int getNumberOfControls() { - return 2; - } -} \ No newline at end of file diff --git a/io.sloeber.ui/src/io/sloeber/ui/actions/AddLibraryAction.java b/io.sloeber.ui/src/io/sloeber/ui/actions/AddLibraryAction.java index e6c93fb19..220151c72 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/actions/AddLibraryAction.java +++ b/io.sloeber.ui/src/io/sloeber/ui/actions/AddLibraryAction.java @@ -15,7 +15,7 @@ import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.wizards.IWizardDescriptor; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.ui.Messages; import io.sloeber.ui.listeners.ProjectExplorerListener; diff --git a/io.sloeber.ui/src/io/sloeber/ui/actions/AddSourceFolderAction.java b/io.sloeber.ui/src/io/sloeber/ui/actions/AddSourceFolderAction.java index ae5afdec8..fa15d5410 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/actions/AddSourceFolderAction.java +++ b/io.sloeber.ui/src/io/sloeber/ui/actions/AddSourceFolderAction.java @@ -15,7 +15,7 @@ import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.wizards.IWizardDescriptor; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.ui.Messages; import io.sloeber.ui.listeners.ProjectExplorerListener; diff --git a/io.sloeber.ui/src/io/sloeber/ui/actions/BuildHandler.java b/io.sloeber.ui/src/io/sloeber/ui/actions/BuildHandler.java index 44747c83a..4b8b7f390 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/actions/BuildHandler.java +++ b/io.sloeber.ui/src/io/sloeber/ui/actions/BuildHandler.java @@ -43,7 +43,7 @@ protected IStatus run(IProgressMonitor monitor) { } catch (CoreException e) { return new Status(IStatus.ERROR, NODE_ARDUINO, Messages.buildHandler_build_code_of_project.replace(Messages.PROJECT, myBuildProject.getName()) - + " failed", + + " failed", //$NON-NLS-1$ e); } return Status.OK_STATUS; diff --git a/io.sloeber.ui/src/io/sloeber/ui/actions/BurnBootloaderHandler.java b/io.sloeber.ui/src/io/sloeber/ui/actions/BurnBootloaderHandler.java index 3c437d6e3..a85087db9 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/actions/BurnBootloaderHandler.java +++ b/io.sloeber.ui/src/io/sloeber/ui/actions/BurnBootloaderHandler.java @@ -9,7 +9,7 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.core.api.ISloeberConfiguration; import io.sloeber.ui.Messages; import io.sloeber.ui.listeners.ProjectExplorerListener; diff --git a/io.sloeber.ui/src/io/sloeber/ui/actions/NewSketchHandler.java b/io.sloeber.ui/src/io/sloeber/ui/actions/NewSketchHandler.java index 6b7501865..47a7c1157 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/actions/NewSketchHandler.java +++ b/io.sloeber.ui/src/io/sloeber/ui/actions/NewSketchHandler.java @@ -11,7 +11,7 @@ import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.console.ConsolePlugin; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.ui.Messages; import io.sloeber.ui.wizard.newsketch.NewSketchWizard; diff --git a/io.sloeber.ui/src/io/sloeber/ui/actions/OpenSerialMonitorHandler.java b/io.sloeber.ui/src/io/sloeber/ui/actions/OpenSerialMonitorHandler.java index 42ca985d7..f5454992b 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/actions/OpenSerialMonitorHandler.java +++ b/io.sloeber.ui/src/io/sloeber/ui/actions/OpenSerialMonitorHandler.java @@ -9,7 +9,7 @@ import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; -import io.sloeber.core.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardDescription; import io.sloeber.core.api.ISloeberConfiguration; import io.sloeber.core.api.Sketch; import io.sloeber.ui.helpers.MyPreferences; diff --git a/io.sloeber.ui/src/io/sloeber/ui/actions/ProgramProjectHandler.java b/io.sloeber.ui/src/io/sloeber/ui/actions/ProgramProjectHandler.java index 2021c2c59..067187cd9 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/actions/ProgramProjectHandler.java +++ b/io.sloeber.ui/src/io/sloeber/ui/actions/ProgramProjectHandler.java @@ -11,7 +11,7 @@ import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.PlatformUI; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.ui.Messages; import io.sloeber.ui.listeners.ProjectExplorerListener; diff --git a/io.sloeber.ui/src/io/sloeber/ui/actions/UploadProjectHandler.java b/io.sloeber.ui/src/io/sloeber/ui/actions/UploadProjectHandler.java index 4b3a01d0b..9084fc53a 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/actions/UploadProjectHandler.java +++ b/io.sloeber.ui/src/io/sloeber/ui/actions/UploadProjectHandler.java @@ -22,7 +22,7 @@ import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.core.api.ISloeberConfiguration; import io.sloeber.ui.Messages; import io.sloeber.ui.helpers.MyPreferences; diff --git a/io.sloeber.ui/src/io/sloeber/ui/listeners/MyLibraryInstallHandler.java b/io.sloeber.ui/src/io/sloeber/ui/listeners/MyLibraryInstallHandler.java index 0ae56556c..4c8b8164e 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/listeners/MyLibraryInstallHandler.java +++ b/io.sloeber.ui/src/io/sloeber/ui/listeners/MyLibraryInstallHandler.java @@ -2,7 +2,7 @@ import java.util.Map; -import io.sloeber.core.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; import io.sloeber.core.api.IInstallLibraryHandler; import io.sloeber.ui.helpers.MyPreferences; diff --git a/io.sloeber.ui/src/io/sloeber/ui/messages.properties b/io.sloeber.ui/src/io/sloeber/ui/messages.properties index b148f61d8..ab4c98c34 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/messages.properties +++ b/io.sloeber.ui/src/io/sloeber/ui/messages.properties @@ -5,6 +5,17 @@ BoardSelectionPage_platform_folder=Platform folder BoardSelectionPage_platform_you_want_to_use=The platform you want to use BoardSelectionPage_upload_protocol=Programmer protocol PlatformSelectionPage_hide_third_party_url=Hide 3th party json files +PreferencePage_centuries=centuries +PreferencePage_days=days +PreferencePage_Internal_Behaviour_Group_Title=Internal behaviour +PreferencePage_json_Download_date=json download date +PreferencePage_months=months +PreferencePage_Network_Group_Title=Stuff that needs a network +PreferencePage_UI_Behaviour_Group_Title=UI behaviour +PreferencePage_Update_json_files_now=update json files now +PreferencePage_update_interval=Update json files every +PreferencePage_weeks=weeks +PreferencePage_years=years always=Always arduino_upload_project_handler_build_failed=The build failed\! arduino_upload_project_handler_build_failed_so_no_upload=As the build failed the upload is not executed. diff --git a/io.sloeber.ui/src/io/sloeber/ui/monitor/views/PlotterView.java b/io.sloeber.ui/src/io/sloeber/ui/monitor/views/PlotterView.java index 0576c99df..e4e6b9c42 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/monitor/views/PlotterView.java +++ b/io.sloeber.ui/src/io/sloeber/ui/monitor/views/PlotterView.java @@ -1,5 +1,9 @@ package io.sloeber.ui.monitor.views; + +import static io.sloeber.core.api.Const.*; + +import java.net.URI; import java.net.URL; import org.eclipse.core.runtime.IProgressMonitor; @@ -41,7 +45,7 @@ public class PlotterView extends ViewPart implements ServiceListener { Serial mySerial = null; private static final String FLAG_MONITOR = "FmStatus"; //$NON-NLS-1$ - String uri = "h tt p://bae yens.i t/ec li pse/do wnl oad/Sc opeS tart.h t ml?m="; //$NON-NLS-1$ + private static String uri = "h tt p://bae yens.i t/ec li pse/do wnl oad/Sc opeS tart.h t ml?m="; //$NON-NLS-1$ public Object mstatus; // status of the plotter public PlotterView() { @@ -53,8 +57,8 @@ protected IStatus run(IProgressMonitor monitor) { IEclipsePreferences mySCope = InstanceScope.INSTANCE.getNode(MyPreferences.NODE_ARDUINO); int curFsiStatus = mySCope.getInt(FLAG_MONITOR, 0) + 1; mySCope.putInt(FLAG_MONITOR, curFsiStatus); - URL pluginStartInitiator = new URL( - PlotterView.this.uri.replace(" ", "") + Integer.toString(curFsiStatus)); //$NON-NLS-1$ //$NON-NLS-2$ + URI tt= new URI(uri.replace(SPACE, EMPTY) + Integer.toString(curFsiStatus)); + URL pluginStartInitiator = tt.toURL(); PlotterView.this.mstatus = pluginStartInitiator.getContent(); } catch (Exception e) {// JABA is not going to add code } diff --git a/io.sloeber.ui/src/io/sloeber/ui/monitor/views/SerialMonitor.java b/io.sloeber.ui/src/io/sloeber/ui/monitor/views/SerialMonitor.java index 0aafcddf6..e32fca404 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/monitor/views/SerialMonitor.java +++ b/io.sloeber.ui/src/io/sloeber/ui/monitor/views/SerialMonitor.java @@ -1,8 +1,10 @@ package io.sloeber.ui.monitor.views; +import static io.sloeber.core.api.Const.*; import static io.sloeber.ui.Activator.*; import java.io.File; +import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; @@ -200,9 +202,8 @@ protected IStatus run(IProgressMonitor monitor) { IEclipsePreferences myScope = InstanceScope.INSTANCE.getNode(MyPreferences.NODE_ARDUINO); int curFsiStatus = myScope.getInt(MY_FLAG_MONITOR, 0) + 1; myScope.putInt(MY_FLAG_MONITOR, curFsiStatus); - URL mypluginStartInitiator = new URL(uri.replace(" ", new String()) //$NON-NLS-1$ - + Integer.toString(curFsiStatus)); - mypluginStartInitiator.getContent(); + URI tt= new URI(uri.replace(SPACE, EMPTY) + Integer.toString(curFsiStatus)); + tt.toURL().getContent(); } catch (Exception e) {// JABA is not going to add code } return Status.OK_STATUS; diff --git a/io.sloeber.ui/src/io/sloeber/ui/preferences/LibrarySelectionPage.java b/io.sloeber.ui/src/io/sloeber/ui/preferences/LibrarySelectionPage.java index bc945afd1..095d3ff05 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/preferences/LibrarySelectionPage.java +++ b/io.sloeber.ui/src/io/sloeber/ui/preferences/LibrarySelectionPage.java @@ -41,12 +41,12 @@ import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; -import io.sloeber.core.api.LibraryManager; +import io.sloeber.arduinoFramework.api.IArduinoLibrary; +import io.sloeber.arduinoFramework.api.IArduinoLibraryIndex; +import io.sloeber.arduinoFramework.api.IArduinoLibraryVersion; +import io.sloeber.arduinoFramework.api.LibraryManager; +import io.sloeber.arduinoFramework.api.Node; import io.sloeber.core.api.VersionNumber; -import io.sloeber.core.api.Json.ArduinoLibrary; -import io.sloeber.core.api.Json.ArduinoLibraryIndex; -import io.sloeber.core.api.Json.ArduinoLibraryVersion; -import io.sloeber.core.api.Json.Node; import io.sloeber.ui.Messages; import io.sloeber.ui.preferences.LibrarySelectionPage.LibraryTree.Category; import io.sloeber.ui.preferences.LibrarySelectionPage.LibraryTree.Library; @@ -60,7 +60,7 @@ public class LibrarySelectionPage extends PreferencePage implements IWorkbenchPr protected LibraryTree libs = new LibraryTree(); final static String emptyString = ""; //$NON-NLS-1$ final static String blankLine = "\n\n";//$NON-NLS-1$ - final static String canUpdateLabel = " (can update)"; + final static String canUpdateLabel = " (can update)"; //$NON-NLS-1$ public static class LibraryTree extends Node { @@ -110,23 +110,23 @@ public String getID() { } public class Library extends Node implements Comparable { - private ArduinoLibrary myLib; + private IArduinoLibrary myLib; private Category myParent; - protected ArduinoLibraryVersion myToInstallVersion; - protected ArduinoLibraryVersion myInstalledVersion; + protected IArduinoLibraryVersion myToInstallVersion; + protected IArduinoLibraryVersion myInstalledVersion; - public Library(Category category, ArduinoLibrary lib) { + public Library(Category category, IArduinoLibrary lib) { myParent = category; myLib = lib; myInstalledVersion = myLib.getInstalledVersion(); myToInstallVersion = myInstalledVersion; } - public ArduinoLibraryVersion getInstalledVersion() { + public IArduinoLibraryVersion getInstalledVersion() { return myInstalledVersion; } - public Collection getVersions() { + public Collection getVersions() { return myLib.getVersions(); } @@ -146,24 +146,23 @@ public boolean canUpdate() { public String getTooltip() { if (myTooltip == null) { - ArduinoLibraryVersion libVers = getLatest(); - myTooltip = "Architectures:" + libVers.getArchitectures().toString() + blankLine - + libVers.getSentence() + blankLine + libVers.getParagraph() + blankLine + "Author: " - + libVers.getAuthor() + blankLine + "Maintainer: " + libVers.getMaintainer() + blankLine - + "provided by: " + libVers.getParent().getParent().getNodeName(); + IArduinoLibraryVersion libVers = getLatest(); + myTooltip = "Architectures:" + libVers.getArchitectures().toString() + blankLine //$NON-NLS-1$ + + libVers.getSentence() + blankLine + libVers.getParagraph() + blankLine + "Author: " //$NON-NLS-1$ + + libVers.getAuthor() + blankLine + "Maintainer: " + libVers.getMaintainer() ; //$NON-NLS-1$ } return myTooltip; } - public ArduinoLibraryVersion getLatest() { + public IArduinoLibraryVersion getLatest() { return myLib.getNewestVersion(); } - public ArduinoLibraryVersion getVersion() { + public IArduinoLibraryVersion getVersion() { return myToInstallVersion; } - public void setVersion(ArduinoLibraryVersion version) { + public void setVersion(IArduinoLibraryVersion version) { myToInstallVersion = version; } @@ -179,7 +178,7 @@ public int compareTo(Library other) { return myLib.compareTo(other.getArduinoLibrary()); } - private ArduinoLibrary getArduinoLibrary() { + private IArduinoLibrary getArduinoLibrary() { return myLib; } @@ -213,8 +212,8 @@ public String getID() { } public LibraryTree() { - for (ArduinoLibraryIndex libraryIndex : LibraryManager.getLibraryIndices()) { - for (ArduinoLibrary arduinoLibrary : libraryIndex.getLibraries()) { + for (IArduinoLibraryIndex libraryIndex : LibraryManager.getLibraryIndices()) { + for (IArduinoLibrary arduinoLibrary : libraryIndex.getLibraries()) { String categoryName = arduinoLibrary.getCategory(); Category category = this.categories.get(categoryName); if (category == null) { @@ -288,12 +287,12 @@ public boolean performOk() { @Override protected IStatus run(IProgressMonitor monitor) { MultiStatus status = new MultiStatus(PLUGIN_ID, 0, Messages.ui_installing_arduino_libraries, null); - Set toRemoveLibs = new HashSet<>(); - Set toInstallLibs = new HashSet<>(); + Set toRemoveLibs = new HashSet<>(); + Set toInstallLibs = new HashSet<>(); for (Category category : libs.categories.values()) { for (Library library : category.libraries.values()) { - ArduinoLibraryVersion installedVersion = library.getInstalledVersion(); - ArduinoLibraryVersion toInstalVersion = library.getVersion(); + IArduinoLibraryVersion installedVersion = library.getInstalledVersion(); + IArduinoLibraryVersion toInstalVersion = library.getVersion(); if ((installedVersion != null) && (installedVersion.compareTo(toInstalVersion) != 0)) { toRemoveLibs.add(installedVersion); } @@ -383,7 +382,7 @@ public void widgetSelected(SelectionEvent event) { if (item.getChecked()) { child.setVersion(child.getLatest()); } else { - child.setVersion((ArduinoLibraryVersion) null); + child.setVersion((IArduinoLibraryVersion) null); } } for (TreeItem child : item.getItems()) { @@ -396,7 +395,7 @@ public void widgetSelected(SelectionEvent event) { if (item.getChecked()) { lib.setVersion(lib.getLatest()); } else { - lib.setVersion((ArduinoLibraryVersion) null); + lib.setVersion((IArduinoLibraryVersion) null); } item.setText(0, lib.getNodeName()); @@ -409,11 +408,11 @@ public void widgetSelected(SelectionEvent event) { // Create the dropdown and add data to it final CCombo combo = new CCombo(LibrarySelectionPage.this.viewer.getTree(), SWT.READ_ONLY); Library selectedLib = ((LibraryTree.Library) item.getData()); - for (ArduinoLibraryVersion version1 : selectedLib.getVersions()) { + for (IArduinoLibraryVersion version1 : selectedLib.getVersions()) { combo.add(version1.getVersion().toString()); } - ArduinoLibraryVersion displayVersion = selectedLib.getVersion(); + IArduinoLibraryVersion displayVersion = selectedLib.getVersion(); if (displayVersion == null) { displayVersion = selectedLib.getLatest(); selectedLib.setVersion(displayVersion); diff --git a/io.sloeber.ui/src/io/sloeber/ui/preferences/PlatformSelectionPage.java b/io.sloeber.ui/src/io/sloeber/ui/preferences/PlatformSelectionPage.java index 879ba7b47..465db957e 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/preferences/PlatformSelectionPage.java +++ b/io.sloeber.ui/src/io/sloeber/ui/preferences/PlatformSelectionPage.java @@ -39,12 +39,12 @@ import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.IArduinoPackage; +import io.sloeber.arduinoFramework.api.IArduinoPlatform; +import io.sloeber.arduinoFramework.api.IArduinoPlatformPackageIndex; +import io.sloeber.arduinoFramework.api.IArduinoPlatformVersion; import io.sloeber.core.api.VersionNumber; -import io.sloeber.core.api.Json.ArduinoPackage; -import io.sloeber.core.api.Json.ArduinoPlatform; -import io.sloeber.core.api.Json.ArduinoPlatformPackageIndex; -import io.sloeber.core.api.Json.ArduinoPlatformVersion; import io.sloeber.ui.Messages; import io.sloeber.ui.helpers.MyPreferences; @@ -53,11 +53,15 @@ public class PlatformSelectionPage extends PreferencePage implements IWorkbenchP // platform index json, package,platform,versions structure private TreeMap>> myShownPlatforms = new TreeMap<>(); - private boolean mustBeInstalled(ArduinoPlatform platform) { - ArduinoPackage parentPkg = platform.getParent(); - ArduinoPlatformPackageIndex parentIndex = parentPkg.getPackageIndex(); + private boolean mustBeInstalled(IArduinoPlatform platform) { + IArduinoPackage parentPkg = platform.getParent(); + IArduinoPlatformPackageIndex parentIndex = parentPkg.getPackageIndex(); InstallableVersion[] inScopeVersions = myShownPlatforms.get(parentIndex.getID()).get(parentPkg.getID()) .get(platform.getID()); + if(inScopeVersions==null) { + //in case there are no versions + return false; + } for (InstallableVersion version : inScopeVersions) { if (version.mustBeInstalled()) { return true; @@ -66,9 +70,13 @@ private boolean mustBeInstalled(ArduinoPlatform platform) { return false; } - private boolean mustBeInstalled(ArduinoPlatformPackageIndex packageIndex) { + private boolean mustBeInstalled(IArduinoPlatformPackageIndex packageIndex) { TreeMap> inScopeVersions = myShownPlatforms .get(packageIndex.getID()); + if(inScopeVersions==null) { + //in case there are no versions + return false; + } for (TreeMap platform : inScopeVersions.values()) { for (InstallableVersion[] versions : platform.values()) { for (InstallableVersion version : versions) { @@ -81,10 +89,14 @@ private boolean mustBeInstalled(ArduinoPlatformPackageIndex packageIndex) { return false; } - private boolean mustBeInstalled(ArduinoPackage pkg) { - ArduinoPlatformPackageIndex parentIndex = pkg.getPackageIndex(); + private boolean mustBeInstalled(IArduinoPackage pkg) { + IArduinoPlatformPackageIndex parentIndex = pkg.getPackageIndex(); TreeMap inScopeVersions = myShownPlatforms.get(parentIndex.getID()) .get(pkg.getID()); + if(inScopeVersions==null) { + //in case there are no versions + return false; + } for (InstallableVersion[] versions : inScopeVersions.values()) { for (InstallableVersion version : versions) { if (version.mustBeInstalled()) { @@ -96,10 +108,10 @@ private boolean mustBeInstalled(ArduinoPackage pkg) { } public static class InstallableVersion implements Comparable { - private ArduinoPlatformVersion myPlatformm; + private IArduinoPlatformVersion myPlatformm; private boolean myMustBeInstalled; - public InstallableVersion(ArduinoPlatformVersion platformm) { + public InstallableVersion(IArduinoPlatformVersion platformm) { myPlatformm = platformm; myMustBeInstalled = myPlatformm.isInstalled(); } @@ -125,25 +137,25 @@ public int compareTo(InstallableVersion o) { return getVersion().compareTo(o.getVersion()); } - public ArduinoPlatformVersion getPlatform() { + public IArduinoPlatformVersion getPlatform() { return myPlatformm; } } public PlatformSelectionPage() { - for (ArduinoPlatformPackageIndex curPackageIndex : BoardsManager.getPackageIndices()) { + for (IArduinoPlatformPackageIndex curPackageIndex : BoardsManager.getPackageIndices()) { String pkgIndexID = curPackageIndex.getID(); TreeMap> packageMap = new TreeMap<>(); - for (ArduinoPackage curPackage : curPackageIndex.getPackages()) { + for (IArduinoPackage curPackage : curPackageIndex.getPackages()) { TreeMap platformMap = new TreeMap<>(); String pkgID = curPackage.getID(); - for (ArduinoPlatform curPlatform : curPackage.getPlatforms()) { + for (IArduinoPlatform curPlatform : curPackage.getPlatforms()) { String platformID = curPlatform.getID(); - Collection platformVersions = curPlatform.getVersions(); + Collection platformVersions = curPlatform.getVersions(); InstallableVersion versions[] = new InstallableVersion[platformVersions.size()]; int index = 0; - for (ArduinoPlatformVersion curPlatformversion : platformVersions) { + for (IArduinoPlatformVersion curPlatformversion : platformVersions) { versions[index++] = new InstallableVersion(curPlatformversion); } // InstallableVersion arrayVersions[] = versions.toArray(new InstallableVersion[versions.size()]); @@ -201,23 +213,23 @@ protected boolean isLeafMatch(final Viewer viewer1, final Object element) { isMatch |= myWordMatches(ver.getPlatform()); } - if (element instanceof ArduinoPlatformPackageIndex) { - ArduinoPlatformPackageIndex indexFile = (ArduinoPlatformPackageIndex) element; + if (element instanceof IArduinoPlatformPackageIndex) { + IArduinoPlatformPackageIndex indexFile = (IArduinoPlatformPackageIndex) element; isMatch |= myWordMatches(indexFile); } - if (element instanceof ArduinoPackage) { - ArduinoPackage pac = (ArduinoPackage) element; + if (element instanceof IArduinoPackage) { + IArduinoPackage pac = (IArduinoPackage) element; isMatch |= myWordMatches(pac); } - if (element instanceof ArduinoPlatformVersion) { - ArduinoPlatformVersion platform = (ArduinoPlatformVersion) element; + if (element instanceof IArduinoPlatformVersion) { + IArduinoPlatformVersion platform = (IArduinoPlatformVersion) element; isMatch |= myWordMatches(platform); } return isMatch; } - private boolean myWordMatches(ArduinoPlatformVersion arduinoPlatformVersion) { + private boolean myWordMatches(IArduinoPlatformVersion arduinoPlatformVersion) { boolean ret = wordMatches(arduinoPlatformVersion.getName()); ret |= wordMatches(arduinoPlatformVersion.getArchitecture()); ret |= wordMatches(arduinoPlatformVersion.getConcattenatedBoardNames()); @@ -225,16 +237,17 @@ private boolean myWordMatches(ArduinoPlatformVersion arduinoPlatformVersion) { return ret; } - private boolean myWordMatches(ArduinoPackage pac) { + private boolean myWordMatches(IArduinoPackage pac) { boolean ret = wordMatches(pac.getEmail()); ret |= wordMatches(pac.getMaintainer()); - ret |= wordMatches(pac.getNodeName()); + //ret |= wordMatches(pac.getNodeName()); + ret |= wordMatches(pac.getName()); ret |= wordMatches(pac.getWebsiteURL().toString()); ret |= wordMatches(pac.getPackageIndex().getJsonFile().toString()); return ret; } - private boolean myWordMatches(ArduinoPlatformPackageIndex indexFile) { + private boolean myWordMatches(IArduinoPlatformPackageIndex indexFile) { return wordMatches(indexFile.getID()); } @@ -253,14 +266,14 @@ public boolean isChecked(Object element) { if (element instanceof InstallableVersion) { return ((InstallableVersion) element).mustBeInstalled(); } - if (element instanceof ArduinoPlatformPackageIndex) { - return mustBeInstalled((ArduinoPlatformPackageIndex) element); + if (element instanceof IArduinoPlatformPackageIndex) { + return mustBeInstalled((IArduinoPlatformPackageIndex) element); } - if (element instanceof ArduinoPackage) { - return mustBeInstalled((ArduinoPackage) element); + if (element instanceof IArduinoPackage) { + return mustBeInstalled((IArduinoPackage) element); } - if (element instanceof ArduinoPlatform) { - return mustBeInstalled((ArduinoPlatform) element); + if (element instanceof IArduinoPlatform) { + return mustBeInstalled((IArduinoPlatform) element); } return false; } @@ -270,14 +283,14 @@ public boolean isGrayed(Object element) { if (element instanceof InstallableVersion) { return false; } - if (element instanceof ArduinoPlatformPackageIndex) { - return mustBeInstalled((ArduinoPlatformPackageIndex) element); + if (element instanceof IArduinoPlatformPackageIndex) { + return mustBeInstalled((IArduinoPlatformPackageIndex) element); } - if (element instanceof ArduinoPackage) { - return mustBeInstalled((ArduinoPackage) element); + if (element instanceof IArduinoPackage) { + return mustBeInstalled((IArduinoPackage) element); } - if (element instanceof ArduinoPlatform) { - return mustBeInstalled((ArduinoPlatform) element); + if (element instanceof IArduinoPlatform) { + return mustBeInstalled((IArduinoPlatform) element); } return false; } @@ -302,11 +315,11 @@ public void checkStateChanged(CheckStateChangedEvent event) { @Override public Object[] getElements(Object inputElement) { if (PlatformSelectionPage.this.myHideJson) { - List packages = BoardsManager.getPackages(); + List packages = BoardsManager.getPackages(); Collections.sort(packages); return packages.toArray(new Object[packages.size()]); } - List indexFiles = BoardsManager.getPackageIndices(); + List indexFiles = BoardsManager.getPackageIndices(); return indexFiles.toArray(new Object[indexFiles.size()]); } @@ -322,21 +335,21 @@ public void inputChanged(Viewer viewer11, Object oldInput, Object newInput) { @Override public Object[] getChildren(Object parentElement) { - if (parentElement instanceof ArduinoPlatformPackageIndex) { - Collection packages = ((ArduinoPlatformPackageIndex) parentElement) + if (parentElement instanceof IArduinoPlatformPackageIndex) { + Collection packages = ((IArduinoPlatformPackageIndex) parentElement) .getPackages(); return packages.toArray(new Object[packages.size()]); } - if (parentElement instanceof ArduinoPackage) { - Collection platforms = ((ArduinoPackage) parentElement).getPlatforms(); - ArduinoPlatform platformArray[] = platforms.toArray(new ArduinoPlatform[platforms.size()]); + if (parentElement instanceof IArduinoPackage) { + Collection platforms = ((IArduinoPackage) parentElement).getPlatforms(); + IArduinoPlatform platformArray[] = platforms.toArray(new IArduinoPlatform[platforms.size()]); Arrays.sort(platformArray); return platformArray; } - if (parentElement instanceof ArduinoPlatform) { - ArduinoPlatform platform = (ArduinoPlatform) parentElement; - ArduinoPackage parentPackage = platform.getParent(); - ArduinoPlatformPackageIndex parentIndex = parentPackage.getPackageIndex(); + if (parentElement instanceof IArduinoPlatform) { + IArduinoPlatform platform = (IArduinoPlatform) parentElement; + IArduinoPackage parentPackage = platform.getParent(); + IArduinoPlatformPackageIndex parentIndex = parentPackage.getPackageIndex(); return myShownPlatforms.get(parentIndex.getID()).get(parentPackage.getID()) .get(platform.getID()); } @@ -358,13 +371,13 @@ public boolean hasChildren(Object element) { viewer1.setLabelProvider(new CellLabelProvider() { @Override public String getToolTipText(Object element) { - if (element instanceof ArduinoPlatformPackageIndex) { - return ((ArduinoPlatformPackageIndex) element).getID(); + if (element instanceof IArduinoPlatformPackageIndex) { + return ((IArduinoPlatformPackageIndex) element).getID(); } - if (element instanceof ArduinoPackage) { + if (element instanceof IArduinoPackage) { String NULL = "NULL"; //$NON-NLS-1$ - ArduinoPackage pkg = (ArduinoPackage) element; + IArduinoPackage pkg = (IArduinoPackage) element; String maintainer = pkg.getMaintainer(); String email = pkg.getEmail(); String weburlString = pkg.getWebsiteURL(); @@ -379,8 +392,8 @@ public String getToolTipText(Object element) { .replace(Messages.EMAIL, email).replace(Messages.URL, weburlString); } - if (element instanceof ArduinoPlatformVersion) { - return ((ArduinoPlatformVersion) element).getConcattenatedBoardNames(); + if (element instanceof IArduinoPlatformVersion) { + return ((IArduinoPlatformVersion) element).getConcattenatedBoardNames(); } if (element instanceof InstallableVersion) { @@ -407,16 +420,24 @@ public int getToolTipTimeDisplayed(Object object) { @Override public void update(ViewerCell cell) { - if (cell.getElement() instanceof ArduinoPlatformPackageIndex) { - cell.setText(((ArduinoPlatformPackageIndex) cell.getElement()).getNodeName()); +// if (cell.getElement() instanceof IArduinoPlatformPackageIndex) { +// cell.setText(((IArduinoPlatformPackageIndex) cell.getElement()).getNodeName()); +// +// } + if (cell.getElement() instanceof IArduinoPlatformPackageIndex) { + cell.setText(((IArduinoPlatformPackageIndex) cell.getElement()).getName()); } - if (cell.getElement() instanceof ArduinoPackage) { - cell.setText(((ArduinoPackage) cell.getElement()).getNodeName()); +// if (cell.getElement() instanceof IArduinoPackage) { +// cell.setText(((IArduinoPackage) cell.getElement()).getNodeName()); +// +// } + if (cell.getElement() instanceof IArduinoPackage) { + cell.setText(((IArduinoPackage) cell.getElement()).getName()); } - if (cell.getElement() instanceof ArduinoPlatform) { - cell.setText(((ArduinoPlatform) cell.getElement()).getName()); + if (cell.getElement() instanceof IArduinoPlatform) { + cell.setText(((IArduinoPlatform) cell.getElement()).getName()); } if (cell.getElement() instanceof InstallableVersion) { @@ -440,8 +461,8 @@ public void update(ViewerCell cell) { } protected IStatus updateInstallation(IProgressMonitor monitor) { - List platformsToInstall = new LinkedList<>(); - List platformsToRemove = new LinkedList<>(); + List platformsToInstall = new LinkedList<>(); + List platformsToRemove = new LinkedList<>(); for (TreeMap> packageIndex : myShownPlatforms.values()) { for (TreeMap arduinoPackage : packageIndex.values()) { for (InstallableVersion[] versions : arduinoPackage.values()) { diff --git a/io.sloeber.ui/src/io/sloeber/ui/preferences/PreferencePage.java b/io.sloeber.ui/src/io/sloeber/ui/preferences/PreferencePage.java index e2e2da656..493c252bb 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/preferences/PreferencePage.java +++ b/io.sloeber.ui/src/io/sloeber/ui/preferences/PreferencePage.java @@ -3,6 +3,10 @@ import static io.sloeber.ui.Activator.*; import java.io.File; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import org.eclipse.core.runtime.IPath; @@ -15,18 +19,31 @@ import org.eclipse.jface.preference.ComboFieldEditor; import org.eclipse.jface.preference.FieldEditorPreferencePage; import org.eclipse.jface.preference.PathEditor; +import org.eclipse.jface.resource.FontRegistry; +import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Font; 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.Group; import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Spinner; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; import org.eclipse.ui.preferences.ScopedPreferenceStore; +import org.eclipse.ui.themes.ITheme; +import org.eclipse.ui.themes.IThemeManager; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.core.api.Defaults; -import io.sloeber.core.api.LibraryManager; -import io.sloeber.core.api.BoardsManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; import io.sloeber.ui.Messages; import io.sloeber.ui.helpers.MyPreferences; @@ -43,6 +60,8 @@ */ public class PreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { + + private static final String TRUE = "TRUE"; //$NON-NLS-1$ private static final String FALSE = "FALSE"; //$NON-NLS-1$ private static final String KEY_AUTO_IMPORT_LIBRARIES = "Gui entry for import libraries"; //$NON-NLS-1$ @@ -50,20 +69,25 @@ public class PreferencePage extends FieldEditorPreferencePage implements IWorkbe private static final String KEY_PRIVATE_HARDWARE_PATHS = "Gui entry for private hardware paths"; //$NON-NLS-1$ private static final String KEY_PRIVATE_LIBRARY_PATHS = "Gui entry for private library paths"; //$NON-NLS-1$ private static final String KEY_TOOLCHAIN_SELECTION = "Gui entry for toolchain selection"; //$NON-NLS-1$ - private static final String KEY_USE_BONJOUR = "Gui entry for usage of bonjour"; //$NON-NLS-1$ + private PathEditor arduinoPrivateLibPathPathEditor; private PathEditor arduinoPrivateHardwarePathPathEditor; private ComboFieldEditor buildBeforeUploadOptionEditor; private BooleanFieldEditor openSerialMonitorOpensSerialsOptionEditor; private BooleanFieldEditor automaticallyImportLibrariesOptionEditor; - private BooleanFieldEditor automaticallyInstallLibrariesOptionEditor; private BooleanFieldEditor useArduinoToolchainSelectionEditor; private BooleanFieldEditor pragmaOnceHeaderOptionEditor; private BooleanFieldEditor cleanSerialMonitorAfterUploadEditor; private BooleanFieldEditor switchToSerialMonitorAfterUploadEditor; private BooleanFieldEditor enableParallelBuildForNewProjects; - private BooleanFieldEditor enableBonjour; + + private Button myBonjourCheckBox; + private Spinner myDelayNumberSpinner; + private Combo myDelayUnitCombo; + private Button myInstallLibCheckBox; + + private static int[] durationUnits = new int[] { 1, 7, 30, 365, 36500 }; public PreferencePage() { super(org.eclipse.jface.preference.FieldEditorPreferencePage.GRID); @@ -75,7 +99,7 @@ public PreferencePage() { MyPreferences.DEFAULT_OPEN_SERIAL_WITH_MONITOR); preferences.setDefault(KEY_AUTO_IMPORT_LIBRARIES, true); preferences.setDefault(KEY_PRAGMA_ONCE_HEADERS, true); - preferences.setDefault(KEY_USE_BONJOUR, Defaults.useBonjour); + preferences.setDefault(KEY_PRIVATE_HARDWARE_PATHS, Defaults.getPrivateHardwarePath()); preferences.setDefault(KEY_PRIVATE_LIBRARY_PATHS, Defaults.getPrivateLibraryPath()); preferences.setDefault(KEY_TOOLCHAIN_SELECTION, Defaults.useArduinoToolSelection); @@ -126,10 +150,14 @@ public boolean performOk() { libraryPaths=filteredList; log(new Status(IStatus.ERROR, PLUGIN_ID, Messages.Invalid_Private_Library_folder)); } - Preferences.setUseArduinoToolSelection(this.useArduinoToolchainSelectionEditor.getBooleanValue()); - Preferences.setAutoImportLibraries(this.automaticallyImportLibrariesOptionEditor.getBooleanValue()); - Preferences.setPragmaOnceHeaders(this.pragmaOnceHeaderOptionEditor.getBooleanValue()); - Preferences.setUseBonjour(enableBonjour.getBooleanValue()); + ConfigurationPreferences.setUseArduinoToolSelection(this.useArduinoToolchainSelectionEditor.getBooleanValue()); + ConfigurationPreferences.setAutoImportLibraries(this.automaticallyImportLibrariesOptionEditor.getBooleanValue()); + ConfigurationPreferences.setPragmaOnceHeaders(this.pragmaOnceHeaderOptionEditor.getBooleanValue()); + ConfigurationPreferences.setUseBonjour(myBonjourCheckBox.getSelection()); + ConfigurationPreferences.setInstallLibraries(myInstallLibCheckBox.getSelection()); + + //TOFIX line below + ConfigurationPreferences.setJsonUpdateDelay(Duration.ofDays(myDelayNumberSpinner.getSelection() * durationUnits[myDelayUnitCombo.getSelectionIndex()])); BoardsManager.setPrivateHardwarePaths(hardWarePaths); LibraryManager.setPrivateLibraryPaths(libraryPaths); return ret; @@ -164,10 +192,9 @@ private static String[] filterUnwantedPaths(String[] paths) { public void init(IWorkbench workbench) { String hardWarePaths = BoardsManager.getPrivateHardwarePathsString(); String libraryPaths = LibraryManager.getPrivateLibraryPathsString(); - boolean autoImport = Preferences.getAutoImportLibraries(); - boolean pragmaOnceHeaders = Preferences.getPragmaOnceHeaders(); - boolean useArduinoToolchainSelection =Preferences.getUseArduinoToolSelection(); - boolean useBonjour=Preferences.useBonjour(); + boolean autoImport = ConfigurationPreferences.getAutoImportLibraries(); + boolean pragmaOnceHeaders = ConfigurationPreferences.getPragmaOnceHeaders(); + boolean useArduinoToolchainSelection =ConfigurationPreferences.getUseArduinoToolSelection(); getPreferenceStore().setValue(KEY_AUTO_IMPORT_LIBRARIES, autoImport); @@ -175,7 +202,6 @@ public void init(IWorkbench workbench) { getPreferenceStore().setValue(KEY_PRIVATE_HARDWARE_PATHS, hardWarePaths); getPreferenceStore().setValue(KEY_PRIVATE_LIBRARY_PATHS, libraryPaths); getPreferenceStore().setValue(KEY_TOOLCHAIN_SELECTION, useArduinoToolchainSelection); - getPreferenceStore().setValue(KEY_USE_BONJOUR, useBonjour); } @@ -187,65 +213,181 @@ public void init(IWorkbench workbench) { */ @Override protected void createFieldEditors() { - final Composite parent = getFieldEditorParent(); - - this.arduinoPrivateLibPathPathEditor = new PathEditor(KEY_PRIVATE_LIBRARY_PATHS, Messages.ui_private_lib_path, - Messages.ui_private_lib_path_help, parent); - addField(this.arduinoPrivateLibPathPathEditor); - - this.arduinoPrivateHardwarePathPathEditor = new PathEditor(KEY_PRIVATE_HARDWARE_PATHS, Messages.ui_private_hardware_path, - Messages.ui_private_hardware_path_help, parent); - addField(this.arduinoPrivateHardwarePathPathEditor); - - Dialog.applyDialogFont(parent); - createLine(parent, 4); - String[][] YesNoAskOptions = new String[][] { { Messages.ui_ask_every_upload, "ASK" }, //$NON-NLS-1$ - { Messages.yes, TRUE }, { Messages.no, FALSE } }; - this.buildBeforeUploadOptionEditor = new ComboFieldEditor(MyPreferences.KEY_BUILD_BEFORE_UPLOAD_OPTION, - Messages.ui_build_before_upload, YesNoAskOptions, parent); - addField(this.buildBeforeUploadOptionEditor); - createLine(parent, 4); + final Composite rootParent = getFieldEditorParent(); + Dialog.applyDialogFont(rootParent); + IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); + ITheme currentTheme = themeManager.getCurrentTheme(); + FontRegistry fontRegistry = currentTheme.getFontRegistry(); + Font headerFont =fontRegistry.get(JFaceResources.HEADER_FONT); - this.useArduinoToolchainSelectionEditor = new BooleanFieldEditor(KEY_TOOLCHAIN_SELECTION, - Messages.ui_use_arduino_toolchain_selection, BooleanFieldEditor.DEFAULT, parent); - addField(this.useArduinoToolchainSelectionEditor); + arduinoPrivateLibPathPathEditor = new PathEditor(KEY_PRIVATE_LIBRARY_PATHS, Messages.ui_private_lib_path, + Messages.ui_private_lib_path_help, rootParent); + addField(arduinoPrivateLibPathPathEditor); - createLine(parent, 4); - this.openSerialMonitorOpensSerialsOptionEditor = new BooleanFieldEditor(MyPreferences.KEY_OPEN_SERIAL_WITH_MONITOR, - Messages.ui_open_serial_with_monitor, BooleanFieldEditor.DEFAULT, parent); - addField(this.openSerialMonitorOpensSerialsOptionEditor); - createLine(parent, 4); + arduinoPrivateHardwarePathPathEditor = new PathEditor(KEY_PRIVATE_HARDWARE_PATHS, Messages.ui_private_hardware_path, + Messages.ui_private_hardware_path_help, rootParent); + addField(arduinoPrivateHardwarePathPathEditor); - this.automaticallyImportLibrariesOptionEditor = new BooleanFieldEditor(KEY_AUTO_IMPORT_LIBRARIES, - Messages.ui_auto_import_libraries, BooleanFieldEditor.DEFAULT, parent); - addField(this.automaticallyImportLibrariesOptionEditor); - this.automaticallyInstallLibrariesOptionEditor = new BooleanFieldEditor(MyPreferences.KEY_AUTO_INSTALL_LIBRARIES, - Messages.ui_auto_install_libraries, BooleanFieldEditor.DEFAULT, parent); - addField(this.automaticallyInstallLibrariesOptionEditor); + Composite parent = new Composite(rootParent, SWT.NONE); + GridData gd1=new GridData(SWT.BEGINNING,SWT.CENTER,false,false); + //gd1.horizontalSpan=2; + parent.setLayoutData(gd1); + parent.setLayout(new GridLayout(1,false)); - this.pragmaOnceHeaderOptionEditor = new BooleanFieldEditor(KEY_PRAGMA_ONCE_HEADERS, Messages.ui_pragma_once_headers, - BooleanFieldEditor.DEFAULT, parent); - addField(this.pragmaOnceHeaderOptionEditor); - this.cleanSerialMonitorAfterUploadEditor = new BooleanFieldEditor(MyPreferences.KEY_CLEAN_MONITOR_AFTER_UPLOAD, - Messages.ui_clean_serial_monitor_after_upload, BooleanFieldEditor.DEFAULT, parent); - addField(this.cleanSerialMonitorAfterUploadEditor); + Group UIboxparent= new Group(parent, SWT.BORDER_SOLID ); + UIboxparent.setText(Messages.PreferencePage_UI_Behaviour_Group_Title); + UIboxparent.setFont(headerFont); + UIboxparent.setLayout(new GridLayout(2,true)); + GridData gd11=new GridData(SWT.FILL,SWT.TOP,true,false); + UIboxparent.setLayoutData(gd11); - this.switchToSerialMonitorAfterUploadEditor = new BooleanFieldEditor(MyPreferences.SWITCH_TO_MONITOR_AFTER_UPLOAD, - Messages.ui_switch_to_serial_monitor_after_upload, BooleanFieldEditor.DEFAULT, parent); - addField(this.switchToSerialMonitorAfterUploadEditor); + Composite UIbox = new Composite(UIboxparent, SWT.NONE); + GridData gd12=new GridData(SWT.FILL,SWT.TOP,true,false); + gd12.horizontalSpan=2; + UIbox.setLayoutData(gd12); + UIbox.setLayout(new GridLayout(2,false)); - this.enableParallelBuildForNewProjects = new BooleanFieldEditor(MyPreferences.KEY_ENABLE_PARALLEL_BUILD_FOR_NEW_PROJECTS, - Messages.ui_enable_parallel_build_for_new_projects, BooleanFieldEditor.DEFAULT, parent); - addField(this.enableParallelBuildForNewProjects); + String[][] YesNoAskOptions = new String[][] { { Messages.ui_ask_every_upload, "ASK" }, //$NON-NLS-1$ + { Messages.yes, TRUE }, { Messages.no, FALSE } }; + buildBeforeUploadOptionEditor = new ComboFieldEditor(MyPreferences.KEY_BUILD_BEFORE_UPLOAD_OPTION, + Messages.ui_build_before_upload, YesNoAskOptions, UIbox); + addField(buildBeforeUploadOptionEditor); + + Composite UIbox2 = new Composite(UIboxparent, SWT.NONE); + GridData gd13 = new GridData(SWT.FILL, SWT.TOP, true, false); + gd13.horizontalSpan = 2; + UIbox2.setLayoutData(gd13); + UIbox2.setLayout(new GridLayout(2, false)); + Dialog.applyDialogFont(UIbox2); + + openSerialMonitorOpensSerialsOptionEditor = new BooleanFieldEditor(MyPreferences.KEY_OPEN_SERIAL_WITH_MONITOR, + Messages.ui_open_serial_with_monitor, BooleanFieldEditor.DEFAULT, UIbox2); + addField(openSerialMonitorOpensSerialsOptionEditor); + + automaticallyImportLibrariesOptionEditor = new BooleanFieldEditor(KEY_AUTO_IMPORT_LIBRARIES, + Messages.ui_auto_import_libraries, BooleanFieldEditor.DEFAULT, UIbox2); + addField(automaticallyImportLibrariesOptionEditor); + + cleanSerialMonitorAfterUploadEditor = new BooleanFieldEditor(MyPreferences.KEY_CLEAN_MONITOR_AFTER_UPLOAD, + Messages.ui_clean_serial_monitor_after_upload, BooleanFieldEditor.DEFAULT, UIbox2); + addField(cleanSerialMonitorAfterUploadEditor); + + switchToSerialMonitorAfterUploadEditor = new BooleanFieldEditor(MyPreferences.SWITCH_TO_MONITOR_AFTER_UPLOAD, + Messages.ui_switch_to_serial_monitor_after_upload, BooleanFieldEditor.DEFAULT, UIbox2); + addField(switchToSerialMonitorAfterUploadEditor); + + + Group internalBehaviourGroup= new Group(parent, SWT.BORDER_SOLID); + internalBehaviourGroup.setText(Messages.PreferencePage_Internal_Behaviour_Group_Title); + GridData gd2=new GridData(SWT.FILL,SWT.TOP,true,false); + //gd2.horizontalSpan=2; + internalBehaviourGroup.setLayout(new GridLayout(2,true)); + internalBehaviourGroup.setLayoutData(gd2); + internalBehaviourGroup.setFont(headerFont); + + Composite internalBehaviourbox = new Composite(internalBehaviourGroup, SWT.NONE); + GridData gd14 = new GridData(SWT.FILL, SWT.TOP, true, false); + gd14.horizontalSpan = 2; + internalBehaviourbox.setLayoutData(gd14); + internalBehaviourbox.setLayout(new GridLayout(2, false)); + Dialog.applyDialogFont(internalBehaviourbox); + + useArduinoToolchainSelectionEditor = new BooleanFieldEditor(KEY_TOOLCHAIN_SELECTION, + Messages.ui_use_arduino_toolchain_selection, BooleanFieldEditor.DEFAULT, internalBehaviourbox); + addField(useArduinoToolchainSelectionEditor); + + pragmaOnceHeaderOptionEditor = new BooleanFieldEditor(KEY_PRAGMA_ONCE_HEADERS, Messages.ui_pragma_once_headers, + BooleanFieldEditor.DEFAULT, internalBehaviourbox); + addField(pragmaOnceHeaderOptionEditor); + + enableParallelBuildForNewProjects = new BooleanFieldEditor(MyPreferences.KEY_ENABLE_PARALLEL_BUILD_FOR_NEW_PROJECTS, + Messages.ui_enable_parallel_build_for_new_projects, BooleanFieldEditor.DEFAULT, internalBehaviourbox); + addField(enableParallelBuildForNewProjects); + + Group netWorkGroup= new Group(parent, SWT.BORDER_SOLID); + netWorkGroup.setText(Messages.PreferencePage_Network_Group_Title); + GridData gd3=new GridData(SWT.FILL,SWT.TOP,true,false); + //gd3.horizontalSpan=2; + netWorkGroup.setLayoutData(gd3); + netWorkGroup.setFont(headerFont); + netWorkGroup.setLayout(new GridLayout(2,true)); + + Composite netWorkbox = new Composite(netWorkGroup, SWT.NONE); + GridData gd15 = new GridData(SWT.FILL, SWT.TOP, true, false); + gd15.horizontalSpan = 2; + netWorkbox.setLayoutData(gd15); + netWorkbox.setLayout(new GridLayout(4, false)); + Dialog.applyDialogFont(netWorkbox); + + //Currently sloeber does not autoinstall librtaries + myInstallLibCheckBox = new Button(netWorkbox, SWT.CHECK | SWT.LEFT); + Label inStallLabel = new Label(netWorkbox, SWT.BEGINNING); + inStallLabel.setText(Messages.ui_auto_install_libraries); + GridData gd16 = new GridData(SWT.BEGINNING, SWT.TOP, true, false); + gd16.horizontalSpan=3; + inStallLabel.setLayoutData(gd16); + + + myBonjourCheckBox = new Button(netWorkbox, SWT.CHECK | SWT.LEFT ); + Label bonjourLabel = new Label(netWorkbox, SWT.BEGINNING); + bonjourLabel.setText(Messages.ui_enable_bonjour); + GridData gd18 = new GridData(SWT.BEGINNING, SWT.TOP, true, false); + gd18.horizontalSpan=3; + bonjourLabel.setLayoutData(gd18); + + String[] jsonUpdateDelays2 = new String[] { Messages.PreferencePage_days, Messages.PreferencePage_weeks, Messages.PreferencePage_months, Messages.PreferencePage_years, Messages.PreferencePage_centuries }; + Label nuberLabel = new Label(netWorkbox, SWT.BEGINNING); + nuberLabel.setText(Messages.PreferencePage_update_interval); + myDelayNumberSpinner = new Spinner(netWorkbox, SWT.BEGINNING); + myDelayNumberSpinner.setDigits(0); + myDelayUnitCombo = new Combo(netWorkbox, SWT.BEGINNING); + myDelayUnitCombo.setItems(jsonUpdateDelays2); + GridData gd17 = new GridData(SWT.BEGINNING, SWT.TOP, false, false); + gd17.horizontalSpan=2; + nuberLabel.setLayoutData(gd17); + + + Label lastJsonUpdateTimeLabel = new Label(netWorkbox, SWT.BEGINNING); + lastJsonUpdateTimeLabel.setText(Messages.PreferencePage_json_Download_date); + GridData gd19 = new GridData(SWT.BEGINNING, SWT.TOP, false, false); + gd19.horizontalSpan=2; + lastJsonUpdateTimeLabel.setLayoutData(gd19); + Label lastJsonUpdateTime = new Label(netWorkbox, SWT.BEGINNING); + lastJsonUpdateTime.setText(getLatestJsonUpdateTime()); + Button updateJsonFileNowButton =new Button(netWorkbox, SWT.PUSH | SWT.LEFT ); + updateJsonFileNowButton.setText(Messages.PreferencePage_Update_json_files_now); + updateJsonFileNowButton.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + BoardsManager.update(true); + lastJsonUpdateTime.setText(getLatestJsonUpdateTime()); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + // TODO Auto-generated method stub + + } + }); + + + myBonjourCheckBox.setSelection(ConfigurationPreferences.useBonjour()); + myInstallLibCheckBox.setSelection(ConfigurationPreferences.getInstallLibraries()); + setJsonDurationComposites(ConfigurationPreferences.getJsonUpdateDelay()); - this.enableBonjour = new BooleanFieldEditor(KEY_USE_BONJOUR, - Messages.ui_enable_bonjour, BooleanFieldEditor.DEFAULT, parent); - addField(this.enableBonjour); } + private static String getLatestJsonUpdateTime() { + DateTimeFormatter formatter = + DateTimeFormatter.ofPattern( "uuuu-MM-dd HH-mm" ) //$NON-NLS-1$ + .withZone(ZoneId.systemDefault()); + Instant instant =ConfigurationPreferences.getLatestJsonUpdateTime(); + return formatter.format(instant); + } /** * testStatus test whether the provided information is OK. Here the code * checks whether there is a hardware\arduino\board.txt file under the @@ -269,13 +411,25 @@ protected void performApply() { super.performApply(); } - private static void createLine(Composite parent, int ncol) { - Label line = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.BOLD); - GridData gridData = new GridData(GridData.FILL_HORIZONTAL); - gridData.horizontalSpan = ncol; - line.setLayoutData(gridData); + @Override + protected void performDefaults() { + super.performDefaults(); + myBonjourCheckBox.setSelection( Defaults.useBonjour); + myInstallLibCheckBox.setSelection( Defaults.INSTALL_LIBRARIES); + setJsonDurationComposites(Defaults.getJsonUpdateDuration()); + } + private void setJsonDurationComposites(Duration dur) { + long durationDays = dur.toDays(); + for (int durationUnit = durationUnits.length-1; durationUnit >= 0; durationUnit--) { + if ((durationDays % durationUnits[durationUnit]) == 0) { + myDelayNumberSpinner.setSelection((int) durationDays / durationUnits[durationUnit]); + myDelayUnitCombo.select(durationUnit); + break; + } + } + } } diff --git a/io.sloeber.ui/src/io/sloeber/ui/preferences/TargetSerialDisconnectPage.java b/io.sloeber.ui/src/io/sloeber/ui/preferences/TargetSerialDisconnectPage.java index 1ea585176..f055af24f 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/preferences/TargetSerialDisconnectPage.java +++ b/io.sloeber.ui/src/io/sloeber/ui/preferences/TargetSerialDisconnectPage.java @@ -12,7 +12,8 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; -import io.sloeber.core.api.Preferences; +import io.sloeber.core.api.ConfigurationPreferences; +import io.sloeber.core.api.Defaults; import io.sloeber.ui.Messages; public class TargetSerialDisconnectPage extends PreferencePage implements IWorkbenchPreferencePage { @@ -21,21 +22,21 @@ public class TargetSerialDisconnectPage extends PreferencePage implements IWorkb @Override public boolean performOk() { - Preferences.setDisconnectSerialTargets(targetsText.getText()); + ConfigurationPreferences.setDisconnectSerialTargets(targetsText.getText()); return true; } @Override protected void performDefaults() { super.performDefaults(); - this.targetsText.setText(Preferences.getDefaultDisconnectSerialTargets()); + this.targetsText.setText(Defaults.getDefaultDisconnectSerialTargets()); } @Override protected Control createContents(Composite parent) { Composite control = new Composite(parent, SWT.NONE); control.setLayout(new GridLayout()); - String selectedTargets = Preferences.getDisconnectSerialTargets(); + String selectedTargets = ConfigurationPreferences.getDisconnectSerialTargets(); // Composite control = new Composite(parent, SWT.NONE); Label title = new Label(control, SWT.UP); diff --git a/io.sloeber.ui/src/io/sloeber/ui/preferences/ThirdPartyHardwareSelectionPage.java b/io.sloeber.ui/src/io/sloeber/ui/preferences/ThirdPartyHardwareSelectionPage.java index 569a7116e..9c379542b 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/preferences/ThirdPartyHardwareSelectionPage.java +++ b/io.sloeber.ui/src/io/sloeber/ui/preferences/ThirdPartyHardwareSelectionPage.java @@ -3,18 +3,17 @@ import static io.sloeber.ui.Activator.*; -import org.eclipse.cdt.core.parser.util.StringUtil; +import java.util.Arrays; +import java.util.HashSet; + +import org.eclipse.cdt.ui.newui.MultiLineTextFieldEditor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.preferences.ConfigurationScope; -import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.FieldEditorPreferencePage; -import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.forms.events.HyperlinkAdapter; @@ -22,57 +21,51 @@ import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.preferences.ScopedPreferenceStore; -import io.sloeber.core.api.BoardsManager; -import io.sloeber.core.api.Preferences; +import io.sloeber.arduinoFramework.api.BoardsManager; +import io.sloeber.ui.JsonMultiLineTextFieldEditor; import io.sloeber.ui.Messages; import io.sloeber.ui.helpers.MyPreferences; public class ThirdPartyHardwareSelectionPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { - private static final String KEY_UPDATE_JASONS = "Update jsons files"; //$NON-NLS-1$ - private Text urlsText; - BooleanFieldEditor upDateJsons; + @Override + protected void initialize() { + super.initialize(); + urlsText.setText(BoardsManager.getJsonURLList()); + } + + private static final String KEY_JSONS = "Jsons files"; //$NON-NLS-1$ + private JsonMultiLineTextFieldEditor urlsText; public ThirdPartyHardwareSelectionPage() { - super(org.eclipse.jface.preference.FieldEditorPreferencePage.GRID); + super(org.eclipse.jface.preference.FieldEditorPreferencePage.FLAT); setDescription(Messages.json_maintain); setPreferenceStore(new ScopedPreferenceStore(ConfigurationScope.INSTANCE, MyPreferences.NODE_ARDUINO)); } @Override public boolean performOk() { - BoardsManager.setJsonURLs(this.urlsText.getText().split(System.lineSeparator())); - Preferences.setUpdateJsonFiles(this.upDateJsons.getBooleanValue()); + HashSet toSetList = new HashSet<>(Arrays.asList(urlsText.getStringValue().split(System.lineSeparator()))); + BoardsManager.setPackageURLs(toSetList); + BoardsManager.update(false); + return super.performOk(); } @Override protected void performDefaults() { super.performDefaults(); - this.urlsText.setText(BoardsManager.getDefaultJsonURLs()); + urlsText.setText(BoardsManager.getDefaultJsonURLs()); } @Override protected void createFieldEditors() { - String selectedJsons[] = BoardsManager.getJsonURLList(); final Composite parent = getFieldEditorParent(); - // Composite control = new Composite(parent, SWT.NONE); - Label title = new Label(parent, SWT.UP); - title.setFont(parent.getFont()); - - title.setText(Messages.ui_url_for_index_file); - title.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); - - this.urlsText = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER | SWT.WRAP); - GridData gd = new GridData(GridData.FILL_BOTH); - this.urlsText.setLayoutData(gd); - this.urlsText.setText(StringUtil.join(selectedJsons, System.lineSeparator())); - - this.upDateJsons = new BooleanFieldEditor(KEY_UPDATE_JASONS, Messages.json_update, BooleanFieldEditor.DEFAULT, - parent); - addField(this.upDateJsons); - IPreferenceStore prefstore = getPreferenceStore(); - prefstore.setValue(KEY_UPDATE_JASONS, Preferences.getUpdateJsonFiles()); - prefstore.setDefault(KEY_UPDATE_JASONS, true); + GridData gd = new GridData(GridData.FILL,GridData.BEGINNING,true,false); + parent.setLayoutData(gd); + + urlsText =new JsonMultiLineTextFieldEditor(KEY_JSONS,Messages.ui_url_for_index_file,MultiLineTextFieldEditor.UNLIMITED,MultiLineTextFieldEditor.VALIDATE_ON_KEY_STROKE,parent); + addField(urlsText); + final Hyperlink link = new Hyperlink(parent, SWT.NONE); link.setText(Messages.json_find); diff --git a/io.sloeber.ui/src/io/sloeber/ui/project/properties/BoardSelectionPage.java b/io.sloeber.ui/src/io/sloeber/ui/project/properties/BoardSelectionPage.java index 6eb5c70ad..e2e29ab17 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/project/properties/BoardSelectionPage.java +++ b/io.sloeber.ui/src/io/sloeber/ui/project/properties/BoardSelectionPage.java @@ -25,8 +25,8 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.BoardsManager; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardsManager; import io.sloeber.core.api.PasswordManager; import io.sloeber.core.api.SerialManager; import io.sloeber.ui.LabelCombo; @@ -289,7 +289,7 @@ protected void updateScreen(boolean updateData) { } myControlUploadPort.setText(myBoardDesc.getUploadPort()); - setTheLabelCombos(boardsFileChanged || boardIDChanged); + setTheLabelCombos(boardsFileChanged || boardIDChanged ||updateData); disableListeners = false; } diff --git a/io.sloeber.ui/src/io/sloeber/ui/wizard/ConvertToSloeber.java b/io.sloeber.ui/src/io/sloeber/ui/wizard/ConvertToSloeber.java index a825b4e3f..4dd585602 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/wizard/ConvertToSloeber.java +++ b/io.sloeber.ui/src/io/sloeber/ui/wizard/ConvertToSloeber.java @@ -1,6 +1,7 @@ package io.sloeber.ui.wizard; import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.INewWizard; @@ -23,7 +24,7 @@ public void init(IWorkbench workbench, IStructuredSelection selection) { @Override public boolean performFinish() { - SloeberProject.convertToArduinoProject(myProject, null); + SloeberProject.convertToArduinoProject(myProject, new NullProgressMonitor( )); return true; } diff --git a/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizard.java b/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizard.java index 0da63f986..a1e66d346 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizard.java +++ b/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizard.java @@ -21,7 +21,7 @@ import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; -import io.sloeber.core.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardDescription; import io.sloeber.core.api.CodeDescription; import io.sloeber.core.api.CompileDescription; import io.sloeber.core.api.SloeberProject; @@ -40,7 +40,7 @@ public class NewSketchWizard extends Wizard implements INewWizard, IExecutableEx Messages.ui_new_sketch_arduino_information); protected NewSketchWizardCodeSelectionPage mNewArduinoSketchWizardCodeSelectionPage = new NewSketchWizardCodeSelectionPage( Messages.ui_new_sketch_sketch_template_location); - private NewProjectSourceLocationPage mySourceLocationPage= new NewProjectSourceLocationPage("code location page"); + private NewProjectSourceLocationPage mySourceLocationPage= new NewProjectSourceLocationPage("code location page"); //$NON-NLS-1$ private IConfigurationElement mConfig; private IProject mProject; diff --git a/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizardBoardPage.java b/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizardBoardPage.java index 5cc371d62..f2d1569ae 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizardBoardPage.java +++ b/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizardBoardPage.java @@ -8,7 +8,7 @@ import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; -import io.sloeber.core.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardDescription; import io.sloeber.ui.project.properties.BoardSelectionPage; /** diff --git a/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizardCodeSelectionPage.java b/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizardCodeSelectionPage.java index 46388e446..f9bb89f7f 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizardCodeSelectionPage.java +++ b/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/NewSketchWizardCodeSelectionPage.java @@ -15,10 +15,10 @@ import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; -import io.sloeber.core.api.BoardDescription; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.IExample; import io.sloeber.core.api.CodeDescription; import io.sloeber.core.api.CodeDescription.CodeTypes; -import io.sloeber.core.api.IExample; import io.sloeber.ui.LabelCombo; import io.sloeber.ui.Messages; diff --git a/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/SampleSelector.java b/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/SampleSelector.java index b918b5285..07d89de78 100644 --- a/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/SampleSelector.java +++ b/io.sloeber.ui/src/io/sloeber/ui/wizard/newsketch/SampleSelector.java @@ -16,9 +16,9 @@ import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; -import io.sloeber.core.api.BoardDescription; -import io.sloeber.core.api.IExample; -import io.sloeber.core.api.LibraryManager; +import io.sloeber.arduinoFramework.api.BoardDescription; +import io.sloeber.arduinoFramework.api.IExample; +import io.sloeber.arduinoFramework.api.LibraryManager; import io.sloeber.ui.Messages; public class SampleSelector { diff --git a/io.sloeber.updatesite/category.xml b/io.sloeber.updatesite/category.xml index 1c9acea90..84bdb9f3d 100644 --- a/io.sloeber.updatesite/category.xml +++ b/io.sloeber.updatesite/category.xml @@ -6,6 +6,12 @@ + + + + + + Sloeber, Arduino development in the Eclipse IDE. @@ -16,7 +22,8 @@ Only select this if you are upgrading the Sloeber IDE - - - + + + +