SWT: The Standard Widget Toolkit-Part 1: Implementation Strategy for Java™Natives

Source: Internet
Author: User
Document directory
  • Part 1: Implementation Strategy for Java natives
  • Portable and native-it can't be done!
  • A Tale of Two implementations
  • One to One mapping-no custom natives
  • Conclusion

SWT: The Standard Widget Toolkit


Part 1: Implementation Strategy for Java natives


The first in a series of articles about the design ideas behind SWT.

Summary
SWT is the software component that delivers native widget functionality for the eclipse platform in an operating system independent manner. it is analogous to AWT/swing in Java with a difference-SWT uses a rich set of native widgets. even in an ideal situation, industrial strength cross platform widget libraries are very difficult to write and maintain. this is due to the inherent complexity of widget systems and the specified subtle differences between platforms. there are several basic approaches that have helped significantly to reduce the complexity of the problem and deliver high quality libraries. this article discusses one of them, the low level implementation techniques used to implement SWT on different platforms. examples are drawn from the windows and motif implementations.

By Steve northover, OTI
March 22,200 1

Portable and native-it can't be done!

Developers demand portable graphics and widgets to allow them to build user interfaces that are competitive with shrink-wrapped applications built using platform specific tools. they need access to platform specific features, with well defined API boundaries. SWT delivers this functionality using a small and consistent API. this API is implemented on different platforms using a combination of Java code and JNI natives specific to each platform.

SWT is implemented entirely in one language: Java. How can this be true when SWT uses native widgets that provide an API in C? The answer is that Java provides a Native Interface to C (JNI) that is used by SWT to invoke the operating system from Java code. JNI is the standard mechanic used by all Java programs to invoke code written in C. SWT goes one step further by enforcingOne-to-one mappingBetween Java Native methods and operating system CILS. The fact that this mapping is strictly enforced is one of the most critical factors in the success of SWT.

A Tale of Two implementations

Let's take a look at the implementation of SWTTextWidget on two different platforms.TextWidget provides the ability to set the selection. SWT application code that uses this API might look something like this:

/* Select positions 2 to 5 */
Text. settext ("0123456780 ");
Text. setselection (2, 5 );

The method signatureSetselectionIn ClassTextLooks like this:

/**
* Sets the selection.
* <P>
* Indexing is zero based. The range of a selection is from 0 .. n
* Where N is the number of characters in the widget.
*/
Public void setselection (INT start, int end)

Here is the Windows implementationSetselection:

Public void setselection (INT start, int end ){
OS. sendmessage (handle, OS. em_setsel, start, end );
}

What areSendmessageAndEm_setsel? Windows programmers recognize this right away. It'sSendmessage, The mechanism that is used to talk to Windows controls.Em_setselIs the message that tells the text control to set the selection. it's not easy reading, but it is familiar to a Windows programmer. the rest of us get to read the Microsoft Developer Network (msdn) library!

Here is the Java code for the SWT classOSOn Windows:

Class OS {
Public static final int em_setsel = 0xb1;
Public static final native int sendmessage (INT hwnd, int MSG, int wparam, int lparam );
...
}

How isSendmessageNative implemented? Here is the C code on Windows:

Jniexport jint jnicall java_org_eclipse_swt_internal_win32_ OS _sendmessage _ iiii
(Jnienv * ENV, jclass that, jint hwnd, jint MSG, jint wparam, jint lparam)
{
Return (jint) sendmessage (hwnd) hwnd, MSG, wparam, lparam );
}

Notice thatThe only thing this native doesIs pass the Java call straight on through to the Windows API. But what about other operating systems? Does the fact thatSetselectionIs implemented in terms of the Windows API mean that SWT is not portable? While it is true that the windows ImplementationTextIs not portable, application code that usesTextIs. How is this achieved? SWT provides a differentTextClass for each platform, but the signature of every public method is the same. Java code that callswt does not know or care whichTextClass is referenced at run time.SendmessageIs not swt api.

Here is the implementationSetselectionOn motif (Java and jni c ):

Public void setselection (INT start, int end ){
Int xdisplay = OS. xtdisplay (handle );
If (xdisplay = 0) return;
OS. xmtextsetselection (handle, start, end, OS. xtlasttimestampprocessed (xdisplay ));
OS. xmtextsetinsertionposition (handle, end );
}

Class OS {
Public static final native void xmtextsetselection (INT widget, int first, int last, int time );
Public static final native int xtlasttimestampprocessed (INT display );
Public static final native void xmtextsetinsertionposition (INT widget, int position );
Public static final native int xtdisplay (INT widget );
...
}

Jniexport void jnicall java_org_eclipse_swt_internal_motif_ OS _xmtextsetselection
(Jnienv * ENV, jclass that, jint widget, jint first, jint last, jint time)
{
Xmtextsetselection (widget) widget, first, last, time );
}

...

What areXtdisplay,Xmtextsetselection,XtlasttimestampprocessedAndXmtextsetinsertionposition? They don't mean much to a Windows programmer, but they are familiar to anyone who has ever programmed motif. Now it's the Windows programmer's turn to consult the motif man pages!

The example code abve was taken directly from SWT but has been simplified by removing range and error checking code for the sake of the example. however, the code that is doing the real work-Setting the selection-is identical to that found in the product.

One to One mapping-no custom natives

Take a moment to review the Java and C codeSetselectionIn the previous section. Wouldn't it be easier to implement oneTextClass for all SWT platforms and hide the platform differences in the natives? Such an implementation might look like this:

Public void setselection (INT start, int end ){
Nativesetselection (START, end)
}
Static final native void nativesetselection (INT start, int end );

Jniexport void jnicall java_org_eclipse_swt_widgets_text_nativesetselection
(Jnienv * ENV, jclass that, jobject widget, jint first, jint last)
{
# Ifdef windows
Hwnd = swtgethandlefromjavawidget (widget );
Sendmessage (hwnd, MSG, wparam, lparam );
# Endif
# Ifdef Motif
Widget * w = swtgethandlefromjavawidget (widget );
Display xdisplay = xtdisplay (w );
If (xdisplay = NULL) return;
Xmtextsetselection (W, start, end, xtlasttimestampprocessed (xdisplay ));
Xmtextsetinsertionposition (W, end );
# Endif
}

Isn' t this easier than having a differentTextClass on each platform? The answer is a resounding"No". Why? In the case ofTextWidget, the code to set the selection is pretty simple but even this causes problems. Before we get into the discussion, consider this:

  • The non-public Native Interface must be identical on all platforms. This means there needs to be an implementationNativesetselectionEverywhere. We also still need to provide the public swt api. So we need to implementSetselectionEverywhere. Why wocould we want to write two portable APIs instead of just one? One API is hard enough to specify and maintain!
  • Java is a powerful high level language with features that promote robust code and program stability. it contains reusable class libraries for high level data types such as hash tables and vectors as well as efficient primitive types. why use C?

Calling the operating system directly from Java helps with debugging. the following problem occurred in an early version of SWT for Windows: When the selection was set in the text widget, sometimes the widget did not scroll to show the I-beam. where was the problem? The code that demonstrated the problem was complicated, but it was clear from stepping through the Java code and consulting the msdn library that the JAVA ImplementationSetselectionWas correct. In fact, because ofOne-to-one mappingBetween our Java natives and C, it was possible to write a simple C example to help isolate the problem and submit a bug report to Microsoft. Why was this so easy? Because, as we have said before, nothing extra ever happens in an SWT native. the Java call is passed right on through to the operating system. this means that C code is guaranteed to exhibit the same behavior. this is great news for debugging and maintenance.

Performance problems are legendary in widget toolkits and finding them is a black art. Where is the performance problem? Is it in the Java code or the natives? Fortunately, SWT natives can't be the problem. we are guaranteed that once we are in a native, the limiting factor is the speed of the Operating System-something beyond our control. this is great news for Performance Tuning: Look at the Java code. in fact, one quickly develops a sense of which operating system operations are expensive and which are cheap. best of all, this knowledge is accurate. a c program that makes the same sequence of operating system callwill exhibit the same performance characteristics. this is a feature of the one-to-one mapping.

What happens when you try to debug a segment fault (or GP )? It's easy enough to step into a Java method and examine arguments but not possible to step into a native. fortunately, nothing special happens in SWT natives so it's easy enough to isolate the code that is causing the problem. while on the subject of GPS, wouldn't it make sense for SWT natives to check their parameters before making the operating system call? It's tempting to check for null or-1 to avoid the crash. On the surface, this seems to make sense-after all, who wants to GP? The answer, of course, is that this wowould violate the one-to-one mapping and wowould mean that an equivalent C program wowould not crash in the same place. that's bad news for debugging and isolating a problem.

For someone implementing and maintaining SWT, the one-to-one mapping is extremely valuable. For example, a Windows programmer knows right away howSetselectionWorks, just by looking at the Java code. everyone else needs to read the msdn library. it's not light reading, but the information is there. the same thing is true for a motif programmer for SWT on motif, and for the other supported operating systems. in fact, it's clear exactly how existing features work and new features are to be implemented. the critial point here is that the documentation for the operating system applies to all SWT natives because they are a one-to-one mapping.

Adding new native features to SWT is a straightforward and well defined process. for example, implementing drag and drop and integrating it with the widgets was not difficult, despite the fact that these are two independent services. why was this so easy? Nothing is hidden in the C code. all of the operating system resources needed to implement SWT are manifested as simple Java objects making it easy to understand how SWT works and to make changes. this allows SWT to be customized to support new platform dependent widgets and operating system services as they become available.

One last point: JNI is rich and powerful. it allows you to allocate Java objects in C, get and set Java fields, invoke new VMS and throw exceptions. the operating system, on the other hand, is typically more primitive. for example, most operating system cballs that access memory require you to allocate the buffer and pass in the size. java arrays know their size, so why do we need to pass it in? JNI allows us to allocate objects in C, so why not allocate buffers in the C code? Wouldn't it be better to try and "fix" the operating system API to make it more java friendly? The answer again is"No". Any deviation from the one-to-one rule means that our Java code no longer behaves the same as the equivalent C code. for example, allocating objects in JNI cocould introduce a hidden performance problem for Java code inside a tight loop. also, it may make sense to allocate one large buffer and pass in a smaller size, or reuse a buffer. it's tempting to use JNI features to attempt to "fix" the operating system API but this is a huge mistake.

Conclusion

All of the natives in SWT are implemented using this simple and consistent strategy. there is no C code to hide the low level details of the operating system such as the event loop, Callbacks or the thread model. no code reaches back into Java from C to get a field or invoke a method. nothing is magic-everything is coded in Java using the terminology and documentation of the operating system. why Is this such a big deal? Some might claim that all SWT does is use JNI to invoke the operating system-nothing fancy. but that's the whole point. without a simple set of rules and a sense of restraint-a characteristic of SWT-it's just too easy for a Widget Toolkit to collapse under its own weight.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.