Open a prespective on eclipse startup - programmatically - java

I am developing a eclipse plugin. I need to open my prespective when we open the eclipse at first time. Any ways to achieve this? i guess some listener must be available but could not trace out.
We can open a prespective after eclipse start using PlatformUI.getWorkbench().showPrespective(<prespective id>)
Similarly is there a way to open the prespective on eclipse startup, so that our desired prespective gets opened when starting the eclipse.

You can use the org.eclipse.ui.startup extension point in your plugin. When the plugin is activated, check/set a preference to decide if you want to switch perspectives and then schedule a UIJob do do it.
Implement the extension point. Some class in the plugin needs implements org.eclipse.ui.IStartup. The activator class is fine in this case. Particularly, since you don't need anything in the earlyStartup method.
In the start method, make the decision to switch and schedule it:
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
final boolean switchPerpective = processPluginUpgrading();
if (switchPerpective) {
final IWorkbench workbench = PlatformUI.getWorkbench();
new UIJob("Switching perspectives"){
#Override
public IStatus runInUIThread(IProgressMonitor monitor) {
try {
workbench.showPerspective(perspectiveId, workbench.getActiveWorkbenchWindow());
} catch (WorkbenchException e) {
return new Status(IStatus.ERROR,PLUGIN_ID,"Error while switching perspectives", e);
}
return Status.OK_STATUS;
}}
.run(new NullProgressMonitor());
}
}
Use the preference store to keep data for your decision logic. In this implementation, the perspective is switched once per workspace whenever the plugin is upgraded. The data recorded in the preference store will allow a future version to have a difference policy. It uses the getPreferenceStore from AbstractUIPlugin so it is scoped per workspace. If you want to use other scopes, see the FAQ.
private Boolean processPluginUpgrading() {
final Version version = getDefault().getBundle().getVersion();
final IPreferenceStore preferenceStore = getDefault().getPreferenceStore();
final String preferenceName = "lastVersionActivated";
final String lastVersionActivated = preferenceStore.getString(preferenceName);
final boolean upgraded =
"".equals(lastVersionActivated)
|| (version.compareTo(new Version(lastVersionActivated)) > 0);
preferenceStore.setValue(preferenceName, version.toString());
return upgraded;
}

One thing I am doing to open my custom perspective in my plugin is to configure it in config.ini in eclipe's installation folder as below:
-perspective <my perspective id>
and it is working fine. I got this information from Lars Vogel's tutorial, which you can find here. Hope this helps.
Other way:
org.eclipse.ui.IPerspectiveRegistry.setDefaultPerspective(id) this sets default perspective to the given id. API Docs for the same.

Go to
D:\{MyTestSpace}\eclipse\features\myCustom.plugin.feature_3.1.0.201607220552
you can see feature.xml under plugin tag you get the id.
Use this id in config.ini which you can find under
D:\{MyTestSpace}\eclipse\configuration
As
-perspective <myCustum.plugin>

Related

Plugin development: listener to resource change in plugin

I am developing plugin of graph that use the objects in the current file that open. If I change the file that open, I want the graph will update.
Now, I am using setFocus() method in my class that extends ViewPart, and update the graph in every call to this function.
This is not what I want, I want to update the graph only when the resource change.
I found this link:
link to similar question
This is like my question, but there is no answer
I need to put the following code in the activator.java file of my plugin?:
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceChangeListener listener = new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
System.out.println("Something changed!");
}
};
workspace.addResourceChangeListener(listener);
//... some time later one ...
workspace.removeResourceChangeListener(listener);
If I need to add this code, where to put it? In which method to put it in the activator.java file?
If not, what I need to do?
Set up the listener in the view part createPartControl.
The activator is not a suitable place to set up listeners as it is only run when some other code in the plugin runs.

Eclipse plugin - accessing the editor

So, I’m currently developing a plugin for the eclipse IDE. In a nutshell, the plugin is a collaborative real time code editor where the editor is eclipse (which is something like Google documents but with the code and on eclipse). Meaning that when I install the plugin, I would be able to connect -using my Gmail account- eclipse to the partner’s eclipse. And when I start coding on my machine, my partner would be seeing what I write and vice versa.
The problem I’m currently facing is accessing eclipse’s editor. For example, I have to monitor all the changes in the active document so that every time a change happens, the other partner’s IDE would be notified with this change.
I found and read about the IDcoumentProvider, IDocument and IEditorInput classes and they’re somehow connected but I can’t understand this connection or how to use it. So if someone can explain this connection I would really appreciate it. Also if there is another way to achieve my goal?
You can access the IEditorPart via the IWorkbenchPage.
IEditorPart editor = ((IWorkbenchPage) PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()).getActiveEditor();
From there, you have access to various other classes, including the editor's IEditorInput, the File loaded by that editor, or the underlying GUI Control element. (Note that depending on the kind of editor (text files, diagram, etc.) you may have to cast to different classes.)
FileEditorInput input = (FileEditorInput) editor.getEditorInput();
StyledText editorControl = ((StyledText) editor.getAdapter(Control.class));
String path = input.getFile().getRawLocationURI().getRawPath();
Now, you can add a listener to the Control, e.g. a KeyAdapter for monitoring all key strokes occurring in the respective editor.
editorControl.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Editing in file " + path);
}
});
Or, if monitoring all key strokes is too much, you can register an IPropertyListener to the editor. This listener will e.g. be notified whenever the editor gets 'dirty' or when it is saved. The meaning of propId can be found in IWorkbenchPartConstants.
editor.addPropertyListener(new IPropertyListener() {
#Override
public void propertyChanged(Object source, int propId) {
if (propId == IWorkbenchPartConstants.PROP_DIRTY) {
System.out.println("'Dirty' Property Changed");
}
}
});

Automatic SVN sync Eclipse

I'm starting with SVN. Is there any way of configuring subclipse to automatically sync with the repo in order to know when a file was modified as soon as possible?
In case of Subversive (and I believe, the same option should be available in case of Subclipse as well) the Synchronize view allows automatic synchronization.
Initialize a synchronization using either Team/Synchronize from the context menu of some projects, or open the Team Synchronizing perspective, and select the set of synchronized projects using the Synchronize button of the Synchronize view (the button is the first button of the view toolbar).
Then the synchronization is performed, and the changes are displayed there. At this point, you could select the Schedule... option from the view menu (down-pointing triangle icon near the top right corner of the Synchronize view), and there you could set the synchronization.
AFAIK this synchronization does not update your workspace automatically (that is a sound idea, e.g. conflict resolution must happen manually), but at least you can look at the changes when needed.
You really do not want to do this. Synchronization with repository is a heavy operation with a lot of side effects. For example you can change file that is being changed in repository now. You do not want to get mismatch of your and other's changes while you are working. You wish to work and then update all files together and resolve conflicts (if any)
In the context menu (right-click on project) there should be an option "Team>Synchronize with repository".
I did find this tutorial useful.
As far as I know, subclipse provides no such option. You could write a cron job that uses the SVN command-line tools to perform an update at regular intervals, but I wouldn't recommend this. You can't automate synchronizing with SVN because updating may cause conflicts which cannot be automatically merged.
Although I agree that in some situations it might be a bad idea to have an automated commit feature, there might be some reasons why you could want to have this option anyway.
I created a small EASE-script that replaced my regular save key binding (ctrl+s). It first saves the file, tries to update the file (which also automatically merges the versions if possible or creates conflicts in which case the script terminates) and commits the file at last.
// ********************************************************************************
// name : SaveUpdateCommit
// keyboard : CTRL+S
// toolbar : PHP Explorer
// script-type : JavaScript
// description : Save a file, update from the repository and commit automatically
// ********************************************************************************
var UI = loadModule("/System/UI");
UI.executeUI(function(){
var editor = UI.getActiveEditor();
editor.doSave(null);
var site = editor.getSite();
var commandService = site.getService(org.eclipse.ui.commands.ICommandService);
var handlerService = site.getService(org.eclipse.ui.handlers.IHandlerService);
var subclipse = org.tigris.subversion.subclipse.core.SVNProviderPlugin.getPlugin();
try
{
var file = editor.getEditorInput().getFile();
}
catch(e)
{
return;
}
var filePath = file.getFullPath();
var project = file.getProject();
var projectPath = project.getWorkingLocation(subclipse.toString());
var workspace = project.getWorkspace();
var localFile = org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot.getSVNFileFor(file);
localFile.refreshStatus();
if(localFile.isDirty()){
var remoteFile = localFile.getBaseResource();
var empty = java.lang.reflect.Array.newInstance(org.eclipse.core.resources.IResource, 0);
var commitFiles = java.lang.reflect.Array.newInstance(org.eclipse.core.resources.IResource, 1);
commitFiles[0] = remoteFile.getResource();
var update = new org.tigris.subversion.subclipse.ui.operations.UpdateOperation(editor, remoteFile.getResource(), org.tigris.subversion.svnclientadapter.SVNRevision.HEAD);
update.run(null);
var commit = new org.tigris.subversion.subclipse.ui.operations.CommitOperation(editor, empty, empty, empty, commitFiles, "AutoCommit", false);
commit.run(null);
}
For this, you need to install Eclipse EASE (http://download.eclipse.org/ease/update/release) and to make this script available through the settings. Also, the script needs UI-access, again this needs to be configured in the settings.
So for your needs you may want to change that behavior to frequent updates. I never played around with timers in eclipse, but i guess it is possible though.

Eclipse plug-in: how to activate terminate button in Debug view

I am writing a plug-in to extend Eclipse for a custom programming language. I have all the launch configuration working and any program in the custom language launches correctly but I cannot seem to activate the Terminate button in the Debug view.
From what I have researched, I know that implementing the Debugger framework provides for the Terminate action but say, I do not want to implement the framework at this stage and would just like to have the option of terminating the program instead of having to cancel via the Task Manager. Is that possible to do? Or is the Debugger Framework the only way to do this?
Here is the code from the LaunchConfigurationDelegate class,
public void launch(ILaunchConfiguration configuration, String mode,
ILaunch launch, IProgressMonitor monitor) throws CoreException {
// getting the resource from the workspace
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
List<String> filenames = configuration.getAttribute(RELATIVE_PATH,
Collections.EMPTY_LIST);
List<String> rawPaths = configuration.getAttribute(RAW_PATH,
Collections.EMPTY_LIST);
List<String> projPaths = configuration.getAttribute(PROJECT_PATH,
Collections.EMPTY_LIST);
//CustomRunner is the interface to manage the custom language execution
CustomRunner runner = null;
try {
CustomOutputHandler outHand = new CustomOutputHandler();
runner = new CustomRunner(new File(projPaths.get(0)));
runner.setOutputHandler(outHand);
for (int i = 0; i < filenames.size(); i++) {
IPath temp = new Path(filenames.get(i));
IResource CustomFile = root.findMember(temp);
if (CustomFile == null) {
String msg = "The file "
+ "<"
+ temp.toString()
+ ">"
+ " could not be found in the workspace.\nIt may have been deleted or renamed.";
throw new FileNotFoundException(msg);
}
CustomFile.deleteMarkers(IMarker.PROBLEM, false,
IResource.DEPTH_INFINITE);
CustomErrorHandler errHand = new CustomErrorHandler(CustomFile);
runner.setErrorHandler(errHand);
//Runs the custom language file
runner.run(rawPaths.get(i));
}
After that there is just a bunch of catch blocks.
I need to be able to now terminate this launch via the Debug view and in the case of Run mode via the Run menu's terminate command.
I do not have any DebugTarget right now at this stage. And my question is: Is there another way to terminate this launch without extending the Debug Framework?
I did try launch.Terminate() in this launch method but that did not work.
Unless you extend the Platform-debug support you cannot hook into the Terminate button in the Debug view - at least there isn't an API for that. You can hack into the internals of the debug framework to add support without extending, but extending might be lot easier than that and will work in the future versions of Eclipse

How to make Android app automatically configure w/ debug vs. release values?

I'm working on an Android app, specifically one that uses the Facebook Android SDK. In development mode, I'm working with a test Facebook app that goes by one ID. However, in release mode, the app will be working with second Facebook app with a different ID.
I'm wondering how most Android (or Java might be a suitable enough realm of knowledge) developers here go about having their app automatically build with debug vs. release values. An ideal solution does not involve a manual switch (e.g.: switching public static final DEBUG = false; to true) before building.
It's been a while since you asked but I thought I'd share how I'm doing it.
Like Sebastian hinted, an Ant script can handle that change for you and generate the static final constants that you're looking for. You can configure IntelliJ or Eclipse to make it almost seamless.
I tried to detail the different steps I took over here, let me know if it helps. I know I never have to make any manual changes before releasing, and it's a nice relief!
In eclipse ADT 17.0 and above there is a new feature for this. Check the BuildConfig.DEBUG that is automatically built with your code.
For more information see http://developer.android.com/sdk/eclipse-adt.html
I can't recommend the IMEI method... the main problem with it is that not all Android devices will have IMEIs. A better way is to examine the signature used to sign the .apk.
// See if we're a debug or a release build
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
if (packageInfo.signatures.length>0) {
String signature = new String(packageInfo.signatures[0].toByteArray());
isReleaseBuild = !signature.contains("Android Debug");
}
} catch (NameNotFoundException e1) {
e1.printStackTrace();
}
I use a slightly more mundane method (in case you're still interested in solutions).
At application launch my application checks for the existence of a text file stored in /sdcard/. Each application I have looks for a specific file like "applicationdebug.txt". If the file exists, then the application goes into debug mode and starts being verbose with log statements and using my debug Facebook key, etc.
Then I simply remove (or rename) the file to on the device to see how the application performs in release mode.
Usually you will use 1 or 2 devices for debugging only. So you can set the DEBUG switch based on the Devices? So you can simply use the IMEI.
add a new Application class to your project and have it initialize the field (suspect to put it in a Const class).
In your Applications onCreate method, call Const.setupDebug(getApplicationContext());
Implement the setupDebug like this
public class Const {
private static boolean debug = false;
public static boolean isDebug() {
return debug;
}
private static void setDebug(boolean debug) {
Const.debug = debug;
}
private static String [] DEBUG_DEVICES = new String[] {
"000000000000000", "gfjdhsgfhjsdg" // add ur devices
};
public static void setupDebug(Context context) {
Arrays.sort(DEBUG_DEVICES);
TelephonyManager mTelephonyMgr = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
String imei = mTelephonyMgr.getDeviceId();
if (imei == null) imei = "000000000000000";
if(Arrays.binarySearch(DEBUG_DEVICES, imei) > -1) {
setDebug(true);
}
}
}
Switch from constant field to constant Method.
Const.isDebug()
With Eclipse I create 3 projects in the workspace :
ApplicationProject
It is a library project
Contain all source code
In values/refs.xml I add
<bool name="debug_mode">true</bool>
ApplicationProjectDEBUG
Use ApplicationProject
Overide AndroidManifest and other xml file with
developement specific config
In values/refs.xml I add
<bool name="debug_mode">true</bool>
ApplicationProjectPROD
Use ApplicationProject
Overide AndroidManifest and other xml file with
production specific config
In values/refs.xml I add
<bool name="debug_mode">false</bool>
I signe APK from this project to put on the store

Categories

Resources