Java: Getting installed text input languages on Windows - java

I was trying to figure out what are the input languages installed on Windows from a Java application. You can manually figure this from out Control Panel->Region and Language->Change keyboards(button)->General->Installed Services(bottom panel).
The background is that in the application I am forcing Locale.US using a following call -
Component component = getAWTComponent();
component.getInputContext().selectInputMethod(Locale.US)
But on some hosts US keyboard language is not installed (say a system in UK). I wanted to verify that the language is not available and throw an error or something.
Also, is it possible to install such services from Java (far-fetched may be..)?

Messing with the default keyboard layout is something that should only be done with great care. If you do this at all, you should give users an option to select which layout they want instead of forcing a certain layout on everyone.
Imagine your reaction if I wrote an app and tried to force you to use the German keyboard.
That said, the API will fall back to a valid keyboard layout when Locale.US isn't available. The code which does that is hidden in sun.awt.im.InputContext.selectInputMethod()
Using reflection, you should be able to replicate the part of the code which checks whether some locale is supported.

static public void main(String[]args) {
Locale al[] = DateFormat.getAvailableLocales();
for (Locale l : al) {
System.out.println(l);
}
}

Java can found your default charset :
public final static Charset CHARSET_SYSTEM =
Charset.forName(System.getProperties().get("sun.jnu.encoding").toString());
then you can use it in a Scanner to transform input charset in UniCode :
Scanner scan = null;
final void defineScan(Charset charsetCanBeNull) {
scan = new Scanner(System.in, (null == charsetCanBeNull)
? charset
: charsetCanBeNull);
}
Then you can use Scanner.methods(..)

Related

Eclipse Plugin Development: How to access code written in the eclipse editor

I'm making an Eclipse plug-in that requires access to code written in the Eclipse editor. I've followed the process mentioned in the link.
Accessing Eclipse editor code
But it's showing filepath instead of code in the message box. The getEditorInput() of IEditorEditor class isn't doing what it should do according to the link. Here's my code. Please help me find what i'm doing wrong.
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IEditorPart editor = ((IWorkbenchPage) PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()).getActiveEditor();
IEditorInput input = (IEditorInput) editor.getEditorInput(); // accessing code from eclipse editor
String code = input.toString();
MessageDialog.openInformation(
window.getShell(),
"Project",
code);
return null;
}
And here's snap of the output.
You can do this two different ways. This way works regardless of whether the contents are backed by a file on disk or not.
This method gets the text IDocument from the editor, which is how the contents are stored and accessed for most uses. StyledText is a widget, and unless you are doing something with Widgets and Controls, it's not the right way in. For that you're going to go from the editor part, through the ITextEditor interface, and then use the IDocumentProvider with the current editor input. This is skipping the instanceof check you'd want to do beforehand, as well as anything you might have to do if this is a page in a MultiPageEditorPart (there's no standard way for handling those).
org.eclipse.jface.text.IDocument document =
((org.eclipse.ui.texteditor.ITextEditor)editor).
getDocumentProvider().
getDocument(input);
You can get, and modify, the contents through the IDocument.

Netbeans Java code formatting issues

I'd like to have some pieces of Java code formatted in more compact way than default Netbeans formatting behaviour, however, I wasn't able to set Netbeans formatting options for code snippets bellow properly, so I'll try to ask here:
1/ Is is possible to set Netbeans formatting to leave single line method as is? For example:
public void printMessage(String message) { System.out.println(message); }
default behaviour formats this snippet as below:
public void printMessage(String message) {
System.out.println(message);
}
2/ Is it possible to have double braces initialization in this form?
private List<String> list = new ArrayList<String>() {{
// some code here
}};
Netbeans always breaks this code into
private List<String> list = new ArrayList<String>() {
{
// some code here
}
};
Thanks for tips.
Take a look at these sites for more info.
-https://netbeans.org/kb/docs/java/editor-formatting-screencast.html
-http://www.informit.com/articles/article.aspx?p=519945&seqNum=15
To adjust formatting rules for Java files:
Choose Tools -> Options.
Click Editor in the left panel and select the Indentation tab.
Adjust the properties for the indentation engine to your taste.
Reformat each file to the new rules by opening the file and pressing Ctrl + Shift + F (with no text selected).

IPhone password field in AWT/SWT?

I want to create a special Password Dialog for my eclipse product, which is used with an on screen keyboard.
It would be very nice, if i could use a component like the IPhone Password field. In this field, the added character is shown for a second and after the second it is converted into the '*' character for hiding the complete password.
Did a jar/library exists, this is implemented in AWT or SWT?
Edit:
I could trying to implement it from scratch (SWT), but for these i would have to create a very special and complicated KeyListener for the password Text component. I would have to catch the keyReleased event and set the characters manually into the field.
So far i was not able to find any libraries in the web. Suggestion how this can be implemented are welcome too.
This is not really a full answer, rather than a discussion starter and I don't know of any out-of-the-box widgets which can do that.
My first idea was to inheriting the swt Text widget and overriding setEchoChar et al., but after looking at the code this doesn't really seem feasible, because this method is merely a wrapper around:
OS.SendMessage (handle, OS.EM_SETPASSWORDCHAR, echo, 0);
If anyone would know the OS specific low-level implementation, that might be helpful.
Anyway, on to a different approach. I would avoid the KeyListener and use a ModifyListener on the Text-Widget.
void addModifyListener(ModifyListener listener)
You could then build a wrapper which catches the entered text using this listener, appends it to a locally held string/stringbuffer (or e.g. the Eclipse Preferencestore) and send a modified full text to the Text widget using setText(String s), replacing all characters except the last by an echo character (e.g. *).
myText.setText((s.substring(0, s.length()-1)).replaceAll("[\\s\\S]","*")+s.charAt(s.length()-1));
This is a bit of a kludge, but it should work.
The not so straightforward bit is the 1 second timing, without stalling the whole view...
Depending on what Jules said the following code is some kind of working.
The code is quick and fast and i would like to have a more thread safe solution.
originalString = new StringBuffer();
passwordField.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
synchronized (passwordField) {
String s = passwordField.getText();
String newS = s.replaceAll("[\\s\\S]", "*");
if (newS.equals(s)) {
while (originalString.length() > s.length()) {
originalString = originalString.deleteCharAt(originalString.length() - 1);
}
usernameField.setText(originalString.toString());
return;
}
if (originalString.length() < s.length()) {
originalString.append(s.charAt(s.length() - 1));
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
}
passwordField.setText(newS);
}
passwordField.redraw();
passwordField.setSelection(passwordField.getText().length());
}
});
Key Events are cached, so you can add more characters, also when the Thread is waiting.
Another Problem is the Cursor handling. the Cursor always moves to the first position, when you set the Text.
I think when this is working it is very near to the iphone solution.

Malformed Farsi characters on AWT

When I started programming with the JDK6, I had no problem with text components, neither in AWT nor in Swing.
But for labels or titles of AWT components I do have a problem. I can't display Farsi characters on AWTs components (in Swing I type them into the source code).
Here's my sample code:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Properties;
public class EmptyFarsiCharsOnAWT extends JFrame{
public EmptyFarsiCharsOnAWT() {
super("مثال");
setDefaultCloseOperation(3);
setVisible(rootPaneCheckingEnabled);
}
public static void main(String[] args) throws AWTException, IOException {
JFrame jFrame = new EmptyFarsiCharsOnAWT();
MenuItem show ;
// approach 1 = HardCoding :
/*
show = new MenuItem("\u0646\u0645\u0627\u06cc\u0634");
*
*/
// approach 2 = using simple utf-8 saved text file :
/*
BufferedReader in = new BufferedReader(new FileReader("farsiLabels.txt"));
String showLabel = in.readLine();
in.close();
show = new MenuItem(showLabel);
*
*/
// approach 3 = using properties file :
FileReader in = new FileReader("farsiLabels.properties");
Properties farsiLabels = new Properties();
farsiLabels.load(in);
show = new MenuItem(farsiLabels.getProperty("tray.show"));
PopupMenu popUp = new PopupMenu();
popUp.add(show);
// creating Tray object
Image iconIamge = Toolkit.getDefaultToolkit().getImage("greenIcon.png");
TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
jFrame.setIconImage(iconIamge);
}
}
These three approaches all work when run with an IDE, but when I make a JAR containing this class (by means of NetBeans > project > clean & build), I don't see the expected characters (it shows EMPTY/BLANK SQUARES)!
Note:
It seems I can not attach anything, so the contents of the text file would be this: نمایش and the contents of properties file:
#Sun May 02 09:45:10 IRDT 2010
tray.show=نمایش
And I think I have to let you know that I posted this question a while ago on SDN and "the Java Ranch" forums and other native forums and still I'm waiting...
By the way I am using latest version of Netbeans IDE...
I will be grateful if anybody has a solution to these damn AWT components never rendering any Farsi character for me...
I suspect that this is platform related. Your example appears to work on my platform using approach 1 in either Netbeans or the command line; I didn't try the other approaches.
There might be a disparity between the IDE and the command line with regard to the default character encoding. I've noticed that NetBeans, Eclipse and many consoles can be set to something other than the platform default. Here's code to check:
System.out.println(System.getProperty("file.encoding"));
System.out.println(Charset.defaultCharset().name());
You might look at this related question, too.
Addendum: Note show string changed to match the JFrame title for comparison. The title and menu look the same from NetBeans' Run > Run Project as well as via these command lines:
$ java -cp build/classes EmptyFarsiCharsOnAWT
$ java -jar dist/test6.jar
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class EmptyFarsiCharsOnAWT extends JFrame{
public EmptyFarsiCharsOnAWT() {
super("مثال");
setDefaultCloseOperation(3);
setVisible(rootPaneCheckingEnabled);
}
public static void main(String[] args) throws AWTException, IOException {
JFrame jFrame = new EmptyFarsiCharsOnAWT();
MenuItem show ;
// approach 1 = HardCoding :
show = new MenuItem("\u0645\u062b\u0627\u0644");
PopupMenu popUp = new PopupMenu();
popUp.add(show);
// creating Tray object
Image iconIamge = Toolkit.getDefaultToolkit().getImage("image.jpg");
TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
jFrame.setIconImage(iconIamge);
}
}
The most exciting part of your reply was:
"$ java -jar dist/test6.jar" !
Does it really shows the real characters (just like the frame title)?!
and not boxes or garbage ?
I'm sorry if I believe it hard, because the only problem in my developing work with Java took such long without any answer nor from searching, nor asking in forums is this!
So, what can I do? what font should I use? Unfortunately I'm not so familiar with fonts, until now I've just used global fonts in Java (Serif,SansSerif,etc.) and only modified their size or style, but after you suggest I examined several Persian ttf fonts through these codes:
File fontFile = new File("F_JADID.TTF");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
show.setFont(font.deriveFont(15f));
but just boxes was the result! (just using HardCoding)
I think i should mention that my envirounment is win xp and i have this problem not only in my machine, but another running xp os too. And I'm using jdk6u17.
I can be agree with you in suspecting the fonts, because encoding problem (in my experience) appears with question mark, but garbage or empty boxes related to rendering characters.
But still i have the problem, just like the first day :(
What font you use and another question i encountered is:
Why swing doesn't have any problem without specifying the font, but AWT.
Addendum: Thanks to Oscar Reyes in this page for giving this link and thanks to StackOverflow :)
They saved me! from this section i should quote:
An application using peered AWT components can only use logical font names.
and from this section should quote:
For applications using AWT peered components, Sun's JREs select fonts for Chinese, Japanese, or Korean only when running on host operating systems localized for these specific languages
Yes, you guess right! by setting the OS locale to Farsi, i got the right result.
but i still should research and see how is it possible to have the right result by not setting the right locale, from that article.
I will explain how, when i got the result, but still will listen to here. wish me luck.

Window ID from Java SWT

I would like to find the window ID of my SWT program.
I start up my SWT shell in the standard way. How do I then find the ID of the window that's been created? The program is executing on Fedora 10 using the Compiz-Fusion window manager (if that makes a difference).
Code to help explain what I mean:
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell();
// find window ID here??
shell.open();
while (!shell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
}
Update 6 Mar 2009
After looking at and trying out a whole range of things (thanks to VonC for the suggestions below), I came across something that's worked so far. It's supremely dodgy but at least allows me to get on with some other work for the moment.
The ID returned from Control.embeddedHandle is close to the window ID. It's different by a predictable offset. So my code is:
public static void main(String[] args) {
...
Shell shell = new shell(display, SWT.NONE);
Composite e = new Composite(shell, SWT.EMBEDDED);
long windowID = e.embeddedHandle - WINDOW_ID_MAGIC_NUMBER;
e.dispose();
....
WINDOW_ID_MAGIC_NUMBER is 5+(number of widgets added to shell before the embedded composite).
It seems reliable on my system so far. I have yet to see if it falls over in a different environment.
If you create a Composite with the style SWT.EMBEDDED style, then under SWT/GTK+ Composite.embeddedHandle will be an X window ID you can use for parenting an XEMBED child.
Composite embed = new Composite(shell, SWT.EMBEDDED);
System.out.println ("X window ID: " + embed.embeddedHandle);
int hwndChild = OS.GetWindow ( c.handle, OS.GW_CHILD);
This supports embedding using the XEMBED protocol.
This is similar to the JNI code used to get the window ID from its handle
GtkWidget *widget = (GtkWidget *) handle;
GdkWindow *window = widget->window;
xwinid = GDK_WINDOW_XWINDOW(window);
Example of code here.
Example of class using OS:
org.eclipse.swt.widgets.Tree, org.eclipse.swt.widgets.CoolItem,
OS I can find is indeed org.eclipse.swt.internal.win32.OS, not gtk, and it is not a perfect solution because you would access an internal package, but that can give you an idea where to look.
In your case, org.eclipse.swt.internal.gtk.OS is the right class, and you should look in Tree or CoolItem sources how they are using the GetWindow function.
Some other function need to be called in GTK, like may be gtk_container_get_children(int container);
It is said in an answer to the message I was referring at the beginning
If you need the X window, there's no way to do this from the public SWT API (even going through internals), and furthermore even if there was a way I don't think you could guarantee it for all controls. I'm not sure if this works but the closest you could get might be to:
make Control.fixedHandle public
Use OS.GTK_WIDGET_WINDOW (control.fixedHandle) to get a GdkWindow
Use OS.gdk_x11_drawable_get_xid (gdkWindow) to translate that to an X window
I guess the other way might be to take Control.handle, and then call GTK_WIDGET_WINDOW() on it, or if that's null keep calling it on its parents until you find one with a GdkWindow, and then translate that to an X window.
The difficulty here is that SWT talks to GTK+, which talks to GDK, which then talks to X. So, there's three layers between you and the X window.
Not sure if this still matters to you, 7 years later :-), but this works for me:
private static long getWindowIdFromShell(Shell shell) {
long handle = shell.handle;
long topWidget = OS._gtk_widget_get_toplevel(handle);
long topWindow = OS._gtk_widget_get_window(topWidget);
long topXid = OS._gdk_x11_window_get_xid(topWindow);
return topXid;
}
In particular, the "get_toplevel" step is what jumps to the root widget/window, and so means you don't need the "minus magic window offset" hack (which I was initially stuck doing as well).

Categories