How to catch file opening eclipse plugin - java

I'm new at plugin development. I have my own editor for files *.example.
I extend org.eclipse.ui.editors.text.TextEditor to edit it.
I want to catch the moment when this file is opened and post it to log (something like "file new.example is opened). But I really don't understand how to do it.

One way is to override the init method of the editor and use the editor input parameter:
#Override
public void init(final IEditorSite site, final IEditorInput input) throws PartInitException {
super.init(site, input);
if (input instanceof IFileEditorInput) {
IFile file = ((IFileEditorInput)input).getFile();
// TODO log the IFile
}
}
Note: The editor input is not always IFileEditorInput, see this answer for more details.

Related

NetBeans platform - open file from output console

I would like to open file specified by its path in NetBeans editor (IOProvider.getDefault().getIO(...);).
I would like the same functionality as is when some Java/C/C++ or any other programming language prints an Exception. As far as I went for now:
Write the output in console (see the example at the end)
By using OutputListener resolve what should be printed as hypertext
OutputListener.outputLineAction that defines what to do when clicked on hypertext IOColorPrint.print(InputOutput io, CharSequence text, OutputListener listener, boolean important, Color color)
Open the file on the system when clicking on
An example of error message I need to resolve:
The export was successful. The exported file can be found in: C:\Users\MY_USER\Desktop\myFile.xml
The problem that I have is that I have to print all the output in one line and the OutputEvent gives me all the line. Is there any way to get only the Highlited text (The path) ?
This call open new console output tab:
IOProvider.getDefault().getIO(...)
You should take inputStream and use class while(x=is.read()!=n ....
IOProvider.getDefault().getIO(...).getInputStream
Let me know, if this was usefull.
Here the Listener :
public class HyperlinkToFileOutputListener implements OutputListener {
private final File file;
public HyperlinkToFileOutputListener(File file) {
this.file = file;
}
#Override
public void outputLineSelected(OutputEvent oe) {
}
#Override
public void outputLineAction(OutputEvent oe) {
try {
if (file.exists()) {
Desktop.getDesktop().open(file);
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
#Override
public void outputLineCleared(OutputEvent oe) {
}
}
here the call
IOColorPrint.print(io, file.getName(), new HyperlinkToFileOutputListener(file), true, Color.BLUE);
best regards

Showing a list of only filenames while having full file paths connected

I would like to be able to display a list of files showing only the file name not the whole file path.
Currently I have a list of files. When I click one of these files the listener passes this to a method out of scope which loads the file.
This means if I was to just pass it a list of just file names it would no longer work as my listener requires a full file path. I do not have any ideas as to how I would go about both storing a list of filenames whilst simultaneously linking them to the full file path.
Happy to answer any questions you may have. Many thanks,
Note: the small for loop shows how I could potentially extract the filename from the file path, but I am not currently doing anything with it at this time. It's just an example to show you how far I have gotten.
public void GetFilesFromFolder(String dirName) throws IOException {
File dir = new File(dirName);
File[] files = dir.listFiles((File dir1, String filename) -> filename.endsWith(".mp3"));
String[] fileName = new String[files.length];
int x = 0;
for (File file : files) {
String fileTemp = file.toString();
fileTemp = fileTemp.substring(fileTemp.lastIndexOf("\\" + 1));
System.out.println(fileTemp);
fileName[x] = fileTemp;
System.out.println(fileName[x]);
x++;
}
observableList.clear();
observableList.addAll(files);
}
public void SetFileListView() throws IOException {
listView.setItems(null);
}
public VBox listStack() throws IOException {
vbox = new VBox();
vbox.getChildren().add(listView);
listView.setItems(observableList);
listView.setMinHeight(500);
MusicDataModel mdm = MainView.getMainView().musicDataModel;
MusicDataViewController mdv = MainView.getMainView().musicDataViewController;
listView.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends File> observable, File oldValue, File newValue) -> {
try {
mdm.load(newValue.toString());
mdv.SetValues();
} catch (UnsupportedTagException | InvalidDataException | IOException | NotSupportedException ex) {
Logger.getLogger(FileListView.class.getName()).log(Level.SEVERE, null, ex);
}
});
return vbox;
}
Populate the list view with Files, as you currently do, and use a cell factory on the list view to change the way the file is displayed:
listView.setCellFactory(lv -> new ListCell<File>() {
#Override
protected void updateItem(File file, boolean empty) {
super.updateItem(file, empty);
setText(file == null ? null : file.getName());
}
});
This will ensure each cell in the list view displays only the file name (the last component of the file's full path), though it still retains the File instance as its data (so you can still get the selected File, etc).

File not found exception? (Voice recog)

Sorry for the long question, I have been stuck on this for a month, and I want to provide as much detail as possible...its just a file not found exception in a simple library... :)
I am getting a file not found exception on my variances file:
I do, however, have the variances file:
I am trying to simply implement voice recognition in my background service, so that I can detect when the user says the word hello (using pocketsphinx).
The problem happens in this method: createSphinxDir();
Here is my service:
#Override
public void onCreate() {
super.onCreate();
setupRecog();
}
private void setupRecog() {
String sphinxDir = createSphinxDir();
Log.v(TAG, "ABOUT TO CREATE SETUP");
if (sphinxDir != null) {
try {
Log.v(TAG, "SETTING UP! :)");
mSpeechRecognizer = defaultSetup()
.setAcousticModel(new File(sphinxDir, "en-us-ptm"))
.setDictionary(new File(sphinxDir, "hello.dict"))
.setBoolean("-allphone_ci", true) //WHAT IS THIS
.getRecognizer();
mSpeechRecognizer.addListener(this);
Log.v(TAG, "ADDED LISTENER");
if ((new File(sphinxDir + File.separator + "command.gram")).isFile()) {
mSpeechRecognizer.addKeywordSearch("hello",
new File(sphinxDir + File.separator + "command.gram"));
Log.v(TAG, "ADDED KEYWORD SEARCH! :)");
}
// Or wherever appropriate
mSpeechRecognizer.startListening("wakeup"); //Is this correct?
Log.v(TAG, "STARTED LISTENING");
} catch (IOException e) {
Log.v("ERROR", TAG);
}
}
}
String createSphinxDir() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String sphinxDir = prefs.getString("sphinx", null);
if (sphinxDir == null) {
Assets assets;
Log.v(TAG, "Assets are not synced, should sync now:");
try {
Log.v(TAG, "In try block!");
assets = new Assets(this);
File sphinxDirFile = assets.syncAssets();
Log.v(TAG, "Syncing assets...should set up listener");
if (sphinxDirFile != null) {
sphinxDir = sphinxDirFile.getAbsolutePath();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("sphinx", sphinxDir);
editor.commit();
Log.v(TAG, "Set up listener");
}else{
Log.v(TAG, "sphinxDirFile is null!");
}
} catch (IOException e) { //THIS IS THE PLACE WHERE I AM GETTING THE ERROR!
e.printStackTrace();
Log.d(TAG, e.toString());
}
}
return sphinxDir;
}
I also have all the call back methods (onPartialResult, onResult, etc.) but they never get called.
Earlier I was getting an exception saying the variances .md5 file didn't exist, so I put a space in between the variances and the .md5, but now I am getting this error, and I don't know why...
Please let me know,
Ruchir
Earlier I was getting an exception saying the variances .md5 file didn't exist, so I put a space in between the variances and the .md5, but now I am getting this error, and I don't know why...
You should not do such things, it causes problems, instead you need to follow the documentation:
The standard way to ship resource files with your application in Android is to put them in assets/ directory of your project. But in order to make them available for pocketsphinx files should have physical path, as long as they are within .apk they don't have one. Assets class from pocketsphinx-android provides a method to automatically copy asset files to external storage of the target device. edu.cmu.pocketsphinx.Assets#syncAssets synchronizes resources reading items from assets.lst file located on the top assets/. Before copying it matches MD5 checksums of an asset and a file on external storage with the same name if such exists. It only does actualy copying if there is incomplete information (no file on external storage, no any of two .md5 files) or there is hash mismatch. PocketSphinxAndroidDemo contains ant script that generates assets.lst as well as .md5 files, look for assets.xml.
Please note that if ant build script doesn't run properly in your build process, assets might be out of sync. Make sure that script runs during the build.
To integrate assets sync in your application do the following
Include app/asset.xml build file from the demo application into your application. Edit build.gradle build file to run assets.xml:
ant.importBuild 'assets.xml'
preBuild.dependsOn(list, checksum)
clean.dependsOn(clean_assets)

How to access right-clicked file in Eclipse RCP using commands?

I implemented an entry in the context menu of my Eclipse RCP application. The function should export the right-clicked file in another format. I already implemented the transformation-function.
What I need, is the path and name of the right-clicked file. This is what I have:
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Shell shell = new Shell();
DirectoryDialog dialog = new DirectoryDialog(shell);
String saveToPath = dialog.open();
String filePath = // ... how to access the clicked file?
exportOtherFormat(filePath, saveToPath);
return null;
}
So basically I would like to know, how I can access the right-clicked file, specially the path and name.
Get the current selection in your handler and adapt it to an IFile with:
ISelection sel = HandlerUtil.getCurrentSelection(event);
if (sel instanceof IStructuredSelection)
{
Object selObj = ((IStructuredSelection)sel).getFirstObject();
IFile file = (IFile)Platform.getAdapterManager().getAdapter(selObj, IFile.class);
// TODO your code
}

Save on change of CommandStack

probably a really easy newbie question but I can't manage to get it for already a pair of days, so I'll aks it here. My scope: I have an RCP application with some Graphical Editors (extensions of EditorPart). In my editor I want to catch any changes and save them directly. For that I catch the moment in which my CommandStack gets changed and start a doSave method. The problem is that my save method calls a CommadStack change event and if i skip this call than my changes are saved but my editor has still got a dirty flag. My wished behaviour would be that the dirty flag is away(like a normal save behaviour).
Both my CommandStack change and my doSave method are below. Could you please help me?
#Override
public void commandStackChanged(EventObject event) {
firePropertyChange(IEditorPart.PROP_DIRTY);
doSave(null);
setDirty(false);
}
public void doSave(final IProgressMonitor progressMonitor) {
editorSaving = true;
SafeRunner.run(new SafeRunnable() {
public void run() throws Exception {
IFile targetFile = getFile();
List<GraphicalEditPart> editParts = DiagramUtil.getAllEditParts(NetEditor.this);
Rectangle offsetBounds = DiagramUtil.getBounds(editParts);
saveDiagramProperties();
List<INetTransition> transitionsToExpand = saveSubdiagramGroups();
FileUtil.saveDiagram(getNetDiagram(), targetFile,
NetEditor.this);
getCommandStack().markSaveLocation();
for (INetTransition trans : transitionsToExpand) {
trans.setExpanded(true);
}
}
});
setDirty(false);
editorSaving = false;
}
With getCommandStack().markSaveLocation() I call once more the commandStackChanged and get in a loop. How can I solve this problem? Without it my editor remains dirty after save.
Thanks and Greets,
Jeff
How about adding IPropertyListener to your Editor and listen for IEditorPart.PROP_DIRTY. For the listener implementation perform save if editor is dirty otherwise do nothing.

Categories

Resources