Using ACE with WT - java

UPDATE 3
Final working code below. YOU NEED THE ace.js FROM THE src FOLDER! It will not work from the libs, you need the pre-packaged version from their site.
WText *editor = new WText(root());
editor->setText("function(){\n hello.abc();\n}\n");
editor->setInline(false);
The above code can set the contents of the ACE window.
MyClass::MyClass(const WEnvironment& env)
: WApplication(env)
{
wApp->require("ace-builds/src/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
editor->resize(500, 500);
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
std::string command =
editor_ref + ".editor = ace.edit(" + editor_ref + ");" +
editor_ref + ".editor.setTheme(\"ace/theme/monokai\");" +
editor_ref + ".editor.getSession().setMode(\"ace/mode/javascript\");";
editor->doJavaScript(command);
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
command = "function(object, event) {" +
jsignal->createCall(editor_ref + ".editor.getValue()") +
";}";
b->clicked().connect(command);
}
void MyClass::textChanged(std::string incoming)
{
}
UPDATE 2
Here is what my project looks like atm, still getting a white screen with a red "Loading..." message from WT in the top right hand corner. More notes below.
MyClass::MyClass(const WEnvironment& env)
: WApplication(env)
{
wApp->require("lib/ace/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
editor->resize(500, 500);
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
std::string command =
editor_ref + ".editor = ace.edit(" + editor_ref + ");" +
editor_ref + ".editor.setTheme(\"ace/theme/monokai\");" +
editor_ref + ".editor.getSession().setMode(\"ace/mode/javascript\");";
editor->doJavaScript(command);
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
command = "function(object, event) {" +
jsignal->createCall(editor_ref + ".editor.getValue()") +
";}";
b->clicked().connect(command);
}
void MyClass::textChanged(std::string incoming)
{
}
"command" variable is equal to the following when it is used for editor->doJavaScript(command)
"Wt3_3_0.$('oy4ycjy').editor = ace.edit(Wt3_3_0.$('oy4ycjy'));Wt3_3_0.$('oy4ycjy').editor.setTheme('ace/theme/monokai');Wt3_3_0.$('oy4ycjy').editor.getSession().setMode('ace/mode/javascript');"
"command" variable is equal to the following when it is used for b->clicked().connect(command);
"function(object, event) {Wt.emit('oy4ycjy','textChanged',Wt3_3_0.$('oy4ycjy').editor.getValue());;}"
UPDATE 1
Added the suggested code to my constructor, however the page does not change from a solid white screen. I am doing nothing else in this WT project, only this code is running.
wApp->require("lib/ace/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
editor->doJavaScript(
editor_ref + ".editor = ace.edit('" + editor_ref + "');" +
editor_ref + ".editor.setTheme('ace/theme/monokai');" +
editor_ref + ".editor.getSession().setMode('ace/mode/javascript');"
);
The value of editor_ref is "Wt3_3_0.$('oumvrgm')" minus the quotes.
Also tried adding the code below, and the page is still blanked out.
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
b->clicked().connect("function(object, event) {" +
jsignal->createCall(editor->jsRef() + ".editor.getValue()") +
";}");
I have also found that commenting out
editor_ref + ".editor = ace.edit('" + editor_ref + "');" +
makes the button show up, but there is a red "Loading..." note at the top right of the screen so WT is waiting on something.
I have textChanged as a do nothing function at the moment.
ORIGINAL POST
So, my problem is this. How can I get ACE http://ace.ajax.org/#nav=about in WT http://www.webtoolkit.eu/wt. More specifically, ACE in a WT Wt::WTextArea or Wt::WTabWidget, the text area would be preferred. I have been trying to do this for a few days now and have not had much success.
I've been able to embed ACE in an HTML page no problem, as their site says "just copy and paste it into your page" and it really is that simple. However, I need to load it locally through WT and into a container. I downloaded their repos from GIT to my machine and have tried using
require("lib/ace/ace.js");
and
doJavaScript(...);
with various commands to no success... I am not nearly as strong in Java and HTML as C++ so I will ask for as much detail as possible if this involves a lot of Java/HTML. Thanks in advance mates!

Maybe this puts you in the right direction:
wApp->require("lib/ace/ace.js")
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(parent);
// editor->jsRef() is a text string that will be the element when executed in JS
editor->doJavaScript(
editor->jsRef() + ".editor = ace.edit(" + editor->jsRef() + ");" +
editor->jsRef() + ".editor.setTheme('ace/theme/monokai');" +
editor->jsRef() + ".editor.getSession().setMode('ace/mode/javascript');"
);
That should decorate the editor. Wt does not automatically send the modifications to a div to the server, so you do this manually through a JSignal (emits a signal from JS to C++):
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, MyClass::textChanged);
WPushButton *b = new WPushButton("Save", parent);
b->clicked().connect("function(object, event) {" +
jsignal->createCall(editor->jsRef() + ".editor.getValue()") +
";}");
(code above is not tested so you may need to adjust a bit)
I have integrated CodeMirror in an earlier JWt (java) project like this:
import eu.webtoolkit.jwt.WApplication;
import eu.webtoolkit.jwt.WContainerWidget;
import eu.webtoolkit.jwt.WTextArea;
public class CodeMirrorTextArea extends WContainerWidget {
private WTextArea textArea;
public CodeMirrorTextArea(WContainerWidget parent) {
super(parent);
textArea = new WTextArea(this);
WApplication app = WApplication.getInstance();
app.require(app.resolveRelativeUrl("codemirror-2.32/lib/codemirror.js"));
app.require(app.resolveRelativeUrl("codemirror-2.32/mode/groovy/groovy.js"));
//TODO:
//We save the editor state to the text area on each key stroke,
//it appears to be not a performance issue,
//however it might very well become one when editing larger fragments of code.
//A better solution would be to save this state to the text area only when
//the form is submitted, currently this is not yet possible in Wt???.
String js =
"var e = " + textArea.getJsRef() + ";" +
"var cm = CodeMirror.fromTextArea(e, {" +
" onKeyEvent : function (editor, event) {" +
" editor.save();" +
" }," +
" lineNumbers: true" +
" });" +
"var self = " + getJsRef() + ";" +
"self.cm = cm;";
this.doJavaScript(js);
}
public CodeMirrorTextArea() {
this(null);
}
public void setText(String text) {
textArea.setText(text);
}
public String getText() {
return textArea.getText();
}
public void setMarker(int line, String htmlMarker) {
String js =
"var self = " + getJsRef() + ";" +
"self.cm.setMarker(" + line + ", " + jsStringLiteral(htmlMarker +
"%N%") + ");";
this.doJavaScript(js);
}
public void clearMarker(int line) {
String js =
"var self = " + getJsRef() + ";" +
"self.cm.clearMarker(" + line + ");";
this.doJavaScript(js);
}
}

Related

Java Selenium with Angular 5

I am trying to work with Selenium in Java with Angular 5 based website.
Selenium does not support it directly, but JavascriptExecutor can help validating the page components finished loading.
The problem is, I do not know how to implement the JavaScript to validate this.
I am using:
return window.getAngularTestability === undefined
to validate Angular 5 exists in the current page, but the next part of the implementation is a mystery to me.
I know I have to use return window.getAngularTestability somehow.
You can create a generic java method for running any javascript within your Java code. Refer below block of code:-
public void executeJavascript(String script) {
((JavascriptExecutor) driver).executeScript(script);
}
You can pass your return javascript statements as parameters to this method.
I found an answer after a lot of research and searching the web.
The solution is not mine, so i do not deserve the credit.
ExpectedCondition<Boolean> expectation = driver -> ((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"if (document.readyState !== 'complete') {" +
" callback('document not ready');" +
"} else {" +
" try {" +
" var testabilities = window.getAllAngularTestabilities();" +
" var count = testabilities.length;" +
" var decrement = function() {" +
" count--;" +
" if (count === 0) {" +
" callback('complete');" +
" }" +
" };" +
" testabilities.forEach(function(testability) {" +
" testability.whenStable(decrement);" +
" });" +
" } catch (err) {" +
" callback(err.message);" +
" }" +
"}"
).toString().equals("complete");
try {
WebDriverWait wait = new WebDriverWait(webDriver(), 15);
wait.until(expectation);
} catch (Throwable error) {
new Exception("Timeout waiting for Page Load Request to complete.");
}

RadioButton to TextArea Issue

I can not get the text from a radio button to show when selected into a text area. can only get a true or false value. The code below is where I am having the issue. I would appreciate any advice.
jTextArea2.setText(String.valueOf("Mixed Flavors:" + jRadioButton1.isSelected() + jRadioButton2.isSelected()
+ jRadioButton3.isSelected() + jRadioButton4.isSelected()));
To get text You have to use getText() on your radiobutton. Also there is no need of using String.valueOf() as the whole thing which you are trying to set in TextArea will became a String.
jTextArea2.setText("Mixed Flavors:" + jRadioButton1.getText() + ":" +
jRadioButton1.isSelected() + " , " + jRadioButton2.getText() + ":" +
jRadioButton2.isSelected() + " , "+ jRadioButton3.getText() + ":" +
jRadioButton3.isSelected() + " , " + jRadioButton4.getText() + ":" +
jRadioButton4.isSelected());
I can not get the text from a radio button to show when selected into a text area, I just hope that means you want to try something like
if( jRadioButton1.isSelected() )
jTextArea2.setText( String.valueOf("BLA") + jRadioButton1.getText() );
if( jRadioButton2.isSelected() )
jTextArea2.setText( String.valueOf("BLA") + jRadioButton2.getText() );
if( jRadioButton3.isSelected() )
jTextArea2.setText( String.valueOf("BLA") + jRadioButton3.getText() );
if( jRadioButton4.isSelected() )
jTextArea2.setText( String.valueOf("BLA") + jRadioButton4.getText() );

Bukkit Coding - Kick message with color codes set in config.yml

So I have a plugin im making where they get kicked with a message. I want that message to be in color that is set in the config.yml. heres my code:
}
if (l == 2) {
settings.getData().set("" + target.getName() + "", null);
settings.saveData();
target.kickPlayer(this.getConfig().getString("BanMessage"));
target.setBanned(true);
Bukkit.getServer().broadcastMessage(ChatColor.RED + target.getName() + " " + "Has been tempbanned for 25 Minutes by " + sender.getName() + "" + "(3/3)");
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
target.setBanned(false);
}
}, 1500 * 20);
return true;
}
Heres my config.yml:
BanMessage: You have been temp banned for 25 Minutes
You could use ChatColor.translateAlternateColorCodes():
String kickMessage = plugin.getConfig().getString("BanMessage");
kickMessage = ChatColor.translateAlternateColorCodes('&', kickMessage);
target.kickPlayer(kickMessage);
target.setBanned(true);
You can use these color codes in your configuration file.
So, putting in &6You have been banned for &4Spamming Will give you ChatColor.GOLD + "You have been banned for " + ChatColor.DARK_RED + " Spamming"
and if you would like to make it so they get that same message whenever they join if they're banned, you can use:
#EventHandler
public void playerJoin(PlayerJoinEvent e){
if(myMethodToCheckIfAPlayerIsTempBanned(e.getPlayer()){
String msg = myMethodToGetPlayersBanMessage(e.getPlayer());
e.getPlayer().kickPlayer(msg);
}
}
This should work:
String kickMessage = this.getConfig().getString("BanMessage");
kickMessage.replaceAll("(?i)&([a-f0-9])", "\u00A7$1");
target.kickPlayer(kickMessage);
target.setBanned(true);
Then, you should be able to use these color codes in your config.
ex.
BanMessage: &3You &0have been banned &1for &425 &3minutes
will display as
You have been temp banned for 25 Minutes

Create HTML in java with background image

I have created an html string in which I need to set the background image.
protected void onPostExecute(HashMap<String,String> hPlaceDetails){
String backgroundImage = ??????
String name = hPlaceDetails.get("name");
String icon = hPlaceDetails.get("icon");
String vicinity = hPlaceDetails.get("vicinity");
String lat = hPlaceDetails.get("lat");
String lng = hPlaceDetails.get("lng");
String formatted_address = hPlaceDetails.get("formatted_address");
String formatted_phone = hPlaceDetails.get("formatted_phone");
String website = hPlaceDetails.get("website");
String rating = hPlaceDetails.get("rating");
String international_phone_number = hPlaceDetails.get("international_phone_number");
String url = hPlaceDetails.get("url");
String mimeType = "text/html";
String encoding = "utf-8";
String data = "<html>"+
"<body background="+backgroundImage+"><img style='float:left' src="+icon+" /><h1><center>"+name+"</center></h1>" +
"<br style='clear:both' />" +
"<hr />"+
"<p>Vicinity : " + vicinity + "</p>" +
"<p>Location : " + lat + "," + lng + "</p>" +
"<p>Address : " + formatted_address + "</p>" +
"<p>Phone : " + formatted_phone + "</p>" +
"<p>Website : " + website + "</p>" +
"<p>Rating : " + rating + "</p>" +
"<p>International Phone : " + international_phone_number + "</p>" +
"<p>URL : <a href='" + url + "'>" + url + "</p>" +
"</body></html>";
// Setting the data in WebView
mWvPlaceDetails.loadDataWithBaseURL("", data, mimeType, encoding, "");
}
Note: I have my background image (background9.png) in the location MyProject/res/drawable-xhdpi. Please suggest how I need to set
<body background="+backgroundImage+">
Instead of using \res\drawable-xhdp\background9.png as the path as you mentioned in your comment, you should use:
<body background='file:///android_res/drawable/background9.png'>
I've just tested this and it works perfectly.
Please add a tag for android to clarify your question.
Anyway, you need to get a reference for your parent layout, by using findViewById(R.id.yourActivitysParentLayout)
You need then to set it's background using a ResourceManager. From the top of my head, the method name you will need is yourparent.setBackgroungDrawable(drawable). The drawable can be obtained from a resource manager instance.
This can all be avoided by setting it's background in the xml if possible by using android:background="#drawable/background9" //sorry not sure if .png is needed. xhdp is not though.

Aligning a String in JOptionPane

I have a string that I want to display in a JOptionPane.
String info = "Name:" + _name + "\n" +
"Phone:" + _phone;
I tried to add \t but it didn't work.
I tried also to
int choose = JOptionPane.showConfirmDialog(this,new JTextArea(info),"XXX",0);
But it doesn't look good.
Are there another ways to do that? (If you know about a solution where I can use something like \t it will be very usefull for me)
* In this specific example I can manually align it, but I'm looking for a general solution.
HTML formatting could help:
String info = "Name:" + _name + "<br>" +
"Phone:" + _phone + "<br>";
int choose =
JOptionPane.showConfirmDialog(this, "<html>" + info + "</html>", "XXX", 0);
Another option is to use a JTable in the JOptionPane dialog as shown in this solution.
I had something like that and it worked:
String st = "<table border = \"0\">" +
"<tr><td>VALUE1: </td><td>" + _value2 + "</td></tr>"+
"<tr><td>VALUE2: </td><td>" + _value4 + "</td></tr>" +
//.....
"</table>";

Categories