How to execute "collapse-all-folds" in the MATLAB editor programatically? - java

I've been struggling with the problem in the subject for a bit longer than I'd like to admit.
I'm attempting to programatically execute the same Action that occurs when the user either clicks on the View > Collapse All button or right-clicks within the editor window and then Code Folding > Fold All.
What I tried\found so far:
The String that corresponds to the Action may be found in the enum com.mathworks.mde.editor.ActionID and is: 'collapse-all-folds'.
When the Action activates, the following method seems to be executed: org.netbeans.api.editor.fold.FoldUtilities.collapseAll(...) (hence the netbeans tag).
This code allows me to get instances of EditorAction, ActionManager, MatlabEditor:
jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor;
jAm = com.mathworks.mde.editor.ActionManager(jEd);
jAc = com.mathworks.mde.editor.EditorAction('collapse-all-folds');
My problem is that I can't find a way to actually activate the Action.
Any ideas / alternatives?
EDIT1: After digging a bit in "the book", I think I came even closer than before (but still not quite there). Quoting from the book:
Java GUI components often use anActionMapto store runnableActionsthat are
invoked by listeners on mouse, keyboard, property, or container events. Unlike object methods,Actionscannot be directly invoked by MATLAB.
And then a workaround is explained which involves roughly: getting some sort of an Action object; creating an ActionEvent and invoking Action's actionPerformed with the ActionEvent as an argument, as implemented below:
import java.awt.event.*;
jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor;
jAm = com.mathworks.mde.editor.ActionManager(jEd);
jAc = jAm.getAction(com.mathworks.mde.editor.EditorAction('collapse-all-folds'));
jAe = ActionEvent(jAm, ActionEvent.ACTION_PERFORMED, '');
jAc.actionPerformed(jAe);
This code runs without errors - but does (seemingly?) nothing. I suspect that I'm calling ActionEvent and actionPerformed on the wrong objects (ActionManager has possibly nothing to do with this problem at all).
P.S.
I know that there's a hotkey that does this (Ctrl + =), but this is not what I'm looking for (unless there's a command to simulate a hotkey press :) ).

After immeasurable digging, trial and way too much error - I've done it!
function FullyCollapseCurrentScript()
%// Get the relevant javax.swing.text.JTextComponent:
jTc = com.mathworks.mlservices.MLEditorServices ...
.getEditorApplication.getActiveEditor.getTextComponent();
%// Get the FoldHierarchy for the JTextComponent:
jFh = org.netbeans.api.editor.fold.FoldHierarchy.get(jTc);
%// Finally, collapse every possible fold:
org.netbeans.api.editor.fold.FoldUtilities.collapseAll(jFh);
end
or if compressed into a single, messy, command:
org.netbeans.api.editor.fold.FoldUtilities.collapseAll(...
org.netbeans.api.editor.fold.FoldHierarchy.get(com.mathworks. ...
mlservices.MLEditorServices.getEditorApplication.getActiveEditor. ...
getTextComponent()));
Note that this works on the script currently open in the editor.

Not a perfect solution but simulating the default hotkey press with java.awt.robot is possible.
...finding a way to actually fire the Action directly would be better...
import java.awt.Robot;
import java.awt.event.*;
RoboKey = Robot;
jTextComp = com.mathworks.mlservices.MLEditorServices. ...
getEditorApplication.getActiveEditor.getTextComponent;
jTextComp.grabFocus()
drawnow; %// give time for focus
if jTextComp.hasFocus()
RoboKey.keyPress(KeyEvent.VK_CONTROL);
RoboKey.keyPress(KeyEvent.VK_EQUALS);
RoboKey.keyRelease(KeyEvent.VK_CONTROL);
RoboKey.keyRelease(KeyEvent.VK_EQUALS);
com.mathworks.mde.cmdwin.CmdWin.getInstance.grabFocus; %// focus back to cmdwin
else
warning('Failed to collapse folds: Editor could not take focus')
end

Related

How to hide JBTextField placeholder when user starts typing

I'm new to plugin development for IntelliJ.
I'm using JBTextField as a text input so I can set the placeholder text using JBTextField.getEmptyText().setText(...) method.
But according to the IntelliJ Platform UI Guidelines it says:
Hide the placeholder when the user starts typing, not when the input field gets the focus.
which is not the way that the textfield itself does. It hides the placeholder when it gets focus.
The question is, how can I change this behavior so that the placeholder disappears when the user type something (For example something like the native IDE's "New Class" popup window).
I found a solution based on this answer by Yann Cebron.
The default behavior from com.intellij.ui.components.TextComponentEmptyText#isStatusVisible can be customized via JBTextField.STATUS_VISIBLE_FUNCTION property which is a reference to a BooleanFunction<JTextComponent>.
So we can reference a boolean function to the STATUS_VISIBLE_FUNCTION key like this:
import com.intellij.ui.components.JBTextField;
import com.intellij.ui.components.TextComponentEmptyText;
import com.intellij.util.BooleanFunction;
textField = new JBTextField();
textField.getEmptyText().setText("Placeholder...");
textField.putClientProperty(
TextComponentEmptyText.STATUS_VISIBLE_FUNCTION,
(BooleanFunction<JBTextField>) tf -> tf.getText().isEmpty()
);

JavaFX: How to check if page available or not

In my project I use simple JavaFX browser, that works in background and do some stuff without displaying it.
More precisely it submitted some form to one online page.
So, I ran into a problem: when this page doesn't available, I can't figure it out from my Java code, it looks like form wasn't submitted and clicks on Submit button do nothing, but in Chrome for example I see that the page isn't available.
So, is there an option to check from Java code if page is available?
Thanks in advance and sorry for bad English.
So, I found an answer.
There is Worker class in JavaFX that associates with WebEngine and it has a field with State type.
State is enum that has 6 options:
READY
SCHEDULED
RUNNING
SUCCEEDED
CANCELLED
FAILED
So State.FAILED can be used for handling errors.
For example, something like that (we'll assume we have WebEngine instance):
webEngine.getLoadWorker().stateProperty().addListener((observable, oldState, newState) -> {
if (newState == Worker.State.FAILED) {
doOnError();
return;
}
doOnSuccess();
});
webEndgine.load("example.com");
So, every time state is changed ObservableValue#changed will be called with new State value as one of parameteres and if state become FAILED we do some error processing.

Not Attached, <Window null#winPop>

I have a problem with my code using zk components.
I am trying to make a popup window without zul file but compose it within my java code.
This is the sample of the code of mine
#Listen("onClick = #btnPopUp")public void popUp(){
Window win = new Window();
win.setId("winPop");
/* i compose some rows, label and other component here...*/
win.doModal();
}
When i click the btnPopUp button, i got an error message ERROR org.zkoss - >> org.zkoss.zk.ui.SuspendNotAllowedException: Not attached, <Window null#winPop>
I got a clue to use Executions.createComponents() method. But is this method can really help? because i usually use this method with a zul file for ex: Window win = (Window) Executions.createComponents("myZul",parent, map);
Thanks guys, really appreciate your help
//Sorry for my bad english :(
‘Not attached‘ is ZK's way of saying the component (the ‘Window‘) doesn't have a parent component.
win.setParent(parent);
or
parent.appendChild(win);
I believe this needs to be done before ‘win.doModal()‘ is called.

Eclipse RCP: Custom console

I am trying to create a console that would work as a shell for a custom programming language. It would be very similar to the pydev interactive console.
Currently, my RCP uses the basic TextConsole and is connected to the shell via pipes so it just displays whatever the shell displays and if the user enters anything in the RCP console, the same is written in the shell.
I want to be able to do a bit more such as move the caret position, add events for up and down arrow keys etc. I believe to do that I need to add a StyledText widget to the console which is done via the ConsoleViewer.
So my question is, that is there any way for me to either override the TextConsole's ConsoleViewer or if I were to extend TextConsole and create my own, then how do I link it with the launch configuration (the one that connects the shell via pipes)?
Also, to get the current default console I use DebugUITools.getConsole(process).
I'm sorry if I haven't put all the information needed; it is a bit difficult to explain. I am happy to add more information.
An idea...
From what I understand I can create a TextConsolePage from the TextConsole using createPage(ConsoleView). Once I have the page I can set the viewer via setViewer(viewer). Here I thought if I create my own viewer (which will have the appropriate stylewidget) then that could be a lead. The only problem is that the viewer needs a Composite and I can't seem to figure out where to get that from.
Why don't you just follow what PyDev does (if you're able to cope with the EPL license)?
The relevant code may be found at:
https://github.com/aptana/Pydev/tree/ad4fd3512c899b73264e4ee981be0c4b69ed5b27/plugins/org.python.pydev/src_dltk_console
https://github.com/aptana/Pydev/tree/ad4fd3512c899b73264e4ee981be0c4b69ed5b27/plugins/org.python.pydev.debug/src_console
So I thought I would answer this myself as I was finally able to accomplish the console. It still is a working prototype but I guess as you keep adding things, you can clean up the code more and more. For my current purposes this is how it worked.
If you want the short version, then I basically mimicked the ProcessConsole provided by Eclipse as that is what I needed: a console in which I can connect a process but since the ProcessConsole is internal, I like to avoid extending those classes.
Following is an outline of the classes I used to achieve interaction with my console. I am not going to give the pretext as to where MyConsole was created. Basically, instead of using DebugUITools.getConsole(myProcess), I used my own myProcess.getConsole() method. MyProcess extends RuntimeProcess.
class MyConsole extends IOConsole {
private IOConsoleInputStream fInput;
private IOConsoleOutputStream fOutput;
private IStreamsProxy fStreamsProxy;
private ConsoleHistory history;
//This is to remember the caret position after the prompt
private int caretAtPrompt;
/* in the console so when you need to replace the command on up and down
* arrow keys you have the position.
* I just did a caretAtPrompt += String.Length wherever string was
* appended to the console. Mainly in the streamlistener and
* InputJob unless you specifically output something to the output
* stream.
*/
//In the constructor you assign all the above fields. Below are some
//to point out.
//fInput = getInputStream();
// fStreamsProxy = process.getStreamsProxy();
// fOutput = newOutputStream();
//We must override the following method to get access to the caret
#Override
public IPageBookViewPage createPage(IConsoleView view) {
return new MyConsolePage(this, view);
}
//After this I followed the ProcessConsole and added the
//InputJob and StreamListener
//defined in there.
}
class MyConsolePage extends TextConsolePage {
//Not much in this class, just override the createViewer
// to return MyConsoleViewer
}
class MyConsoleViewer extends TextConsoleViewer {
//This is the most important class and most of the work is done here
//Again I basically copied everything from IOConsoleViewer and then
//updated whatever I needed
//I added a VerifyKeyListener for the up and down arrow
//keys for the console history
MyConsoleViewer (Composite parent, MyConsole console) {
//I have omitted a lot of code as it was too much to put up,
//just highlighted a few
getTextWidget().addVerifyKeyListener(new MyKeyChecker());
}
class MyKeyChecker implements VerifyKeyListener {...}
}
This is the code for ProcessConsole.
This is the code for IOConsoleViewer.
The ConsoleHistory class I created just had a doubly linked string list to save all the commands the user entered. Quite a simple class to create.
Once you look at the Eclipse classes (ProcessConsole and IOConsoleViewer) it is actually all quite self explanatory. I haven't put in much code here because there is quite a bit. But hopefully this gives some direction as I was completely lost when I started.
I am happy to answer questions though and add more specific code if anyone asks.

Drag&Drop with swing

I need some help. Is it possible to simulate a drag & drop without registering a component?
E.g. I click the mousekey anywhere on the window and hold the mousekey down, at this moment, I want to create or simulate a DragSourceEvent programmatically with Java.
Is this possible?
Update:
Regarding Bob's reply, at least I got it, I can create a listener for the drag & drop:
DragSource dragSource = new DragSource();
DragGestureListener listener = new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent event) {
event.startDrag (null, strSel) ;
...
}
}
listener.dragGestureRecognized(new DragGestureEvent(
new DragGestureRecognizer(dragSource, component) {
}, DnDConstants.ACTION_COPY, new Point(0,0), events ));
but unfortunately i get this exception:
java.lang.IllegalArgumentException:
source actions at
java.awt.dnd.DragSourceContext.(DragSourceContext.java:169)
at
java.awt.dnd.DragSource.createDragSourceContext(DragSource.java:454)
at
java.awt.dnd.DragSource.startDrag(DragSource.java:293)
at
java.awt.dnd.DragSource.startDrag(DragSource.java:403)
at
java.awt.dnd.DragGestureEvent.startDrag(DragGestureEvent.java:203)
any suggestions?
The question you asked:
I haven't tried it, but in theory you should be able to create the Event object and get a handle on the Swing Event Queue from one of the system classes. However without having a valid component, there may be problems when methods try to work with the event.
What you probably meant:
Registering events for a standard window -- you should be able to set up drag and drop support for an empty JPanel or JFrame, but it'll take some hacking. Drag & Drop is a pain to work with at this level when not built in -- I suggest using something like an invisible component or something instead.

Categories

Resources