Skip to main content

Notice: This Wiki is now read only and edits are no longer possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "CDT/Developer/Code Snippets"

< CDT
(Launch a dialogue from a non-ui thread and get a return value)
 
(10 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
+
{{warning|Note: The contents of this page has been migrated to GitHub. Please see the [https://github.com/eclipse-cdt/cdt/tree/main/FAQ#code-snippets-for-cdt-developers-and-extenders Code Snippets section in the FAQ] for current information}}
  
 
== General ==
 
== General ==
Line 6: Line 6:
  
 
Please feel free to fix bugs in code below or suggest improvements on talk page.
 
Please feel free to fix bugs in code below or suggest improvements on talk page.
 +
 +
== Contributing to Source pop-up menu ==
 +
 +
Please see extended write up on [[CDT/Developer/FAQ/popupMenu]]
  
 
== Template Category ==  
 
== Template Category ==  
Line 31: Line 35:
 
== Build Related Snippets ==
 
== Build Related Snippets ==
  
===  Programmatically set an option in the project settings ===
+
===  Programmatically set an option in the project settings UNDER CONSTRUCTION ===
 
Before we get into the code, you have to understand a couple of concepts:   
 
Before we get into the code, you have to understand a couple of concepts:   
  
 
C and C++ build settings are stored in the .cproject file in the root folder of your project. It's an xml file with your settings.  
 
C and C++ build settings are stored in the .cproject file in the root folder of your project. It's an xml file with your settings.  
  
* '''ITool''' -- an  ITool is a sort of utility. Here are a few examples of tools:
+
* '''ITool''' -- an  ITool is a sort of utility.  
GCC Archiver, GCC C++ Compiler, GCC C Compiler, GCC C Linker, GCC C++ Linker, GCC Assembler
+
The parent tool is one of these guys:
 +
Archiver, GCC C++ Compiler, GCC C Compiler, GCC C Linker, GCC C++ Linker, GCC Assembler
  
 
* ITool ''extends'' IHoldsOptions -- i.e, methods that ask for an IHoldsOptions will happily accept an ITool.
 
* ITool ''extends'' IHoldsOptions -- i.e, methods that ask for an IHoldsOptions will happily accept an ITool.
Line 49: Line 54:
  
 
<source lang="java">
 
<source lang="java">
        //Code to mimic gui 'ok' button actions from:
+
    public static boolean setOption_inCDT(IProject project, String optionIDString, boolean value, String parentToolName) {
  
         //------ Get store that holds the tools settings.
+
         // ------ Get configuration
         ToolSettingsPrefStore toolsPrefStore = ToolSettingsPrefStore.getDefault();
+
         IConfiguration ActiveConf = helper_getActiveConfiguration(project);
  
         //------  Get gprof Option.
+
         // Get the ITool the option.
        //Similar to: org.eclipse.cdt.managedbuilder.ui.properties.BuildOptionSettingsUI.propertyChange(PropertyChangeEvent)
+
         ITool gccCompileriTool = helper_getGccCompilerTool(parentToolName, ActiveConf);
        Object[] ImmutableOption = toolsPrefStore.getOption("gnu.cpp.compiler.option.debugging.gprof"); //$NON-NLS-1$
+
         IOption changedOption = (IOption)ImmutableOption[1];
+
  
         //------ Get configuration
+
         //------- Get Template Opiton.
         IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project);
+
         //Get Option ~Immutable. This is like a 'templete' that we will base the actual option on.
         IConfiguration ActiveConf = buildInfo.getDefaultConfiguration(); //TMP comment: Improved way of getting conf. works
+
         IOption optionTemplate = gccCompileriTool.getOptionById(optionIDString);
  
         //Get the ITool of the super class of gprof (which is GCC C++ compiler).
+
 
         ITool[] tools = ActiveConf.getTools();
+
         //Check that we got a good option.
        ITool gccCompileriTool = null;
+
         if (optionTemplate == null) {
        for (ITool iTool : tools) {
+
             MessageDialogSyncedRunnable.openErrorSyncedRunnable("Error", "Could not aquire Option template VREF__0000040"); //$NON-NLS-1$ //$NON-NLS-2$
             if (iTool.getName().equals("GCC C++ Compiler")) {
+
            return false;
                gccCompileriTool = iTool;
+
                break;
+
            }
+
 
         }
 
         }
  
         //Now we acquire an option that can be 'set' to something.
+
        //------- Get Actual Option .
         //In contrast to the immutable option, if the user never checked/unchecked the option by hand,
+
         // Now we acquire an option that can be 'set' to something.
         //then the first time 'set' of this option will work correctly. Whereas
+
         // In contrast to the immutable option above, if the user never checked/unchecked the option by hand,
         //the immutable option would only work if the user checked/unchecked the option by hand before.
+
         // then the first time 'set' of this option will work correctly. Whereas
 +
         // the immutable option would only work if the user checked/unchecked the option by hand before.
 
         IOption MutableOptionToSet = null;
 
         IOption MutableOptionToSet = null;
 
         try {
 
         try {
             MutableOptionToSet = gccCompileriTool.getOptionToSet(changedOption, false);
+
             MutableOptionToSet = gccCompileriTool.getOptionToSet(optionTemplate, false);
             MutableOptionToSet.setValue(true);
+
             MutableOptionToSet.setValue(value);
 
         } catch (BuildException e) {
 
         } catch (BuildException e) {
             // TODO Auto-generated catch block
+
             //This is reached if the template that was provided was bad.
 +
            MessageDialogSyncedRunnable.openErrorSyncedRunnable("Error", "Failed to get option for writing VREF__0000034"); //$NON-NLS-1$ //$NON-NLS-2$
 
             e.printStackTrace();
 
             e.printStackTrace();
 
         }
 
         }
  
         //-- get resource info.
+
         // -- get resource info. (where things are saved to).
 
         IResourceInfo resourceInfos[] = ActiveConf.getResourceInfos();
 
         IResourceInfo resourceInfos[] = ActiveConf.getResourceInfos();
 
         IResourceInfo resourceInfo = resourceInfos[0];
 
         IResourceInfo resourceInfo = resourceInfos[0];
  
         //------ Mark the option as enabled in the build manager.
+
         // ------ Mark the option as enabled in the build manager.
         IOption setOption = ManagedBuildManager.setOption(resourceInfo , gccCompileriTool, MutableOptionToSet, true);
+
         ManagedBuildManager.setOption(resourceInfo, gccCompileriTool, MutableOptionToSet,
 +
                true);
  
         //------ Save to disk.
+
         // ------ Save this business to disk.
 
         ManagedBuildManager.saveBuildInfo(project, true);
 
         ManagedBuildManager.saveBuildInfo(project, true);
 +
        return true;
 +
    }
 
</source>
 
</source>
 +
 +
Originally from:
 +
<source lang="html4strict">org.eclipse.linuxtools.profiling.ui.CProjectBuildHelpers.setOption_inCDT(IProject, String, boolean, String) </source>
 +
 +
=== Programmatically add/remove a language settings provider ===
 +
 +
The code below assumes you have access to your '''IProject''' instance. If not please see: [http://cdt-devel-faq.wikidot.com/#toc4 getting IProject]
 +
 +
The CDT's API does not make it easy to find how to do this, because '''ICConfigurationDescription''' doesn't extend '''ILanguageSettingsProvidersKeeper''', but standard implementations (i.e. '''CConfigurationDescription''') do. Note that this setting is stored in a project's '''.settings/language.settings.xml''' file, not in '''.cproject'''.
 +
 +
<source lang="java">
 +
/* Inspired by org.eclipse.cdt.core.language.settings.providers.LanguageSettingsProviderReferencedProjectsTests.testReferencedProjectProvider() */
 +
private void fiddleProjectLanguageSettingsProvider(IProject project) throws CoreException {
 +
        final CoreModel cmodel = CoreModel.getDefault();
 +
 +
final ICProjectDescription projDesc = cmodel.getProjectDescription(project);
 +
final ICConfigurationDescription[] projConfigs = projDesc.getConfigurations();
 +
final ICConfigurationDescription projConfig = projConfigs[0];
 +
 +
        /* Get language settings provider */
 +
final ILanguageSettingsProvidersKeeper lspKeeper = (ILanguageSettingsProvidersKeeper) projConfig;
 +
final List<ILanguageSettingsProvider> lspProviders = lspKeeper.getLanguageSettingProviders();
 +
final List<ILanguageSettingsProvider> fiddled = new ArrayList<>(lspProviders);
 +
     
 +
        /* Prepare new language settings provider by modifying 'fiddled' */
 +
        your own business...;
 +
 +
        /* Set them back: */
 +
lspKeeper.setLanguageSettingProviders(fiddled);
 +
 +
        /* Don't forget to save the changes! */
 +
final ICProjectDescriptionManager pdMgr = cmodel.getProjectDescriptionManager();
 +
pdMgr.setProjectDescription(project, projDesc);
 +
}
 +
</source>
 +
 +
[[Category:CDT]]

Latest revision as of 22:06, 3 October 2022

Warning2.png
Note: The contents of this page has been migrated to GitHub. Please see the Code Snippets section in the FAQ for current information


General

During CDT development, you may be interested in using code snippets to get certain things done. This page categorizes and provides these code snippets and explains their usage context.

Please feel free to fix bugs in code below or suggest improvements on talk page.

Contributing to Source pop-up menu

Please see extended write up on CDT/Developer/FAQ/popupMenu

Template Category

Copy & paste, explain what the category is about.

Template snippet

Explanation

source code:

  System.out.println("Hello world");

UI Snippets

Snippets related to making dialogues or explaining how to interact with it.

Launch a dialogue from a non-ui thread and get a return value

Please see [Launch a dialogue from a non-ui thread and get a return value]

Dialogue for caught exceptions

Often when catching exceptions, it's puzzling as to what one is suppose to do with them.

Please see [Message Dialogue for exceptions]

Build Related Snippets

Programmatically set an option in the project settings UNDER CONSTRUCTION

Before we get into the code, you have to understand a couple of concepts:

C and C++ build settings are stored in the .cproject file in the root folder of your project. It's an xml file with your settings.

  • ITool -- an ITool is a sort of utility.

The parent tool is one of these guys:

Archiver, GCC C++ Compiler, GCC C Compiler, GCC C Linker, GCC C++ Linker, GCC Assembler
  • ITool extends IHoldsOptions -- i.e, methods that ask for an IHoldsOptions will happily accept an ITool.
  • IOption -- an IOption holds some configuration. E.g a boolean whether a checkbox is checked/unchecked.

Now one must note, there are instances of an IOption that are generic 'abstract' instances of an option, and there are more concrete IOptions that can be used to save to disk.

One must also be careful as to how one aquires the IHoldsOptions. You should avoid getting IHoldsOption from the option directly, because if setting it for the first time, it might not be defined and your save-to-disk won't work. Instead get the IHoldsOption directly from your configuration and then get a mutable copy of IOptions from this IHolds options.

The code below assumes you have access to your IProject instance. If not please see: getting IProject

     public static boolean setOption_inCDT(IProject project, String optionIDString, boolean value, String parentToolName) {
 
        // ------ Get configuration
        IConfiguration ActiveConf = helper_getActiveConfiguration(project);
 
        // Get the ITool the option.
        ITool gccCompileriTool = helper_getGccCompilerTool(parentToolName, ActiveConf);
 
        //------- Get Template Opiton.
        //Get Option ~Immutable. This is like a 'templete' that we will base the actual option on.
        IOption optionTemplate = gccCompileriTool.getOptionById(optionIDString);
 
 
        //Check that we got a good option.
        if (optionTemplate == null) {
            MessageDialogSyncedRunnable.openErrorSyncedRunnable("Error", "Could not aquire Option template VREF__0000040"); //$NON-NLS-1$ //$NON-NLS-2$
            return false;
        }
 
        //------- Get Actual Option .
        // Now we acquire an option that can be 'set' to something.
        // In contrast to the immutable option above, if the user never checked/unchecked the option by hand,
        // then the first time 'set' of this option will work correctly. Whereas
        // the immutable option would only work if the user checked/unchecked the option by hand before.
        IOption MutableOptionToSet = null;
        try {
            MutableOptionToSet = gccCompileriTool.getOptionToSet(optionTemplate, false);
            MutableOptionToSet.setValue(value);
        } catch (BuildException e) {
            //This is reached if the template that was provided was bad.
            MessageDialogSyncedRunnable.openErrorSyncedRunnable("Error", "Failed to get option for writing VREF__0000034"); //$NON-NLS-1$ //$NON-NLS-2$
            e.printStackTrace();
        }
 
        // -- get resource info. (where things are saved to).
        IResourceInfo resourceInfos[] = ActiveConf.getResourceInfos();
        IResourceInfo resourceInfo = resourceInfos[0];
 
        // ------ Mark the option as enabled in the build manager.
        ManagedBuildManager.setOption(resourceInfo, gccCompileriTool, MutableOptionToSet,
                true);
 
        // ------ Save this business to disk.
        ManagedBuildManager.saveBuildInfo(project, true);
        return true;
    }

Originally from:

org.eclipse.linuxtools.profiling.ui.CProjectBuildHelpers.setOption_inCDT(IProject, String, boolean, String)

Programmatically add/remove a language settings provider

The code below assumes you have access to your IProject instance. If not please see: getting IProject

The CDT's API does not make it easy to find how to do this, because ICConfigurationDescription doesn't extend ILanguageSettingsProvidersKeeper, but standard implementations (i.e. CConfigurationDescription) do. Note that this setting is stored in a project's .settings/language.settings.xml file, not in .cproject.

/* Inspired by org.eclipse.cdt.core.language.settings.providers.LanguageSettingsProviderReferencedProjectsTests.testReferencedProjectProvider() */
private void fiddleProjectLanguageSettingsProvider(IProject project) throws CoreException {
        final CoreModel cmodel = CoreModel.getDefault();
 
	final ICProjectDescription projDesc = cmodel.getProjectDescription(project);
	final ICConfigurationDescription[] projConfigs = projDesc.getConfigurations();
	final ICConfigurationDescription projConfig = projConfigs[0];
 
        /* Get language settings provider */
	final ILanguageSettingsProvidersKeeper lspKeeper = (ILanguageSettingsProvidersKeeper) projConfig;
	final List<ILanguageSettingsProvider> lspProviders = lspKeeper.getLanguageSettingProviders();
	final List<ILanguageSettingsProvider> fiddled = new ArrayList<>(lspProviders);
 
        /* Prepare new language settings provider by modifying 'fiddled' */
        your own business...;
 
        /* Set them back: */
	lspKeeper.setLanguageSettingProviders(fiddled);
 
        /* Don't forget to save the changes! */
	final ICProjectDescriptionManager pdMgr = cmodel.getProjectDescriptionManager();
	pdMgr.setProjectDescription(project, projDesc);
}

Back to the top