summaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
authorVeronika Irvine <veronika>2003-03-05 18:08:48 +0000
committerVeronika Irvine <veronika>2003-03-05 18:08:48 +0000
commit5f0a43f5b96ff1bf18fe8995d1b162bd6a21031c (patch)
tree9a1e83e7cfeb5b708432975c6b7735159ea70492 /examples
parent8d95651bd484e1f1f2a8817b538fa6ab423708e4 (diff)
downloadeclipse.platform.swt-5f0a43f5b96ff1bf18fe8995d1b162bd6a21031c.tar.gz
eclipse.platform.swt-5f0a43f5b96ff1bf18fe8995d1b162bd6a21031c.tar.xz
eclipse.platform.swt-5f0a43f5b96ff1bf18fe8995d1b162bd6a21031c.zip
Converting Binary files to ASCII
Diffstat (limited to 'examples')
-rw-r--r--examples/org.eclipse.swt.examples.controls/.project60
-rwxr-xr-xexamples/org.eclipse.swt.examples.controls/build.properties20
-rw-r--r--examples/org.eclipse.swt.examples.controls/doc-html/hglegal2002.htm28
-rwxr-xr-xexamples/org.eclipse.swt.examples.controls/doc-html/swt_controls_ex.html54
-rwxr-xr-xexamples/org.eclipse.swt.examples.controls/plugin.properties30
-rwxr-xr-xexamples/org.eclipse.swt.examples.controls/plugin.xml112
-rwxr-xr-xexamples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlPlugin.java54
-rwxr-xr-xexamples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlView.java96
-rw-r--r--examples/org.eclipse.swt.examples.launcher/.project60
-rwxr-xr-xexamples/org.eclipse.swt.examples.launcher/build.properties24
-rw-r--r--examples/org.eclipse.swt.examples.launcher/doc-html/hglegal2002.htm28
-rwxr-xr-xexamples/org.eclipse.swt.examples.launcher/doc-html/swt_launcher_ex.html90
-rwxr-xr-xexamples/org.eclipse.swt.examples.launcher/plugin.properties78
-rwxr-xr-xexamples/org.eclipse.swt.examples.launcher/plugin.xml160
-rwxr-xr-xexamples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/ItemDescriptor.java2
-rwxr-xr-xexamples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherPlugin.java750
-rwxr-xr-xexamples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherView.java450
-rwxr-xr-xexamples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/SplitLayout.java24
-rw-r--r--examples/org.eclipse.swt.examples.layouts/.project60
-rw-r--r--examples/org.eclipse.swt.examples.layouts/doc-html/hglegal2002.htm28
-rw-r--r--examples/org.eclipse.swt.examples.layouts/doc-html/swt_layout_ex.html56
-rw-r--r--examples/org.eclipse.swt.examples.ole.win32/.project58
-rwxr-xr-xexamples/org.eclipse.swt.examples.ole.win32/build.properties20
-rw-r--r--examples/org.eclipse.swt.examples.ole.win32/doc-html/hglegal2002.htm28
-rwxr-xr-xexamples/org.eclipse.swt.examples.ole.win32/doc-html/swt_ole_ex.html68
-rwxr-xr-xexamples/org.eclipse.swt.examples.ole.win32/plugin.properties100
-rwxr-xr-xexamples/org.eclipse.swt.examples.ole.win32/plugin.xml110
-rwxr-xr-xexamples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleBrowserView.java716
-rwxr-xr-xexamples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OlePlugin.java338
-rwxr-xr-xexamples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleWebBrowser.java442
-rw-r--r--examples/org.eclipse.swt.examples.paint/.project58
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/build.properties20
-rw-r--r--examples/org.eclipse.swt.examples.paint/doc-html/hglegal2002.htm28
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/doc-html/swt_paint_ex.html72
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/plugin.properties248
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/plugin.xml110
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/AirbrushTool.java142
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/BasicPaintSession.java18
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContainerFigure.java172
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContinuousPaintSession.java450
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/DragPaintSession.java256
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseFigure.java90
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseTool.java112
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/Figure.java62
-rw-r--r--examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/FigureDrawContext.java66
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineFigure.java90
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineTool.java102
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintPlugin.java154
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSession.java102
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSurface.java56
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintTool.java24
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintView.java986
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PencilTool.java102
-rw-r--r--examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PointFigure.java66
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PolyLineTool.java136
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleFigure.java88
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleTool.java128
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleFigure.java92
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleTool.java114
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SegmentedPaintSession.java304
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidEllipseFigure.java74
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidPolygonFigure.java104
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRectangleFigure.java72
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRoundedRectangleFigure.java76
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextFigure.java84
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextTool.java240
-rwxr-xr-xexamples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ToolSettings.java52
-rw-r--r--examples/org.eclipse.swt.examples/.project58
-rwxr-xr-xexamples/org.eclipse.swt.examples/build.properties18
-rw-r--r--examples/org.eclipse.swt.examples/doc-html/hglegal2002.htm28
-rwxr-xr-xexamples/org.eclipse.swt.examples/doc-html/swt_addressbook_ex.html62
-rwxr-xr-xexamples/org.eclipse.swt.examples/doc-html/swt_fileviewer_ex.html66
-rwxr-xr-xexamples/org.eclipse.swt.examples/doc-html/swt_helloworld_ex.html122
-rwxr-xr-xexamples/org.eclipse.swt.examples/doc-html/swt_hoverhelp_ex.html74
-rwxr-xr-xexamples/org.eclipse.swt.examples/doc-html/swt_imageanalyzer_ex.html114
-rwxr-xr-xexamples/org.eclipse.swt.examples/doc-html/swt_javaviewer_ex.html66
-rwxr-xr-xexamples/org.eclipse.swt.examples/doc-html/swt_manual_setup.html238
-rwxr-xr-xexamples/org.eclipse.swt.examples/doc-html/swt_texteditor_ex.html70
-rwxr-xr-xexamples/org.eclipse.swt.examples/plugin.properties224
-rwxr-xr-xexamples/org.eclipse.swt.examples/plugin.xml284
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/AddressBook.java1708
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/DataEntryDialog.java310
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/FindListener.java20
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/SearchDialog.java388
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/AlignableTab.java164
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ButtonTab.java380
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ComboTab.java222
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ControlExample.java656
-rw-r--r--examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/CoolBarTab.java846
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/DialogTab.java878
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/LabelTab.java344
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ListTab.java156
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ProgressBarTab.java276
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/RangeTab.java352
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SashTab.java354
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ScrollableTab.java112
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ShellTab.java568
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SliderTab.java492
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/Tab.java1076
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TableTab.java562
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TextTab.java432
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ToolBarTab.java490
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TreeTab.java264
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/FileViewer.java3406
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/IconCache.java290
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld1.java56
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld2.java68
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld3.java82
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld4.java74
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld5.java96
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/hoverhelp/HoverHelp.java668
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/imageanalyzer/ImageAnalyzer.java4146
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaLineStyler.java740
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaViewer.java346
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/Images.java102
-rwxr-xr-xexamples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/TextEditor.java682
116 files changed, 16262 insertions, 16262 deletions
diff --git a/examples/org.eclipse.swt.examples.controls/.project b/examples/org.eclipse.swt.examples.controls/.project
index 8ef8047fe2..6dd25a0fdf 100644
--- a/examples/org.eclipse.swt.examples.controls/.project
+++ b/examples/org.eclipse.swt.examples.controls/.project
@@ -1,30 +1,30 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipse.swt.examples.controls</name>
- <comment></comment>
- <projects>
- <project>org.eclipse.swt</project>
- <project>org.eclipse.swt.examples</project>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.swt.examples.controls</name>
+ <comment></comment>
+ <projects>
+ <project>org.eclipse.swt</project>
+ <project>org.eclipse.swt.examples</project>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ </natures>
+</projectDescription>
diff --git a/examples/org.eclipse.swt.examples.controls/build.properties b/examples/org.eclipse.swt.examples.controls/build.properties
index daf2c0b0be..76c667e35f 100755
--- a/examples/org.eclipse.swt.examples.controls/build.properties
+++ b/examples/org.eclipse.swt.examples.controls/build.properties
@@ -1,10 +1,10 @@
-bin.includes = doc-html/,\
- icons/,\
- plugin.properties,\
- plugin.xml,\
- about.html,\
- *.jar
-
-src.includes = about.html
-
-source.controls.jar = src/
+bin.includes = doc-html/,\
+ icons/,\
+ plugin.properties,\
+ plugin.xml,\
+ about.html,\
+ *.jar
+
+src.includes = about.html
+
+source.controls.jar = src/
diff --git a/examples/org.eclipse.swt.examples.controls/doc-html/hglegal2002.htm b/examples/org.eclipse.swt.examples.controls/doc-html/hglegal2002.htm
index 74393f08f3..5df454d51a 100644
--- a/examples/org.eclipse.swt.examples.controls/doc-html/hglegal2002.htm
+++ b/examples/org.eclipse.swt.examples.controls/doc-html/hglegal2002.htm
@@ -1,14 +1,14 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
- <title>Legal Notices</title>
-</head>
-<body>
-
-<h3>
-<a NAME="Notices"></a>Notices</h3>
-(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
+ <title>Legal Notices</title>
+</head>
+<body>
+
+<h3>
+<a NAME="Notices"></a>Notices</h3>
+(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.controls/doc-html/swt_controls_ex.html b/examples/org.eclipse.swt.examples.controls/doc-html/swt_controls_ex.html
index d18d828525..12d74b4009 100755
--- a/examples/org.eclipse.swt.examples.controls/doc-html/swt_controls_ex.html
+++ b/examples/org.eclipse.swt.examples.controls/doc-html/swt_controls_ex.html
@@ -1,27 +1,27 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Controls Example</title>
-</head>
-<body>
-
-<h2>SWT Example - Controls Example</h2>
-
-<p>
-The Controls example is a simple demonstration of common SWT controls.
-It consists of a tab folder where each tab in the folder allows the user
-to interact with a different control.
-The user can change styles and settings and view how this affects the control.
-</p>
-
-<h3>Running the example</h3>
-<p>From the Window menu select Show View --> Other.
-In the Show View dialog, expand SWT Examples and select the
-view named SWT Controls. A view titled SWT Controls will appear in your current perspective.
-</p>
-
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Controls Example</title>
+</head>
+<body>
+
+<h2>SWT Example - Controls Example</h2>
+
+<p>
+The Controls example is a simple demonstration of common SWT controls.
+It consists of a tab folder where each tab in the folder allows the user
+to interact with a different control.
+The user can change styles and settings and view how this affects the control.
+</p>
+
+<h3>Running the example</h3>
+<p>From the Window menu select Show View --> Other.
+In the Show View dialog, expand SWT Examples and select the
+view named SWT Controls. A view titled SWT Controls will appear in your current perspective.
+</p>
+
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.controls/plugin.properties b/examples/org.eclipse.swt.examples.controls/plugin.properties
index 418cd71a1e..0ec4672067 100755
--- a/examples/org.eclipse.swt.examples.controls/plugin.properties
+++ b/examples/org.eclipse.swt.examples.controls/plugin.properties
@@ -1,16 +1,16 @@
-providerName = Eclipse.org
-plugin.SWTControlsExample.name = SWT Controls Example Plugin
-category.SWTExamples.name = SWT Examples
-view.ControlsExample.name = SWT Controls
-
-launchcategory.SWTViewExamples.name = Workbench Views
-launchcategory.SWTViewExamples.description = \
- A collection of Standard Widget Toolkit examples that run as Views inside the Workbench. \
- These examples will create a new View in the current Perspective.
-
-launchitem.ControlsExample.name = Controls
-launchitem.ControlsExample.description = \
- This example is a simple demonstration of common SWT controls.\n\n\
- It consists of a tab folder where each tab allows the user \
- to interact with a different SWT control. \
+providerName = Eclipse.org
+plugin.SWTControlsExample.name = SWT Controls Example Plugin
+category.SWTExamples.name = SWT Examples
+view.ControlsExample.name = SWT Controls
+
+launchcategory.SWTViewExamples.name = Workbench Views
+launchcategory.SWTViewExamples.description = \
+ A collection of Standard Widget Toolkit examples that run as Views inside the Workbench. \
+ These examples will create a new View in the current Perspective.
+
+launchitem.ControlsExample.name = Controls
+launchitem.ControlsExample.description = \
+ This example is a simple demonstration of common SWT controls.\n\n\
+ It consists of a tab folder where each tab allows the user \
+ to interact with a different SWT control. \
The user can change styles and settings and view how this affects the control. \ No newline at end of file
diff --git a/examples/org.eclipse.swt.examples.controls/plugin.xml b/examples/org.eclipse.swt.examples.controls/plugin.xml
index 0bad5bc6de..3b9795ed05 100755
--- a/examples/org.eclipse.swt.examples.controls/plugin.xml
+++ b/examples/org.eclipse.swt.examples.controls/plugin.xml
@@ -1,56 +1,56 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin
- id="org.eclipse.swt.examples.controls"
- name="%plugin.SWTControlsExample.name"
- version="2.1.0"
- provider-name="%providerName"
- class="org.eclipse.swt.examples.controls.ControlPlugin">
-
-<!-- Runtime -->
-<!-- Runtime -->
- <runtime>
- <library name="controls.jar">
- <packages prefixes="org.eclipse.swt.examples.controls"/>
- </library>
- </runtime>
-<!-- Required plugins -->
- <requires>
- <import plugin="org.eclipse.core.runtime"/>
- <import plugin="org.eclipse.ui"/>
- <import plugin="org.eclipse.swt"/>
- <import plugin="org.eclipse.swt.examples"/>
- </requires>
-
-
-<!-- Extension points -->
-<!-- Extensions -->
- <extension
- point="org.eclipse.ui.views">
- <view
- name="%view.ControlsExample.name"
- icon="icons/controls_example.gif"
- category="org.eclipse.swt.examples.category"
- class="org.eclipse.swt.examples.controls.ControlView"
- id="org.eclipse.swt.examples.controls.view">
- </view>
- </extension>
- <extension
- point="org.eclipse.swt.examples.launcher.launchItems">
- <category
- name="%launchcategory.SWTViewExamples.name"
- description="%launchcategory.SWTViewExamples.description"
- id="org.eclipse.swt.examples.launchViewCategory">
- </category>
- <item
- name="%launchitem.ControlsExample.name"
- icon="icons/controls_example.gif"
- description="%launchitem.ControlsExample.description"
- category="org.eclipse.swt.examples.launchViewCategory"
- id="org.eclipse.swt.examples.controls.viewlauncher">
- <view
- viewId="org.eclipse.swt.examples.controls.view">
- </view>
- </item>
- </extension>
-
-</plugin>
+<?xml version="1.0" encoding="UTF-8"?>
+<plugin
+ id="org.eclipse.swt.examples.controls"
+ name="%plugin.SWTControlsExample.name"
+ version="2.1.0"
+ provider-name="%providerName"
+ class="org.eclipse.swt.examples.controls.ControlPlugin">
+
+<!-- Runtime -->
+<!-- Runtime -->
+ <runtime>
+ <library name="controls.jar">
+ <packages prefixes="org.eclipse.swt.examples.controls"/>
+ </library>
+ </runtime>
+<!-- Required plugins -->
+ <requires>
+ <import plugin="org.eclipse.core.runtime"/>
+ <import plugin="org.eclipse.ui"/>
+ <import plugin="org.eclipse.swt"/>
+ <import plugin="org.eclipse.swt.examples"/>
+ </requires>
+
+
+<!-- Extension points -->
+<!-- Extensions -->
+ <extension
+ point="org.eclipse.ui.views">
+ <view
+ name="%view.ControlsExample.name"
+ icon="icons/controls_example.gif"
+ category="org.eclipse.swt.examples.category"
+ class="org.eclipse.swt.examples.controls.ControlView"
+ id="org.eclipse.swt.examples.controls.view">
+ </view>
+ </extension>
+ <extension
+ point="org.eclipse.swt.examples.launcher.launchItems">
+ <category
+ name="%launchcategory.SWTViewExamples.name"
+ description="%launchcategory.SWTViewExamples.description"
+ id="org.eclipse.swt.examples.launchViewCategory">
+ </category>
+ <item
+ name="%launchitem.ControlsExample.name"
+ icon="icons/controls_example.gif"
+ description="%launchitem.ControlsExample.description"
+ category="org.eclipse.swt.examples.launchViewCategory"
+ id="org.eclipse.swt.examples.controls.viewlauncher">
+ <view
+ viewId="org.eclipse.swt.examples.controls.view">
+ </view>
+ </item>
+ </extension>
+
+</plugin>
diff --git a/examples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlPlugin.java b/examples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlPlugin.java
index 25bf20ed1b..c963e2f639 100755
--- a/examples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlPlugin.java
+++ b/examples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlPlugin.java
@@ -1,30 +1,30 @@
-package org.eclipse.swt.examples.controls;
-
-/*
+package org.eclipse.swt.examples.controls;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.core.runtime.*;
-import org.eclipse.ui.plugin.*;
-
-/**
- * The main plugin class to be used in the desktop.
- */
-public class ControlPlugin extends AbstractUIPlugin {
- /**
- * The constructor.
- */
- public ControlPlugin(IPluginDescriptor descriptor) {
- super(descriptor);
- }
-
- /**
- * Clean up
- */
- public void shutdown() throws CoreException {
- super.shutdown();
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.core.runtime.*;
+import org.eclipse.ui.plugin.*;
+
+/**
+ * The main plugin class to be used in the desktop.
+ */
+public class ControlPlugin extends AbstractUIPlugin {
+ /**
+ * The constructor.
+ */
+ public ControlPlugin(IPluginDescriptor descriptor) {
+ super(descriptor);
+ }
+
+ /**
+ * Clean up
+ */
+ public void shutdown() throws CoreException {
+ super.shutdown();
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlView.java b/examples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlView.java
index a55b7545a5..07f5f7a59b 100755
--- a/examples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlView.java
+++ b/examples/org.eclipse.swt.examples.controls/src/org/eclipse/swt/examples/controls/ControlView.java
@@ -1,51 +1,51 @@
-package org.eclipse.swt.examples.controls;
-
-/*
+package org.eclipse.swt.examples.controls;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.examples.controlexample.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.ui.part.*;
-
-/**
- * <code>Controls</code> is a simple demonstration
- * of the controls defined by SWT. It consists of a workbench
- * view and tab folder where each tab in the folder allows the
- * user to interact with a control.
- *
- * @see ViewPart
- */
-public class ControlView extends ViewPart {
- ControlExample instance = null;
-
- /**
- * Create the example
- *
- * @see ViewPart#createPartControl
- */
- public void createPartControl(Composite frame) {
- instance = new ControlExample(frame);
- }
-
- /**
- * Called when we must grab focus.
- *
- * @see org.eclipse.ui.part.ViewPart#setFocus
- */
- public void setFocus() {
- instance.setFocus();
- }
-
- /**
- * Called when the View is to be disposed
- */
- public void dispose() {
- instance.dispose();
- instance = null;
- super.dispose();
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.examples.controlexample.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.ui.part.*;
+
+/**
+ * <code>Controls</code> is a simple demonstration
+ * of the controls defined by SWT. It consists of a workbench
+ * view and tab folder where each tab in the folder allows the
+ * user to interact with a control.
+ *
+ * @see ViewPart
+ */
+public class ControlView extends ViewPart {
+ ControlExample instance = null;
+
+ /**
+ * Create the example
+ *
+ * @see ViewPart#createPartControl
+ */
+ public void createPartControl(Composite frame) {
+ instance = new ControlExample(frame);
+ }
+
+ /**
+ * Called when we must grab focus.
+ *
+ * @see org.eclipse.ui.part.ViewPart#setFocus
+ */
+ public void setFocus() {
+ instance.setFocus();
+ }
+
+ /**
+ * Called when the View is to be disposed
+ */
+ public void dispose() {
+ instance.dispose();
+ instance = null;
+ super.dispose();
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.launcher/.project b/examples/org.eclipse.swt.examples.launcher/.project
index 3aa0f07860..bcb6941eaa 100644
--- a/examples/org.eclipse.swt.examples.launcher/.project
+++ b/examples/org.eclipse.swt.examples.launcher/.project
@@ -1,30 +1,30 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipse.swt.examples.launcher</name>
- <comment></comment>
- <projects>
- <project>org.eclipse.swt</project>
- <project>org.eclipse.swt.examples</project>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.swt.examples.launcher</name>
+ <comment></comment>
+ <projects>
+ <project>org.eclipse.swt</project>
+ <project>org.eclipse.swt.examples</project>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ </natures>
+</projectDescription>
diff --git a/examples/org.eclipse.swt.examples.launcher/build.properties b/examples/org.eclipse.swt.examples.launcher/build.properties
index 8d7ddf74e0..a5438fcbe1 100755
--- a/examples/org.eclipse.swt.examples.launcher/build.properties
+++ b/examples/org.eclipse.swt.examples.launcher/build.properties
@@ -1,12 +1,12 @@
-bin.includes = doc/,\
- doc-html/,\
- icons/,\
- schema/,\
- plugin.properties,\
- plugin.xml,\
- about.html,\
- *.jar
-
-src.includes = about.html
-
-source.launcher.jar = src/
+bin.includes = doc/,\
+ doc-html/,\
+ icons/,\
+ schema/,\
+ plugin.properties,\
+ plugin.xml,\
+ about.html,\
+ *.jar
+
+src.includes = about.html
+
+source.launcher.jar = src/
diff --git a/examples/org.eclipse.swt.examples.launcher/doc-html/hglegal2002.htm b/examples/org.eclipse.swt.examples.launcher/doc-html/hglegal2002.htm
index 74393f08f3..5df454d51a 100644
--- a/examples/org.eclipse.swt.examples.launcher/doc-html/hglegal2002.htm
+++ b/examples/org.eclipse.swt.examples.launcher/doc-html/hglegal2002.htm
@@ -1,14 +1,14 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
- <title>Legal Notices</title>
-</head>
-<body>
-
-<h3>
-<a NAME="Notices"></a>Notices</h3>
-(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
+ <title>Legal Notices</title>
+</head>
+<body>
+
+<h3>
+<a NAME="Notices"></a>Notices</h3>
+(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.launcher/doc-html/swt_launcher_ex.html b/examples/org.eclipse.swt.examples.launcher/doc-html/swt_launcher_ex.html
index 6ed28916dc..8e134ddd8c 100755
--- a/examples/org.eclipse.swt.examples.launcher/doc-html/swt_launcher_ex.html
+++ b/examples/org.eclipse.swt.examples.launcher/doc-html/swt_launcher_ex.html
@@ -1,45 +1,45 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Example Launcher</title>
-</head>
-<body>
-
-<h2>SWT Example Launcher</h2>
-
-<p>
-The Example Launcher is used to launch SWT examples which can either be Workbench Views,
-or Standalone applications.
-</p>
-
-<ul>
-<li>Workbench Views are examples that are integrated into Eclipse. When the Launcher
-starts a Workbench View, it is opened in the currently active perspective.
-<li>Standalone applications are launched in a separate window.
-</ul>
-
-<h3>Running the Example Launcher</h3>
-
-<p>
-From the Window menu, select Show View --> Other.
-In the Show View dialog, expand SWT Examples and select the SWT Example Launcher view.
-A view containing a list of examples will appear in your current perspective.
-Select an example from the list. A brief description of the example is displayed.
-Click on the Run button to launch the example.
-</p>
-
-
-<h3>Details</h3>
-<p>The example launcher view contains a tree list, a text area, and a button.
-The tree list contains a list of all the SWT examples you can choose
-to run. When an example is selected from the tree, the text area
-displays a short description of the example. The selected example can
-be launched by clicking on the Run button. Standalone examples are run in the
-same thread as the workbench's UI but they are not integrated into the perspective.
-The launcher invokes the <code>open()</code> method of the standalone example.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Example Launcher</title>
+</head>
+<body>
+
+<h2>SWT Example Launcher</h2>
+
+<p>
+The Example Launcher is used to launch SWT examples which can either be Workbench Views,
+or Standalone applications.
+</p>
+
+<ul>
+<li>Workbench Views are examples that are integrated into Eclipse. When the Launcher
+starts a Workbench View, it is opened in the currently active perspective.
+<li>Standalone applications are launched in a separate window.
+</ul>
+
+<h3>Running the Example Launcher</h3>
+
+<p>
+From the Window menu, select Show View --> Other.
+In the Show View dialog, expand SWT Examples and select the SWT Example Launcher view.
+A view containing a list of examples will appear in your current perspective.
+Select an example from the list. A brief description of the example is displayed.
+Click on the Run button to launch the example.
+</p>
+
+
+<h3>Details</h3>
+<p>The example launcher view contains a tree list, a text area, and a button.
+The tree list contains a list of all the SWT examples you can choose
+to run. When an example is selected from the tree, the text area
+displays a short description of the example. The selected example can
+be launched by clicking on the Run button. Standalone examples are run in the
+same thread as the workbench's UI but they are not integrated into the perspective.
+The launcher invokes the <code>open()</code> method of the standalone example.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.launcher/plugin.properties b/examples/org.eclipse.swt.examples.launcher/plugin.properties
index 05c328a5f7..28db6584d6 100755
--- a/examples/org.eclipse.swt.examples.launcher/plugin.properties
+++ b/examples/org.eclipse.swt.examples.launcher/plugin.properties
@@ -1,39 +1,39 @@
-providerName = Eclipse.org
-plugin.SWTLauncherExample.name = SWT Launcher Example Plugin
-category.SWTExamples.name = SWT Examples
-view.LauncherExample.name = SWT Example Launcher
-
-extension-point.launchItems.name = Launch Items
-
-launchcategory.SWTViewExamples.name = Workbench Views
-launchcategory.SWTViewExamples.description = \
- A collection of Standard Widget Toolkit examples that run as Views inside the Workbench. \
- These examples will create a new View in the current Perspective.
-
-launchitem.LauncherExample.name = Launcher
-launchitem.LauncherExample.description = \
- The Example Launcher is used to launch SWT examples which can either be \
- Workbench Views, or Standalone applications.\n\n\
- Workbench Views are examples that are integrated into Eclipse. When the Launcher \
- starts a Workbench View, it is opened in the currently active perspective.\n\n\
- Standalone applications are launched in a separate window.
-
-error.CouldNotLoadResources = Unable to load resources
-error.CouldNotFindRegisteredExtensions = Could Not Find Registered Extensions
-error.IncompleteProgramLaunchItem = Incomplete XML ProgramLaunchItem definition, id = {0}
-error.IncompleteViewLaunchItem = Incomplete XML ViewLaunchItem definition, id = {0}
-error.IncompleteLaunchItem = Incomplete or unrecognized XML LaunchItem definition, id = {0}
-
-launchitem.Null.description = <<no item selected>>
-
-launchitem.Missing.name = <<unnamed>>
-launchitem.Missing.description = <<no description available>>
-
-view.launchGroup.text = Examples
-view.launchButton.text = Run
-view.descriptionGroup.text = Description
-
-run.error.Invocation = A fatal error occurred while launching the program.
-run.error.DoesNotImplementMethod = The class does not implement the open() method.
-run.error.CouldNotFindClass = Could not find the class to run.
-run.error.CouldNotInstantiateClass = Could not instantiate the class to run.
+providerName = Eclipse.org
+plugin.SWTLauncherExample.name = SWT Launcher Example Plugin
+category.SWTExamples.name = SWT Examples
+view.LauncherExample.name = SWT Example Launcher
+
+extension-point.launchItems.name = Launch Items
+
+launchcategory.SWTViewExamples.name = Workbench Views
+launchcategory.SWTViewExamples.description = \
+ A collection of Standard Widget Toolkit examples that run as Views inside the Workbench. \
+ These examples will create a new View in the current Perspective.
+
+launchitem.LauncherExample.name = Launcher
+launchitem.LauncherExample.description = \
+ The Example Launcher is used to launch SWT examples which can either be \
+ Workbench Views, or Standalone applications.\n\n\
+ Workbench Views are examples that are integrated into Eclipse. When the Launcher \
+ starts a Workbench View, it is opened in the currently active perspective.\n\n\
+ Standalone applications are launched in a separate window.
+
+error.CouldNotLoadResources = Unable to load resources
+error.CouldNotFindRegisteredExtensions = Could Not Find Registered Extensions
+error.IncompleteProgramLaunchItem = Incomplete XML ProgramLaunchItem definition, id = {0}
+error.IncompleteViewLaunchItem = Incomplete XML ViewLaunchItem definition, id = {0}
+error.IncompleteLaunchItem = Incomplete or unrecognized XML LaunchItem definition, id = {0}
+
+launchitem.Null.description = <<no item selected>>
+
+launchitem.Missing.name = <<unnamed>>
+launchitem.Missing.description = <<no description available>>
+
+view.launchGroup.text = Examples
+view.launchButton.text = Run
+view.descriptionGroup.text = Description
+
+run.error.Invocation = A fatal error occurred while launching the program.
+run.error.DoesNotImplementMethod = The class does not implement the open() method.
+run.error.CouldNotFindClass = Could not find the class to run.
+run.error.CouldNotInstantiateClass = Could not instantiate the class to run.
diff --git a/examples/org.eclipse.swt.examples.launcher/plugin.xml b/examples/org.eclipse.swt.examples.launcher/plugin.xml
index 5f385382f3..3d7fbd737f 100755
--- a/examples/org.eclipse.swt.examples.launcher/plugin.xml
+++ b/examples/org.eclipse.swt.examples.launcher/plugin.xml
@@ -1,80 +1,80 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin
- id="org.eclipse.swt.examples.launcher"
- name="%plugin.SWTLauncherExample.name"
- version="2.1.0"
- provider-name="%providerName"
- class="org.eclipse.swt.examples.launcher.LauncherPlugin">
-
-<!-- Runtime -->
-<!-- Runtime -->
-<!-- Runtime -->
-<!-- Runtime -->
- <runtime>
- <library name="launcher.jar">
- <packages prefixes="org.eclipse.swt.examples.launcher"/>
- </library>
- </runtime>
-<!-- Required plugins -->
- <requires>
- <import plugin="org.eclipse.core.runtime"/>
- <import plugin="org.eclipse.core.resources"/>
- <import plugin="org.eclipse.ui"/>
- <import plugin="org.eclipse.swt"/>
- <import plugin="org.eclipse.jdt.launching"/>
- <import plugin="org.eclipse.debug.core"/>
- <import plugin="org.eclipse.core.boot"/>
- <import plugin="org.eclipse.jdt.core"/>
- <import plugin="org.eclipse.swt.examples"/>
- </requires>
-
-
-<!-- Extension points -->
- <extension-point id="launchItems" name="%extension-point.launchItems.name" schema="schema/org.eclipse.swt.examples.launcher.launchItems.exsd"/>
-
-<!-- Extensions -->
- <extension
- id="application"
- point="org.eclipse.core.runtime.applications">
- <application>
- <run
- name="%launchitem.LauncherApplication.name"
- class="org.eclipse.swt.examples.launcher.LauncherApplication">
- </run>
- </application>
- </extension>
- <extension
- point="org.eclipse.ui.views">
- <category
- name="%category.SWTExamples.name"
- id="org.eclipse.swt.examples.category">
- </category>
- <view
- name="%view.LauncherExample.name"
- icon="icons/launcher_example.gif"
- category="org.eclipse.swt.examples.category"
- class="org.eclipse.swt.examples.launcher.LauncherView"
- id="org.eclipse.swt.examples.launcher.view">
- </view>
- </extension>
- <extension
- point="org.eclipse.swt.examples.launcher.launchItems">
- <category
- name="%launchcategory.SWTViewExamples.name"
- description="%launchcategory.SWTViewExamples.description"
- id="org.eclipse.swt.examples.launchViewCategory">
- </category>
- <item
- name="%launchitem.LauncherExample.name"
- enabled="false"
- icon="icons/launcher_example.gif"
- description="%launchitem.LauncherExample.description"
- category="org.eclipse.swt.examples.launchViewCategory"
- id="org.eclipse.swt.examples.launcher.viewlauncher">
- <view
- viewId="org.eclipse.swt.examples.launcher.view">
- </view>
- </item>
- </extension>
-
-</plugin>
+<?xml version="1.0" encoding="UTF-8"?>
+<plugin
+ id="org.eclipse.swt.examples.launcher"
+ name="%plugin.SWTLauncherExample.name"
+ version="2.1.0"
+ provider-name="%providerName"
+ class="org.eclipse.swt.examples.launcher.LauncherPlugin">
+
+<!-- Runtime -->
+<!-- Runtime -->
+<!-- Runtime -->
+<!-- Runtime -->
+ <runtime>
+ <library name="launcher.jar">
+ <packages prefixes="org.eclipse.swt.examples.launcher"/>
+ </library>
+ </runtime>
+<!-- Required plugins -->
+ <requires>
+ <import plugin="org.eclipse.core.runtime"/>
+ <import plugin="org.eclipse.core.resources"/>
+ <import plugin="org.eclipse.ui"/>
+ <import plugin="org.eclipse.swt"/>
+ <import plugin="org.eclipse.jdt.launching"/>
+ <import plugin="org.eclipse.debug.core"/>
+ <import plugin="org.eclipse.core.boot"/>
+ <import plugin="org.eclipse.jdt.core"/>
+ <import plugin="org.eclipse.swt.examples"/>
+ </requires>
+
+
+<!-- Extension points -->
+ <extension-point id="launchItems" name="%extension-point.launchItems.name" schema="schema/org.eclipse.swt.examples.launcher.launchItems.exsd"/>
+
+<!-- Extensions -->
+ <extension
+ id="application"
+ point="org.eclipse.core.runtime.applications">
+ <application>
+ <run
+ name="%launchitem.LauncherApplication.name"
+ class="org.eclipse.swt.examples.launcher.LauncherApplication">
+ </run>
+ </application>
+ </extension>
+ <extension
+ point="org.eclipse.ui.views">
+ <category
+ name="%category.SWTExamples.name"
+ id="org.eclipse.swt.examples.category">
+ </category>
+ <view
+ name="%view.LauncherExample.name"
+ icon="icons/launcher_example.gif"
+ category="org.eclipse.swt.examples.category"
+ class="org.eclipse.swt.examples.launcher.LauncherView"
+ id="org.eclipse.swt.examples.launcher.view">
+ </view>
+ </extension>
+ <extension
+ point="org.eclipse.swt.examples.launcher.launchItems">
+ <category
+ name="%launchcategory.SWTViewExamples.name"
+ description="%launchcategory.SWTViewExamples.description"
+ id="org.eclipse.swt.examples.launchViewCategory">
+ </category>
+ <item
+ name="%launchitem.LauncherExample.name"
+ enabled="false"
+ icon="icons/launcher_example.gif"
+ description="%launchitem.LauncherExample.description"
+ category="org.eclipse.swt.examples.launchViewCategory"
+ id="org.eclipse.swt.examples.launcher.viewlauncher">
+ <view
+ viewId="org.eclipse.swt.examples.launcher.view">
+ </view>
+ </item>
+ </extension>
+
+</plugin>
diff --git a/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/ItemDescriptor.java b/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/ItemDescriptor.java
index 11ff9372b0..11ebb38e50 100755
--- a/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/ItemDescriptor.java
+++ b/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/ItemDescriptor.java
@@ -3,7 +3,7 @@ package org.eclipse.swt.examples.launcher; /* * Copyright (c) 2000, 2002 IBM C
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html */ import org.eclipse.swt.graphics.*;
/** * ItemDescriptor collects information about a launch item. */
-class ItemDescriptor {
+class ItemDescriptor {
private String id;
private String name;
private String description; private Image icon; private String view; private String mainType; private String pluginId;
diff --git a/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherPlugin.java b/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherPlugin.java
index 21a680140a..ed1b30cd3a 100755
--- a/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherPlugin.java
+++ b/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherPlugin.java
@@ -1,379 +1,379 @@
-package org.eclipse.swt.examples.launcher;
-
-/*
+package org.eclipse.swt.examples.launcher;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import java.io.*; import java.net.*; import java.text.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.swt.graphics.*; import org.eclipse.ui.plugin.*;
-
-/**
- * The main plugin class to be used in the desktop.
- */
-public class LauncherPlugin extends AbstractUIPlugin {
- //The shared instance.
- private static LauncherPlugin plugin;
- private static ResourceBundle resourceBundle;
-
- private static final String
- LAUNCH_ITEMS_POINT_ID = "org.eclipse.swt.examples.launcher.launchItems",
- LAUNCH_ITEMS_XML_CATEGORY = "category",
- LAUNCH_ITEMS_XML_ITEM = "item",
- LAUNCH_ITEMS_XML_ITEM_ICON = "icon",
- LAUNCH_ITEMS_XML_ITEM_DESCRIPTION = "description",
- LAUNCH_ITEMS_XML_PROGRAM = "program",
- LAUNCH_ITEMS_XML_PROGRAM_PLUGIN = "pluginId",
- LAUNCH_ITEMS_XML_PROGRAM_CLASS = "mainClass",
- LAUNCH_ITEMS_XML_VIEW = "view",
- LAUNCH_ITEMS_XML_VIEW_VIEWID = "viewId",
- LAUNCH_ITEMS_XML_ATTRIB_ID = "id",
- LAUNCH_ITEMS_XML_ATTRIB_NAME = "name",
- LAUNCH_ITEMS_XML_ATTRIB_ENABLED = "enabled",
- LAUNCH_ITEMS_XML_ATTRIB_CATEGORY = "category",
- LAUNCH_ITEMS_XML_VALUE_TRUE = "true",
- LAUNCH_ITEMS_XML_VALUE_FALSE = "false";
-
- static final int
- liClosedFolder = 0,
- liOpenFolder = 1,
- liGenericExample = 2;
- static final String[] imageLocations = {
- "icons/closedFolder.gif",
- "icons/openFolder.gif",
- "icons/generic_example.gif" };
- static Image images[];
-
- /**
- * Constructs the LauncherPlugin.
- */
- public LauncherPlugin(IPluginDescriptor descriptor) {
- super(descriptor);
- plugin = this;
- resourceBundle = descriptor.getResourceBundle();
- }
-
- /**
- * Clean up
- */
- public void shutdown() throws CoreException {
- super.shutdown();
- freeResources();
- }
-
- /**
- * Returns the shared instance.
- */
- public static LauncherPlugin getDefault() {
- return plugin;
- }
-
- /**
- * Loads the resources
- */
- public static void initResources() {
- if (images == null) {
- images = new Image[imageLocations.length];
-
- for (int i = 0; i < imageLocations.length; ++i) {
- images[i] = getImageFromPlugin(plugin.getDescriptor(), imageLocations[i]);
- if (images[i] == null) {
- freeResources();
- logError(getResourceString("error.CouldNotLoadResources"), null);
- throw new IllegalStateException();
- }
- }
- }
- }
-
- /**
- * Frees the resources
- */
- public static void freeResources() {
- if (images != null) {
- for (int i = 0; i < images.length; ++i) {
- final Image image = images[i];
- if (image != null) image.dispose();
- }
- images = null;
- }
- }
-
- /**
- * Log an error to the ILog for this plugin
- *
- * @param message the localized error message text
- * @param exception the associated exception, or null
- */
- public static void logError(String message, Throwable exception) {
- plugin.getLog().log(new Status(IStatus.ERROR, plugin.getDescriptor().getUniqueIdentifier(),
- 0, message, exception));
- }
-
- /**
- * Returns a string from the resource bundle.
- * We don't want to crash because of a missing String.
- * Returns the key if not found.
- */
- public static String getResourceString(String key) {
- try {
- return resourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Returns a string from the resource bundle and binds it
- * with the given arguments. If the key is not found,
- * return the key.
- */
- public static String getResourceString(String key, Object[] args) {
- try {
- return MessageFormat.format(getResourceString(key), args);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Constructs a list of available programs from registered extensions.
- *
- * @return an ItemTreeNode representing the root of a tree of items (the root is not to be displayed)
- */
- public static ItemTreeNode getLaunchItemTree() {
- ItemTreeNode categoryTree =
- new ItemTreeNode(new ItemDescriptor("<<Root>>", "<<Root>>", null, null, null, null, null));
-
- // get the platform's public plugin registry
- IPluginRegistry pluginRegistry = Platform.getPluginRegistry();
- // retrieve all configuration elements registered at our launchItems extension-point
- IConfigurationElement[] configurationElements =
- pluginRegistry.getConfigurationElementsFor(LAUNCH_ITEMS_POINT_ID);
-
- if (configurationElements == null || configurationElements.length == 0) {
- logError(getResourceString("error.CouldNotFindRegisteredExtensions"), null);
- return categoryTree;
- }
-
- /* Collect all launch categories -- coalesce those with same ID */
- HashMap idMap = new HashMap();
- for (int i = 0; i < configurationElements.length; ++i) {
- final IConfigurationElement ce = configurationElements[i];
- final String ceName = ce.getName();
- final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);
-
- if (idMap.containsKey(attribId)) continue;
- if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
- final String attribName = getItemName(ce);
- ItemDescriptor theDescriptor = new ItemDescriptor(attribId, attribName,
- getItemDescription(ce), null, null, null, null);
- idMap.put(attribId, new ItemTreeNode(theDescriptor));
- }
- }
-
- /* Generate launch category hierarchy */
- Set tempIdSet = new HashSet(); // used to prevent duplicates from being entered into the tree
- for (int i = 0; i < configurationElements.length; ++i) {
- final IConfigurationElement ce = configurationElements[i];
- final String ceName = ce.getName();
- final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);
-
- if (tempIdSet.contains(attribId)) continue;
- if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
- final ItemTreeNode theNode = (ItemTreeNode) idMap.get(attribId);
- addItemByCategory(ce, categoryTree, theNode, idMap);
- tempIdSet.add(attribId);
- }
- }
-
- /* Generate program tree */
- for (int i = 0; i < configurationElements.length; ++i) {
- final IConfigurationElement ce = configurationElements[i];
- final String ceName = ce.getName();
- final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);
-
- if (idMap.containsKey(attribId)) continue;
- if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
- // ignore
- } else if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_ITEM)) {
- final String enabled = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ENABLED,
- LAUNCH_ITEMS_XML_VALUE_TRUE);
- if (enabled.equalsIgnoreCase(LAUNCH_ITEMS_XML_VALUE_FALSE)) continue;
- ItemDescriptor theDescriptor = createItemDescriptor(ce, attribId);
-
- if (theDescriptor != null) {
- final ItemTreeNode theNode = new ItemTreeNode(theDescriptor);
- addItemByCategory(ce, categoryTree, theNode, idMap);
- idMap.put(attribId, theNode);
- }
- }
- }
- return categoryTree;
- }
-
-
- /**
- * Adds an item to the category tree.
- */
- private static void addItemByCategory(IConfigurationElement ce, ItemTreeNode root,
- ItemTreeNode theNode, HashMap idMap) {
- final String attribCategory = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_CATEGORY, null);
-
- // locate the parent node
- ItemTreeNode parentNode = null;
- if (attribCategory != null) {
- parentNode = (ItemTreeNode) idMap.get(attribCategory);
- }
- if (parentNode == null) parentNode = root;
-
- // add the item
- parentNode.addSortedNode(theNode);
- }
-
- /**
- * Creates an ItemDescriptor from an XML definition.
- *
- * @param ce the IConfigurationElement describing the item
- * @param attribId the attribute id
- * @return a new ItemDescriptor, or null if an error occurs
- */
- private static ItemDescriptor createItemDescriptor(IConfigurationElement ce, String attribId) {
- final String attribName = getItemName(ce);
- final Image attribIcon = getItemIcon(ce);
- final String attribDescription = getItemDescription(ce);
-
- IConfigurationElement viewCE = getItemElement(ce, LAUNCH_ITEMS_XML_VIEW);
- if (viewCE != null) {
- //Item is a view
- final String attribView = getItemAttribute(viewCE, LAUNCH_ITEMS_XML_VIEW_VIEWID, null);
- if (attribView == null) {
- logError(getResourceString("error.IncompleteViewLaunchItem",
- new Object[] { attribId } ), null);
- return null;
- }
- return new ItemDescriptor(attribId, attribName, attribDescription,
- attribIcon, attribView, null, null);
- } else {
- //Item is a standalone
- IConfigurationElement programCE = getItemElement(ce, LAUNCH_ITEMS_XML_PROGRAM);
- if (programCE != null) {
- final String attribPluginId = getItemAttribute(programCE, LAUNCH_ITEMS_XML_PROGRAM_PLUGIN, null);
- final String attribClass = getItemAttribute(programCE, LAUNCH_ITEMS_XML_PROGRAM_CLASS, null);
- if (attribClass == null || attribPluginId == null) {
- logError(getResourceString("error.IncompleteProgramLaunchItem",
- new Object[] { attribId } ), null);
- return null;
- }
- return new ItemDescriptor(attribId, attribName, attribDescription,
- attribIcon, null, attribClass, attribPluginId);
- } else {
- logError(getResourceString("error.IncompleteLaunchItem",
- new Object[] { attribId } ), null);
- return null;
- }
- }
- }
-
- /**
- * Returns the first instance of a particular child XML element.
- *
- * @param ce the IConfigurationElement parent
- * @param element the name of the element to fetch
- * @return the element's IConfigurationElement, or null if not found
- */
- private static IConfigurationElement getItemElement(IConfigurationElement ce, String element) {
- IConfigurationElement[] elementCEs = ce.getChildren(element);
- return (elementCEs != null && elementCEs.length != 0) ? elementCEs[0] : null;
- }
-
- /**
- * Returns the value of an XML attribute for an item.
- *
- * @param ce the IConfigurationElement describing the item
- * @param attribute the attribute to fetch
- * @param defaultValue the value to return if the attribute is not found
- * @return the attribute value
- */
- private static String getItemAttribute(IConfigurationElement ce, String attribute, String defaultValue) {
- String value = ce.getAttribute(attribute);
- return (value != null) ? value : defaultValue;
- }
-
- /**
- * Returns the description string given the IConfigurationElement for an item.
- *
- * @param ce the IConfigurationElement describing the item
- * @return a newline-delimited string that describes this item, or null if none
- */
- private static String getItemDescription(IConfigurationElement ce) {
- String description = getItemAttribute(ce, LAUNCH_ITEMS_XML_ITEM_DESCRIPTION, "");
- return (description.length() == 0) ? null : description;
- }
-
- /**
- * Returns the name of an item.
- *
- * @param ce the IConfigurationElement describing the item
- * @return the attribute value
- */
- private static String getItemName(IConfigurationElement ce) {
- return getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_NAME,
- getResourceString("launchitem.Missing.name"));
- }
-
-
- /**
- * Returns the icon for an item.
- *
- * @param ce the IConfigurationElement describing the item
- * @return an icon
- */
- private static Image getItemIcon(IConfigurationElement ce) {
- String iconPath = getItemAttribute(ce, LAUNCH_ITEMS_XML_ITEM_ICON, "");
- if (iconPath.length() != 0) {
- Image icon = getImageFromPlugin(ce.getDeclaringExtension().getDeclaringPluginDescriptor(),
- iconPath);
- if (icon != null) {
- Image[] newImages = new Image[images.length + 1];
- System.arraycopy(images, 0, newImages, 0, images.length);
- newImages[images.length] = icon;
- images = newImages;
- return icon;
- }
- }
- return images[liGenericExample];
- }
-
- /**
- * Gets an image from a path relative to the plugin install directory.
- *
- * @param pd the plugin descriptor for the plugin with the image
- * @param iconPath the path relative to the install directory
- * @return the image, or null if not found
- */
- private static Image getImageFromPlugin(IPluginDescriptor pd, String iconPath) {
- InputStream is = null;
- try {
- URL installUrl = pd.getInstallURL();
- URL url = new URL(installUrl, iconPath);
- is = url.openConnection().getInputStream();
- ImageData source = new ImageData(is);
- ImageData mask = source.getTransparencyMask();
- Image image = new Image(null, source, mask);
- return image;
- } catch (Throwable ex) {
- return null;
- } finally {
- try {
- if (is != null) is.close();
- } catch (IOException e) {
- }
- }
- }
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import java.io.*; import java.net.*; import java.text.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.swt.graphics.*; import org.eclipse.ui.plugin.*;
+
+/**
+ * The main plugin class to be used in the desktop.
+ */
+public class LauncherPlugin extends AbstractUIPlugin {
+ //The shared instance.
+ private static LauncherPlugin plugin;
+ private static ResourceBundle resourceBundle;
+
+ private static final String
+ LAUNCH_ITEMS_POINT_ID = "org.eclipse.swt.examples.launcher.launchItems",
+ LAUNCH_ITEMS_XML_CATEGORY = "category",
+ LAUNCH_ITEMS_XML_ITEM = "item",
+ LAUNCH_ITEMS_XML_ITEM_ICON = "icon",
+ LAUNCH_ITEMS_XML_ITEM_DESCRIPTION = "description",
+ LAUNCH_ITEMS_XML_PROGRAM = "program",
+ LAUNCH_ITEMS_XML_PROGRAM_PLUGIN = "pluginId",
+ LAUNCH_ITEMS_XML_PROGRAM_CLASS = "mainClass",
+ LAUNCH_ITEMS_XML_VIEW = "view",
+ LAUNCH_ITEMS_XML_VIEW_VIEWID = "viewId",
+ LAUNCH_ITEMS_XML_ATTRIB_ID = "id",
+ LAUNCH_ITEMS_XML_ATTRIB_NAME = "name",
+ LAUNCH_ITEMS_XML_ATTRIB_ENABLED = "enabled",
+ LAUNCH_ITEMS_XML_ATTRIB_CATEGORY = "category",
+ LAUNCH_ITEMS_XML_VALUE_TRUE = "true",
+ LAUNCH_ITEMS_XML_VALUE_FALSE = "false";
+
+ static final int
+ liClosedFolder = 0,
+ liOpenFolder = 1,
+ liGenericExample = 2;
+ static final String[] imageLocations = {
+ "icons/closedFolder.gif",
+ "icons/openFolder.gif",
+ "icons/generic_example.gif" };
+ static Image images[];
+
+ /**
+ * Constructs the LauncherPlugin.
+ */
+ public LauncherPlugin(IPluginDescriptor descriptor) {
+ super(descriptor);
+ plugin = this;
+ resourceBundle = descriptor.getResourceBundle();
+ }
+
+ /**
+ * Clean up
+ */
+ public void shutdown() throws CoreException {
+ super.shutdown();
+ freeResources();
+ }
+
+ /**
+ * Returns the shared instance.
+ */
+ public static LauncherPlugin getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Loads the resources
+ */
+ public static void initResources() {
+ if (images == null) {
+ images = new Image[imageLocations.length];
+
+ for (int i = 0; i < imageLocations.length; ++i) {
+ images[i] = getImageFromPlugin(plugin.getDescriptor(), imageLocations[i]);
+ if (images[i] == null) {
+ freeResources();
+ logError(getResourceString("error.CouldNotLoadResources"), null);
+ throw new IllegalStateException();
+ }
+ }
+ }
+ }
+
+ /**
+ * Frees the resources
+ */
+ public static void freeResources() {
+ if (images != null) {
+ for (int i = 0; i < images.length; ++i) {
+ final Image image = images[i];
+ if (image != null) image.dispose();
+ }
+ images = null;
+ }
+ }
+
+ /**
+ * Log an error to the ILog for this plugin
+ *
+ * @param message the localized error message text
+ * @param exception the associated exception, or null
+ */
+ public static void logError(String message, Throwable exception) {
+ plugin.getLog().log(new Status(IStatus.ERROR, plugin.getDescriptor().getUniqueIdentifier(),
+ 0, message, exception));
+ }
+
+ /**
+ * Returns a string from the resource bundle.
+ * We don't want to crash because of a missing String.
+ * Returns the key if not found.
+ */
+ public static String getResourceString(String key) {
+ try {
+ return resourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Returns a string from the resource bundle and binds it
+ * with the given arguments. If the key is not found,
+ * return the key.
+ */
+ public static String getResourceString(String key, Object[] args) {
+ try {
+ return MessageFormat.format(getResourceString(key), args);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Constructs a list of available programs from registered extensions.
+ *
+ * @return an ItemTreeNode representing the root of a tree of items (the root is not to be displayed)
+ */
+ public static ItemTreeNode getLaunchItemTree() {
+ ItemTreeNode categoryTree =
+ new ItemTreeNode(new ItemDescriptor("<<Root>>", "<<Root>>", null, null, null, null, null));
+
+ // get the platform's public plugin registry
+ IPluginRegistry pluginRegistry = Platform.getPluginRegistry();
+ // retrieve all configuration elements registered at our launchItems extension-point
+ IConfigurationElement[] configurationElements =
+ pluginRegistry.getConfigurationElementsFor(LAUNCH_ITEMS_POINT_ID);
+
+ if (configurationElements == null || configurationElements.length == 0) {
+ logError(getResourceString("error.CouldNotFindRegisteredExtensions"), null);
+ return categoryTree;
+ }
+
+ /* Collect all launch categories -- coalesce those with same ID */
+ HashMap idMap = new HashMap();
+ for (int i = 0; i < configurationElements.length; ++i) {
+ final IConfigurationElement ce = configurationElements[i];
+ final String ceName = ce.getName();
+ final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);
+
+ if (idMap.containsKey(attribId)) continue;
+ if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
+ final String attribName = getItemName(ce);
+ ItemDescriptor theDescriptor = new ItemDescriptor(attribId, attribName,
+ getItemDescription(ce), null, null, null, null);
+ idMap.put(attribId, new ItemTreeNode(theDescriptor));
+ }
+ }
+
+ /* Generate launch category hierarchy */
+ Set tempIdSet = new HashSet(); // used to prevent duplicates from being entered into the tree
+ for (int i = 0; i < configurationElements.length; ++i) {
+ final IConfigurationElement ce = configurationElements[i];
+ final String ceName = ce.getName();
+ final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);
+
+ if (tempIdSet.contains(attribId)) continue;
+ if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
+ final ItemTreeNode theNode = (ItemTreeNode) idMap.get(attribId);
+ addItemByCategory(ce, categoryTree, theNode, idMap);
+ tempIdSet.add(attribId);
+ }
+ }
+
+ /* Generate program tree */
+ for (int i = 0; i < configurationElements.length; ++i) {
+ final IConfigurationElement ce = configurationElements[i];
+ final String ceName = ce.getName();
+ final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);
+
+ if (idMap.containsKey(attribId)) continue;
+ if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
+ // ignore
+ } else if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_ITEM)) {
+ final String enabled = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ENABLED,
+ LAUNCH_ITEMS_XML_VALUE_TRUE);
+ if (enabled.equalsIgnoreCase(LAUNCH_ITEMS_XML_VALUE_FALSE)) continue;
+ ItemDescriptor theDescriptor = createItemDescriptor(ce, attribId);
+
+ if (theDescriptor != null) {
+ final ItemTreeNode theNode = new ItemTreeNode(theDescriptor);
+ addItemByCategory(ce, categoryTree, theNode, idMap);
+ idMap.put(attribId, theNode);
+ }
+ }
+ }
+ return categoryTree;
+ }
+
+
+ /**
+ * Adds an item to the category tree.
+ */
+ private static void addItemByCategory(IConfigurationElement ce, ItemTreeNode root,
+ ItemTreeNode theNode, HashMap idMap) {
+ final String attribCategory = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_CATEGORY, null);
+
+ // locate the parent node
+ ItemTreeNode parentNode = null;
+ if (attribCategory != null) {
+ parentNode = (ItemTreeNode) idMap.get(attribCategory);
+ }
+ if (parentNode == null) parentNode = root;
+
+ // add the item
+ parentNode.addSortedNode(theNode);
+ }
+
+ /**
+ * Creates an ItemDescriptor from an XML definition.
+ *
+ * @param ce the IConfigurationElement describing the item
+ * @param attribId the attribute id
+ * @return a new ItemDescriptor, or null if an error occurs
+ */
+ private static ItemDescriptor createItemDescriptor(IConfigurationElement ce, String attribId) {
+ final String attribName = getItemName(ce);
+ final Image attribIcon = getItemIcon(ce);
+ final String attribDescription = getItemDescription(ce);
+
+ IConfigurationElement viewCE = getItemElement(ce, LAUNCH_ITEMS_XML_VIEW);
+ if (viewCE != null) {
+ //Item is a view
+ final String attribView = getItemAttribute(viewCE, LAUNCH_ITEMS_XML_VIEW_VIEWID, null);
+ if (attribView == null) {
+ logError(getResourceString("error.IncompleteViewLaunchItem",
+ new Object[] { attribId } ), null);
+ return null;
+ }
+ return new ItemDescriptor(attribId, attribName, attribDescription,
+ attribIcon, attribView, null, null);
+ } else {
+ //Item is a standalone
+ IConfigurationElement programCE = getItemElement(ce, LAUNCH_ITEMS_XML_PROGRAM);
+ if (programCE != null) {
+ final String attribPluginId = getItemAttribute(programCE, LAUNCH_ITEMS_XML_PROGRAM_PLUGIN, null);
+ final String attribClass = getItemAttribute(programCE, LAUNCH_ITEMS_XML_PROGRAM_CLASS, null);
+ if (attribClass == null || attribPluginId == null) {
+ logError(getResourceString("error.IncompleteProgramLaunchItem",
+ new Object[] { attribId } ), null);
+ return null;
+ }
+ return new ItemDescriptor(attribId, attribName, attribDescription,
+ attribIcon, null, attribClass, attribPluginId);
+ } else {
+ logError(getResourceString("error.IncompleteLaunchItem",
+ new Object[] { attribId } ), null);
+ return null;
+ }
+ }
+ }
+
+ /**
+ * Returns the first instance of a particular child XML element.
+ *
+ * @param ce the IConfigurationElement parent
+ * @param element the name of the element to fetch
+ * @return the element's IConfigurationElement, or null if not found
+ */
+ private static IConfigurationElement getItemElement(IConfigurationElement ce, String element) {
+ IConfigurationElement[] elementCEs = ce.getChildren(element);
+ return (elementCEs != null && elementCEs.length != 0) ? elementCEs[0] : null;
+ }
+
+ /**
+ * Returns the value of an XML attribute for an item.
+ *
+ * @param ce the IConfigurationElement describing the item
+ * @param attribute the attribute to fetch
+ * @param defaultValue the value to return if the attribute is not found
+ * @return the attribute value
+ */
+ private static String getItemAttribute(IConfigurationElement ce, String attribute, String defaultValue) {
+ String value = ce.getAttribute(attribute);
+ return (value != null) ? value : defaultValue;
+ }
+
+ /**
+ * Returns the description string given the IConfigurationElement for an item.
+ *
+ * @param ce the IConfigurationElement describing the item
+ * @return a newline-delimited string that describes this item, or null if none
+ */
+ private static String getItemDescription(IConfigurationElement ce) {
+ String description = getItemAttribute(ce, LAUNCH_ITEMS_XML_ITEM_DESCRIPTION, "");
+ return (description.length() == 0) ? null : description;
+ }
+
+ /**
+ * Returns the name of an item.
+ *
+ * @param ce the IConfigurationElement describing the item
+ * @return the attribute value
+ */
+ private static String getItemName(IConfigurationElement ce) {
+ return getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_NAME,
+ getResourceString("launchitem.Missing.name"));
+ }
+
+
+ /**
+ * Returns the icon for an item.
+ *
+ * @param ce the IConfigurationElement describing the item
+ * @return an icon
+ */
+ private static Image getItemIcon(IConfigurationElement ce) {
+ String iconPath = getItemAttribute(ce, LAUNCH_ITEMS_XML_ITEM_ICON, "");
+ if (iconPath.length() != 0) {
+ Image icon = getImageFromPlugin(ce.getDeclaringExtension().getDeclaringPluginDescriptor(),
+ iconPath);
+ if (icon != null) {
+ Image[] newImages = new Image[images.length + 1];
+ System.arraycopy(images, 0, newImages, 0, images.length);
+ newImages[images.length] = icon;
+ images = newImages;
+ return icon;
+ }
+ }
+ return images[liGenericExample];
+ }
+
+ /**
+ * Gets an image from a path relative to the plugin install directory.
+ *
+ * @param pd the plugin descriptor for the plugin with the image
+ * @param iconPath the path relative to the install directory
+ * @return the image, or null if not found
+ */
+ private static Image getImageFromPlugin(IPluginDescriptor pd, String iconPath) {
+ InputStream is = null;
+ try {
+ URL installUrl = pd.getInstallURL();
+ URL url = new URL(installUrl, iconPath);
+ is = url.openConnection().getInputStream();
+ ImageData source = new ImageData(is);
+ ImageData mask = source.getTransparencyMask();
+ Image image = new Image(null, source, mask);
+ return image;
+ } catch (Throwable ex) {
+ return null;
+ } finally {
+ try {
+ if (is != null) is.close();
+ } catch (IOException e) {
+ }
+ }
+ }
} \ No newline at end of file
diff --git a/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherView.java b/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherView.java
index 8177538056..33beeee555 100755
--- a/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherView.java
+++ b/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/LauncherView.java
@@ -1,229 +1,229 @@
-package org.eclipse.swt.examples.launcher;
-
-/*
+package org.eclipse.swt.examples.launcher;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.ui.*;
-import org.eclipse.ui.part.*;
-import java.lang.reflect.*;
-
-/**
- * Launcher uses <code>org.eclipse.swt</code>
- * to launch the other registered examples.
- *
- * @see ViewPart
- */
-public class LauncherView extends ViewPart {
- private Shell workbenchShell;
-
- private Tree launchTree;
- private Text descriptionText;
- private Button runButton;
-
- /**
- * Constructs a LauncherView.
- */
- public LauncherView() {
- LauncherPlugin.initResources();
- }
-
- /**
- * Creates the example.
- *
- * @see ViewPart#createPartControl
- */
- public void createPartControl(Composite parent) {
- workbenchShell = getSite().getShell();
- parent.setLayout(new SplitLayout());
-
- Group launchGroup = new Group(parent, SWT.NULL);
- launchGroup.setText(LauncherPlugin.getResourceString("view.launchGroup.text"));
-
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 2;
- launchGroup.setLayout(gridLayout);
-
- launchTree = new Tree(launchGroup, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
- GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
- gridData.horizontalSpan = 2;
- launchTree.setLayoutData(gridData);
- launchTree.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent event) {
- final ItemDescriptor item = getSelectedItem();
- setDescriptionByItem(item);
- }
- public void widgetDefaultSelected(SelectionEvent event) {
- final ItemDescriptor item = getSelectedItem();
- setDescriptionByItem(item);
- launchItem(getSelectedItem());
- }
- });
- launchTree.addTreeListener(new TreeListener() {
- public void treeCollapsed(TreeEvent event) {
- final TreeItem item = (TreeItem) event.item;
- if (item == null) return;
- item.setImage(LauncherPlugin.images[LauncherPlugin.liClosedFolder]);
- }
- public void treeExpanded(TreeEvent event) {
- final TreeItem item = (TreeItem) event.item;
- if (item == null) return;
- item.setImage(LauncherPlugin.images[LauncherPlugin.liOpenFolder]);
- }
- });
-
- runButton = new Button(launchGroup, SWT.PUSH);
- runButton.setText(LauncherPlugin.getResourceString("view.launchButton.text"));
- runButton.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent event) {
- launchItem(getSelectedItem());
- }
- public void widgetDefaultSelected(SelectionEvent event) {
- }
- });
-
- Group descriptionGroup = new Group(parent, SWT.NULL);
- descriptionGroup.setText(LauncherPlugin.getResourceString("view.descriptionGroup.text"));
- descriptionGroup.setLayout(new FillLayout());
-
- descriptionText = new Text(descriptionGroup, SWT.MULTI | SWT.BORDER |
- SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY);
-
- setDescriptionByItem(null);
- setItemDescriptors(LauncherPlugin.getLaunchItemTree());
- }
-
- /**
- * Called when we must grab focus.
- *
- * @see org.eclipse.ui.part.ViewPart#setFocus
- */
- public void setFocus() {
- launchTree.setFocus();
- runButton.getShell().setDefaultButton(runButton);
- }
-
- /**
- * Called when the View is to be disposed
- */
- public void dispose() {
- workbenchShell = null;
- launchTree = null;
- descriptionText = null;
- runButton = null;
- super.dispose();
- }
-
- /**
- * Installs a new launch list.
- *
- * @param newRoot the new tree of launch items for the UI
- */
- public void setItemDescriptors(final ItemTreeNode newRoot) {
- if (workbenchShell == null) return;
- workbenchShell.getDisplay().syncExec(new Runnable() {
- public void run() {
- if ((launchTree == null) || (launchTree.isDisposed())) return;
- launchTree.removeAll();
-
- for (ItemTreeNode node = newRoot.getFirstChild(); node != null;
- node = node.getNextSibling()) {
- doNode(node, new TreeItem(launchTree, SWT.NONE)); // top-level TreeItem
- }
- }
- private void addGroup(TreeItem parent, ItemTreeNode node) {
- for (;node != null; node = node.getNextSibling()) {
- doNode(node, new TreeItem(parent, SWT.NONE)); // TreeItem at depth > 0
- }
- }
- private void doNode(ItemTreeNode node, TreeItem treeItem) {
- final ItemDescriptor item = node.getDescriptor();
- treeItem.setText(item.getName());
- treeItem.setData(item);
- if (node.getDescriptor().isFolder()) {
- treeItem.setExpanded(false);
- treeItem.setImage(LauncherPlugin.images[LauncherPlugin.liClosedFolder]);
- } else {
- treeItem.setImage(node.getDescriptor().getIcon());
- }
- addGroup(treeItem, node.getFirstChild());
- }
- });
- }
-
- /**
- * Runs the specified launch item.
- *
- * @param itemDescriptor the launch item to execute
- */
- private void launchItem(ItemDescriptor itemDescriptor) {
- /* Case 1: The launch item is a view */
- String pluginViewId = itemDescriptor.getView ();
- if (pluginViewId != null) {
- final IWorkbenchPart workbenchPart = this;
- final IWorkbenchPartSite workbenchPartSite = workbenchPart.getSite();
- final IWorkbenchPage workbenchPage = workbenchPartSite.getPage();
- try {
- workbenchPage.showView(pluginViewId);
- } catch (PartInitException e) {
- LauncherPlugin.logError(LauncherPlugin.getResourceString("run.error.Invocation"), e);
- }
- return;
- }
- /* Case 2: The launch item is a standalone program */
- if (workbenchShell == null) return;
- try {
- Class cl = Class.forName(itemDescriptor.getMainType());
- Display display = workbenchShell.getDisplay();
- Object exampleInstance = cl.newInstance();
- Method openMethod = cl.getDeclaredMethod("open", new Class[] {Display.class});
- openMethod.invoke(exampleInstance, new Object[] {display});
- } catch (NoSuchMethodException e) {
- LauncherPlugin.logError(LauncherPlugin.getResourceString("run.error.DoesNotImplementMethod"), null);
- } catch (ClassNotFoundException e) {
- LauncherPlugin.logError(LauncherPlugin.getResourceString("run.error.CouldNotFindClass"), e);
- } catch (Exception e) {
- LauncherPlugin.logError(LauncherPlugin.getResourceString("run.error.CouldNotInstantiateClass"), e);
- }
- }
-
- /**
- * Obtains the selected launch item.
- *
- * @return the currently selected ItemDescriptor
- */
- private ItemDescriptor getSelectedItem() {
- final TreeItem[] selections = launchTree.getSelection();
- if (selections.length == 0) return null;
- final ItemDescriptor itemDescriptor = (ItemDescriptor) selections[0].getData();
- return itemDescriptor;
- }
-
- /**
- * Sets the currently visible description text to reflect that of a particular ItemDescriptor.
- *
- * @param itemDescriptor the launch item whose description is to be displayed, or null if none
- */
- private void setDescriptionByItem(ItemDescriptor itemDescriptor) {
- String description;
- if (itemDescriptor == null) {
- description = LauncherPlugin.getResourceString("launchitem.Null.description");
- if (runButton != null) runButton.setEnabled(false);
- } else {
- description = itemDescriptor.getDescription();
- if (description == null)
- description = LauncherPlugin.getResourceString("launchitem.Missing.description");
- if (runButton != null) {
- runButton.setEnabled(itemDescriptor.getView() != null || itemDescriptor.getMainType() != null);
- }
- }
- descriptionText.setText(description);
- }
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.ui.*;
+import org.eclipse.ui.part.*;
+import java.lang.reflect.*;
+
+/**
+ * Launcher uses <code>org.eclipse.swt</code>
+ * to launch the other registered examples.
+ *
+ * @see ViewPart
+ */
+public class LauncherView extends ViewPart {
+ private Shell workbenchShell;
+
+ private Tree launchTree;
+ private Text descriptionText;
+ private Button runButton;
+
+ /**
+ * Constructs a LauncherView.
+ */
+ public LauncherView() {
+ LauncherPlugin.initResources();
+ }
+
+ /**
+ * Creates the example.
+ *
+ * @see ViewPart#createPartControl
+ */
+ public void createPartControl(Composite parent) {
+ workbenchShell = getSite().getShell();
+ parent.setLayout(new SplitLayout());
+
+ Group launchGroup = new Group(parent, SWT.NULL);
+ launchGroup.setText(LauncherPlugin.getResourceString("view.launchGroup.text"));
+
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 2;
+ launchGroup.setLayout(gridLayout);
+
+ launchTree = new Tree(launchGroup, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
+ GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
+ gridData.horizontalSpan = 2;
+ launchTree.setLayoutData(gridData);
+ launchTree.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent event) {
+ final ItemDescriptor item = getSelectedItem();
+ setDescriptionByItem(item);
+ }
+ public void widgetDefaultSelected(SelectionEvent event) {
+ final ItemDescriptor item = getSelectedItem();
+ setDescriptionByItem(item);
+ launchItem(getSelectedItem());
+ }
+ });
+ launchTree.addTreeListener(new TreeListener() {
+ public void treeCollapsed(TreeEvent event) {
+ final TreeItem item = (TreeItem) event.item;
+ if (item == null) return;
+ item.setImage(LauncherPlugin.images[LauncherPlugin.liClosedFolder]);
+ }
+ public void treeExpanded(TreeEvent event) {
+ final TreeItem item = (TreeItem) event.item;
+ if (item == null) return;
+ item.setImage(LauncherPlugin.images[LauncherPlugin.liOpenFolder]);
+ }
+ });
+
+ runButton = new Button(launchGroup, SWT.PUSH);
+ runButton.setText(LauncherPlugin.getResourceString("view.launchButton.text"));
+ runButton.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent event) {
+ launchItem(getSelectedItem());
+ }
+ public void widgetDefaultSelected(SelectionEvent event) {
+ }
+ });
+
+ Group descriptionGroup = new Group(parent, SWT.NULL);
+ descriptionGroup.setText(LauncherPlugin.getResourceString("view.descriptionGroup.text"));
+ descriptionGroup.setLayout(new FillLayout());
+
+ descriptionText = new Text(descriptionGroup, SWT.MULTI | SWT.BORDER |
+ SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY);
+
+ setDescriptionByItem(null);
+ setItemDescriptors(LauncherPlugin.getLaunchItemTree());
+ }
+
+ /**
+ * Called when we must grab focus.
+ *
+ * @see org.eclipse.ui.part.ViewPart#setFocus
+ */
+ public void setFocus() {
+ launchTree.setFocus();
+ runButton.getShell().setDefaultButton(runButton);
+ }
+
+ /**
+ * Called when the View is to be disposed
+ */
+ public void dispose() {
+ workbenchShell = null;
+ launchTree = null;
+ descriptionText = null;
+ runButton = null;
+ super.dispose();
+ }
+
+ /**
+ * Installs a new launch list.
+ *
+ * @param newRoot the new tree of launch items for the UI
+ */
+ public void setItemDescriptors(final ItemTreeNode newRoot) {
+ if (workbenchShell == null) return;
+ workbenchShell.getDisplay().syncExec(new Runnable() {
+ public void run() {
+ if ((launchTree == null) || (launchTree.isDisposed())) return;
+ launchTree.removeAll();
+
+ for (ItemTreeNode node = newRoot.getFirstChild(); node != null;
+ node = node.getNextSibling()) {
+ doNode(node, new TreeItem(launchTree, SWT.NONE)); // top-level TreeItem
+ }
+ }
+ private void addGroup(TreeItem parent, ItemTreeNode node) {
+ for (;node != null; node = node.getNextSibling()) {
+ doNode(node, new TreeItem(parent, SWT.NONE)); // TreeItem at depth > 0
+ }
+ }
+ private void doNode(ItemTreeNode node, TreeItem treeItem) {
+ final ItemDescriptor item = node.getDescriptor();
+ treeItem.setText(item.getName());
+ treeItem.setData(item);
+ if (node.getDescriptor().isFolder()) {
+ treeItem.setExpanded(false);
+ treeItem.setImage(LauncherPlugin.images[LauncherPlugin.liClosedFolder]);
+ } else {
+ treeItem.setImage(node.getDescriptor().getIcon());
+ }
+ addGroup(treeItem, node.getFirstChild());
+ }
+ });
+ }
+
+ /**
+ * Runs the specified launch item.
+ *
+ * @param itemDescriptor the launch item to execute
+ */
+ private void launchItem(ItemDescriptor itemDescriptor) {
+ /* Case 1: The launch item is a view */
+ String pluginViewId = itemDescriptor.getView ();
+ if (pluginViewId != null) {
+ final IWorkbenchPart workbenchPart = this;
+ final IWorkbenchPartSite workbenchPartSite = workbenchPart.getSite();
+ final IWorkbenchPage workbenchPage = workbenchPartSite.getPage();
+ try {
+ workbenchPage.showView(pluginViewId);
+ } catch (PartInitException e) {
+ LauncherPlugin.logError(LauncherPlugin.getResourceString("run.error.Invocation"), e);
+ }
+ return;
+ }
+ /* Case 2: The launch item is a standalone program */
+ if (workbenchShell == null) return;
+ try {
+ Class cl = Class.forName(itemDescriptor.getMainType());
+ Display display = workbenchShell.getDisplay();
+ Object exampleInstance = cl.newInstance();
+ Method openMethod = cl.getDeclaredMethod("open", new Class[] {Display.class});
+ openMethod.invoke(exampleInstance, new Object[] {display});
+ } catch (NoSuchMethodException e) {
+ LauncherPlugin.logError(LauncherPlugin.getResourceString("run.error.DoesNotImplementMethod"), null);
+ } catch (ClassNotFoundException e) {
+ LauncherPlugin.logError(LauncherPlugin.getResourceString("run.error.CouldNotFindClass"), e);
+ } catch (Exception e) {
+ LauncherPlugin.logError(LauncherPlugin.getResourceString("run.error.CouldNotInstantiateClass"), e);
+ }
+ }
+
+ /**
+ * Obtains the selected launch item.
+ *
+ * @return the currently selected ItemDescriptor
+ */
+ private ItemDescriptor getSelectedItem() {
+ final TreeItem[] selections = launchTree.getSelection();
+ if (selections.length == 0) return null;
+ final ItemDescriptor itemDescriptor = (ItemDescriptor) selections[0].getData();
+ return itemDescriptor;
+ }
+
+ /**
+ * Sets the currently visible description text to reflect that of a particular ItemDescriptor.
+ *
+ * @param itemDescriptor the launch item whose description is to be displayed, or null if none
+ */
+ private void setDescriptionByItem(ItemDescriptor itemDescriptor) {
+ String description;
+ if (itemDescriptor == null) {
+ description = LauncherPlugin.getResourceString("launchitem.Null.description");
+ if (runButton != null) runButton.setEnabled(false);
+ } else {
+ description = itemDescriptor.getDescription();
+ if (description == null)
+ description = LauncherPlugin.getResourceString("launchitem.Missing.description");
+ if (runButton != null) {
+ runButton.setEnabled(itemDescriptor.getView() != null || itemDescriptor.getMainType() != null);
+ }
+ }
+ descriptionText.setText(description);
+ }
} \ No newline at end of file
diff --git a/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/SplitLayout.java b/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/SplitLayout.java
index 6eee1cdb9d..f7be09acfb 100755
--- a/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/SplitLayout.java
+++ b/examples/org.eclipse.swt.examples.launcher/src/org/eclipse/swt/examples/launcher/SplitLayout.java
@@ -1,15 +1,15 @@
package org.eclipse.swt.examples.launcher; /* * (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html */ import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; /** * A Layout class that automatically switches from a horizontal split to a vertical * split layout to accomodate changing size conditions. * * Later on we might improve this class to take into account the "preferred" size of * the widgets. */
-public class SplitLayout extends Layout { private static final int splitHorizontally = 0, splitVertically = 1; private int splitDirection = splitHorizontally; public int spacing = 3; public int marginTop = 3;
- public int marginLeft = 3; public int marginRight = 3; public int marginBottom = 3; /**
- * Creates a new layout
- */
- public SplitLayout() { }
- /** * @see Layout#computeSize(Composite, int, int, boolean) */ protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { if (wHint == SWT.DEFAULT) { if (hHint == SWT.DEFAULT) { Point hSplitSize = computeHSplitSize(composite, wHint, hHint, flushCache); Point vSplitSize = computeVSplitSize(composite, wHint, hHint, false); int hSplitArea = hSplitSize.x * hSplitSize.y; int vSplitArea = vSplitSize.x * vSplitSize.y; // Choose direction consuming least area if (hSplitArea < vSplitArea) { splitDirection = splitHorizontally; return hSplitSize; } else { splitDirection = splitVertically; return vSplitSize; } } else { // Constrained in height: split vertically splitDirection = splitVertically; return computeVSplitSize(composite, wHint, hHint, flushCache); } } else { if (hHint == SWT.DEFAULT) { // Constrained in width: split horizontally splitDirection = splitHorizontally; return computeHSplitSize(composite, wHint, hHint, flushCache); } else { if (hHint < wHint) { splitDirection = splitVertically; return computeVSplitSize(composite, wHint, hHint, flushCache); } else { splitDirection = splitHorizontally; return computeHSplitSize(composite, wHint, hHint, flushCache); } } } }
- /**
- * @see Layout#layout(Composite, boolean)
- */
- protected void layout(Composite composite, boolean flushCache) { Rectangle clientArea = composite.getClientArea(); computeSize(composite, clientArea.width, clientArea.height, false); Control[] children = composite.getChildren(); clientArea.x += marginLeft; clientArea.y += marginTop; clientArea.width -= marginRight + marginLeft; clientArea.height -= marginBottom + marginTop; Point position = new Point(clientArea.x, clientArea.y); for (int i = 0; i < children.length; ++i) { final Control child = children[i]; final Rectangle bounds; if (splitDirection == splitHorizontally) { int height = clientArea.height / children.length; bounds = new Rectangle(position.x, position.y, clientArea.width, height); position.y += height + spacing; } else { int width = clientArea.width / children.length; bounds = new Rectangle(position.x, position.y, width, clientArea.height); position.x += width + spacing; } bounds.width = Math.max(bounds.width, 0); bounds.height = Math.max(bounds.height, 0); child.setBounds(bounds); } }
- private Point computeHSplitSize(Composite composite, int wHint, int hHint, boolean flushCache) { Point size = new Point(marginLeft + marginRight, marginTop + marginBottom); Control[] children = composite.getChildren(); for (int i = 0; i < children.length; ++i) { final Control child = children[i]; Point childSize = child.computeSize(wHint, hHint, flushCache); size.x = Math.max(size.x, childSize.x); size.y += childSize.y + spacing; } return size; } private Point computeVSplitSize(Composite composite, int wHint, int hHint, boolean flushCache) { Point size = new Point(marginLeft + marginRight, marginTop + marginBottom); Control[] children = composite.getChildren(); for (int i = 0; i < children.length; ++i) { final Control child = children[i]; Point childSize = child.computeSize(wHint, hHint, flushCache); size.x += childSize.x + spacing; size.y = Math.max(size.y, childSize.y); } return size; } }
+ * http://www.eclipse.org/legal/cpl-v10.html */ import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; /** * A Layout class that automatically switches from a horizontal split to a vertical * split layout to accomodate changing size conditions. * * Later on we might improve this class to take into account the "preferred" size of * the widgets. */
+public class SplitLayout extends Layout { private static final int splitHorizontally = 0, splitVertically = 1; private int splitDirection = splitHorizontally; public int spacing = 3; public int marginTop = 3;
+ public int marginLeft = 3; public int marginRight = 3; public int marginBottom = 3; /**
+ * Creates a new layout
+ */
+ public SplitLayout() { }
+ /** * @see Layout#computeSize(Composite, int, int, boolean) */ protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { if (wHint == SWT.DEFAULT) { if (hHint == SWT.DEFAULT) { Point hSplitSize = computeHSplitSize(composite, wHint, hHint, flushCache); Point vSplitSize = computeVSplitSize(composite, wHint, hHint, false); int hSplitArea = hSplitSize.x * hSplitSize.y; int vSplitArea = vSplitSize.x * vSplitSize.y; // Choose direction consuming least area if (hSplitArea < vSplitArea) { splitDirection = splitHorizontally; return hSplitSize; } else { splitDirection = splitVertically; return vSplitSize; } } else { // Constrained in height: split vertically splitDirection = splitVertically; return computeVSplitSize(composite, wHint, hHint, flushCache); } } else { if (hHint == SWT.DEFAULT) { // Constrained in width: split horizontally splitDirection = splitHorizontally; return computeHSplitSize(composite, wHint, hHint, flushCache); } else { if (hHint < wHint) { splitDirection = splitVertically; return computeVSplitSize(composite, wHint, hHint, flushCache); } else { splitDirection = splitHorizontally; return computeHSplitSize(composite, wHint, hHint, flushCache); } } } }
+ /**
+ * @see Layout#layout(Composite, boolean)
+ */
+ protected void layout(Composite composite, boolean flushCache) { Rectangle clientArea = composite.getClientArea(); computeSize(composite, clientArea.width, clientArea.height, false); Control[] children = composite.getChildren(); clientArea.x += marginLeft; clientArea.y += marginTop; clientArea.width -= marginRight + marginLeft; clientArea.height -= marginBottom + marginTop; Point position = new Point(clientArea.x, clientArea.y); for (int i = 0; i < children.length; ++i) { final Control child = children[i]; final Rectangle bounds; if (splitDirection == splitHorizontally) { int height = clientArea.height / children.length; bounds = new Rectangle(position.x, position.y, clientArea.width, height); position.y += height + spacing; } else { int width = clientArea.width / children.length; bounds = new Rectangle(position.x, position.y, width, clientArea.height); position.x += width + spacing; } bounds.width = Math.max(bounds.width, 0); bounds.height = Math.max(bounds.height, 0); child.setBounds(bounds); } }
+ private Point computeHSplitSize(Composite composite, int wHint, int hHint, boolean flushCache) { Point size = new Point(marginLeft + marginRight, marginTop + marginBottom); Control[] children = composite.getChildren(); for (int i = 0; i < children.length; ++i) { final Control child = children[i]; Point childSize = child.computeSize(wHint, hHint, flushCache); size.x = Math.max(size.x, childSize.x); size.y += childSize.y + spacing; } return size; } private Point computeVSplitSize(Composite composite, int wHint, int hHint, boolean flushCache) { Point size = new Point(marginLeft + marginRight, marginTop + marginBottom); Control[] children = composite.getChildren(); for (int i = 0; i < children.length; ++i) { final Control child = children[i]; Point childSize = child.computeSize(wHint, hHint, flushCache); size.x += childSize.x + spacing; size.y = Math.max(size.y, childSize.y); } return size; } }
diff --git a/examples/org.eclipse.swt.examples.layouts/.project b/examples/org.eclipse.swt.examples.layouts/.project
index cbc0d66613..e5d7079d5d 100644
--- a/examples/org.eclipse.swt.examples.layouts/.project
+++ b/examples/org.eclipse.swt.examples.layouts/.project
@@ -1,30 +1,30 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipse.swt.examples.layouts</name>
- <comment></comment>
- <projects>
- <project>org.eclipse.swt</project>
- <project>org.eclipse.swt.examples</project>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.swt.examples.layouts</name>
+ <comment></comment>
+ <projects>
+ <project>org.eclipse.swt</project>
+ <project>org.eclipse.swt.examples</project>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ </natures>
+</projectDescription>
diff --git a/examples/org.eclipse.swt.examples.layouts/doc-html/hglegal2002.htm b/examples/org.eclipse.swt.examples.layouts/doc-html/hglegal2002.htm
index 74393f08f3..5df454d51a 100644
--- a/examples/org.eclipse.swt.examples.layouts/doc-html/hglegal2002.htm
+++ b/examples/org.eclipse.swt.examples.layouts/doc-html/hglegal2002.htm
@@ -1,14 +1,14 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
- <title>Legal Notices</title>
-</head>
-<body>
-
-<h3>
-<a NAME="Notices"></a>Notices</h3>
-(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
+ <title>Legal Notices</title>
+</head>
+<body>
+
+<h3>
+<a NAME="Notices"></a>Notices</h3>
+(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.layouts/doc-html/swt_layout_ex.html b/examples/org.eclipse.swt.examples.layouts/doc-html/swt_layout_ex.html
index d021ab39fa..b8921a2dce 100644
--- a/examples/org.eclipse.swt.examples.layouts/doc-html/swt_layout_ex.html
+++ b/examples/org.eclipse.swt.examples.layouts/doc-html/swt_layout_ex.html
@@ -1,29 +1,29 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Layout Overview</title>
-</head>
-<body>
-
-<h2>SWT Example - Layout Overview</h2>
-
-<p>
-This example is a simple demonstration of common SWT layouts.
-It consists of a tab folder where each tab allows the
-user to interact with a different SWT layout.
-The user can insert widgets into a layout and set the values of the layout data
-using a property sheet. When the user has a suitable arrangement, code can be
-generated by clicking on the Code button.
-</p>
-
-<h3>Running the example</h3>
-
-<p>From the Window menu select Show View --> Other.
-In the Show View dialog, expand SWT Examples and select the
-view named SWT Layouts. A view titled SWT Layouts will appear in your current perspective.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Layout Overview</title>
+</head>
+<body>
+
+<h2>SWT Example - Layout Overview</h2>
+
+<p>
+This example is a simple demonstration of common SWT layouts.
+It consists of a tab folder where each tab allows the
+user to interact with a different SWT layout.
+The user can insert widgets into a layout and set the values of the layout data
+using a property sheet. When the user has a suitable arrangement, code can be
+generated by clicking on the Code button.
+</p>
+
+<h3>Running the example</h3>
+
+<p>From the Window menu select Show View --> Other.
+In the Show View dialog, expand SWT Examples and select the
+view named SWT Layouts. A view titled SWT Layouts will appear in your current perspective.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
</html> \ No newline at end of file
diff --git a/examples/org.eclipse.swt.examples.ole.win32/.project b/examples/org.eclipse.swt.examples.ole.win32/.project
index b160136cdd..9ea059d7d5 100644
--- a/examples/org.eclipse.swt.examples.ole.win32/.project
+++ b/examples/org.eclipse.swt.examples.ole.win32/.project
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipse.swt.examples.ole.win32</name>
- <comment></comment>
- <projects>
- <project>org.eclipse.swt</project>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.swt.examples.ole.win32</name>
+ <comment></comment>
+ <projects>
+ <project>org.eclipse.swt</project>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ </natures>
+</projectDescription>
diff --git a/examples/org.eclipse.swt.examples.ole.win32/build.properties b/examples/org.eclipse.swt.examples.ole.win32/build.properties
index ac90c6ffa3..e625ea0278 100755
--- a/examples/org.eclipse.swt.examples.ole.win32/build.properties
+++ b/examples/org.eclipse.swt.examples.ole.win32/build.properties
@@ -1,10 +1,10 @@
-bin.includes = doc-html/,\
- icons/,\
- plugin.properties,\
- plugin.xml,\
- about.html,\
- *.jar
-
-src.includes = about.html
-
-source.olewin32.jar = src/
+bin.includes = doc-html/,\
+ icons/,\
+ plugin.properties,\
+ plugin.xml,\
+ about.html,\
+ *.jar
+
+src.includes = about.html
+
+source.olewin32.jar = src/
diff --git a/examples/org.eclipse.swt.examples.ole.win32/doc-html/hglegal2002.htm b/examples/org.eclipse.swt.examples.ole.win32/doc-html/hglegal2002.htm
index 74393f08f3..5df454d51a 100644
--- a/examples/org.eclipse.swt.examples.ole.win32/doc-html/hglegal2002.htm
+++ b/examples/org.eclipse.swt.examples.ole.win32/doc-html/hglegal2002.htm
@@ -1,14 +1,14 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
- <title>Legal Notices</title>
-</head>
-<body>
-
-<h3>
-<a NAME="Notices"></a>Notices</h3>
-(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
+ <title>Legal Notices</title>
+</head>
+<body>
+
+<h3>
+<a NAME="Notices"></a>Notices</h3>
+(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.ole.win32/doc-html/swt_ole_ex.html b/examples/org.eclipse.swt.examples.ole.win32/doc-html/swt_ole_ex.html
index 8191de138f..26023156c4 100755
--- a/examples/org.eclipse.swt.examples.ole.win32/doc-html/swt_ole_ex.html
+++ b/examples/org.eclipse.swt.examples.ole.win32/doc-html/swt_ole_ex.html
@@ -1,34 +1,34 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - OLE Web Browser</title>
-</head>
-<body>
-
-<h2>Example - OLE Web Browser</h2>
-
-<p>
-This example demonstrates how to embed an Active X control into an SWT application or an Eclipse view.
-<p>
-</p>
-When the view is opened, it will create an instance of the Windows Internet Explorer
-control. The OLE Web Browser has
-Back and Forward buttons to take you to recently visited pages. The browser also contains
-a Home button to take you to the web browser's home page, a Stop button which stops the
-current transfer, a Search button which will search for text typed in the Address text field, and
-a Refresh button which re-draws the contents of the currently displayed page. There is also a
-Go button which, when clicked, will attempt to load the page specified in the Address field.
-</p>
-
-<h3>Running the example</h3>
-
-<p>
-From the Window menu select Show View --> Other.
-In the Show View dialog, expand SWT Examples and select
-the view named OLE Web Browser (Win32). A view containing a web browser will appear.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - OLE Web Browser</title>
+</head>
+<body>
+
+<h2>Example - OLE Web Browser</h2>
+
+<p>
+This example demonstrates how to embed an Active X control into an SWT application or an Eclipse view.
+<p>
+</p>
+When the view is opened, it will create an instance of the Windows Internet Explorer
+control. The OLE Web Browser has
+Back and Forward buttons to take you to recently visited pages. The browser also contains
+a Home button to take you to the web browser's home page, a Stop button which stops the
+current transfer, a Search button which will search for text typed in the Address text field, and
+a Refresh button which re-draws the contents of the currently displayed page. There is also a
+Go button which, when clicked, will attempt to load the page specified in the Address field.
+</p>
+
+<h3>Running the example</h3>
+
+<p>
+From the Window menu select Show View --> Other.
+In the Show View dialog, expand SWT Examples and select
+the view named OLE Web Browser (Win32). A view containing a web browser will appear.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.ole.win32/plugin.properties b/examples/org.eclipse.swt.examples.ole.win32/plugin.properties
index 82d8e49fe5..cb6475b8d9 100755
--- a/examples/org.eclipse.swt.examples.ole.win32/plugin.properties
+++ b/examples/org.eclipse.swt.examples.ole.win32/plugin.properties
@@ -1,50 +1,50 @@
-providerName = Eclipse.org
-plugin.SWTOLEExample.name = SWT OLE Example Plugin (Win32)
-category.SWTExamples.name = SWT Examples
-view.OLEWebBrowserExample.name = OLE Web Browser (Win32)
-
-launchcategory.SWTWin32OnlyExamples.name = Win32 only
-launchcategory.SWTWin32OnlyExamples.description = \
- A collection of Standard Widget Toolkit examples for Windows systems only.
-
-launchitem.OLEWebBrowserExample.name = OLE Web Browser
-launchitem.OLEWebBrowserExample.description = \
- This example demonstrates how to embed an Active X control into an SWT application or an Eclipse view.\n\n\
- When the view is opened, it will create an instance of the Windows Internet Explorer \
- control. The OLE Web Browser has \
- Back and Forward buttons to take you to recently visited pages. The browser also contains \
- a Home button to take you to the web browser's home page, a Stop button which stops the \
- current transfer, a Search button which will search for text typed in the Address text field, and \
- a Refresh button which re-draws the contents of the currently displayed page. There is also a \
- Go button which, when clicked, will attempt to load the page specified in the Address field.
-
-browser.Back.text = Backward
-browser.Back.tooltip = Go to previous Web site in the history list
-
-browser.Forward.text = Forward
-browser.Forward.tooltip = Go to next Web site in the history list
-
-browser.Home.text = Home
-browser.Home.tooltip = Go to home Web site
-
-browser.Stop.text = Stop
-browser.Stop.tooltip = Stop loading current Web site
-
-browser.Refresh.text = Refresh
-browser.Refresh.tooltip = Refresh current Web site
-
-browser.Search.text = Search
-browser.Search.tooltip = Search the Web
-
-browser.Address.label = Address :
-
-browser.Go.text = Go
-
-browser.State.Uninitialized.text = Not ready.
-browser.State.Loading.text = Loading Web site...
-browser.State.Loaded.text = Ready.
-browser.State.Interactive.text = Loading Web site...
-browser.State.Complete.text = Done.
-
-error.CouldNotLoadResources = Unable to load resources
-error.CouldNotCreateBrowserControl = Unable to create <<Browser Control>>
+providerName = Eclipse.org
+plugin.SWTOLEExample.name = SWT OLE Example Plugin (Win32)
+category.SWTExamples.name = SWT Examples
+view.OLEWebBrowserExample.name = OLE Web Browser (Win32)
+
+launchcategory.SWTWin32OnlyExamples.name = Win32 only
+launchcategory.SWTWin32OnlyExamples.description = \
+ A collection of Standard Widget Toolkit examples for Windows systems only.
+
+launchitem.OLEWebBrowserExample.name = OLE Web Browser
+launchitem.OLEWebBrowserExample.description = \
+ This example demonstrates how to embed an Active X control into an SWT application or an Eclipse view.\n\n\
+ When the view is opened, it will create an instance of the Windows Internet Explorer \
+ control. The OLE Web Browser has \
+ Back and Forward buttons to take you to recently visited pages. The browser also contains \
+ a Home button to take you to the web browser's home page, a Stop button which stops the \
+ current transfer, a Search button which will search for text typed in the Address text field, and \
+ a Refresh button which re-draws the contents of the currently displayed page. There is also a \
+ Go button which, when clicked, will attempt to load the page specified in the Address field.
+
+browser.Back.text = Backward
+browser.Back.tooltip = Go to previous Web site in the history list
+
+browser.Forward.text = Forward
+browser.Forward.tooltip = Go to next Web site in the history list
+
+browser.Home.text = Home
+browser.Home.tooltip = Go to home Web site
+
+browser.Stop.text = Stop
+browser.Stop.tooltip = Stop loading current Web site
+
+browser.Refresh.text = Refresh
+browser.Refresh.tooltip = Refresh current Web site
+
+browser.Search.text = Search
+browser.Search.tooltip = Search the Web
+
+browser.Address.label = Address :
+
+browser.Go.text = Go
+
+browser.State.Uninitialized.text = Not ready.
+browser.State.Loading.text = Loading Web site...
+browser.State.Loaded.text = Ready.
+browser.State.Interactive.text = Loading Web site...
+browser.State.Complete.text = Done.
+
+error.CouldNotLoadResources = Unable to load resources
+error.CouldNotCreateBrowserControl = Unable to create <<Browser Control>>
diff --git a/examples/org.eclipse.swt.examples.ole.win32/plugin.xml b/examples/org.eclipse.swt.examples.ole.win32/plugin.xml
index 09b30f9c15..0fdfb5953f 100755
--- a/examples/org.eclipse.swt.examples.ole.win32/plugin.xml
+++ b/examples/org.eclipse.swt.examples.ole.win32/plugin.xml
@@ -1,55 +1,55 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- File written by PDE 1.0 -->
-<plugin
- id="org.eclipse.swt.examples.ole.win32"
- name="%plugin.SWTOLEExample.name"
- version="2.1.0"
- provider-name="%providerName"
- class="org.eclipse.swt.examples.ole.win32.OlePlugin">
-<!-- Required plugins -->
-<requires>
- <import plugin="org.eclipse.core.runtime"/>
- <import plugin="org.eclipse.core.resources"/>
- <import plugin="org.eclipse.ui"/>
- <import plugin="org.eclipse.swt"/>
-</requires>
-
-<!-- Runtime -->
-<!-- Runtime -->
-<runtime>
- <library name="olewin32.jar">
- <packages prefixes="org.eclipse.swt.examples.ole"/>
- </library>
-</runtime>
-
-<!-- Extensions -->
-<!-- Extension points -->
-<extension
- point="org.eclipse.ui.views">
- <view
- name="%view.OLEWebBrowserExample.name"
- icon="icons/webbrowser_example.gif"
- category="org.eclipse.swt.examples.category"
- class="org.eclipse.swt.examples.ole.win32.OleBrowserView"
- id="org.eclipse.swt.examples.ole.win32.browserView">
- </view>
-</extension>
-<extension
- point="org.eclipse.swt.examples.launcher.launchItems">
- <category
- name="%launchcategory.SWTWin32OnlyExamples.name"
- description="%launchcategory.SWTWin32OnlyExamples.description"
- id="org.eclipse.swt.examples.launchWin32OnlyCategory">
- </category>
- <item
- name="%launchitem.OLEWebBrowserExample.name"
- icon="icons/webbrowser_example.gif"
- description="%launchitem.OLEWebBrowserExample.description"
- category="org.eclipse.swt.examples.launchWin32OnlyCategory"
- id="org.eclipse.swt.examples.ole.win32.viewlauncher">
- <view
- viewId="org.eclipse.swt.examples.ole.win32.browserView">
- </view>
- </item>
-</extension>
-</plugin>
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- File written by PDE 1.0 -->
+<plugin
+ id="org.eclipse.swt.examples.ole.win32"
+ name="%plugin.SWTOLEExample.name"
+ version="2.1.0"
+ provider-name="%providerName"
+ class="org.eclipse.swt.examples.ole.win32.OlePlugin">
+<!-- Required plugins -->
+<requires>
+ <import plugin="org.eclipse.core.runtime"/>
+ <import plugin="org.eclipse.core.resources"/>
+ <import plugin="org.eclipse.ui"/>
+ <import plugin="org.eclipse.swt"/>
+</requires>
+
+<!-- Runtime -->
+<!-- Runtime -->
+<runtime>
+ <library name="olewin32.jar">
+ <packages prefixes="org.eclipse.swt.examples.ole"/>
+ </library>
+</runtime>
+
+<!-- Extensions -->
+<!-- Extension points -->
+<extension
+ point="org.eclipse.ui.views">
+ <view
+ name="%view.OLEWebBrowserExample.name"
+ icon="icons/webbrowser_example.gif"
+ category="org.eclipse.swt.examples.category"
+ class="org.eclipse.swt.examples.ole.win32.OleBrowserView"
+ id="org.eclipse.swt.examples.ole.win32.browserView">
+ </view>
+</extension>
+<extension
+ point="org.eclipse.swt.examples.launcher.launchItems">
+ <category
+ name="%launchcategory.SWTWin32OnlyExamples.name"
+ description="%launchcategory.SWTWin32OnlyExamples.description"
+ id="org.eclipse.swt.examples.launchWin32OnlyCategory">
+ </category>
+ <item
+ name="%launchitem.OLEWebBrowserExample.name"
+ icon="icons/webbrowser_example.gif"
+ description="%launchitem.OLEWebBrowserExample.description"
+ category="org.eclipse.swt.examples.launchWin32OnlyCategory"
+ id="org.eclipse.swt.examples.ole.win32.viewlauncher">
+ <view
+ viewId="org.eclipse.swt.examples.ole.win32.browserView">
+ </view>
+ </item>
+</extension>
+</plugin>
diff --git a/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleBrowserView.java b/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleBrowserView.java
index 4efbe377f0..2e886bcdac 100755
--- a/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleBrowserView.java
+++ b/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleBrowserView.java
@@ -1,361 +1,361 @@
-package org.eclipse.swt.examples.ole.win32;
-
-/*
+package org.eclipse.swt.examples.ole.win32;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.ole.win32.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.part.*;
-
-/**
- * Ole uses <code>org.eclipse.swt</code> to demonstrate Win32 OLE / ActiveX
- * integration.
- *
- * @see ViewPart
- */
-public class OleBrowserView extends ViewPart {
-
- private Composite displayArea;
-
- private OleFrame webFrame;
- private OleWebBrowser webBrowser;
- private Text webUrl;
- private OleControlSite webControlSite;
- private ProgressBar webProgress;
- private Label webStatus;
- private Button webNavigateButton;
-
- private ToolItem webCommandBackward;
- private ToolItem webCommandForward;
- private ToolItem webCommandHome;
- private ToolItem webCommandStop;
- private ToolItem webCommandRefresh;
- private ToolItem webCommandSearch;
-
- private boolean activated = false;
-
- private static final int DISPID_AMBIENT_DLCONTROL = -5512;
- private static final int DLCTL_NO_SCRIPTS = 0x80;
-
- /**
- * Constructs the OLE browser view.
- */
- public OleBrowserView() {
- OlePlugin.initResources();
- }
-
- /**
- * Creates the example.
- *
- * @see ViewPart#createPartControl
- */
- public void createPartControl(Composite parent) {
- displayArea = new Composite(parent, SWT.NONE);
-
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 3;
- displayArea.setLayout(gridLayout);
-
- createToolbar();
- createBrowserFrame();
- createStatusArea();
- createBrowserControl();
- }
-
- /**
- * Cleanup
- */
- public void dispose() {
- if (activated) {
- webControlSite.deactivateInPlaceClient();
- activated = false;
- }
- if (webBrowser != null) webBrowser.dispose();
- webBrowser = null;
- super.dispose();
- }
-
- /**
- * Called when we must grab focus.
- *
- * @see org.eclipse.ui.part.ViewPart#setFocus
- */
- public void setFocus() {
- webUrl.setFocus();
- }
-
- /**
- * Creates the Web browser toolbar.
- */
- private void createToolbar() {
- // Add a toolbar
- ToolBar bar = new ToolBar(displayArea, SWT.NONE);
- GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
- gridData.horizontalSpan = 3;
- bar.setLayoutData(gridData);
-
- // Add a button to navigate backwards through previously visited web sites
- webCommandBackward = new ToolItem(bar, SWT.NONE);
- webCommandBackward.setToolTipText(OlePlugin.getResourceString("browser.Back.tooltip"));
- webCommandBackward.setText(OlePlugin.getResourceString("browser.Back.text"));
- webCommandBackward.setImage(OlePlugin.images[OlePlugin.biBack]);
- webCommandBackward.setEnabled(false);
- webCommandBackward.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event e) {
- if (webBrowser == null) return;
- webBrowser.GoBack();
- }
- });
-
- // Add a button to navigate forward through previously visited web sites
- webCommandForward = new ToolItem(bar, SWT.NONE);
- webCommandForward.setToolTipText(OlePlugin.getResourceString("browser.Forward.tooltip"));
- webCommandForward.setText(OlePlugin.getResourceString("browser.Forward.text"));
- webCommandForward.setImage(OlePlugin.images[OlePlugin.biForward]);
- webCommandForward.setEnabled(false);
- webCommandForward.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event e) {
- if (webBrowser == null) return;
- webBrowser.GoForward();
- }
- });
-
- // Add a separator
- new ToolItem(bar, SWT.SEPARATOR);
-
- // Add a button to navigate to the Home page
- webCommandHome = new ToolItem(bar, SWT.NONE);
- webCommandHome.setToolTipText(OlePlugin.getResourceString("browser.Home.tooltip"));
- webCommandHome.setText(OlePlugin.getResourceString("browser.Home.text"));
- webCommandHome.setImage(OlePlugin.images[OlePlugin.biHome]);
- webCommandHome.setEnabled(false);
- webCommandHome.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event e) {
- if (webBrowser == null) return;
- webBrowser.GoHome();
- }
- });
-
- // Add a button to abort web page loading
- webCommandStop = new ToolItem(bar, SWT.NONE);
- webCommandStop.setToolTipText(OlePlugin.getResourceString("browser.Stop.tooltip"));
- webCommandStop.setText(OlePlugin.getResourceString("browser.Stop.text"));
- webCommandStop.setImage(OlePlugin.images[OlePlugin.biStop]);
- webCommandStop.setEnabled(false);
- webCommandStop.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event e) {
- if (webBrowser == null) return;
- webBrowser.Stop();
- }
- });
-
- // Add a button to refresh the current web page
- webCommandRefresh = new ToolItem(bar, SWT.NONE);
- webCommandRefresh.setToolTipText(OlePlugin.getResourceString("browser.Refresh.tooltip"));
- webCommandRefresh.setText(OlePlugin.getResourceString("browser.Refresh.text"));
- webCommandRefresh.setImage(OlePlugin.images[OlePlugin.biRefresh]);
- webCommandRefresh.setEnabled(false);
- webCommandRefresh.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event e) {
- if (webBrowser == null) return;
- webBrowser.Refresh();
- }
- });
-
- // Add a separator
- new ToolItem(bar, SWT.SEPARATOR);
-
- // Add a button to search the web
- webCommandSearch = new ToolItem(bar, SWT.NONE);
- webCommandSearch.setToolTipText(OlePlugin.getResourceString("browser.Search.tooltip"));
- webCommandSearch.setText(OlePlugin.getResourceString("browser.Search.text"));
- webCommandSearch.setImage(OlePlugin.images[OlePlugin.biSearch]);
- webCommandSearch.setEnabled(false);
- webCommandSearch.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event e) {
- if (webBrowser == null) return;
- webBrowser.GoSearch();
- }
- });
-
- // Add a text area for Users to enter a url
- Composite addressBar = new Composite(displayArea, SWT.NONE);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
- gridData.horizontalSpan = 3;
- addressBar.setLayoutData(gridData);
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 3;
- addressBar.setLayout(gridLayout);
-
- Label addressLabel = new Label(addressBar, SWT.NONE);
- gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
- addressLabel.setLayoutData(gridData);
- addressLabel.setText(OlePlugin.getResourceString("browser.Address.label"));
- addressLabel.setFont(OlePlugin.browserFont);
-
- webUrl = new Text(addressBar, SWT.SINGLE | SWT.BORDER);
- webUrl.setFont(OlePlugin.browserFont);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
- webUrl.setLayoutData(gridData);
- webUrl.addFocusListener(new FocusAdapter() {
- public void focusGained(FocusEvent e) {
- webNavigateButton.getShell().setDefaultButton(webNavigateButton);
- }
- });
-
- // Add a button to navigate to the web site specified in the Text area defined above
- webNavigateButton = new Button(addressBar, SWT.PUSH);
- gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
- webNavigateButton.setLayoutData(gridData);
- webNavigateButton.setText(OlePlugin.getResourceString("browser.Go.text"));
- webNavigateButton.setFont(OlePlugin.browserFont);
- webNavigateButton.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- if (webBrowser == null) return;
- webBrowser.Navigate(webUrl.getText());
- }
- });
- }
-
- /**
- * Creates the Web browser OleFrame.
- */
- private void createBrowserFrame() {
- // Every control must have an associated OleFrame:
- webFrame = new OleFrame(displayArea, SWT.NONE);
- GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
- gridData.horizontalSpan = 3;
- webFrame.setLayoutData(gridData);
- }
-
- /**
- * Creates the Web browser status area.
- */
- private void createStatusArea() {
- // Add a progress bar to display downloading progress information
- webProgress = new ProgressBar(displayArea, SWT.BORDER);
- GridData gridData = new GridData();
- gridData.horizontalAlignment = GridData.BEGINNING;
- gridData.verticalAlignment = GridData.FILL;
- webProgress.setLayoutData(gridData);
-
- // Add a label for displaying status messages as they are received from the control
- webStatus = new Label(displayArea, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
- gridData.horizontalSpan = 2;
- webStatus.setLayoutData(gridData);
- webStatus.setFont(OlePlugin.browserFont);
- }
-
- /**
- * Creates Web browser control.
- */
- private void createBrowserControl() {
- try {
- // Create an Automation object for access to extended capabilities
- webControlSite = new OleControlSite(webFrame, SWT.NONE, "Shell.Explorer");
- Variant download = new Variant(DLCTL_NO_SCRIPTS);
- webControlSite.setSiteProperty(DISPID_AMBIENT_DLCONTROL, download);
- OleAutomation oleAutomation = new OleAutomation(webControlSite);
- webBrowser = new OleWebBrowser(oleAutomation);
- } catch (SWTException ex) {
- // Creation may have failed because control is not installed on machine
- Label label = new Label(webFrame, SWT.BORDER);
- OlePlugin.logError(OlePlugin.getResourceString("error.CouldNotCreateBrowserControl"), ex);
- label.setText(OlePlugin.getResourceString("error.CouldNotCreateBrowserControl"));
- return;
- }
-
- // Respond to ProgressChange events by updating the Progress bar
- webControlSite.addEventListener(OleWebBrowser.ProgressChange, new OleListener() {
- public void handleEvent(OleEvent event) {
- Variant progress = event.arguments[0];
- Variant maxProgress = event.arguments[1];
- if (progress == null || maxProgress == null)
- return;
- webProgress.setMaximum(maxProgress.getInt());
- webProgress.setSelection(progress.getInt());
- }
- });
-
- // Respond to StatusTextChange events by updating the Status Text label
- webControlSite.addEventListener(OleWebBrowser.StatusTextChange, new OleListener() {
- public void handleEvent(OleEvent event) {
- Variant statusText = event.arguments[0];
- if (statusText == null) return;
- String text = statusText.getString();
- if (text != null)
- webStatus.setText(text);
- }
- });
-
- // Listen for changes to the ready state and print out the current state
- webControlSite.addPropertyListener(OleWebBrowser.DISPID_READYSTATE, new OleListener() {
- public void handleEvent(OleEvent event) {
- if (event.detail == OLE.PROPERTY_CHANGING) return;
- int state = webBrowser.getReadyState();
- switch (state) {
- case OleWebBrowser.READYSTATE_UNINITIALIZED:
- webStatus.setText(
- OlePlugin.getResourceString("browser.State.Uninitialized.text"));
- webCommandBackward.setEnabled(false);
- webCommandForward.setEnabled(false);
- webCommandHome.setEnabled(false);
- webCommandRefresh.setEnabled(false);
- webCommandStop.setEnabled(false);
- webCommandSearch.setEnabled(false);
- break;
- case OleWebBrowser.READYSTATE_LOADING:
- webStatus.setText(
- OlePlugin.getResourceString("browser.State.Loading.text"));
- webCommandHome.setEnabled(true);
- webCommandRefresh.setEnabled(true);
- webCommandStop.setEnabled(true);
- webCommandSearch.setEnabled(true);
- break;
- case OleWebBrowser.READYSTATE_LOADED:
- webStatus.setText(
- OlePlugin.getResourceString("browser.State.Loaded.text"));
- webCommandStop.setEnabled(true);
- break;
- case OleWebBrowser.READYSTATE_INTERACTIVE:
- webStatus.setText(
- OlePlugin.getResourceString("browser.State.Interactive.text"));
- webCommandStop.setEnabled(true);
- break;
- case OleWebBrowser.READYSTATE_COMPLETE:
- webStatus.setText(
- OlePlugin.getResourceString("browser.State.Complete.text"));
- webCommandStop.setEnabled(false);
- break;
- }
- }
- });
-
- // Listen for changes to the active command states
- webControlSite.addEventListener(OleWebBrowser.CommandStateChange, new OleListener() {
- public void handleEvent(OleEvent event) {
- if (event.type != OleWebBrowser.CommandStateChange) return;
- final int commandID =
- (event.arguments[0] != null) ? event.arguments[0].getInt() : 0;
- final boolean commandEnabled =
- (event.arguments[1] != null) ? event.arguments[1].getBoolean() : false;
-
- switch (commandID) {
- case OleWebBrowser.CSC_NAVIGATEBACK:
- webCommandBackward.setEnabled(commandEnabled);
- break;
- case OleWebBrowser.CSC_NAVIGATEFORWARD:
- webCommandForward.setEnabled(commandEnabled);
- break;
- }
- }
- });
-
- // in place activate the ActiveX control
- activated = (webControlSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE) == OLE.S_OK);
- if (activated) webBrowser.GoHome();
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.ole.win32.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.part.*;
+
+/**
+ * Ole uses <code>org.eclipse.swt</code> to demonstrate Win32 OLE / ActiveX
+ * integration.
+ *
+ * @see ViewPart
+ */
+public class OleBrowserView extends ViewPart {
+
+ private Composite displayArea;
+
+ private OleFrame webFrame;
+ private OleWebBrowser webBrowser;
+ private Text webUrl;
+ private OleControlSite webControlSite;
+ private ProgressBar webProgress;
+ private Label webStatus;
+ private Button webNavigateButton;
+
+ private ToolItem webCommandBackward;
+ private ToolItem webCommandForward;
+ private ToolItem webCommandHome;
+ private ToolItem webCommandStop;
+ private ToolItem webCommandRefresh;
+ private ToolItem webCommandSearch;
+
+ private boolean activated = false;
+
+ private static final int DISPID_AMBIENT_DLCONTROL = -5512;
+ private static final int DLCTL_NO_SCRIPTS = 0x80;
+
+ /**
+ * Constructs the OLE browser view.
+ */
+ public OleBrowserView() {
+ OlePlugin.initResources();
+ }
+
+ /**
+ * Creates the example.
+ *
+ * @see ViewPart#createPartControl
+ */
+ public void createPartControl(Composite parent) {
+ displayArea = new Composite(parent, SWT.NONE);
+
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 3;
+ displayArea.setLayout(gridLayout);
+
+ createToolbar();
+ createBrowserFrame();
+ createStatusArea();
+ createBrowserControl();
+ }
+
+ /**
+ * Cleanup
+ */
+ public void dispose() {
+ if (activated) {
+ webControlSite.deactivateInPlaceClient();
+ activated = false;
+ }
+ if (webBrowser != null) webBrowser.dispose();
+ webBrowser = null;
+ super.dispose();
+ }
+
+ /**
+ * Called when we must grab focus.
+ *
+ * @see org.eclipse.ui.part.ViewPart#setFocus
+ */
+ public void setFocus() {
+ webUrl.setFocus();
+ }
+
+ /**
+ * Creates the Web browser toolbar.
+ */
+ private void createToolbar() {
+ // Add a toolbar
+ ToolBar bar = new ToolBar(displayArea, SWT.NONE);
+ GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
+ gridData.horizontalSpan = 3;
+ bar.setLayoutData(gridData);
+
+ // Add a button to navigate backwards through previously visited web sites
+ webCommandBackward = new ToolItem(bar, SWT.NONE);
+ webCommandBackward.setToolTipText(OlePlugin.getResourceString("browser.Back.tooltip"));
+ webCommandBackward.setText(OlePlugin.getResourceString("browser.Back.text"));
+ webCommandBackward.setImage(OlePlugin.images[OlePlugin.biBack]);
+ webCommandBackward.setEnabled(false);
+ webCommandBackward.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event e) {
+ if (webBrowser == null) return;
+ webBrowser.GoBack();
+ }
+ });
+
+ // Add a button to navigate forward through previously visited web sites
+ webCommandForward = new ToolItem(bar, SWT.NONE);
+ webCommandForward.setToolTipText(OlePlugin.getResourceString("browser.Forward.tooltip"));
+ webCommandForward.setText(OlePlugin.getResourceString("browser.Forward.text"));
+ webCommandForward.setImage(OlePlugin.images[OlePlugin.biForward]);
+ webCommandForward.setEnabled(false);
+ webCommandForward.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event e) {
+ if (webBrowser == null) return;
+ webBrowser.GoForward();
+ }
+ });
+
+ // Add a separator
+ new ToolItem(bar, SWT.SEPARATOR);
+
+ // Add a button to navigate to the Home page
+ webCommandHome = new ToolItem(bar, SWT.NONE);
+ webCommandHome.setToolTipText(OlePlugin.getResourceString("browser.Home.tooltip"));
+ webCommandHome.setText(OlePlugin.getResourceString("browser.Home.text"));
+ webCommandHome.setImage(OlePlugin.images[OlePlugin.biHome]);
+ webCommandHome.setEnabled(false);
+ webCommandHome.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event e) {
+ if (webBrowser == null) return;
+ webBrowser.GoHome();
+ }
+ });
+
+ // Add a button to abort web page loading
+ webCommandStop = new ToolItem(bar, SWT.NONE);
+ webCommandStop.setToolTipText(OlePlugin.getResourceString("browser.Stop.tooltip"));
+ webCommandStop.setText(OlePlugin.getResourceString("browser.Stop.text"));
+ webCommandStop.setImage(OlePlugin.images[OlePlugin.biStop]);
+ webCommandStop.setEnabled(false);
+ webCommandStop.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event e) {
+ if (webBrowser == null) return;
+ webBrowser.Stop();
+ }
+ });
+
+ // Add a button to refresh the current web page
+ webCommandRefresh = new ToolItem(bar, SWT.NONE);
+ webCommandRefresh.setToolTipText(OlePlugin.getResourceString("browser.Refresh.tooltip"));
+ webCommandRefresh.setText(OlePlugin.getResourceString("browser.Refresh.text"));
+ webCommandRefresh.setImage(OlePlugin.images[OlePlugin.biRefresh]);
+ webCommandRefresh.setEnabled(false);
+ webCommandRefresh.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event e) {
+ if (webBrowser == null) return;
+ webBrowser.Refresh();
+ }
+ });
+
+ // Add a separator
+ new ToolItem(bar, SWT.SEPARATOR);
+
+ // Add a button to search the web
+ webCommandSearch = new ToolItem(bar, SWT.NONE);
+ webCommandSearch.setToolTipText(OlePlugin.getResourceString("browser.Search.tooltip"));
+ webCommandSearch.setText(OlePlugin.getResourceString("browser.Search.text"));
+ webCommandSearch.setImage(OlePlugin.images[OlePlugin.biSearch]);
+ webCommandSearch.setEnabled(false);
+ webCommandSearch.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event e) {
+ if (webBrowser == null) return;
+ webBrowser.GoSearch();
+ }
+ });
+
+ // Add a text area for Users to enter a url
+ Composite addressBar = new Composite(displayArea, SWT.NONE);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
+ gridData.horizontalSpan = 3;
+ addressBar.setLayoutData(gridData);
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 3;
+ addressBar.setLayout(gridLayout);
+
+ Label addressLabel = new Label(addressBar, SWT.NONE);
+ gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
+ addressLabel.setLayoutData(gridData);
+ addressLabel.setText(OlePlugin.getResourceString("browser.Address.label"));
+ addressLabel.setFont(OlePlugin.browserFont);
+
+ webUrl = new Text(addressBar, SWT.SINGLE | SWT.BORDER);
+ webUrl.setFont(OlePlugin.browserFont);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
+ webUrl.setLayoutData(gridData);
+ webUrl.addFocusListener(new FocusAdapter() {
+ public void focusGained(FocusEvent e) {
+ webNavigateButton.getShell().setDefaultButton(webNavigateButton);
+ }
+ });
+
+ // Add a button to navigate to the web site specified in the Text area defined above
+ webNavigateButton = new Button(addressBar, SWT.PUSH);
+ gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
+ webNavigateButton.setLayoutData(gridData);
+ webNavigateButton.setText(OlePlugin.getResourceString("browser.Go.text"));
+ webNavigateButton.setFont(OlePlugin.browserFont);
+ webNavigateButton.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ if (webBrowser == null) return;
+ webBrowser.Navigate(webUrl.getText());
+ }
+ });
+ }
+
+ /**
+ * Creates the Web browser OleFrame.
+ */
+ private void createBrowserFrame() {
+ // Every control must have an associated OleFrame:
+ webFrame = new OleFrame(displayArea, SWT.NONE);
+ GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
+ gridData.horizontalSpan = 3;
+ webFrame.setLayoutData(gridData);
+ }
+
+ /**
+ * Creates the Web browser status area.
+ */
+ private void createStatusArea() {
+ // Add a progress bar to display downloading progress information
+ webProgress = new ProgressBar(displayArea, SWT.BORDER);
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = GridData.BEGINNING;
+ gridData.verticalAlignment = GridData.FILL;
+ webProgress.setLayoutData(gridData);
+
+ // Add a label for displaying status messages as they are received from the control
+ webStatus = new Label(displayArea, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
+ gridData.horizontalSpan = 2;
+ webStatus.setLayoutData(gridData);
+ webStatus.setFont(OlePlugin.browserFont);
+ }
+
+ /**
+ * Creates Web browser control.
+ */
+ private void createBrowserControl() {
+ try {
+ // Create an Automation object for access to extended capabilities
+ webControlSite = new OleControlSite(webFrame, SWT.NONE, "Shell.Explorer");
+ Variant download = new Variant(DLCTL_NO_SCRIPTS);
+ webControlSite.setSiteProperty(DISPID_AMBIENT_DLCONTROL, download);
+ OleAutomation oleAutomation = new OleAutomation(webControlSite);
+ webBrowser = new OleWebBrowser(oleAutomation);
+ } catch (SWTException ex) {
+ // Creation may have failed because control is not installed on machine
+ Label label = new Label(webFrame, SWT.BORDER);
+ OlePlugin.logError(OlePlugin.getResourceString("error.CouldNotCreateBrowserControl"), ex);
+ label.setText(OlePlugin.getResourceString("error.CouldNotCreateBrowserControl"));
+ return;
+ }
+
+ // Respond to ProgressChange events by updating the Progress bar
+ webControlSite.addEventListener(OleWebBrowser.ProgressChange, new OleListener() {
+ public void handleEvent(OleEvent event) {
+ Variant progress = event.arguments[0];
+ Variant maxProgress = event.arguments[1];
+ if (progress == null || maxProgress == null)
+ return;
+ webProgress.setMaximum(maxProgress.getInt());
+ webProgress.setSelection(progress.getInt());
+ }
+ });
+
+ // Respond to StatusTextChange events by updating the Status Text label
+ webControlSite.addEventListener(OleWebBrowser.StatusTextChange, new OleListener() {
+ public void handleEvent(OleEvent event) {
+ Variant statusText = event.arguments[0];
+ if (statusText == null) return;
+ String text = statusText.getString();
+ if (text != null)
+ webStatus.setText(text);
+ }
+ });
+
+ // Listen for changes to the ready state and print out the current state
+ webControlSite.addPropertyListener(OleWebBrowser.DISPID_READYSTATE, new OleListener() {
+ public void handleEvent(OleEvent event) {
+ if (event.detail == OLE.PROPERTY_CHANGING) return;
+ int state = webBrowser.getReadyState();
+ switch (state) {
+ case OleWebBrowser.READYSTATE_UNINITIALIZED:
+ webStatus.setText(
+ OlePlugin.getResourceString("browser.State.Uninitialized.text"));
+ webCommandBackward.setEnabled(false);
+ webCommandForward.setEnabled(false);
+ webCommandHome.setEnabled(false);
+ webCommandRefresh.setEnabled(false);
+ webCommandStop.setEnabled(false);
+ webCommandSearch.setEnabled(false);
+ break;
+ case OleWebBrowser.READYSTATE_LOADING:
+ webStatus.setText(
+ OlePlugin.getResourceString("browser.State.Loading.text"));
+ webCommandHome.setEnabled(true);
+ webCommandRefresh.setEnabled(true);
+ webCommandStop.setEnabled(true);
+ webCommandSearch.setEnabled(true);
+ break;
+ case OleWebBrowser.READYSTATE_LOADED:
+ webStatus.setText(
+ OlePlugin.getResourceString("browser.State.Loaded.text"));
+ webCommandStop.setEnabled(true);
+ break;
+ case OleWebBrowser.READYSTATE_INTERACTIVE:
+ webStatus.setText(
+ OlePlugin.getResourceString("browser.State.Interactive.text"));
+ webCommandStop.setEnabled(true);
+ break;
+ case OleWebBrowser.READYSTATE_COMPLETE:
+ webStatus.setText(
+ OlePlugin.getResourceString("browser.State.Complete.text"));
+ webCommandStop.setEnabled(false);
+ break;
+ }
+ }
+ });
+
+ // Listen for changes to the active command states
+ webControlSite.addEventListener(OleWebBrowser.CommandStateChange, new OleListener() {
+ public void handleEvent(OleEvent event) {
+ if (event.type != OleWebBrowser.CommandStateChange) return;
+ final int commandID =
+ (event.arguments[0] != null) ? event.arguments[0].getInt() : 0;
+ final boolean commandEnabled =
+ (event.arguments[1] != null) ? event.arguments[1].getBoolean() : false;
+
+ switch (commandID) {
+ case OleWebBrowser.CSC_NAVIGATEBACK:
+ webCommandBackward.setEnabled(commandEnabled);
+ break;
+ case OleWebBrowser.CSC_NAVIGATEFORWARD:
+ webCommandForward.setEnabled(commandEnabled);
+ break;
+ }
+ }
+ });
+
+ // in place activate the ActiveX control
+ activated = (webControlSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE) == OLE.S_OK);
+ if (activated) webBrowser.GoHome();
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OlePlugin.java b/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OlePlugin.java
index 478c97be2f..edf531d99c 100755
--- a/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OlePlugin.java
+++ b/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OlePlugin.java
@@ -1,172 +1,172 @@
-package org.eclipse.swt.examples.ole.win32;
-
-/*
+package org.eclipse.swt.examples.ole.win32;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import java.io.*; import java.net.*; import java.text.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.ui.plugin.*;
-
-/**
- * The main plugin class to be used in the desktop.
- */
-public class OlePlugin extends AbstractUIPlugin {
- //The shared instance.
- private static OlePlugin plugin;
- private static ResourceBundle resourceBundle;
-
- static final int
- biBack = 0,
- biForward = 1,
- biHome = 2,
- biStop = 3,
- biRefresh = 4,
- biSearch = 5;
- static final String[] imageLocations = {
- "icons/backward_nav.gif",
- "icons/forward_nav.gif",
- "icons/home_nav.gif",
- "icons/stop_nav.gif",
- "icons/refresh_nav.gif",
- "icons/search_nav.gif" };
- static Image images[];
- static Font browserFont;
-
- /**
- * Constructs an OLE plugin.
- */
- public OlePlugin(IPluginDescriptor descriptor) {
- super(descriptor);
- plugin = this;
- resourceBundle = descriptor.getResourceBundle();
- }
-
- /**
- * Clean up
- */
- public void shutdown() throws CoreException {
- super.shutdown();
- freeResources();
- }
-
- /**
- * Returns the shared instance.
- */
- public static OlePlugin getDefault() {
- return plugin;
- }
-
- /**
- * Returns a string from the resource bundle.
- * We don't want to crash because of a missing String.
- * Returns the key if not found.
- */
- public static String getResourceString(String key) {
- try {
- return resourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Returns a string from the resource bundle and binds it
- * with the given arguments. If the key is not found,
- * return the key.
- */
- public static String getResourceString(String key, Object[] args) {
- try {
- return MessageFormat.format(getResourceString(key), args);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Log an error to the ILog for this plugin
- *
- * @param message the localized error message text
- * @param exception the associated exception, or null
- */
- public static void logError(String message, Throwable exception) {
- plugin.getLog().log(new Status(IStatus.ERROR, plugin.getDescriptor().getUniqueIdentifier(),
- 0, message, exception));
- }
-
- /**
- * Loads the resources.
- */
- public static void initResources() {
- if (images == null) {
- images = new Image[imageLocations.length];
-
- for (int i = 0; i < imageLocations.length; ++i) {
- images[i] = getImageFromPlugin(plugin.getDescriptor(), imageLocations[i]);
- if (images[i] == null) {
- freeResources();
- logError(getResourceString("error.CouldNotLoadResources"), null);
- throw new IllegalStateException();
- }
- }
- }
- if (browserFont == null) {
- try {
- browserFont = new Font (null, "MS Sans Serif", 8, SWT.NULL);
- } catch (Throwable ex) {
- }
- }
- if (images == null || browserFont == null) {
- freeResources();
- logError(getResourceString("error.CouldNotLoadResources"), null);
- throw new IllegalStateException();
- }
- }
-
- /**
- * Frees the resources
- */
- public static void freeResources() {
- if (images != null) {
- for (int i = 0; i < images.length; ++i) {
- final Image image = images[i];
- if (image != null) image.dispose();
- }
- images = null;
- }
- if (browserFont != null) browserFont.dispose ();
- browserFont = null;
- }
-
- /**
- * Gets an image from a path relative to the plugin install directory.
- *
- * @param pd the plugin descriptor for the plugin with the image
- * @param iconPath the path relative to the install directory
- * @return the image, or null if not found
- */
- private static Image getImageFromPlugin(IPluginDescriptor pd, String iconPath) {
- InputStream is = null;
- try {
- URL installUrl = pd.getInstallURL();
- URL url = new URL(installUrl, iconPath);
- is = url.openConnection().getInputStream();
- ImageData source = new ImageData(is);
- ImageData mask = source.getTransparencyMask();
- Image image = new Image(null, source, mask);
- return image;
- } catch (Throwable ex) {
- return null;
- } finally {
- try {
- if (is != null) is.close();
- } catch (IOException e) {
- }
- }
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import java.io.*; import java.net.*; import java.text.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.ui.plugin.*;
+
+/**
+ * The main plugin class to be used in the desktop.
+ */
+public class OlePlugin extends AbstractUIPlugin {
+ //The shared instance.
+ private static OlePlugin plugin;
+ private static ResourceBundle resourceBundle;
+
+ static final int
+ biBack = 0,
+ biForward = 1,
+ biHome = 2,
+ biStop = 3,
+ biRefresh = 4,
+ biSearch = 5;
+ static final String[] imageLocations = {
+ "icons/backward_nav.gif",
+ "icons/forward_nav.gif",
+ "icons/home_nav.gif",
+ "icons/stop_nav.gif",
+ "icons/refresh_nav.gif",
+ "icons/search_nav.gif" };
+ static Image images[];
+ static Font browserFont;
+
+ /**
+ * Constructs an OLE plugin.
+ */
+ public OlePlugin(IPluginDescriptor descriptor) {
+ super(descriptor);
+ plugin = this;
+ resourceBundle = descriptor.getResourceBundle();
+ }
+
+ /**
+ * Clean up
+ */
+ public void shutdown() throws CoreException {
+ super.shutdown();
+ freeResources();
+ }
+
+ /**
+ * Returns the shared instance.
+ */
+ public static OlePlugin getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns a string from the resource bundle.
+ * We don't want to crash because of a missing String.
+ * Returns the key if not found.
+ */
+ public static String getResourceString(String key) {
+ try {
+ return resourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Returns a string from the resource bundle and binds it
+ * with the given arguments. If the key is not found,
+ * return the key.
+ */
+ public static String getResourceString(String key, Object[] args) {
+ try {
+ return MessageFormat.format(getResourceString(key), args);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Log an error to the ILog for this plugin
+ *
+ * @param message the localized error message text
+ * @param exception the associated exception, or null
+ */
+ public static void logError(String message, Throwable exception) {
+ plugin.getLog().log(new Status(IStatus.ERROR, plugin.getDescriptor().getUniqueIdentifier(),
+ 0, message, exception));
+ }
+
+ /**
+ * Loads the resources.
+ */
+ public static void initResources() {
+ if (images == null) {
+ images = new Image[imageLocations.length];
+
+ for (int i = 0; i < imageLocations.length; ++i) {
+ images[i] = getImageFromPlugin(plugin.getDescriptor(), imageLocations[i]);
+ if (images[i] == null) {
+ freeResources();
+ logError(getResourceString("error.CouldNotLoadResources"), null);
+ throw new IllegalStateException();
+ }
+ }
+ }
+ if (browserFont == null) {
+ try {
+ browserFont = new Font (null, "MS Sans Serif", 8, SWT.NULL);
+ } catch (Throwable ex) {
+ }
+ }
+ if (images == null || browserFont == null) {
+ freeResources();
+ logError(getResourceString("error.CouldNotLoadResources"), null);
+ throw new IllegalStateException();
+ }
+ }
+
+ /**
+ * Frees the resources
+ */
+ public static void freeResources() {
+ if (images != null) {
+ for (int i = 0; i < images.length; ++i) {
+ final Image image = images[i];
+ if (image != null) image.dispose();
+ }
+ images = null;
+ }
+ if (browserFont != null) browserFont.dispose ();
+ browserFont = null;
+ }
+
+ /**
+ * Gets an image from a path relative to the plugin install directory.
+ *
+ * @param pd the plugin descriptor for the plugin with the image
+ * @param iconPath the path relative to the install directory
+ * @return the image, or null if not found
+ */
+ private static Image getImageFromPlugin(IPluginDescriptor pd, String iconPath) {
+ InputStream is = null;
+ try {
+ URL installUrl = pd.getInstallURL();
+ URL url = new URL(installUrl, iconPath);
+ is = url.openConnection().getInputStream();
+ ImageData source = new ImageData(is);
+ ImageData mask = source.getTransparencyMask();
+ Image image = new Image(null, source, mask);
+ return image;
+ } catch (Throwable ex) {
+ return null;
+ } finally {
+ try {
+ if (is != null) is.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleWebBrowser.java b/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleWebBrowser.java
index b82c9d5cae..012d108c5a 100755
--- a/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleWebBrowser.java
+++ b/examples/org.eclipse.swt.examples.ole.win32/src/org/eclipse/swt/examples/ole/win32/OleWebBrowser.java
@@ -1,224 +1,224 @@
-package org.eclipse.swt.examples.ole.win32;
-
-/*
+package org.eclipse.swt.examples.ole.win32;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.ole.win32.*;
-
-/**
- * Wrapper for an OleAutomation object used to send commands
- * to a Win32 "Shell.Explorer" OLE control.
- *
- * Instances of this class manage the setup, typical use and teardown of
- * a simple web browser.
- */
-class OleWebBrowser {
- /* See the Windows Platform SDK documentation for more information about the
- * OLE control used here and its usage.
- */
- // Generated from typelib filename: shdocvw.dll
-
- // Constants for WebBrowser CommandStateChange
- public static final int CSC_UPDATECOMMANDS = -1;
- public static final int CSC_NAVIGATEFORWARD = 1;
- public static final int CSC_NAVIGATEBACK = 2;
-
- // COnstants for Web Browser ReadyState
- public static final int READYSTATE_UNINITIALIZED = 0;
- public static final int READYSTATE_LOADING = 1;
- public static final int READYSTATE_LOADED = 2;
- public static final int READYSTATE_INTERACTIVE = 3;
- public static final int READYSTATE_COMPLETE = 4;
-
- // Web Browser Control Events
- public static final int BeforeNavigate = 100; // Fired when a new hyperlink is being navigated to.
- public static final int NavigateComplete = 101; // Fired when the document being navigated to becomes visible and enters the navigation stack.
- public static final int StatusTextChange = 102; // Statusbar text changed.
- public static final int ProgressChange = 108; // Fired when download progress is updated.
- public static final int DownloadComplete = 104; // Download of page complete.
- public static final int CommandStateChange = 105; // The enabled state of a command changed
- public static final int DownloadBegin = 106; // Download of a page started.
- public static final int NewWindow = 107; // Fired when a new window should be created.
- public static final int TitleChange = 113; // Document title changed.
- public static final int FrameBeforeNavigate = 200; // Fired when a new hyperlink is being navigated to in a frame.
- public static final int FrameNavigateComplete = 201; // Fired when a new hyperlink is being navigated to in a frame.
- public static final int FrameNewWindow = 204; // Fired when a new window should be created.
- public static final int Quit = 103; // Fired when application is quiting.
- public static final int WindowMove = 109; // Fired when window has been moved.
- public static final int WindowResize = 110; // Fired when window has been sized.
- public static final int WindowActivate = 111; // Fired when window has been activated.
- public static final int PropertyChange = 112; // Fired when the PutProperty method has been called.
-
- // Web Browser properties
- public static final int DISPID_READYSTATE = -525;
-
- private OleAutomation oleAutomation;
-
- /**
- * Creates a Web browser control.
- * <p>
- * Typical use:<br>
- * <code>
- * OleControlSite oleControlSite = new OleControlSite(oleFrame, style, "Shell.Explorer");<br>
- * OleAutomation oleAutomation = new OleAutomation(oleControlSite);<br>
- * OleWebBrowser webBrowser = new OleWebBrowser(oleControlSite, oleAutomation);<br>
- * </code>
- *
- * @param oleAutomation the OleAutomation object for this control.
- * @param oleControlSite the OleControlSite object for this control.
- */
- public OleWebBrowser(OleAutomation oleAutomation) {
- this.oleAutomation = oleAutomation;
- }
-
-
- /**
- * Disposes of the Web browser control.
- */
- public void dispose() {
- if (oleAutomation != null) oleAutomation.dispose();
- oleAutomation = null;
- }
-
- /*
- * Interact with the Control via OLE Automation
- *
- * Note: You can hard code the DISPIDs if you know them beforehand
- * this is of course the fastest way, but you increase coupling
- * to the control.
- */
-
- /**
- * Returns the current web page title.
- *
- * @return the current web page title String
- */
- public String getLocationName() {
- // dispid=210, type=PROPGET, name="LocationName"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"LocationName"});
- int dispIdMember = rgdispid[0];
- Variant pVarResult = oleAutomation.getProperty(dispIdMember);
- if (pVarResult == null || pVarResult.getType() != OLE.VT_BSTR) return null;
- return pVarResult.getString();
- }
-
- /**
- * Returns the current URL.
- *
- * @return the current URL String
- */
- public String getLocationURL() {
- // dispid=211, type=PROPGET, name="LocationURL"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"LocationURL"});
- int dispIdMember = rgdispid[0];
-
- Variant pVarResult = oleAutomation.getProperty(dispIdMember);
- if (pVarResult == null || pVarResult.getType() != OLE.VT_BSTR) return null;
- return pVarResult.getString();
- }
-
- /**
- * Returns the current state of the control.
- *
- * @return the current state of the control, one of:
- * READYSTATE_UNINITIALIZED;
- * READYSTATE_LOADING;
- * READYSTATE_LOADED;
- * READYSTATE_INTERACTIVE;
- * READYSTATE_COMPLETE.
- */
- public int getReadyState() {
- // dispid=4294966771, type=PROPGET, name="ReadyState"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"ReadyState"});
- int dispIdMember = rgdispid[0];
-
- Variant pVarResult = oleAutomation.getProperty(dispIdMember);
- if (pVarResult == null || pVarResult.getType() != OLE.VT_I4) return -1;
- return pVarResult.getInt();
- }
-
- /**
- * Navigates backwards through previously visited web sites.
- */
- public void GoBack() {
-
- // dispid=100, type=METHOD, name="GoBack"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"GoBack"});
- int dispIdMember = rgdispid[0];
- oleAutomation.invoke(dispIdMember);
- }
-
- /**
- * Navigates backwards through previously visited web sites.
- */
- public void GoForward() {
-
- // dispid=101, type=METHOD, name="GoForward"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"GoForward"});
- int dispIdMember = rgdispid[0];
- oleAutomation.invoke(dispIdMember);
- }
-
- /**
- * Navigates to home page.
- */
- public void GoHome() {
- // dispid=102, type=METHOD, name="GoHome"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"GoHome"});
- int dispIdMember = rgdispid[0];
- oleAutomation.invoke(dispIdMember);
- }
-
- /**
- * Navigates to user-specified Web search gateway.
- */
- public void GoSearch() {
- // dispid=103, type=METHOD, name="GoSearch"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"GoSearch"});
- int dispIdMember = rgdispid[0];
- oleAutomation.invoke(dispIdMember);
- }
-
- /**
- * Navigates to a particular URL.
- */
- public void Navigate(String url) {
- // dispid=104, type=METHOD, name="Navigate"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"Navigate", "URL"});
- int dispIdMember = rgdispid[0];
-
- Variant[] rgvarg = new Variant[1];
- rgvarg[0] = new Variant(url);
- int[] rgdispidNamedArgs = new int[1];
- rgdispidNamedArgs[0] = rgdispid[1]; // identifier of argument
- oleAutomation.invoke(dispIdMember, rgvarg, rgdispidNamedArgs);
- }
-
- /**
- * Refreshes the currently viewed page.
- *
- * @return the platform-defined result code for the "Refresh" method invocation
- */
- public void Refresh(){
- // dispid= 4294966746, type=METHOD, name="Refresh"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"Refresh"});
- int dispIdMember = rgdispid[0];
- oleAutomation.invokeNoReply(dispIdMember);
- }
-
- /**
- * Aborts loading of the currnet page.
- *
- * @return the platform-defined result code for the "Stop" method invocation
- */
- public void Stop() {
- // dispid=106, type=METHOD, name="Stop"
- int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"Stop"});
- int dispIdMember = rgdispid[0];
- oleAutomation.invoke(dispIdMember);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.ole.win32.*;
+
+/**
+ * Wrapper for an OleAutomation object used to send commands
+ * to a Win32 "Shell.Explorer" OLE control.
+ *
+ * Instances of this class manage the setup, typical use and teardown of
+ * a simple web browser.
+ */
+class OleWebBrowser {
+ /* See the Windows Platform SDK documentation for more information about the
+ * OLE control used here and its usage.
+ */
+ // Generated from typelib filename: shdocvw.dll
+
+ // Constants for WebBrowser CommandStateChange
+ public static final int CSC_UPDATECOMMANDS = -1;
+ public static final int CSC_NAVIGATEFORWARD = 1;
+ public static final int CSC_NAVIGATEBACK = 2;
+
+ // COnstants for Web Browser ReadyState
+ public static final int READYSTATE_UNINITIALIZED = 0;
+ public static final int READYSTATE_LOADING = 1;
+ public static final int READYSTATE_LOADED = 2;
+ public static final int READYSTATE_INTERACTIVE = 3;
+ public static final int READYSTATE_COMPLETE = 4;
+
+ // Web Browser Control Events
+ public static final int BeforeNavigate = 100; // Fired when a new hyperlink is being navigated to.
+ public static final int NavigateComplete = 101; // Fired when the document being navigated to becomes visible and enters the navigation stack.
+ public static final int StatusTextChange = 102; // Statusbar text changed.
+ public static final int ProgressChange = 108; // Fired when download progress is updated.
+ public static final int DownloadComplete = 104; // Download of page complete.
+ public static final int CommandStateChange = 105; // The enabled state of a command changed
+ public static final int DownloadBegin = 106; // Download of a page started.
+ public static final int NewWindow = 107; // Fired when a new window should be created.
+ public static final int TitleChange = 113; // Document title changed.
+ public static final int FrameBeforeNavigate = 200; // Fired when a new hyperlink is being navigated to in a frame.
+ public static final int FrameNavigateComplete = 201; // Fired when a new hyperlink is being navigated to in a frame.
+ public static final int FrameNewWindow = 204; // Fired when a new window should be created.
+ public static final int Quit = 103; // Fired when application is quiting.
+ public static final int WindowMove = 109; // Fired when window has been moved.
+ public static final int WindowResize = 110; // Fired when window has been sized.
+ public static final int WindowActivate = 111; // Fired when window has been activated.
+ public static final int PropertyChange = 112; // Fired when the PutProperty method has been called.
+
+ // Web Browser properties
+ public static final int DISPID_READYSTATE = -525;
+
+ private OleAutomation oleAutomation;
+
+ /**
+ * Creates a Web browser control.
+ * <p>
+ * Typical use:<br>
+ * <code>
+ * OleControlSite oleControlSite = new OleControlSite(oleFrame, style, "Shell.Explorer");<br>
+ * OleAutomation oleAutomation = new OleAutomation(oleControlSite);<br>
+ * OleWebBrowser webBrowser = new OleWebBrowser(oleControlSite, oleAutomation);<br>
+ * </code>
+ *
+ * @param oleAutomation the OleAutomation object for this control.
+ * @param oleControlSite the OleControlSite object for this control.
+ */
+ public OleWebBrowser(OleAutomation oleAutomation) {
+ this.oleAutomation = oleAutomation;
+ }
+
+
+ /**
+ * Disposes of the Web browser control.
+ */
+ public void dispose() {
+ if (oleAutomation != null) oleAutomation.dispose();
+ oleAutomation = null;
+ }
+
+ /*
+ * Interact with the Control via OLE Automation
+ *
+ * Note: You can hard code the DISPIDs if you know them beforehand
+ * this is of course the fastest way, but you increase coupling
+ * to the control.
+ */
+
+ /**
+ * Returns the current web page title.
+ *
+ * @return the current web page title String
+ */
+ public String getLocationName() {
+ // dispid=210, type=PROPGET, name="LocationName"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"LocationName"});
+ int dispIdMember = rgdispid[0];
+ Variant pVarResult = oleAutomation.getProperty(dispIdMember);
+ if (pVarResult == null || pVarResult.getType() != OLE.VT_BSTR) return null;
+ return pVarResult.getString();
+ }
+
+ /**
+ * Returns the current URL.
+ *
+ * @return the current URL String
+ */
+ public String getLocationURL() {
+ // dispid=211, type=PROPGET, name="LocationURL"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"LocationURL"});
+ int dispIdMember = rgdispid[0];
+
+ Variant pVarResult = oleAutomation.getProperty(dispIdMember);
+ if (pVarResult == null || pVarResult.getType() != OLE.VT_BSTR) return null;
+ return pVarResult.getString();
+ }
+
+ /**
+ * Returns the current state of the control.
+ *
+ * @return the current state of the control, one of:
+ * READYSTATE_UNINITIALIZED;
+ * READYSTATE_LOADING;
+ * READYSTATE_LOADED;
+ * READYSTATE_INTERACTIVE;
+ * READYSTATE_COMPLETE.
+ */
+ public int getReadyState() {
+ // dispid=4294966771, type=PROPGET, name="ReadyState"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"ReadyState"});
+ int dispIdMember = rgdispid[0];
+
+ Variant pVarResult = oleAutomation.getProperty(dispIdMember);
+ if (pVarResult == null || pVarResult.getType() != OLE.VT_I4) return -1;
+ return pVarResult.getInt();
+ }
+
+ /**
+ * Navigates backwards through previously visited web sites.
+ */
+ public void GoBack() {
+
+ // dispid=100, type=METHOD, name="GoBack"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"GoBack"});
+ int dispIdMember = rgdispid[0];
+ oleAutomation.invoke(dispIdMember);
+ }
+
+ /**
+ * Navigates backwards through previously visited web sites.
+ */
+ public void GoForward() {
+
+ // dispid=101, type=METHOD, name="GoForward"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"GoForward"});
+ int dispIdMember = rgdispid[0];
+ oleAutomation.invoke(dispIdMember);
+ }
+
+ /**
+ * Navigates to home page.
+ */
+ public void GoHome() {
+ // dispid=102, type=METHOD, name="GoHome"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"GoHome"});
+ int dispIdMember = rgdispid[0];
+ oleAutomation.invoke(dispIdMember);
+ }
+
+ /**
+ * Navigates to user-specified Web search gateway.
+ */
+ public void GoSearch() {
+ // dispid=103, type=METHOD, name="GoSearch"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"GoSearch"});
+ int dispIdMember = rgdispid[0];
+ oleAutomation.invoke(dispIdMember);
+ }
+
+ /**
+ * Navigates to a particular URL.
+ */
+ public void Navigate(String url) {
+ // dispid=104, type=METHOD, name="Navigate"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"Navigate", "URL"});
+ int dispIdMember = rgdispid[0];
+
+ Variant[] rgvarg = new Variant[1];
+ rgvarg[0] = new Variant(url);
+ int[] rgdispidNamedArgs = new int[1];
+ rgdispidNamedArgs[0] = rgdispid[1]; // identifier of argument
+ oleAutomation.invoke(dispIdMember, rgvarg, rgdispidNamedArgs);
+ }
+
+ /**
+ * Refreshes the currently viewed page.
+ *
+ * @return the platform-defined result code for the "Refresh" method invocation
+ */
+ public void Refresh(){
+ // dispid= 4294966746, type=METHOD, name="Refresh"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"Refresh"});
+ int dispIdMember = rgdispid[0];
+ oleAutomation.invokeNoReply(dispIdMember);
+ }
+
+ /**
+ * Aborts loading of the currnet page.
+ *
+ * @return the platform-defined result code for the "Stop" method invocation
+ */
+ public void Stop() {
+ // dispid=106, type=METHOD, name="Stop"
+ int[] rgdispid = oleAutomation.getIDsOfNames(new String[]{"Stop"});
+ int dispIdMember = rgdispid[0];
+ oleAutomation.invoke(dispIdMember);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/.project b/examples/org.eclipse.swt.examples.paint/.project
index 3cb7c3ea6d..be659d3d57 100644
--- a/examples/org.eclipse.swt.examples.paint/.project
+++ b/examples/org.eclipse.swt.examples.paint/.project
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipse.swt.examples.paint</name>
- <comment></comment>
- <projects>
- <project>org.eclipse.swt</project>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.swt.examples.paint</name>
+ <comment></comment>
+ <projects>
+ <project>org.eclipse.swt</project>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ </natures>
+</projectDescription>
diff --git a/examples/org.eclipse.swt.examples.paint/build.properties b/examples/org.eclipse.swt.examples.paint/build.properties
index db39eb3db8..1ca4f10f3a 100755
--- a/examples/org.eclipse.swt.examples.paint/build.properties
+++ b/examples/org.eclipse.swt.examples.paint/build.properties
@@ -1,10 +1,10 @@
-bin.includes = doc-html/,\
- icons/,\
- plugin.properties,\
- plugin.xml,\
- about.html,\
- *.jar
-
-src.includes = about.html
-
-source.paint.jar = src/
+bin.includes = doc-html/,\
+ icons/,\
+ plugin.properties,\
+ plugin.xml,\
+ about.html,\
+ *.jar
+
+src.includes = about.html
+
+source.paint.jar = src/
diff --git a/examples/org.eclipse.swt.examples.paint/doc-html/hglegal2002.htm b/examples/org.eclipse.swt.examples.paint/doc-html/hglegal2002.htm
index 74393f08f3..5df454d51a 100644
--- a/examples/org.eclipse.swt.examples.paint/doc-html/hglegal2002.htm
+++ b/examples/org.eclipse.swt.examples.paint/doc-html/hglegal2002.htm
@@ -1,14 +1,14 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
- <title>Legal Notices</title>
-</head>
-<body>
-
-<h3>
-<a NAME="Notices"></a>Notices</h3>
-(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
+ <title>Legal Notices</title>
+</head>
+<body>
+
+<h3>
+<a NAME="Notices"></a>Notices</h3>
+(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.paint/doc-html/swt_paint_ex.html b/examples/org.eclipse.swt.examples.paint/doc-html/swt_paint_ex.html
index 8449ba4ebb..a75668f8b2 100755
--- a/examples/org.eclipse.swt.examples.paint/doc-html/swt_paint_ex.html
+++ b/examples/org.eclipse.swt.examples.paint/doc-html/swt_paint_ex.html
@@ -1,36 +1,36 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Paint Tool</title>
-</head>
-<body>
-
-<h2>SWT Example - Paint Tool</h2>
-
-<p>
-This example demonstrates the use of SWT graphics operations in the form of a
-rudimentary bitmap painting program. The Airbrush Tool implementation also
-demonstrates a mechanism for managing timed GUI operations in the background
-that are triggered by user input.
-</p>
-<p>
-Select a tool with which to draw in the drawing area. There are a number of tools
-to choose from on the toolbar. To change the color selection, click on a color in the
-palette below the drawing area: left-click for the foreground color, right-click for the
-background color.
-</p>
-<p>
-Uses SWT's GC and FontDialog, and JFace's InputDialog and action set support.
-</p>
-
-<h3>Running the example</h3>
-
-<p>From the Window menu select Show View --> Other.
-In the Show View dialog, expand SWT Examples and select the
-view named Paint. A view titled Paint will appear in your current perspective.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Paint Tool</title>
+</head>
+<body>
+
+<h2>SWT Example - Paint Tool</h2>
+
+<p>
+This example demonstrates the use of SWT graphics operations in the form of a
+rudimentary bitmap painting program. The Airbrush Tool implementation also
+demonstrates a mechanism for managing timed GUI operations in the background
+that are triggered by user input.
+</p>
+<p>
+Select a tool with which to draw in the drawing area. There are a number of tools
+to choose from on the toolbar. To change the color selection, click on a color in the
+palette below the drawing area: left-click for the foreground color, right-click for the
+background color.
+</p>
+<p>
+Uses SWT's GC and FontDialog, and JFace's InputDialog and action set support.
+</p>
+
+<h3>Running the example</h3>
+
+<p>From the Window menu select Show View --> Other.
+In the Show View dialog, expand SWT Examples and select the
+view named Paint. A view titled Paint will appear in your current perspective.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples.paint/plugin.properties b/examples/org.eclipse.swt.examples.paint/plugin.properties
index 7ec46f1cde..3b8f21a750 100755
--- a/examples/org.eclipse.swt.examples.paint/plugin.properties
+++ b/examples/org.eclipse.swt.examples.paint/plugin.properties
@@ -1,124 +1,124 @@
-providerName = Eclipse.org
-plugin.SWTPaintExample.name = SWT Paint Example Plugin
-category.SWTExamples.name = SWT Examples
-view.PaintExample.name = Paint
-
-launchcategory.SWTViewExamples.name = Workbench Views
-launchcategory.SWTViewExamples.description = \
- A collection of Standard Widget Toolkit examples that run as Views inside the Workbench. \
- These examples will create a new View in the current Perspective.
-
-launchitem.PaintExample.name = Paint
-launchitem.PaintExample.description = \
- This example demonstrates the use of SWT graphics operations in the form of a \
- rudimentary bitmap painting program. The Airbrush Tool implementation also \
- demonstrates a mechanism for managing timed GUI operations in the background \
- that are triggered by user input.\n\n\
- Select a tool with which to draw in the drawing area. There are a number of tools \
- to choose from on the toolbar. To change the color selection, click on a color in the \
- palette below the drawing area: left-click for the foreground color, right-click for the \
- background color.\n\n\
- Uses SWT's GC and FontDialog, and JFace's InputDialog and action set support.
-
-menu.Tools.label = Tools
-menu.Options.label = Options
-
-tool.Pencil.label = Pencil
-tool.Pencil.tooltip = Pencil tool
-tool.Pencil.image = icons/tool_pencil.gif
-tool.Pencil.description = Selects the Pencil tool.
-
-tool.Airbrush.label = Airbrush
-tool.Airbrush.tooltip = Airbrush tool
-tool.Airbrush.image = icons/tool_airbrush.gif
-tool.Airbrush.description = Selects the Airbrush tool.
-
-tool.Line.label = Line
-tool.Line.tooltip = Line tool
-tool.Line.image = icons/tool_line.gif
-tool.Line.description = Selects the Line tool.
-
-tool.PolyLine.label = Polygon
-tool.PolyLine.tooltip = Polygon tool
-tool.PolyLine.image = icons/tool_polyline.gif
-tool.PolyLine.description = Selects the PolyLine tool.
-
-tool.Rectangle.label = Rectangle
-tool.Rectangle.tooltip = Rectangle tool
-tool.Rectangle.image = icons/tool_rectangle.gif
-tool.Rectangle.description = Selects the Rectangle tool.
-
-tool.Ellipse.label = Ellipse
-tool.Ellipse.tooltip = Ellipse tool
-tool.Ellipse.image = icons/tool_ellipse.gif
-tool.Ellipse.description = Selects the Ellipse tool.
-
-tool.RoundedRectangle.label = Rounded Rectangle
-tool.RoundedRectangle.tooltip = Rounded Rectangle
-tool.RoundedRectangle.image = icons/tool_roundedrectangle.gif
-tool.RoundedRectangle.description = Selects the Rounded Rectangle tool.
-
-tool.Text.label = Text
-tool.Text.tooltip = Text tool
-tool.Text.image = icons/tool_text.gif
-tool.Text.description = Selects the Text tool.
-tool.Text.settings.defaulttext = Hello!
-tool.Text.dialog.title = Text Tool Settings
-tool.Text.dialog.message = Please enter the new text string to be painted.
-
-tool.Null.label = <none>
-
-fill.None.label = No Fill
-fill.None.tooltip = No fill mode
-fill.None.image = icons/fill_none.gif
-fill.None.description = Selects No Fill mode.
-
-fill.Outline.label = Outline Fill
-fill.Outline.tooltip = Outline fill mode
-fill.Outline.image = icons/fill_outline.gif
-fill.Outline.description = Selects Outline Fill mode.
-
-fill.Solid.label = Solid Fill
-fill.Solid.tooltip = Solid fill mode
-fill.Solid.image = icons/fill_solid.gif
-fill.Solid.description = Selects Solid Fill mode.
-
-linestyle.Solid.label = Solid Line
-linestyle.Solid.tooltip = Solid line style
-linestyle.Solid.image = icons/linestyle_solid.gif
-linestyle.Solid.description = Select Solid Line style.
-
-linestyle.Dot.label = Dotted Line
-linestyle.Dot.tooltip = Dotted line style
-linestyle.Dot.image = icons/linestyle_dot.gif
-linestyle.Dot.description = Select Dotted Line style.
-
-linestyle.Dash.label = Dashed Line
-linestyle.Dash.tooltip = Dashed line style
-linestyle.Dash.image = icons/linestyle_dash.gif
-linestyle.Dash.description = Select Dashed Line style.
-
-linestyle.DashDot.label = Dash-Dot Line
-linestyle.DashDot.tooltip = Dash-Dot line style
-linestyle.DashDot.image = icons/linestyle_dashdot.gif
-linestyle.DashDot.description = Select Dash-Dot Line style.
-
-options.Font.label = Text Tool Font
-options.Font.tooltip = Select Text Tool font
-options.Font.image = icons/options_font.gif
-options.Font.description = Selects Text Tool font.
-options.Font.dialog.title = Text Tool Font
-
-settings.AirbrushRadius.text = Airbrush Radius
-settings.AirbrushIntensity.text = Airbrush Intensity
-
-session.Null.message = Select a tool...
-session.ContinuousPaint.message = Click and drag to draw...
-session.DragInteractivePaint.message = Click and drag to preview, release to draw, right-click to cancel...
-session.SegmentedInteractivePaint.message.anchorMode = Click to set anchor...
-session.SegmentedInteractivePaint.message.interactiveMode = Click to draw, double-click to close figure, right-click to cancel...
-session.Text.message = Click to draw text, right-click to edit text...
-
-status.Coord.format = ({0}, {1})
-status.CoordRange.format = ({0}, {1}) - ({2}, {3})
-status.Bar.format = {0} : {1} {2}
+providerName = Eclipse.org
+plugin.SWTPaintExample.name = SWT Paint Example Plugin
+category.SWTExamples.name = SWT Examples
+view.PaintExample.name = Paint
+
+launchcategory.SWTViewExamples.name = Workbench Views
+launchcategory.SWTViewExamples.description = \
+ A collection of Standard Widget Toolkit examples that run as Views inside the Workbench. \
+ These examples will create a new View in the current Perspective.
+
+launchitem.PaintExample.name = Paint
+launchitem.PaintExample.description = \
+ This example demonstrates the use of SWT graphics operations in the form of a \
+ rudimentary bitmap painting program. The Airbrush Tool implementation also \
+ demonstrates a mechanism for managing timed GUI operations in the background \
+ that are triggered by user input.\n\n\
+ Select a tool with which to draw in the drawing area. There are a number of tools \
+ to choose from on the toolbar. To change the color selection, click on a color in the \
+ palette below the drawing area: left-click for the foreground color, right-click for the \
+ background color.\n\n\
+ Uses SWT's GC and FontDialog, and JFace's InputDialog and action set support.
+
+menu.Tools.label = Tools
+menu.Options.label = Options
+
+tool.Pencil.label = Pencil
+tool.Pencil.tooltip = Pencil tool
+tool.Pencil.image = icons/tool_pencil.gif
+tool.Pencil.description = Selects the Pencil tool.
+
+tool.Airbrush.label = Airbrush
+tool.Airbrush.tooltip = Airbrush tool
+tool.Airbrush.image = icons/tool_airbrush.gif
+tool.Airbrush.description = Selects the Airbrush tool.
+
+tool.Line.label = Line
+tool.Line.tooltip = Line tool
+tool.Line.image = icons/tool_line.gif
+tool.Line.description = Selects the Line tool.
+
+tool.PolyLine.label = Polygon
+tool.PolyLine.tooltip = Polygon tool
+tool.PolyLine.image = icons/tool_polyline.gif
+tool.PolyLine.description = Selects the PolyLine tool.
+
+tool.Rectangle.label = Rectangle
+tool.Rectangle.tooltip = Rectangle tool
+tool.Rectangle.image = icons/tool_rectangle.gif
+tool.Rectangle.description = Selects the Rectangle tool.
+
+tool.Ellipse.label = Ellipse
+tool.Ellipse.tooltip = Ellipse tool
+tool.Ellipse.image = icons/tool_ellipse.gif
+tool.Ellipse.description = Selects the Ellipse tool.
+
+tool.RoundedRectangle.label = Rounded Rectangle
+tool.RoundedRectangle.tooltip = Rounded Rectangle
+tool.RoundedRectangle.image = icons/tool_roundedrectangle.gif
+tool.RoundedRectangle.description = Selects the Rounded Rectangle tool.
+
+tool.Text.label = Text
+tool.Text.tooltip = Text tool
+tool.Text.image = icons/tool_text.gif
+tool.Text.description = Selects the Text tool.
+tool.Text.settings.defaulttext = Hello!
+tool.Text.dialog.title = Text Tool Settings
+tool.Text.dialog.message = Please enter the new text string to be painted.
+
+tool.Null.label = <none>
+
+fill.None.label = No Fill
+fill.None.tooltip = No fill mode
+fill.None.image = icons/fill_none.gif
+fill.None.description = Selects No Fill mode.
+
+fill.Outline.label = Outline Fill
+fill.Outline.tooltip = Outline fill mode
+fill.Outline.image = icons/fill_outline.gif
+fill.Outline.description = Selects Outline Fill mode.
+
+fill.Solid.label = Solid Fill
+fill.Solid.tooltip = Solid fill mode
+fill.Solid.image = icons/fill_solid.gif
+fill.Solid.description = Selects Solid Fill mode.
+
+linestyle.Solid.label = Solid Line
+linestyle.Solid.tooltip = Solid line style
+linestyle.Solid.image = icons/linestyle_solid.gif
+linestyle.Solid.description = Select Solid Line style.
+
+linestyle.Dot.label = Dotted Line
+linestyle.Dot.tooltip = Dotted line style
+linestyle.Dot.image = icons/linestyle_dot.gif
+linestyle.Dot.description = Select Dotted Line style.
+
+linestyle.Dash.label = Dashed Line
+linestyle.Dash.tooltip = Dashed line style
+linestyle.Dash.image = icons/linestyle_dash.gif
+linestyle.Dash.description = Select Dashed Line style.
+
+linestyle.DashDot.label = Dash-Dot Line
+linestyle.DashDot.tooltip = Dash-Dot line style
+linestyle.DashDot.image = icons/linestyle_dashdot.gif
+linestyle.DashDot.description = Select Dash-Dot Line style.
+
+options.Font.label = Text Tool Font
+options.Font.tooltip = Select Text Tool font
+options.Font.image = icons/options_font.gif
+options.Font.description = Selects Text Tool font.
+options.Font.dialog.title = Text Tool Font
+
+settings.AirbrushRadius.text = Airbrush Radius
+settings.AirbrushIntensity.text = Airbrush Intensity
+
+session.Null.message = Select a tool...
+session.ContinuousPaint.message = Click and drag to draw...
+session.DragInteractivePaint.message = Click and drag to preview, release to draw, right-click to cancel...
+session.SegmentedInteractivePaint.message.anchorMode = Click to set anchor...
+session.SegmentedInteractivePaint.message.interactiveMode = Click to draw, double-click to close figure, right-click to cancel...
+session.Text.message = Click to draw text, right-click to edit text...
+
+status.Coord.format = ({0}, {1})
+status.CoordRange.format = ({0}, {1}) - ({2}, {3})
+status.Bar.format = {0} : {1} {2}
diff --git a/examples/org.eclipse.swt.examples.paint/plugin.xml b/examples/org.eclipse.swt.examples.paint/plugin.xml
index 33c25bec28..47542615b6 100755
--- a/examples/org.eclipse.swt.examples.paint/plugin.xml
+++ b/examples/org.eclipse.swt.examples.paint/plugin.xml
@@ -1,55 +1,55 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin
- id="org.eclipse.swt.examples.paint"
- name="%plugin.SWTPaintExample.name"
- version="2.1.0"
- provider-name="%providerName"
- class="org.eclipse.swt.examples.paint.PaintPlugin">
-
-<!-- Runtime -->
- <runtime>
- <library name="paint.jar">
- <packages prefixes="org.eclipse.swt.examples.paint"/>
- </library>
- </runtime>
-<!-- Required plugins -->
- <requires>
- <import plugin="org.eclipse.core.runtime"/>
- <import plugin="org.eclipse.core.resources"/>
- <import plugin="org.eclipse.ui"/>
- <import plugin="org.eclipse.swt"/>
- </requires>
-
-
-<!-- Extension points -->
-<!-- Extensions -->
- <extension
- point="org.eclipse.ui.views">
- <view
- name="%view.PaintExample.name"
- icon="icons/paint_example.gif"
- category="org.eclipse.swt.examples.category"
- class="org.eclipse.swt.examples.paint.PaintView"
- id="org.eclipse.swt.examples.paint.view">
- </view>
- </extension>
- <extension
- point="org.eclipse.swt.examples.launcher.launchItems">
- <category
- name="%launchcategory.SWTViewExamples.name"
- description="%launchcategory.SWTViewExamples.description"
- id="org.eclipse.swt.examples.launchViewCategory">
- </category>
- <item
- name="%launchitem.PaintExample.name"
- icon="icons/paint_example.gif"
- description="%launchitem.PaintExample.description"
- category="org.eclipse.swt.examples.launchViewCategory"
- id="org.eclipse.swt.examples.paint.viewlauncher">
- <view
- viewId="org.eclipse.swt.examples.paint.view">
- </view>
- </item>
- </extension>
-
-</plugin>
+<?xml version="1.0" encoding="UTF-8"?>
+<plugin
+ id="org.eclipse.swt.examples.paint"
+ name="%plugin.SWTPaintExample.name"
+ version="2.1.0"
+ provider-name="%providerName"
+ class="org.eclipse.swt.examples.paint.PaintPlugin">
+
+<!-- Runtime -->
+ <runtime>
+ <library name="paint.jar">
+ <packages prefixes="org.eclipse.swt.examples.paint"/>
+ </library>
+ </runtime>
+<!-- Required plugins -->
+ <requires>
+ <import plugin="org.eclipse.core.runtime"/>
+ <import plugin="org.eclipse.core.resources"/>
+ <import plugin="org.eclipse.ui"/>
+ <import plugin="org.eclipse.swt"/>
+ </requires>
+
+
+<!-- Extension points -->
+<!-- Extensions -->
+ <extension
+ point="org.eclipse.ui.views">
+ <view
+ name="%view.PaintExample.name"
+ icon="icons/paint_example.gif"
+ category="org.eclipse.swt.examples.category"
+ class="org.eclipse.swt.examples.paint.PaintView"
+ id="org.eclipse.swt.examples.paint.view">
+ </view>
+ </extension>
+ <extension
+ point="org.eclipse.swt.examples.launcher.launchItems">
+ <category
+ name="%launchcategory.SWTViewExamples.name"
+ description="%launchcategory.SWTViewExamples.description"
+ id="org.eclipse.swt.examples.launchViewCategory">
+ </category>
+ <item
+ name="%launchitem.PaintExample.name"
+ icon="icons/paint_example.gif"
+ description="%launchitem.PaintExample.description"
+ category="org.eclipse.swt.examples.launchViewCategory"
+ id="org.eclipse.swt.examples.paint.viewlauncher">
+ <view
+ viewId="org.eclipse.swt.examples.paint.view">
+ </view>
+ </item>
+ </extension>
+
+</plugin>
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/AirbrushTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/AirbrushTool.java
index b6884de51a..15d0b38bcc 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/AirbrushTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/AirbrushTool.java
@@ -1,74 +1,74 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import java.util.Random; import org.eclipse.swt.graphics.*;
-
-/**
- * An airbrush tool.
- */
-public class AirbrushTool extends ContinuousPaintSession implements PaintTool {
- private ToolSettings settings;
- private Random random;
- private int cachedRadiusSquared;
- private int cachedNumPoints;
-
- /**
- * Constructs a Tool.
- *
- * @param toolSettings the new tool settings
- * @param paintSurface the PaintSurface we will render on.
- */
- public AirbrushTool(ToolSettings toolSettings, PaintSurface paintSurface) {
- super(paintSurface);
- random = new Random();
- setRetriggerTimer(10);
- set(toolSettings);
- }
-
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings) {
- // compute things we need to know for drawing
- settings = toolSettings;
- cachedRadiusSquared = settings.airbrushRadius * settings.airbrushRadius;
- cachedNumPoints = 314 * settings.airbrushIntensity * cachedRadiusSquared / 250000;
- if (cachedNumPoints == 0 && settings.airbrushIntensity != 0)
- cachedNumPoints = 1;
- }
-
- /**
- * Returns the name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName() {
- return PaintPlugin.getResourceString("tool.Airbrush.label");
- }
-
- /*
- * Template method for drawing
- */
- protected void render(Point point) {
- // Draws a bunch (cachedNumPoints) of random pixels within a specified circle (cachedRadiusSquared).
- ContainerFigure cfig = new ContainerFigure();
-
- for (int i = 0; i < cachedNumPoints; ++i) {
- int randX, randY;
- do {
- randX = (int) ((random.nextDouble() - 0.5) * settings.airbrushRadius * 2.0);
- randY = (int) ((random.nextDouble() - 0.5) * settings.airbrushRadius * 2.0);
- } while (randX * randX + randY * randY > cachedRadiusSquared);
- cfig.add(new PointFigure(settings.commonForegroundColor, point.x + randX, point.y + randY));
- }
- getPaintSurface().drawFigure(cfig);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import java.util.Random; import org.eclipse.swt.graphics.*;
+
+/**
+ * An airbrush tool.
+ */
+public class AirbrushTool extends ContinuousPaintSession implements PaintTool {
+ private ToolSettings settings;
+ private Random random;
+ private int cachedRadiusSquared;
+ private int cachedNumPoints;
+
+ /**
+ * Constructs a Tool.
+ *
+ * @param toolSettings the new tool settings
+ * @param paintSurface the PaintSurface we will render on.
+ */
+ public AirbrushTool(ToolSettings toolSettings, PaintSurface paintSurface) {
+ super(paintSurface);
+ random = new Random();
+ setRetriggerTimer(10);
+ set(toolSettings);
+ }
+
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings) {
+ // compute things we need to know for drawing
+ settings = toolSettings;
+ cachedRadiusSquared = settings.airbrushRadius * settings.airbrushRadius;
+ cachedNumPoints = 314 * settings.airbrushIntensity * cachedRadiusSquared / 250000;
+ if (cachedNumPoints == 0 && settings.airbrushIntensity != 0)
+ cachedNumPoints = 1;
+ }
+
+ /**
+ * Returns the name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName() {
+ return PaintPlugin.getResourceString("tool.Airbrush.label");
+ }
+
+ /*
+ * Template method for drawing
+ */
+ protected void render(Point point) {
+ // Draws a bunch (cachedNumPoints) of random pixels within a specified circle (cachedRadiusSquared).
+ ContainerFigure cfig = new ContainerFigure();
+
+ for (int i = 0; i < cachedNumPoints; ++i) {
+ int randX, randY;
+ do {
+ randX = (int) ((random.nextDouble() - 0.5) * settings.airbrushRadius * 2.0);
+ randY = (int) ((random.nextDouble() - 0.5) * settings.airbrushRadius * 2.0);
+ } while (randX * randX + randY * randY > cachedRadiusSquared);
+ cfig.add(new PointFigure(settings.commonForegroundColor, point.x + randX, point.y + randY));
+ }
+ getPaintSurface().drawFigure(cfig);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/BasicPaintSession.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/BasicPaintSession.java
index 1a7e3942b6..2807cc28ce 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/BasicPaintSession.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/BasicPaintSession.java
@@ -1,12 +1,12 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-public abstract class BasicPaintSession implements PaintSession {
- /** * The paint surface */ private PaintSurface paintSurface; /** * Constructs a PaintSession. * * @param paintSurface the drawing surface to use */ protected BasicPaintSession(PaintSurface paintSurface) { this.paintSurface = paintSurface; } /**
- * Returns the paint surface associated with this paint session. * * @return the associated PaintSurface */ public PaintSurface getPaintSurface() { return paintSurface; } }
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+public abstract class BasicPaintSession implements PaintSession {
+ /** * The paint surface */ private PaintSurface paintSurface; /** * Constructs a PaintSession. * * @param paintSurface the drawing surface to use */ protected BasicPaintSession(PaintSurface paintSurface) { this.paintSurface = paintSurface; } /**
+ * Returns the paint surface associated with this paint session. * * @return the associated PaintSurface */ public PaintSurface getPaintSurface() { return paintSurface; } }
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContainerFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContainerFigure.java
index 8416429f6a..4c511841c1 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContainerFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContainerFigure.java
@@ -1,89 +1,89 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * Container for Figure objects with stacking preview mechanism.
- */
-public class ContainerFigure extends Figure {
- private static final int INITIAL_ARRAY_SIZE = 16;
-
- Figure[] objectStack = null;
- int nextIndex = 0;
-
- /**
- * Constructs an empty Container
- */
- public ContainerFigure() {
- }
- /**
- * Adds an object to the container for later drawing.
- *
- * @param object the object to add to the drawing list
- */
- public void add(Figure object) {
- if (objectStack == null) {
- objectStack = new Figure[INITIAL_ARRAY_SIZE];
- } else if (objectStack.length <= nextIndex) {
- Figure[] newObjectStack = new Figure[objectStack.length * 2];
- System.arraycopy(objectStack, 0, newObjectStack, 0, objectStack.length);
- objectStack = newObjectStack;
- }
- objectStack[nextIndex] = object;
- ++nextIndex;
- }
- /**
- * Determines if the container is empty.
- * @return true if the container is empty
- */
- public boolean isEmpty() {
- return nextIndex == 0;
- }
- /**
- * Adds an object to the container and draws its preview then updates the supplied preview state.
- *
- * @param object the object to add to the drawing list
- * @param gc the GC to draw on
- * @param offset the offset to add to virtual coordinates to get display coordinates
- * @param rememberedState the state returned by a previous drawPreview() or addAndPreview()
- * using this Container, may be null if there was no such previous call
- * @return object state that must be passed to erasePreview() later to erase this object
- */
-// public Object addAndPreview(Figure object, GC gc, Point offset, Object rememberedState) {
-// Object[] stateStack = (Object[]) rememberedState;
-// if (stateStack == null) {
-// stateStack = new Object[INITIAL_ARRAY_SIZE];
-// } else if (stateStack.length <= nextIndex) {
-// Object[] newStateStack = new Object[stateStack.length * 2];
-// System.arraycopy(stateStack, 0, newStateStack, 0, stateStack.length);
-// stateStack = newStateStack;
-// }
-// add(object);
-// stateStack[nextIndex - 1] = object.drawPreview(gc, offset);
-// return stateStack;
-// }
- /**
- * Clears the container.
- * <p>
- * Note that erasePreview() cannot be called after this point to erase any previous
- * drawPreview()'s.
- * </p>
- */
- public void clear() {
- while (--nextIndex > 0) objectStack[nextIndex] = null;
- nextIndex = 0;
- }
- public void draw(FigureDrawContext fdc) {
- for (int i = 0; i < nextIndex; ++i) objectStack[i].draw(fdc);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- for (int i = 0; i < nextIndex; ++i) objectStack[i].addDamagedRegion(fdc, region);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * Container for Figure objects with stacking preview mechanism.
+ */
+public class ContainerFigure extends Figure {
+ private static final int INITIAL_ARRAY_SIZE = 16;
+
+ Figure[] objectStack = null;
+ int nextIndex = 0;
+
+ /**
+ * Constructs an empty Container
+ */
+ public ContainerFigure() {
+ }
+ /**
+ * Adds an object to the container for later drawing.
+ *
+ * @param object the object to add to the drawing list
+ */
+ public void add(Figure object) {
+ if (objectStack == null) {
+ objectStack = new Figure[INITIAL_ARRAY_SIZE];
+ } else if (objectStack.length <= nextIndex) {
+ Figure[] newObjectStack = new Figure[objectStack.length * 2];
+ System.arraycopy(objectStack, 0, newObjectStack, 0, objectStack.length);
+ objectStack = newObjectStack;
+ }
+ objectStack[nextIndex] = object;
+ ++nextIndex;
+ }
+ /**
+ * Determines if the container is empty.
+ * @return true if the container is empty
+ */
+ public boolean isEmpty() {
+ return nextIndex == 0;
+ }
+ /**
+ * Adds an object to the container and draws its preview then updates the supplied preview state.
+ *
+ * @param object the object to add to the drawing list
+ * @param gc the GC to draw on
+ * @param offset the offset to add to virtual coordinates to get display coordinates
+ * @param rememberedState the state returned by a previous drawPreview() or addAndPreview()
+ * using this Container, may be null if there was no such previous call
+ * @return object state that must be passed to erasePreview() later to erase this object
+ */
+// public Object addAndPreview(Figure object, GC gc, Point offset, Object rememberedState) {
+// Object[] stateStack = (Object[]) rememberedState;
+// if (stateStack == null) {
+// stateStack = new Object[INITIAL_ARRAY_SIZE];
+// } else if (stateStack.length <= nextIndex) {
+// Object[] newStateStack = new Object[stateStack.length * 2];
+// System.arraycopy(stateStack, 0, newStateStack, 0, stateStack.length);
+// stateStack = newStateStack;
+// }
+// add(object);
+// stateStack[nextIndex - 1] = object.drawPreview(gc, offset);
+// return stateStack;
+// }
+ /**
+ * Clears the container.
+ * <p>
+ * Note that erasePreview() cannot be called after this point to erase any previous
+ * drawPreview()'s.
+ * </p>
+ */
+ public void clear() {
+ while (--nextIndex > 0) objectStack[nextIndex] = null;
+ nextIndex = 0;
+ }
+ public void draw(FigureDrawContext fdc) {
+ for (int i = 0; i < nextIndex; ++i) objectStack[i].draw(fdc);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ for (int i = 0; i < nextIndex; ++i) objectStack[i].addDamagedRegion(fdc, region);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContinuousPaintSession.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContinuousPaintSession.java
index f5efcb789d..cfaf886c50 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContinuousPaintSession.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ContinuousPaintSession.java
@@ -1,228 +1,228 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*;
-
-/**
- * The superclass for paint tools that draw continuously along the path
- * traced by the mouse's movement while the button is depressed
- */
-public abstract class ContinuousPaintSession extends BasicPaintSession {
- /**
- * True if a click-drag is in progress.
- */
- private boolean dragInProgress = false;
-
- /**
- * A cached Point array for drawing.
- */
- private Point[] points = new Point[] { new Point(-1, -1), new Point(-1, -1) };
-
- /**
- * The time to wait between retriggers in milliseconds.
- */
- private int retriggerInterval = 0;
-
- /**
- * The currently valid RetriggerHandler
- */
- protected Runnable retriggerHandler = null;
-
- /**
- * Constructs a ContinuousPaintSession.
- *
- * @param paintSurface the drawing surface to use
- */
- protected ContinuousPaintSession(PaintSurface paintSurface) {
- super(paintSurface);
- }
-
- /**
- * Sets the retrigger timer.
- * <p>
- * After the timer elapses, if the mouse is still hovering over the same point with the
- * drag button pressed, a new render order is issued and the timer is restarted.
- * </p>
- * @param interval the time in milliseconds to wait between retriggers, 0 to disable
- */
- public void setRetriggerTimer(int interval) {
- retriggerInterval = interval;
- }
-
- /**
- * Activates the tool.
- */
- public void beginSession() {
- getPaintSurface().
- setStatusMessage(PaintPlugin.getResourceString("session.ContinuousPaint.message"));
- dragInProgress = false;
- }
-
- /**
- * Deactivates the tool.
- */
- public void endSession() {
- abortRetrigger();
- }
-
- /**
- * Aborts the current operation.
- */
- public void resetSession() {
- abortRetrigger();
- }
-
- /**
- * Handles a mouseDown event.
- *
- * @param event the mouse event detail information
- */
- public final void mouseDown(MouseEvent event) {
- if (event.button != 1) return;
- if (dragInProgress) return; // spurious event
- dragInProgress = true;
-
- points[0].x = event.x;
- points[0].y = event.y;
- render(points[0]);
- prepareRetrigger();
- }
-
- /**
- * Handles a mouseDoubleClick event.
- *
- * @param event the mouse event detail information
- */
- public final void mouseDoubleClick(MouseEvent event) {
- }
-
- /**
- * Handles a mouseUp event.
- *
- * @param event the mouse event detail information
- */
- public final void mouseUp(MouseEvent event) {
- if (event.button != 1) return;
- if (! dragInProgress) return; // spurious event
- abortRetrigger();
- mouseSegmentFinished(event);
- dragInProgress = false;
- }
-
- /**
- * Handles a mouseMove event.
- *
- * @param event the mouse event detail information
- */
- public final void mouseMove(MouseEvent event) {
- final PaintSurface ps = getPaintSurface();
- ps.setStatusCoord(ps.getCurrentPosition());
- if (! dragInProgress) return;
- mouseSegmentFinished(event);
- prepareRetrigger();
- }
-
- /**
- * Handle a rendering segment
- *
- * @param event the mouse event detail information
- */
- private final void mouseSegmentFinished(MouseEvent event) {
- if (points[0].x == -1) return; // spurious event
- if (points[0].x != event.x || points[0].y != event.y) {
- // draw new segment
- points[1].x = event.x;
- points[1].y = event.y;
- renderContinuousSegment();
- }
- }
-
- /**
- * Draws a continuous segment from points[0] to points[1].
- * Assumes points[0] has been drawn already.
- *
- * @post points[0] will refer to the same point as points[1]
- */
- protected void renderContinuousSegment() {
- /* A lazy but effective line drawing algorithm */
- final int dX = points[1].x - points[0].x;
- final int dY = points[1].y - points[0].y;
- int absdX = Math.abs(dX);
- int absdY = Math.abs(dY);
-
- if ((dX == 0) && (dY == 0)) return;
-
- if (absdY > absdX) {
- final int incfpX = (dX << 16) / absdY;
- final int incY = (dY > 0) ? 1 : -1;
- int fpX = points[0].x << 16; // X in fixedpoint format
-
- while (--absdY >= 0) {
- points[0].y += incY;
- points[0].x = (fpX += incfpX) >> 16;
- render(points[0]);
- }
- if (points[0].x == points[1].x) return;
- points[0].x = points[1].x;
- } else {
- final int incfpY = (dY << 16) / absdX;
- final int incX = (dX > 0) ? 1 : -1;
- int fpY = points[0].y << 16; // Y in fixedpoint format
-
- while (--absdX >= 0) {
- points[0].x += incX;
- points[0].y = (fpY += incfpY) >> 16;
- render(points[0]);
- }
- if (points[0].y == points[1].y) return;
- points[0].y = points[1].y;
- }
- render(points[0]);
- }
-
- /**
- * Prepare the retrigger timer
- */
- private final void prepareRetrigger() {
- if (retriggerInterval > 0) {
- /*
- * timerExec() provides a lightweight mechanism for running code at intervals from within
- * the event loop when timing accuracy is not important.
- *
- * Since it is not possible to cancel a timerExec(), we remember the Runnable that is
- * active in order to distinguish the valid one from the stale ones. In practice,
- * if the interval is 1/100th of a second, then creating a few hundred new RetriggerHandlers
- * each second will not cause a significant performance hit.
- */
- Display display = getPaintSurface().getDisplay();
- retriggerHandler = new Runnable() {
- public void run() {
- if (retriggerHandler == this) {
- render(points[0]);
- prepareRetrigger();
- }
- }
- };
- display.timerExec(retriggerInterval, retriggerHandler);
- }
- }
-
- /**
- * Aborts the retrigger timer
- */
- private final void abortRetrigger() {
- retriggerHandler = null;
- }
-
- /**
- * Template method: Renders a point.
- * @param point, the point to render
- */
- protected abstract void render(Point point);
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*;
+
+/**
+ * The superclass for paint tools that draw continuously along the path
+ * traced by the mouse's movement while the button is depressed
+ */
+public abstract class ContinuousPaintSession extends BasicPaintSession {
+ /**
+ * True if a click-drag is in progress.
+ */
+ private boolean dragInProgress = false;
+
+ /**
+ * A cached Point array for drawing.
+ */
+ private Point[] points = new Point[] { new Point(-1, -1), new Point(-1, -1) };
+
+ /**
+ * The time to wait between retriggers in milliseconds.
+ */
+ private int retriggerInterval = 0;
+
+ /**
+ * The currently valid RetriggerHandler
+ */
+ protected Runnable retriggerHandler = null;
+
+ /**
+ * Constructs a ContinuousPaintSession.
+ *
+ * @param paintSurface the drawing surface to use
+ */
+ protected ContinuousPaintSession(PaintSurface paintSurface) {
+ super(paintSurface);
+ }
+
+ /**
+ * Sets the retrigger timer.
+ * <p>
+ * After the timer elapses, if the mouse is still hovering over the same point with the
+ * drag button pressed, a new render order is issued and the timer is restarted.
+ * </p>
+ * @param interval the time in milliseconds to wait between retriggers, 0 to disable
+ */
+ public void setRetriggerTimer(int interval) {
+ retriggerInterval = interval;
+ }
+
+ /**
+ * Activates the tool.
+ */
+ public void beginSession() {
+ getPaintSurface().
+ setStatusMessage(PaintPlugin.getResourceString("session.ContinuousPaint.message"));
+ dragInProgress = false;
+ }
+
+ /**
+ * Deactivates the tool.
+ */
+ public void endSession() {
+ abortRetrigger();
+ }
+
+ /**
+ * Aborts the current operation.
+ */
+ public void resetSession() {
+ abortRetrigger();
+ }
+
+ /**
+ * Handles a mouseDown event.
+ *
+ * @param event the mouse event detail information
+ */
+ public final void mouseDown(MouseEvent event) {
+ if (event.button != 1) return;
+ if (dragInProgress) return; // spurious event
+ dragInProgress = true;
+
+ points[0].x = event.x;
+ points[0].y = event.y;
+ render(points[0]);
+ prepareRetrigger();
+ }
+
+ /**
+ * Handles a mouseDoubleClick event.
+ *
+ * @param event the mouse event detail information
+ */
+ public final void mouseDoubleClick(MouseEvent event) {
+ }
+
+ /**
+ * Handles a mouseUp event.
+ *
+ * @param event the mouse event detail information
+ */
+ public final void mouseUp(MouseEvent event) {
+ if (event.button != 1) return;
+ if (! dragInProgress) return; // spurious event
+ abortRetrigger();
+ mouseSegmentFinished(event);
+ dragInProgress = false;
+ }
+
+ /**
+ * Handles a mouseMove event.
+ *
+ * @param event the mouse event detail information
+ */
+ public final void mouseMove(MouseEvent event) {
+ final PaintSurface ps = getPaintSurface();
+ ps.setStatusCoord(ps.getCurrentPosition());
+ if (! dragInProgress) return;
+ mouseSegmentFinished(event);
+ prepareRetrigger();
+ }
+
+ /**
+ * Handle a rendering segment
+ *
+ * @param event the mouse event detail information
+ */
+ private final void mouseSegmentFinished(MouseEvent event) {
+ if (points[0].x == -1) return; // spurious event
+ if (points[0].x != event.x || points[0].y != event.y) {
+ // draw new segment
+ points[1].x = event.x;
+ points[1].y = event.y;
+ renderContinuousSegment();
+ }
+ }
+
+ /**
+ * Draws a continuous segment from points[0] to points[1].
+ * Assumes points[0] has been drawn already.
+ *
+ * @post points[0] will refer to the same point as points[1]
+ */
+ protected void renderContinuousSegment() {
+ /* A lazy but effective line drawing algorithm */
+ final int dX = points[1].x - points[0].x;
+ final int dY = points[1].y - points[0].y;
+ int absdX = Math.abs(dX);
+ int absdY = Math.abs(dY);
+
+ if ((dX == 0) && (dY == 0)) return;
+
+ if (absdY > absdX) {
+ final int incfpX = (dX << 16) / absdY;
+ final int incY = (dY > 0) ? 1 : -1;
+ int fpX = points[0].x << 16; // X in fixedpoint format
+
+ while (--absdY >= 0) {
+ points[0].y += incY;
+ points[0].x = (fpX += incfpX) >> 16;
+ render(points[0]);
+ }
+ if (points[0].x == points[1].x) return;
+ points[0].x = points[1].x;
+ } else {
+ final int incfpY = (dY << 16) / absdX;
+ final int incX = (dX > 0) ? 1 : -1;
+ int fpY = points[0].y << 16; // Y in fixedpoint format
+
+ while (--absdX >= 0) {
+ points[0].x += incX;
+ points[0].y = (fpY += incfpY) >> 16;
+ render(points[0]);
+ }
+ if (points[0].y == points[1].y) return;
+ points[0].y = points[1].y;
+ }
+ render(points[0]);
+ }
+
+ /**
+ * Prepare the retrigger timer
+ */
+ private final void prepareRetrigger() {
+ if (retriggerInterval > 0) {
+ /*
+ * timerExec() provides a lightweight mechanism for running code at intervals from within
+ * the event loop when timing accuracy is not important.
+ *
+ * Since it is not possible to cancel a timerExec(), we remember the Runnable that is
+ * active in order to distinguish the valid one from the stale ones. In practice,
+ * if the interval is 1/100th of a second, then creating a few hundred new RetriggerHandlers
+ * each second will not cause a significant performance hit.
+ */
+ Display display = getPaintSurface().getDisplay();
+ retriggerHandler = new Runnable() {
+ public void run() {
+ if (retriggerHandler == this) {
+ render(points[0]);
+ prepareRetrigger();
+ }
+ }
+ };
+ display.timerExec(retriggerInterval, retriggerHandler);
+ }
+ }
+
+ /**
+ * Aborts the retrigger timer
+ */
+ private final void abortRetrigger() {
+ retriggerHandler = null;
+ }
+
+ /**
+ * Template method: Renders a point.
+ * @param point, the point to render
+ */
+ protected abstract void render(Point point);
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/DragPaintSession.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/DragPaintSession.java
index 728f1707a1..91d343cdec 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/DragPaintSession.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/DragPaintSession.java
@@ -1,131 +1,131 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.*;
-
-/**
- * The superclass for paint tools that use click-drag-release motions to
- * draw objects.
- */
-public abstract class DragPaintSession extends BasicPaintSession {
- /**
- * True if a click-drag is in progress
- */
- private boolean dragInProgress = false;
-
- /**
- * The position of the first click in a click-drag
- */
- private Point anchorPosition = new Point(-1, -1);
-
- /**
- * A temporary point
- */
- private Point tempPosition = new Point(-1, -1);
-
- /**
- * Constructs a PaintSession.
- *
- * @param getPaintSurface() the drawing surface to use
- */
- protected DragPaintSession(PaintSurface paintSurface) {
- super(paintSurface);
- }
-
- /**
- * Activates the tool.
- */
- public void beginSession() {
- getPaintSurface().
- setStatusMessage(PaintPlugin.getResourceString("session.DragInteractivePaint.message"));
- anchorPosition.x = -1;
- dragInProgress = false;
- }
-
- /**
- * Deactivates the tool.
- */
- public void endSession() {
- }
-
- /**
- * Resets the tool.
- * Aborts any operation in progress.
- */
- public void resetSession() {
- getPaintSurface().clearRubberbandSelection();
- anchorPosition.x = -1;
- dragInProgress = false;
- }
-
- /**
- * Handles a mouseDown event.
- *
- * @param event the mouse event detail information
- */
- public void mouseDown(MouseEvent event) {
- if (event.button != 1) return;
- if (dragInProgress) return; // spurious event
- dragInProgress = true;
-
- anchorPosition.x = event.x;
- anchorPosition.y = event.y;
- }
-
- /**
- * Handles a mouseDoubleClick event.
- *
- * @param event the mouse event detail information
- */
- public void mouseDoubleClick(MouseEvent event) {
- }
-
- /**
- * Handles a mouseUp event.
- *
- * @param event the mouse event detail information
- */
- public void mouseUp(MouseEvent event) {
- if (event.button != 1) {
- resetSession(); // abort if right or middle mouse button pressed
- return;
- }
- if (! dragInProgress) return; // spurious event
- dragInProgress = false;
- if (anchorPosition.x == -1) return; // spurious event
-
- getPaintSurface().commitRubberbandSelection();
- }
-
- /**
- * Handles a mouseMove event.
- *
- * @param event the mouse event detail information
- */
- public void mouseMove(MouseEvent event) {
- final PaintSurface ps = getPaintSurface();
- if (! dragInProgress) {
- ps.setStatusCoord(ps.getCurrentPosition());
- return;
- }
- ps.setStatusCoordRange(anchorPosition, ps.getCurrentPosition());
- ps.clearRubberbandSelection();
- tempPosition.x = event.x;
- tempPosition.y = event.y;
- ps.addRubberbandSelection(createFigure(anchorPosition, tempPosition));
- }
-
- /**
- * Template Method: Creates a Figure for drawing rubberband entities and the final product
- *
- * @param anchor the anchor point
- * @param cursor the point marking the current pointer location
- */
- protected abstract Figure createFigure(Point anchor, Point cursor);
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.*;
+
+/**
+ * The superclass for paint tools that use click-drag-release motions to
+ * draw objects.
+ */
+public abstract class DragPaintSession extends BasicPaintSession {
+ /**
+ * True if a click-drag is in progress
+ */
+ private boolean dragInProgress = false;
+
+ /**
+ * The position of the first click in a click-drag
+ */
+ private Point anchorPosition = new Point(-1, -1);
+
+ /**
+ * A temporary point
+ */
+ private Point tempPosition = new Point(-1, -1);
+
+ /**
+ * Constructs a PaintSession.
+ *
+ * @param getPaintSurface() the drawing surface to use
+ */
+ protected DragPaintSession(PaintSurface paintSurface) {
+ super(paintSurface);
+ }
+
+ /**
+ * Activates the tool.
+ */
+ public void beginSession() {
+ getPaintSurface().
+ setStatusMessage(PaintPlugin.getResourceString("session.DragInteractivePaint.message"));
+ anchorPosition.x = -1;
+ dragInProgress = false;
+ }
+
+ /**
+ * Deactivates the tool.
+ */
+ public void endSession() {
+ }
+
+ /**
+ * Resets the tool.
+ * Aborts any operation in progress.
+ */
+ public void resetSession() {
+ getPaintSurface().clearRubberbandSelection();
+ anchorPosition.x = -1;
+ dragInProgress = false;
+ }
+
+ /**
+ * Handles a mouseDown event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseDown(MouseEvent event) {
+ if (event.button != 1) return;
+ if (dragInProgress) return; // spurious event
+ dragInProgress = true;
+
+ anchorPosition.x = event.x;
+ anchorPosition.y = event.y;
+ }
+
+ /**
+ * Handles a mouseDoubleClick event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseDoubleClick(MouseEvent event) {
+ }
+
+ /**
+ * Handles a mouseUp event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseUp(MouseEvent event) {
+ if (event.button != 1) {
+ resetSession(); // abort if right or middle mouse button pressed
+ return;
+ }
+ if (! dragInProgress) return; // spurious event
+ dragInProgress = false;
+ if (anchorPosition.x == -1) return; // spurious event
+
+ getPaintSurface().commitRubberbandSelection();
+ }
+
+ /**
+ * Handles a mouseMove event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseMove(MouseEvent event) {
+ final PaintSurface ps = getPaintSurface();
+ if (! dragInProgress) {
+ ps.setStatusCoord(ps.getCurrentPosition());
+ return;
+ }
+ ps.setStatusCoordRange(anchorPosition, ps.getCurrentPosition());
+ ps.clearRubberbandSelection();
+ tempPosition.x = event.x;
+ tempPosition.y = event.y;
+ ps.addRubberbandSelection(createFigure(anchorPosition, tempPosition));
+ }
+
+ /**
+ * Template Method: Creates a Figure for drawing rubberband entities and the final product
+ *
+ * @param anchor the anchor point
+ * @param cursor the point marking the current pointer location
+ */
+ protected abstract Figure createFigure(Point anchor, Point cursor);
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseFigure.java
index 27eedb39b5..4676f49693 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseFigure.java
@@ -1,48 +1,48 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D Ellipse object
- */
-public class EllipseFigure extends Figure {
- private Color foregroundColor, backgroundColor;
- private int lineStyle, x1, y1, x2, y2;
- /**
- * Constructs an Ellipse
- * These objects are defined by any two diametrically opposing corners of a box
- * bounding the ellipse.
- *
- * @param color the color for this object
- * @param lineStyle the line style for this object
- * @param x1 the virtual X coordinate of the first corner
- * @param y1 the virtual Y coordinate of the first corner
- * @param x2 the virtual X coordinate of the second corner
- * @param y2 the virtual Y coordinate of the second corner
- */
- public EllipseFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
- this.foregroundColor = foregroundColor;
- this.backgroundColor = backgroundColor;
- this.lineStyle = lineStyle;
- this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
- }
- public void draw(FigureDrawContext fdc) {
- Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
- fdc.gc.setForeground(foregroundColor);
- fdc.gc.setBackground(backgroundColor);
- fdc.gc.setLineStyle(lineStyle);
- fdc.gc.drawOval(r.x, r.y, r.width - 1, r.height - 1);
- fdc.gc.setLineStyle(SWT.LINE_SOLID);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- region.add(fdc.toClientRectangle(x1, y1, x2, y2));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D Ellipse object
+ */
+public class EllipseFigure extends Figure {
+ private Color foregroundColor, backgroundColor;
+ private int lineStyle, x1, y1, x2, y2;
+ /**
+ * Constructs an Ellipse
+ * These objects are defined by any two diametrically opposing corners of a box
+ * bounding the ellipse.
+ *
+ * @param color the color for this object
+ * @param lineStyle the line style for this object
+ * @param x1 the virtual X coordinate of the first corner
+ * @param y1 the virtual Y coordinate of the first corner
+ * @param x2 the virtual X coordinate of the second corner
+ * @param y2 the virtual Y coordinate of the second corner
+ */
+ public EllipseFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
+ this.foregroundColor = foregroundColor;
+ this.backgroundColor = backgroundColor;
+ this.lineStyle = lineStyle;
+ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
+ fdc.gc.setForeground(foregroundColor);
+ fdc.gc.setBackground(backgroundColor);
+ fdc.gc.setLineStyle(lineStyle);
+ fdc.gc.drawOval(r.x, r.y, r.width - 1, r.height - 1);
+ fdc.gc.setLineStyle(SWT.LINE_SOLID);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ region.add(fdc.toClientRectangle(x1, y1, x2, y2));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseTool.java
index 3b3f11f2d9..4b4f07b937 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/EllipseTool.java
@@ -1,59 +1,59 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * A drawing tool.
- */
-public class EllipseTool extends DragPaintSession implements PaintTool {
- private ToolSettings settings;
-
- /**
- * Constructs a EllipseTool.
- *
- * @param toolSettings the new tool settings
- * @param paintSurface the PaintSurface we will render on.
- */
- public EllipseTool(ToolSettings toolSettings, PaintSurface paintSurface) {
- super(paintSurface);
- set(toolSettings);
- }
-
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings) {
- settings = toolSettings;
- }
-
- /**
- * Returns name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName() {
- return PaintPlugin.getResourceString("tool.Ellipse.label");
- }
-
- /*
- * Template methods for drawing
- */
- protected Figure createFigure(Point a, Point b) {
- ContainerFigure container = new ContainerFigure();
- if (settings.commonFillType != ToolSettings.ftNone)
- container.add(new SolidEllipseFigure(settings.commonBackgroundColor, a.x, a.y, b.x, b.y));
- if (settings.commonFillType != ToolSettings.ftSolid)
- container.add(new EllipseFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
- a.x, a.y, b.x, b.y));
- return container;
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * A drawing tool.
+ */
+public class EllipseTool extends DragPaintSession implements PaintTool {
+ private ToolSettings settings;
+
+ /**
+ * Constructs a EllipseTool.
+ *
+ * @param toolSettings the new tool settings
+ * @param paintSurface the PaintSurface we will render on.
+ */
+ public EllipseTool(ToolSettings toolSettings, PaintSurface paintSurface) {
+ super(paintSurface);
+ set(toolSettings);
+ }
+
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings) {
+ settings = toolSettings;
+ }
+
+ /**
+ * Returns name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName() {
+ return PaintPlugin.getResourceString("tool.Ellipse.label");
+ }
+
+ /*
+ * Template methods for drawing
+ */
+ protected Figure createFigure(Point a, Point b) {
+ ContainerFigure container = new ContainerFigure();
+ if (settings.commonFillType != ToolSettings.ftNone)
+ container.add(new SolidEllipseFigure(settings.commonBackgroundColor, a.x, a.y, b.x, b.y));
+ if (settings.commonFillType != ToolSettings.ftSolid)
+ container.add(new EllipseFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
+ a.x, a.y, b.x, b.y));
+ return container;
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/Figure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/Figure.java
index be049d1700..c828f17d66 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/Figure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/Figure.java
@@ -1,34 +1,34 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * Superinterface for all drawing objects.
- * All drawing objects know how to render themselved to the screen and can draw a
- * temporary version of themselves for previewing the general appearance of the
- * object onscreen before it gets committed.
- */
-public abstract class Figure {
- /**
- * Draws this object.
- *
- * @param fdc a parameter block specifying drawing-related information
- */
- public abstract void draw(FigureDrawContext fdc);
-
- /**
- * Computes the damaged screen region caused by drawing this object (imprecise), then
- * appends it to the supplied region.
- *
- * @param fdc a parameter block specifying drawing-related information
- * @param region a region to which additional damage areas will be added
- */
- public abstract void addDamagedRegion(FigureDrawContext fdc, Region region);
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * Superinterface for all drawing objects.
+ * All drawing objects know how to render themselved to the screen and can draw a
+ * temporary version of themselves for previewing the general appearance of the
+ * object onscreen before it gets committed.
+ */
+public abstract class Figure {
+ /**
+ * Draws this object.
+ *
+ * @param fdc a parameter block specifying drawing-related information
+ */
+ public abstract void draw(FigureDrawContext fdc);
+
+ /**
+ * Computes the damaged screen region caused by drawing this object (imprecise), then
+ * appends it to the supplied region.
+ *
+ * @param fdc a parameter block specifying drawing-related information
+ * @param region a region to which additional damage areas will be added
+ */
+ public abstract void addDamagedRegion(FigureDrawContext fdc, Region region);
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/FigureDrawContext.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/FigureDrawContext.java
index 4c08aa86cd..a1ee077c33 100644
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/FigureDrawContext.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/FigureDrawContext.java
@@ -1,36 +1,36 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-public class FigureDrawContext {
- /*
- * <p>
- * The GC must be set up as follows
- * (it will be returned to this state upon completion of drawing operations)
- * <ul>
- * <li>setXORMode(false)
- * </ul>
- * </p>
- */
- public GC gc = null;
- public int xOffset = 0, yOffset = 0; // substract to get GC coords
- public int xScale = 1, yScale = 1;
-
- public Rectangle toClientRectangle(int x1, int y1, int x2, int y2) {
- return new Rectangle(
- Math.min(x1, x2) * xScale - xOffset,
- Math.min(y1, y2) * yScale - yOffset,
- (Math.abs(x2 - x1) + 1) * xScale,
- (Math.abs(y2 - y1) + 1) * yScale);
- }
- public Point toClientPoint(int x, int y) {
- return new Point(x * xScale - xOffset, y * yScale - yOffset);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+public class FigureDrawContext {
+ /*
+ * <p>
+ * The GC must be set up as follows
+ * (it will be returned to this state upon completion of drawing operations)
+ * <ul>
+ * <li>setXORMode(false)
+ * </ul>
+ * </p>
+ */
+ public GC gc = null;
+ public int xOffset = 0, yOffset = 0; // substract to get GC coords
+ public int xScale = 1, yScale = 1;
+
+ public Rectangle toClientRectangle(int x1, int y1, int x2, int y2) {
+ return new Rectangle(
+ Math.min(x1, x2) * xScale - xOffset,
+ Math.min(y1, y2) * yScale - yOffset,
+ (Math.abs(x2 - x1) + 1) * xScale,
+ (Math.abs(y2 - y1) + 1) * yScale);
+ }
+ public Point toClientPoint(int x, int y) {
+ return new Point(x * xScale - xOffset, y * yScale - yOffset);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineFigure.java
index f7b0605cb0..cf7e68cc45 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineFigure.java
@@ -1,48 +1,48 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D Line object
- */
-public class LineFigure extends Figure {
- private Color foregroundColor, backgroundColor;
- private int lineStyle, x1, y1, x2, y2;
- /**
- * Constructs a Line
- * These objects are defined by their two end-points.
- *
- * @param color the color for this object
- * @param lineStyle the line style for this object
- * @param x1 the virtual X coordinate of the first end-point
- * @param y1 the virtual Y coordinate of the first end-point
- * @param x2 the virtual X coordinate of the second end-point
- * @param y2 the virtual Y coordinate of the second end-point
- */
- public LineFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
- this.foregroundColor = foregroundColor;
- this.backgroundColor = backgroundColor;
- this.lineStyle = lineStyle;
- this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
- }
- public void draw(FigureDrawContext fdc) {
- Point p1 = fdc.toClientPoint(x1, y1);
- Point p2 = fdc.toClientPoint(x2, y2);
- fdc.gc.setForeground(foregroundColor);
- fdc.gc.setBackground(backgroundColor);
- fdc.gc.setLineStyle(lineStyle);
- fdc.gc.drawLine(p1.x, p1.y, p2.x, p2.y);
- fdc.gc.setLineStyle(SWT.LINE_SOLID);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- region.add(fdc.toClientRectangle(x1, y1, x2, y2));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D Line object
+ */
+public class LineFigure extends Figure {
+ private Color foregroundColor, backgroundColor;
+ private int lineStyle, x1, y1, x2, y2;
+ /**
+ * Constructs a Line
+ * These objects are defined by their two end-points.
+ *
+ * @param color the color for this object
+ * @param lineStyle the line style for this object
+ * @param x1 the virtual X coordinate of the first end-point
+ * @param y1 the virtual Y coordinate of the first end-point
+ * @param x2 the virtual X coordinate of the second end-point
+ * @param y2 the virtual Y coordinate of the second end-point
+ */
+ public LineFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
+ this.foregroundColor = foregroundColor;
+ this.backgroundColor = backgroundColor;
+ this.lineStyle = lineStyle;
+ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Point p1 = fdc.toClientPoint(x1, y1);
+ Point p2 = fdc.toClientPoint(x2, y2);
+ fdc.gc.setForeground(foregroundColor);
+ fdc.gc.setBackground(backgroundColor);
+ fdc.gc.setLineStyle(lineStyle);
+ fdc.gc.drawLine(p1.x, p1.y, p2.x, p2.y);
+ fdc.gc.setLineStyle(SWT.LINE_SOLID);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ region.add(fdc.toClientRectangle(x1, y1, x2, y2));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineTool.java
index f919965c86..f802bce5d5 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/LineTool.java
@@ -1,54 +1,54 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * A line drawing tool
- */
-public class LineTool extends DragPaintSession implements PaintTool {
- private ToolSettings settings;
-
- /**
- * Constructs a LineTool.
- *
- * @param toolSettings the new tool settings
- * @param paintSurface the PaintSurface we will render on.
- */
- public LineTool(ToolSettings toolSettings, PaintSurface paintSurface) {
- super(paintSurface);
- set(toolSettings);
- }
-
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings) {
- settings = toolSettings;
- }
-
- /**
- * Returns name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName() {
- return PaintPlugin.getResourceString("tool.Line.label");
- }
-
- /*
- * Template methods for drawing
- */
- protected Figure createFigure(Point a, Point b) {
- return new LineFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
- a.x, a.y, b.x, b.y);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * A line drawing tool
+ */
+public class LineTool extends DragPaintSession implements PaintTool {
+ private ToolSettings settings;
+
+ /**
+ * Constructs a LineTool.
+ *
+ * @param toolSettings the new tool settings
+ * @param paintSurface the PaintSurface we will render on.
+ */
+ public LineTool(ToolSettings toolSettings, PaintSurface paintSurface) {
+ super(paintSurface);
+ set(toolSettings);
+ }
+
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings) {
+ settings = toolSettings;
+ }
+
+ /**
+ * Returns name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName() {
+ return PaintPlugin.getResourceString("tool.Line.label");
+ }
+
+ /*
+ * Template methods for drawing
+ */
+ protected Figure createFigure(Point a, Point b) {
+ return new LineFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
+ a.x, a.y, b.x, b.y);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintPlugin.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintPlugin.java
index e4da0cf02f..fcb6a570ea 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintPlugin.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintPlugin.java
@@ -1,80 +1,80 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.core.runtime.*;
-import org.eclipse.ui.plugin.*;
-
-import java.text.*;
-import java.util.*;
-
-/**
- * The main plugin class to be used in the desktop.
- */
-public class PaintPlugin extends AbstractUIPlugin {
- //The shared instance.
- private static PaintPlugin plugin;
- private static ResourceBundle resourceBundle;
-
- /**
- * Constructs the Paint plugin.
- */
- public PaintPlugin(IPluginDescriptor descriptor) {
- super(descriptor);
- plugin = this;
- resourceBundle = descriptor.getResourceBundle();
- }
-
- /**
- * Returns the shared instance.
- */
- public static PaintPlugin getDefault() {
- return plugin;
- }
-
- /**
- * Log an error to the ILog for this plugin
- *
- * @param message the localized error message text
- * @param exception the associated exception, or null
- */
- public static void logError(String message, Throwable exception) {
- plugin.getLog().log(new Status(IStatus.ERROR, plugin.getDescriptor().getUniqueIdentifier(),
- 0, message, exception));
- }
-
- /**
- * Returns a string from the resource bundle.
- * We don't want to crash because of a missing String.
- * Returns the key if not found.
- */
- public static String getResourceString(String key) {
- try {
- return resourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Returns a string from the resource bundle and binds it
- * with the given arguments. If the key is not found,
- * return the key.
- */
- public static String getResourceString(String key, Object[] args) {
- try {
- return MessageFormat.format(getResourceString(key), args);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.core.runtime.*;
+import org.eclipse.ui.plugin.*;
+
+import java.text.*;
+import java.util.*;
+
+/**
+ * The main plugin class to be used in the desktop.
+ */
+public class PaintPlugin extends AbstractUIPlugin {
+ //The shared instance.
+ private static PaintPlugin plugin;
+ private static ResourceBundle resourceBundle;
+
+ /**
+ * Constructs the Paint plugin.
+ */
+ public PaintPlugin(IPluginDescriptor descriptor) {
+ super(descriptor);
+ plugin = this;
+ resourceBundle = descriptor.getResourceBundle();
+ }
+
+ /**
+ * Returns the shared instance.
+ */
+ public static PaintPlugin getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Log an error to the ILog for this plugin
+ *
+ * @param message the localized error message text
+ * @param exception the associated exception, or null
+ */
+ public static void logError(String message, Throwable exception) {
+ plugin.getLog().log(new Status(IStatus.ERROR, plugin.getDescriptor().getUniqueIdentifier(),
+ 0, message, exception));
+ }
+
+ /**
+ * Returns a string from the resource bundle.
+ * We don't want to crash because of a missing String.
+ * Returns the key if not found.
+ */
+ public static String getResourceString(String key) {
+ try {
+ return resourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Returns a string from the resource bundle and binds it
+ * with the given arguments. If the key is not found,
+ * return the key.
+ */
+ public static String getResourceString(String key, Object[] args) {
+ try {
+ return MessageFormat.format(getResourceString(key), args);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSession.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSession.java
index a5a43d03cc..342a2d0bbe 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSession.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSession.java
@@ -1,54 +1,54 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.events.*;
-
-/**
- * Manages an interactive paint session.
- * Note that the coordinates received via the listener interfaces are virtualized to zero-origin
- * relative to the painting surface.
- */
-public interface PaintSession extends MouseListener, MouseMoveListener {
- /**
- * Returns the paint surface associated with this paint session
- *
- * @return the associated PaintSurface
- */
- public PaintSurface getPaintSurface();
-
- /**
- * Activates the session.
- *
- * Note: When overriding this method, call super.beginSession() at method start.
- */
- public abstract void beginSession();
-
- /**
- * Deactivates the session.
- *
- * Note: When overriding this method, call super.endSession() at method exit.
- */
- public abstract void endSession();
-
- /**
- * Resets the session.
- * Aborts any operation in progress.
- *
- * Note: When overriding this method, call super.resetSession() at method exit.
- */
- public abstract void resetSession();
-
-
- /**
- * Returns the name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName();
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.events.*;
+
+/**
+ * Manages an interactive paint session.
+ * Note that the coordinates received via the listener interfaces are virtualized to zero-origin
+ * relative to the painting surface.
+ */
+public interface PaintSession extends MouseListener, MouseMoveListener {
+ /**
+ * Returns the paint surface associated with this paint session
+ *
+ * @return the associated PaintSurface
+ */
+ public PaintSurface getPaintSurface();
+
+ /**
+ * Activates the session.
+ *
+ * Note: When overriding this method, call super.beginSession() at method start.
+ */
+ public abstract void beginSession();
+
+ /**
+ * Deactivates the session.
+ *
+ * Note: When overriding this method, call super.endSession() at method exit.
+ */
+ public abstract void endSession();
+
+ /**
+ * Resets the session.
+ * Aborts any operation in progress.
+ *
+ * Note: When overriding this method, call super.resetSession() at method exit.
+ */
+ public abstract void resetSession();
+
+
+ /**
+ * Returns the name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName();
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSurface.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSurface.java
index f9fd2064a2..451c4087a0 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSurface.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintSurface.java
@@ -1,31 +1,31 @@
-package org.eclipse.swt.examples.paint;
-/*
+package org.eclipse.swt.examples.paint;
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
- import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*;
- /** * Manages a simple drawing surface. */
-public class PaintSurface { private Point currentPosition = new Point(0, 0);
- private Canvas paintCanvas; private PaintSession paintSession; private Image image; private Image paintImage; // buffer for refresh blits private int imageWidth, imageHeight; private int visibleWidth, visibleHeight; private FigureDrawContext displayFDC = new FigureDrawContext(); private FigureDrawContext imageFDC = new FigureDrawContext(); private FigureDrawContext paintFDC = new FigureDrawContext(); /* Rubberband */ private ContainerFigure rubberband = new ContainerFigure(); // the active rubberband selection private int rubberbandHiddenNestingCount = 0; // always >= 0, if > 0 rubberband has been hidden /* Status */ private Text statusText; private String statusActionInfo, statusMessageInfo, statusCoordInfo; /** * Constructs a PaintSurface. * <p> * paintCanvas must have SWT.NO_REDRAW_RESIZE and SWT.NO_BACKGROUND styles, * and may have SWT.V_SCROLL and/or SWT.H_SCROLL. * </p> * @param paintCanvas the Canvas object in which to render * @param paintStatus the PaintStatus object to use for providing user feedback * @param fillColor the color to fill the canvas with initially */
- public PaintSurface(Canvas paintCanvas, Text statusText, Color fillColor) { this.paintCanvas = paintCanvas; this.statusText = statusText; clearStatus(); /* Set up the drawing surface */ Rectangle displayRect = paintCanvas.getDisplay().getClientArea(); imageWidth = displayRect.width; imageHeight = displayRect.height; image = new Image(paintCanvas.getDisplay(), imageWidth, imageHeight); imageFDC.gc = new GC(image); imageFDC.gc.setBackground(fillColor); imageFDC.gc.fillRectangle(0, 0, imageWidth, imageHeight); displayFDC.gc = new GC(paintCanvas); /* Initialize the session */ setPaintSession(null); /* Add our listeners */ paintCanvas.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { displayFDC.gc.dispose(); } }); paintCanvas.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent event) { processMouseEventCoordinates(event); if (paintSession != null) paintSession.mouseDown(event); } public void mouseUp(MouseEvent event) { processMouseEventCoordinates(event); if (paintSession != null) paintSession.mouseUp(event); } public void mouseDoubleClick(MouseEvent event) { processMouseEventCoordinates(event); if (paintSession != null) paintSession.mouseDoubleClick(event); } }); paintCanvas.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent event) { processMouseEventCoordinates(event); if (paintSession != null) paintSession.mouseMove(event); } }); paintCanvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent event) { if (rubberband.isEmpty()) { // Nothing to merge, so we just refresh event.gc.drawImage(image, displayFDC.xOffset + event.x, displayFDC.yOffset + event.y, event.width, event.height, event.x, event.y, event.width, event.height); } else { /* * Avoid flicker when merging overlayed objects by constructing the image on * a backbuffer first, then blitting it to the screen. */ // Check that the backbuffer is large enough if (paintImage != null) { Rectangle rect = paintImage.getBounds(); if ((event.width + event.x > rect.width) || (event.height + event.y > rect.height)) { paintFDC.gc.dispose(); paintImage.dispose(); paintImage = null; } } if (paintImage == null) { Display display = getDisplay(); Rectangle rect = display.getClientArea(); paintImage = new Image(display, Math.max(rect.width, event.width + event.x), Math.max(rect.height, event.height + event.y)); paintFDC.gc = new GC(paintImage); } // Setup clipping and the FDC Region clipRegion = new Region(); event.gc.getClipping(clipRegion); paintFDC.gc.setClipping(clipRegion); clipRegion.dispose(); paintFDC.xOffset = displayFDC.xOffset; paintFDC.yOffset = displayFDC.yOffset; paintFDC.xScale = displayFDC.xScale; paintFDC.yScale = displayFDC.yScale; // Merge the overlayed objects into the image, then blit paintFDC.gc.drawImage(image, displayFDC.xOffset + event.x, displayFDC.yOffset + event.y, event.width, event.height, event.x, event.y, event.width, event.height); rubberband.draw(paintFDC); event.gc.drawImage(paintImage, event.x, event.y, event.width, event.height, event.x, event.y, event.width, event.height); } } }); paintCanvas.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent event) { handleResize(); } }); /* Set up the paint canvas scroll bars */ ScrollBar horizontal = paintCanvas.getHorizontalBar(); horizontal.setVisible(true); horizontal.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { scrollHorizontally((ScrollBar)event.widget); } }); ScrollBar vertical = paintCanvas.getVerticalBar(); vertical.setVisible(true); vertical.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { scrollVertically((ScrollBar)event.widget); } }); handleResize(); } /** * Disposes of the PaintSurface's resources. */ public void dispose() { imageFDC.gc.dispose(); image.dispose(); if (paintImage != null) { paintImage.dispose(); paintFDC.gc.dispose(); } currentPosition = null; paintCanvas = null; paintSession = null; image = null; paintImage = null; displayFDC = null; imageFDC = null; paintFDC = null; rubberband = null; statusText = null; statusActionInfo = null; statusMessageInfo = null; statusCoordInfo = null; } /** * Called when we must grab focus. */ public void setFocus() { paintCanvas.setFocus(); } /** * Returns the Display on which the PaintSurface resides. * @return the Display */ public Display getDisplay() { return paintCanvas.getDisplay(); } /** * Returns the Shell in which the PaintSurface resides. * @return the Shell */ public Shell getShell() { return paintCanvas.getShell(); } /**
- * Sets the current paint session. * <p>
- * If oldPaintSession != paintSession calls oldPaintSession.end() * and paintSession.begin() * </p> *
- * @param paintSession the paint session to activate; null to disable all sessions
- */
- public void setPaintSession(PaintSession paintSession) {
- if (this.paintSession != null) { if (this.paintSession == paintSession) return;
- this.paintSession.endSession(); }
- this.paintSession = paintSession;
- clearStatus(); if (paintSession != null) { setStatusAction(paintSession.getDisplayName()); paintSession.beginSession(); } else { setStatusAction(PaintPlugin.getResourceString("tool.Null.label")); setStatusMessage(PaintPlugin.getResourceString("session.Null.message")); } }
-
- /**
- * Returns the current paint session.
- *
- * @return the current paint session, null if none is active
- */
- public PaintSession getPaintSession() {
- return paintSession;
- }
- /** * Returns the current paint tool. * * @return the current paint tool, null if none is active (though some other session * might be) */ public PaintTool getPaintTool() { return (paintSession != null && paintSession instanceof PaintTool) ? (PaintTool)paintSession : null; } /** * Returns the current position in an interactive operation. * * @return the last known position of the pointer */ public Point getCurrentPosition() { return currentPosition; } /** * Draws a Figure object to the screen and to the backing store permanently. * * @param object the object to draw onscreen */ public void drawFigure(Figure object) { object.draw(imageFDC); object.draw(displayFDC); } /** * Adds a Figure object to the active rubberband selection. * <p> * This object will be drawn to the screen as a preview and refreshed appropriately * until the selection is either cleared or committed. * </p> * * @param object the object to add to the selection */ public void addRubberbandSelection(Figure object) { rubberband.add(object); if (! isRubberbandHidden()) object.draw(displayFDC); } /** * Clears the active rubberband selection. * <p> * Erases any rubberband objects on the screen then clears the selection. * </p> */ public void clearRubberbandSelection() { if (! isRubberbandHidden()) { Region region = new Region(); rubberband.addDamagedRegion(displayFDC, region); Rectangle r = region.getBounds(); paintCanvas.redraw(r.x, r.y, r.width, r.height, true); region.dispose(); } rubberband.clear(); } /** * Commits the active rubberband selection. * <p> * Redraws any rubberband objects on the screen as permanent objects then clears the selection. * </p> */ public void commitRubberbandSelection() { rubberband.draw(imageFDC); if (isRubberbandHidden()) rubberband.draw(displayFDC); rubberband.clear(); } /** * Hides the rubberband (but does not eliminate it). * <p> * Increments by one the rubberband "hide" nesting count. The rubberband * is hidden from view (but remains active) if it wasn't already hidden. * </p> */ public void hideRubberband() { if (rubberbandHiddenNestingCount++ <= 0) { Region region = new Region(); rubberband.addDamagedRegion(displayFDC, region); Rectangle r = region.getBounds(); paintCanvas.redraw(r.x, r.y, r.width, r.height, true); region.dispose(); } } /** * Shows (un-hides) the rubberband. * <p> * Decrements by one the rubberband "hide" nesting count. The rubberband * is only made visible when showRubberband() has been called once for each * previous hideRubberband(). It is not permitted to call showRubberband() if * the rubber band is not presently hidden. * </p> */ public void showRubberband() { if (rubberbandHiddenNestingCount <= 0) throw new IllegalStateException("rubberbandHiddenNestingCount > 0"); if (--rubberbandHiddenNestingCount == 0) { rubberband.draw(displayFDC); } } /** * Determines if the rubberband is hidden. * * @return true iff the rubber is hidden */ public boolean isRubberbandHidden() { return rubberbandHiddenNestingCount > 0; } /** * Handles a horizontal scroll event * * @param scrollbar the horizontal scroll bar that posted this event */ public void scrollHorizontally(ScrollBar scrollBar) { if (image == null) return; if (imageWidth > visibleWidth) { final int oldOffset = displayFDC.xOffset; final int newOffset = Math.min(scrollBar.getSelection(), imageWidth - visibleWidth); if (oldOffset != newOffset) { paintCanvas.update(); displayFDC.xOffset = newOffset; paintCanvas.scroll(Math.max(oldOffset - newOffset, 0), 0, Math.max(newOffset - oldOffset, 0), 0, visibleWidth, visibleHeight, false); } } } /** * Handles a vertical scroll event * * @param scrollbar the vertical scroll bar that posted this event */ public void scrollVertically(ScrollBar scrollBar) { if (image == null) return; if (imageHeight > visibleHeight) { final int oldOffset = displayFDC.yOffset; final int newOffset = Math.min(scrollBar.getSelection(), imageHeight - visibleHeight); if (oldOffset != newOffset) { paintCanvas.update(); displayFDC.yOffset = newOffset; paintCanvas.scroll(0, Math.max(oldOffset - newOffset, 0), 0, Math.max(newOffset - oldOffset, 0), visibleWidth, visibleHeight, false); } } } /** * Handles resize events */ private void handleResize() { paintCanvas.update(); Rectangle visibleRect = paintCanvas.getClientArea(); visibleWidth = visibleRect.width; visibleHeight = visibleRect.height; ScrollBar horizontal = paintCanvas.getHorizontalBar(); if (horizontal != null) { displayFDC.xOffset = Math.min(horizontal.getSelection(), imageWidth - visibleWidth); if (imageWidth <= visibleWidth) { horizontal.setEnabled(false); horizontal.setSelection(0); } else { final int max = imageWidth - visibleWidth; horizontal.setEnabled(true); horizontal.setValues(displayFDC.xOffset, 0, imageWidth, visibleWidth, 8, visibleWidth); } } ScrollBar vertical = paintCanvas.getVerticalBar(); if (vertical != null) { displayFDC.yOffset = Math.min(vertical.getSelection(), imageHeight - visibleHeight); if (imageHeight <= visibleHeight) { vertical.setEnabled(false); vertical.setSelection(0); } else { final int max = imageHeight - visibleHeight; vertical.setEnabled(true); vertical.setValues(displayFDC.yOffset, 0, imageHeight, visibleHeight, 8, visibleHeight); } } } /** * Virtualizes MouseEvent coordinates and stores the current position. */ private void processMouseEventCoordinates(MouseEvent event) { currentPosition.x = event.x = Math.min(Math.max(event.x, 0), visibleWidth - 1) + displayFDC.xOffset; currentPosition.y = event.y = Math.min(Math.max(event.y, 0), visibleHeight - 1) + displayFDC.yOffset; } /** * Clears the status bar. */ public void clearStatus() { statusActionInfo = ""; statusMessageInfo = ""; statusCoordInfo = ""; updateStatus(); } /** * Sets the status bar action text. * * @param action the action in progress, null to clear */ public void setStatusAction(String action) { statusActionInfo = (action != null) ? action : ""; updateStatus(); } /** * Sets the status bar message text. * * @param message the message to display, null to clear */ public void setStatusMessage(String message) { statusMessageInfo = (message != null) ? message : ""; updateStatus(); } /** * Sets the coordinates in the status bar. * * @param coord the coordinates to display, null to clear */ public void setStatusCoord(Point coord) { statusCoordInfo = (coord != null) ? PaintPlugin.getResourceString("status.Coord.format", new Object[] { new Integer(coord.x), new Integer(coord.y)}) : ""; updateStatus(); } /** * Sets the coordinate range in the status bar. * * @param a the "from" coordinate, must not be null * @param b the "to" coordinate, must not be null */ public void setStatusCoordRange(Point a, Point b) { statusCoordInfo = PaintPlugin.getResourceString("status.CoordRange.format", new Object[] { new Integer(a.x), new Integer(a.y), new Integer(b.x), new Integer(b.y)}); updateStatus(); } /** * Updates the display. */ private void updateStatus() { statusText.setText( PaintPlugin.getResourceString("status.Bar.format", new Object[] { statusActionInfo, statusMessageInfo, statusCoordInfo })); } }
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+ import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*;
+ /** * Manages a simple drawing surface. */
+public class PaintSurface { private Point currentPosition = new Point(0, 0);
+ private Canvas paintCanvas; private PaintSession paintSession; private Image image; private Image paintImage; // buffer for refresh blits private int imageWidth, imageHeight; private int visibleWidth, visibleHeight; private FigureDrawContext displayFDC = new FigureDrawContext(); private FigureDrawContext imageFDC = new FigureDrawContext(); private FigureDrawContext paintFDC = new FigureDrawContext(); /* Rubberband */ private ContainerFigure rubberband = new ContainerFigure(); // the active rubberband selection private int rubberbandHiddenNestingCount = 0; // always >= 0, if > 0 rubberband has been hidden /* Status */ private Text statusText; private String statusActionInfo, statusMessageInfo, statusCoordInfo; /** * Constructs a PaintSurface. * <p> * paintCanvas must have SWT.NO_REDRAW_RESIZE and SWT.NO_BACKGROUND styles, * and may have SWT.V_SCROLL and/or SWT.H_SCROLL. * </p> * @param paintCanvas the Canvas object in which to render * @param paintStatus the PaintStatus object to use for providing user feedback * @param fillColor the color to fill the canvas with initially */
+ public PaintSurface(Canvas paintCanvas, Text statusText, Color fillColor) { this.paintCanvas = paintCanvas; this.statusText = statusText; clearStatus(); /* Set up the drawing surface */ Rectangle displayRect = paintCanvas.getDisplay().getClientArea(); imageWidth = displayRect.width; imageHeight = displayRect.height; image = new Image(paintCanvas.getDisplay(), imageWidth, imageHeight); imageFDC.gc = new GC(image); imageFDC.gc.setBackground(fillColor); imageFDC.gc.fillRectangle(0, 0, imageWidth, imageHeight); displayFDC.gc = new GC(paintCanvas); /* Initialize the session */ setPaintSession(null); /* Add our listeners */ paintCanvas.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { displayFDC.gc.dispose(); } }); paintCanvas.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent event) { processMouseEventCoordinates(event); if (paintSession != null) paintSession.mouseDown(event); } public void mouseUp(MouseEvent event) { processMouseEventCoordinates(event); if (paintSession != null) paintSession.mouseUp(event); } public void mouseDoubleClick(MouseEvent event) { processMouseEventCoordinates(event); if (paintSession != null) paintSession.mouseDoubleClick(event); } }); paintCanvas.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent event) { processMouseEventCoordinates(event); if (paintSession != null) paintSession.mouseMove(event); } }); paintCanvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent event) { if (rubberband.isEmpty()) { // Nothing to merge, so we just refresh event.gc.drawImage(image, displayFDC.xOffset + event.x, displayFDC.yOffset + event.y, event.width, event.height, event.x, event.y, event.width, event.height); } else { /* * Avoid flicker when merging overlayed objects by constructing the image on * a backbuffer first, then blitting it to the screen. */ // Check that the backbuffer is large enough if (paintImage != null) { Rectangle rect = paintImage.getBounds(); if ((event.width + event.x > rect.width) || (event.height + event.y > rect.height)) { paintFDC.gc.dispose(); paintImage.dispose(); paintImage = null; } } if (paintImage == null) { Display display = getDisplay(); Rectangle rect = display.getClientArea(); paintImage = new Image(display, Math.max(rect.width, event.width + event.x), Math.max(rect.height, event.height + event.y)); paintFDC.gc = new GC(paintImage); } // Setup clipping and the FDC Region clipRegion = new Region(); event.gc.getClipping(clipRegion); paintFDC.gc.setClipping(clipRegion); clipRegion.dispose(); paintFDC.xOffset = displayFDC.xOffset; paintFDC.yOffset = displayFDC.yOffset; paintFDC.xScale = displayFDC.xScale; paintFDC.yScale = displayFDC.yScale; // Merge the overlayed objects into the image, then blit paintFDC.gc.drawImage(image, displayFDC.xOffset + event.x, displayFDC.yOffset + event.y, event.width, event.height, event.x, event.y, event.width, event.height); rubberband.draw(paintFDC); event.gc.drawImage(paintImage, event.x, event.y, event.width, event.height, event.x, event.y, event.width, event.height); } } }); paintCanvas.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent event) { handleResize(); } }); /* Set up the paint canvas scroll bars */ ScrollBar horizontal = paintCanvas.getHorizontalBar(); horizontal.setVisible(true); horizontal.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { scrollHorizontally((ScrollBar)event.widget); } }); ScrollBar vertical = paintCanvas.getVerticalBar(); vertical.setVisible(true); vertical.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { scrollVertically((ScrollBar)event.widget); } }); handleResize(); } /** * Disposes of the PaintSurface's resources. */ public void dispose() { imageFDC.gc.dispose(); image.dispose(); if (paintImage != null) { paintImage.dispose(); paintFDC.gc.dispose(); } currentPosition = null; paintCanvas = null; paintSession = null; image = null; paintImage = null; displayFDC = null; imageFDC = null; paintFDC = null; rubberband = null; statusText = null; statusActionInfo = null; statusMessageInfo = null; statusCoordInfo = null; } /** * Called when we must grab focus. */ public void setFocus() { paintCanvas.setFocus(); } /** * Returns the Display on which the PaintSurface resides. * @return the Display */ public Display getDisplay() { return paintCanvas.getDisplay(); } /** * Returns the Shell in which the PaintSurface resides. * @return the Shell */ public Shell getShell() { return paintCanvas.getShell(); } /**
+ * Sets the current paint session. * <p>
+ * If oldPaintSession != paintSession calls oldPaintSession.end() * and paintSession.begin() * </p> *
+ * @param paintSession the paint session to activate; null to disable all sessions
+ */
+ public void setPaintSession(PaintSession paintSession) {
+ if (this.paintSession != null) { if (this.paintSession == paintSession) return;
+ this.paintSession.endSession(); }
+ this.paintSession = paintSession;
+ clearStatus(); if (paintSession != null) { setStatusAction(paintSession.getDisplayName()); paintSession.beginSession(); } else { setStatusAction(PaintPlugin.getResourceString("tool.Null.label")); setStatusMessage(PaintPlugin.getResourceString("session.Null.message")); } }
+
+ /**
+ * Returns the current paint session.
+ *
+ * @return the current paint session, null if none is active
+ */
+ public PaintSession getPaintSession() {
+ return paintSession;
+ }
+ /** * Returns the current paint tool. * * @return the current paint tool, null if none is active (though some other session * might be) */ public PaintTool getPaintTool() { return (paintSession != null && paintSession instanceof PaintTool) ? (PaintTool)paintSession : null; } /** * Returns the current position in an interactive operation. * * @return the last known position of the pointer */ public Point getCurrentPosition() { return currentPosition; } /** * Draws a Figure object to the screen and to the backing store permanently. * * @param object the object to draw onscreen */ public void drawFigure(Figure object) { object.draw(imageFDC); object.draw(displayFDC); } /** * Adds a Figure object to the active rubberband selection. * <p> * This object will be drawn to the screen as a preview and refreshed appropriately * until the selection is either cleared or committed. * </p> * * @param object the object to add to the selection */ public void addRubberbandSelection(Figure object) { rubberband.add(object); if (! isRubberbandHidden()) object.draw(displayFDC); } /** * Clears the active rubberband selection. * <p> * Erases any rubberband objects on the screen then clears the selection. * </p> */ public void clearRubberbandSelection() { if (! isRubberbandHidden()) { Region region = new Region(); rubberband.addDamagedRegion(displayFDC, region); Rectangle r = region.getBounds(); paintCanvas.redraw(r.x, r.y, r.width, r.height, true); region.dispose(); } rubberband.clear(); } /** * Commits the active rubberband selection. * <p> * Redraws any rubberband objects on the screen as permanent objects then clears the selection. * </p> */ public void commitRubberbandSelection() { rubberband.draw(imageFDC); if (isRubberbandHidden()) rubberband.draw(displayFDC); rubberband.clear(); } /** * Hides the rubberband (but does not eliminate it). * <p> * Increments by one the rubberband "hide" nesting count. The rubberband * is hidden from view (but remains active) if it wasn't already hidden. * </p> */ public void hideRubberband() { if (rubberbandHiddenNestingCount++ <= 0) { Region region = new Region(); rubberband.addDamagedRegion(displayFDC, region); Rectangle r = region.getBounds(); paintCanvas.redraw(r.x, r.y, r.width, r.height, true); region.dispose(); } } /** * Shows (un-hides) the rubberband. * <p> * Decrements by one the rubberband "hide" nesting count. The rubberband * is only made visible when showRubberband() has been called once for each * previous hideRubberband(). It is not permitted to call showRubberband() if * the rubber band is not presently hidden. * </p> */ public void showRubberband() { if (rubberbandHiddenNestingCount <= 0) throw new IllegalStateException("rubberbandHiddenNestingCount > 0"); if (--rubberbandHiddenNestingCount == 0) { rubberband.draw(displayFDC); } } /** * Determines if the rubberband is hidden. * * @return true iff the rubber is hidden */ public boolean isRubberbandHidden() { return rubberbandHiddenNestingCount > 0; } /** * Handles a horizontal scroll event * * @param scrollbar the horizontal scroll bar that posted this event */ public void scrollHorizontally(ScrollBar scrollBar) { if (image == null) return; if (imageWidth > visibleWidth) { final int oldOffset = displayFDC.xOffset; final int newOffset = Math.min(scrollBar.getSelection(), imageWidth - visibleWidth); if (oldOffset != newOffset) { paintCanvas.update(); displayFDC.xOffset = newOffset; paintCanvas.scroll(Math.max(oldOffset - newOffset, 0), 0, Math.max(newOffset - oldOffset, 0), 0, visibleWidth, visibleHeight, false); } } } /** * Handles a vertical scroll event * * @param scrollbar the vertical scroll bar that posted this event */ public void scrollVertically(ScrollBar scrollBar) { if (image == null) return; if (imageHeight > visibleHeight) { final int oldOffset = displayFDC.yOffset; final int newOffset = Math.min(scrollBar.getSelection(), imageHeight - visibleHeight); if (oldOffset != newOffset) { paintCanvas.update(); displayFDC.yOffset = newOffset; paintCanvas.scroll(0, Math.max(oldOffset - newOffset, 0), 0, Math.max(newOffset - oldOffset, 0), visibleWidth, visibleHeight, false); } } } /** * Handles resize events */ private void handleResize() { paintCanvas.update(); Rectangle visibleRect = paintCanvas.getClientArea(); visibleWidth = visibleRect.width; visibleHeight = visibleRect.height; ScrollBar horizontal = paintCanvas.getHorizontalBar(); if (horizontal != null) { displayFDC.xOffset = Math.min(horizontal.getSelection(), imageWidth - visibleWidth); if (imageWidth <= visibleWidth) { horizontal.setEnabled(false); horizontal.setSelection(0); } else { final int max = imageWidth - visibleWidth; horizontal.setEnabled(true); horizontal.setValues(displayFDC.xOffset, 0, imageWidth, visibleWidth, 8, visibleWidth); } } ScrollBar vertical = paintCanvas.getVerticalBar(); if (vertical != null) { displayFDC.yOffset = Math.min(vertical.getSelection(), imageHeight - visibleHeight); if (imageHeight <= visibleHeight) { vertical.setEnabled(false); vertical.setSelection(0); } else { final int max = imageHeight - visibleHeight; vertical.setEnabled(true); vertical.setValues(displayFDC.yOffset, 0, imageHeight, visibleHeight, 8, visibleHeight); } } } /** * Virtualizes MouseEvent coordinates and stores the current position. */ private void processMouseEventCoordinates(MouseEvent event) { currentPosition.x = event.x = Math.min(Math.max(event.x, 0), visibleWidth - 1) + displayFDC.xOffset; currentPosition.y = event.y = Math.min(Math.max(event.y, 0), visibleHeight - 1) + displayFDC.yOffset; } /** * Clears the status bar. */ public void clearStatus() { statusActionInfo = ""; statusMessageInfo = ""; statusCoordInfo = ""; updateStatus(); } /** * Sets the status bar action text. * * @param action the action in progress, null to clear */ public void setStatusAction(String action) { statusActionInfo = (action != null) ? action : ""; updateStatus(); } /** * Sets the status bar message text. * * @param message the message to display, null to clear */ public void setStatusMessage(String message) { statusMessageInfo = (message != null) ? message : ""; updateStatus(); } /** * Sets the coordinates in the status bar. * * @param coord the coordinates to display, null to clear */ public void setStatusCoord(Point coord) { statusCoordInfo = (coord != null) ? PaintPlugin.getResourceString("status.Coord.format", new Object[] { new Integer(coord.x), new Integer(coord.y)}) : ""; updateStatus(); } /** * Sets the coordinate range in the status bar. * * @param a the "from" coordinate, must not be null * @param b the "to" coordinate, must not be null */ public void setStatusCoordRange(Point a, Point b) { statusCoordInfo = PaintPlugin.getResourceString("status.CoordRange.format", new Object[] { new Integer(a.x), new Integer(a.y), new Integer(b.x), new Integer(b.y)}); updateStatus(); } /** * Updates the display. */ private void updateStatus() { statusText.setText( PaintPlugin.getResourceString("status.Bar.format", new Object[] { statusActionInfo, statusMessageInfo, statusCoordInfo })); } }
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintTool.java
index da27e96033..887f9a83da 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintTool.java
@@ -1,15 +1,15 @@
-package org.eclipse.swt.examples.paint;
-/*
+package org.eclipse.swt.examples.paint;
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
- public interface PaintTool extends PaintSession {
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings);
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+ public interface PaintTool extends PaintSession {
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings);
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintView.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintView.java
index 174de42e8d..64a02f3229 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintView.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PaintView.java
@@ -1,496 +1,496 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.jface.action.*;
-import org.eclipse.jface.resource.*;
-import org.eclipse.swt.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.ui.*;
-import org.eclipse.ui.part.*;
-
-import java.net.*;
-import java.util.*;
-
-/**
- * The view for the paint application.
- * All rendering happens inside the area created by createPartControl().
- *
- * @see ViewPart
- */
-public class PaintView extends ViewPart {
- private Display workbenchDisplay;
-
- // current active settings
- private ToolSettings toolSettings;
-
- // paint surface for drawing
- private PaintSurface paintSurface;
-
- // map action ids to useful data
- private HashMap /* of String to PaintTool */ paintToolMap;
- private HashMap /* of String to Integer */ paintFillTypeMap;
- private HashMap /* of String to Integer */ paintLineStyleMap;
-
- /** UI data **/
- // handle of currently active tool IAction on the UI
- private IAction activeToolAction;
- // handle of currently active filltype IAction on the UI
- private IAction activeFillTypeAction;
- // handle of currently active linetype IAction on the UI
- private IAction activeLineStyleAction;
-
- // handle of active foreground color box Canvas widget
- private Canvas activeForegroundColorCanvas;
- // handle of active background color box Canvas widget
- private Canvas activeBackgroundColorCanvas;
-
- private static final int numPaletteRows = 3;
- private static final int numPaletteCols = 50;
-
- // shared data
- private Color paintColorBlack, paintColorWhite; // alias for paintColors[0] and [1]
- private Color[] paintColors;
- private Font paintDefaultFont; // do not free
-
- /**
- * Constructs a Paint view.
- */
- public PaintView() {
- }
-
- /**
- * Cleanup
- */
- public void dispose() {
- if (paintSurface != null) paintSurface.dispose();
- if (paintColors != null) {
- for (int i = 0; i < paintColors.length; ++i) {
- final Color color = paintColors[i];
- if (color != null) color.dispose();
- }
- }
- paintDefaultFont = null;
- paintColors = null;
- paintSurface = null;
- super.dispose();
- }
-
- /**
- * Called when we must grab focus.
- *
- * @see org.eclipse.ui.part.ViewPart#setFocus
- */
- public void setFocus() {
- paintSurface.setFocus();
- }
-
- /**
- * Creates the example.
- *
- * @see ViewPart#createPartControl
- */
- public void createPartControl(Composite parent) {
- /*** Initialize shared data ***/
- workbenchDisplay = parent.getDisplay();
-
- paintColorWhite = new Color(workbenchDisplay, 255, 255, 255);
- paintColorBlack = new Color(workbenchDisplay, 0, 0, 0);
-
- paintDefaultFont = workbenchDisplay.getSystemFont();
-
- paintColors = new Color[numPaletteCols * numPaletteRows];
- paintColors[0] = paintColorBlack;
- paintColors[1] = paintColorWhite;
- for (int i = 2; i < paintColors.length; i++) {
- paintColors[i] = new Color(workbenchDisplay,
- ((i*7)%255),((i*23)%255), ((i*51)%255));
- }
-
- toolSettings = new ToolSettings();
- toolSettings.commonForegroundColor = paintColorBlack;
- toolSettings.commonBackgroundColor = paintColorWhite;
- toolSettings.commonFont = paintDefaultFont;
-
- /*** Add toolbar contributions ***/
- final IActionBars actionBars = getViewSite().getActionBars();
- IToolBarManager toolbarManager = actionBars.getToolBarManager();
-
- toolbarManager.add(new GroupMarker("group.tools"));
- toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Pencil"));
- toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Airbrush"));
- toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Line"));
- toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.PolyLine"));
- toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Rectangle"));
- toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.RoundedRectangle"));
- toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Ellipse"));
- toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Text"));
- toolbarManager.add(new Separator());
- toolbarManager.add(new GroupMarker("group.options.fill"));
- toolbarManager.appendToGroup("group.options.fill", new SelectFillTypeAction("fill.None"));
- toolbarManager.appendToGroup("group.options.fill", new SelectFillTypeAction("fill.Outline"));
- toolbarManager.appendToGroup("group.options.fill", new SelectFillTypeAction("fill.Solid"));
- toolbarManager.add(new Separator());
- toolbarManager.add(new GroupMarker("group.options.linestyle"));
- toolbarManager.appendToGroup("group.options.linestyle", new SelectLineStyleAction("linestyle.Solid"));
- toolbarManager.appendToGroup("group.options.linestyle", new SelectLineStyleAction("linestyle.Dash"));
- toolbarManager.appendToGroup("group.options.linestyle", new SelectLineStyleAction("linestyle.Dot"));
- toolbarManager.appendToGroup("group.options.linestyle", new SelectLineStyleAction("linestyle.DashDot"));
- toolbarManager.add(new Separator());
- toolbarManager.add(new GroupMarker("group.options"));
- toolbarManager.appendToGroup("group.options", new SelectFontAction("options.Font"));
- actionBars.updateActionBars();
-
- /*** Build GUI ***/
- createGUI(parent);
-
- /*** Set defaults ***/
- setPaintToolByID("tool.Pencil");
- setFillTypeByID("fill.None");
- setLineStyleByID("linestyle.Solid");
- setForegroundColor(paintColorBlack);
- setBackgroundColor(paintColorWhite);
- }
-
- /**
- * Creates the GUI.
- */
- private void createGUI(Composite parent) {
- GridLayout gridLayout;
- GridData gridData;
-
- /*** Create principal GUI layout elements ***/
- Composite displayArea = new Composite(parent, SWT.NONE);
- gridLayout = new GridLayout();
- gridLayout.numColumns = 1;
- displayArea.setLayout(gridLayout);
-
- // Creating these elements here avoids the need to instantiate the GUI elements
- // in strict layout order. The natural layout ordering is an artifact of using
- // SWT layouts, but unfortunately it is not the same order as that required to
- // instantiate all of the non-GUI application elements to satisfy referential
- // dependencies. It is possible to reorder the initialization to some extent, but
- // this can be very tedious.
-
- // paint canvas
- final Canvas paintCanvas = new Canvas(displayArea, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL |
- SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
- paintCanvas.setLayoutData(gridData);
- paintCanvas.setBackground(paintColorWhite);
-
- // color selector frame
- final Composite colorFrame = new Composite(displayArea, SWT.NONE);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
- colorFrame.setLayoutData(gridData);
-
- // tool settings frame
- final Composite toolSettingsFrame = new Composite(displayArea, SWT.NONE);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
- toolSettingsFrame.setLayoutData(gridData);
-
- // status text
- final Text statusText = new Text(displayArea, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
- statusText.setLayoutData(gridData);
-
- /*** Create the remaining application elements inside the principal GUI layout elements ***/
- // paintSurface
- paintSurface = new PaintSurface(paintCanvas, statusText, paintColorWhite);
-
- // paintToolMap
- paintToolMap = new HashMap();
- paintToolMap.put("tool.Pencil", new PencilTool(toolSettings, paintSurface));
- paintToolMap.put("tool.Airbrush", new AirbrushTool(toolSettings, paintSurface));
- paintToolMap.put("tool.Line", new LineTool(toolSettings, paintSurface));
- paintToolMap.put("tool.PolyLine", new PolyLineTool(toolSettings, paintSurface));
- paintToolMap.put("tool.Rectangle", new RectangleTool(toolSettings, paintSurface));
- paintToolMap.put("tool.RoundedRectangle", new RoundedRectangleTool(toolSettings, paintSurface));
- paintToolMap.put("tool.Ellipse", new EllipseTool(toolSettings, paintSurface));
- paintToolMap.put("tool.Text", new TextTool(toolSettings, paintSurface));
- paintToolMap.put("tool.Null", null);
-
- // paintFillTypeMap
- paintFillTypeMap = new HashMap();
- paintFillTypeMap.put("fill.None", new Integer(ToolSettings.ftNone));
- paintFillTypeMap.put("fill.Outline", new Integer(ToolSettings.ftOutline));
- paintFillTypeMap.put("fill.Solid", new Integer(ToolSettings.ftSolid));
-
- // paintLineStyleMap
- paintLineStyleMap = new HashMap();
- paintLineStyleMap.put("linestyle.Solid", new Integer(SWT.LINE_SOLID));
- paintLineStyleMap.put("linestyle.Dash", new Integer(SWT.LINE_DASH));
- paintLineStyleMap.put("linestyle.Dot", new Integer(SWT.LINE_DOT));
- paintLineStyleMap.put("linestyle.DashDot", new Integer(SWT.LINE_DASHDOT));
-
- // colorFrame
- gridLayout = new GridLayout();
- gridLayout.numColumns = 3;
- gridLayout.marginHeight = 0;
- gridLayout.marginWidth = 0;
- colorFrame.setLayout(gridLayout);
-
- // activeForegroundColorCanvas, activeBackgroundColorCanvas
- activeForegroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
- gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gridData.heightHint = 24;
- gridData.widthHint = 24;
- activeForegroundColorCanvas.setLayoutData(gridData);
-
- activeBackgroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
- gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gridData.heightHint = 24;
- gridData.widthHint = 24;
- activeBackgroundColorCanvas.setLayoutData(gridData);
-
- // paletteCanvas
- final Canvas paletteCanvas = new Canvas(colorFrame, SWT.BORDER | SWT.NO_BACKGROUND);
- gridData = new GridData(GridData.FILL_HORIZONTAL);
- gridData.heightHint = 24;
- paletteCanvas.setLayoutData(gridData);
- paletteCanvas.addListener(SWT.MouseDown, new Listener() {
- public void handleEvent(Event e) {
- Rectangle bounds = paletteCanvas.getClientArea();
- Color color = getColorAt(bounds, e.x, e.y);
-
- if (e.button == 1) setForegroundColor(color);
- else setBackgroundColor(color);
- }
- private Color getColorAt(Rectangle bounds, int x, int y) {
- if (bounds.height <= 1 && bounds.width <= 1) return paintColorWhite;
- final int row = (y - bounds.y) * numPaletteRows / bounds.height;
- final int col = (x - bounds.x) * numPaletteCols / bounds.width;
- return paintColors[Math.min(Math.max(row * numPaletteCols + col, 0), paintColors.length - 1)];
- }
- });
- Listener refreshListener = new Listener() {
- public void handleEvent(Event e) {
- if (e.gc == null) return;
- Rectangle bounds = paletteCanvas.getClientArea();
- for (int row = 0; row < numPaletteRows; ++row) {
- for (int col = 0; col < numPaletteCols; ++col) {
- final int x = bounds.width * col / numPaletteCols;
- final int y = bounds.height * row / numPaletteRows;
- final int width = Math.max(bounds.width * (col + 1) / numPaletteCols - x, 1);
- final int height = Math.max(bounds.height * (row + 1) / numPaletteRows - y, 1);
- e.gc.setBackground(paintColors[row * numPaletteCols + col]);
- e.gc.fillRectangle(bounds.x + x, bounds.y + y, width, height);
- }
- }
- }
- };
- paletteCanvas.addListener(SWT.Resize, refreshListener);
- paletteCanvas.addListener(SWT.Paint, refreshListener);
- //paletteCanvas.redraw();
-
- // toolSettingsFrame
- gridLayout = new GridLayout();
- gridLayout.numColumns = 4;
- gridLayout.marginHeight = 0;
- gridLayout.marginWidth = 0;
- toolSettingsFrame.setLayout(gridLayout);
-
- Label label = new Label(toolSettingsFrame, SWT.NONE);
- label.setText(PaintPlugin.getResourceString("settings.AirbrushRadius.text"));
-
- final Scale airbrushRadiusScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
- airbrushRadiusScale.setMinimum(5);
- airbrushRadiusScale.setMaximum(50);
- airbrushRadiusScale.setSelection(toolSettings.airbrushRadius);
- airbrushRadiusScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
- airbrushRadiusScale.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- toolSettings.airbrushRadius = airbrushRadiusScale.getSelection();
- updateToolSettings();
- }
- });
-
- label = new Label(toolSettingsFrame, SWT.NONE);
- label.setText(PaintPlugin.getResourceString("settings.AirbrushIntensity.text"));
-
- final Scale airbrushIntensityScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
- airbrushIntensityScale.setMinimum(1);
- airbrushIntensityScale.setMaximum(100);
- airbrushIntensityScale.setSelection(toolSettings.airbrushIntensity);
- airbrushIntensityScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
- airbrushIntensityScale.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- toolSettings.airbrushIntensity = airbrushIntensityScale.getSelection();
- updateToolSettings();
- }
- });
- }
-
- /**
- * Notifies the tool that its settings have changed.
- */
- private void updateToolSettings() {
- final PaintTool activePaintTool = paintSurface.getPaintTool();
- if (activePaintTool == null) return;
-
- activePaintTool.endSession();
- activePaintTool.set(toolSettings);
- activePaintTool.beginSession();
- }
-
- /**
- * Sets the tool foreground color.
- *
- * @param color the new color to use
- */
- public void setForegroundColor(Color color) {
- if (activeForegroundColorCanvas != null)
- activeForegroundColorCanvas.setBackground(color);
- toolSettings.commonForegroundColor = color;
- updateToolSettings();
- }
-
- /**
- * Set the tool background color.
- *
- * @param color the new color to use
- */
- public void setBackgroundColor(Color color) {
- if (activeBackgroundColorCanvas != null)
- activeBackgroundColorCanvas.setBackground(color);
- toolSettings.commonBackgroundColor = color;
- updateToolSettings();
- }
-
- /**
- * Selects a tool given its ID.
- */
- public void setPaintToolByID(String id) {
- activeToolAction = handleRadioAction(activeToolAction, id);
-
- final PaintTool paintTool = (PaintTool) paintToolMap.get(id);
- paintSurface.setPaintSession(paintTool);
- updateToolSettings();
- }
-
- /**
- * Selects a filltype given its ID.
- */
- public void setFillTypeByID(String id) {
- activeFillTypeAction = handleRadioAction(activeFillTypeAction, id);
-
- final Integer fillType = (Integer) paintFillTypeMap.get(id);
- toolSettings.commonFillType = fillType.intValue();
- updateToolSettings();
- }
-
- /**
- * Selects line type given its ID.
- */
- public void setLineStyleByID(String id) {
- activeLineStyleAction = handleRadioAction(activeLineStyleAction, id);
-
- final Integer lineType = (Integer) paintLineStyleMap.get(id);
- toolSettings.commonLineStyle = lineType.intValue();
- updateToolSettings();
- }
-
- /**
- * Gets the IAction for an ID belonging to a set of mutually exclusive actions, and
- * toggles the old action off if necessary.
- */
- private IAction handleRadioAction(IAction oldAction, String id) {
- IAction action = getActionByID(id);
- if (action != null) {
- if (oldAction != null) oldAction.setChecked(false);
- if (! action.isChecked()) action.setChecked(true);
- return action;
- }
- return oldAction;
- }
-
- /**
- * Gets the IAction representing the UI toolbar button with the specified ID.
- */
- private IAction getActionByID(String id) {
- final IActionBars actionBars = getViewSite().getActionBars();
- IToolBarManager toolbarManager = actionBars.getToolBarManager();
- ActionContributionItem contributionItem = (ActionContributionItem) toolbarManager.find(id);
- if (contributionItem == null) return null;
- return contributionItem.getAction();
- }
-
- /**
- * Returns the Display.
- *
- * @return the display we're using
- */
- public Display getDisplay() {
- return workbenchDisplay;
- }
-
- /**
- * Action set glue.
- */
- abstract class PaintAction extends Action {
- public PaintAction(String id) {
- super();
- setId(id);
-
- try {
- final URL installUrl = PaintPlugin.getDefault().getDescriptor().getInstallURL();
- final URL imageUrl = new URL(installUrl, PaintPlugin.getResourceString(id + ".image"));
- setImageDescriptor(ImageDescriptor.createFromURL(imageUrl));
- } catch (MalformedURLException e) {
- PaintPlugin.logError("", e);
- }
-
- setText(PaintPlugin.getResourceString(id + ".label"));
- setToolTipText(PaintPlugin.getResourceString(id + ".tooltip"));
- setDescription(PaintPlugin.getResourceString(id + ".description"));
- }
- }
- class SelectPaintToolAction extends PaintAction {
- public SelectPaintToolAction(String id) { super(id); }
- public int getStyle() { return IAction.AS_CHECK_BOX; }
- public void run() { setPaintToolByID(getId()); }
-
- }
- class SelectFillTypeAction extends PaintAction {
- public SelectFillTypeAction(String id) { super(id); }
- public int getStyle() { return IAction.AS_CHECK_BOX; }
- public void run() { setFillTypeByID(getId()); }
- }
- class SelectLineStyleAction extends PaintAction {
- public SelectLineStyleAction(String id) { super(id); }
- public int getStyle() { return IAction.AS_CHECK_BOX; }
- public void run() { setLineStyleByID(getId()); }
- }
- class SelectFontAction extends PaintAction {
- public SelectFontAction(String id) { super(id); }
- public int getStyle() { return IAction.AS_PUSH_BUTTON; }
- public void run() {
- FontDialog fontDialog = new FontDialog(paintSurface.getShell(), SWT.PRIMARY_MODAL);
- FontData[] fontDatum = toolSettings.commonFont.getFontData();
- if (fontDatum != null && fontDatum.length > 0) {
- fontDialog.setFontData(fontDatum[0]);
- }
- fontDialog.setText(PaintPlugin.getResourceString("options.Font.dialog.title"));
-
- paintSurface.hideRubberband();
- FontData fontData = fontDialog.open();
- paintSurface.showRubberband();
- if (fontData != null) {
- try {
- Font font = new Font(workbenchDisplay, fontData);
- toolSettings.commonFont = font;
- updateToolSettings();
- } catch (SWTException e) {
- }
- }
- }
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.jface.action.*;
+import org.eclipse.jface.resource.*;
+import org.eclipse.swt.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.ui.*;
+import org.eclipse.ui.part.*;
+
+import java.net.*;
+import java.util.*;
+
+/**
+ * The view for the paint application.
+ * All rendering happens inside the area created by createPartControl().
+ *
+ * @see ViewPart
+ */
+public class PaintView extends ViewPart {
+ private Display workbenchDisplay;
+
+ // current active settings
+ private ToolSettings toolSettings;
+
+ // paint surface for drawing
+ private PaintSurface paintSurface;
+
+ // map action ids to useful data
+ private HashMap /* of String to PaintTool */ paintToolMap;
+ private HashMap /* of String to Integer */ paintFillTypeMap;
+ private HashMap /* of String to Integer */ paintLineStyleMap;
+
+ /** UI data **/
+ // handle of currently active tool IAction on the UI
+ private IAction activeToolAction;
+ // handle of currently active filltype IAction on the UI
+ private IAction activeFillTypeAction;
+ // handle of currently active linetype IAction on the UI
+ private IAction activeLineStyleAction;
+
+ // handle of active foreground color box Canvas widget
+ private Canvas activeForegroundColorCanvas;
+ // handle of active background color box Canvas widget
+ private Canvas activeBackgroundColorCanvas;
+
+ private static final int numPaletteRows = 3;
+ private static final int numPaletteCols = 50;
+
+ // shared data
+ private Color paintColorBlack, paintColorWhite; // alias for paintColors[0] and [1]
+ private Color[] paintColors;
+ private Font paintDefaultFont; // do not free
+
+ /**
+ * Constructs a Paint view.
+ */
+ public PaintView() {
+ }
+
+ /**
+ * Cleanup
+ */
+ public void dispose() {
+ if (paintSurface != null) paintSurface.dispose();
+ if (paintColors != null) {
+ for (int i = 0; i < paintColors.length; ++i) {
+ final Color color = paintColors[i];
+ if (color != null) color.dispose();
+ }
+ }
+ paintDefaultFont = null;
+ paintColors = null;
+ paintSurface = null;
+ super.dispose();
+ }
+
+ /**
+ * Called when we must grab focus.
+ *
+ * @see org.eclipse.ui.part.ViewPart#setFocus
+ */
+ public void setFocus() {
+ paintSurface.setFocus();
+ }
+
+ /**
+ * Creates the example.
+ *
+ * @see ViewPart#createPartControl
+ */
+ public void createPartControl(Composite parent) {
+ /*** Initialize shared data ***/
+ workbenchDisplay = parent.getDisplay();
+
+ paintColorWhite = new Color(workbenchDisplay, 255, 255, 255);
+ paintColorBlack = new Color(workbenchDisplay, 0, 0, 0);
+
+ paintDefaultFont = workbenchDisplay.getSystemFont();
+
+ paintColors = new Color[numPaletteCols * numPaletteRows];
+ paintColors[0] = paintColorBlack;
+ paintColors[1] = paintColorWhite;
+ for (int i = 2; i < paintColors.length; i++) {
+ paintColors[i] = new Color(workbenchDisplay,
+ ((i*7)%255),((i*23)%255), ((i*51)%255));
+ }
+
+ toolSettings = new ToolSettings();
+ toolSettings.commonForegroundColor = paintColorBlack;
+ toolSettings.commonBackgroundColor = paintColorWhite;
+ toolSettings.commonFont = paintDefaultFont;
+
+ /*** Add toolbar contributions ***/
+ final IActionBars actionBars = getViewSite().getActionBars();
+ IToolBarManager toolbarManager = actionBars.getToolBarManager();
+
+ toolbarManager.add(new GroupMarker("group.tools"));
+ toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Pencil"));
+ toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Airbrush"));
+ toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Line"));
+ toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.PolyLine"));
+ toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Rectangle"));
+ toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.RoundedRectangle"));
+ toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Ellipse"));
+ toolbarManager.appendToGroup("group.tools", new SelectPaintToolAction("tool.Text"));
+ toolbarManager.add(new Separator());
+ toolbarManager.add(new GroupMarker("group.options.fill"));
+ toolbarManager.appendToGroup("group.options.fill", new SelectFillTypeAction("fill.None"));
+ toolbarManager.appendToGroup("group.options.fill", new SelectFillTypeAction("fill.Outline"));
+ toolbarManager.appendToGroup("group.options.fill", new SelectFillTypeAction("fill.Solid"));
+ toolbarManager.add(new Separator());
+ toolbarManager.add(new GroupMarker("group.options.linestyle"));
+ toolbarManager.appendToGroup("group.options.linestyle", new SelectLineStyleAction("linestyle.Solid"));
+ toolbarManager.appendToGroup("group.options.linestyle", new SelectLineStyleAction("linestyle.Dash"));
+ toolbarManager.appendToGroup("group.options.linestyle", new SelectLineStyleAction("linestyle.Dot"));
+ toolbarManager.appendToGroup("group.options.linestyle", new SelectLineStyleAction("linestyle.DashDot"));
+ toolbarManager.add(new Separator());
+ toolbarManager.add(new GroupMarker("group.options"));
+ toolbarManager.appendToGroup("group.options", new SelectFontAction("options.Font"));
+ actionBars.updateActionBars();
+
+ /*** Build GUI ***/
+ createGUI(parent);
+
+ /*** Set defaults ***/
+ setPaintToolByID("tool.Pencil");
+ setFillTypeByID("fill.None");
+ setLineStyleByID("linestyle.Solid");
+ setForegroundColor(paintColorBlack);
+ setBackgroundColor(paintColorWhite);
+ }
+
+ /**
+ * Creates the GUI.
+ */
+ private void createGUI(Composite parent) {
+ GridLayout gridLayout;
+ GridData gridData;
+
+ /*** Create principal GUI layout elements ***/
+ Composite displayArea = new Composite(parent, SWT.NONE);
+ gridLayout = new GridLayout();
+ gridLayout.numColumns = 1;
+ displayArea.setLayout(gridLayout);
+
+ // Creating these elements here avoids the need to instantiate the GUI elements
+ // in strict layout order. The natural layout ordering is an artifact of using
+ // SWT layouts, but unfortunately it is not the same order as that required to
+ // instantiate all of the non-GUI application elements to satisfy referential
+ // dependencies. It is possible to reorder the initialization to some extent, but
+ // this can be very tedious.
+
+ // paint canvas
+ final Canvas paintCanvas = new Canvas(displayArea, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL |
+ SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
+ paintCanvas.setLayoutData(gridData);
+ paintCanvas.setBackground(paintColorWhite);
+
+ // color selector frame
+ final Composite colorFrame = new Composite(displayArea, SWT.NONE);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
+ colorFrame.setLayoutData(gridData);
+
+ // tool settings frame
+ final Composite toolSettingsFrame = new Composite(displayArea, SWT.NONE);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
+ toolSettingsFrame.setLayoutData(gridData);
+
+ // status text
+ final Text statusText = new Text(displayArea, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
+ statusText.setLayoutData(gridData);
+
+ /*** Create the remaining application elements inside the principal GUI layout elements ***/
+ // paintSurface
+ paintSurface = new PaintSurface(paintCanvas, statusText, paintColorWhite);
+
+ // paintToolMap
+ paintToolMap = new HashMap();
+ paintToolMap.put("tool.Pencil", new PencilTool(toolSettings, paintSurface));
+ paintToolMap.put("tool.Airbrush", new AirbrushTool(toolSettings, paintSurface));
+ paintToolMap.put("tool.Line", new LineTool(toolSettings, paintSurface));
+ paintToolMap.put("tool.PolyLine", new PolyLineTool(toolSettings, paintSurface));
+ paintToolMap.put("tool.Rectangle", new RectangleTool(toolSettings, paintSurface));
+ paintToolMap.put("tool.RoundedRectangle", new RoundedRectangleTool(toolSettings, paintSurface));
+ paintToolMap.put("tool.Ellipse", new EllipseTool(toolSettings, paintSurface));
+ paintToolMap.put("tool.Text", new TextTool(toolSettings, paintSurface));
+ paintToolMap.put("tool.Null", null);
+
+ // paintFillTypeMap
+ paintFillTypeMap = new HashMap();
+ paintFillTypeMap.put("fill.None", new Integer(ToolSettings.ftNone));
+ paintFillTypeMap.put("fill.Outline", new Integer(ToolSettings.ftOutline));
+ paintFillTypeMap.put("fill.Solid", new Integer(ToolSettings.ftSolid));
+
+ // paintLineStyleMap
+ paintLineStyleMap = new HashMap();
+ paintLineStyleMap.put("linestyle.Solid", new Integer(SWT.LINE_SOLID));
+ paintLineStyleMap.put("linestyle.Dash", new Integer(SWT.LINE_DASH));
+ paintLineStyleMap.put("linestyle.Dot", new Integer(SWT.LINE_DOT));
+ paintLineStyleMap.put("linestyle.DashDot", new Integer(SWT.LINE_DASHDOT));
+
+ // colorFrame
+ gridLayout = new GridLayout();
+ gridLayout.numColumns = 3;
+ gridLayout.marginHeight = 0;
+ gridLayout.marginWidth = 0;
+ colorFrame.setLayout(gridLayout);
+
+ // activeForegroundColorCanvas, activeBackgroundColorCanvas
+ activeForegroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
+ gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
+ gridData.heightHint = 24;
+ gridData.widthHint = 24;
+ activeForegroundColorCanvas.setLayoutData(gridData);
+
+ activeBackgroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
+ gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
+ gridData.heightHint = 24;
+ gridData.widthHint = 24;
+ activeBackgroundColorCanvas.setLayoutData(gridData);
+
+ // paletteCanvas
+ final Canvas paletteCanvas = new Canvas(colorFrame, SWT.BORDER | SWT.NO_BACKGROUND);
+ gridData = new GridData(GridData.FILL_HORIZONTAL);
+ gridData.heightHint = 24;
+ paletteCanvas.setLayoutData(gridData);
+ paletteCanvas.addListener(SWT.MouseDown, new Listener() {
+ public void handleEvent(Event e) {
+ Rectangle bounds = paletteCanvas.getClientArea();
+ Color color = getColorAt(bounds, e.x, e.y);
+
+ if (e.button == 1) setForegroundColor(color);
+ else setBackgroundColor(color);
+ }
+ private Color getColorAt(Rectangle bounds, int x, int y) {
+ if (bounds.height <= 1 && bounds.width <= 1) return paintColorWhite;
+ final int row = (y - bounds.y) * numPaletteRows / bounds.height;
+ final int col = (x - bounds.x) * numPaletteCols / bounds.width;
+ return paintColors[Math.min(Math.max(row * numPaletteCols + col, 0), paintColors.length - 1)];
+ }
+ });
+ Listener refreshListener = new Listener() {
+ public void handleEvent(Event e) {
+ if (e.gc == null) return;
+ Rectangle bounds = paletteCanvas.getClientArea();
+ for (int row = 0; row < numPaletteRows; ++row) {
+ for (int col = 0; col < numPaletteCols; ++col) {
+ final int x = bounds.width * col / numPaletteCols;
+ final int y = bounds.height * row / numPaletteRows;
+ final int width = Math.max(bounds.width * (col + 1) / numPaletteCols - x, 1);
+ final int height = Math.max(bounds.height * (row + 1) / numPaletteRows - y, 1);
+ e.gc.setBackground(paintColors[row * numPaletteCols + col]);
+ e.gc.fillRectangle(bounds.x + x, bounds.y + y, width, height);
+ }
+ }
+ }
+ };
+ paletteCanvas.addListener(SWT.Resize, refreshListener);
+ paletteCanvas.addListener(SWT.Paint, refreshListener);
+ //paletteCanvas.redraw();
+
+ // toolSettingsFrame
+ gridLayout = new GridLayout();
+ gridLayout.numColumns = 4;
+ gridLayout.marginHeight = 0;
+ gridLayout.marginWidth = 0;
+ toolSettingsFrame.setLayout(gridLayout);
+
+ Label label = new Label(toolSettingsFrame, SWT.NONE);
+ label.setText(PaintPlugin.getResourceString("settings.AirbrushRadius.text"));
+
+ final Scale airbrushRadiusScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
+ airbrushRadiusScale.setMinimum(5);
+ airbrushRadiusScale.setMaximum(50);
+ airbrushRadiusScale.setSelection(toolSettings.airbrushRadius);
+ airbrushRadiusScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
+ airbrushRadiusScale.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ toolSettings.airbrushRadius = airbrushRadiusScale.getSelection();
+ updateToolSettings();
+ }
+ });
+
+ label = new Label(toolSettingsFrame, SWT.NONE);
+ label.setText(PaintPlugin.getResourceString("settings.AirbrushIntensity.text"));
+
+ final Scale airbrushIntensityScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
+ airbrushIntensityScale.setMinimum(1);
+ airbrushIntensityScale.setMaximum(100);
+ airbrushIntensityScale.setSelection(toolSettings.airbrushIntensity);
+ airbrushIntensityScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
+ airbrushIntensityScale.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ toolSettings.airbrushIntensity = airbrushIntensityScale.getSelection();
+ updateToolSettings();
+ }
+ });
+ }
+
+ /**
+ * Notifies the tool that its settings have changed.
+ */
+ private void updateToolSettings() {
+ final PaintTool activePaintTool = paintSurface.getPaintTool();
+ if (activePaintTool == null) return;
+
+ activePaintTool.endSession();
+ activePaintTool.set(toolSettings);
+ activePaintTool.beginSession();
+ }
+
+ /**
+ * Sets the tool foreground color.
+ *
+ * @param color the new color to use
+ */
+ public void setForegroundColor(Color color) {
+ if (activeForegroundColorCanvas != null)
+ activeForegroundColorCanvas.setBackground(color);
+ toolSettings.commonForegroundColor = color;
+ updateToolSettings();
+ }
+
+ /**
+ * Set the tool background color.
+ *
+ * @param color the new color to use
+ */
+ public void setBackgroundColor(Color color) {
+ if (activeBackgroundColorCanvas != null)
+ activeBackgroundColorCanvas.setBackground(color);
+ toolSettings.commonBackgroundColor = color;
+ updateToolSettings();
+ }
+
+ /**
+ * Selects a tool given its ID.
+ */
+ public void setPaintToolByID(String id) {
+ activeToolAction = handleRadioAction(activeToolAction, id);
+
+ final PaintTool paintTool = (PaintTool) paintToolMap.get(id);
+ paintSurface.setPaintSession(paintTool);
+ updateToolSettings();
+ }
+
+ /**
+ * Selects a filltype given its ID.
+ */
+ public void setFillTypeByID(String id) {
+ activeFillTypeAction = handleRadioAction(activeFillTypeAction, id);
+
+ final Integer fillType = (Integer) paintFillTypeMap.get(id);
+ toolSettings.commonFillType = fillType.intValue();
+ updateToolSettings();
+ }
+
+ /**
+ * Selects line type given its ID.
+ */
+ public void setLineStyleByID(String id) {
+ activeLineStyleAction = handleRadioAction(activeLineStyleAction, id);
+
+ final Integer lineType = (Integer) paintLineStyleMap.get(id);
+ toolSettings.commonLineStyle = lineType.intValue();
+ updateToolSettings();
+ }
+
+ /**
+ * Gets the IAction for an ID belonging to a set of mutually exclusive actions, and
+ * toggles the old action off if necessary.
+ */
+ private IAction handleRadioAction(IAction oldAction, String id) {
+ IAction action = getActionByID(id);
+ if (action != null) {
+ if (oldAction != null) oldAction.setChecked(false);
+ if (! action.isChecked()) action.setChecked(true);
+ return action;
+ }
+ return oldAction;
+ }
+
+ /**
+ * Gets the IAction representing the UI toolbar button with the specified ID.
+ */
+ private IAction getActionByID(String id) {
+ final IActionBars actionBars = getViewSite().getActionBars();
+ IToolBarManager toolbarManager = actionBars.getToolBarManager();
+ ActionContributionItem contributionItem = (ActionContributionItem) toolbarManager.find(id);
+ if (contributionItem == null) return null;
+ return contributionItem.getAction();
+ }
+
+ /**
+ * Returns the Display.
+ *
+ * @return the display we're using
+ */
+ public Display getDisplay() {
+ return workbenchDisplay;
+ }
+
+ /**
+ * Action set glue.
+ */
+ abstract class PaintAction extends Action {
+ public PaintAction(String id) {
+ super();
+ setId(id);
+
+ try {
+ final URL installUrl = PaintPlugin.getDefault().getDescriptor().getInstallURL();
+ final URL imageUrl = new URL(installUrl, PaintPlugin.getResourceString(id + ".image"));
+ setImageDescriptor(ImageDescriptor.createFromURL(imageUrl));
+ } catch (MalformedURLException e) {
+ PaintPlugin.logError("", e);
+ }
+
+ setText(PaintPlugin.getResourceString(id + ".label"));
+ setToolTipText(PaintPlugin.getResourceString(id + ".tooltip"));
+ setDescription(PaintPlugin.getResourceString(id + ".description"));
+ }
+ }
+ class SelectPaintToolAction extends PaintAction {
+ public SelectPaintToolAction(String id) { super(id); }
+ public int getStyle() { return IAction.AS_CHECK_BOX; }
+ public void run() { setPaintToolByID(getId()); }
+
+ }
+ class SelectFillTypeAction extends PaintAction {
+ public SelectFillTypeAction(String id) { super(id); }
+ public int getStyle() { return IAction.AS_CHECK_BOX; }
+ public void run() { setFillTypeByID(getId()); }
+ }
+ class SelectLineStyleAction extends PaintAction {
+ public SelectLineStyleAction(String id) { super(id); }
+ public int getStyle() { return IAction.AS_CHECK_BOX; }
+ public void run() { setLineStyleByID(getId()); }
+ }
+ class SelectFontAction extends PaintAction {
+ public SelectFontAction(String id) { super(id); }
+ public int getStyle() { return IAction.AS_PUSH_BUTTON; }
+ public void run() {
+ FontDialog fontDialog = new FontDialog(paintSurface.getShell(), SWT.PRIMARY_MODAL);
+ FontData[] fontDatum = toolSettings.commonFont.getFontData();
+ if (fontDatum != null && fontDatum.length > 0) {
+ fontDialog.setFontData(fontDatum[0]);
+ }
+ fontDialog.setText(PaintPlugin.getResourceString("options.Font.dialog.title"));
+
+ paintSurface.hideRubberband();
+ FontData fontData = fontDialog.open();
+ paintSurface.showRubberband();
+ if (fontData != null) {
+ try {
+ Font font = new Font(workbenchDisplay, fontData);
+ toolSettings.commonFont = font;
+ updateToolSettings();
+ } catch (SWTException e) {
+ }
+ }
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PencilTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PencilTool.java
index ee51916ce9..a1d6c78968 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PencilTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PencilTool.java
@@ -1,54 +1,54 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * A pencil tool.
- */
-public class PencilTool extends ContinuousPaintSession implements PaintTool {
- private ToolSettings settings;
-
- /**
- * Constructs a pencil tool.
- *
- * @param toolSettings the new tool settings
- * @param getPaintSurface() the PaintSurface we will render on.
- */
- public PencilTool(ToolSettings toolSettings, PaintSurface paintSurface) {
- super(paintSurface);
- set(toolSettings);
- }
-
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings) {
- settings = toolSettings;
- }
-
- /**
- * Returns the name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName() {
- return PaintPlugin.getResourceString("tool.Pencil.label");
- }
-
- /*
- * Template method for drawing
- */
- public void render(final Point point) {
- final PaintSurface ps = getPaintSurface();
- ps.drawFigure(new PointFigure(settings.commonForegroundColor, point.x, point.y));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * A pencil tool.
+ */
+public class PencilTool extends ContinuousPaintSession implements PaintTool {
+ private ToolSettings settings;
+
+ /**
+ * Constructs a pencil tool.
+ *
+ * @param toolSettings the new tool settings
+ * @param getPaintSurface() the PaintSurface we will render on.
+ */
+ public PencilTool(ToolSettings toolSettings, PaintSurface paintSurface) {
+ super(paintSurface);
+ set(toolSettings);
+ }
+
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings) {
+ settings = toolSettings;
+ }
+
+ /**
+ * Returns the name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName() {
+ return PaintPlugin.getResourceString("tool.Pencil.label");
+ }
+
+ /*
+ * Template method for drawing
+ */
+ public void render(final Point point) {
+ final PaintSurface ps = getPaintSurface();
+ ps.drawFigure(new PointFigure(settings.commonForegroundColor, point.x, point.y));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PointFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PointFigure.java
index 07fedbd352..53b97f475c 100644
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PointFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PointFigure.java
@@ -1,36 +1,36 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D Point object
- */
-public class PointFigure extends Figure {
- private Color color;
- private int x, y;
- /**
- * Constructs a Point
- *
- * @param color the color for this object
- * @param x the virtual X coordinate of the first end-point
- * @param y the virtual Y coordinate of the first end-point
- */
- public PointFigure(Color color, int x, int y) {
- this.color = color; this.x = x; this.y = y;
- }
- public void draw(FigureDrawContext fdc) {
- Point p = fdc.toClientPoint(x, y);
- fdc.gc.setBackground(color);
- fdc.gc.fillRectangle(p.x, p.y, 1, 1);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- region.add(fdc.toClientRectangle(x, y, x, y));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D Point object
+ */
+public class PointFigure extends Figure {
+ private Color color;
+ private int x, y;
+ /**
+ * Constructs a Point
+ *
+ * @param color the color for this object
+ * @param x the virtual X coordinate of the first end-point
+ * @param y the virtual Y coordinate of the first end-point
+ */
+ public PointFigure(Color color, int x, int y) {
+ this.color = color; this.x = x; this.y = y;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Point p = fdc.toClientPoint(x, y);
+ fdc.gc.setBackground(color);
+ fdc.gc.fillRectangle(p.x, p.y, 1, 1);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ region.add(fdc.toClientRectangle(x, y, x, y));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PolyLineTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PolyLineTool.java
index f2db962fd0..bb9c747193 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PolyLineTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/PolyLineTool.java
@@ -1,71 +1,71 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * A polyline drawing tool.
- */
-public class PolyLineTool extends SegmentedPaintSession implements PaintTool {
- private ToolSettings settings;
-
- /**
- * Constructs a PolyLineTool.
- *
- * @param toolSettings the new tool settings
- * @param paintSurface the PaintSurface we will render on.
- */
- public PolyLineTool(ToolSettings toolSettings, PaintSurface paintSurface) {
- super(paintSurface);
- set(toolSettings);
- }
-
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings) {
- settings = toolSettings;
- }
-
- /**
- * Returns the name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName() {
- return PaintPlugin.getResourceString("tool.PolyLine.label");
- }
-
- /*
- * Template methods for drawing
- */
- protected Figure createFigure(Point[] points, int numPoints, boolean closed) {
- ContainerFigure container = new ContainerFigure();
- if (closed && settings.commonFillType != ToolSettings.ftNone && numPoints >= 3) {
- container.add(new SolidPolygonFigure(settings.commonBackgroundColor, points, numPoints));
- }
- if (! closed || settings.commonFillType != ToolSettings.ftSolid || numPoints < 3) {
- for (int i = 0; i < numPoints - 1; ++i) {
- final Point a = points[i];
- final Point b = points[i + 1];
- container.add(new LineFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
- a.x, a.y, b.x, b.y));
- }
- if (closed) {
- final Point a = points[points.length - 1];
- final Point b = points[0];
- container.add(new LineFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
- a.x, a.y, b.x, b.y));
- }
- }
- return container;
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * A polyline drawing tool.
+ */
+public class PolyLineTool extends SegmentedPaintSession implements PaintTool {
+ private ToolSettings settings;
+
+ /**
+ * Constructs a PolyLineTool.
+ *
+ * @param toolSettings the new tool settings
+ * @param paintSurface the PaintSurface we will render on.
+ */
+ public PolyLineTool(ToolSettings toolSettings, PaintSurface paintSurface) {
+ super(paintSurface);
+ set(toolSettings);
+ }
+
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings) {
+ settings = toolSettings;
+ }
+
+ /**
+ * Returns the name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName() {
+ return PaintPlugin.getResourceString("tool.PolyLine.label");
+ }
+
+ /*
+ * Template methods for drawing
+ */
+ protected Figure createFigure(Point[] points, int numPoints, boolean closed) {
+ ContainerFigure container = new ContainerFigure();
+ if (closed && settings.commonFillType != ToolSettings.ftNone && numPoints >= 3) {
+ container.add(new SolidPolygonFigure(settings.commonBackgroundColor, points, numPoints));
+ }
+ if (! closed || settings.commonFillType != ToolSettings.ftSolid || numPoints < 3) {
+ for (int i = 0; i < numPoints - 1; ++i) {
+ final Point a = points[i];
+ final Point b = points[i + 1];
+ container.add(new LineFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
+ a.x, a.y, b.x, b.y));
+ }
+ if (closed) {
+ final Point a = points[points.length - 1];
+ final Point b = points[0];
+ container.add(new LineFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
+ a.x, a.y, b.x, b.y));
+ }
+ }
+ return container;
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleFigure.java
index a2b4625fe6..f13b423fab 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleFigure.java
@@ -1,47 +1,47 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D Rectangle object
- */
-public class RectangleFigure extends Figure {
- private Color foregroundColor, backgroundColor;
- private int lineStyle, x1, y1, x2, y2;
- /**
- * Constructs a Rectangle
- * These objects are defined by any two diametrically opposing corners.
- *
- * @param color the color for this object
- * @param lineStyle the line style for this object
- * @param x1 the virtual X coordinate of the first corner
- * @param y1 the virtual Y coordinate of the first corner
- * @param x2 the virtual X coordinate of the second corner
- * @param y2 the virtual Y coordinate of the second corner
- */
- public RectangleFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
- this.foregroundColor = foregroundColor;
- this.backgroundColor = backgroundColor;
- this.lineStyle = lineStyle;
- this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
- }
- public void draw(FigureDrawContext fdc) {
- Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
- fdc.gc.setForeground(foregroundColor);
- fdc.gc.setBackground(backgroundColor);
- fdc.gc.setLineStyle(lineStyle);
- fdc.gc.drawRectangle(r.x, r.y, r.width - 1, r.height - 1);
- fdc.gc.setLineStyle(SWT.LINE_SOLID);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- region.add(fdc.toClientRectangle(x1, y1, x2, y2));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D Rectangle object
+ */
+public class RectangleFigure extends Figure {
+ private Color foregroundColor, backgroundColor;
+ private int lineStyle, x1, y1, x2, y2;
+ /**
+ * Constructs a Rectangle
+ * These objects are defined by any two diametrically opposing corners.
+ *
+ * @param color the color for this object
+ * @param lineStyle the line style for this object
+ * @param x1 the virtual X coordinate of the first corner
+ * @param y1 the virtual Y coordinate of the first corner
+ * @param x2 the virtual X coordinate of the second corner
+ * @param y2 the virtual Y coordinate of the second corner
+ */
+ public RectangleFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
+ this.foregroundColor = foregroundColor;
+ this.backgroundColor = backgroundColor;
+ this.lineStyle = lineStyle;
+ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
+ fdc.gc.setForeground(foregroundColor);
+ fdc.gc.setBackground(backgroundColor);
+ fdc.gc.setLineStyle(lineStyle);
+ fdc.gc.drawRectangle(r.x, r.y, r.width - 1, r.height - 1);
+ fdc.gc.setLineStyle(SWT.LINE_SOLID);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ region.add(fdc.toClientRectangle(x1, y1, x2, y2));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleTool.java
index 2da6fa3296..9255f12287 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RectangleTool.java
@@ -1,67 +1,67 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * A drawing tool.
- */
-public class RectangleTool extends DragPaintSession implements PaintTool {
- private ToolSettings settings;
-
- /**
- * Constructs a RectangleTool.
- *
- * @param toolSettings the new tool settings
- * @param paintSurface the PaintSurface we will render on.
- */
- public RectangleTool(ToolSettings toolSettings, PaintSurface paintSurface) {
- super(paintSurface);
- set(toolSettings);
- }
-
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings) {
- settings = toolSettings;
- }
-
- /**
- * Returns name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName() {
- return PaintPlugin.getResourceString("tool.Rectangle.label");
- }
-
- /*
- * Template method for drawing
- */
- protected Figure createFigure(Point a, Point b) {
- switch (settings.commonFillType) {
- default:
- case ToolSettings.ftNone:
- return new RectangleFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
- a.x, a.y, b.x, b.y);
- case ToolSettings.ftSolid:
- return new SolidRectangleFigure(settings.commonBackgroundColor, a.x, a.y, b.x, b.y);
- case ToolSettings.ftOutline: {
- ContainerFigure container = new ContainerFigure();
- container.add(new SolidRectangleFigure(settings.commonBackgroundColor, a.x, a.y, b.x, b.y));
- container.add(new RectangleFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
- a.x, a.y, b.x, b.y));
- return container;
- }
- }
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * A drawing tool.
+ */
+public class RectangleTool extends DragPaintSession implements PaintTool {
+ private ToolSettings settings;
+
+ /**
+ * Constructs a RectangleTool.
+ *
+ * @param toolSettings the new tool settings
+ * @param paintSurface the PaintSurface we will render on.
+ */
+ public RectangleTool(ToolSettings toolSettings, PaintSurface paintSurface) {
+ super(paintSurface);
+ set(toolSettings);
+ }
+
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings) {
+ settings = toolSettings;
+ }
+
+ /**
+ * Returns name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName() {
+ return PaintPlugin.getResourceString("tool.Rectangle.label");
+ }
+
+ /*
+ * Template method for drawing
+ */
+ protected Figure createFigure(Point a, Point b) {
+ switch (settings.commonFillType) {
+ default:
+ case ToolSettings.ftNone:
+ return new RectangleFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
+ a.x, a.y, b.x, b.y);
+ case ToolSettings.ftSolid:
+ return new SolidRectangleFigure(settings.commonBackgroundColor, a.x, a.y, b.x, b.y);
+ case ToolSettings.ftOutline: {
+ ContainerFigure container = new ContainerFigure();
+ container.add(new SolidRectangleFigure(settings.commonBackgroundColor, a.x, a.y, b.x, b.y));
+ container.add(new RectangleFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle,
+ a.x, a.y, b.x, b.y));
+ return container;
+ }
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleFigure.java
index 2dd0bfd29c..1b544021b9 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleFigure.java
@@ -1,49 +1,49 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D Rectangle object
- */
-public class RoundedRectangleFigure extends Figure {
- private Color foregroundColor, backgroundColor;
- private int lineStyle, x1, y1, x2, y2, diameter;
- /**
- * Constructs a Rectangle
- * These objects are defined by any two diametrically opposing corners.
- *
- * @param color the color for this object
- * @param lineStyle the line style for this object
- * @param x1 the virtual X coordinate of the first corner
- * @param y1 the virtual Y coordinate of the first corner
- * @param x2 the virtual X coordinate of the second corner
- * @param y2 the virtual Y coordinate of the second corner
- * @param diameter the diameter of curvature of all four corners
- */
- public RoundedRectangleFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2, int diameter) {
- this.foregroundColor = foregroundColor;
- this.backgroundColor = backgroundColor;
- this.lineStyle = lineStyle;
- this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
- this.diameter = diameter;
- }
- public void draw(FigureDrawContext fdc) {
- Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
- fdc.gc.setForeground(foregroundColor);
- fdc.gc.setBackground(backgroundColor);
- fdc.gc.setLineStyle(lineStyle);
- fdc.gc.drawRoundRectangle(r.x, r.y, r.width - 1, r.height - 1, diameter, diameter);
- fdc.gc.setLineStyle(SWT.LINE_SOLID);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- region.add(fdc.toClientRectangle(x1, y1, x2, y2));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D Rectangle object
+ */
+public class RoundedRectangleFigure extends Figure {
+ private Color foregroundColor, backgroundColor;
+ private int lineStyle, x1, y1, x2, y2, diameter;
+ /**
+ * Constructs a Rectangle
+ * These objects are defined by any two diametrically opposing corners.
+ *
+ * @param color the color for this object
+ * @param lineStyle the line style for this object
+ * @param x1 the virtual X coordinate of the first corner
+ * @param y1 the virtual Y coordinate of the first corner
+ * @param x2 the virtual X coordinate of the second corner
+ * @param y2 the virtual Y coordinate of the second corner
+ * @param diameter the diameter of curvature of all four corners
+ */
+ public RoundedRectangleFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2, int diameter) {
+ this.foregroundColor = foregroundColor;
+ this.backgroundColor = backgroundColor;
+ this.lineStyle = lineStyle;
+ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
+ this.diameter = diameter;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
+ fdc.gc.setForeground(foregroundColor);
+ fdc.gc.setBackground(backgroundColor);
+ fdc.gc.setLineStyle(lineStyle);
+ fdc.gc.drawRoundRectangle(r.x, r.y, r.width - 1, r.height - 1, diameter, diameter);
+ fdc.gc.setLineStyle(SWT.LINE_SOLID);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ region.add(fdc.toClientRectangle(x1, y1, x2, y2));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleTool.java
index beec38ec56..56a25ac60e 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/RoundedRectangleTool.java
@@ -1,60 +1,60 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * A drawing tool.
- */
-public class RoundedRectangleTool extends DragPaintSession implements PaintTool {
- private ToolSettings settings;
-
- /**
- * Constructs a RoundedRectangleTool.
- *
- * @param toolSettings the new tool settings
- * @param paintSurface the PaintSurface we will render on.
- */
- public RoundedRectangleTool(ToolSettings toolSettings, PaintSurface paintSurface) {
- super(paintSurface);
- set(toolSettings);
- }
-
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings) {
- settings = toolSettings;
- }
-
- /**
- * Returns name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName() {
- return PaintPlugin.getResourceString("tool.RoundedRectangle.label");
- }
-
- /*
- * Template methods for drawing
- */
- protected Figure createFigure(Point a, Point b) {
- ContainerFigure container = new ContainerFigure();
- if (settings.commonFillType != ToolSettings.ftNone)
- container.add(new SolidRoundedRectangleFigure(settings.commonBackgroundColor,
- a.x, a.y, b.x, b.y, settings.roundedRectangleCornerDiameter));
- if (settings.commonFillType != ToolSettings.ftSolid)
- container.add(new RoundedRectangleFigure(settings.commonForegroundColor, settings.commonBackgroundColor,
- settings.commonLineStyle, a.x, a.y, b.x, b.y, settings.roundedRectangleCornerDiameter));
- return container;
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * A drawing tool.
+ */
+public class RoundedRectangleTool extends DragPaintSession implements PaintTool {
+ private ToolSettings settings;
+
+ /**
+ * Constructs a RoundedRectangleTool.
+ *
+ * @param toolSettings the new tool settings
+ * @param paintSurface the PaintSurface we will render on.
+ */
+ public RoundedRectangleTool(ToolSettings toolSettings, PaintSurface paintSurface) {
+ super(paintSurface);
+ set(toolSettings);
+ }
+
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings) {
+ settings = toolSettings;
+ }
+
+ /**
+ * Returns name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName() {
+ return PaintPlugin.getResourceString("tool.RoundedRectangle.label");
+ }
+
+ /*
+ * Template methods for drawing
+ */
+ protected Figure createFigure(Point a, Point b) {
+ ContainerFigure container = new ContainerFigure();
+ if (settings.commonFillType != ToolSettings.ftNone)
+ container.add(new SolidRoundedRectangleFigure(settings.commonBackgroundColor,
+ a.x, a.y, b.x, b.y, settings.roundedRectangleCornerDiameter));
+ if (settings.commonFillType != ToolSettings.ftSolid)
+ container.add(new RoundedRectangleFigure(settings.commonForegroundColor, settings.commonBackgroundColor,
+ settings.commonLineStyle, a.x, a.y, b.x, b.y, settings.roundedRectangleCornerDiameter));
+ return container;
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SegmentedPaintSession.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SegmentedPaintSession.java
index d1697eb2eb..0e9e7d812a 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SegmentedPaintSession.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SegmentedPaintSession.java
@@ -1,155 +1,155 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.graphics.*;
-
-import java.util.*;
-
-/**
- * The superclass for paint tools that contruct objects from individually
- * picked segments.
- */
-public abstract class SegmentedPaintSession extends BasicPaintSession {
- /**
- * The set of control points making up the segmented selection
- */
- private Vector /* of Point */ controlPoints = new Vector();
-
- /**
- * The previous figure (so that we can abort with right-button)
- */
- private Figure previousFigure = null;
-
- /**
- * The current figure (so that we can abort with right-button)
- */
- private Figure currentFigure = null;
-
- /**
- * Constructs a PaintSession.
- *
- * @param paintSurface the drawing surface to use
- */
- protected SegmentedPaintSession(PaintSurface paintSurface) {
- super(paintSurface);
- }
-
- /**
- * Activates the tool.
- */
- public void beginSession() {
- getPaintSurface().setStatusMessage(PaintPlugin.getResourceString(
- "session.SegmentedInteractivePaint.message.anchorMode"));
- previousFigure = null;
- currentFigure = null;
- controlPoints.clear();
- }
-
- /**
- * Deactivates the tool.
- */
- public void endSession() {
- getPaintSurface().clearRubberbandSelection();
- if (previousFigure != null) getPaintSurface().drawFigure(previousFigure);
- }
-
- /**
- * Resets the tool.
- * Aborts any operation in progress.
- */
- public void resetSession() {
- getPaintSurface().clearRubberbandSelection();
- if (previousFigure != null) getPaintSurface().drawFigure(previousFigure);
-
- getPaintSurface().setStatusMessage(PaintPlugin.getResourceString(
- "session.SegmentedInteractivePaint.message.anchorMode"));
- previousFigure = null;
- currentFigure = null;
- controlPoints.clear();
- }
-
- /**
- * Handles a mouseDown event.
- *
- * @param event the mouse event detail information
- */
- public void mouseDown(MouseEvent event) {
- if (event.button != 1) return;
-
- getPaintSurface().setStatusMessage(PaintPlugin.getResourceString(
- "session.SegmentedInteractivePaint.message.interactiveMode"));
- previousFigure = currentFigure;
-
- if (controlPoints.size() > 0) {
- final Point lastPoint = (Point) controlPoints.elementAt(controlPoints.size() - 1);
- if (lastPoint.x == event.x || lastPoint.y == event.y) return; // spurious event
- }
- controlPoints.add(new Point(event.x, event.y));
- }
-
- /**
- * Handles a mouseDoubleClick event.
- *
- * @param event the mouse event detail information
- */
- public void mouseDoubleClick(MouseEvent event) {
- if (event.button != 1) return;
- if (controlPoints.size() >= 2) {
- getPaintSurface().clearRubberbandSelection();
- previousFigure = createFigure(
- (Point[]) controlPoints.toArray(new Point[controlPoints.size()]),
- controlPoints.size(), true);
- }
- resetSession();
- }
-
- /**
- * Handles a mouseUp event.
- *
- * @param event the mouse event detail information
- */
- public void mouseUp(MouseEvent event) {
- if (event.button != 1) {
- resetSession(); // abort if right or middle mouse button pressed
- return;
- }
- }
-
- /**
- * Handles a mouseMove event.
- *
- * @param event the mouse event detail information
- */
- public void mouseMove(MouseEvent event) {
- final PaintSurface ps = getPaintSurface();
- if (controlPoints.size() == 0) {
- ps.setStatusCoord(ps.getCurrentPosition());
- return; // spurious event
- } else {
- ps.setStatusCoordRange((Point) controlPoints.elementAt(controlPoints.size() - 1),
- ps.getCurrentPosition());
- }
-
- ps.clearRubberbandSelection();
- Point[] points = (Point[]) controlPoints.toArray(new Point[controlPoints.size() + 1]);
- points[controlPoints.size()] = ps.getCurrentPosition();
- currentFigure = createFigure(points, points.length, false);
- ps.addRubberbandSelection(currentFigure);
- }
-
- /**
- * Template Method: Creates a Figure for drawing rubberband entities and the final product
- *
- * @param points the array of control points
- * @param numPoints the number of valid points in the array (n >= 2)
- * @param closed true if the user double-clicked on the final control point
- */
- protected abstract Figure createFigure(Point[] points, int numPoints, boolean closed);
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.graphics.*;
+
+import java.util.*;
+
+/**
+ * The superclass for paint tools that contruct objects from individually
+ * picked segments.
+ */
+public abstract class SegmentedPaintSession extends BasicPaintSession {
+ /**
+ * The set of control points making up the segmented selection
+ */
+ private Vector /* of Point */ controlPoints = new Vector();
+
+ /**
+ * The previous figure (so that we can abort with right-button)
+ */
+ private Figure previousFigure = null;
+
+ /**
+ * The current figure (so that we can abort with right-button)
+ */
+ private Figure currentFigure = null;
+
+ /**
+ * Constructs a PaintSession.
+ *
+ * @param paintSurface the drawing surface to use
+ */
+ protected SegmentedPaintSession(PaintSurface paintSurface) {
+ super(paintSurface);
+ }
+
+ /**
+ * Activates the tool.
+ */
+ public void beginSession() {
+ getPaintSurface().setStatusMessage(PaintPlugin.getResourceString(
+ "session.SegmentedInteractivePaint.message.anchorMode"));
+ previousFigure = null;
+ currentFigure = null;
+ controlPoints.clear();
+ }
+
+ /**
+ * Deactivates the tool.
+ */
+ public void endSession() {
+ getPaintSurface().clearRubberbandSelection();
+ if (previousFigure != null) getPaintSurface().drawFigure(previousFigure);
+ }
+
+ /**
+ * Resets the tool.
+ * Aborts any operation in progress.
+ */
+ public void resetSession() {
+ getPaintSurface().clearRubberbandSelection();
+ if (previousFigure != null) getPaintSurface().drawFigure(previousFigure);
+
+ getPaintSurface().setStatusMessage(PaintPlugin.getResourceString(
+ "session.SegmentedInteractivePaint.message.anchorMode"));
+ previousFigure = null;
+ currentFigure = null;
+ controlPoints.clear();
+ }
+
+ /**
+ * Handles a mouseDown event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseDown(MouseEvent event) {
+ if (event.button != 1) return;
+
+ getPaintSurface().setStatusMessage(PaintPlugin.getResourceString(
+ "session.SegmentedInteractivePaint.message.interactiveMode"));
+ previousFigure = currentFigure;
+
+ if (controlPoints.size() > 0) {
+ final Point lastPoint = (Point) controlPoints.elementAt(controlPoints.size() - 1);
+ if (lastPoint.x == event.x || lastPoint.y == event.y) return; // spurious event
+ }
+ controlPoints.add(new Point(event.x, event.y));
+ }
+
+ /**
+ * Handles a mouseDoubleClick event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseDoubleClick(MouseEvent event) {
+ if (event.button != 1) return;
+ if (controlPoints.size() >= 2) {
+ getPaintSurface().clearRubberbandSelection();
+ previousFigure = createFigure(
+ (Point[]) controlPoints.toArray(new Point[controlPoints.size()]),
+ controlPoints.size(), true);
+ }
+ resetSession();
+ }
+
+ /**
+ * Handles a mouseUp event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseUp(MouseEvent event) {
+ if (event.button != 1) {
+ resetSession(); // abort if right or middle mouse button pressed
+ return;
+ }
+ }
+
+ /**
+ * Handles a mouseMove event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseMove(MouseEvent event) {
+ final PaintSurface ps = getPaintSurface();
+ if (controlPoints.size() == 0) {
+ ps.setStatusCoord(ps.getCurrentPosition());
+ return; // spurious event
+ } else {
+ ps.setStatusCoordRange((Point) controlPoints.elementAt(controlPoints.size() - 1),
+ ps.getCurrentPosition());
+ }
+
+ ps.clearRubberbandSelection();
+ Point[] points = (Point[]) controlPoints.toArray(new Point[controlPoints.size() + 1]);
+ points[controlPoints.size()] = ps.getCurrentPosition();
+ currentFigure = createFigure(points, points.length, false);
+ ps.addRubberbandSelection(currentFigure);
+ }
+
+ /**
+ * Template Method: Creates a Figure for drawing rubberband entities and the final product
+ *
+ * @param points the array of control points
+ * @param numPoints the number of valid points in the array (n >= 2)
+ * @param closed true if the user double-clicked on the final control point
+ */
+ protected abstract Figure createFigure(Point[] points, int numPoints, boolean closed);
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidEllipseFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidEllipseFigure.java
index 123417fd5e..eef46b9ac7 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidEllipseFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidEllipseFigure.java
@@ -1,40 +1,40 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D Solid Ellipse object
- */
-public class SolidEllipseFigure extends Figure {
- private Color color;
- private int x1, y1, x2, y2;
- /**
- * Constructs a SolidEllipse
- * These objects are defined by any two diametrically opposing corners of a box
- * bounding the ellipse.
- *
- * @param color the color for this object
- * @param x1 the virtual X coordinate of the first corner
- * @param y1 the virtual Y coordinate of the first corner
- * @param x2 the virtual X coordinate of the second corner
- * @param y2 the virtual Y coordinate of the second corner
- */
- public SolidEllipseFigure(Color color, int x1, int y1, int x2, int y2) {
- this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
- }
- public void draw(FigureDrawContext fdc) {
- Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
- fdc.gc.setBackground(color);
- fdc.gc.fillOval(r.x, r.y, r.width, r.height);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- region.add(fdc.toClientRectangle(x1, y1, x2, y2));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D Solid Ellipse object
+ */
+public class SolidEllipseFigure extends Figure {
+ private Color color;
+ private int x1, y1, x2, y2;
+ /**
+ * Constructs a SolidEllipse
+ * These objects are defined by any two diametrically opposing corners of a box
+ * bounding the ellipse.
+ *
+ * @param color the color for this object
+ * @param x1 the virtual X coordinate of the first corner
+ * @param y1 the virtual Y coordinate of the first corner
+ * @param x2 the virtual X coordinate of the second corner
+ * @param y2 the virtual Y coordinate of the second corner
+ */
+ public SolidEllipseFigure(Color color, int x1, int y1, int x2, int y2) {
+ this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
+ fdc.gc.setBackground(color);
+ fdc.gc.fillOval(r.x, r.y, r.width, r.height);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ region.add(fdc.toClientRectangle(x1, y1, x2, y2));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidPolygonFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidPolygonFigure.java
index 30b47100b4..7426d37017 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidPolygonFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidPolygonFigure.java
@@ -1,55 +1,55 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D Line object
- */
-public class SolidPolygonFigure extends Figure {
- private Color color;
- private int[] points;
- /**
- * Constructs a SolidPolygon
- * These objects are defined by a sequence of vertices.
- *
- * @param color the color for this object
- * @param vertices the array of vertices making up the polygon
- * @param numPoint the number of valid points in the array (n >= 3)
- */
- public SolidPolygonFigure(Color color, Point[] vertices, int numPoints) {
- this.color = color;
- this.points = new int[numPoints * 2];
- for (int i = 0; i < numPoints; ++i) {
- points[i * 2] = vertices[i].x;
- points[i * 2 + 1] = vertices[i].y;
- }
- }
- public void draw(FigureDrawContext fdc) {
- int[] drawPoints = new int[points.length];
- for (int i = 0; i < points.length; i += 2) {
- drawPoints[i] = points[i] * fdc.xScale - fdc.xOffset;
- drawPoints[i + 1] = points[i + 1] * fdc.yScale - fdc.yOffset;
- }
- fdc.gc.setBackground(color);
- fdc.gc.fillPolygon(drawPoints);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- int xmin = Integer.MAX_VALUE, ymin = Integer.MAX_VALUE;
- int xmax = Integer.MIN_VALUE, ymax = Integer.MIN_VALUE;
-
- for (int i = 0; i < points.length; i += 2) {
- if (points[i] < xmin) xmin = points[i];
- if (points[i] > xmax) xmax = points[i];
- if (points[i+1] < ymin) ymin = points[i+1];
- if (points[i+1] > ymax) ymax = points[i+1];
- }
- region.add(fdc.toClientRectangle(xmin, ymin, xmax, ymax));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D Line object
+ */
+public class SolidPolygonFigure extends Figure {
+ private Color color;
+ private int[] points;
+ /**
+ * Constructs a SolidPolygon
+ * These objects are defined by a sequence of vertices.
+ *
+ * @param color the color for this object
+ * @param vertices the array of vertices making up the polygon
+ * @param numPoint the number of valid points in the array (n >= 3)
+ */
+ public SolidPolygonFigure(Color color, Point[] vertices, int numPoints) {
+ this.color = color;
+ this.points = new int[numPoints * 2];
+ for (int i = 0; i < numPoints; ++i) {
+ points[i * 2] = vertices[i].x;
+ points[i * 2 + 1] = vertices[i].y;
+ }
+ }
+ public void draw(FigureDrawContext fdc) {
+ int[] drawPoints = new int[points.length];
+ for (int i = 0; i < points.length; i += 2) {
+ drawPoints[i] = points[i] * fdc.xScale - fdc.xOffset;
+ drawPoints[i + 1] = points[i + 1] * fdc.yScale - fdc.yOffset;
+ }
+ fdc.gc.setBackground(color);
+ fdc.gc.fillPolygon(drawPoints);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ int xmin = Integer.MAX_VALUE, ymin = Integer.MAX_VALUE;
+ int xmax = Integer.MIN_VALUE, ymax = Integer.MIN_VALUE;
+
+ for (int i = 0; i < points.length; i += 2) {
+ if (points[i] < xmin) xmin = points[i];
+ if (points[i] > xmax) xmax = points[i];
+ if (points[i+1] < ymin) ymin = points[i+1];
+ if (points[i+1] > ymax) ymax = points[i+1];
+ }
+ region.add(fdc.toClientRectangle(xmin, ymin, xmax, ymax));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRectangleFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRectangleFigure.java
index 9f2d7b64a3..5e88f2cbf2 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRectangleFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRectangleFigure.java
@@ -1,39 +1,39 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D SolidRectangle object
- */
-public class SolidRectangleFigure extends Figure {
- private Color color;
- private int x1, y1, x2, y2;
- /**
- * Constructs a SolidRectangle
- * These objects are defined by any two diametrically opposing corners.
- *
- * @param color the color for this object
- * @param x1 the virtual X coordinate of the first corner
- * @param y1 the virtual Y coordinate of the first corner
- * @param x2 the virtual X coordinate of the second corner
- * @param y2 the virtual Y coordinate of the second corner
- */
- public SolidRectangleFigure(Color color, int x1, int y1, int x2, int y2) {
- this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
- }
- public void draw(FigureDrawContext fdc) {
- Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
- fdc.gc.setBackground(color);
- fdc.gc.fillRectangle(r.x, r.y, r.width, r.height);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- region.add(fdc.toClientRectangle(x1, y1, x2, y2));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D SolidRectangle object
+ */
+public class SolidRectangleFigure extends Figure {
+ private Color color;
+ private int x1, y1, x2, y2;
+ /**
+ * Constructs a SolidRectangle
+ * These objects are defined by any two diametrically opposing corners.
+ *
+ * @param color the color for this object
+ * @param x1 the virtual X coordinate of the first corner
+ * @param y1 the virtual Y coordinate of the first corner
+ * @param x2 the virtual X coordinate of the second corner
+ * @param y2 the virtual Y coordinate of the second corner
+ */
+ public SolidRectangleFigure(Color color, int x1, int y1, int x2, int y2) {
+ this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
+ fdc.gc.setBackground(color);
+ fdc.gc.fillRectangle(r.x, r.y, r.width, r.height);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ region.add(fdc.toClientRectangle(x1, y1, x2, y2));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRoundedRectangleFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRoundedRectangleFigure.java
index de07824310..4faab8b354 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRoundedRectangleFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/SolidRoundedRectangleFigure.java
@@ -1,41 +1,41 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D SolidRectangle object
- */
-public class SolidRoundedRectangleFigure extends Figure {
- private Color color;
- private int x1, y1, x2, y2, diameter;
- /**
- * Constructs a SolidRectangle
- * These objects are defined by any two diametrically opposing corners.
- *
- * @param color the color for this object
- * @param x1 the virtual X coordinate of the first corner
- * @param y1 the virtual Y coordinate of the first corner
- * @param x2 the virtual X coordinate of the second corner
- * @param y2 the virtual Y coordinate of the second corner
- * @param diameter the diameter of curvature of all four corners
- */
- public SolidRoundedRectangleFigure(Color color, int x1, int y1, int x2, int y2, int diameter) {
- this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
- this.diameter = diameter;
- }
- public void draw(FigureDrawContext fdc) {
- Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
- fdc.gc.setBackground(color);
- fdc.gc.fillRoundRectangle(r.x, r.y, r.width, r.height, diameter, diameter);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- region.add(fdc.toClientRectangle(x1, y1, x2, y2));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D SolidRectangle object
+ */
+public class SolidRoundedRectangleFigure extends Figure {
+ private Color color;
+ private int x1, y1, x2, y2, diameter;
+ /**
+ * Constructs a SolidRectangle
+ * These objects are defined by any two diametrically opposing corners.
+ *
+ * @param color the color for this object
+ * @param x1 the virtual X coordinate of the first corner
+ * @param y1 the virtual Y coordinate of the first corner
+ * @param x2 the virtual X coordinate of the second corner
+ * @param y2 the virtual Y coordinate of the second corner
+ * @param diameter the diameter of curvature of all four corners
+ */
+ public SolidRoundedRectangleFigure(Color color, int x1, int y1, int x2, int y2, int diameter) {
+ this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
+ this.diameter = diameter;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
+ fdc.gc.setBackground(color);
+ fdc.gc.fillRoundRectangle(r.x, r.y, r.width, r.height, diameter, diameter);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ region.add(fdc.toClientRectangle(x1, y1, x2, y2));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextFigure.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextFigure.java
index 9317772e94..9b618380c7 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextFigure.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextFigure.java
@@ -1,45 +1,45 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-
-/**
- * 2D Rectangle object
- */
-public class TextFigure extends Figure {
- private Color color;
- private Font font;
- private String text;
- private int x, y;
- /**
- * Constructs a TextFigure
- *
- * @param color the color for this object
- * @param font the font for this object
- * @param text the text to draw, tab and new-line expansion is performed
- * @param x the virtual X coordinate of the top-left corner of the text bounding box
- * @param y the virtual Y coordinate of the top-left corner of the text bounding box
- */
- public TextFigure(Color color, Font font, String text, int x, int y) {
- this.color = color; this.font = font; this.text = text; this.x = x; this.y = y;
- }
- public void draw(FigureDrawContext fdc) {
- Point p = fdc.toClientPoint(x, y);
- fdc.gc.setFont(font);
- fdc.gc.setForeground(color);
- fdc.gc.drawText(text, p.x, p.y, true);
- }
- public void addDamagedRegion(FigureDrawContext fdc, Region region) {
- Font oldFont = fdc.gc.getFont();
- fdc.gc.setFont(font);
- Point textExtent = fdc.gc.textExtent(text);
- fdc.gc.setFont(oldFont);
- region.add(fdc.toClientRectangle(x, y, x + textExtent.x, y + textExtent.y));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+
+/**
+ * 2D Rectangle object
+ */
+public class TextFigure extends Figure {
+ private Color color;
+ private Font font;
+ private String text;
+ private int x, y;
+ /**
+ * Constructs a TextFigure
+ *
+ * @param color the color for this object
+ * @param font the font for this object
+ * @param text the text to draw, tab and new-line expansion is performed
+ * @param x the virtual X coordinate of the top-left corner of the text bounding box
+ * @param y the virtual Y coordinate of the top-left corner of the text bounding box
+ */
+ public TextFigure(Color color, Font font, String text, int x, int y) {
+ this.color = color; this.font = font; this.text = text; this.x = x; this.y = y;
+ }
+ public void draw(FigureDrawContext fdc) {
+ Point p = fdc.toClientPoint(x, y);
+ fdc.gc.setFont(font);
+ fdc.gc.setForeground(color);
+ fdc.gc.drawText(text, p.x, p.y, true);
+ }
+ public void addDamagedRegion(FigureDrawContext fdc, Region region) {
+ Font oldFont = fdc.gc.getFont();
+ fdc.gc.setFont(font);
+ Point textExtent = fdc.gc.textExtent(text);
+ fdc.gc.setFont(oldFont);
+ region.add(fdc.toClientRectangle(x, y, x + textExtent.x, y + textExtent.y));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextTool.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextTool.java
index bf051dc1d3..5858fe3353 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextTool.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/TextTool.java
@@ -1,123 +1,123 @@
-package org.eclipse.swt.examples.paint;
-
-/*
+package org.eclipse.swt.examples.paint;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.jface.dialogs.*;
-import org.eclipse.swt.events.*;
-
-/**
- * A text drawing tool.
- */
-public class TextTool extends BasicPaintSession implements PaintTool {
- private ToolSettings settings;
- private String drawText = PaintPlugin.getResourceString("tool.Text.settings.defaulttext");
-
- /**
- * Constructs a PaintTool.
- *
- * @param toolSettings the new tool settings
- * @param paintSurface the PaintSurface we will render on.
- */
- public TextTool(ToolSettings toolSettings, PaintSurface paintSurface) {
- super(paintSurface);
- set(toolSettings);
- }
-
- /**
- * Sets the tool's settings.
- *
- * @param toolSettings the new tool settings
- */
- public void set(ToolSettings toolSettings) {
- settings = toolSettings;
- }
-
- /**
- * Returns name associated with this tool.
- *
- * @return the localized name of this tool
- */
- public String getDisplayName() {
- return PaintPlugin.getResourceString("tool.Text.label");
- }
-
- /**
- * Activates the tool.
- */
- public void beginSession() {
- getPaintSurface().setStatusMessage(PaintPlugin.getResourceString(
- "session.Text.message"));
- }
-
- /**
- * Deactivates the tool.
- */
- public void endSession() {
- getPaintSurface().clearRubberbandSelection();
- }
-
- /**
- * Aborts the current operation.
- */
- public void resetSession() {
- getPaintSurface().clearRubberbandSelection();
- }
-
- /**
- * Handles a mouseDown event.
- *
- * @param event the mouse event detail information
- */
- public void mouseDown(MouseEvent event) {
- if (event.button == 1) {
- // draw with left mouse button
- getPaintSurface().commitRubberbandSelection();
- } else {
- // set text with right mouse button
- getPaintSurface().clearRubberbandSelection();
- InputDialog inputDialog = new InputDialog(getPaintSurface().getShell(),
- PaintPlugin.getResourceString("tool.Text.dialog.title"),
- PaintPlugin.getResourceString("tool.Text.dialog.message"),
- drawText, null);
- inputDialog.setBlockOnOpen(true);
- inputDialog.open();
- if (inputDialog.getReturnCode() == InputDialog.OK) drawText = inputDialog.getValue();
- inputDialog.close();
- }
- }
-
- /**
- * Handles a mouseDoubleClick event.
- *
- * @param event the mouse event detail information
- */
- public void mouseDoubleClick(MouseEvent event) {
- }
-
- /**
- * Handles a mouseUp event.
- *
- * @param event the mouse event detail information
- */
- public void mouseUp(MouseEvent event) {
- }
-
- /**
- * Handles a mouseMove event.
- *
- * @param event the mouse event detail information
- */
- public void mouseMove(MouseEvent event) {
- final PaintSurface ps = getPaintSurface();
- ps.setStatusCoord(ps.getCurrentPosition());
- ps.clearRubberbandSelection();
- ps.addRubberbandSelection(
- new TextFigure(settings.commonForegroundColor, settings.commonFont,
- drawText, event.x, event.y));
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.jface.dialogs.*;
+import org.eclipse.swt.events.*;
+
+/**
+ * A text drawing tool.
+ */
+public class TextTool extends BasicPaintSession implements PaintTool {
+ private ToolSettings settings;
+ private String drawText = PaintPlugin.getResourceString("tool.Text.settings.defaulttext");
+
+ /**
+ * Constructs a PaintTool.
+ *
+ * @param toolSettings the new tool settings
+ * @param paintSurface the PaintSurface we will render on.
+ */
+ public TextTool(ToolSettings toolSettings, PaintSurface paintSurface) {
+ super(paintSurface);
+ set(toolSettings);
+ }
+
+ /**
+ * Sets the tool's settings.
+ *
+ * @param toolSettings the new tool settings
+ */
+ public void set(ToolSettings toolSettings) {
+ settings = toolSettings;
+ }
+
+ /**
+ * Returns name associated with this tool.
+ *
+ * @return the localized name of this tool
+ */
+ public String getDisplayName() {
+ return PaintPlugin.getResourceString("tool.Text.label");
+ }
+
+ /**
+ * Activates the tool.
+ */
+ public void beginSession() {
+ getPaintSurface().setStatusMessage(PaintPlugin.getResourceString(
+ "session.Text.message"));
+ }
+
+ /**
+ * Deactivates the tool.
+ */
+ public void endSession() {
+ getPaintSurface().clearRubberbandSelection();
+ }
+
+ /**
+ * Aborts the current operation.
+ */
+ public void resetSession() {
+ getPaintSurface().clearRubberbandSelection();
+ }
+
+ /**
+ * Handles a mouseDown event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseDown(MouseEvent event) {
+ if (event.button == 1) {
+ // draw with left mouse button
+ getPaintSurface().commitRubberbandSelection();
+ } else {
+ // set text with right mouse button
+ getPaintSurface().clearRubberbandSelection();
+ InputDialog inputDialog = new InputDialog(getPaintSurface().getShell(),
+ PaintPlugin.getResourceString("tool.Text.dialog.title"),
+ PaintPlugin.getResourceString("tool.Text.dialog.message"),
+ drawText, null);
+ inputDialog.setBlockOnOpen(true);
+ inputDialog.open();
+ if (inputDialog.getReturnCode() == InputDialog.OK) drawText = inputDialog.getValue();
+ inputDialog.close();
+ }
+ }
+
+ /**
+ * Handles a mouseDoubleClick event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseDoubleClick(MouseEvent event) {
+ }
+
+ /**
+ * Handles a mouseUp event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseUp(MouseEvent event) {
+ }
+
+ /**
+ * Handles a mouseMove event.
+ *
+ * @param event the mouse event detail information
+ */
+ public void mouseMove(MouseEvent event) {
+ final PaintSurface ps = getPaintSurface();
+ ps.setStatusCoord(ps.getCurrentPosition());
+ ps.clearRubberbandSelection();
+ ps.addRubberbandSelection(
+ new TextFigure(settings.commonForegroundColor, settings.commonFont,
+ drawText, event.x, event.y));
+ }
+}
diff --git a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ToolSettings.java b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ToolSettings.java
index 6c5aee8e72..52b3a8ecdd 100755
--- a/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ToolSettings.java
+++ b/examples/org.eclipse.swt.examples.paint/src/org/eclipse/swt/examples/paint/ToolSettings.java
@@ -1,29 +1,29 @@
-package org.eclipse.swt.examples.paint;
-/*
+package org.eclipse.swt.examples.paint;
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
- import org.eclipse.swt.*; import org.eclipse.swt.graphics.*;
- /** * Tool Settings objects group tool-related configuration information. */
-public class ToolSettings {
- public static final int ftNone = 0, ftOutline = 1, ftSolid = 2; /**
- * commonForegroundColor: current tool foreground colour
- */
- public Color commonForegroundColor;
-
- /**
- * commonBackgroundColor: current tool background colour
- */
- public Color commonBackgroundColor;
- /** * commonFont: current font */ public Font commonFont; /** * commonFillType: current fill type * <p>One of ftNone, ftOutline, ftSolid.</p> */ public int commonFillType = ftNone; /** * commonLineStyle: current line type */ public int commonLineStyle = SWT.LINE_SOLID;
- /**
- * airbrushRadius: coverage radius in pixels
- */
- public int airbrushRadius = 10;
-
- /**
- * airbrushIntensity: average surface area coverage in region defined by radius per "jot"
- */
- public int airbrushIntensity = 30; /** * roundedRectangleCornerDiameter: the diameter of curvature of corners in a rounded rectangle */ public int roundedRectangleCornerDiameter = 16; }
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+ import org.eclipse.swt.*; import org.eclipse.swt.graphics.*;
+ /** * Tool Settings objects group tool-related configuration information. */
+public class ToolSettings {
+ public static final int ftNone = 0, ftOutline = 1, ftSolid = 2; /**
+ * commonForegroundColor: current tool foreground colour
+ */
+ public Color commonForegroundColor;
+
+ /**
+ * commonBackgroundColor: current tool background colour
+ */
+ public Color commonBackgroundColor;
+ /** * commonFont: current font */ public Font commonFont; /** * commonFillType: current fill type * <p>One of ftNone, ftOutline, ftSolid.</p> */ public int commonFillType = ftNone; /** * commonLineStyle: current line type */ public int commonLineStyle = SWT.LINE_SOLID;
+ /**
+ * airbrushRadius: coverage radius in pixels
+ */
+ public int airbrushRadius = 10;
+
+ /**
+ * airbrushIntensity: average surface area coverage in region defined by radius per "jot"
+ */
+ public int airbrushIntensity = 30; /** * roundedRectangleCornerDiameter: the diameter of curvature of corners in a rounded rectangle */ public int roundedRectangleCornerDiameter = 16; }
diff --git a/examples/org.eclipse.swt.examples/.project b/examples/org.eclipse.swt.examples/.project
index 7dfd92eb80..069b3a1b00 100644
--- a/examples/org.eclipse.swt.examples/.project
+++ b/examples/org.eclipse.swt.examples/.project
@@ -1,29 +1,29 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.eclipse.swt.examples</name>
- <comment></comment>
- <projects>
- <project>org.eclipse.swt</project>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.swt.examples</name>
+ <comment></comment>
+ <projects>
+ <project>org.eclipse.swt</project>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ </natures>
+</projectDescription>
diff --git a/examples/org.eclipse.swt.examples/build.properties b/examples/org.eclipse.swt.examples/build.properties
index 62ce80a8a4..a9076c7f02 100755
--- a/examples/org.eclipse.swt.examples/build.properties
+++ b/examples/org.eclipse.swt.examples/build.properties
@@ -1,9 +1,9 @@
-bin.includes = doc-html/,\
- plugin.properties,\
- plugin.xml,\
- about.html,\
- swtexamples.jar
-
-src.includes = about.html
-
-source.swtexamples.jar = src/
+bin.includes = doc-html/,\
+ plugin.properties,\
+ plugin.xml,\
+ about.html,\
+ swtexamples.jar
+
+src.includes = about.html
+
+source.swtexamples.jar = src/
diff --git a/examples/org.eclipse.swt.examples/doc-html/hglegal2002.htm b/examples/org.eclipse.swt.examples/doc-html/hglegal2002.htm
index 74393f08f3..5df454d51a 100644
--- a/examples/org.eclipse.swt.examples/doc-html/hglegal2002.htm
+++ b/examples/org.eclipse.swt.examples/doc-html/hglegal2002.htm
@@ -1,14 +1,14 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
- <title>Legal Notices</title>
-</head>
-<body>
-
-<h3>
-<a NAME="Notices"></a>Notices</h3>
-(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
+ <title>Legal Notices</title>
+</head>
+<body>
+
+<h3>
+<a NAME="Notices"></a>Notices</h3>
+(c) Copyright IBM Corp. 2000, 2002. All Rights Reserved.
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/doc-html/swt_addressbook_ex.html b/examples/org.eclipse.swt.examples/doc-html/swt_addressbook_ex.html
index 74a6801bd3..e7f7c47618 100755
--- a/examples/org.eclipse.swt.examples/doc-html/swt_addressbook_ex.html
+++ b/examples/org.eclipse.swt.examples/doc-html/swt_addressbook_ex.html
@@ -1,31 +1,31 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Address Book Example</title>
-</head>
-<body>
-
-<h2>SWT Standalone Example - Address Book</h2>
-
-<p>
-The AddressBook example shows how the Table control can be used to
-present information in a tabular format. The application can save and load data
-from a file, sort the entries, and search for strings within the fields.
-</p>
-
-<h3>Running the example</h3>
-<p>
-Follow the <a href="swt_manual_setup.html">Manual Setup</a>
-instructions to install and run the example from your workspace.
-</p>
-<p>
-The "Main" class is <code>org.eclipse.swt.examples.addressbook.AddressBook</code>.
-</p>
-<p>
-This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
-Select the Address Book item from the Standalone category and click Run.
-</p>
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Address Book Example</title>
+</head>
+<body>
+
+<h2>SWT Standalone Example - Address Book</h2>
+
+<p>
+The AddressBook example shows how the Table control can be used to
+present information in a tabular format. The application can save and load data
+from a file, sort the entries, and search for strings within the fields.
+</p>
+
+<h3>Running the example</h3>
+<p>
+Follow the <a href="swt_manual_setup.html">Manual Setup</a>
+instructions to install and run the example from your workspace.
+</p>
+<p>
+The "Main" class is <code>org.eclipse.swt.examples.addressbook.AddressBook</code>.
+</p>
+<p>
+This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
+Select the Address Book item from the Standalone category and click Run.
+</p>
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/doc-html/swt_fileviewer_ex.html b/examples/org.eclipse.swt.examples/doc-html/swt_fileviewer_ex.html
index a3d06c10af..4b19776747 100755
--- a/examples/org.eclipse.swt.examples/doc-html/swt_fileviewer_ex.html
+++ b/examples/org.eclipse.swt.examples/doc-html/swt_fileviewer_ex.html
@@ -1,33 +1,33 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - File Viewer Example</title>
-</head>
-<body>
-
-<h2>SWT Standalone Example - File Viewer</h2>
-
-<p>
-The File Viewer example shows how a simple application can be implemented using SWT.
-This application provides the ability to navigate files and folders and manipulate them via Drag and Drop.
-It includes the use of alternate threads for long actions and demonstrates the use of the Tree,
-Table, Toolbar and Program.
-</p>
-
-<h3>Running the example</h3>
-<p>
-Follow the <a href="swt_manual_setup.html">Manual Setup</a>
-instructions to install and run the example from your workspace.
-</p>
-<p>
-The "Main" class is <code>org.eclipse.swt.examples.fileviewer.FileViewer</code>.
-</p>
-<p>
-This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
-Select the File Viewer item from the Standalone category and click Run.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - File Viewer Example</title>
+</head>
+<body>
+
+<h2>SWT Standalone Example - File Viewer</h2>
+
+<p>
+The File Viewer example shows how a simple application can be implemented using SWT.
+This application provides the ability to navigate files and folders and manipulate them via Drag and Drop.
+It includes the use of alternate threads for long actions and demonstrates the use of the Tree,
+Table, Toolbar and Program.
+</p>
+
+<h3>Running the example</h3>
+<p>
+Follow the <a href="swt_manual_setup.html">Manual Setup</a>
+instructions to install and run the example from your workspace.
+</p>
+<p>
+The "Main" class is <code>org.eclipse.swt.examples.fileviewer.FileViewer</code>.
+</p>
+<p>
+This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
+Select the File Viewer item from the Standalone category and click Run.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/doc-html/swt_helloworld_ex.html b/examples/org.eclipse.swt.examples/doc-html/swt_helloworld_ex.html
index f9e8953276..804407af18 100755
--- a/examples/org.eclipse.swt.examples/doc-html/swt_helloworld_ex.html
+++ b/examples/org.eclipse.swt.examples/doc-html/swt_helloworld_ex.html
@@ -1,61 +1,61 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Hello World Examples</title>
-</head>
-<body>
-
-<h2>SWT Standalone Example - Hello World</h2>
-
-<p>
-The Hello World examples are a set of introductory examples to show how to get started
-creating an application with SWT. They cover creating a shell, using event listeners,
-processing events in an event loop, using layouts, and drawing with a Graphic Context.
-</p>
-
-<h4>Hello World 1</h4>
-<p>
-This example demonstrates how to open a Shell and process the events.
-</p>
-
-<h4>Hello World 2</h4>
-<p>
-This example builds on HelloWorld1 and demonstrates how to display a Label inside the Shell.
-</p>
-
-<h4>Hello World 3</h4>
-<p>
-This example builds on HelloWorld2 and demonstrates how to resize the Label
-when the Shell resizes using a Listener mechanism.
-</p>
-
-<h4>Hello World 4</h4>
-<p>
-This example builds on HelloWorld2 and demonstrates how to resize the Label
-when the Shell resizes using a Layout.
-</p>
-
-<h4>Hello World 5</h4>
-<p>
-This example builds on HelloWorld1 and demonstrates how to draw directly
-on an SWT Control using a graphic context.
-</p>
-
-<h3>Running the example</h3>
-
-<p>
-Follow the <a href="swt_manual_setup.html">Manual Setup</a>
-instructions to install and run the example from your workspace.
-</p>
-<p>
-The "Main" class is <code>org.eclipse.swt.examples.helloworld.HelloWorld[1-5]</code>.
-</p>
-<p>
-This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
-Select the Hello World item from the Standalone category and click Run.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Hello World Examples</title>
+</head>
+<body>
+
+<h2>SWT Standalone Example - Hello World</h2>
+
+<p>
+The Hello World examples are a set of introductory examples to show how to get started
+creating an application with SWT. They cover creating a shell, using event listeners,
+processing events in an event loop, using layouts, and drawing with a Graphic Context.
+</p>
+
+<h4>Hello World 1</h4>
+<p>
+This example demonstrates how to open a Shell and process the events.
+</p>
+
+<h4>Hello World 2</h4>
+<p>
+This example builds on HelloWorld1 and demonstrates how to display a Label inside the Shell.
+</p>
+
+<h4>Hello World 3</h4>
+<p>
+This example builds on HelloWorld2 and demonstrates how to resize the Label
+when the Shell resizes using a Listener mechanism.
+</p>
+
+<h4>Hello World 4</h4>
+<p>
+This example builds on HelloWorld2 and demonstrates how to resize the Label
+when the Shell resizes using a Layout.
+</p>
+
+<h4>Hello World 5</h4>
+<p>
+This example builds on HelloWorld1 and demonstrates how to draw directly
+on an SWT Control using a graphic context.
+</p>
+
+<h3>Running the example</h3>
+
+<p>
+Follow the <a href="swt_manual_setup.html">Manual Setup</a>
+instructions to install and run the example from your workspace.
+</p>
+<p>
+The "Main" class is <code>org.eclipse.swt.examples.helloworld.HelloWorld[1-5]</code>.
+</p>
+<p>
+This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
+Select the Hello World item from the Standalone category and click Run.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/doc-html/swt_hoverhelp_ex.html b/examples/org.eclipse.swt.examples/doc-html/swt_hoverhelp_ex.html
index 29712faba7..3f171b7219 100755
--- a/examples/org.eclipse.swt.examples/doc-html/swt_hoverhelp_ex.html
+++ b/examples/org.eclipse.swt.examples/doc-html/swt_hoverhelp_ex.html
@@ -1,37 +1,37 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Hover Help Example</title>
-</head>
-<body>
-
-<h2>SWT Standalone Example - Hover Help</h2>
-
-<p>
-The Hover Help example shows how to implement custom tooltips and hover help support
-on a number of different SWT controls including Buttons, TableItems, ToolItems and TreeItems.
-The example implements its own tooltip and hover help support.
-To see the custom tooltips in action, hover over an item or button in the UI.
-Notice that images appear in the left-hand corner of the tooltip.
-To see the custom hover help in action, hover over an item or button in the UI until
-the tooltip is displayed. Without moving the mouse, hit F1. A new Shell will pop up with the
-extended hover help information for the UI element in question.
-</p>
-
-<h3>Running the example</h3>
-<p>
-Follow the <a href="swt_manual_setup.html">Manual Setup</a>
-instructions to install and run the example from your workspace.
-</p>
-<p>
-The "Main" class is <code>org.eclipse.swt.examples.hoverhelp.HoverHelp</code>.
-</p>
-<p>
-This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
-Select the Hover Help item from the Standalone category and click Run.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Hover Help Example</title>
+</head>
+<body>
+
+<h2>SWT Standalone Example - Hover Help</h2>
+
+<p>
+The Hover Help example shows how to implement custom tooltips and hover help support
+on a number of different SWT controls including Buttons, TableItems, ToolItems and TreeItems.
+The example implements its own tooltip and hover help support.
+To see the custom tooltips in action, hover over an item or button in the UI.
+Notice that images appear in the left-hand corner of the tooltip.
+To see the custom hover help in action, hover over an item or button in the UI until
+the tooltip is displayed. Without moving the mouse, hit F1. A new Shell will pop up with the
+extended hover help information for the UI element in question.
+</p>
+
+<h3>Running the example</h3>
+<p>
+Follow the <a href="swt_manual_setup.html">Manual Setup</a>
+instructions to install and run the example from your workspace.
+</p>
+<p>
+The "Main" class is <code>org.eclipse.swt.examples.hoverhelp.HoverHelp</code>.
+</p>
+<p>
+This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
+Select the Hover Help item from the Standalone category and click Run.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/doc-html/swt_imageanalyzer_ex.html b/examples/org.eclipse.swt.examples/doc-html/swt_imageanalyzer_ex.html
index 5a25923051..b83e9a3358 100755
--- a/examples/org.eclipse.swt.examples/doc-html/swt_imageanalyzer_ex.html
+++ b/examples/org.eclipse.swt.examples/doc-html/swt_imageanalyzer_ex.html
@@ -1,57 +1,57 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Image Analyzer Example</title>
-</head>
-<body>
-
-<h2>SWT Standalone Example - Image Analyzer</h2>
-
-<p>
-The ImageAnalyzer opens image files and displays the visual contents of the file along with a
-summary of the data in the image file.
-The user can make adjustments to various elements of the image such as scaling and Alpha
-blending and can save these changes to a file.
-</p>
-<p>
-The ImageAnalyzer will load and display image files of type GIF, JPEG, BMP, ICO, and PNG.
-To open a file, use the File --> Open... menu item, and select the image file in the FileDialog.
-If the file is an interlaced GIF or PNG or a progressive JPEG, and Incremental Display is selected,
-then the ImageAnalyzer displays the image increments as they are being loaded.
-If the file contains an animated GIF, then the Next, Previous, and Animate buttons become enabled,
-and they can be used to cycle through the images in the file, or animate them. If a GIF defines a background color,
-as many animated GIFs do, selecting Background will use the GIF's background color.
-If the image has transparency (possible with GIF, PNG, or ICO), then selecting Display Mask will draw the image's transparency
-mask to the right of the image. You can change the background color of the ImageAnalyzer to see the transparency work.
-To turn off the transparency, deselect Display Transparency.
-After an image is loaded, it can be scaled or have alpha transparency applied, using the Scale and Alpha-K combos,
-and the Alpha menu. File --> Reopen restores scaling and Alpha to their default values and reloads the current image file.
-File --> Save As... can be used to save the currently loaded image to another type of image file. If the image has transparency,
-File --> Save Mask As... saves the image's transparency mask.
-</p>
-<p>
-When SWT loads an image file, an instance of org.eclipse.swt.graphics.ImageData is created. (In the case of an ICO file or
-multi-image GIF, an array of ImageData instances is created). The ImageAnalyzer displays all of the data stored in the ImageData
-instance(s) for the currently loaded image file, including the pixel data. Hovering over a pixel in the image display will show the RGB
-color data for that pixel. For certain images (particularly animated GIFs) additional data is stored in the org.eclipse.swt.graphics.ImageLoader
-instance used to load the image. The ImageAnalyzer displays this data as well.
-</p>
-
-<h3>Running the example</h3>
-
-<p>
-Follow the <a href="swt_manual_setup.html">Manual Setup</a>
-instructions to install and run the example from your workspace.
-</p>
-<p>
-The "Main" class is <code>org.eclipse.swt.examples.imageanalyzer.ImageAnalyzer</code>.
-</p>
-<p>
-This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
-Select the Image Analyzer item from the Standalone category and click Run.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Image Analyzer Example</title>
+</head>
+<body>
+
+<h2>SWT Standalone Example - Image Analyzer</h2>
+
+<p>
+The ImageAnalyzer opens image files and displays the visual contents of the file along with a
+summary of the data in the image file.
+The user can make adjustments to various elements of the image such as scaling and Alpha
+blending and can save these changes to a file.
+</p>
+<p>
+The ImageAnalyzer will load and display image files of type GIF, JPEG, BMP, ICO, and PNG.
+To open a file, use the File --> Open... menu item, and select the image file in the FileDialog.
+If the file is an interlaced GIF or PNG or a progressive JPEG, and Incremental Display is selected,
+then the ImageAnalyzer displays the image increments as they are being loaded.
+If the file contains an animated GIF, then the Next, Previous, and Animate buttons become enabled,
+and they can be used to cycle through the images in the file, or animate them. If a GIF defines a background color,
+as many animated GIFs do, selecting Background will use the GIF's background color.
+If the image has transparency (possible with GIF, PNG, or ICO), then selecting Display Mask will draw the image's transparency
+mask to the right of the image. You can change the background color of the ImageAnalyzer to see the transparency work.
+To turn off the transparency, deselect Display Transparency.
+After an image is loaded, it can be scaled or have alpha transparency applied, using the Scale and Alpha-K combos,
+and the Alpha menu. File --> Reopen restores scaling and Alpha to their default values and reloads the current image file.
+File --> Save As... can be used to save the currently loaded image to another type of image file. If the image has transparency,
+File --> Save Mask As... saves the image's transparency mask.
+</p>
+<p>
+When SWT loads an image file, an instance of org.eclipse.swt.graphics.ImageData is created. (In the case of an ICO file or
+multi-image GIF, an array of ImageData instances is created). The ImageAnalyzer displays all of the data stored in the ImageData
+instance(s) for the currently loaded image file, including the pixel data. Hovering over a pixel in the image display will show the RGB
+color data for that pixel. For certain images (particularly animated GIFs) additional data is stored in the org.eclipse.swt.graphics.ImageLoader
+instance used to load the image. The ImageAnalyzer displays this data as well.
+</p>
+
+<h3>Running the example</h3>
+
+<p>
+Follow the <a href="swt_manual_setup.html">Manual Setup</a>
+instructions to install and run the example from your workspace.
+</p>
+<p>
+The "Main" class is <code>org.eclipse.swt.examples.imageanalyzer.ImageAnalyzer</code>.
+</p>
+<p>
+This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
+Select the Image Analyzer item from the Standalone category and click Run.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/doc-html/swt_javaviewer_ex.html b/examples/org.eclipse.swt.examples/doc-html/swt_javaviewer_ex.html
index be071be4b3..cac2acda1b 100755
--- a/examples/org.eclipse.swt.examples/doc-html/swt_javaviewer_ex.html
+++ b/examples/org.eclipse.swt.examples/doc-html/swt_javaviewer_ex.html
@@ -1,33 +1,33 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Java Syntax Viewer Example</title>
-</head>
-<body>
-
-<h2>SWT Standalone Example - Java Syntax Viewer</h2>
-
-<p>
-This example demonstrates how to implement a user-defined line styler for the StyledText widget.
-The example provides a typical editor interface.
-To see the effect of the line styler, open a *.java file.
-When the contents of the file are displayed in the editor area, notice that the keywords have been highlighted.
-</p>
-
-<h3>Running the example</h3>
-<p>
-Follow the <a href="swt_manual_setup.html">Manual Setup</a>
-instructions to install and run the example from your workspace.
-</p>
-<p>
-The "Main" class is <code>org.eclipse.swt.examples.javaviewer.JavaViewer</code>.
-</p>
-<p>
-This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
-Select the Java Syntax Viewer item from the Standalone category and click Run.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Java Syntax Viewer Example</title>
+</head>
+<body>
+
+<h2>SWT Standalone Example - Java Syntax Viewer</h2>
+
+<p>
+This example demonstrates how to implement a user-defined line styler for the StyledText widget.
+The example provides a typical editor interface.
+To see the effect of the line styler, open a *.java file.
+When the contents of the file are displayed in the editor area, notice that the keywords have been highlighted.
+</p>
+
+<h3>Running the example</h3>
+<p>
+Follow the <a href="swt_manual_setup.html">Manual Setup</a>
+instructions to install and run the example from your workspace.
+</p>
+<p>
+The "Main" class is <code>org.eclipse.swt.examples.javaviewer.JavaViewer</code>.
+</p>
+<p>
+This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
+Select the Java Syntax Viewer item from the Standalone category and click Run.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/doc-html/swt_manual_setup.html b/examples/org.eclipse.swt.examples/doc-html/swt_manual_setup.html
index 9f36ca2756..2681c4d14a 100755
--- a/examples/org.eclipse.swt.examples/doc-html/swt_manual_setup.html
+++ b/examples/org.eclipse.swt.examples/doc-html/swt_manual_setup.html
@@ -1,119 +1,119 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT Standalone Examples Setup</title>
-</head>
-<body>
-
-<h2>SWT Standalone Examples Setup</h2>
-
-<h3>Importing Example Source</h3>
-
-<p>
-*** In the following description, substitute the location in which you installed Eclipse for INSTALLDIR ***
-</p>
-
-<p>Import the example code and all its required resources into your workspace:</p>
-
-<ol>
-<li>Create a Java Project called "SWT Examples".
-<li>Select the project "SWT Examples" in the Packages view.
-<li>Select the File --> Import menu. Select Zip File. Click on Next.
-<li>Locate the source zip file for the SWT examples. For example:
- <ul>
- <li><b>win32: </b><code>INSTALLDIR\eclipse\plugins\org.eclipse.swt.examples_2.0.0\swtexamplessrc.zip</code>
- <li><b>*nix: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.examples_2.0.0/swtexamplessrc.zip</code>
- </ul>
-<li>Click on Finish.
-<li>Select the File --> Import menu. In the Import dialog, select Zip File. Click on Next.
-<li>Locate the jar file for the SWT examples. For example:
- <ul>
- <li><b>win32: </b><code>INSTALLDIR\eclipse\plugins\org.eclipse.swt.examples_2.0.0\swtexamples.jar</code>
- <li><b>*nix: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.examples_2.0.0/swtexamples.jar</code>
- </ul>
-<li>Expand the top level directory of the zip file (/). <b>Uncheck "org" and "META-INF"</b>.
-<li>Click on Finish.
-</ol>
-
-<p>Now you need to compile the SWT examples. In order to do this, you must add the SWT jar(s) to
-the compile path:</p>
-<ol>
-<li>Select the project "SWT Examples" in the Packages view and from the pop up menu select Properties.
-<li>Select the Java Build Path item.
-<li>Go to the Libraries tab.
-<li>Click on the Add External JARS... button.
-<li>Locate the swt jar for the platform on which you wish to run:<br>
- <ul>
- <li><b>win32: </b><code>INSTALLDIR\eclipse\plugins\org.eclipse.swt.win32_2.0.0\ws\win32\swt.jar</code>
- <li><b>gtk: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.gtk_2.0.0/ws/gtk/swt.jar</code>
- <li><b>motif: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/ws/motif/swt.jar</code>
- <li><b>photon: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.photon_2.0.0/ws/photon/swt.jar</code>
- <li><b>macosx: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.carbon_2.0.0/ws/carbon/swt.jar</code>
- </ul>
-<li>Click on OK.
-</ol>
-<p><b>NOTE:</b> For some platforms (such as GTK), more than one jar is required to run SWT (on
-GTK there is a swt.jar and a swt-pi.jar file). In this case, all the required jars must
-be added to the class path. This is done by repeating the steps above for each jar file.
-All jar files are located in the same directory/folder.</p>
-
-<p>At this point your SWT examples should be compiled without any errors. Check the Task
-view for errors. If you get an error like "<code>java.lang.Object</code> not found" it means
-you have not configured a JRE. Go to the Window --> Preferences dialog.
-Select Java --> Installed JREs and ensure that a JRE is installed
-and that the path to the JRE is correct.</p>
-
-<h3><a NAME="Run"></a>Running the Example</h3>
-
-<p>Now you have to configure Eclipse to run the example. This requires putting the SWT
-JNI libraries on the library path so that the VM can find them:
-
-<ol>
-<li>Open the Java Perspective.
-<li>In the Packages view, select the Main class that you want to run.
- For example, the Main class for the Address Book example is
- &nbsp;&nbsp;&nbsp;&nbsp;<code>org.eclipse.swt.examples.addressbook.AddressBook</code>.
-<li>SelectRun --> Run... from the main menu.
-<li>In the Launch Configurations dialog that appears, select Java Application and click
- on the New button.
-<li>Fill in the Name, Project and Main class fields according to the example you wish to run.
-<li>Select the Arguments tab. In the VM Arguements area specify the location of the SWT
- library depending on your target platform as follows:
- <ul>
- <li><b>win32: </b><code>-Djava.library.path=INSTALLDIR\plugins\org.eclipse.swt.win32_2.0.0\os\win32\x86</code>
- <li><b>linux gtk: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.gtk_2.0.0/os/linux/x86</code>
- <li><b>linux motif: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/os/linux/x86</code>
- <li><b>solaris motif: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/os/solaris/sparc</code>
- <li><b>aix motif: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/os/aix/ppc</code>
- <li><b>hpux motif: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/os/hpux/PA_RISC</code>
- <li><b>photon qnx: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.photon_2.0.0/os/qnx/x86</code>
- <li><b>macosx: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.carbon_2.0.0/os/macosx/ppc</code>
- </ul>
-<li>Click on the Run button.
-</ol>
-
-
-<h3>Examples Overview</h3>
-<p>
-Consult the documentation of each individual example for the names of
-its Main class and additional details.
-</p>
-<p>
-The following examples are included in the <code>swtexamples.jar</code>:
-</p>
-<ul>
-<li><a href="swt_addressbook_ex.html">Address Book</a>
-<li><a href="swt_controls_ex.html">Controls</a>
-<li><a href="swt_fileviewer_ex.html">File Viewer</a>
-<li><a href="swt_helloworld_ex.html">Hello World [1-5]</a>
-<li><a href="swt_hoverhelp_ex.html">Hover Help</a>
-<li><a href="swt_imageanalyzer_ex.html">Image Analyzer</a>
-<li><a href="swt_javaviewer_ex.html">Java Viewer</a>
-<li><a href="swt_layout_ex.html">Layout</a>
-<li><a href="swt_texteditor_ex.html">Text Editor</a>
-</ul>
-
-<p><br><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT Standalone Examples Setup</title>
+</head>
+<body>
+
+<h2>SWT Standalone Examples Setup</h2>
+
+<h3>Importing Example Source</h3>
+
+<p>
+*** In the following description, substitute the location in which you installed Eclipse for INSTALLDIR ***
+</p>
+
+<p>Import the example code and all its required resources into your workspace:</p>
+
+<ol>
+<li>Create a Java Project called "SWT Examples".
+<li>Select the project "SWT Examples" in the Packages view.
+<li>Select the File --> Import menu. Select Zip File. Click on Next.
+<li>Locate the source zip file for the SWT examples. For example:
+ <ul>
+ <li><b>win32: </b><code>INSTALLDIR\eclipse\plugins\org.eclipse.swt.examples_2.0.0\swtexamplessrc.zip</code>
+ <li><b>*nix: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.examples_2.0.0/swtexamplessrc.zip</code>
+ </ul>
+<li>Click on Finish.
+<li>Select the File --> Import menu. In the Import dialog, select Zip File. Click on Next.
+<li>Locate the jar file for the SWT examples. For example:
+ <ul>
+ <li><b>win32: </b><code>INSTALLDIR\eclipse\plugins\org.eclipse.swt.examples_2.0.0\swtexamples.jar</code>
+ <li><b>*nix: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.examples_2.0.0/swtexamples.jar</code>
+ </ul>
+<li>Expand the top level directory of the zip file (/). <b>Uncheck "org" and "META-INF"</b>.
+<li>Click on Finish.
+</ol>
+
+<p>Now you need to compile the SWT examples. In order to do this, you must add the SWT jar(s) to
+the compile path:</p>
+<ol>
+<li>Select the project "SWT Examples" in the Packages view and from the pop up menu select Properties.
+<li>Select the Java Build Path item.
+<li>Go to the Libraries tab.
+<li>Click on the Add External JARS... button.
+<li>Locate the swt jar for the platform on which you wish to run:<br>
+ <ul>
+ <li><b>win32: </b><code>INSTALLDIR\eclipse\plugins\org.eclipse.swt.win32_2.0.0\ws\win32\swt.jar</code>
+ <li><b>gtk: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.gtk_2.0.0/ws/gtk/swt.jar</code>
+ <li><b>motif: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/ws/motif/swt.jar</code>
+ <li><b>photon: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.photon_2.0.0/ws/photon/swt.jar</code>
+ <li><b>macosx: </b><code>INSTALLDIR/eclipse/plugins/org.eclipse.swt.carbon_2.0.0/ws/carbon/swt.jar</code>
+ </ul>
+<li>Click on OK.
+</ol>
+<p><b>NOTE:</b> For some platforms (such as GTK), more than one jar is required to run SWT (on
+GTK there is a swt.jar and a swt-pi.jar file). In this case, all the required jars must
+be added to the class path. This is done by repeating the steps above for each jar file.
+All jar files are located in the same directory/folder.</p>
+
+<p>At this point your SWT examples should be compiled without any errors. Check the Task
+view for errors. If you get an error like "<code>java.lang.Object</code> not found" it means
+you have not configured a JRE. Go to the Window --> Preferences dialog.
+Select Java --> Installed JREs and ensure that a JRE is installed
+and that the path to the JRE is correct.</p>
+
+<h3><a NAME="Run"></a>Running the Example</h3>
+
+<p>Now you have to configure Eclipse to run the example. This requires putting the SWT
+JNI libraries on the library path so that the VM can find them:
+
+<ol>
+<li>Open the Java Perspective.
+<li>In the Packages view, select the Main class that you want to run.
+ For example, the Main class for the Address Book example is
+ &nbsp;&nbsp;&nbsp;&nbsp;<code>org.eclipse.swt.examples.addressbook.AddressBook</code>.
+<li>SelectRun --> Run... from the main menu.
+<li>In the Launch Configurations dialog that appears, select Java Application and click
+ on the New button.
+<li>Fill in the Name, Project and Main class fields according to the example you wish to run.
+<li>Select the Arguments tab. In the VM Arguements area specify the location of the SWT
+ library depending on your target platform as follows:
+ <ul>
+ <li><b>win32: </b><code>-Djava.library.path=INSTALLDIR\plugins\org.eclipse.swt.win32_2.0.0\os\win32\x86</code>
+ <li><b>linux gtk: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.gtk_2.0.0/os/linux/x86</code>
+ <li><b>linux motif: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/os/linux/x86</code>
+ <li><b>solaris motif: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/os/solaris/sparc</code>
+ <li><b>aix motif: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/os/aix/ppc</code>
+ <li><b>hpux motif: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.motif_2.0.0/os/hpux/PA_RISC</code>
+ <li><b>photon qnx: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.photon_2.0.0/os/qnx/x86</code>
+ <li><b>macosx: </b><code>-Djava.library.path=INSTALLDIR/eclipse/plugins/org.eclipse.swt.carbon_2.0.0/os/macosx/ppc</code>
+ </ul>
+<li>Click on the Run button.
+</ol>
+
+
+<h3>Examples Overview</h3>
+<p>
+Consult the documentation of each individual example for the names of
+its Main class and additional details.
+</p>
+<p>
+The following examples are included in the <code>swtexamples.jar</code>:
+</p>
+<ul>
+<li><a href="swt_addressbook_ex.html">Address Book</a>
+<li><a href="swt_controls_ex.html">Controls</a>
+<li><a href="swt_fileviewer_ex.html">File Viewer</a>
+<li><a href="swt_helloworld_ex.html">Hello World [1-5]</a>
+<li><a href="swt_hoverhelp_ex.html">Hover Help</a>
+<li><a href="swt_imageanalyzer_ex.html">Image Analyzer</a>
+<li><a href="swt_javaviewer_ex.html">Java Viewer</a>
+<li><a href="swt_layout_ex.html">Layout</a>
+<li><a href="swt_texteditor_ex.html">Text Editor</a>
+</ul>
+
+<p><br><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/doc-html/swt_texteditor_ex.html b/examples/org.eclipse.swt.examples/doc-html/swt_texteditor_ex.html
index 3d5571b25f..563887b98b 100755
--- a/examples/org.eclipse.swt.examples/doc-html/swt_texteditor_ex.html
+++ b/examples/org.eclipse.swt.examples/doc-html/swt_texteditor_ex.html
@@ -1,35 +1,35 @@
-<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>SWT - Text Editor Example</title>
-</head>
-<body>
-
-<h2>SWT Standalone Example - Text Editor</h2>
-
-<p>
-This example demonstrates how to use the StyledText widget to implement
-a text editor with formatting support.
-The example has a typical text editor interface.
-The Edit menu contains Cut, Copy, Paste and Set Font items and the toolbar
-provides a bold text toggle, three colour tools that operate on the current
-selection, and a reset to defaults button that also operates on the current selection.
-</p>
-
-<h3>Running the example</h3>
-<p>
-Follow the <a href="swt_manual_setup.html">Manual Setup</a>
-instructions to install and run the example from your workspace.
-</p>
-<p>
-The "Main" class is <code>org.eclipse.swt.examples.texteditor.TextEditor</code>.
-</p>
-<p>
-This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
-Select the Text Editor item from the Standalone category and click Run.
-</p>
-
-<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
-</body>
-</html>
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>SWT - Text Editor Example</title>
+</head>
+<body>
+
+<h2>SWT Standalone Example - Text Editor</h2>
+
+<p>
+This example demonstrates how to use the StyledText widget to implement
+a text editor with formatting support.
+The example has a typical text editor interface.
+The Edit menu contains Cut, Copy, Paste and Set Font items and the toolbar
+provides a bold text toggle, three colour tools that operate on the current
+selection, and a reset to defaults button that also operates on the current selection.
+</p>
+
+<h3>Running the example</h3>
+<p>
+Follow the <a href="swt_manual_setup.html">Manual Setup</a>
+instructions to install and run the example from your workspace.
+</p>
+<p>
+The "Main" class is <code>org.eclipse.swt.examples.texteditor.TextEditor</code>.
+</p>
+<p>
+This example can also be run using the <a href="swt_launcher_ex.html">Example Launcher</a>.
+Select the Text Editor item from the Standalone category and click Run.
+</p>
+
+<p><a href="hglegal2002.htm"><img SRC="ngibmcpy2002.gif" ALT="Copyright IBM Corporation and others 2000, 2002. All Rights Reserved." BORDER=0 height=14 width=324></a></p>
+</body>
+</html>
diff --git a/examples/org.eclipse.swt.examples/plugin.properties b/examples/org.eclipse.swt.examples/plugin.properties
index 6382611aed..0474358711 100755
--- a/examples/org.eclipse.swt.examples/plugin.properties
+++ b/examples/org.eclipse.swt.examples/plugin.properties
@@ -1,113 +1,113 @@
-providerName = Eclipse.org
-plugin.SWTStandaloneExampleSet.name = SWT Standalone Examples Plugin
-
-launchcategory.SWTStandaloneExamples.name = Standalone
-launchcategory.SWTStandaloneExamples.description = \
- A collection of Standard Widget Toolkit examples that run independant \
- of the Eclipse Platform.
-
-launchitem.AddressBook.name = Address Book
-launchitem.AddressBook.description = \
- The AddressBook example shows how the Table control can be used to \
- present information in a tabular format.\n\n\
- The application can save and load data from a file, sort the entries, and \
- search for strings within the fields.
-
-launchitem.ControlExample.name = SWT Controls Example
-launchitem.ControlExample.description = \
- The Controls example is a simple demonstration of common SWT controls. \n\n\
- It consists of a tab folder where each tab in the folder allows the user \
- to interact with a different control. \
- The user can change styles and settings and view how this affects the control.
-
-launchitem.FileViewer.name = File Viewer
-launchitem.FileViewer.description = \
- The File Viewer example shows how a simple application can be implemented using SWT.\n\n\
- This application provides the ability to navigate files and folders and manipulate them via Drag and Drop. \
- It includes the use of alternate threads for long actions and demonstrates the use of the Tree, \
- Table, Toolbar and Program.
-
-launchitem.HoverHelp.name = Hover Help
-launchitem.HoverHelp.description = \
- The Hover Help example shows how to implement custom tooltips and hover help support \
- on a number of different SWT controls including Buttons, TableItems, ToolItems and TreeItems.\n\n\
- The example implements its own tooltip and hover help support. \
- To see the custom tooltips in action, hover over an item or button in the UI. \
- An image appears in the left-hand corner of the tooltip.\n\n\
- To see the custom hover help in action, hover over an item or button in the UI until \
- the tooltip is displayed. Without moving the mouse, hit F1. A new Shell will pop up with the \
- extended hover help information for the UI element in question
-
-launchitem.HelloWorld1.name = Hello World (1)
-launchitem.HelloWorld1.description = \
- This example demonstrates how to open a Shell and process the events.
-
-launchitem.HelloWorld2.name = Hello World (2)
-launchitem.HelloWorld2.description = \
- This example builds on HelloWorld1 and demonstrates how to display a Label inside the Shell.
-
-launchitem.HelloWorld3.name = Hello World (3)
-launchitem.HelloWorld3.description = \
- This example builds on HelloWorld2 and demonstrates how to resize the Label \
- when the Shell resizes using a Listener mechanism.
-
-launchitem.HelloWorld4.name = Hello World (4)
-launchitem.HelloWorld4.description = \
- This example builds on HelloWorld2 and demonstrates how to resize the Label \
- when the Shell resizes using a Layout.
-
-launchitem.HelloWorld5.name = Hello World (5)
-launchitem.HelloWorld5.description = \
- This example builds on HelloWorld1 and demonstrates how to draw directly on an SWT Control using a graphic context.
-
-launchitem.ImageAnalyzer.name = Image Analyzer
-launchitem.ImageAnalyzer.description = \
- The ImageAnalyzer opens image files and displays the visual contents of the file along with a \
- summary of the data in the image file.\n\n\
- The user can make adjustments to various elements of the image such as scaling and Alpha \
- blending and can save these changes to a file.\n\n\
- The ImageAnalyzer will load and display image files of type GIF, JPEG, BMP, ICO, and PNG. \
- To open a file, use the File->Open... menu item, and select the image file in the FileDialog.\n\n\
- If the file is an interlaced GIF or PNG or a progressive JPEG, and Incremental Display is selected, \
- then the ImageAnalyzer displays the image increments as they are being loaded.\n\n\
- If the file contains an animated GIF, then the Next, Previous, and Animate buttons become enabled, \
- and they can be used to cycle through the images in the file, or animate them. If a GIF defines a background color, \
- as many animated GIFs do, selecting Background will use the GIF's background color.\n\n\
- If the image has transparency (possible with GIF, PNG, or ICO), then selecting Display Mask will draw the image's transparency \
- mask to the right of the image. You can change the background color of the ImageAnalyzer to see the transparency work. \
- To turn off the transparency, deselect Display Transparency.\n\n\
- After an image is loaded, it can be scaled or have alpha transparency applied, using the Scale and Alpha-K combos, \
- and the Alpha menu. File->Reopen restores scaling and Alpha to their default values and reloads the current image file.\n\n\
- File->Save As... can be used to save the currently loaded image to another type of image file. If the image has transparency, \
- File->Save Mask As... saves the image's transparency mask.\n\n\
- When SWT loads an image file, an instance of org.eclipse.swt.graphics.ImageData is created. (In the case of an ICO file or \
- multi-image GIF, an array of ImageData instances is created). The ImageAnalyzer displays all of the data stored in the ImageData \
- instance(s) for the currently loaded image file, including the pixel data. Hovering over a pixel in the image display will show the RGB \
- color data for that pixel. For certain images (particularly animated GIFs) additional data is stored in the org.eclipse.swt.graphics.ImageLoader \
- instance used to load the image. The ImageAnalyzer displays this data as well.
-
-launchitem.JavaViewer.name = Java Syntax Viewer
-launchitem.JavaViewer.description = \
- This example demonstrates how to implement a user-defined line styler for the StyledText widget.\n\n\
- The example provides a typical editor interface. \
- To see the effect of the line styler, open a *.java file. \
- When the contents of the file are displayed in the editor area, notice that the keywords have been highlighted.
-
-launchitem.LayoutExample.name = Layout Example
-launchitem.LayoutExample.description = \
- This example is a simple demonstration of common SWT layouts. \n\n\
- It consists of a tab folder where each tab in the folder allows the \
- user to interact with a different SWT layout. \
- The user can insert widgets into a layout and set the values of the layout data \
- using a property sheet. When the user has a suitable arrangement, code can be \
- generated by clicking on the Code button.
-
-launchitem.TextEditor.name = Text Editor
-launchitem.TextEditor.description = \
- This example demonstrates how to use the StyledText widget to implement \
- a text editor with formatting support.\n\n\
- The example has a typical text editor interface. \
- The Edit menu contains Cut, Copy, Paste and Set Font items and the toolbar \
- provides a bold text toggle, three colour tools that operate on the current \
- selection, and a reset to defaults button that also operates on the current selection.
+providerName = Eclipse.org
+plugin.SWTStandaloneExampleSet.name = SWT Standalone Examples Plugin
+
+launchcategory.SWTStandaloneExamples.name = Standalone
+launchcategory.SWTStandaloneExamples.description = \
+ A collection of Standard Widget Toolkit examples that run independant \
+ of the Eclipse Platform.
+
+launchitem.AddressBook.name = Address Book
+launchitem.AddressBook.description = \
+ The AddressBook example shows how the Table control can be used to \
+ present information in a tabular format.\n\n\
+ The application can save and load data from a file, sort the entries, and \
+ search for strings within the fields.
+
+launchitem.ControlExample.name = SWT Controls Example
+launchitem.ControlExample.description = \
+ The Controls example is a simple demonstration of common SWT controls. \n\n\
+ It consists of a tab folder where each tab in the folder allows the user \
+ to interact with a different control. \
+ The user can change styles and settings and view how this affects the control.
+
+launchitem.FileViewer.name = File Viewer
+launchitem.FileViewer.description = \
+ The File Viewer example shows how a simple application can be implemented using SWT.\n\n\
+ This application provides the ability to navigate files and folders and manipulate them via Drag and Drop. \
+ It includes the use of alternate threads for long actions and demonstrates the use of the Tree, \
+ Table, Toolbar and Program.
+
+launchitem.HoverHelp.name = Hover Help
+launchitem.HoverHelp.description = \
+ The Hover Help example shows how to implement custom tooltips and hover help support \
+ on a number of different SWT controls including Buttons, TableItems, ToolItems and TreeItems.\n\n\
+ The example implements its own tooltip and hover help support. \
+ To see the custom tooltips in action, hover over an item or button in the UI. \
+ An image appears in the left-hand corner of the tooltip.\n\n\
+ To see the custom hover help in action, hover over an item or button in the UI until \
+ the tooltip is displayed. Without moving the mouse, hit F1. A new Shell will pop up with the \
+ extended hover help information for the UI element in question
+
+launchitem.HelloWorld1.name = Hello World (1)
+launchitem.HelloWorld1.description = \
+ This example demonstrates how to open a Shell and process the events.
+
+launchitem.HelloWorld2.name = Hello World (2)
+launchitem.HelloWorld2.description = \
+ This example builds on HelloWorld1 and demonstrates how to display a Label inside the Shell.
+
+launchitem.HelloWorld3.name = Hello World (3)
+launchitem.HelloWorld3.description = \
+ This example builds on HelloWorld2 and demonstrates how to resize the Label \
+ when the Shell resizes using a Listener mechanism.
+
+launchitem.HelloWorld4.name = Hello World (4)
+launchitem.HelloWorld4.description = \
+ This example builds on HelloWorld2 and demonstrates how to resize the Label \
+ when the Shell resizes using a Layout.
+
+launchitem.HelloWorld5.name = Hello World (5)
+launchitem.HelloWorld5.description = \
+ This example builds on HelloWorld1 and demonstrates how to draw directly on an SWT Control using a graphic context.
+
+launchitem.ImageAnalyzer.name = Image Analyzer
+launchitem.ImageAnalyzer.description = \
+ The ImageAnalyzer opens image files and displays the visual contents of the file along with a \
+ summary of the data in the image file.\n\n\
+ The user can make adjustments to various elements of the image such as scaling and Alpha \
+ blending and can save these changes to a file.\n\n\
+ The ImageAnalyzer will load and display image files of type GIF, JPEG, BMP, ICO, and PNG. \
+ To open a file, use the File->Open... menu item, and select the image file in the FileDialog.\n\n\
+ If the file is an interlaced GIF or PNG or a progressive JPEG, and Incremental Display is selected, \
+ then the ImageAnalyzer displays the image increments as they are being loaded.\n\n\
+ If the file contains an animated GIF, then the Next, Previous, and Animate buttons become enabled, \
+ and they can be used to cycle through the images in the file, or animate them. If a GIF defines a background color, \
+ as many animated GIFs do, selecting Background will use the GIF's background color.\n\n\
+ If the image has transparency (possible with GIF, PNG, or ICO), then selecting Display Mask will draw the image's transparency \
+ mask to the right of the image. You can change the background color of the ImageAnalyzer to see the transparency work. \
+ To turn off the transparency, deselect Display Transparency.\n\n\
+ After an image is loaded, it can be scaled or have alpha transparency applied, using the Scale and Alpha-K combos, \
+ and the Alpha menu. File->Reopen restores scaling and Alpha to their default values and reloads the current image file.\n\n\
+ File->Save As... can be used to save the currently loaded image to another type of image file. If the image has transparency, \
+ File->Save Mask As... saves the image's transparency mask.\n\n\
+ When SWT loads an image file, an instance of org.eclipse.swt.graphics.ImageData is created. (In the case of an ICO file or \
+ multi-image GIF, an array of ImageData instances is created). The ImageAnalyzer displays all of the data stored in the ImageData \
+ instance(s) for the currently loaded image file, including the pixel data. Hovering over a pixel in the image display will show the RGB \
+ color data for that pixel. For certain images (particularly animated GIFs) additional data is stored in the org.eclipse.swt.graphics.ImageLoader \
+ instance used to load the image. The ImageAnalyzer displays this data as well.
+
+launchitem.JavaViewer.name = Java Syntax Viewer
+launchitem.JavaViewer.description = \
+ This example demonstrates how to implement a user-defined line styler for the StyledText widget.\n\n\
+ The example provides a typical editor interface. \
+ To see the effect of the line styler, open a *.java file. \
+ When the contents of the file are displayed in the editor area, notice that the keywords have been highlighted.
+
+launchitem.LayoutExample.name = Layout Example
+launchitem.LayoutExample.description = \
+ This example is a simple demonstration of common SWT layouts. \n\n\
+ It consists of a tab folder where each tab in the folder allows the \
+ user to interact with a different SWT layout. \
+ The user can insert widgets into a layout and set the values of the layout data \
+ using a property sheet. When the user has a suitable arrangement, code can be \
+ generated by clicking on the Code button.
+
+launchitem.TextEditor.name = Text Editor
+launchitem.TextEditor.description = \
+ This example demonstrates how to use the StyledText widget to implement \
+ a text editor with formatting support.\n\n\
+ The example has a typical text editor interface. \
+ The Edit menu contains Cut, Copy, Paste and Set Font items and the toolbar \
+ provides a bold text toggle, three colour tools that operate on the current \
+ selection, and a reset to defaults button that also operates on the current selection.
\ No newline at end of file
diff --git a/examples/org.eclipse.swt.examples/plugin.xml b/examples/org.eclipse.swt.examples/plugin.xml
index 3562e1fc6d..a6520d061b 100755
--- a/examples/org.eclipse.swt.examples/plugin.xml
+++ b/examples/org.eclipse.swt.examples/plugin.xml
@@ -1,142 +1,142 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- File written by PDE 1.0 -->
-<plugin
- id="org.eclipse.swt.examples"
- name="%plugin.SWTStandaloneExampleSet.name"
- version="2.1.0"
- provider-name="%providerName"
- class="">
-<!-- Required plugins -->
-<requires>
- <import plugin="org.eclipse.swt"/>
-</requires>
-
-<!-- Runtime -->
-<runtime>
- <library name="swtexamples.jar">
- <export name="*"/>
- <packages prefixes="org.eclipse.swt.examples"/>
- </library>
-</runtime>
-
-<!-- Extensions -->
-<!-- Extension points -->
-<extension
- point="org.eclipse.swt.examples.launcher.launchItems">
- <category
- name="%launchcategory.SWTStandaloneExamples.name"
- description="%launchcategory.SWTStandaloneExamples.description"
- id="org.eclipse.swt.examples.launchStandaloneCategory">
- </category>
- <item
- name="%launchitem.AddressBook.name"
- description="%launchitem.AddressBook.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.addressbook.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.addressbook.AddressBook">
- </program>
- </item>
- <item
- name="%launchitem.FileViewer.name"
- description="%launchitem.FileViewer.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.fileviewer.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.fileviewer.FileViewer">
- </program>
- </item>
- <item
- name="%launchitem.HoverHelp.name"
- description="%launchitem.HoverHelp.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.hoverhelp.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.hoverhelp.HoverHelp">
- </program>
- </item>
- <item
- name="%launchitem.HelloWorld1.name"
- description="%launchitem.HelloWorld1.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.helloworld1.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.helloworld.HelloWorld1">
- </program>
- </item>
- <item
- name="%launchitem.HelloWorld2.name"
- description="%launchitem.HelloWorld2.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.helloworld2.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.helloworld.HelloWorld2">
- </program>
- </item>
- <item
- name="%launchitem.HelloWorld3.name"
- description="%launchitem.HelloWorld3.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.helloworld3.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.helloworld.HelloWorld3">
- </program>
- </item>
- <item
- name="%launchitem.HelloWorld4.name"
- description="%launchitem.HelloWorld4.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.helloworld4.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.helloworld.HelloWorld4">
- </program>
- </item>
- <item
- name="%launchitem.HelloWorld5.name"
- description="%launchitem.HelloWorld5.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.helloworld5.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.helloworld.HelloWorld5">
- </program>
- </item>
- <item
- name="%launchitem.ImageAnalyzer.name"
- description="%launchitem.ImageAnalyzer.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.imageanalyzer.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.imageanalyzer.ImageAnalyzer">
- </program>
- </item>
- <item
- name="%launchitem.JavaViewer.name"
- description="%launchitem.JavaViewer.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.javaviewer.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.javaviewer.JavaViewer">
- </program>
- </item>
- <item
- name="%launchitem.TextEditor.name"
- description="%launchitem.TextEditor.description"
- category="org.eclipse.swt.examples.launchStandaloneCategory"
- id="org.eclipse.swt.examples.texteditor.standalonelauncher">
- <program
- pluginId="org.eclipse.swt.examples"
- mainClass="org.eclipse.swt.examples.texteditor.TextEditor">
- </program>
- </item>
-</extension>
-</plugin>
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- File written by PDE 1.0 -->
+<plugin
+ id="org.eclipse.swt.examples"
+ name="%plugin.SWTStandaloneExampleSet.name"
+ version="2.1.0"
+ provider-name="%providerName"
+ class="">
+<!-- Required plugins -->
+<requires>
+ <import plugin="org.eclipse.swt"/>
+</requires>
+
+<!-- Runtime -->
+<runtime>
+ <library name="swtexamples.jar">
+ <export name="*"/>
+ <packages prefixes="org.eclipse.swt.examples"/>
+ </library>
+</runtime>
+
+<!-- Extensions -->
+<!-- Extension points -->
+<extension
+ point="org.eclipse.swt.examples.launcher.launchItems">
+ <category
+ name="%launchcategory.SWTStandaloneExamples.name"
+ description="%launchcategory.SWTStandaloneExamples.description"
+ id="org.eclipse.swt.examples.launchStandaloneCategory">
+ </category>
+ <item
+ name="%launchitem.AddressBook.name"
+ description="%launchitem.AddressBook.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.addressbook.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.addressbook.AddressBook">
+ </program>
+ </item>
+ <item
+ name="%launchitem.FileViewer.name"
+ description="%launchitem.FileViewer.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.fileviewer.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.fileviewer.FileViewer">
+ </program>
+ </item>
+ <item
+ name="%launchitem.HoverHelp.name"
+ description="%launchitem.HoverHelp.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.hoverhelp.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.hoverhelp.HoverHelp">
+ </program>
+ </item>
+ <item
+ name="%launchitem.HelloWorld1.name"
+ description="%launchitem.HelloWorld1.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.helloworld1.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.helloworld.HelloWorld1">
+ </program>
+ </item>
+ <item
+ name="%launchitem.HelloWorld2.name"
+ description="%launchitem.HelloWorld2.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.helloworld2.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.helloworld.HelloWorld2">
+ </program>
+ </item>
+ <item
+ name="%launchitem.HelloWorld3.name"
+ description="%launchitem.HelloWorld3.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.helloworld3.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.helloworld.HelloWorld3">
+ </program>
+ </item>
+ <item
+ name="%launchitem.HelloWorld4.name"
+ description="%launchitem.HelloWorld4.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.helloworld4.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.helloworld.HelloWorld4">
+ </program>
+ </item>
+ <item
+ name="%launchitem.HelloWorld5.name"
+ description="%launchitem.HelloWorld5.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.helloworld5.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.helloworld.HelloWorld5">
+ </program>
+ </item>
+ <item
+ name="%launchitem.ImageAnalyzer.name"
+ description="%launchitem.ImageAnalyzer.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.imageanalyzer.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.imageanalyzer.ImageAnalyzer">
+ </program>
+ </item>
+ <item
+ name="%launchitem.JavaViewer.name"
+ description="%launchitem.JavaViewer.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.javaviewer.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.javaviewer.JavaViewer">
+ </program>
+ </item>
+ <item
+ name="%launchitem.TextEditor.name"
+ description="%launchitem.TextEditor.description"
+ category="org.eclipse.swt.examples.launchStandaloneCategory"
+ id="org.eclipse.swt.examples.texteditor.standalonelauncher">
+ <program
+ pluginId="org.eclipse.swt.examples"
+ mainClass="org.eclipse.swt.examples.texteditor.TextEditor">
+ </program>
+ </item>
+</extension>
+</plugin>
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/AddressBook.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/AddressBook.java
index 72be27130d..56517b1df8 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/AddressBook.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/AddressBook.java
@@ -1,857 +1,857 @@
-package org.eclipse.swt.examples.addressbook;
-
-/*
+package org.eclipse.swt.examples.addressbook;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-/* Imports */
-import java.io.*;
-import java.util.*;
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.widgets.*;
-
-/**
- * AddressBookExample is an example that uses <code>org.eclipse.swt</code>
- * libraries to implement a simple address book. This application has
- * save, load, sorting, and searching functions common
- * to basic address books.
- */
-public class AddressBook {
-
- private static ResourceBundle resAddressBook = ResourceBundle.getBundle("examples_addressbook");
- private Shell shell;
-
- private Table table;
- private SearchDialog searchDialog;
-
- private File file;
- private boolean isModified;
-
- private String[] copyBuffer;
-
- private static final String DELIMITER = "\t";
- private static final String[] columnNames = {resAddressBook.getString("Last_name"),
- resAddressBook.getString("First_name"),
- resAddressBook.getString("Business_phone"),
- resAddressBook.getString("Home_phone"),
- resAddressBook.getString("Email"),
- resAddressBook.getString("Fax")};
-
-public static void main(String[] args) {
- Display display = new Display();
- AddressBook application = new AddressBook();
- Shell shell = application.open(display);
- while(!shell.isDisposed()){
- if(!display.readAndDispatch())
- display.sleep();
- }
- display.dispose();
-}
-public Shell open(Display display) {
- shell = new Shell(display);
- shell.setLayout(new FillLayout());
- shell.addShellListener(new ShellAdapter() {
- public void shellClosed(ShellEvent e) {
- e.doit = closeAddressBook();
- }
- });
-
- createMenuBar();
-
- searchDialog = new SearchDialog(shell);
- searchDialog.setSearchAreaNames(columnNames);
- searchDialog.setSearchAreaLabel(resAddressBook.getString("Column"));
- searchDialog.addFindListener(new FindListener () {
- public boolean find() {
- return findEntry();
- }
- });
-
- table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
- table.setHeaderVisible(true);
- table.setMenu(createPopUpMenu());
- table.addSelectionListener(new SelectionAdapter() {
- public void widgetDefaultSelected(SelectionEvent e) {
- TableItem[] items = table.getSelection();
- if (items.length > 0) editEntry(items[0]);
- }
- });
- for(int i = 0; i < columnNames.length; i++) {
- TableColumn column = new TableColumn(table, SWT.NONE);
- column.setText(columnNames[i]);
- column.setWidth(150);
- final int columnIndex = i;
- column.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- sort(columnIndex);
- }
- });
- }
-
- newAddressBook();
-
- shell.setSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
- shell.open();
- return shell;
-}
-
-private boolean closeAddressBook() {
- if(isModified) {
- //ask user if they want to save current address book
- MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO | SWT.CANCEL);
- box.setText(shell.getText());
- box.setMessage(resAddressBook.getString("Close_save"));
-
- int choice = box.open();
- if(choice == SWT.CANCEL) {
- return false;
- } else if(choice == SWT.YES) {
- if (!save()) return false;
- }
- }
-
- TableItem[] items = table.getItems();
- for (int i = 0; i < items.length; i ++) {
- items[i].dispose();
- }
-
- return true;
-}
-/**
- * Creates the menu at the top of the shell where most
- * of the programs functionality is accessed.
- *
- * @return The <code>Menu</code> widget that was created
- */
-private Menu createMenuBar() {
- Menu menuBar = new Menu(shell, SWT.BAR);
- shell.setMenuBar(menuBar);
-
- //create each header and subMenu for the menuBar
- createFileMenu(menuBar);
- createEditMenu(menuBar);
- createSearchMenu(menuBar);
- createHelpMenu(menuBar);
-
- return menuBar;
-}
-
-/**
- * Converts an encoded <code>String</code> to a String array representing a table entry.
- */
-private String[] decodeLine(String line) {
- if(line == null) return null;
-
- String[] parsedLine = new String[table.getColumnCount()];
- for(int i = 0; i < parsedLine.length - 1; i++) {
- int index = line.indexOf(DELIMITER);
- if (index > -1) {
- parsedLine[i] = line.substring(0, index);
- line = line.substring(index + DELIMITER.length(), line.length());
- } else {
- return null;
- }
- }
-
- if (line.indexOf(DELIMITER) != -1) return null;
-
- parsedLine[parsedLine.length - 1] = line;
-
- return parsedLine;
-}
-private void displayError(String msg) {
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
- box.setMessage(msg);
- box.open();
-}
-private void editEntry(TableItem item) {
- DataEntryDialog dialog = new DataEntryDialog(shell);
- dialog.setLabels(columnNames);
- String[] values = new String[table.getColumnCount()];
- for (int i = 0; i < values.length; i++) {
- values[i] = item.getText(i);
- }
- dialog.setValues(values);
- values = dialog.open();
- if (values != null) {
- item.setText(values);
- isModified = true;
- }
-}
-private String encodeLine(String[] tableItems) {
- String line = "";
- for (int i = 0; i < tableItems.length - 1; i++) {
- line += tableItems[i] + DELIMITER;
- }
- line += tableItems[tableItems.length - 1] + "\n";
-
- return line;
-}
-private boolean findEntry() {
- Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
-
- boolean matchCase = searchDialog.getMatchCase();
- boolean matchWord = searchDialog.getMatchWord();
- String searchString = searchDialog.getSearchString();
- int column = searchDialog.getSelectedSearchArea();
-
- searchString = matchCase ? searchString : searchString.toLowerCase();
-
- boolean found = false;
- if (searchDialog.getSearchDown()) {
- for(int i = table.getSelectionIndex() + 1; i < table.getItemCount(); i++) {
- if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)){
- table.setSelection(i);
- break;
- }
- }
- } else {
- for(int i = table.getSelectionIndex() - 1; i > -1; i--) {
- if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)){
- table.setSelection(i);
- break;
- }
- }
- }
-
- shell.setCursor(null);
- if (waitCursor != null)
- waitCursor.dispose();
-
- return found;
-}
-private boolean findMatch(String searchString, TableItem item, int column, boolean matchWord, boolean matchCase) {
-
- String tableText = matchCase ? item.getText(column) : item.getText(column).toLowerCase();
- if (matchWord) {
- if (tableText != null && tableText.equals(searchString)) {
- return true;
- }
-
- } else {
- if(tableText!= null && tableText.indexOf(searchString) != -1) {
- return true;
- }
- }
- return false;
-}
-private void newAddressBook() {
- shell.setText(resAddressBook.getString("Title_bar") + resAddressBook.getString("New_title"));
- file = null;
- isModified = false;
-}
-private void newEntry() {
- DataEntryDialog dialog = new DataEntryDialog(shell);
- dialog.setLabels(columnNames);
- String[] data = dialog.open();
- if (data != null) {
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(data);
- isModified = true;
- }
-}
-
-private void openAddressBook() {
- FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
-
- fileDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
- fileDialog.setFilterNames(new String[] {resAddressBook.getString("Book_filter_name") + " (*.adr)",
- resAddressBook.getString("All_filter_name") + " (*.*)"});
- String name = fileDialog.open();
-
- if(name == null) return;
- File file = new File(name);
- if (!file.exists()) {
- displayError(resAddressBook.getString("File")+file.getName()+" "+resAddressBook.getString("Does_not_exist"));
- return;
- }
-
- Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
-
- FileReader fileReader = null;
- BufferedReader bufferedReader = null;
- String[] data = new String[0];
- try {
- fileReader = new FileReader(file.getAbsolutePath());
- bufferedReader = new BufferedReader(fileReader);
- String nextLine = bufferedReader.readLine();
- while (nextLine != null){
- String[] newData = new String[data.length + 1];
- System.arraycopy(data, 0, newData, 0, data.length);
- newData[data.length] = nextLine;
- data = newData;
- nextLine = bufferedReader.readLine();
- }
- } catch(FileNotFoundException e) {
- displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName());
- return;
- } catch (IOException e ) {
- displayError(resAddressBook.getString("IO_error_read") + "\n" + file.getName());
- return;
- } finally {
-
- shell.setCursor(null);
- waitCursor.dispose();
-
- if(fileReader != null) {
- try {
- fileReader.close();
- } catch(IOException e) {
- displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName());
- return;
- }
- }
- }
-
- String[][] tableInfo = new String[data.length][table.getColumnCount()];
- for (int i = 0; i < data.length; i++) {
- tableInfo[i] = decodeLine(data[i]);
- }
-
- Arrays.sort(tableInfo, new RowComparator(0));
-
- for (int i = 0; i < tableInfo.length; i++) {
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(tableInfo[i]);
- }
- shell.setText(resAddressBook.getString("Title_bar")+fileDialog.getFileName());
- isModified = false;
- this.file = file;
-}
-private boolean save() {
- if(file == null) return saveAs();
-
- Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
-
- TableItem[] items = table.getItems();
- String[] lines = new String[items.length];
- for(int i = 0; i < items.length; i++) {
- String[] itemText = new String[table.getColumnCount()];
- for (int j = 0; j < itemText.length; j++) {
- itemText[j] = items[i].getText(j);
- }
- lines[i] = encodeLine(itemText);
- }
-
- FileWriter fileWriter = null;
- try {
- fileWriter = new FileWriter(file.getAbsolutePath(), false);
- for (int i = 0; i < lines.length; i++) {
- fileWriter.write(lines[i]);
- }
- } catch(FileNotFoundException e) {
- displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName());
- return false;
- } catch(IOException e ) {
- displayError(resAddressBook.getString("IO_error_write") + "\n" + file.getName());
- return false;
- } finally {
- shell.setCursor(null);
- waitCursor.dispose();
-
- if(fileWriter != null) {
- try {
- fileWriter.close();
- } catch(IOException e) {
- displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName());
- return false;
- }
- }
- }
-
- shell.setText(resAddressBook.getString("Title_bar")+file.getName());
- isModified = false;
- return true;
-}
-private boolean saveAs() {
-
- FileDialog saveDialog = new FileDialog(shell, SWT.SAVE);
- saveDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
- saveDialog.setFilterNames(new String[] {"Address Books (*.adr)", "All Files "});
-
- saveDialog.open();
- String name = saveDialog.getFileName();
-
- if(name.equals("")) return false;
-
- if(name.indexOf(".adr") != name.length() - 4) {
- name += ".adr";
- }
-
- File file = new File(saveDialog.getFilterPath(), name);
- if(file.exists()) {
- MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO);
- box.setText(resAddressBook.getString("Save_as_title"));
- box.setMessage(resAddressBook.getString("File") + file.getName()+" "+resAddressBook.getString("Query_overwrite"));
- if(box.open() != SWT.YES) {
- return false;
- }
- }
- this.file = file;
- return save();
-}
-private void sort(int column) {
- if(table.getItemCount() <= 1) return;
-
- TableItem[] items = table.getItems();
- String[][] data = new String[items.length][table.getColumnCount()];
- for(int i = 0; i < items.length; i++) {
- for(int j = 0; j < table.getColumnCount(); j++) {
- data[i][j] = items[i].getText(j);
- }
- }
-
- Arrays.sort(data, new RowComparator(column));
-
- for (int i = 0; i < data.length; i++) {
- items[i].setText(data[i]);
- }
-
-}
-/**
- * Creates all the items located in the File submenu and
- * associate all the menu items with their appropriate
- * functions.
- *
- * @param menuBar Menu
- * the <code>Menu</code> that file contain
- * the File submenu.
- */
-private void createFileMenu(Menu menuBar) {
- //File menu.
- MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
- item.setText(resAddressBook.getString("File_menu_title"));
- Menu menu = new Menu(shell, SWT.DROP_DOWN);
- item.setMenu(menu);
- /**
- * Adds a listener to handle enabling and disabling
- * some items in the Edit submenu.
- */
- menu.addMenuListener(new MenuAdapter() {
- public void menuShown(MenuEvent e) {
- Menu menu = (Menu)e.widget;
- MenuItem[] items = menu.getItems();
- items[1].setEnabled(table.getSelectionCount() != 0); // edit contact
- items[5].setEnabled((file != null) && isModified); // save
- items[6].setEnabled(table.getItemCount() != 0); // save as
- }
- });
-
-
- //File -> New Contact
- MenuItem subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("New_contact"));
- subItem.setAccelerator(SWT.MOD1 + 'N');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- newEntry();
- }
- });
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("Edit_contact"));
- subItem.setAccelerator(SWT.MOD1 + 'E');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- TableItem[] items = table.getSelection();
- if (items.length == 0) return;
- editEntry(items[0]);
- }
- });
-
-
- new MenuItem(menu, SWT.SEPARATOR);
-
- //File -> New Address Book
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("New_address_book"));
- subItem.setAccelerator(SWT.MOD1 + 'B');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (closeAddressBook()) {
- newAddressBook();
- }
- }
- });
-
- //File -> Open
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("Open_address_book"));
- subItem.setAccelerator(SWT.MOD1 + 'O');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (closeAddressBook()) {
- openAddressBook();
- }
- }
- });
-
- //File -> Save.
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("Save_address_book"));
- subItem.setAccelerator(SWT.MOD1 + 'S');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- save();
- }
- });
-
- //File -> Save As.
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("Save_book_as"));
- subItem.setAccelerator(SWT.MOD1 + 'A');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- saveAs();
- }
- });
-
-
- new MenuItem(menu, SWT.SEPARATOR);
-
- //File -> Exit.
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("Exit"));
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- shell.close();
- }
- });
-}
-
-/**
- * Creates all the items located in the Edit submenu and
- * associate all the menu items with their appropriate
- * functions.
- *
- * @param menuBar Menu
- * the <code>Menu</code> that file contain
- * the Edit submenu.
- *
- * @see #createSortMenu()
- */
-private MenuItem createEditMenu(Menu menuBar) {
- //Edit menu.
- MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
- item.setText(resAddressBook.getString("Edit_menu_title"));
- Menu menu = new Menu(shell, SWT.DROP_DOWN);
- item.setMenu(menu);
-
- /**
- * Add a listener to handle enabling and disabling
- * some items in the Edit submenu.
- */
- menu.addMenuListener(new MenuAdapter() {
- public void menuShown(MenuEvent e) {
- Menu menu = (Menu)e.widget;
- MenuItem[] items = menu.getItems();
- int count = table.getSelectionCount();
- items[0].setEnabled(count != 0); // edit
- items[1].setEnabled(count != 0); // copy
- items[2].setEnabled(copyBuffer != null); // paste
- items[3].setEnabled(count != 0); // delete
- items[5].setEnabled(table.getItemCount() != 0); // sort
- }
- });
-
- //Edit -> Edit
- MenuItem subItem = new MenuItem(menu, SWT.CASCADE);
- subItem.setText(resAddressBook.getString("Edit"));
- subItem.setAccelerator(SWT.MOD1 + 'E');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- TableItem[] items = table.getSelection();
- if (items.length == 0) return;
- editEntry(items[0]);
- }
- });
-
- //Edit -> Copy
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("Copy"));
- subItem.setAccelerator(SWT.MOD1 + 'C');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- TableItem[] items = table.getSelection();
- if (items.length == 0) return;
- copyBuffer = new String[table.getColumnCount()];
- for (int i = 0; i < copyBuffer.length; i++) {
- copyBuffer[i] = items[0].getText(i);
- }
- }
- });
-
- //Edit -> Paste
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("Paste"));
- subItem.setAccelerator(SWT.MOD1 + 'V');
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (copyBuffer == null) return;
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(copyBuffer);
- isModified = true;
- }
- });
-
- //Edit -> Delete
- subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("Delete"));
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- TableItem[] items = table.getSelection();
- if (items.length == 0) return;
- items[0].dispose();
- isModified = true; }
- });
-
- new MenuItem(menu, SWT.SEPARATOR);
-
- //Edit -> Sort(Cascade)
- subItem = new MenuItem(menu, SWT.CASCADE);
- subItem.setText(resAddressBook.getString("Sort"));
- Menu submenu = createSortMenu();
- subItem.setMenu(submenu);
-
- return item;
-
-}
-
-/**
- * Creates all the items located in the Sort cascading submenu and
- * associate all the menu items with their appropriate
- * functions.
- *
- * @return Menu
- * The cascading menu with all the sort menu items on it.
- */
-private Menu createSortMenu() {
- Menu submenu = new Menu(shell, SWT.DROP_DOWN);
- MenuItem subitem;
- for(int i = 0; i < columnNames.length; i++) {
- subitem = new MenuItem (submenu, SWT.NULL);
- subitem.setText(columnNames [i]);
- final int column = i;
- subitem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- sort(column);
- }
- });
-
- }
-
- return submenu;
-}
-
-/**
- * Creates all the items located in the Search submenu and
- * associate all the menu items with their appropriate
- * functions.
- *
- * @param menuBar Menu
- * the <code>Menu</code> that file contain
- * the Search submenu.
- */
-private void createSearchMenu(Menu menuBar) {
- //Search menu.
- MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
- item.setText(resAddressBook.getString("Search_menu_title"));
- Menu searchMenu = new Menu(shell, SWT.DROP_DOWN);
- item.setMenu(searchMenu);
-
- //Search -> Find...
- item = new MenuItem(searchMenu, SWT.NULL);
- item.setText(resAddressBook.getString("Find"));
- item.setAccelerator(SWT.MOD1 + 'F');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- searchDialog.setMatchCase(false);
- searchDialog.setMatchWord(false);
- searchDialog.setSearchDown(true);
- searchDialog.setSearchString("");
- searchDialog.setSelectedSearchArea(0);
- searchDialog.open();
- }
- });
-
- //Search -> Find Next
- item = new MenuItem(searchMenu, SWT.NULL);
- item.setText(resAddressBook.getString("Find_next"));
- item.setAccelerator(SWT.F3);
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- searchDialog.open();
- }
- });
-}
-
-/**
- * Creates all items located in the popup menu and associates
- * all the menu items with their appropriate functions.
- *
- * @return Menu
- * The created popup menu.
- */
-private Menu createPopUpMenu() {
- Menu popUpMenu = new Menu(shell, SWT.POP_UP);
-
- /**
- * Adds a listener to handle enabling and disabling
- * some items in the Edit submenu.
- */
- popUpMenu.addMenuListener(new MenuAdapter() {
- public void menuShown(MenuEvent e) {
- Menu menu = (Menu)e.widget;
- MenuItem[] items = menu.getItems();
- int count = table.getSelectionCount();
- items[2].setEnabled(count != 0); // edit
- items[3].setEnabled(count != 0); // copy
- items[4].setEnabled(copyBuffer != null); // paste
- items[5].setEnabled(count != 0); // delete
- items[7].setEnabled(table.getItemCount() != 0); // find
- }
- });
-
- //New
- MenuItem item = new MenuItem(popUpMenu, SWT.CASCADE);
- item.setText(resAddressBook.getString("Pop_up_new"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- newEntry();
- }
- });
-
- new MenuItem(popUpMenu, SWT.SEPARATOR);
-
- //Edit
- item = new MenuItem(popUpMenu, SWT.CASCADE);
- item.setText(resAddressBook.getString("Pop_up_edit"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- TableItem[] items = table.getSelection();
- if (items.length == 0) return;
- editEntry(items[0]);
- }
- });
-
- //Copy
- item = new MenuItem(popUpMenu, SWT.CASCADE);
- item.setText(resAddressBook.getString("Pop_up_copy"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- TableItem[] items = table.getSelection();
- if (items.length == 0) return;
- copyBuffer = new String[table.getColumnCount()];
- for (int i = 0; i < copyBuffer.length; i++) {
- copyBuffer[i] = items[0].getText(i);
- }
- }
- });
-
- //Paste
- item = new MenuItem(popUpMenu, SWT.CASCADE);
- item.setText(resAddressBook.getString("Pop_up_paste"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (copyBuffer == null) return;
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(copyBuffer);
- isModified = true;
- }
- });
-
- //Delete
- item = new MenuItem(popUpMenu, SWT.CASCADE);
- item.setText(resAddressBook.getString("Pop_up_delete"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- TableItem[] items = table.getSelection();
- if (items.length == 0) return;
- items[0].dispose();
- isModified = true;
- }
- });
-
- new MenuItem(popUpMenu, SWT.SEPARATOR);
-
- //Find...
- item = new MenuItem(popUpMenu, SWT.NULL);
- item.setText(resAddressBook.getString("Pop_up_find"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- searchDialog.open();
- }
- });
-
- return popUpMenu;
-}
-
-/**
- * Creates all the items located in the Help submenu and
- * associate all the menu items with their appropriate
- * functions.
- *
- * @param menuBar Menu
- * the <code>Menu</code> that file contain
- * the Help submenu.
- */
-private void createHelpMenu(Menu menuBar) {
-
- //Help Menu
- MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
- item.setText(resAddressBook.getString("Help_menu_title"));
- Menu menu = new Menu(shell, SWT.DROP_DOWN);
- item.setMenu(menu);
-
- //Help -> About Text Editor
- MenuItem subItem = new MenuItem(menu, SWT.NULL);
- subItem.setText(resAddressBook.getString("About"));
- subItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- MessageBox box = new MessageBox(shell, SWT.NONE);
- box.setText(resAddressBook.getString("About_1") + shell.getText());
- box.setMessage(shell.getText() + resAddressBook.getString("About_2"));
- box.open();
- }
- });
-}
-
-/**
- * To compare entries (rows) by the given column
- */
-private class RowComparator implements Comparator {
- private int column;
-
- /**
- * Constructs a RowComparator given the column index
- * @param col The index (starting at zero) of the column
- */
- public RowComparator(int col) {
- column = col;
- }
-
- /**
- * Compares two rows (type String[]) using the specified
- * column entry.
- * @param obj1 First row to compare
- * @param obj2 Second row to compare
- * @return negative if obj1 less than obj2, positive if
- * obj1 greater than obj2, and zero if equal.
- */
- public int compare(Object obj1, Object obj2) {
- String[] row1 = (String[])obj1;
- String[] row2 = (String[])obj2;
-
- return row1[column].compareTo(row2[column]);
- }
-}
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+/* Imports */
+import java.io.*;
+import java.util.*;
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.widgets.*;
+
+/**
+ * AddressBookExample is an example that uses <code>org.eclipse.swt</code>
+ * libraries to implement a simple address book. This application has
+ * save, load, sorting, and searching functions common
+ * to basic address books.
+ */
+public class AddressBook {
+
+ private static ResourceBundle resAddressBook = ResourceBundle.getBundle("examples_addressbook");
+ private Shell shell;
+
+ private Table table;
+ private SearchDialog searchDialog;
+
+ private File file;
+ private boolean isModified;
+
+ private String[] copyBuffer;
+
+ private static final String DELIMITER = "\t";
+ private static final String[] columnNames = {resAddressBook.getString("Last_name"),
+ resAddressBook.getString("First_name"),
+ resAddressBook.getString("Business_phone"),
+ resAddressBook.getString("Home_phone"),
+ resAddressBook.getString("Email"),
+ resAddressBook.getString("Fax")};
+
+public static void main(String[] args) {
+ Display display = new Display();
+ AddressBook application = new AddressBook();
+ Shell shell = application.open(display);
+ while(!shell.isDisposed()){
+ if(!display.readAndDispatch())
+ display.sleep();
+ }
+ display.dispose();
+}
+public Shell open(Display display) {
+ shell = new Shell(display);
+ shell.setLayout(new FillLayout());
+ shell.addShellListener(new ShellAdapter() {
+ public void shellClosed(ShellEvent e) {
+ e.doit = closeAddressBook();
+ }
+ });
+
+ createMenuBar();
+
+ searchDialog = new SearchDialog(shell);
+ searchDialog.setSearchAreaNames(columnNames);
+ searchDialog.setSearchAreaLabel(resAddressBook.getString("Column"));
+ searchDialog.addFindListener(new FindListener () {
+ public boolean find() {
+ return findEntry();
+ }
+ });
+
+ table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
+ table.setHeaderVisible(true);
+ table.setMenu(createPopUpMenu());
+ table.addSelectionListener(new SelectionAdapter() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ TableItem[] items = table.getSelection();
+ if (items.length > 0) editEntry(items[0]);
+ }
+ });
+ for(int i = 0; i < columnNames.length; i++) {
+ TableColumn column = new TableColumn(table, SWT.NONE);
+ column.setText(columnNames[i]);
+ column.setWidth(150);
+ final int columnIndex = i;
+ column.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ sort(columnIndex);
+ }
+ });
+ }
+
+ newAddressBook();
+
+ shell.setSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
+ shell.open();
+ return shell;
+}
+
+private boolean closeAddressBook() {
+ if(isModified) {
+ //ask user if they want to save current address book
+ MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO | SWT.CANCEL);
+ box.setText(shell.getText());
+ box.setMessage(resAddressBook.getString("Close_save"));
+
+ int choice = box.open();
+ if(choice == SWT.CANCEL) {
+ return false;
+ } else if(choice == SWT.YES) {
+ if (!save()) return false;
+ }
+ }
+
+ TableItem[] items = table.getItems();
+ for (int i = 0; i < items.length; i ++) {
+ items[i].dispose();
+ }
+
+ return true;
+}
+/**
+ * Creates the menu at the top of the shell where most
+ * of the programs functionality is accessed.
+ *
+ * @return The <code>Menu</code> widget that was created
+ */
+private Menu createMenuBar() {
+ Menu menuBar = new Menu(shell, SWT.BAR);
+ shell.setMenuBar(menuBar);
+
+ //create each header and subMenu for the menuBar
+ createFileMenu(menuBar);
+ createEditMenu(menuBar);
+ createSearchMenu(menuBar);
+ createHelpMenu(menuBar);
+
+ return menuBar;
+}
+
+/**
+ * Converts an encoded <code>String</code> to a String array representing a table entry.
+ */
+private String[] decodeLine(String line) {
+ if(line == null) return null;
+
+ String[] parsedLine = new String[table.getColumnCount()];
+ for(int i = 0; i < parsedLine.length - 1; i++) {
+ int index = line.indexOf(DELIMITER);
+ if (index > -1) {
+ parsedLine[i] = line.substring(0, index);
+ line = line.substring(index + DELIMITER.length(), line.length());
+ } else {
+ return null;
+ }
+ }
+
+ if (line.indexOf(DELIMITER) != -1) return null;
+
+ parsedLine[parsedLine.length - 1] = line;
+
+ return parsedLine;
+}
+private void displayError(String msg) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
+ box.setMessage(msg);
+ box.open();
+}
+private void editEntry(TableItem item) {
+ DataEntryDialog dialog = new DataEntryDialog(shell);
+ dialog.setLabels(columnNames);
+ String[] values = new String[table.getColumnCount()];
+ for (int i = 0; i < values.length; i++) {
+ values[i] = item.getText(i);
+ }
+ dialog.setValues(values);
+ values = dialog.open();
+ if (values != null) {
+ item.setText(values);
+ isModified = true;
+ }
+}
+private String encodeLine(String[] tableItems) {
+ String line = "";
+ for (int i = 0; i < tableItems.length - 1; i++) {
+ line += tableItems[i] + DELIMITER;
+ }
+ line += tableItems[tableItems.length - 1] + "\n";
+
+ return line;
+}
+private boolean findEntry() {
+ Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+
+ boolean matchCase = searchDialog.getMatchCase();
+ boolean matchWord = searchDialog.getMatchWord();
+ String searchString = searchDialog.getSearchString();
+ int column = searchDialog.getSelectedSearchArea();
+
+ searchString = matchCase ? searchString : searchString.toLowerCase();
+
+ boolean found = false;
+ if (searchDialog.getSearchDown()) {
+ for(int i = table.getSelectionIndex() + 1; i < table.getItemCount(); i++) {
+ if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)){
+ table.setSelection(i);
+ break;
+ }
+ }
+ } else {
+ for(int i = table.getSelectionIndex() - 1; i > -1; i--) {
+ if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)){
+ table.setSelection(i);
+ break;
+ }
+ }
+ }
+
+ shell.setCursor(null);
+ if (waitCursor != null)
+ waitCursor.dispose();
+
+ return found;
+}
+private boolean findMatch(String searchString, TableItem item, int column, boolean matchWord, boolean matchCase) {
+
+ String tableText = matchCase ? item.getText(column) : item.getText(column).toLowerCase();
+ if (matchWord) {
+ if (tableText != null && tableText.equals(searchString)) {
+ return true;
+ }
+
+ } else {
+ if(tableText!= null && tableText.indexOf(searchString) != -1) {
+ return true;
+ }
+ }
+ return false;
+}
+private void newAddressBook() {
+ shell.setText(resAddressBook.getString("Title_bar") + resAddressBook.getString("New_title"));
+ file = null;
+ isModified = false;
+}
+private void newEntry() {
+ DataEntryDialog dialog = new DataEntryDialog(shell);
+ dialog.setLabels(columnNames);
+ String[] data = dialog.open();
+ if (data != null) {
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(data);
+ isModified = true;
+ }
+}
+
+private void openAddressBook() {
+ FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
+
+ fileDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
+ fileDialog.setFilterNames(new String[] {resAddressBook.getString("Book_filter_name") + " (*.adr)",
+ resAddressBook.getString("All_filter_name") + " (*.*)"});
+ String name = fileDialog.open();
+
+ if(name == null) return;
+ File file = new File(name);
+ if (!file.exists()) {
+ displayError(resAddressBook.getString("File")+file.getName()+" "+resAddressBook.getString("Does_not_exist"));
+ return;
+ }
+
+ Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+
+ FileReader fileReader = null;
+ BufferedReader bufferedReader = null;
+ String[] data = new String[0];
+ try {
+ fileReader = new FileReader(file.getAbsolutePath());
+ bufferedReader = new BufferedReader(fileReader);
+ String nextLine = bufferedReader.readLine();
+ while (nextLine != null){
+ String[] newData = new String[data.length + 1];
+ System.arraycopy(data, 0, newData, 0, data.length);
+ newData[data.length] = nextLine;
+ data = newData;
+ nextLine = bufferedReader.readLine();
+ }
+ } catch(FileNotFoundException e) {
+ displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName());
+ return;
+ } catch (IOException e ) {
+ displayError(resAddressBook.getString("IO_error_read") + "\n" + file.getName());
+ return;
+ } finally {
+
+ shell.setCursor(null);
+ waitCursor.dispose();
+
+ if(fileReader != null) {
+ try {
+ fileReader.close();
+ } catch(IOException e) {
+ displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName());
+ return;
+ }
+ }
+ }
+
+ String[][] tableInfo = new String[data.length][table.getColumnCount()];
+ for (int i = 0; i < data.length; i++) {
+ tableInfo[i] = decodeLine(data[i]);
+ }
+
+ Arrays.sort(tableInfo, new RowComparator(0));
+
+ for (int i = 0; i < tableInfo.length; i++) {
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(tableInfo[i]);
+ }
+ shell.setText(resAddressBook.getString("Title_bar")+fileDialog.getFileName());
+ isModified = false;
+ this.file = file;
+}
+private boolean save() {
+ if(file == null) return saveAs();
+
+ Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+
+ TableItem[] items = table.getItems();
+ String[] lines = new String[items.length];
+ for(int i = 0; i < items.length; i++) {
+ String[] itemText = new String[table.getColumnCount()];
+ for (int j = 0; j < itemText.length; j++) {
+ itemText[j] = items[i].getText(j);
+ }
+ lines[i] = encodeLine(itemText);
+ }
+
+ FileWriter fileWriter = null;
+ try {
+ fileWriter = new FileWriter(file.getAbsolutePath(), false);
+ for (int i = 0; i < lines.length; i++) {
+ fileWriter.write(lines[i]);
+ }
+ } catch(FileNotFoundException e) {
+ displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName());
+ return false;
+ } catch(IOException e ) {
+ displayError(resAddressBook.getString("IO_error_write") + "\n" + file.getName());
+ return false;
+ } finally {
+ shell.setCursor(null);
+ waitCursor.dispose();
+
+ if(fileWriter != null) {
+ try {
+ fileWriter.close();
+ } catch(IOException e) {
+ displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName());
+ return false;
+ }
+ }
+ }
+
+ shell.setText(resAddressBook.getString("Title_bar")+file.getName());
+ isModified = false;
+ return true;
+}
+private boolean saveAs() {
+
+ FileDialog saveDialog = new FileDialog(shell, SWT.SAVE);
+ saveDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
+ saveDialog.setFilterNames(new String[] {"Address Books (*.adr)", "All Files "});
+
+ saveDialog.open();
+ String name = saveDialog.getFileName();
+
+ if(name.equals("")) return false;
+
+ if(name.indexOf(".adr") != name.length() - 4) {
+ name += ".adr";
+ }
+
+ File file = new File(saveDialog.getFilterPath(), name);
+ if(file.exists()) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO);
+ box.setText(resAddressBook.getString("Save_as_title"));
+ box.setMessage(resAddressBook.getString("File") + file.getName()+" "+resAddressBook.getString("Query_overwrite"));
+ if(box.open() != SWT.YES) {
+ return false;
+ }
+ }
+ this.file = file;
+ return save();
+}
+private void sort(int column) {
+ if(table.getItemCount() <= 1) return;
+
+ TableItem[] items = table.getItems();
+ String[][] data = new String[items.length][table.getColumnCount()];
+ for(int i = 0; i < items.length; i++) {
+ for(int j = 0; j < table.getColumnCount(); j++) {
+ data[i][j] = items[i].getText(j);
+ }
+ }
+
+ Arrays.sort(data, new RowComparator(column));
+
+ for (int i = 0; i < data.length; i++) {
+ items[i].setText(data[i]);
+ }
+
+}
+/**
+ * Creates all the items located in the File submenu and
+ * associate all the menu items with their appropriate
+ * functions.
+ *
+ * @param menuBar Menu
+ * the <code>Menu</code> that file contain
+ * the File submenu.
+ */
+private void createFileMenu(Menu menuBar) {
+ //File menu.
+ MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
+ item.setText(resAddressBook.getString("File_menu_title"));
+ Menu menu = new Menu(shell, SWT.DROP_DOWN);
+ item.setMenu(menu);
+ /**
+ * Adds a listener to handle enabling and disabling
+ * some items in the Edit submenu.
+ */
+ menu.addMenuListener(new MenuAdapter() {
+ public void menuShown(MenuEvent e) {
+ Menu menu = (Menu)e.widget;
+ MenuItem[] items = menu.getItems();
+ items[1].setEnabled(table.getSelectionCount() != 0); // edit contact
+ items[5].setEnabled((file != null) && isModified); // save
+ items[6].setEnabled(table.getItemCount() != 0); // save as
+ }
+ });
+
+
+ //File -> New Contact
+ MenuItem subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("New_contact"));
+ subItem.setAccelerator(SWT.MOD1 + 'N');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ newEntry();
+ }
+ });
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("Edit_contact"));
+ subItem.setAccelerator(SWT.MOD1 + 'E');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] items = table.getSelection();
+ if (items.length == 0) return;
+ editEntry(items[0]);
+ }
+ });
+
+
+ new MenuItem(menu, SWT.SEPARATOR);
+
+ //File -> New Address Book
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("New_address_book"));
+ subItem.setAccelerator(SWT.MOD1 + 'B');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ if (closeAddressBook()) {
+ newAddressBook();
+ }
+ }
+ });
+
+ //File -> Open
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("Open_address_book"));
+ subItem.setAccelerator(SWT.MOD1 + 'O');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ if (closeAddressBook()) {
+ openAddressBook();
+ }
+ }
+ });
+
+ //File -> Save.
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("Save_address_book"));
+ subItem.setAccelerator(SWT.MOD1 + 'S');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ save();
+ }
+ });
+
+ //File -> Save As.
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("Save_book_as"));
+ subItem.setAccelerator(SWT.MOD1 + 'A');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ saveAs();
+ }
+ });
+
+
+ new MenuItem(menu, SWT.SEPARATOR);
+
+ //File -> Exit.
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("Exit"));
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ shell.close();
+ }
+ });
+}
+
+/**
+ * Creates all the items located in the Edit submenu and
+ * associate all the menu items with their appropriate
+ * functions.
+ *
+ * @param menuBar Menu
+ * the <code>Menu</code> that file contain
+ * the Edit submenu.
+ *
+ * @see #createSortMenu()
+ */
+private MenuItem createEditMenu(Menu menuBar) {
+ //Edit menu.
+ MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
+ item.setText(resAddressBook.getString("Edit_menu_title"));
+ Menu menu = new Menu(shell, SWT.DROP_DOWN);
+ item.setMenu(menu);
+
+ /**
+ * Add a listener to handle enabling and disabling
+ * some items in the Edit submenu.
+ */
+ menu.addMenuListener(new MenuAdapter() {
+ public void menuShown(MenuEvent e) {
+ Menu menu = (Menu)e.widget;
+ MenuItem[] items = menu.getItems();
+ int count = table.getSelectionCount();
+ items[0].setEnabled(count != 0); // edit
+ items[1].setEnabled(count != 0); // copy
+ items[2].setEnabled(copyBuffer != null); // paste
+ items[3].setEnabled(count != 0); // delete
+ items[5].setEnabled(table.getItemCount() != 0); // sort
+ }
+ });
+
+ //Edit -> Edit
+ MenuItem subItem = new MenuItem(menu, SWT.CASCADE);
+ subItem.setText(resAddressBook.getString("Edit"));
+ subItem.setAccelerator(SWT.MOD1 + 'E');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] items = table.getSelection();
+ if (items.length == 0) return;
+ editEntry(items[0]);
+ }
+ });
+
+ //Edit -> Copy
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("Copy"));
+ subItem.setAccelerator(SWT.MOD1 + 'C');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] items = table.getSelection();
+ if (items.length == 0) return;
+ copyBuffer = new String[table.getColumnCount()];
+ for (int i = 0; i < copyBuffer.length; i++) {
+ copyBuffer[i] = items[0].getText(i);
+ }
+ }
+ });
+
+ //Edit -> Paste
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("Paste"));
+ subItem.setAccelerator(SWT.MOD1 + 'V');
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ if (copyBuffer == null) return;
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(copyBuffer);
+ isModified = true;
+ }
+ });
+
+ //Edit -> Delete
+ subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("Delete"));
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] items = table.getSelection();
+ if (items.length == 0) return;
+ items[0].dispose();
+ isModified = true; }
+ });
+
+ new MenuItem(menu, SWT.SEPARATOR);
+
+ //Edit -> Sort(Cascade)
+ subItem = new MenuItem(menu, SWT.CASCADE);
+ subItem.setText(resAddressBook.getString("Sort"));
+ Menu submenu = createSortMenu();
+ subItem.setMenu(submenu);
+
+ return item;
+
+}
+
+/**
+ * Creates all the items located in the Sort cascading submenu and
+ * associate all the menu items with their appropriate
+ * functions.
+ *
+ * @return Menu
+ * The cascading menu with all the sort menu items on it.
+ */
+private Menu createSortMenu() {
+ Menu submenu = new Menu(shell, SWT.DROP_DOWN);
+ MenuItem subitem;
+ for(int i = 0; i < columnNames.length; i++) {
+ subitem = new MenuItem (submenu, SWT.NULL);
+ subitem.setText(columnNames [i]);
+ final int column = i;
+ subitem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ sort(column);
+ }
+ });
+
+ }
+
+ return submenu;
+}
+
+/**
+ * Creates all the items located in the Search submenu and
+ * associate all the menu items with their appropriate
+ * functions.
+ *
+ * @param menuBar Menu
+ * the <code>Menu</code> that file contain
+ * the Search submenu.
+ */
+private void createSearchMenu(Menu menuBar) {
+ //Search menu.
+ MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
+ item.setText(resAddressBook.getString("Search_menu_title"));
+ Menu searchMenu = new Menu(shell, SWT.DROP_DOWN);
+ item.setMenu(searchMenu);
+
+ //Search -> Find...
+ item = new MenuItem(searchMenu, SWT.NULL);
+ item.setText(resAddressBook.getString("Find"));
+ item.setAccelerator(SWT.MOD1 + 'F');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ searchDialog.setMatchCase(false);
+ searchDialog.setMatchWord(false);
+ searchDialog.setSearchDown(true);
+ searchDialog.setSearchString("");
+ searchDialog.setSelectedSearchArea(0);
+ searchDialog.open();
+ }
+ });
+
+ //Search -> Find Next
+ item = new MenuItem(searchMenu, SWT.NULL);
+ item.setText(resAddressBook.getString("Find_next"));
+ item.setAccelerator(SWT.F3);
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ searchDialog.open();
+ }
+ });
+}
+
+/**
+ * Creates all items located in the popup menu and associates
+ * all the menu items with their appropriate functions.
+ *
+ * @return Menu
+ * The created popup menu.
+ */
+private Menu createPopUpMenu() {
+ Menu popUpMenu = new Menu(shell, SWT.POP_UP);
+
+ /**
+ * Adds a listener to handle enabling and disabling
+ * some items in the Edit submenu.
+ */
+ popUpMenu.addMenuListener(new MenuAdapter() {
+ public void menuShown(MenuEvent e) {
+ Menu menu = (Menu)e.widget;
+ MenuItem[] items = menu.getItems();
+ int count = table.getSelectionCount();
+ items[2].setEnabled(count != 0); // edit
+ items[3].setEnabled(count != 0); // copy
+ items[4].setEnabled(copyBuffer != null); // paste
+ items[5].setEnabled(count != 0); // delete
+ items[7].setEnabled(table.getItemCount() != 0); // find
+ }
+ });
+
+ //New
+ MenuItem item = new MenuItem(popUpMenu, SWT.CASCADE);
+ item.setText(resAddressBook.getString("Pop_up_new"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ newEntry();
+ }
+ });
+
+ new MenuItem(popUpMenu, SWT.SEPARATOR);
+
+ //Edit
+ item = new MenuItem(popUpMenu, SWT.CASCADE);
+ item.setText(resAddressBook.getString("Pop_up_edit"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] items = table.getSelection();
+ if (items.length == 0) return;
+ editEntry(items[0]);
+ }
+ });
+
+ //Copy
+ item = new MenuItem(popUpMenu, SWT.CASCADE);
+ item.setText(resAddressBook.getString("Pop_up_copy"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] items = table.getSelection();
+ if (items.length == 0) return;
+ copyBuffer = new String[table.getColumnCount()];
+ for (int i = 0; i < copyBuffer.length; i++) {
+ copyBuffer[i] = items[0].getText(i);
+ }
+ }
+ });
+
+ //Paste
+ item = new MenuItem(popUpMenu, SWT.CASCADE);
+ item.setText(resAddressBook.getString("Pop_up_paste"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ if (copyBuffer == null) return;
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(copyBuffer);
+ isModified = true;
+ }
+ });
+
+ //Delete
+ item = new MenuItem(popUpMenu, SWT.CASCADE);
+ item.setText(resAddressBook.getString("Pop_up_delete"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] items = table.getSelection();
+ if (items.length == 0) return;
+ items[0].dispose();
+ isModified = true;
+ }
+ });
+
+ new MenuItem(popUpMenu, SWT.SEPARATOR);
+
+ //Find...
+ item = new MenuItem(popUpMenu, SWT.NULL);
+ item.setText(resAddressBook.getString("Pop_up_find"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ searchDialog.open();
+ }
+ });
+
+ return popUpMenu;
+}
+
+/**
+ * Creates all the items located in the Help submenu and
+ * associate all the menu items with their appropriate
+ * functions.
+ *
+ * @param menuBar Menu
+ * the <code>Menu</code> that file contain
+ * the Help submenu.
+ */
+private void createHelpMenu(Menu menuBar) {
+
+ //Help Menu
+ MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
+ item.setText(resAddressBook.getString("Help_menu_title"));
+ Menu menu = new Menu(shell, SWT.DROP_DOWN);
+ item.setMenu(menu);
+
+ //Help -> About Text Editor
+ MenuItem subItem = new MenuItem(menu, SWT.NULL);
+ subItem.setText(resAddressBook.getString("About"));
+ subItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ MessageBox box = new MessageBox(shell, SWT.NONE);
+ box.setText(resAddressBook.getString("About_1") + shell.getText());
+ box.setMessage(shell.getText() + resAddressBook.getString("About_2"));
+ box.open();
+ }
+ });
+}
+
+/**
+ * To compare entries (rows) by the given column
+ */
+private class RowComparator implements Comparator {
+ private int column;
+
+ /**
+ * Constructs a RowComparator given the column index
+ * @param col The index (starting at zero) of the column
+ */
+ public RowComparator(int col) {
+ column = col;
+ }
+
+ /**
+ * Compares two rows (type String[]) using the specified
+ * column entry.
+ * @param obj1 First row to compare
+ * @param obj2 Second row to compare
+ * @return negative if obj1 less than obj2, positive if
+ * obj1 greater than obj2, and zero if equal.
+ */
+ public int compare(Object obj1, Object obj2) {
+ String[] row1 = (String[])obj1;
+ String[] row2 = (String[])obj2;
+
+ return row1[column].compareTo(row2[column]);
+ }
+}
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/DataEntryDialog.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/DataEntryDialog.java
index 6be9f908bc..af087e7f37 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/DataEntryDialog.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/DataEntryDialog.java
@@ -1,159 +1,159 @@
-package org.eclipse.swt.examples.addressbook;
-
-/*
+package org.eclipse.swt.examples.addressbook;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-/* Imports */
-import org.eclipse.swt.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.widgets.*;
-import java.util.ResourceBundle;
-
-/**
- * DataEntryDialog class uses <code>org.eclipse.swt</code>
- * libraries to implement a dialog that accepts basic personal information that
- * is added to a <code>Table</code> widget or edits a <code>TableItem</code> entry
- * to represent the entered data.
- */
-public class DataEntryDialog {
-
- private static ResourceBundle resAddressBook = ResourceBundle.getBundle("examples_addressbook");
-
- Shell shell;
- String[] values;
- String[] labels;
-
-public DataEntryDialog(Shell parent) {
- shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.PRIMARY_MODAL);
- shell.setLayout(new GridLayout());
-}
-
-private void addTextListener(final Text text) {
- text.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e){
- Integer index = (Integer)(text.getData("index"));
- values[index.intValue()] = text.getText();
- }
- });
-}
-private void createControlButtons() {
- Composite composite = new Composite(shell, SWT.NULL);
- composite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- composite.setLayout(layout);
-
- Button okButton = new Button(composite, SWT.PUSH);
- okButton.setText(resAddressBook.getString("OK"));
- okButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- shell.close();
- }
- });
-
- Button cancelButton = new Button(composite, SWT.PUSH);
- cancelButton.setText(resAddressBook.getString("Cancel"));
- cancelButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- values = null;
- shell.close();
- }
- });
-
- shell.setDefaultButton(okButton);
-}
-
-private void createTextWidgets() {
- if (labels == null) return;
-
- Composite composite = new Composite(shell, SWT.NULL);
- composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridLayout layout= new GridLayout();
- layout.numColumns = 2;
- composite.setLayout(layout);
-
- if (values == null)
- values = new String[labels.length];
-
- for (int i = 0; i < labels.length; i++) {
- Label label = new Label(composite, SWT.RIGHT);
- label.setText(labels[i]);
- Text text = new Text(composite, SWT.BORDER);
- GridData gridData = new GridData();
- gridData.widthHint = 400;
- text.setLayoutData(gridData);
- if (values[i] != null) {
- text.setText(values[i]);
- }
- text.setData("index", new Integer(i));
- addTextListener(text);
- }
-}
-
-public String[] getLabels() {
- return labels;
-}
-public String getTitle() {
- return shell.getText();
-}
-/**
- * Returns the contents of the <code>Text</code> widgets in the dialog in a
- * <code>String</code> array.
- *
- * @return String[]
- * The contents of the text widgets of the dialog.
- * May return null if all text widgets are empty.
- */
-public String[] getValues() {
- return values;
-}
-/**
- * Opens the dialog in the given state. Sets <code>Text</code> widget contents
- * and dialog behaviour accordingly.
- *
- * @param dialogState int
- * The state the dialog should be opened in.
- */
-public String[] open() {
- createTextWidgets();
- createControlButtons();
- shell.pack();
- shell.open();
- Display display = shell.getDisplay();
- while(!shell.isDisposed()){
- if(!display.readAndDispatch())
- display.sleep();
- }
-
- return getValues();
-}
-public void setLabels(String[] labels) {
- this.labels = labels;
-}
-public void setTitle(String title) {
- shell.setText(title);
-}
-/**
- * Sets the values of the <code>Text</code> widgets of the dialog to
- * the values supplied in the parameter array.
- *
- * @param itemInfo String[]
- * The values to which the dialog contents will be set.
- */
-public void setValues(String[] itemInfo) {
- if (labels == null) return;
-
- if (values == null)
- values = new String[labels.length];
-
- int numItems = Math.min(values.length, itemInfo.length);
- for(int i = 0; i < numItems; i++) {
- values[i] = itemInfo[i];
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+/* Imports */
+import org.eclipse.swt.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.widgets.*;
+import java.util.ResourceBundle;
+
+/**
+ * DataEntryDialog class uses <code>org.eclipse.swt</code>
+ * libraries to implement a dialog that accepts basic personal information that
+ * is added to a <code>Table</code> widget or edits a <code>TableItem</code> entry
+ * to represent the entered data.
+ */
+public class DataEntryDialog {
+
+ private static ResourceBundle resAddressBook = ResourceBundle.getBundle("examples_addressbook");
+
+ Shell shell;
+ String[] values;
+ String[] labels;
+
+public DataEntryDialog(Shell parent) {
+ shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.PRIMARY_MODAL);
+ shell.setLayout(new GridLayout());
+}
+
+private void addTextListener(final Text text) {
+ text.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e){
+ Integer index = (Integer)(text.getData("index"));
+ values[index.intValue()] = text.getText();
+ }
+ });
+}
+private void createControlButtons() {
+ Composite composite = new Composite(shell, SWT.NULL);
+ composite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+
+ Button okButton = new Button(composite, SWT.PUSH);
+ okButton.setText(resAddressBook.getString("OK"));
+ okButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ shell.close();
+ }
+ });
+
+ Button cancelButton = new Button(composite, SWT.PUSH);
+ cancelButton.setText(resAddressBook.getString("Cancel"));
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ values = null;
+ shell.close();
+ }
+ });
+
+ shell.setDefaultButton(okButton);
+}
+
+private void createTextWidgets() {
+ if (labels == null) return;
+
+ Composite composite = new Composite(shell, SWT.NULL);
+ composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ GridLayout layout= new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+
+ if (values == null)
+ values = new String[labels.length];
+
+ for (int i = 0; i < labels.length; i++) {
+ Label label = new Label(composite, SWT.RIGHT);
+ label.setText(labels[i]);
+ Text text = new Text(composite, SWT.BORDER);
+ GridData gridData = new GridData();
+ gridData.widthHint = 400;
+ text.setLayoutData(gridData);
+ if (values[i] != null) {
+ text.setText(values[i]);
+ }
+ text.setData("index", new Integer(i));
+ addTextListener(text);
+ }
+}
+
+public String[] getLabels() {
+ return labels;
+}
+public String getTitle() {
+ return shell.getText();
+}
+/**
+ * Returns the contents of the <code>Text</code> widgets in the dialog in a
+ * <code>String</code> array.
+ *
+ * @return String[]
+ * The contents of the text widgets of the dialog.
+ * May return null if all text widgets are empty.
+ */
+public String[] getValues() {
+ return values;
+}
+/**
+ * Opens the dialog in the given state. Sets <code>Text</code> widget contents
+ * and dialog behaviour accordingly.
+ *
+ * @param dialogState int
+ * The state the dialog should be opened in.
+ */
+public String[] open() {
+ createTextWidgets();
+ createControlButtons();
+ shell.pack();
+ shell.open();
+ Display display = shell.getDisplay();
+ while(!shell.isDisposed()){
+ if(!display.readAndDispatch())
+ display.sleep();
+ }
+
+ return getValues();
+}
+public void setLabels(String[] labels) {
+ this.labels = labels;
+}
+public void setTitle(String title) {
+ shell.setText(title);
+}
+/**
+ * Sets the values of the <code>Text</code> widgets of the dialog to
+ * the values supplied in the parameter array.
+ *
+ * @param itemInfo String[]
+ * The values to which the dialog contents will be set.
+ */
+public void setValues(String[] itemInfo) {
+ if (labels == null) return;
+
+ if (values == null)
+ values = new String[labels.length];
+
+ int numItems = Math.min(values.length, itemInfo.length);
+ for(int i = 0; i < numItems; i++) {
+ values[i] = itemInfo[i];
+ }
+}
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/FindListener.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/FindListener.java
index ab0f020fa6..0d41ba5457 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/FindListener.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/FindListener.java
@@ -1,14 +1,14 @@
-package org.eclipse.swt.examples.addressbook;
-
-/*
+package org.eclipse.swt.examples.addressbook;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-public interface FindListener {
-
-public boolean find();
-
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+public interface FindListener {
+
+public boolean find();
+
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/SearchDialog.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/SearchDialog.java
index 4835dc06af..83c8644095 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/SearchDialog.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/addressbook/SearchDialog.java
@@ -1,198 +1,198 @@
-package org.eclipse.swt.examples.addressbook;
-
-/*
+package org.eclipse.swt.examples.addressbook;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-/* Imports */
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-import java.util.ResourceBundle;
-
-/**
- * SearchDialog is a simple class that uses <code>org.eclipse.swt</code>
- * libraries to implement a basic search dialog.
- */
-public class SearchDialog {
-
- private static ResourceBundle resAddressBook = ResourceBundle.getBundle("examples_addressbook");
-
- Shell shell;
- Text searchText;
- Combo searchArea;
- Label searchAreaLabel;
- Button matchCase;
- Button matchWord;
- Button findButton;
- Button down;
- FindListener findHandler;
-
-/**
- * Class constructor that sets the parent shell and the table widget that
- * the dialog will search.
- *
- * @param parent Shell
- * The shell that is the parent of the dialog.
- */
-public SearchDialog(Shell parent) {
- shell = new Shell(parent, SWT.CLOSE | SWT.BORDER | SWT.TITLE);
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- shell.setLayout(layout);
- shell.setText(resAddressBook.getString("Search_dialog_title"));
- shell.addShellListener(new ShellAdapter(){
- public void shellClosed(ShellEvent e) {
- // don't dispose of the shell, just hide it for later use
- e.doit = false;
- shell.setVisible(false);
- }
- });
-
- Label label = new Label(shell, SWT.LEFT);
- label.setText(resAddressBook.getString("Dialog_find_what"));
- searchText = new Text(shell, SWT.BORDER);
- GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
- gridData.widthHint = 200;
- searchText.setLayoutData(gridData);
- searchText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- boolean enableFind = (searchText.getCharCount() != 0);
- findButton.setEnabled(enableFind);
- }
- });
-
- searchAreaLabel = new Label(shell, SWT.LEFT);
- searchArea = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY);
- gridData = new GridData(GridData.FILL_HORIZONTAL);
- gridData.widthHint = 200;
- searchArea.setLayoutData(gridData);
-
- matchCase = new Button(shell, SWT.CHECK);
- matchCase.setText(resAddressBook.getString("Dialog_match_case"));
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- matchCase.setLayoutData(gridData);
-
- matchWord = new Button(shell, SWT.CHECK);
- matchWord.setText(resAddressBook.getString("Dialog_match_word"));
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- matchWord.setLayoutData(gridData);
-
- Group direction = new Group(shell, SWT.NONE);
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- direction.setLayoutData(gridData);
- direction.setLayout (new FillLayout ());
- direction.setText(resAddressBook.getString("Dialog_direction"));
-
- Button up = new Button(direction, SWT.RADIO);
- up.setText(resAddressBook.getString("Dialog_dir_up"));
- up.setSelection(false);
-
- down = new Button(direction, SWT.RADIO);
- down.setText(resAddressBook.getString("Dialog_dir_down"));
- down.setSelection(true);
-
- Composite composite = new Composite(shell, SWT.NONE);
- gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gridData.horizontalSpan = 2;
- composite.setLayoutData(gridData);
- layout = new GridLayout();
- layout.numColumns = 2;
- layout.makeColumnsEqualWidth = true;
- composite.setLayout(layout);
-
- findButton = new Button(composite, SWT.PUSH);
- findButton.setText(resAddressBook.getString("Dialog_find"));
- findButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
- findButton.setEnabled(false);
- findButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (!findHandler.find()){
- MessageBox box = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK | SWT.PRIMARY_MODAL);
- box.setText(shell.getText());
- box.setMessage(resAddressBook.getString("Cannot_find") + "\"" + searchText.getText() + "\"");
- box.open();
- }
- }
- });
-
- Button cancelButton = new Button(composite, SWT.PUSH);
- cancelButton.setText(resAddressBook.getString("Cancel"));
- cancelButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
- cancelButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- shell.setVisible(false);
- }
- });
-
- shell.pack();
-}
-public String getSearchAreaLabel(String label) {
- return searchAreaLabel.getText();
-}
-
-public String[] getsearchAreaNames() {
- return searchArea.getItems();
-}
-public boolean getMatchCase() {
- return matchCase.getSelection();
-}
-public boolean getMatchWord() {
- return matchWord.getSelection();
-}
-public String getSearchString() {
- return searchText.getText();
-}
-public boolean getSearchDown(){
- return down.getSelection();
-}
-public int getSelectedSearchArea() {
- return searchArea.getSelectionIndex();
-}
-public void open() {
- if (shell.isVisible()) {
- shell.setFocus();
- } else {
- shell.open();
- }
- searchText.setFocus();
-}
-public void setSearchAreaNames(String[] names) {
- for (int i = 0; i < names.length; i++) {
- searchArea.add(names[i]);
- }
- searchArea.select(0);
-}
-public void setSearchAreaLabel(String label) {
- searchAreaLabel.setText(label);
-}
-public void setMatchCase(boolean match) {
- matchCase.setSelection(match);
-}
-public void setMatchWord(boolean match) {
- matchWord.setSelection(match);
-}
-public void setSearchDown(boolean searchDown){
- down.setSelection(searchDown);
-}
-public void setSearchString(String searchString) {
- searchText.setText(searchString);
-}
-
-public void setSelectedSearchArea(int index) {
- searchArea.select(index);
-}
-public void addFindListener(FindListener listener) {
- this.findHandler = listener;
-}
-public void removeFindListener(FindListener listener) {
- this.findHandler = null;
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+/* Imports */
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+import java.util.ResourceBundle;
+
+/**
+ * SearchDialog is a simple class that uses <code>org.eclipse.swt</code>
+ * libraries to implement a basic search dialog.
+ */
+public class SearchDialog {
+
+ private static ResourceBundle resAddressBook = ResourceBundle.getBundle("examples_addressbook");
+
+ Shell shell;
+ Text searchText;
+ Combo searchArea;
+ Label searchAreaLabel;
+ Button matchCase;
+ Button matchWord;
+ Button findButton;
+ Button down;
+ FindListener findHandler;
+
+/**
+ * Class constructor that sets the parent shell and the table widget that
+ * the dialog will search.
+ *
+ * @param parent Shell
+ * The shell that is the parent of the dialog.
+ */
+public SearchDialog(Shell parent) {
+ shell = new Shell(parent, SWT.CLOSE | SWT.BORDER | SWT.TITLE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ shell.setLayout(layout);
+ shell.setText(resAddressBook.getString("Search_dialog_title"));
+ shell.addShellListener(new ShellAdapter(){
+ public void shellClosed(ShellEvent e) {
+ // don't dispose of the shell, just hide it for later use
+ e.doit = false;
+ shell.setVisible(false);
+ }
+ });
+
+ Label label = new Label(shell, SWT.LEFT);
+ label.setText(resAddressBook.getString("Dialog_find_what"));
+ searchText = new Text(shell, SWT.BORDER);
+ GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
+ gridData.widthHint = 200;
+ searchText.setLayoutData(gridData);
+ searchText.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ boolean enableFind = (searchText.getCharCount() != 0);
+ findButton.setEnabled(enableFind);
+ }
+ });
+
+ searchAreaLabel = new Label(shell, SWT.LEFT);
+ searchArea = new Combo(shell, SWT.DROP_DOWN | SWT.READ_ONLY);
+ gridData = new GridData(GridData.FILL_HORIZONTAL);
+ gridData.widthHint = 200;
+ searchArea.setLayoutData(gridData);
+
+ matchCase = new Button(shell, SWT.CHECK);
+ matchCase.setText(resAddressBook.getString("Dialog_match_case"));
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ matchCase.setLayoutData(gridData);
+
+ matchWord = new Button(shell, SWT.CHECK);
+ matchWord.setText(resAddressBook.getString("Dialog_match_word"));
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ matchWord.setLayoutData(gridData);
+
+ Group direction = new Group(shell, SWT.NONE);
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ direction.setLayoutData(gridData);
+ direction.setLayout (new FillLayout ());
+ direction.setText(resAddressBook.getString("Dialog_direction"));
+
+ Button up = new Button(direction, SWT.RADIO);
+ up.setText(resAddressBook.getString("Dialog_dir_up"));
+ up.setSelection(false);
+
+ down = new Button(direction, SWT.RADIO);
+ down.setText(resAddressBook.getString("Dialog_dir_down"));
+ down.setSelection(true);
+
+ Composite composite = new Composite(shell, SWT.NONE);
+ gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
+ gridData.horizontalSpan = 2;
+ composite.setLayoutData(gridData);
+ layout = new GridLayout();
+ layout.numColumns = 2;
+ layout.makeColumnsEqualWidth = true;
+ composite.setLayout(layout);
+
+ findButton = new Button(composite, SWT.PUSH);
+ findButton.setText(resAddressBook.getString("Dialog_find"));
+ findButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
+ findButton.setEnabled(false);
+ findButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ if (!findHandler.find()){
+ MessageBox box = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK | SWT.PRIMARY_MODAL);
+ box.setText(shell.getText());
+ box.setMessage(resAddressBook.getString("Cannot_find") + "\"" + searchText.getText() + "\"");
+ box.open();
+ }
+ }
+ });
+
+ Button cancelButton = new Button(composite, SWT.PUSH);
+ cancelButton.setText(resAddressBook.getString("Cancel"));
+ cancelButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ shell.setVisible(false);
+ }
+ });
+
+ shell.pack();
+}
+public String getSearchAreaLabel(String label) {
+ return searchAreaLabel.getText();
+}
+
+public String[] getsearchAreaNames() {
+ return searchArea.getItems();
+}
+public boolean getMatchCase() {
+ return matchCase.getSelection();
+}
+public boolean getMatchWord() {
+ return matchWord.getSelection();
+}
+public String getSearchString() {
+ return searchText.getText();
+}
+public boolean getSearchDown(){
+ return down.getSelection();
+}
+public int getSelectedSearchArea() {
+ return searchArea.getSelectionIndex();
+}
+public void open() {
+ if (shell.isVisible()) {
+ shell.setFocus();
+ } else {
+ shell.open();
+ }
+ searchText.setFocus();
+}
+public void setSearchAreaNames(String[] names) {
+ for (int i = 0; i < names.length; i++) {
+ searchArea.add(names[i]);
+ }
+ searchArea.select(0);
+}
+public void setSearchAreaLabel(String label) {
+ searchAreaLabel.setText(label);
+}
+public void setMatchCase(boolean match) {
+ matchCase.setSelection(match);
+}
+public void setMatchWord(boolean match) {
+ matchWord.setSelection(match);
+}
+public void setSearchDown(boolean searchDown){
+ down.setSelection(searchDown);
+}
+public void setSearchString(String searchString) {
+ searchText.setText(searchString);
+}
+
+public void setSelectedSearchArea(int index) {
+ searchArea.select(index);
+}
+public void addFindListener(FindListener listener) {
+ this.findHandler = listener;
+}
+public void removeFindListener(FindListener listener) {
+ this.findHandler = null;
+}
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/AlignableTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/AlignableTab.java
index 43346a8946..148c6c06d5 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/AlignableTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/AlignableTab.java
@@ -1,85 +1,85 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-/**
- * <code>AlignableTab</code> is the abstract
- * superclass of example controls that can be
- * aligned.
- */
-abstract class AlignableTab extends Tab {
-
- /* Allignment Controls */
- Button leftButton, rightButton, centerButton;
-
- /* Alignment Group */
- Group allignmentGroup;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- AlignableTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Control" group.
- */
- void createControlGroup () {
- super.createControlGroup ();
-
- /* Create the group */
- allignmentGroup = new Group (controlGroup, SWT.NONE);
- allignmentGroup.setLayout (new GridLayout ());
- allignmentGroup.setLayoutData (new GridData(GridData.HORIZONTAL_ALIGN_FILL |
- GridData.VERTICAL_ALIGN_FILL));
- allignmentGroup.setText (ControlExample.getResourceString("Alignment"));
-
- /* Create the controls */
- leftButton = new Button (allignmentGroup, SWT.RADIO);
- leftButton.setText (ControlExample.getResourceString("Left"));
- centerButton = new Button (allignmentGroup, SWT.RADIO);
- centerButton.setText(ControlExample.getResourceString("Center"));
- rightButton = new Button (allignmentGroup, SWT.RADIO);
- rightButton.setText (ControlExample.getResourceString("Right"));
-
- /* Add the listeners */
- SelectionListener selectionListener = new SelectionAdapter () {
- public void widgetSelected(SelectionEvent event) {
- if (!((Button) event.widget).getSelection ()) return;
- setExampleWidgetAlignment ();
- };
- };
- leftButton.addSelectionListener (selectionListener);
- centerButton.addSelectionListener (selectionListener);
- rightButton.addSelectionListener (selectionListener);
- }
-
- /**
- * Sets the alignment of the "Example" widgets.
- */
- abstract void setExampleWidgetAlignment ();
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- Control [] controls = getExampleWidgets ();
- if (controls.length != 0) {
- leftButton.setSelection ((controls [0].getStyle () & SWT.LEFT) != 0);
- centerButton.setSelection ((controls [0].getStyle () & SWT.CENTER) != 0);
- rightButton.setSelection ((controls [0].getStyle () & SWT.RIGHT) != 0);
- }
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+/**
+ * <code>AlignableTab</code> is the abstract
+ * superclass of example controls that can be
+ * aligned.
+ */
+abstract class AlignableTab extends Tab {
+
+ /* Allignment Controls */
+ Button leftButton, rightButton, centerButton;
+
+ /* Alignment Group */
+ Group allignmentGroup;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ AlignableTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Control" group.
+ */
+ void createControlGroup () {
+ super.createControlGroup ();
+
+ /* Create the group */
+ allignmentGroup = new Group (controlGroup, SWT.NONE);
+ allignmentGroup.setLayout (new GridLayout ());
+ allignmentGroup.setLayoutData (new GridData(GridData.HORIZONTAL_ALIGN_FILL |
+ GridData.VERTICAL_ALIGN_FILL));
+ allignmentGroup.setText (ControlExample.getResourceString("Alignment"));
+
+ /* Create the controls */
+ leftButton = new Button (allignmentGroup, SWT.RADIO);
+ leftButton.setText (ControlExample.getResourceString("Left"));
+ centerButton = new Button (allignmentGroup, SWT.RADIO);
+ centerButton.setText(ControlExample.getResourceString("Center"));
+ rightButton = new Button (allignmentGroup, SWT.RADIO);
+ rightButton.setText (ControlExample.getResourceString("Right"));
+
+ /* Add the listeners */
+ SelectionListener selectionListener = new SelectionAdapter () {
+ public void widgetSelected(SelectionEvent event) {
+ if (!((Button) event.widget).getSelection ()) return;
+ setExampleWidgetAlignment ();
+ };
+ };
+ leftButton.addSelectionListener (selectionListener);
+ centerButton.addSelectionListener (selectionListener);
+ rightButton.addSelectionListener (selectionListener);
+ }
+
+ /**
+ * Sets the alignment of the "Example" widgets.
+ */
+ abstract void setExampleWidgetAlignment ();
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ Control [] controls = getExampleWidgets ();
+ if (controls.length != 0) {
+ leftButton.setSelection ((controls [0].getStyle () & SWT.LEFT) != 0);
+ centerButton.setSelection ((controls [0].getStyle () & SWT.CENTER) != 0);
+ rightButton.setSelection ((controls [0].getStyle () & SWT.RIGHT) != 0);
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ButtonTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ButtonTab.java
index fcc841449a..eb0b6c3898 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ButtonTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ButtonTab.java
@@ -1,193 +1,193 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-/**
- * <code>ButtonTab</code> is the class that
- * demonstrates SWT buttons.
- */
-class ButtonTab extends AlignableTab {
-
- /* Example widgets and groups that contain them */
- Button button1, button2, button3, button4, button5, button6;
- Group textButtonGroup, imageButtonGroup;
-
- /* Allignment widgets added to the "Control" group */
- Button upButton, downButton;
-
- /* Style widgets added to the "Style" group */
- Button pushButton, checkButton, radioButton, toggleButton, arrowButton, flatButton;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- ButtonTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Control" group.
- */
- void createControlGroup () {
- super.createControlGroup ();
-
- /* Create the controls */
- upButton = new Button (allignmentGroup, SWT.RADIO);
- upButton.setText (ControlExample.getResourceString("Up"));
- downButton = new Button (allignmentGroup, SWT.RADIO);
- downButton.setText (ControlExample.getResourceString("Down"));
-
- /* Add the listeners */
- SelectionListener selectionListener = new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- if (!((Button) event.widget).getSelection()) return;
- setExampleWidgetAlignment ();
- };
- };
- upButton.addSelectionListener(selectionListener);
- downButton.addSelectionListener(selectionListener);
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for text buttons */
- textButtonGroup = new Group(exampleGroup, SWT.NONE);
- GridLayout gridLayout = new GridLayout ();
- textButtonGroup.setLayout(gridLayout);
- gridLayout.numColumns = 3;
- textButtonGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- textButtonGroup.setText (ControlExample.getResourceString("Text_Buttons"));
-
- /* Create a group for the image buttons */
- imageButtonGroup = new Group(exampleGroup, SWT.NONE);
- gridLayout = new GridLayout();
- imageButtonGroup.setLayout(gridLayout);
- gridLayout.numColumns = 3;
- imageButtonGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- imageButtonGroup.setText (ControlExample.getResourceString("Image_Buttons"));
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
-
- /* Compute the widget style */
- int style = SWT.NONE;
- if (pushButton.getSelection()) style |= SWT.PUSH;
- if (checkButton.getSelection()) style |= SWT.CHECK;
- if (radioButton.getSelection()) style |= SWT.RADIO;
- if (toggleButton.getSelection()) style |= SWT.TOGGLE;
- if (arrowButton.getSelection()) style |= SWT.ARROW;
- if (flatButton.getSelection()) style |= SWT.FLAT;
- if (borderButton.getSelection()) style |= SWT.BORDER;
-
- /* Create the example widgets */
- button1 = new Button(textButtonGroup, style);
- button1.setText(ControlExample.getResourceString("One"));
- button2 = new Button(textButtonGroup, style);
- button2.setText(ControlExample.getResourceString("Two"));
- button3 = new Button(textButtonGroup, style);
- button3.setText(ControlExample.getResourceString("Three"));
- button4 = new Button(imageButtonGroup, style);
- button4.setImage(instance.images[ControlExample.ciClosedFolder]);
- button5 = new Button(imageButtonGroup, style);
- button5.setImage(instance.images[ControlExample.ciOpenFolder]);
- button6 = new Button(imageButtonGroup, style);
- button6.setImage(instance.images[ControlExample.ciTarget]);
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup() {
- super.createStyleGroup ();
-
- /* Create the extra widgets */
- pushButton = new Button (styleGroup, SWT.RADIO);
- pushButton.setText("SWT.PUSH");
- checkButton = new Button (styleGroup, SWT.RADIO);
- checkButton.setText ("SWT.CHECK");
- radioButton = new Button (styleGroup, SWT.RADIO);
- radioButton.setText ("SWT.RADIO");
- toggleButton = new Button (styleGroup, SWT.RADIO);
- toggleButton.setText ("SWT.TOGGLE");
- arrowButton = new Button (styleGroup, SWT.RADIO);
- arrowButton.setText ("SWT.ARROW");
- flatButton = new Button (styleGroup, SWT.CHECK);
- flatButton.setText ("SWT.FLAT");
- borderButton = new Button (styleGroup, SWT.CHECK);
- borderButton.setText ("SWT.BORDER");
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {button1, button2, button3, button4, button5, button6};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Button";
- }
-
- /**
- * Sets the alignment of the "Example" widgets.
- */
- void setExampleWidgetAlignment () {
- int allignment = 0;
- if (leftButton.getSelection ()) allignment = SWT.LEFT;
- if (centerButton.getSelection ()) allignment = SWT.CENTER;
- if (rightButton.getSelection ()) allignment = SWT.RIGHT;
- if (upButton.getSelection ()) allignment = SWT.UP;
- if (downButton.getSelection ()) allignment = SWT.DOWN;
- button1.setAlignment (allignment);
- button2.setAlignment (allignment);
- button3.setAlignment (allignment);
- button4.setAlignment (allignment);
- button5.setAlignment (allignment);
- button6.setAlignment (allignment);
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- if (arrowButton.getSelection ()) {
- upButton.setEnabled (true);
- centerButton.setEnabled (false);
- downButton.setEnabled (true);
- } else {
- upButton.setEnabled (false);
- centerButton.setEnabled (true);
- downButton.setEnabled (false);
- }
- upButton.setSelection ((button1.getStyle () & SWT.UP) != 0);
- downButton.setSelection ((button1.getStyle () & SWT.DOWN) != 0);
- pushButton.setSelection ((button1.getStyle () & SWT.PUSH) != 0);
- checkButton.setSelection ((button1.getStyle () & SWT.CHECK) != 0);
- radioButton.setSelection ((button1.getStyle () & SWT.RADIO) != 0);
- toggleButton.setSelection ((button1.getStyle () & SWT.TOGGLE) != 0);
- arrowButton.setSelection ((button1.getStyle () & SWT.ARROW) != 0);
- flatButton.setSelection ((button1.getStyle () & SWT.FLAT) != 0);
- borderButton.setSelection ((button1.getStyle () & SWT.BORDER) != 0);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+/**
+ * <code>ButtonTab</code> is the class that
+ * demonstrates SWT buttons.
+ */
+class ButtonTab extends AlignableTab {
+
+ /* Example widgets and groups that contain them */
+ Button button1, button2, button3, button4, button5, button6;
+ Group textButtonGroup, imageButtonGroup;
+
+ /* Allignment widgets added to the "Control" group */
+ Button upButton, downButton;
+
+ /* Style widgets added to the "Style" group */
+ Button pushButton, checkButton, radioButton, toggleButton, arrowButton, flatButton;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ ButtonTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Control" group.
+ */
+ void createControlGroup () {
+ super.createControlGroup ();
+
+ /* Create the controls */
+ upButton = new Button (allignmentGroup, SWT.RADIO);
+ upButton.setText (ControlExample.getResourceString("Up"));
+ downButton = new Button (allignmentGroup, SWT.RADIO);
+ downButton.setText (ControlExample.getResourceString("Down"));
+
+ /* Add the listeners */
+ SelectionListener selectionListener = new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ if (!((Button) event.widget).getSelection()) return;
+ setExampleWidgetAlignment ();
+ };
+ };
+ upButton.addSelectionListener(selectionListener);
+ downButton.addSelectionListener(selectionListener);
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for text buttons */
+ textButtonGroup = new Group(exampleGroup, SWT.NONE);
+ GridLayout gridLayout = new GridLayout ();
+ textButtonGroup.setLayout(gridLayout);
+ gridLayout.numColumns = 3;
+ textButtonGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ textButtonGroup.setText (ControlExample.getResourceString("Text_Buttons"));
+
+ /* Create a group for the image buttons */
+ imageButtonGroup = new Group(exampleGroup, SWT.NONE);
+ gridLayout = new GridLayout();
+ imageButtonGroup.setLayout(gridLayout);
+ gridLayout.numColumns = 3;
+ imageButtonGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ imageButtonGroup.setText (ControlExample.getResourceString("Image_Buttons"));
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (pushButton.getSelection()) style |= SWT.PUSH;
+ if (checkButton.getSelection()) style |= SWT.CHECK;
+ if (radioButton.getSelection()) style |= SWT.RADIO;
+ if (toggleButton.getSelection()) style |= SWT.TOGGLE;
+ if (arrowButton.getSelection()) style |= SWT.ARROW;
+ if (flatButton.getSelection()) style |= SWT.FLAT;
+ if (borderButton.getSelection()) style |= SWT.BORDER;
+
+ /* Create the example widgets */
+ button1 = new Button(textButtonGroup, style);
+ button1.setText(ControlExample.getResourceString("One"));
+ button2 = new Button(textButtonGroup, style);
+ button2.setText(ControlExample.getResourceString("Two"));
+ button3 = new Button(textButtonGroup, style);
+ button3.setText(ControlExample.getResourceString("Three"));
+ button4 = new Button(imageButtonGroup, style);
+ button4.setImage(instance.images[ControlExample.ciClosedFolder]);
+ button5 = new Button(imageButtonGroup, style);
+ button5.setImage(instance.images[ControlExample.ciOpenFolder]);
+ button6 = new Button(imageButtonGroup, style);
+ button6.setImage(instance.images[ControlExample.ciTarget]);
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup() {
+ super.createStyleGroup ();
+
+ /* Create the extra widgets */
+ pushButton = new Button (styleGroup, SWT.RADIO);
+ pushButton.setText("SWT.PUSH");
+ checkButton = new Button (styleGroup, SWT.RADIO);
+ checkButton.setText ("SWT.CHECK");
+ radioButton = new Button (styleGroup, SWT.RADIO);
+ radioButton.setText ("SWT.RADIO");
+ toggleButton = new Button (styleGroup, SWT.RADIO);
+ toggleButton.setText ("SWT.TOGGLE");
+ arrowButton = new Button (styleGroup, SWT.RADIO);
+ arrowButton.setText ("SWT.ARROW");
+ flatButton = new Button (styleGroup, SWT.CHECK);
+ flatButton.setText ("SWT.FLAT");
+ borderButton = new Button (styleGroup, SWT.CHECK);
+ borderButton.setText ("SWT.BORDER");
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {button1, button2, button3, button4, button5, button6};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Button";
+ }
+
+ /**
+ * Sets the alignment of the "Example" widgets.
+ */
+ void setExampleWidgetAlignment () {
+ int allignment = 0;
+ if (leftButton.getSelection ()) allignment = SWT.LEFT;
+ if (centerButton.getSelection ()) allignment = SWT.CENTER;
+ if (rightButton.getSelection ()) allignment = SWT.RIGHT;
+ if (upButton.getSelection ()) allignment = SWT.UP;
+ if (downButton.getSelection ()) allignment = SWT.DOWN;
+ button1.setAlignment (allignment);
+ button2.setAlignment (allignment);
+ button3.setAlignment (allignment);
+ button4.setAlignment (allignment);
+ button5.setAlignment (allignment);
+ button6.setAlignment (allignment);
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ if (arrowButton.getSelection ()) {
+ upButton.setEnabled (true);
+ centerButton.setEnabled (false);
+ downButton.setEnabled (true);
+ } else {
+ upButton.setEnabled (false);
+ centerButton.setEnabled (true);
+ downButton.setEnabled (false);
+ }
+ upButton.setSelection ((button1.getStyle () & SWT.UP) != 0);
+ downButton.setSelection ((button1.getStyle () & SWT.DOWN) != 0);
+ pushButton.setSelection ((button1.getStyle () & SWT.PUSH) != 0);
+ checkButton.setSelection ((button1.getStyle () & SWT.CHECK) != 0);
+ radioButton.setSelection ((button1.getStyle () & SWT.RADIO) != 0);
+ toggleButton.setSelection ((button1.getStyle () & SWT.TOGGLE) != 0);
+ arrowButton.setSelection ((button1.getStyle () & SWT.ARROW) != 0);
+ flatButton.setSelection ((button1.getStyle () & SWT.FLAT) != 0);
+ borderButton.setSelection ((button1.getStyle () & SWT.BORDER) != 0);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ComboTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ComboTab.java
index 63f405a1bd..88d5299cfd 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ComboTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ComboTab.java
@@ -1,114 +1,114 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-
-class ComboTab extends Tab {
-
- /* Example widgets and groups that contain them */
- Combo combo1;
- Group comboGroup;
-
- /* Style widgets added to the "Style" group */
- Button dropDownButton, readOnlyButton, simpleButton;
-
- static String [] ListData = {ControlExample.getResourceString("ListData0_0"),
- ControlExample.getResourceString("ListData0_1"),
- ControlExample.getResourceString("ListData0_2"),
- ControlExample.getResourceString("ListData0_3"),
- ControlExample.getResourceString("ListData0_4"),
- ControlExample.getResourceString("ListData0_5"),
- ControlExample.getResourceString("ListData0_6"),
- ControlExample.getResourceString("ListData0_7"),
- ControlExample.getResourceString("ListData0_8")};
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- ComboTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for the combo box */
- comboGroup = new Group (exampleGroup, SWT.NONE);
- comboGroup.setLayout (new GridLayout ());
- comboGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- comboGroup.setText ("Combo");
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
-
- /* Compute the widget style */
- int style = SWT.NONE;
- if (dropDownButton.getSelection ()) style |= SWT.DROP_DOWN;
- if (readOnlyButton.getSelection ()) style |= SWT.READ_ONLY;
- if (simpleButton.getSelection ()) style |= SWT.SIMPLE;
- if (borderButton.getSelection ()) style |= SWT.BORDER;
-
- /* Create the example widgets */
- combo1 = new Combo (comboGroup, style);
- combo1.setItems (ListData);
- if (ListData.length >= 3) {
- combo1.setText(ListData [2]);
- }
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup () {
- super.createStyleGroup ();
-
- /* Create the extra widgets */
- dropDownButton = new Button (styleGroup, SWT.RADIO);
- dropDownButton.setText ("SWT.DROP_DOWN");
- simpleButton = new Button (styleGroup, SWT.RADIO);
- simpleButton.setText("SWT.SIMPLE");
- readOnlyButton = new Button (styleGroup, SWT.CHECK);
- readOnlyButton.setText ("SWT.READ_ONLY");
- borderButton = new Button (styleGroup, SWT.CHECK);
- borderButton.setText ("SWT.BORDER");
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {combo1};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Combo";
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- dropDownButton.setSelection ((combo1.getStyle () & SWT.DROP_DOWN) != 0);
- simpleButton.setSelection ((combo1.getStyle () & SWT.SIMPLE) != 0);
- readOnlyButton.setSelection ((combo1.getStyle () & SWT.READ_ONLY) != 0);
- borderButton.setSelection ((combo1.getStyle () & SWT.BORDER) != 0);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+
+class ComboTab extends Tab {
+
+ /* Example widgets and groups that contain them */
+ Combo combo1;
+ Group comboGroup;
+
+ /* Style widgets added to the "Style" group */
+ Button dropDownButton, readOnlyButton, simpleButton;
+
+ static String [] ListData = {ControlExample.getResourceString("ListData0_0"),
+ ControlExample.getResourceString("ListData0_1"),
+ ControlExample.getResourceString("ListData0_2"),
+ ControlExample.getResourceString("ListData0_3"),
+ ControlExample.getResourceString("ListData0_4"),
+ ControlExample.getResourceString("ListData0_5"),
+ ControlExample.getResourceString("ListData0_6"),
+ ControlExample.getResourceString("ListData0_7"),
+ ControlExample.getResourceString("ListData0_8")};
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ ComboTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for the combo box */
+ comboGroup = new Group (exampleGroup, SWT.NONE);
+ comboGroup.setLayout (new GridLayout ());
+ comboGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ comboGroup.setText ("Combo");
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (dropDownButton.getSelection ()) style |= SWT.DROP_DOWN;
+ if (readOnlyButton.getSelection ()) style |= SWT.READ_ONLY;
+ if (simpleButton.getSelection ()) style |= SWT.SIMPLE;
+ if (borderButton.getSelection ()) style |= SWT.BORDER;
+
+ /* Create the example widgets */
+ combo1 = new Combo (comboGroup, style);
+ combo1.setItems (ListData);
+ if (ListData.length >= 3) {
+ combo1.setText(ListData [2]);
+ }
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup () {
+ super.createStyleGroup ();
+
+ /* Create the extra widgets */
+ dropDownButton = new Button (styleGroup, SWT.RADIO);
+ dropDownButton.setText ("SWT.DROP_DOWN");
+ simpleButton = new Button (styleGroup, SWT.RADIO);
+ simpleButton.setText("SWT.SIMPLE");
+ readOnlyButton = new Button (styleGroup, SWT.CHECK);
+ readOnlyButton.setText ("SWT.READ_ONLY");
+ borderButton = new Button (styleGroup, SWT.CHECK);
+ borderButton.setText ("SWT.BORDER");
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {combo1};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Combo";
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ dropDownButton.setSelection ((combo1.getStyle () & SWT.DROP_DOWN) != 0);
+ simpleButton.setSelection ((combo1.getStyle () & SWT.SIMPLE) != 0);
+ readOnlyButton.setSelection ((combo1.getStyle () & SWT.READ_ONLY) != 0);
+ borderButton.setSelection ((combo1.getStyle () & SWT.BORDER) != 0);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ControlExample.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ControlExample.java
index afbb3ed9bb..9e33ffcb64 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ControlExample.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ControlExample.java
@@ -1,331 +1,331 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.custom.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.widgets.*;
-
-import java.text.*;
-import java.util.*;
-
-public class ControlExample {
- private static ResourceBundle resourceBundle =
- ResourceBundle.getBundle("examples_control");
- private ShellTab shellTab;
- private SashForm form;
- private TabFolder tabFolder;
- private Text eventConsole;
- private boolean logging = false;
- private boolean [] eventsFilter = new boolean [35];
- static boolean standAlone = false;
- Image images[];
-
- static final int ciClosedFolder = 0, ciOpenFolder = 1, ciTarget = 2;
- static final String[] imageLocations = {
- "closedFolder.gif",
- "openFolder.gif",
- "target.gif" };
- static final String [] EVENT_TYPES = { "",
- "KeyDown", "KeyUp", "MouseDown", "MouseUp", "MouseMove", "MouseEnter",
- "MouseExit", "MouseDoubleClick", "Paint", "Move", "Resize", "Dispose",
- "Selection", "DefaultSelection", "FocusIn", "FocusOut", "Expand", "Collapse",
- "Iconify", "Deiconify", "Close", "Show", "Hide", "Modify",
- "Verify", "Activate", "Deactivate", "Help", "DragDetect", "Arm",
- "Traverse", "MouseHover", "HardKeyDown", "HardKeyUp"
- };
- static final int [] DEFAULT_FILTER = {
- SWT.KeyDown, SWT.KeyUp, SWT.MouseDown, SWT.MouseUp, SWT.MouseDoubleClick, SWT.Selection,
- SWT.DefaultSelection, SWT.Expand, SWT.Collapse, SWT.Iconify, SWT.Deiconify, SWT.Close,
- SWT.Show, SWT.Hide, SWT.Modify, SWT.Verify, SWT.Activate, SWT.Deactivate,
- SWT.Help, SWT.DragDetect, SWT.Arm, SWT.Traverse, SWT.HardKeyDown, SWT.HardKeyUp
- };
-
- /**
- * Creates an instance of a ControlExample embedded inside
- * the supplied parent Composite.
- *
- * @param parent the container of the example
- */
- public ControlExample(Composite parent) {
- initResources();
- form = new SashForm (parent,SWT.VERTICAL);
- tabFolder = new TabFolder (form, SWT.NONE);
- Tab [] tabs = createTabs();
- for (int i=0; i<tabs.length; i++) {
- TabItem item = new TabItem (tabFolder, SWT.NONE);
- item.setText (tabs [i].getTabText ());
- item.setControl (tabs [i].createTabFolderPage (tabFolder));
- item.setData (tabs [i]);
- }
- if (standAlone) {
- createControlExampleMenu (parent.getShell ());
- eventConsole = new Text(form, SWT.MULTI | SWT.V_SCROLL);
- form.setWeights(new int[] {100, 0});
- createEventConsolePopup (eventConsole);
- for (int i = 0; i < DEFAULT_FILTER.length; i++) {
- eventsFilter [DEFAULT_FILTER [i]] = true;
- }
- }
- }
-
- /**
- * Hide the event logger.
- */
- void closeEventConsole() {
- logging = false;
- form.setWeights(new int[] {100, 0});
- eventConsole.setEnabled (false);
- TabItem[] tabs = tabFolder.getItems ();
- for (int i = 0; i < tabs.length; i++) {
- Tab tab = (Tab) tabs[i].getData ();
- tab.recreateExampleWidgets ();
- }
- }
-
- /**
- * Create the menubar
- */
- void createControlExampleMenu(final Shell shell) {
- Menu bar = new Menu (shell, SWT.BAR);
- MenuItem consoleItem = new MenuItem (bar, SWT.CASCADE);
- consoleItem.setText ("Controls");
- shell.setMenuBar (bar);
- Menu dropDown = new Menu (bar);
- consoleItem.setMenu (dropDown);
-
- final MenuItem showEvents = new MenuItem (dropDown, SWT.CHECK);
- showEvents.setText ("&Log Events");
- showEvents.addListener (SWT.Selection, new Listener () {
- public void handleEvent (Event e) {
- if (showEvents.getSelection()) {
- openEventConsole (shell);
- } else {
- closeEventConsole ();
- }
- }
- });
-
- final MenuItem exit = new MenuItem (dropDown, SWT.NONE);
- exit.setText ("E&xit");
- exit.addListener (SWT.Selection, new Listener () {
- public void handleEvent (Event e) {
- shell.dispose();
- }
- });
- }
-
- /**
- * Create the menubar
- */
- void createEventConsolePopup (final Text console) {
- Menu popup = new Menu (console.getShell (), SWT.POP_UP);
- console.setMenu (popup);
-
- MenuItem copy = new MenuItem (popup, SWT.PUSH);
- copy.setAccelerator(SWT.MOD1 + 'C');
- copy.setText ("&Copy\tCtrl+C");
- copy.addListener (SWT.Selection, new Listener () {
- public void handleEvent (Event event) {
- console.copy ();
- }
- });
- MenuItem selectAll = new MenuItem (popup, SWT.PUSH);
- selectAll.setAccelerator(SWT.MOD1 + 'A');
- selectAll.setText("Select &All");
- selectAll.addListener (SWT.Selection, new Listener () {
- public void handleEvent (Event event) {
- console.selectAll ();
- }
- });
- MenuItem clear = new MenuItem (popup, SWT.PUSH);
- clear.setText ("C&lear");
- clear.addListener (SWT.Selection, new Listener () {
- public void handleEvent (Event event) {
- console.setText ("");
- }
- });
- }
-
- /**
- * Answers the set of example Tabs
- */
- Tab[] createTabs() {
- return new Tab [] {
- new ButtonTab (this),
- new ComboTab (this),
- new CoolBarTab (this),
- new DialogTab (this),
- new LabelTab (this),
- new ListTab (this),
- new ProgressBarTab (this),
- new SashTab (this),
- shellTab = new ShellTab(this),
- new SliderTab (this),
- new TableTab (this),
- new TextTab (this),
- new ToolBarTab (this),
- new TreeTab (this),
- };
- }
-
- /**
- * Disposes of all resources associated with a particular
- * instance of the ControlExample.
- */
- public void dispose() {
- /*
- * Destroy any shells that may have been created
- * by the Shells tab. When a shell is disposed,
- * all child shells are also disposed. Therefore
- * it is necessary to check for disposed shells
- * in the shells list to avoid disposing a shell
- * twice.
- */
- if (shellTab != null) shellTab.closeAllShells ();
- shellTab = null;
- tabFolder = null;
- freeResources();
- }
-
- /**
- * Frees the resources
- */
- void freeResources() {
- if (images != null) {
- for (int i = 0; i < images.length; ++i) {
- final Image image = images[i];
- if (image != null) image.dispose();
- }
- images = null;
- }
- }
-
- /**
- * Gets a string from the resource bundle.
- * We don't want to crash because of a missing String.
- * Returns the key if not found.
- */
- static String getResourceString(String key) {
- try {
- return resourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Gets a string from the resource bundle and binds it
- * with the given arguments. If the key is not found,
- * return the key.
- */
- static String getResourceString(String key, Object[] args) {
- try {
- return MessageFormat.format(getResourceString(key), args);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Loads the resources
- */
- void initResources() {
- final Class clazz = ControlExample.class;
- if (resourceBundle != null) {
- try {
- if (images == null) {
- images = new Image[imageLocations.length];
-
- for (int i = 0; i < imageLocations.length; ++i) {
- ImageData source = new ImageData(clazz.getResourceAsStream(
- imageLocations[i]));
- ImageData mask = source.getTransparencyMask();
- images[i] = new Image(null, source, mask);
- }
- }
- return;
- } catch (Throwable t) {
- }
- }
- String error = (resourceBundle != null) ?
- getResourceString("error.CouldNotLoadResources") :
- "Unable to load resources";
- freeResources();
- throw new RuntimeException(error);
- }
-
- /**
- * Answers true if this example is currently logging all
- * events, and false otherwise.
- */
- public boolean isLogging () {
- return logging;
- }
- /**
- * Logs an event to the event console.
- */
- void log(Event event) {
- if (logging && eventsFilter [event.type]) {
- StringBuffer output = new StringBuffer (EVENT_TYPES[event.type]);
- output.append (": ");
- output.append (event.widget.toString ());
- output.append (" X: ");
- output.append (event.x);
- output.append (" Y: ");
- output.append (event.y);
- output.append ("\n");
- eventConsole.append (output.toString ());
- }
- }
-
- /**
- * Invokes as a standalone program.
- */
- public static void main(String[] args) {
- standAlone = true;
- Display display = new Display();
- Shell shell = new Shell(display);
- shell.setLayout(new FillLayout());
- ControlExample instance = new ControlExample(shell);
- shell.setText(getResourceString("window.title"));
- shell.open();
- while (! shell.isDisposed()) {
- if (! display.readAndDispatch()) display.sleep();
- }
- instance.dispose();
- }
-
- /**
- * Open the event logger.
- */
- void openEventConsole(Shell shell) {
- logging = true;
- form.setWeights(new int[] {80,20});
- eventConsole.setEnabled (true);
- TabItem[] tabs = tabFolder.getItems ();
- for (int i = 0; i < tabs.length; i++) {
- Tab tab = (Tab) tabs[i].getData ();
- tab.recreateExampleWidgets ();
- }
- }
-
- /**
- * Grabs input focus.
- */
- public void setFocus() {
- tabFolder.setFocus();
- }
-}
-
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.custom.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.widgets.*;
+
+import java.text.*;
+import java.util.*;
+
+public class ControlExample {
+ private static ResourceBundle resourceBundle =
+ ResourceBundle.getBundle("examples_control");
+ private ShellTab shellTab;
+ private SashForm form;
+ private TabFolder tabFolder;
+ private Text eventConsole;
+ private boolean logging = false;
+ private boolean [] eventsFilter = new boolean [35];
+ static boolean standAlone = false;
+ Image images[];
+
+ static final int ciClosedFolder = 0, ciOpenFolder = 1, ciTarget = 2;
+ static final String[] imageLocations = {
+ "closedFolder.gif",
+ "openFolder.gif",
+ "target.gif" };
+ static final String [] EVENT_TYPES = { "",
+ "KeyDown", "KeyUp", "MouseDown", "MouseUp", "MouseMove", "MouseEnter",
+ "MouseExit", "MouseDoubleClick", "Paint", "Move", "Resize", "Dispose",
+ "Selection", "DefaultSelection", "FocusIn", "FocusOut", "Expand", "Collapse",
+ "Iconify", "Deiconify", "Close", "Show", "Hide", "Modify",
+ "Verify", "Activate", "Deactivate", "Help", "DragDetect", "Arm",
+ "Traverse", "MouseHover", "HardKeyDown", "HardKeyUp"
+ };
+ static final int [] DEFAULT_FILTER = {
+ SWT.KeyDown, SWT.KeyUp, SWT.MouseDown, SWT.MouseUp, SWT.MouseDoubleClick, SWT.Selection,
+ SWT.DefaultSelection, SWT.Expand, SWT.Collapse, SWT.Iconify, SWT.Deiconify, SWT.Close,
+ SWT.Show, SWT.Hide, SWT.Modify, SWT.Verify, SWT.Activate, SWT.Deactivate,
+ SWT.Help, SWT.DragDetect, SWT.Arm, SWT.Traverse, SWT.HardKeyDown, SWT.HardKeyUp
+ };
+
+ /**
+ * Creates an instance of a ControlExample embedded inside
+ * the supplied parent Composite.
+ *
+ * @param parent the container of the example
+ */
+ public ControlExample(Composite parent) {
+ initResources();
+ form = new SashForm (parent,SWT.VERTICAL);
+ tabFolder = new TabFolder (form, SWT.NONE);
+ Tab [] tabs = createTabs();
+ for (int i=0; i<tabs.length; i++) {
+ TabItem item = new TabItem (tabFolder, SWT.NONE);
+ item.setText (tabs [i].getTabText ());
+ item.setControl (tabs [i].createTabFolderPage (tabFolder));
+ item.setData (tabs [i]);
+ }
+ if (standAlone) {
+ createControlExampleMenu (parent.getShell ());
+ eventConsole = new Text(form, SWT.MULTI | SWT.V_SCROLL);
+ form.setWeights(new int[] {100, 0});
+ createEventConsolePopup (eventConsole);
+ for (int i = 0; i < DEFAULT_FILTER.length; i++) {
+ eventsFilter [DEFAULT_FILTER [i]] = true;
+ }
+ }
+ }
+
+ /**
+ * Hide the event logger.
+ */
+ void closeEventConsole() {
+ logging = false;
+ form.setWeights(new int[] {100, 0});
+ eventConsole.setEnabled (false);
+ TabItem[] tabs = tabFolder.getItems ();
+ for (int i = 0; i < tabs.length; i++) {
+ Tab tab = (Tab) tabs[i].getData ();
+ tab.recreateExampleWidgets ();
+ }
+ }
+
+ /**
+ * Create the menubar
+ */
+ void createControlExampleMenu(final Shell shell) {
+ Menu bar = new Menu (shell, SWT.BAR);
+ MenuItem consoleItem = new MenuItem (bar, SWT.CASCADE);
+ consoleItem.setText ("Controls");
+ shell.setMenuBar (bar);
+ Menu dropDown = new Menu (bar);
+ consoleItem.setMenu (dropDown);
+
+ final MenuItem showEvents = new MenuItem (dropDown, SWT.CHECK);
+ showEvents.setText ("&Log Events");
+ showEvents.addListener (SWT.Selection, new Listener () {
+ public void handleEvent (Event e) {
+ if (showEvents.getSelection()) {
+ openEventConsole (shell);
+ } else {
+ closeEventConsole ();
+ }
+ }
+ });
+
+ final MenuItem exit = new MenuItem (dropDown, SWT.NONE);
+ exit.setText ("E&xit");
+ exit.addListener (SWT.Selection, new Listener () {
+ public void handleEvent (Event e) {
+ shell.dispose();
+ }
+ });
+ }
+
+ /**
+ * Create the menubar
+ */
+ void createEventConsolePopup (final Text console) {
+ Menu popup = new Menu (console.getShell (), SWT.POP_UP);
+ console.setMenu (popup);
+
+ MenuItem copy = new MenuItem (popup, SWT.PUSH);
+ copy.setAccelerator(SWT.MOD1 + 'C');
+ copy.setText ("&Copy\tCtrl+C");
+ copy.addListener (SWT.Selection, new Listener () {
+ public void handleEvent (Event event) {
+ console.copy ();
+ }
+ });
+ MenuItem selectAll = new MenuItem (popup, SWT.PUSH);
+ selectAll.setAccelerator(SWT.MOD1 + 'A');
+ selectAll.setText("Select &All");
+ selectAll.addListener (SWT.Selection, new Listener () {
+ public void handleEvent (Event event) {
+ console.selectAll ();
+ }
+ });
+ MenuItem clear = new MenuItem (popup, SWT.PUSH);
+ clear.setText ("C&lear");
+ clear.addListener (SWT.Selection, new Listener () {
+ public void handleEvent (Event event) {
+ console.setText ("");
+ }
+ });
+ }
+
+ /**
+ * Answers the set of example Tabs
+ */
+ Tab[] createTabs() {
+ return new Tab [] {
+ new ButtonTab (this),
+ new ComboTab (this),
+ new CoolBarTab (this),
+ new DialogTab (this),
+ new LabelTab (this),
+ new ListTab (this),
+ new ProgressBarTab (this),
+ new SashTab (this),
+ shellTab = new ShellTab(this),
+ new SliderTab (this),
+ new TableTab (this),
+ new TextTab (this),
+ new ToolBarTab (this),
+ new TreeTab (this),
+ };
+ }
+
+ /**
+ * Disposes of all resources associated with a particular
+ * instance of the ControlExample.
+ */
+ public void dispose() {
+ /*
+ * Destroy any shells that may have been created
+ * by the Shells tab. When a shell is disposed,
+ * all child shells are also disposed. Therefore
+ * it is necessary to check for disposed shells
+ * in the shells list to avoid disposing a shell
+ * twice.
+ */
+ if (shellTab != null) shellTab.closeAllShells ();
+ shellTab = null;
+ tabFolder = null;
+ freeResources();
+ }
+
+ /**
+ * Frees the resources
+ */
+ void freeResources() {
+ if (images != null) {
+ for (int i = 0; i < images.length; ++i) {
+ final Image image = images[i];
+ if (image != null) image.dispose();
+ }
+ images = null;
+ }
+ }
+
+ /**
+ * Gets a string from the resource bundle.
+ * We don't want to crash because of a missing String.
+ * Returns the key if not found.
+ */
+ static String getResourceString(String key) {
+ try {
+ return resourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Gets a string from the resource bundle and binds it
+ * with the given arguments. If the key is not found,
+ * return the key.
+ */
+ static String getResourceString(String key, Object[] args) {
+ try {
+ return MessageFormat.format(getResourceString(key), args);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Loads the resources
+ */
+ void initResources() {
+ final Class clazz = ControlExample.class;
+ if (resourceBundle != null) {
+ try {
+ if (images == null) {
+ images = new Image[imageLocations.length];
+
+ for (int i = 0; i < imageLocations.length; ++i) {
+ ImageData source = new ImageData(clazz.getResourceAsStream(
+ imageLocations[i]));
+ ImageData mask = source.getTransparencyMask();
+ images[i] = new Image(null, source, mask);
+ }
+ }
+ return;
+ } catch (Throwable t) {
+ }
+ }
+ String error = (resourceBundle != null) ?
+ getResourceString("error.CouldNotLoadResources") :
+ "Unable to load resources";
+ freeResources();
+ throw new RuntimeException(error);
+ }
+
+ /**
+ * Answers true if this example is currently logging all
+ * events, and false otherwise.
+ */
+ public boolean isLogging () {
+ return logging;
+ }
+ /**
+ * Logs an event to the event console.
+ */
+ void log(Event event) {
+ if (logging && eventsFilter [event.type]) {
+ StringBuffer output = new StringBuffer (EVENT_TYPES[event.type]);
+ output.append (": ");
+ output.append (event.widget.toString ());
+ output.append (" X: ");
+ output.append (event.x);
+ output.append (" Y: ");
+ output.append (event.y);
+ output.append ("\n");
+ eventConsole.append (output.toString ());
+ }
+ }
+
+ /**
+ * Invokes as a standalone program.
+ */
+ public static void main(String[] args) {
+ standAlone = true;
+ Display display = new Display();
+ Shell shell = new Shell(display);
+ shell.setLayout(new FillLayout());
+ ControlExample instance = new ControlExample(shell);
+ shell.setText(getResourceString("window.title"));
+ shell.open();
+ while (! shell.isDisposed()) {
+ if (! display.readAndDispatch()) display.sleep();
+ }
+ instance.dispose();
+ }
+
+ /**
+ * Open the event logger.
+ */
+ void openEventConsole(Shell shell) {
+ logging = true;
+ form.setWeights(new int[] {80,20});
+ eventConsole.setEnabled (true);
+ TabItem[] tabs = tabFolder.getItems ();
+ for (int i = 0; i < tabs.length; i++) {
+ Tab tab = (Tab) tabs[i].getData ();
+ tab.recreateExampleWidgets ();
+ }
+ }
+
+ /**
+ * Grabs input focus.
+ */
+ public void setFocus() {
+ tabFolder.setFocus();
+ }
+}
+
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/CoolBarTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/CoolBarTab.java
index c4358fdf7f..c779235d8c 100644
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/CoolBarTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/CoolBarTab.java
@@ -1,426 +1,426 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-class CoolBarTab extends Tab {
- Button dropDownButton, lockedButton;
-
- /* Example widgets and group that contains them */
- CoolBar coolBar;
- CoolItem pushItem, dropDownItem, radioItem, checkItem;
- Group coolBarGroup;
-
- Point[] sizes;
- int[] wrapIndices;
- int[] order;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- CoolBarTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Display" group.
- */
- void createDisplayGroup () {
- super.createDisplayGroup ();
-
- /* Create display controls specific to this example */
- lockedButton = new Button (displayGroup, SWT.CHECK);
- lockedButton.setText (ControlExample.getResourceString("Locked"));
-
- /* Add the listeners */
- lockedButton.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setWidgetLocked ();
- }
- });
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
- coolBarGroup = new Group (exampleGroup, SWT.NONE);
- coolBarGroup.setLayout (new GridLayout ());
- coolBarGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- coolBarGroup.setText ("CoolBar");
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
- int style = 0, itemStyle = 0;
-
- /* Compute the widget style */
- int toolBarStyle = SWT.FLAT;
- if (borderButton.getSelection()) style |= SWT.BORDER;
- if (dropDownButton.getSelection()) itemStyle |= SWT.DROP_DOWN;
-
- /*
- * Create the example widgets.
- */
- coolBar = new CoolBar (coolBarGroup, style);
-
- /* create the push button toolbar */
- ToolBar toolBar = new ToolBar (coolBar, toolBarStyle);
- ToolItem item = new ToolItem (toolBar, SWT.PUSH);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.PUSH");
- item = new ToolItem (toolBar, SWT.PUSH);
- item.setImage (instance.images[ControlExample.ciOpenFolder]);
- item.setToolTipText ("SWT.PUSH");
- item = new ToolItem (toolBar, SWT.PUSH);
- item.setImage (instance.images[ControlExample.ciTarget]);
- item.setToolTipText ("SWT.PUSH");
- item = new ToolItem (toolBar, SWT.SEPARATOR);
- item = new ToolItem (toolBar, SWT.PUSH);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.PUSH");
- item = new ToolItem (toolBar, SWT.PUSH);
- item.setImage (instance.images[ControlExample.ciOpenFolder]);
- item.setToolTipText ("SWT.PUSH");
- pushItem = new CoolItem (coolBar, itemStyle);
- pushItem.setControl (toolBar);
- Point pushSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- pushSize = pushItem.computeSize(pushSize.x, pushSize.y);
- pushItem.setSize(pushSize);
- pushItem.setMinimumSize(item.getWidth(), pushSize.y);
- pushItem.addSelectionListener (new CoolItemSelectionListener());
-
- /* create the dropdown toolbar */
- toolBar = new ToolBar (coolBar, toolBarStyle);
- item = new ToolItem (toolBar, SWT.DROP_DOWN);
- item.setImage (instance.images[ControlExample.ciOpenFolder]);
- item.setToolTipText ("SWT.DROP_DOWN");
- item.addSelectionListener (new DropDownSelectionListener());
- item = new ToolItem (toolBar, SWT.DROP_DOWN);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.DROP_DOWN");
- item.addSelectionListener (new DropDownSelectionListener());
- dropDownItem = new CoolItem (coolBar, itemStyle);
- dropDownItem.setControl (toolBar);
- Point dropSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- dropSize = dropDownItem.computeSize(dropSize.x, dropSize.y);
- dropDownItem.setSize(dropSize);
- dropDownItem.setMinimumSize(item.getWidth(), dropSize.y);
- dropDownItem.addSelectionListener (new CoolItemSelectionListener());
-
- /* create the radio button toolbar */
- toolBar = new ToolBar (coolBar, toolBarStyle);
- item = new ToolItem (toolBar, SWT.RADIO);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.RADIO");
- item = new ToolItem (toolBar, SWT.RADIO);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.RADIO");
- item = new ToolItem (toolBar, SWT.RADIO);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.RADIO");
- radioItem = new CoolItem (coolBar, itemStyle);
- radioItem.setControl (toolBar);
- Point radioSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- radioSize = radioItem.computeSize(radioSize.x, radioSize.y);
- radioItem.setSize(radioSize);
- radioItem.setMinimumSize(item.getWidth(), radioSize.y);
- radioItem.addSelectionListener (new CoolItemSelectionListener());
-
- /* create the check button toolbar */
- toolBar = new ToolBar (coolBar, toolBarStyle);
- item = new ToolItem (toolBar, SWT.CHECK);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.CHECK");
- item = new ToolItem (toolBar, SWT.CHECK);
- item.setImage (instance.images[ControlExample.ciTarget]);
- item.setToolTipText ("SWT.CHECK");
- item = new ToolItem (toolBar, SWT.CHECK);
- item.setImage (instance.images[ControlExample.ciOpenFolder]);
- item.setToolTipText ("SWT.CHECK");
- item = new ToolItem (toolBar, SWT.CHECK);
- item.setImage (instance.images[ControlExample.ciTarget]);
- item.setToolTipText ("SWT.CHECK");
- checkItem = new CoolItem (coolBar, itemStyle);
- checkItem.setControl (toolBar);
- Point checkSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- checkSize = checkItem.computeSize(checkSize.x, checkSize.y);
- checkItem.setSize(checkSize);
- checkItem.setMinimumSize(item.getWidth(), checkSize.y);
- checkItem.addSelectionListener (new CoolItemSelectionListener());
-
- /* if we have saved state, restore it */
- if (order != null) {
- coolBar.setItemLayout(order, wrapIndices, sizes);
- /*
- * special case: because setItemLayout will restore the items
- * to the sizes the user left them at, the preferred size may not
- * be the same as the actual size. Thus we must explicitly set
- * the preferred sizes.
- */
- pushItem.setPreferredSize(pushSize);
- dropDownItem.setPreferredSize(dropSize);
- radioItem.setPreferredSize(radioSize);
- checkItem.setPreferredSize(checkSize);
- }
- else {
- coolBar.setWrapIndices(new int[] {1, 3});
- }
-
- /* add a listener to resize the group box to match the coolbar */
- coolBar.addListener(SWT.Resize, new Listener() {
- public void handleEvent(Event event) {
- exampleGroup.layout();
- }
- });
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup() {
- super.createStyleGroup();
-
- /* Create the extra widget */
- borderButton = new Button (styleGroup, SWT.CHECK);
- borderButton.setText ("SWT.BORDER");
- Group itemGroup = new Group(styleGroup, SWT.NONE);
- itemGroup.setLayout (new GridLayout ());
- itemGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- itemGroup.setText(ControlExample.getResourceString("Item_Styles"));
- dropDownButton = new Button (itemGroup, SWT.CHECK);
- dropDownButton.setText ("SWT.DROP_DOWN");
- dropDownButton.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- recreateExampleWidgets ();
- }
- });
- }
-
- /**
- * Disposes the "Example" widgets.
- */
- void disposeExampleWidgets () {
- /* store the state of the toolbar if applicable */
- if (coolBar != null) {
- sizes = coolBar.getItemSizes();
- wrapIndices = coolBar.getWrapIndices();
- order = coolBar.getItemOrder();
- }
- super.disposeExampleWidgets();
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {coolBar};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "CoolBar";
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- borderButton.setSelection ((coolBar.getStyle () & SWT.BORDER) != 0);
- dropDownButton.setSelection ((coolBar.getItem(0).getStyle () & SWT.DROP_DOWN) != 0);
- setWidgetLocked ();
- }
-
- /**
- * Sets the header visible state of the "Example" widgets.
- */
- void setWidgetLocked () {
- coolBar.setLocked (lockedButton.getSelection ());
- }
-
- /**
- * Listens to widgetSelected() events on SWT.DROP_DOWN type ToolItems
- * and opens/closes a menu when appropriate.
- */
- class DropDownSelectionListener extends SelectionAdapter {
- private Menu menu = null;
- private boolean visible = false;
-
- public void widgetSelected(SelectionEvent event) {
- // Create the menu if it has not already been created
- if (menu == null) {
- // Lazy create the menu.
- Shell shell = tabFolderPage.getShell();
- menu = new Menu(shell);
- for (int i = 0; i < 9; ++i) {
- final String text = ControlExample.getResourceString("DropDownData_" + i);
- if (text.length() != 0) {
- MenuItem menuItem = new MenuItem(menu, SWT.NONE);
- menuItem.setText(text);
- /*
- * Add a menu selection listener so that the menu is hidden
- * when the user selects an item from the drop down menu.
- */
- menuItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setMenuVisible(false);
- }
- });
- } else {
- new MenuItem(menu, SWT.SEPARATOR);
- }
- }
- }
-
- /**
- * A selection event will be fired when a drop down tool
- * item is selected in the main area and in the drop
- * down arrow. Examine the event detail to determine
- * where the widget was selected.
- */
- if (event.detail == SWT.ARROW) {
- /*
- * The drop down arrow was selected.
- */
- if (visible) {
- // Hide the menu to give the Arrow the appearance of being a toggle button.
- setMenuVisible(false);
- } else {
- // Position the menu below and vertically aligned with the the drop down tool button.
- final ToolItem toolItem = (ToolItem) event.widget;
- final ToolBar toolBar = toolItem.getParent();
-
- Rectangle toolItemBounds = toolItem.getBounds();
- Point point = toolBar.toDisplay(new Point(toolItemBounds.x, toolItemBounds.y));
- menu.setLocation(point.x, point.y + toolItemBounds.height);
- setMenuVisible(true);
- }
- } else {
- /*
- * Main area of drop down tool item selected.
- * An application would invoke the code to perform the action for the tool item.
- */
- }
- }
- private void setMenuVisible(boolean visible) {
- menu.setVisible(visible);
- this.visible = visible;
- }
- }
-
- /**
- * Listens to widgetSelected() events on SWT.DROP_DOWN type CoolItems
- * and opens/closes a menu when appropriate.
- */
- class CoolItemSelectionListener extends SelectionAdapter {
- private Menu menu = null;
-
- public void widgetSelected(SelectionEvent event) {
- /**
- * A selection event will be fired when the cool item
- * is selected by its gripper or if the drop down arrow
- * (or 'chevron') is selected. Examine the event detail
- * to determine where the widget was selected.
- */
- if (event.detail == SWT.ARROW) {
- /* If the popup menu is already up (i.e. user pressed arrow twice),
- * then dispose it.
- */
- if (menu != null) {
- menu.dispose();
- menu = null;
- return;
- }
-
- /* Get the cool item and convert its bounds to display coordinates. */
- CoolItem coolItem = (CoolItem) event.widget;
- Rectangle itemBounds = coolItem.getBounds ();
- Point pt = coolBar.toDisplay(new Point (itemBounds.x, itemBounds.y));
- itemBounds.x = pt.x;
- itemBounds.y = pt.y;
-
- /* Get the toolbar from the cool item. */
- ToolBar toolBar = (ToolBar) coolItem.getControl ();
- ToolItem[] tools = toolBar.getItems ();
- int toolCount = tools.length;
-
- /* Convert the bounds of each tool item to display coordinates,
- * and determine which ones are past the bounds of the cool item.
- */
- int i = 0;
- while (i < toolCount) {
- Rectangle toolBounds = tools[i].getBounds ();
- pt = toolBar.toDisplay(new Point(toolBounds.x, toolBounds.y));
- toolBounds.x = pt.x;
- toolBounds.y = pt.y;
- Rectangle intersection = itemBounds.intersection (toolBounds);
- if (!intersection.equals (toolBounds)) break;
- i++;
- }
-
- /* Create a pop-up menu with items for each of the hidden buttons. */
- menu = new Menu (coolBar);
- for (int j = i; j < toolCount; j++) {
- ToolItem tool = tools[j];
- Image image = tool.getImage();
- if (image == null) {
- new MenuItem (menu, SWT.SEPARATOR);
- } else {
- if ((tool.getStyle() & SWT.DROP_DOWN) != 0) {
- MenuItem menuItem = new MenuItem (menu, SWT.CASCADE);
- menuItem.setImage(image);
- Menu m = new Menu(menu);
- menuItem.setMenu(m);
- for (int k = 0; k < 9; ++k) {
- String text = ControlExample.getResourceString("DropDownData_" + k);
- if (text.length() != 0) {
- MenuItem mi = new MenuItem(m, SWT.NONE);
- mi.setText(text);
- /* Application code to perform the action for the submenu item would go here. */
- } else {
- new MenuItem(m, SWT.SEPARATOR);
- }
- }
- } else {
- MenuItem menuItem = new MenuItem (menu, SWT.NONE);
- menuItem.setImage(image);
- }
- /* Application code to perform the action for the menu item would go here. */
-
- }
- }
-
- /* Display the pop-up menu at the lower left corner of the arrow button.
- * Dispose the menu when the user is done with it.
- */
- pt = coolBar.toDisplay(new Point(event.x, event.y));
- menu.setLocation (pt.x, pt.y);
- menu.setVisible (true);
- Display display = coolBar.getDisplay ();
- while (menu != null && menu.isVisible ()) {
- if (!display.readAndDispatch ()) display.sleep ();
- }
- if (menu != null) {
- menu.dispose ();
- menu = null;
- }
- }
- }
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+class CoolBarTab extends Tab {
+ Button dropDownButton, lockedButton;
+
+ /* Example widgets and group that contains them */
+ CoolBar coolBar;
+ CoolItem pushItem, dropDownItem, radioItem, checkItem;
+ Group coolBarGroup;
+
+ Point[] sizes;
+ int[] wrapIndices;
+ int[] order;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ CoolBarTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Display" group.
+ */
+ void createDisplayGroup () {
+ super.createDisplayGroup ();
+
+ /* Create display controls specific to this example */
+ lockedButton = new Button (displayGroup, SWT.CHECK);
+ lockedButton.setText (ControlExample.getResourceString("Locked"));
+
+ /* Add the listeners */
+ lockedButton.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setWidgetLocked ();
+ }
+ });
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+ coolBarGroup = new Group (exampleGroup, SWT.NONE);
+ coolBarGroup.setLayout (new GridLayout ());
+ coolBarGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ coolBarGroup.setText ("CoolBar");
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+ int style = 0, itemStyle = 0;
+
+ /* Compute the widget style */
+ int toolBarStyle = SWT.FLAT;
+ if (borderButton.getSelection()) style |= SWT.BORDER;
+ if (dropDownButton.getSelection()) itemStyle |= SWT.DROP_DOWN;
+
+ /*
+ * Create the example widgets.
+ */
+ coolBar = new CoolBar (coolBarGroup, style);
+
+ /* create the push button toolbar */
+ ToolBar toolBar = new ToolBar (coolBar, toolBarStyle);
+ ToolItem item = new ToolItem (toolBar, SWT.PUSH);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.PUSH");
+ item = new ToolItem (toolBar, SWT.PUSH);
+ item.setImage (instance.images[ControlExample.ciOpenFolder]);
+ item.setToolTipText ("SWT.PUSH");
+ item = new ToolItem (toolBar, SWT.PUSH);
+ item.setImage (instance.images[ControlExample.ciTarget]);
+ item.setToolTipText ("SWT.PUSH");
+ item = new ToolItem (toolBar, SWT.SEPARATOR);
+ item = new ToolItem (toolBar, SWT.PUSH);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.PUSH");
+ item = new ToolItem (toolBar, SWT.PUSH);
+ item.setImage (instance.images[ControlExample.ciOpenFolder]);
+ item.setToolTipText ("SWT.PUSH");
+ pushItem = new CoolItem (coolBar, itemStyle);
+ pushItem.setControl (toolBar);
+ Point pushSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ pushSize = pushItem.computeSize(pushSize.x, pushSize.y);
+ pushItem.setSize(pushSize);
+ pushItem.setMinimumSize(item.getWidth(), pushSize.y);
+ pushItem.addSelectionListener (new CoolItemSelectionListener());
+
+ /* create the dropdown toolbar */
+ toolBar = new ToolBar (coolBar, toolBarStyle);
+ item = new ToolItem (toolBar, SWT.DROP_DOWN);
+ item.setImage (instance.images[ControlExample.ciOpenFolder]);
+ item.setToolTipText ("SWT.DROP_DOWN");
+ item.addSelectionListener (new DropDownSelectionListener());
+ item = new ToolItem (toolBar, SWT.DROP_DOWN);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.DROP_DOWN");
+ item.addSelectionListener (new DropDownSelectionListener());
+ dropDownItem = new CoolItem (coolBar, itemStyle);
+ dropDownItem.setControl (toolBar);
+ Point dropSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ dropSize = dropDownItem.computeSize(dropSize.x, dropSize.y);
+ dropDownItem.setSize(dropSize);
+ dropDownItem.setMinimumSize(item.getWidth(), dropSize.y);
+ dropDownItem.addSelectionListener (new CoolItemSelectionListener());
+
+ /* create the radio button toolbar */
+ toolBar = new ToolBar (coolBar, toolBarStyle);
+ item = new ToolItem (toolBar, SWT.RADIO);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.RADIO");
+ item = new ToolItem (toolBar, SWT.RADIO);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.RADIO");
+ item = new ToolItem (toolBar, SWT.RADIO);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.RADIO");
+ radioItem = new CoolItem (coolBar, itemStyle);
+ radioItem.setControl (toolBar);
+ Point radioSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ radioSize = radioItem.computeSize(radioSize.x, radioSize.y);
+ radioItem.setSize(radioSize);
+ radioItem.setMinimumSize(item.getWidth(), radioSize.y);
+ radioItem.addSelectionListener (new CoolItemSelectionListener());
+
+ /* create the check button toolbar */
+ toolBar = new ToolBar (coolBar, toolBarStyle);
+ item = new ToolItem (toolBar, SWT.CHECK);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.CHECK");
+ item = new ToolItem (toolBar, SWT.CHECK);
+ item.setImage (instance.images[ControlExample.ciTarget]);
+ item.setToolTipText ("SWT.CHECK");
+ item = new ToolItem (toolBar, SWT.CHECK);
+ item.setImage (instance.images[ControlExample.ciOpenFolder]);
+ item.setToolTipText ("SWT.CHECK");
+ item = new ToolItem (toolBar, SWT.CHECK);
+ item.setImage (instance.images[ControlExample.ciTarget]);
+ item.setToolTipText ("SWT.CHECK");
+ checkItem = new CoolItem (coolBar, itemStyle);
+ checkItem.setControl (toolBar);
+ Point checkSize = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ checkSize = checkItem.computeSize(checkSize.x, checkSize.y);
+ checkItem.setSize(checkSize);
+ checkItem.setMinimumSize(item.getWidth(), checkSize.y);
+ checkItem.addSelectionListener (new CoolItemSelectionListener());
+
+ /* if we have saved state, restore it */
+ if (order != null) {
+ coolBar.setItemLayout(order, wrapIndices, sizes);
+ /*
+ * special case: because setItemLayout will restore the items
+ * to the sizes the user left them at, the preferred size may not
+ * be the same as the actual size. Thus we must explicitly set
+ * the preferred sizes.
+ */
+ pushItem.setPreferredSize(pushSize);
+ dropDownItem.setPreferredSize(dropSize);
+ radioItem.setPreferredSize(radioSize);
+ checkItem.setPreferredSize(checkSize);
+ }
+ else {
+ coolBar.setWrapIndices(new int[] {1, 3});
+ }
+
+ /* add a listener to resize the group box to match the coolbar */
+ coolBar.addListener(SWT.Resize, new Listener() {
+ public void handleEvent(Event event) {
+ exampleGroup.layout();
+ }
+ });
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup() {
+ super.createStyleGroup();
+
+ /* Create the extra widget */
+ borderButton = new Button (styleGroup, SWT.CHECK);
+ borderButton.setText ("SWT.BORDER");
+ Group itemGroup = new Group(styleGroup, SWT.NONE);
+ itemGroup.setLayout (new GridLayout ());
+ itemGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ itemGroup.setText(ControlExample.getResourceString("Item_Styles"));
+ dropDownButton = new Button (itemGroup, SWT.CHECK);
+ dropDownButton.setText ("SWT.DROP_DOWN");
+ dropDownButton.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ recreateExampleWidgets ();
+ }
+ });
+ }
+
+ /**
+ * Disposes the "Example" widgets.
+ */
+ void disposeExampleWidgets () {
+ /* store the state of the toolbar if applicable */
+ if (coolBar != null) {
+ sizes = coolBar.getItemSizes();
+ wrapIndices = coolBar.getWrapIndices();
+ order = coolBar.getItemOrder();
+ }
+ super.disposeExampleWidgets();
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {coolBar};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "CoolBar";
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ borderButton.setSelection ((coolBar.getStyle () & SWT.BORDER) != 0);
+ dropDownButton.setSelection ((coolBar.getItem(0).getStyle () & SWT.DROP_DOWN) != 0);
+ setWidgetLocked ();
+ }
+
+ /**
+ * Sets the header visible state of the "Example" widgets.
+ */
+ void setWidgetLocked () {
+ coolBar.setLocked (lockedButton.getSelection ());
+ }
+
+ /**
+ * Listens to widgetSelected() events on SWT.DROP_DOWN type ToolItems
+ * and opens/closes a menu when appropriate.
+ */
+ class DropDownSelectionListener extends SelectionAdapter {
+ private Menu menu = null;
+ private boolean visible = false;
+
+ public void widgetSelected(SelectionEvent event) {
+ // Create the menu if it has not already been created
+ if (menu == null) {
+ // Lazy create the menu.
+ Shell shell = tabFolderPage.getShell();
+ menu = new Menu(shell);
+ for (int i = 0; i < 9; ++i) {
+ final String text = ControlExample.getResourceString("DropDownData_" + i);
+ if (text.length() != 0) {
+ MenuItem menuItem = new MenuItem(menu, SWT.NONE);
+ menuItem.setText(text);
+ /*
+ * Add a menu selection listener so that the menu is hidden
+ * when the user selects an item from the drop down menu.
+ */
+ menuItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setMenuVisible(false);
+ }
+ });
+ } else {
+ new MenuItem(menu, SWT.SEPARATOR);
+ }
+ }
+ }
+
+ /**
+ * A selection event will be fired when a drop down tool
+ * item is selected in the main area and in the drop
+ * down arrow. Examine the event detail to determine
+ * where the widget was selected.
+ */
+ if (event.detail == SWT.ARROW) {
+ /*
+ * The drop down arrow was selected.
+ */
+ if (visible) {
+ // Hide the menu to give the Arrow the appearance of being a toggle button.
+ setMenuVisible(false);
+ } else {
+ // Position the menu below and vertically aligned with the the drop down tool button.
+ final ToolItem toolItem = (ToolItem) event.widget;
+ final ToolBar toolBar = toolItem.getParent();
+
+ Rectangle toolItemBounds = toolItem.getBounds();
+ Point point = toolBar.toDisplay(new Point(toolItemBounds.x, toolItemBounds.y));
+ menu.setLocation(point.x, point.y + toolItemBounds.height);
+ setMenuVisible(true);
+ }
+ } else {
+ /*
+ * Main area of drop down tool item selected.
+ * An application would invoke the code to perform the action for the tool item.
+ */
+ }
+ }
+ private void setMenuVisible(boolean visible) {
+ menu.setVisible(visible);
+ this.visible = visible;
+ }
+ }
+
+ /**
+ * Listens to widgetSelected() events on SWT.DROP_DOWN type CoolItems
+ * and opens/closes a menu when appropriate.
+ */
+ class CoolItemSelectionListener extends SelectionAdapter {
+ private Menu menu = null;
+
+ public void widgetSelected(SelectionEvent event) {
+ /**
+ * A selection event will be fired when the cool item
+ * is selected by its gripper or if the drop down arrow
+ * (or 'chevron') is selected. Examine the event detail
+ * to determine where the widget was selected.
+ */
+ if (event.detail == SWT.ARROW) {
+ /* If the popup menu is already up (i.e. user pressed arrow twice),
+ * then dispose it.
+ */
+ if (menu != null) {
+ menu.dispose();
+ menu = null;
+ return;
+ }
+
+ /* Get the cool item and convert its bounds to display coordinates. */
+ CoolItem coolItem = (CoolItem) event.widget;
+ Rectangle itemBounds = coolItem.getBounds ();
+ Point pt = coolBar.toDisplay(new Point (itemBounds.x, itemBounds.y));
+ itemBounds.x = pt.x;
+ itemBounds.y = pt.y;
+
+ /* Get the toolbar from the cool item. */
+ ToolBar toolBar = (ToolBar) coolItem.getControl ();
+ ToolItem[] tools = toolBar.getItems ();
+ int toolCount = tools.length;
+
+ /* Convert the bounds of each tool item to display coordinates,
+ * and determine which ones are past the bounds of the cool item.
+ */
+ int i = 0;
+ while (i < toolCount) {
+ Rectangle toolBounds = tools[i].getBounds ();
+ pt = toolBar.toDisplay(new Point(toolBounds.x, toolBounds.y));
+ toolBounds.x = pt.x;
+ toolBounds.y = pt.y;
+ Rectangle intersection = itemBounds.intersection (toolBounds);
+ if (!intersection.equals (toolBounds)) break;
+ i++;
+ }
+
+ /* Create a pop-up menu with items for each of the hidden buttons. */
+ menu = new Menu (coolBar);
+ for (int j = i; j < toolCount; j++) {
+ ToolItem tool = tools[j];
+ Image image = tool.getImage();
+ if (image == null) {
+ new MenuItem (menu, SWT.SEPARATOR);
+ } else {
+ if ((tool.getStyle() & SWT.DROP_DOWN) != 0) {
+ MenuItem menuItem = new MenuItem (menu, SWT.CASCADE);
+ menuItem.setImage(image);
+ Menu m = new Menu(menu);
+ menuItem.setMenu(m);
+ for (int k = 0; k < 9; ++k) {
+ String text = ControlExample.getResourceString("DropDownData_" + k);
+ if (text.length() != 0) {
+ MenuItem mi = new MenuItem(m, SWT.NONE);
+ mi.setText(text);
+ /* Application code to perform the action for the submenu item would go here. */
+ } else {
+ new MenuItem(m, SWT.SEPARATOR);
+ }
+ }
+ } else {
+ MenuItem menuItem = new MenuItem (menu, SWT.NONE);
+ menuItem.setImage(image);
+ }
+ /* Application code to perform the action for the menu item would go here. */
+
+ }
+ }
+
+ /* Display the pop-up menu at the lower left corner of the arrow button.
+ * Dispose the menu when the user is done with it.
+ */
+ pt = coolBar.toDisplay(new Point(event.x, event.y));
+ menu.setLocation (pt.x, pt.y);
+ menu.setVisible (true);
+ Display display = coolBar.getDisplay ();
+ while (menu != null && menu.isVisible ()) {
+ if (!display.readAndDispatch ()) display.sleep ();
+ }
+ if (menu != null) {
+ menu.dispose ();
+ menu = null;
+ }
+ }
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/DialogTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/DialogTab.java
index 61e7f507c8..b06390b66e 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/DialogTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/DialogTab.java
@@ -1,442 +1,442 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.printing.*;
-import org.eclipse.swt.events.*;
-
-class DialogTab extends Tab {
- /* Example widgets and groups that contain them */
- Group dialogStyleGroup, resultGroup;
- Text textWidget;
-
- /* Style widgets added to the "Style" group */
- Combo dialogCombo;
- Button okButton, cancelButton;
- Button yesButton, noButton;
- Button retryButton;
- Button abortButton, ignoreButton;
- Button iconErrorButton, iconInformationButton, iconQuestionButton;
- Button iconWarningButton, iconWorkingButton;
- Button modelessButton, primaryModalButton, applicationModalButton, systemModalButton;
- Button saveButton, openButton;
-
- static String [] FilterExtensions = {"*.txt", "*.bat", "*.doc"};
- static String [] FilterNames = {ControlExample.getResourceString("FilterName_0"),
- ControlExample.getResourceString("FilterName_1"),
- ControlExample.getResourceString("FilterName_2")};
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- DialogTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Handle a button style selection event.
- *
- * @param event the selection event
- */
- void buttonStyleSelected(SelectionEvent event) {
- /*
- * Only certain combinations of button styles are
- * supported for various dialogs. Make sure the
- * control widget reflects only valid combinations.
- */
- okButton.setEnabled (
- !(yesButton.getSelection () || noButton.getSelection () ||
- retryButton.getSelection () || abortButton.getSelection () ||
- ignoreButton.getSelection ()));
- cancelButton.setEnabled (
- !(abortButton.getSelection () || ignoreButton.getSelection ()));
- yesButton.setEnabled (
- !(okButton.getSelection () || retryButton.getSelection () ||
- abortButton.getSelection () || ignoreButton.getSelection ()));
- noButton.setEnabled (
- !(okButton.getSelection () || retryButton.getSelection () ||
- abortButton.getSelection () || ignoreButton.getSelection ()));
- retryButton.setEnabled (
- !(okButton.getSelection() || yesButton.getSelection() || noButton.getSelection ()));
- abortButton.setEnabled (
- !(okButton.getSelection () || cancelButton.getSelection () ||
- yesButton.getSelection () || noButton.getSelection ()));
- ignoreButton.setEnabled (
- !(okButton.getSelection () || cancelButton.getSelection () |
- yesButton.getSelection () || noButton.getSelection ()));
- }
-
- /**
- * Handle the create button selection event.
- *
- * @param event org.eclipse.swt.events.SelectionEvent
- */
- void createButtonSelected(SelectionEvent event) {
-
- /* Compute the appropriate dialog style */
- int style = SWT.NONE;
- if (okButton.getEnabled () && okButton.getSelection ()) style |= SWT.OK;
- if (cancelButton.getEnabled () && cancelButton.getSelection ()) style |= SWT.CANCEL;
- if (yesButton.getEnabled () && yesButton.getSelection ()) style |= SWT.YES;
- if (noButton.getEnabled () && noButton.getSelection ()) style |= SWT.NO;
- if (retryButton.getEnabled () && retryButton.getSelection ()) style |= SWT.RETRY;
- if (abortButton.getEnabled () && abortButton.getSelection ()) style |= SWT.ABORT;
- if (ignoreButton.getEnabled () && ignoreButton.getSelection ()) style |= SWT.IGNORE;
- if (iconErrorButton.getEnabled () && iconErrorButton.getSelection ()) style |= SWT.ICON_ERROR;
- if (iconInformationButton.getEnabled () && iconInformationButton.getSelection ()) style |= SWT.ICON_INFORMATION;
- if (iconQuestionButton.getEnabled () && iconQuestionButton.getSelection ()) style |= SWT.ICON_QUESTION;
- if (iconWarningButton.getEnabled () && iconWarningButton.getSelection ()) style |= SWT.ICON_WARNING;
- if (iconWorkingButton.getEnabled () && iconWorkingButton.getSelection ()) style |= SWT.ICON_WORKING;
- if (primaryModalButton.getEnabled () && primaryModalButton.getSelection ()) style |= SWT.PRIMARY_MODAL;
- if (applicationModalButton.getEnabled () && applicationModalButton.getSelection ()) style |= SWT.APPLICATION_MODAL;
- if (systemModalButton.getEnabled () && systemModalButton.getSelection ()) style |= SWT.SYSTEM_MODAL;
- if (saveButton.getEnabled () && saveButton.getSelection ()) style |= SWT.SAVE;
- if (openButton.getEnabled () && openButton.getSelection ()) style |= SWT.OPEN;
-
- /* Open the appropriate dialog type */
- String name = dialogCombo.getText ();
- Shell shell = tabFolderPage.getShell ();
-
- if (name.equals (ControlExample.getResourceString("ColorDialog"))) {
- ColorDialog dialog = new ColorDialog (shell ,style);
- dialog.setRGB (new RGB (100, 100, 100));
- dialog.setText (ControlExample.getResourceString("Title"));
- RGB result = dialog.open ();
- textWidget.append (ControlExample.getResourceString("ColorDialog") + Text.DELIMITER);
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
- return;
- }
-
- if (name.equals (ControlExample.getResourceString("DirectoryDialog"))) {
- DirectoryDialog dialog = new DirectoryDialog (shell, style);
- dialog.setMessage (ControlExample.getResourceString("Example_string"));
- dialog.setText (ControlExample.getResourceString("Title"));
- String result = dialog.open ();
- textWidget.append (ControlExample.getResourceString("DirectoryDialog") + Text.DELIMITER);
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
- return;
- }
-
- if (name.equals (ControlExample.getResourceString("FileDialog"))) {
- FileDialog dialog = new FileDialog (shell, style);
- dialog.setFileName (ControlExample.getResourceString("readme_txt"));
- dialog.setFilterNames (FilterNames);
- dialog.setFilterExtensions (FilterExtensions);
- dialog.setText (ControlExample.getResourceString("Title"));
- String result = dialog.open();
- textWidget.append (ControlExample.getResourceString("FileDialog") + Text.DELIMITER);
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
- return;
- }
-
- if (name.equals (ControlExample.getResourceString("FontDialog"))) {
- FontDialog dialog = new FontDialog (shell, style);
- dialog.setText (ControlExample.getResourceString("Title"));
- FontData result = dialog.open ();
- textWidget.append (ControlExample.getResourceString("FontDialog") + Text.DELIMITER);
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
- return;
- }
-
- if (name.equals (ControlExample.getResourceString("PrintDialog"))) {
- PrintDialog dialog = new PrintDialog (shell, style);
- dialog.setText(ControlExample.getResourceString("Title"));
- PrinterData result = dialog.open ();
- textWidget.append (ControlExample.getResourceString("PrintDialog") + Text.DELIMITER);
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
- return;
- }
-
- if (name.equals(ControlExample.getResourceString("MessageBox"))) {
- MessageBox dialog = new MessageBox (shell, style);
- dialog.setMessage (ControlExample.getResourceString("Example_string"));
- dialog.setText (ControlExample.getResourceString("Title"));
- int result = dialog.open ();
- textWidget.append (ControlExample.getResourceString("MessageBox") + Text.DELIMITER);
- /*
- * The resulting integer depends on the original
- * dialog style. Decode the result and display it.
- */
- switch (result) {
- case SWT.OK:
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.OK"}));
- break;
- case SWT.YES:
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.YES"}));
- break;
- case SWT.NO:
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.NO"}));
- break;
- case SWT.CANCEL:
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.CANCEL"}));
- break;
- case SWT.ABORT:
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.ABORT"}));
- break;
- case SWT.RETRY:
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.RETRY"}));
- break;
- case SWT.IGNORE:
- textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.IGNORE"}));
- break;
- default:
- textWidget.append(ControlExample.getResourceString("Result", new String [] {"" + result}));
- break;
- }
- textWidget.append (Text.DELIMITER + Text.DELIMITER);
- }
- }
-
- /**
- * Creates the "Control" group.
- */
- void createControlGroup () {
- /*
- * Create the "Control" group. This is the group on the
- * left half of each example tab. It consists of the
- * style group, the display group and the size group.
- */
- controlGroup = new Group (tabFolderPage, SWT.NONE);
- GridLayout gridLayout= new GridLayout ();
- controlGroup.setLayout(gridLayout);
- gridLayout.numColumns = 2;
- gridLayout.makeColumnsEqualWidth = true;
- controlGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- controlGroup.setText (ControlExample.getResourceString("Parameters"));
-
- /*
- * Create a group to hold the dialog style combo box and
- * create dialog button.
- */
- dialogStyleGroup = new Group (controlGroup, SWT.NONE);
- dialogStyleGroup.setLayout (new GridLayout ());
- GridData gridData = new GridData (GridData.HORIZONTAL_ALIGN_CENTER);
- gridData.horizontalSpan = 2;
- dialogStyleGroup.setLayoutData (gridData);
- dialogStyleGroup.setText (ControlExample.getResourceString("Dialog_Type"));
- }
-
- /**
- * Creates the "Control" widget children.
- */
- void createControlWidgets () {
-
- /* Create the combo */
- String [] strings = {
- ControlExample.getResourceString("ColorDialog"),
- ControlExample.getResourceString("DirectoryDialog"),
- ControlExample.getResourceString("FileDialog"),
- ControlExample.getResourceString("FontDialog"),
- ControlExample.getResourceString("PrintDialog"),
- ControlExample.getResourceString("MessageBox"),
- };
- dialogCombo = new Combo (dialogStyleGroup, SWT.READ_ONLY);
- dialogCombo.setItems (strings);
- dialogCombo.setText (strings [0]);
-
- /* Create the create dialog button */
- Button createButton = new Button(dialogStyleGroup, SWT.NONE);
- createButton.setText (ControlExample.getResourceString("Create_Dialog"));
- createButton.setLayoutData (new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
-
- /* Create a group for the various dialog button style controls */
- Group buttonStyleGroup = new Group (controlGroup, SWT.NONE);
- buttonStyleGroup.setLayout (new GridLayout ());
- buttonStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- buttonStyleGroup.setText (ControlExample.getResourceString("Button_Styles"));
-
- /* Create the button style buttons */
- okButton = new Button (buttonStyleGroup, SWT.CHECK);
- okButton.setText ("SWT.OK");
- cancelButton = new Button (buttonStyleGroup, SWT.CHECK);
- cancelButton.setText ("SWT.CANCEL");
- yesButton = new Button (buttonStyleGroup, SWT.CHECK);
- yesButton.setText ("SWT.YES");
- noButton = new Button (buttonStyleGroup, SWT.CHECK);
- noButton.setText ("SWT.NO");
- retryButton = new Button (buttonStyleGroup, SWT.CHECK);
- retryButton.setText ("SWT.RETRY");
- abortButton = new Button (buttonStyleGroup, SWT.CHECK);
- abortButton.setText ("SWT.ABORT");
- ignoreButton = new Button (buttonStyleGroup, SWT.CHECK);
- ignoreButton.setText ("SWT.IGNORE");
-
- /* Create a group for the icon style controls */
- Group iconStyleGroup = new Group (controlGroup, SWT.NONE);
- iconStyleGroup.setLayout (new GridLayout ());
- iconStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- iconStyleGroup.setText (ControlExample.getResourceString("Icon_Styles"));
-
- /* Create the icon style buttons */
- iconErrorButton = new Button (iconStyleGroup, SWT.RADIO);
- iconErrorButton.setText ("SWT.ICON_ERROR");
- iconInformationButton = new Button (iconStyleGroup, SWT.RADIO);
- iconInformationButton.setText ("SWT.ICON_INFORMATION");
- iconQuestionButton = new Button (iconStyleGroup, SWT.RADIO);
- iconQuestionButton.setText ("SWT.ICON_QUESTION");
- iconWarningButton = new Button (iconStyleGroup, SWT.RADIO);
- iconWarningButton.setText ("SWT.ICON_WARNING");
- iconWorkingButton = new Button (iconStyleGroup, SWT.RADIO);
- iconWorkingButton.setText ("SWT.ICON_WORKING");
-
- /* Create a group for the modal style controls */
- Group modalStyleGroup = new Group (controlGroup, SWT.NONE);
- modalStyleGroup.setLayout (new GridLayout ());
- modalStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- modalStyleGroup.setText (ControlExample.getResourceString("Modal_Styles"));
-
- /* Create the modal style buttons */
- modelessButton = new Button (modalStyleGroup, SWT.RADIO);
- modelessButton.setText ("SWT.MODELESS");
- primaryModalButton = new Button (modalStyleGroup, SWT.RADIO);
- primaryModalButton.setText ("SWT.PRIMARY_MODAL");
- applicationModalButton = new Button (modalStyleGroup, SWT.RADIO);
- applicationModalButton.setText ("SWT.APPLICATION_MODAL");
- systemModalButton = new Button (modalStyleGroup, SWT.RADIO);
- systemModalButton.setText ("SWT.SYSTEM_MODAL");
-
- /* Create a group for the file dialog style controls */
- Group fileDialogStyleGroup = new Group (controlGroup, SWT.NONE);
- fileDialogStyleGroup.setLayout (new GridLayout ());
- fileDialogStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- fileDialogStyleGroup.setText (ControlExample.getResourceString("File_Dialog_Styles"));
-
- /* Create the file dialog style buttons */
- saveButton = new Button (fileDialogStyleGroup, SWT.RADIO);
- saveButton.setText ("SWT.SAVE");
- openButton = new Button(fileDialogStyleGroup, SWT.RADIO);
- openButton.setText("SWT.OPEN");
-
- /* Add the listeners */
- dialogCombo.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- dialogSelected (event);
- };
- });
- createButton.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- createButtonSelected (event);
- };
- });
- SelectionListener buttonStyleListener = new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- buttonStyleSelected (event);
- };
- };
- okButton.addSelectionListener (buttonStyleListener);
- cancelButton.addSelectionListener (buttonStyleListener);
- yesButton.addSelectionListener (buttonStyleListener);
- noButton.addSelectionListener (buttonStyleListener);
- retryButton.addSelectionListener (buttonStyleListener);
- abortButton.addSelectionListener (buttonStyleListener);
- ignoreButton.addSelectionListener (buttonStyleListener);
-
- /* Set default values for style buttons */
- okButton.setEnabled (false);
- cancelButton.setEnabled (false);
- yesButton.setEnabled (false);
- noButton.setEnabled (false);
- retryButton.setEnabled (false);
- abortButton.setEnabled (false);
- ignoreButton.setEnabled (false);
- iconErrorButton.setEnabled (false);
- iconInformationButton.setEnabled (false);
- iconQuestionButton.setEnabled (false);
- iconWarningButton.setEnabled (false);
- iconWorkingButton.setEnabled (false);
- saveButton.setEnabled (false);
- openButton.setEnabled (false);
- openButton.setSelection (true);
- iconInformationButton.setSelection (true);
- modelessButton.setSelection (true);
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /*
- * Create a group for the text widget to display
- * the results returned by the example dialogs.
- */
- resultGroup = new Group (exampleGroup, SWT.NONE);
- resultGroup.setLayout (new GridLayout ());
- resultGroup.setLayoutData (new GridData (GridData.FILL_BOTH));
- resultGroup.setText (ControlExample.getResourceString("Dialog_Result"));
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
- /*
- * Create a multi lined, scrolled text widget for output.
- */
- textWidget = new Text(resultGroup, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
- GridData gridData = new GridData (GridData.FILL_BOTH);
- textWidget.setLayoutData (gridData);
- }
-
- /**
- * Handle a dialog type combo selection event.
- *
- * @param event the selection event
- */
- void dialogSelected (SelectionEvent event) {
-
- /* Enable/Disable the buttons */
- String name = dialogCombo.getText ();
- boolean isMessageBox = name.equals (ControlExample.getResourceString("MessageBox"));
- boolean isFileDialog = name.equals (ControlExample.getResourceString("FileDialog"));
- okButton.setEnabled (isMessageBox);
- cancelButton.setEnabled (isMessageBox);
- yesButton.setEnabled (isMessageBox);
- noButton.setEnabled (isMessageBox);
- retryButton.setEnabled (isMessageBox);
- abortButton.setEnabled (isMessageBox);
- ignoreButton.setEnabled (isMessageBox);
- iconErrorButton.setEnabled (isMessageBox);
- iconInformationButton.setEnabled (isMessageBox);
- iconQuestionButton.setEnabled (isMessageBox);
- iconWarningButton.setEnabled (isMessageBox);
- iconWorkingButton.setEnabled (isMessageBox);
- saveButton.setEnabled (isFileDialog);
- openButton.setEnabled (isFileDialog);
-
- /* Unselect the buttons */
- if (!isMessageBox) {
- okButton.setSelection (false);
- cancelButton.setSelection (false);
- yesButton.setSelection (false);
- noButton.setSelection (false);
- retryButton.setSelection (false);
- abortButton.setSelection (false);
- ignoreButton.setSelection (false);
- }
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [0];
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Dialog";
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.printing.*;
+import org.eclipse.swt.events.*;
+
+class DialogTab extends Tab {
+ /* Example widgets and groups that contain them */
+ Group dialogStyleGroup, resultGroup;
+ Text textWidget;
+
+ /* Style widgets added to the "Style" group */
+ Combo dialogCombo;
+ Button okButton, cancelButton;
+ Button yesButton, noButton;
+ Button retryButton;
+ Button abortButton, ignoreButton;
+ Button iconErrorButton, iconInformationButton, iconQuestionButton;
+ Button iconWarningButton, iconWorkingButton;
+ Button modelessButton, primaryModalButton, applicationModalButton, systemModalButton;
+ Button saveButton, openButton;
+
+ static String [] FilterExtensions = {"*.txt", "*.bat", "*.doc"};
+ static String [] FilterNames = {ControlExample.getResourceString("FilterName_0"),
+ ControlExample.getResourceString("FilterName_1"),
+ ControlExample.getResourceString("FilterName_2")};
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ DialogTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Handle a button style selection event.
+ *
+ * @param event the selection event
+ */
+ void buttonStyleSelected(SelectionEvent event) {
+ /*
+ * Only certain combinations of button styles are
+ * supported for various dialogs. Make sure the
+ * control widget reflects only valid combinations.
+ */
+ okButton.setEnabled (
+ !(yesButton.getSelection () || noButton.getSelection () ||
+ retryButton.getSelection () || abortButton.getSelection () ||
+ ignoreButton.getSelection ()));
+ cancelButton.setEnabled (
+ !(abortButton.getSelection () || ignoreButton.getSelection ()));
+ yesButton.setEnabled (
+ !(okButton.getSelection () || retryButton.getSelection () ||
+ abortButton.getSelection () || ignoreButton.getSelection ()));
+ noButton.setEnabled (
+ !(okButton.getSelection () || retryButton.getSelection () ||
+ abortButton.getSelection () || ignoreButton.getSelection ()));
+ retryButton.setEnabled (
+ !(okButton.getSelection() || yesButton.getSelection() || noButton.getSelection ()));
+ abortButton.setEnabled (
+ !(okButton.getSelection () || cancelButton.getSelection () ||
+ yesButton.getSelection () || noButton.getSelection ()));
+ ignoreButton.setEnabled (
+ !(okButton.getSelection () || cancelButton.getSelection () |
+ yesButton.getSelection () || noButton.getSelection ()));
+ }
+
+ /**
+ * Handle the create button selection event.
+ *
+ * @param event org.eclipse.swt.events.SelectionEvent
+ */
+ void createButtonSelected(SelectionEvent event) {
+
+ /* Compute the appropriate dialog style */
+ int style = SWT.NONE;
+ if (okButton.getEnabled () && okButton.getSelection ()) style |= SWT.OK;
+ if (cancelButton.getEnabled () && cancelButton.getSelection ()) style |= SWT.CANCEL;
+ if (yesButton.getEnabled () && yesButton.getSelection ()) style |= SWT.YES;
+ if (noButton.getEnabled () && noButton.getSelection ()) style |= SWT.NO;
+ if (retryButton.getEnabled () && retryButton.getSelection ()) style |= SWT.RETRY;
+ if (abortButton.getEnabled () && abortButton.getSelection ()) style |= SWT.ABORT;
+ if (ignoreButton.getEnabled () && ignoreButton.getSelection ()) style |= SWT.IGNORE;
+ if (iconErrorButton.getEnabled () && iconErrorButton.getSelection ()) style |= SWT.ICON_ERROR;
+ if (iconInformationButton.getEnabled () && iconInformationButton.getSelection ()) style |= SWT.ICON_INFORMATION;
+ if (iconQuestionButton.getEnabled () && iconQuestionButton.getSelection ()) style |= SWT.ICON_QUESTION;
+ if (iconWarningButton.getEnabled () && iconWarningButton.getSelection ()) style |= SWT.ICON_WARNING;
+ if (iconWorkingButton.getEnabled () && iconWorkingButton.getSelection ()) style |= SWT.ICON_WORKING;
+ if (primaryModalButton.getEnabled () && primaryModalButton.getSelection ()) style |= SWT.PRIMARY_MODAL;
+ if (applicationModalButton.getEnabled () && applicationModalButton.getSelection ()) style |= SWT.APPLICATION_MODAL;
+ if (systemModalButton.getEnabled () && systemModalButton.getSelection ()) style |= SWT.SYSTEM_MODAL;
+ if (saveButton.getEnabled () && saveButton.getSelection ()) style |= SWT.SAVE;
+ if (openButton.getEnabled () && openButton.getSelection ()) style |= SWT.OPEN;
+
+ /* Open the appropriate dialog type */
+ String name = dialogCombo.getText ();
+ Shell shell = tabFolderPage.getShell ();
+
+ if (name.equals (ControlExample.getResourceString("ColorDialog"))) {
+ ColorDialog dialog = new ColorDialog (shell ,style);
+ dialog.setRGB (new RGB (100, 100, 100));
+ dialog.setText (ControlExample.getResourceString("Title"));
+ RGB result = dialog.open ();
+ textWidget.append (ControlExample.getResourceString("ColorDialog") + Text.DELIMITER);
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
+ return;
+ }
+
+ if (name.equals (ControlExample.getResourceString("DirectoryDialog"))) {
+ DirectoryDialog dialog = new DirectoryDialog (shell, style);
+ dialog.setMessage (ControlExample.getResourceString("Example_string"));
+ dialog.setText (ControlExample.getResourceString("Title"));
+ String result = dialog.open ();
+ textWidget.append (ControlExample.getResourceString("DirectoryDialog") + Text.DELIMITER);
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
+ return;
+ }
+
+ if (name.equals (ControlExample.getResourceString("FileDialog"))) {
+ FileDialog dialog = new FileDialog (shell, style);
+ dialog.setFileName (ControlExample.getResourceString("readme_txt"));
+ dialog.setFilterNames (FilterNames);
+ dialog.setFilterExtensions (FilterExtensions);
+ dialog.setText (ControlExample.getResourceString("Title"));
+ String result = dialog.open();
+ textWidget.append (ControlExample.getResourceString("FileDialog") + Text.DELIMITER);
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
+ return;
+ }
+
+ if (name.equals (ControlExample.getResourceString("FontDialog"))) {
+ FontDialog dialog = new FontDialog (shell, style);
+ dialog.setText (ControlExample.getResourceString("Title"));
+ FontData result = dialog.open ();
+ textWidget.append (ControlExample.getResourceString("FontDialog") + Text.DELIMITER);
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
+ return;
+ }
+
+ if (name.equals (ControlExample.getResourceString("PrintDialog"))) {
+ PrintDialog dialog = new PrintDialog (shell, style);
+ dialog.setText(ControlExample.getResourceString("Title"));
+ PrinterData result = dialog.open ();
+ textWidget.append (ControlExample.getResourceString("PrintDialog") + Text.DELIMITER);
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"" + result}) + Text.DELIMITER + Text.DELIMITER);
+ return;
+ }
+
+ if (name.equals(ControlExample.getResourceString("MessageBox"))) {
+ MessageBox dialog = new MessageBox (shell, style);
+ dialog.setMessage (ControlExample.getResourceString("Example_string"));
+ dialog.setText (ControlExample.getResourceString("Title"));
+ int result = dialog.open ();
+ textWidget.append (ControlExample.getResourceString("MessageBox") + Text.DELIMITER);
+ /*
+ * The resulting integer depends on the original
+ * dialog style. Decode the result and display it.
+ */
+ switch (result) {
+ case SWT.OK:
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.OK"}));
+ break;
+ case SWT.YES:
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.YES"}));
+ break;
+ case SWT.NO:
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.NO"}));
+ break;
+ case SWT.CANCEL:
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.CANCEL"}));
+ break;
+ case SWT.ABORT:
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.ABORT"}));
+ break;
+ case SWT.RETRY:
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.RETRY"}));
+ break;
+ case SWT.IGNORE:
+ textWidget.append (ControlExample.getResourceString("Result", new String [] {"SWT.IGNORE"}));
+ break;
+ default:
+ textWidget.append(ControlExample.getResourceString("Result", new String [] {"" + result}));
+ break;
+ }
+ textWidget.append (Text.DELIMITER + Text.DELIMITER);
+ }
+ }
+
+ /**
+ * Creates the "Control" group.
+ */
+ void createControlGroup () {
+ /*
+ * Create the "Control" group. This is the group on the
+ * left half of each example tab. It consists of the
+ * style group, the display group and the size group.
+ */
+ controlGroup = new Group (tabFolderPage, SWT.NONE);
+ GridLayout gridLayout= new GridLayout ();
+ controlGroup.setLayout(gridLayout);
+ gridLayout.numColumns = 2;
+ gridLayout.makeColumnsEqualWidth = true;
+ controlGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ controlGroup.setText (ControlExample.getResourceString("Parameters"));
+
+ /*
+ * Create a group to hold the dialog style combo box and
+ * create dialog button.
+ */
+ dialogStyleGroup = new Group (controlGroup, SWT.NONE);
+ dialogStyleGroup.setLayout (new GridLayout ());
+ GridData gridData = new GridData (GridData.HORIZONTAL_ALIGN_CENTER);
+ gridData.horizontalSpan = 2;
+ dialogStyleGroup.setLayoutData (gridData);
+ dialogStyleGroup.setText (ControlExample.getResourceString("Dialog_Type"));
+ }
+
+ /**
+ * Creates the "Control" widget children.
+ */
+ void createControlWidgets () {
+
+ /* Create the combo */
+ String [] strings = {
+ ControlExample.getResourceString("ColorDialog"),
+ ControlExample.getResourceString("DirectoryDialog"),
+ ControlExample.getResourceString("FileDialog"),
+ ControlExample.getResourceString("FontDialog"),
+ ControlExample.getResourceString("PrintDialog"),
+ ControlExample.getResourceString("MessageBox"),
+ };
+ dialogCombo = new Combo (dialogStyleGroup, SWT.READ_ONLY);
+ dialogCombo.setItems (strings);
+ dialogCombo.setText (strings [0]);
+
+ /* Create the create dialog button */
+ Button createButton = new Button(dialogStyleGroup, SWT.NONE);
+ createButton.setText (ControlExample.getResourceString("Create_Dialog"));
+ createButton.setLayoutData (new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
+
+ /* Create a group for the various dialog button style controls */
+ Group buttonStyleGroup = new Group (controlGroup, SWT.NONE);
+ buttonStyleGroup.setLayout (new GridLayout ());
+ buttonStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ buttonStyleGroup.setText (ControlExample.getResourceString("Button_Styles"));
+
+ /* Create the button style buttons */
+ okButton = new Button (buttonStyleGroup, SWT.CHECK);
+ okButton.setText ("SWT.OK");
+ cancelButton = new Button (buttonStyleGroup, SWT.CHECK);
+ cancelButton.setText ("SWT.CANCEL");
+ yesButton = new Button (buttonStyleGroup, SWT.CHECK);
+ yesButton.setText ("SWT.YES");
+ noButton = new Button (buttonStyleGroup, SWT.CHECK);
+ noButton.setText ("SWT.NO");
+ retryButton = new Button (buttonStyleGroup, SWT.CHECK);
+ retryButton.setText ("SWT.RETRY");
+ abortButton = new Button (buttonStyleGroup, SWT.CHECK);
+ abortButton.setText ("SWT.ABORT");
+ ignoreButton = new Button (buttonStyleGroup, SWT.CHECK);
+ ignoreButton.setText ("SWT.IGNORE");
+
+ /* Create a group for the icon style controls */
+ Group iconStyleGroup = new Group (controlGroup, SWT.NONE);
+ iconStyleGroup.setLayout (new GridLayout ());
+ iconStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ iconStyleGroup.setText (ControlExample.getResourceString("Icon_Styles"));
+
+ /* Create the icon style buttons */
+ iconErrorButton = new Button (iconStyleGroup, SWT.RADIO);
+ iconErrorButton.setText ("SWT.ICON_ERROR");
+ iconInformationButton = new Button (iconStyleGroup, SWT.RADIO);
+ iconInformationButton.setText ("SWT.ICON_INFORMATION");
+ iconQuestionButton = new Button (iconStyleGroup, SWT.RADIO);
+ iconQuestionButton.setText ("SWT.ICON_QUESTION");
+ iconWarningButton = new Button (iconStyleGroup, SWT.RADIO);
+ iconWarningButton.setText ("SWT.ICON_WARNING");
+ iconWorkingButton = new Button (iconStyleGroup, SWT.RADIO);
+ iconWorkingButton.setText ("SWT.ICON_WORKING");
+
+ /* Create a group for the modal style controls */
+ Group modalStyleGroup = new Group (controlGroup, SWT.NONE);
+ modalStyleGroup.setLayout (new GridLayout ());
+ modalStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ modalStyleGroup.setText (ControlExample.getResourceString("Modal_Styles"));
+
+ /* Create the modal style buttons */
+ modelessButton = new Button (modalStyleGroup, SWT.RADIO);
+ modelessButton.setText ("SWT.MODELESS");
+ primaryModalButton = new Button (modalStyleGroup, SWT.RADIO);
+ primaryModalButton.setText ("SWT.PRIMARY_MODAL");
+ applicationModalButton = new Button (modalStyleGroup, SWT.RADIO);
+ applicationModalButton.setText ("SWT.APPLICATION_MODAL");
+ systemModalButton = new Button (modalStyleGroup, SWT.RADIO);
+ systemModalButton.setText ("SWT.SYSTEM_MODAL");
+
+ /* Create a group for the file dialog style controls */
+ Group fileDialogStyleGroup = new Group (controlGroup, SWT.NONE);
+ fileDialogStyleGroup.setLayout (new GridLayout ());
+ fileDialogStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ fileDialogStyleGroup.setText (ControlExample.getResourceString("File_Dialog_Styles"));
+
+ /* Create the file dialog style buttons */
+ saveButton = new Button (fileDialogStyleGroup, SWT.RADIO);
+ saveButton.setText ("SWT.SAVE");
+ openButton = new Button(fileDialogStyleGroup, SWT.RADIO);
+ openButton.setText("SWT.OPEN");
+
+ /* Add the listeners */
+ dialogCombo.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ dialogSelected (event);
+ };
+ });
+ createButton.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ createButtonSelected (event);
+ };
+ });
+ SelectionListener buttonStyleListener = new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ buttonStyleSelected (event);
+ };
+ };
+ okButton.addSelectionListener (buttonStyleListener);
+ cancelButton.addSelectionListener (buttonStyleListener);
+ yesButton.addSelectionListener (buttonStyleListener);
+ noButton.addSelectionListener (buttonStyleListener);
+ retryButton.addSelectionListener (buttonStyleListener);
+ abortButton.addSelectionListener (buttonStyleListener);
+ ignoreButton.addSelectionListener (buttonStyleListener);
+
+ /* Set default values for style buttons */
+ okButton.setEnabled (false);
+ cancelButton.setEnabled (false);
+ yesButton.setEnabled (false);
+ noButton.setEnabled (false);
+ retryButton.setEnabled (false);
+ abortButton.setEnabled (false);
+ ignoreButton.setEnabled (false);
+ iconErrorButton.setEnabled (false);
+ iconInformationButton.setEnabled (false);
+ iconQuestionButton.setEnabled (false);
+ iconWarningButton.setEnabled (false);
+ iconWorkingButton.setEnabled (false);
+ saveButton.setEnabled (false);
+ openButton.setEnabled (false);
+ openButton.setSelection (true);
+ iconInformationButton.setSelection (true);
+ modelessButton.setSelection (true);
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /*
+ * Create a group for the text widget to display
+ * the results returned by the example dialogs.
+ */
+ resultGroup = new Group (exampleGroup, SWT.NONE);
+ resultGroup.setLayout (new GridLayout ());
+ resultGroup.setLayoutData (new GridData (GridData.FILL_BOTH));
+ resultGroup.setText (ControlExample.getResourceString("Dialog_Result"));
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+ /*
+ * Create a multi lined, scrolled text widget for output.
+ */
+ textWidget = new Text(resultGroup, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
+ GridData gridData = new GridData (GridData.FILL_BOTH);
+ textWidget.setLayoutData (gridData);
+ }
+
+ /**
+ * Handle a dialog type combo selection event.
+ *
+ * @param event the selection event
+ */
+ void dialogSelected (SelectionEvent event) {
+
+ /* Enable/Disable the buttons */
+ String name = dialogCombo.getText ();
+ boolean isMessageBox = name.equals (ControlExample.getResourceString("MessageBox"));
+ boolean isFileDialog = name.equals (ControlExample.getResourceString("FileDialog"));
+ okButton.setEnabled (isMessageBox);
+ cancelButton.setEnabled (isMessageBox);
+ yesButton.setEnabled (isMessageBox);
+ noButton.setEnabled (isMessageBox);
+ retryButton.setEnabled (isMessageBox);
+ abortButton.setEnabled (isMessageBox);
+ ignoreButton.setEnabled (isMessageBox);
+ iconErrorButton.setEnabled (isMessageBox);
+ iconInformationButton.setEnabled (isMessageBox);
+ iconQuestionButton.setEnabled (isMessageBox);
+ iconWarningButton.setEnabled (isMessageBox);
+ iconWorkingButton.setEnabled (isMessageBox);
+ saveButton.setEnabled (isFileDialog);
+ openButton.setEnabled (isFileDialog);
+
+ /* Unselect the buttons */
+ if (!isMessageBox) {
+ okButton.setSelection (false);
+ cancelButton.setSelection (false);
+ yesButton.setSelection (false);
+ noButton.setSelection (false);
+ retryButton.setSelection (false);
+ abortButton.setSelection (false);
+ ignoreButton.setSelection (false);
+ }
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [0];
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Dialog";
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/LabelTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/LabelTab.java
index 491b068167..2cbb912791 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/LabelTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/LabelTab.java
@@ -1,175 +1,175 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-class LabelTab extends AlignableTab {
- /* Example widgets and groups that contain them */
- Label label1, label2, label3, label4, label5, label6;
- Group textLabelGroup, imageLabelGroup;
-
- /* Style widgets added to the "Style" group */
- Button separatorButton, wrapButton, horizontalButton, verticalButton, shadowInButton, shadowOutButton;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- LabelTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for the text labels */
- textLabelGroup = new Group(exampleGroup, SWT.NONE);
- GridLayout gridLayout = new GridLayout ();
- textLabelGroup.setLayout (gridLayout);
- gridLayout.numColumns = 3;
- textLabelGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- textLabelGroup.setText (ControlExample.getResourceString("Text_Labels"));
-
- /* Create a group for the image labels */
- imageLabelGroup = new Group (exampleGroup, SWT.SHADOW_NONE);
- gridLayout = new GridLayout ();
- imageLabelGroup.setLayout (gridLayout);
- gridLayout.numColumns = 3;
- imageLabelGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- imageLabelGroup.setText (ControlExample.getResourceString("Image_Labels"));
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
-
- /* Compute the widget style */
- int style = SWT.NONE;
- if (separatorButton.getSelection ()) style |= SWT.SEPARATOR;
- if (wrapButton.getSelection ()) style |= SWT.WRAP;
- if (horizontalButton.getSelection ()) style |= SWT.HORIZONTAL;
- if (verticalButton.getSelection ()) style |= SWT.VERTICAL;
- if (shadowInButton.getSelection ()) style |= SWT.SHADOW_IN;
- if (shadowOutButton.getSelection ()) style |= SWT.SHADOW_OUT;
- if (borderButton.getSelection ()) style |= SWT.BORDER;
-
- /* Create the example widgets */
- label1 = new Label (textLabelGroup, style);
- label1.setText(ControlExample.getResourceString("One"));
- label2 = new Label (textLabelGroup, style);
- label2.setText(ControlExample.getResourceString("Two"));
- label3 = new Label (textLabelGroup, style);
- if (wrapButton.getSelection ()) {
- label3.setText (ControlExample.getResourceString("Wrap_Text"));
- } else {
- label3.setText (ControlExample.getResourceString("Three"));
- }
- label4 = new Label (imageLabelGroup, style);
- label4.setImage (instance.images[ControlExample.ciClosedFolder]);
- label5 = new Label (imageLabelGroup, style);
- label5.setImage (instance.images[ControlExample.ciOpenFolder]);
- label6 = new Label(imageLabelGroup, style);
- label6.setImage (instance.images[ControlExample.ciTarget]);
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup() {
- super.createStyleGroup ();
-
- /* Create the extra widgets */
- separatorButton = new Button (styleGroup, SWT.CHECK);
- separatorButton.setText ("SWT.SEPARATOR");
- wrapButton = new Button (styleGroup, SWT.CHECK);
- wrapButton.setText ("SWT.WRAP");
- horizontalButton = new Button (styleGroup, SWT.RADIO);
- horizontalButton.setText ("SWT.HORIZONTAL");
- verticalButton = new Button (styleGroup, SWT.RADIO);
- verticalButton.setText ("SWT.VERTICAL");
- Group styleSubGroup = new Group (styleGroup, SWT.NONE);
- styleSubGroup.setLayout (new GridLayout ());
- shadowInButton = new Button (styleSubGroup, SWT.RADIO);
- shadowInButton.setText ("SWT.SHADOW_IN");
- shadowOutButton = new Button (styleSubGroup, SWT.RADIO);
- shadowOutButton.setText ("SWT.SHADOW_OUT");
- borderButton = new Button(styleGroup, SWT.CHECK);
- borderButton.setText("SWT.BORDER");
-
- /* Add the listeners */
- SelectionListener selectionListener = new SelectionAdapter () {
- public void widgetSelected(SelectionEvent event) {
- if ((event.widget.getStyle() & SWT.RADIO) != 0) {
- if (!((Button) event.widget).getSelection ()) return;
- }
- recreateExampleWidgets ();
- };
- };
- shadowInButton.addSelectionListener (selectionListener);
- shadowOutButton.addSelectionListener (selectionListener);
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {label1, label2, label3, label4, label5, label6};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Label";
- }
-
- /**
- * Sets the alignment of the "Example" widgets.
- */
- void setExampleWidgetAlignment () {
- int alignment = 0;
- if (leftButton.getSelection ()) alignment = SWT.LEFT;
- if (centerButton.getSelection ()) alignment = SWT.CENTER;
- if (rightButton.getSelection ()) alignment = SWT.RIGHT;
- label1.setAlignment (alignment);
- label2.setAlignment (alignment);
- label3.setAlignment (alignment);
- label4.setAlignment (alignment);
- label5.setAlignment (alignment);
- label6.setAlignment (alignment);
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- boolean isSeparator = (label1.getStyle () & SWT.SEPARATOR) != 0;
- wrapButton.setSelection (!isSeparator && (label1.getStyle () & SWT.WRAP) != 0);
- leftButton.setSelection (!isSeparator && (label1.getStyle () & SWT.LEFT) != 0);
- centerButton.setSelection (!isSeparator && (label1.getStyle () & SWT.CENTER) != 0);
- rightButton.setSelection (!isSeparator && (label1.getStyle () & SWT.RIGHT) != 0);
- shadowInButton.setSelection (isSeparator && (label1.getStyle () & SWT.SHADOW_IN) != 0);
- shadowOutButton.setSelection (!shadowInButton.getSelection ());
- wrapButton.setEnabled (!isSeparator);
- leftButton.setEnabled (!isSeparator);
- centerButton.setEnabled (!isSeparator);
- rightButton.setEnabled (!isSeparator);
- shadowInButton.setEnabled (isSeparator);
- shadowOutButton.setEnabled (isSeparator);
- horizontalButton.setEnabled (isSeparator);
- verticalButton.setEnabled (isSeparator);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+class LabelTab extends AlignableTab {
+ /* Example widgets and groups that contain them */
+ Label label1, label2, label3, label4, label5, label6;
+ Group textLabelGroup, imageLabelGroup;
+
+ /* Style widgets added to the "Style" group */
+ Button separatorButton, wrapButton, horizontalButton, verticalButton, shadowInButton, shadowOutButton;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ LabelTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for the text labels */
+ textLabelGroup = new Group(exampleGroup, SWT.NONE);
+ GridLayout gridLayout = new GridLayout ();
+ textLabelGroup.setLayout (gridLayout);
+ gridLayout.numColumns = 3;
+ textLabelGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ textLabelGroup.setText (ControlExample.getResourceString("Text_Labels"));
+
+ /* Create a group for the image labels */
+ imageLabelGroup = new Group (exampleGroup, SWT.SHADOW_NONE);
+ gridLayout = new GridLayout ();
+ imageLabelGroup.setLayout (gridLayout);
+ gridLayout.numColumns = 3;
+ imageLabelGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ imageLabelGroup.setText (ControlExample.getResourceString("Image_Labels"));
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (separatorButton.getSelection ()) style |= SWT.SEPARATOR;
+ if (wrapButton.getSelection ()) style |= SWT.WRAP;
+ if (horizontalButton.getSelection ()) style |= SWT.HORIZONTAL;
+ if (verticalButton.getSelection ()) style |= SWT.VERTICAL;
+ if (shadowInButton.getSelection ()) style |= SWT.SHADOW_IN;
+ if (shadowOutButton.getSelection ()) style |= SWT.SHADOW_OUT;
+ if (borderButton.getSelection ()) style |= SWT.BORDER;
+
+ /* Create the example widgets */
+ label1 = new Label (textLabelGroup, style);
+ label1.setText(ControlExample.getResourceString("One"));
+ label2 = new Label (textLabelGroup, style);
+ label2.setText(ControlExample.getResourceString("Two"));
+ label3 = new Label (textLabelGroup, style);
+ if (wrapButton.getSelection ()) {
+ label3.setText (ControlExample.getResourceString("Wrap_Text"));
+ } else {
+ label3.setText (ControlExample.getResourceString("Three"));
+ }
+ label4 = new Label (imageLabelGroup, style);
+ label4.setImage (instance.images[ControlExample.ciClosedFolder]);
+ label5 = new Label (imageLabelGroup, style);
+ label5.setImage (instance.images[ControlExample.ciOpenFolder]);
+ label6 = new Label(imageLabelGroup, style);
+ label6.setImage (instance.images[ControlExample.ciTarget]);
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup() {
+ super.createStyleGroup ();
+
+ /* Create the extra widgets */
+ separatorButton = new Button (styleGroup, SWT.CHECK);
+ separatorButton.setText ("SWT.SEPARATOR");
+ wrapButton = new Button (styleGroup, SWT.CHECK);
+ wrapButton.setText ("SWT.WRAP");
+ horizontalButton = new Button (styleGroup, SWT.RADIO);
+ horizontalButton.setText ("SWT.HORIZONTAL");
+ verticalButton = new Button (styleGroup, SWT.RADIO);
+ verticalButton.setText ("SWT.VERTICAL");
+ Group styleSubGroup = new Group (styleGroup, SWT.NONE);
+ styleSubGroup.setLayout (new GridLayout ());
+ shadowInButton = new Button (styleSubGroup, SWT.RADIO);
+ shadowInButton.setText ("SWT.SHADOW_IN");
+ shadowOutButton = new Button (styleSubGroup, SWT.RADIO);
+ shadowOutButton.setText ("SWT.SHADOW_OUT");
+ borderButton = new Button(styleGroup, SWT.CHECK);
+ borderButton.setText("SWT.BORDER");
+
+ /* Add the listeners */
+ SelectionListener selectionListener = new SelectionAdapter () {
+ public void widgetSelected(SelectionEvent event) {
+ if ((event.widget.getStyle() & SWT.RADIO) != 0) {
+ if (!((Button) event.widget).getSelection ()) return;
+ }
+ recreateExampleWidgets ();
+ };
+ };
+ shadowInButton.addSelectionListener (selectionListener);
+ shadowOutButton.addSelectionListener (selectionListener);
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {label1, label2, label3, label4, label5, label6};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Label";
+ }
+
+ /**
+ * Sets the alignment of the "Example" widgets.
+ */
+ void setExampleWidgetAlignment () {
+ int alignment = 0;
+ if (leftButton.getSelection ()) alignment = SWT.LEFT;
+ if (centerButton.getSelection ()) alignment = SWT.CENTER;
+ if (rightButton.getSelection ()) alignment = SWT.RIGHT;
+ label1.setAlignment (alignment);
+ label2.setAlignment (alignment);
+ label3.setAlignment (alignment);
+ label4.setAlignment (alignment);
+ label5.setAlignment (alignment);
+ label6.setAlignment (alignment);
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ boolean isSeparator = (label1.getStyle () & SWT.SEPARATOR) != 0;
+ wrapButton.setSelection (!isSeparator && (label1.getStyle () & SWT.WRAP) != 0);
+ leftButton.setSelection (!isSeparator && (label1.getStyle () & SWT.LEFT) != 0);
+ centerButton.setSelection (!isSeparator && (label1.getStyle () & SWT.CENTER) != 0);
+ rightButton.setSelection (!isSeparator && (label1.getStyle () & SWT.RIGHT) != 0);
+ shadowInButton.setSelection (isSeparator && (label1.getStyle () & SWT.SHADOW_IN) != 0);
+ shadowOutButton.setSelection (!shadowInButton.getSelection ());
+ wrapButton.setEnabled (!isSeparator);
+ leftButton.setEnabled (!isSeparator);
+ centerButton.setEnabled (!isSeparator);
+ rightButton.setEnabled (!isSeparator);
+ shadowInButton.setEnabled (isSeparator);
+ shadowOutButton.setEnabled (isSeparator);
+ horizontalButton.setEnabled (isSeparator);
+ verticalButton.setEnabled (isSeparator);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ListTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ListTab.java
index f63e1d6f84..2cf49fb1cf 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ListTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ListTab.java
@@ -1,81 +1,81 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-
-class ListTab extends ScrollableTab {
-
- /* Example widgets and groups that contain them */
- List list1;
- Group listGroup;
-
- static String [] ListData1 = {ControlExample.getResourceString("ListData1_0"),
- ControlExample.getResourceString("ListData1_1"),
- ControlExample.getResourceString("ListData1_2"),
- ControlExample.getResourceString("ListData1_3"),
- ControlExample.getResourceString("ListData1_4"),
- ControlExample.getResourceString("ListData1_5"),
- ControlExample.getResourceString("ListData1_6"),
- ControlExample.getResourceString("ListData1_7"),
- ControlExample.getResourceString("ListData1_8")};
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- ListTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for the list */
- listGroup = new Group (exampleGroup, SWT.NONE);
- listGroup.setLayout (new GridLayout ());
- listGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- listGroup.setText ("List");
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
-
- /* Compute the widget style */
- int style = SWT.NONE;
- if (singleButton.getSelection ()) style |= SWT.SINGLE;
- if (multiButton.getSelection ()) style |= SWT.MULTI;
- if (horizontalButton.getSelection ()) style |= SWT.H_SCROLL;
- if (verticalButton.getSelection ()) style |= SWT.V_SCROLL;
- if (borderButton.getSelection ()) style |= SWT.BORDER;
-
- /* Create the example widgets */
- list1 = new List (listGroup, style);
- list1.setItems (ListData1);
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {list1};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "List";
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+
+class ListTab extends ScrollableTab {
+
+ /* Example widgets and groups that contain them */
+ List list1;
+ Group listGroup;
+
+ static String [] ListData1 = {ControlExample.getResourceString("ListData1_0"),
+ ControlExample.getResourceString("ListData1_1"),
+ ControlExample.getResourceString("ListData1_2"),
+ ControlExample.getResourceString("ListData1_3"),
+ ControlExample.getResourceString("ListData1_4"),
+ ControlExample.getResourceString("ListData1_5"),
+ ControlExample.getResourceString("ListData1_6"),
+ ControlExample.getResourceString("ListData1_7"),
+ ControlExample.getResourceString("ListData1_8")};
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ ListTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for the list */
+ listGroup = new Group (exampleGroup, SWT.NONE);
+ listGroup.setLayout (new GridLayout ());
+ listGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ listGroup.setText ("List");
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (singleButton.getSelection ()) style |= SWT.SINGLE;
+ if (multiButton.getSelection ()) style |= SWT.MULTI;
+ if (horizontalButton.getSelection ()) style |= SWT.H_SCROLL;
+ if (verticalButton.getSelection ()) style |= SWT.V_SCROLL;
+ if (borderButton.getSelection ()) style |= SWT.BORDER;
+
+ /* Create the example widgets */
+ list1 = new List (listGroup, style);
+ list1.setItems (ListData1);
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {list1};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "List";
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ProgressBarTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ProgressBarTab.java
index 9a350e8c1a..f56f5ae6ff 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ProgressBarTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ProgressBarTab.java
@@ -1,141 +1,141 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-
-class ProgressBarTab extends RangeTab {
- /* Example widgets and groups that contain them */
- ProgressBar progressBar1;
- Group progressBarGroup;
-
- /* Style widgets added to the "Style" group */
- Button smoothButton;
- Button indeterminateButton;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- ProgressBarTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup() {
- super.createExampleGroup ();
-
- /* Create a group for the progress bar */
- progressBarGroup = new Group (exampleGroup, SWT.NONE);
- progressBarGroup.setLayout (new GridLayout ());
- progressBarGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- progressBarGroup.setText ("ProgressBar");
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
-
- /* Compute the widget style */
- int style = SWT.NONE;
- if (horizontalButton.getSelection ()) style |= SWT.HORIZONTAL;
- if (verticalButton.getSelection ()) style |= SWT.VERTICAL;
- if (smoothButton.getSelection ()) style |= SWT.SMOOTH;
- if (borderButton.getSelection ()) style |= SWT.BORDER;
- if (indeterminateButton.getSelection ()) style |= SWT.INDETERMINATE;
-
- /* Create the example widgets */
- progressBar1 = new ProgressBar (progressBarGroup, style);
- progressBar1.setMaximum (100);
- progressBar1.setSelection (50);
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup () {
- super.createStyleGroup ();
-
- /* Create the extra widgets */
- smoothButton = new Button (styleGroup, SWT.CHECK);
- smoothButton.setText ("SWT.SMOOTH");
- indeterminateButton = new Button (styleGroup, SWT.CHECK);
- indeterminateButton.setText ("SWT.INDETERMINATE");
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {progressBar1};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "ProgressBar";
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- if (indeterminateButton.getSelection ()) {
- selectionScale.setEnabled (false);
- minimumScale.setEnabled (false);
- maximumScale.setEnabled (false);
- } else {
- selectionScale.setEnabled (true);
- minimumScale.setEnabled (true);
- maximumScale.setEnabled (true);
- }
- maximumScale.setMaximum (progressBar1.getMaximum ());
- smoothButton.setSelection ((progressBar1.getStyle () & SWT.SMOOTH) != 0);
- indeterminateButton.setSelection ((progressBar1.getStyle () & SWT.INDETERMINATE) != 0);
- }
-
- /**
- * Sets the maximum of the "Example" widgets.
- */
- void setWidgetMaximum () {
- progressBar1.setMaximum (maximumScale.getSelection ());
- updateScales ();
- }
-
- /**
- * Sets the minimim of the "Example" widgets.
- */
- void setWidgetMinimum () {
- progressBar1.setMinimum (minimumScale.getSelection ());
- updateScales ();
- }
-
- /**
- * Sets the selection of the "Example" widgets.
- */
- void setWidgetSelection () {
- progressBar1.setSelection (selectionScale.getSelection ());
- updateScales ();
- }
-
- /**
- * Update the scale widgets to reflect the actual value set
- * on the "Example" widget.
- */
- void updateScales () {
- minimumScale.setSelection (progressBar1.getMinimum ());
- selectionScale.setSelection (progressBar1.getSelection ());
- maximumScale.setSelection (progressBar1.getMaximum ());
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+
+class ProgressBarTab extends RangeTab {
+ /* Example widgets and groups that contain them */
+ ProgressBar progressBar1;
+ Group progressBarGroup;
+
+ /* Style widgets added to the "Style" group */
+ Button smoothButton;
+ Button indeterminateButton;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ ProgressBarTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup() {
+ super.createExampleGroup ();
+
+ /* Create a group for the progress bar */
+ progressBarGroup = new Group (exampleGroup, SWT.NONE);
+ progressBarGroup.setLayout (new GridLayout ());
+ progressBarGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ progressBarGroup.setText ("ProgressBar");
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (horizontalButton.getSelection ()) style |= SWT.HORIZONTAL;
+ if (verticalButton.getSelection ()) style |= SWT.VERTICAL;
+ if (smoothButton.getSelection ()) style |= SWT.SMOOTH;
+ if (borderButton.getSelection ()) style |= SWT.BORDER;
+ if (indeterminateButton.getSelection ()) style |= SWT.INDETERMINATE;
+
+ /* Create the example widgets */
+ progressBar1 = new ProgressBar (progressBarGroup, style);
+ progressBar1.setMaximum (100);
+ progressBar1.setSelection (50);
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup () {
+ super.createStyleGroup ();
+
+ /* Create the extra widgets */
+ smoothButton = new Button (styleGroup, SWT.CHECK);
+ smoothButton.setText ("SWT.SMOOTH");
+ indeterminateButton = new Button (styleGroup, SWT.CHECK);
+ indeterminateButton.setText ("SWT.INDETERMINATE");
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {progressBar1};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "ProgressBar";
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ if (indeterminateButton.getSelection ()) {
+ selectionScale.setEnabled (false);
+ minimumScale.setEnabled (false);
+ maximumScale.setEnabled (false);
+ } else {
+ selectionScale.setEnabled (true);
+ minimumScale.setEnabled (true);
+ maximumScale.setEnabled (true);
+ }
+ maximumScale.setMaximum (progressBar1.getMaximum ());
+ smoothButton.setSelection ((progressBar1.getStyle () & SWT.SMOOTH) != 0);
+ indeterminateButton.setSelection ((progressBar1.getStyle () & SWT.INDETERMINATE) != 0);
+ }
+
+ /**
+ * Sets the maximum of the "Example" widgets.
+ */
+ void setWidgetMaximum () {
+ progressBar1.setMaximum (maximumScale.getSelection ());
+ updateScales ();
+ }
+
+ /**
+ * Sets the minimim of the "Example" widgets.
+ */
+ void setWidgetMinimum () {
+ progressBar1.setMinimum (minimumScale.getSelection ());
+ updateScales ();
+ }
+
+ /**
+ * Sets the selection of the "Example" widgets.
+ */
+ void setWidgetSelection () {
+ progressBar1.setSelection (selectionScale.getSelection ());
+ updateScales ();
+ }
+
+ /**
+ * Update the scale widgets to reflect the actual value set
+ * on the "Example" widget.
+ */
+ void updateScales () {
+ minimumScale.setSelection (progressBar1.getMinimum ());
+ selectionScale.setSelection (progressBar1.getSelection ());
+ maximumScale.setSelection (progressBar1.getMaximum ());
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/RangeTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/RangeTab.java
index f72f61fff5..549d427c15 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/RangeTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/RangeTab.java
@@ -1,179 +1,179 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-abstract class RangeTab extends Tab {
- /* Style widgets added to the "Style" group */
- Button horizontalButton, verticalButton;
-
- /* Scale widgets added to the "Control" group */
- Scale minimumScale, selectionScale, maximumScale;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- RangeTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Control" widget children.
- */
- void createControlWidgets () {
- /* Create controls specific to this example */
- createMinimumGroup ();
- createMaximumGroup ();
- createSelectionGroup ();
- }
-
- /**
- * Create a group of widgets to control the maximum
- * attribute of the example widget.
- */
- void createMaximumGroup() {
-
- /* Create the group */
- Group maximumGroup = new Group (controlGroup, SWT.NONE);
- maximumGroup.setLayout (new GridLayout ());
- maximumGroup.setText (ControlExample.getResourceString("Maximum"));
- maximumGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
-
- /* Create a scale widget */
- maximumScale = new Scale (maximumGroup, SWT.NONE);
- maximumScale.setMaximum (100);
- maximumScale.setSelection (100);
- maximumScale.setPageIncrement (10);
- maximumScale.setIncrement (5);
-
- GridData data = new GridData (GridData.FILL_HORIZONTAL);
- data.widthHint = 100;
- maximumScale.setLayoutData (data);
-
- /* Add the listeners */
- maximumScale.addSelectionListener(new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setWidgetMaximum ();
- };
- });
- }
-
- /**
- * Create a group of widgets to control the minimum
- * attribute of the example widget.
- */
- void createMinimumGroup() {
-
- /* Create the group */
- Group minimumGroup = new Group (controlGroup, SWT.NONE);
- minimumGroup.setLayout (new GridLayout ());
- minimumGroup.setText (ControlExample.getResourceString("Minimum"));
- minimumGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
-
- /* Create a scale widget */
- minimumScale = new Scale (minimumGroup, SWT.NONE);
- minimumScale.setMaximum (100);
- minimumScale.setPageIncrement (10);
- minimumScale.setIncrement (5);
-
- GridData data = new GridData (GridData.FILL_HORIZONTAL);
- data.widthHint = 100;
- minimumScale.setLayoutData (data);
-
- /* Add the listeners */
- minimumScale.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setWidgetMinimum ();
- };
- });
-
- }
-
- /**
- * Create a group of widgets to control the selection
- * attribute of the example widget.
- */
- void createSelectionGroup() {
-
- /* Create the group */
- Group selectionGroup = new Group(controlGroup, SWT.NONE);
- selectionGroup.setLayout(new GridLayout());
- GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
- selectionGroup.setLayoutData(gridData);
- selectionGroup.setText(ControlExample.getResourceString("Selection"));
-
- /* Create a scale widget */
- selectionScale = new Scale (selectionGroup, SWT.NONE);
- selectionScale.setMaximum (100);
- selectionScale.setSelection (50);
- selectionScale.setPageIncrement (10);
- selectionScale.setIncrement (5);
-
- GridData data = new GridData (GridData.FILL_HORIZONTAL);
- data.widthHint = 100;
- selectionScale.setLayoutData (data);
-
- /* Add the listeners */
- selectionScale.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- setWidgetSelection ();
- };
- });
-
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup () {
- super.createStyleGroup ();
-
- /* Create the extra widgets */
- horizontalButton = new Button (styleGroup, SWT.RADIO);
- horizontalButton.setText ("SWT.HORIZONTAL");
- verticalButton = new Button (styleGroup, SWT.RADIO);
- verticalButton.setText ("SWT.VERTICAL");
- borderButton = new Button (styleGroup, SWT.CHECK);
- borderButton.setText ("SWT.BORDER");
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- setWidgetMinimum ();
- setWidgetMaximum ();
- setWidgetSelection ();
- Control [] controls = getExampleWidgets ();
- if (controls.length != 0){
- horizontalButton.setSelection ((controls [0].getStyle () & SWT.HORIZONTAL) != 0);
- verticalButton.setSelection ((controls [0].getStyle () & SWT.VERTICAL) != 0);
- borderButton.setSelection ((controls [0].getStyle () & SWT.BORDER) != 0);
- }
- }
-
- /**
- * Sets the maximum of the "Example" widgets.
- */
- abstract void setWidgetMaximum ();
-
- /**
- * Sets the minimim of the "Example" widgets.
- */
- abstract void setWidgetMinimum ();
-
- /**
- * Sets the selection of the "Example" widgets.
- */
- abstract void setWidgetSelection ();
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+abstract class RangeTab extends Tab {
+ /* Style widgets added to the "Style" group */
+ Button horizontalButton, verticalButton;
+
+ /* Scale widgets added to the "Control" group */
+ Scale minimumScale, selectionScale, maximumScale;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ RangeTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Control" widget children.
+ */
+ void createControlWidgets () {
+ /* Create controls specific to this example */
+ createMinimumGroup ();
+ createMaximumGroup ();
+ createSelectionGroup ();
+ }
+
+ /**
+ * Create a group of widgets to control the maximum
+ * attribute of the example widget.
+ */
+ void createMaximumGroup() {
+
+ /* Create the group */
+ Group maximumGroup = new Group (controlGroup, SWT.NONE);
+ maximumGroup.setLayout (new GridLayout ());
+ maximumGroup.setText (ControlExample.getResourceString("Maximum"));
+ maximumGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
+
+ /* Create a scale widget */
+ maximumScale = new Scale (maximumGroup, SWT.NONE);
+ maximumScale.setMaximum (100);
+ maximumScale.setSelection (100);
+ maximumScale.setPageIncrement (10);
+ maximumScale.setIncrement (5);
+
+ GridData data = new GridData (GridData.FILL_HORIZONTAL);
+ data.widthHint = 100;
+ maximumScale.setLayoutData (data);
+
+ /* Add the listeners */
+ maximumScale.addSelectionListener(new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setWidgetMaximum ();
+ };
+ });
+ }
+
+ /**
+ * Create a group of widgets to control the minimum
+ * attribute of the example widget.
+ */
+ void createMinimumGroup() {
+
+ /* Create the group */
+ Group minimumGroup = new Group (controlGroup, SWT.NONE);
+ minimumGroup.setLayout (new GridLayout ());
+ minimumGroup.setText (ControlExample.getResourceString("Minimum"));
+ minimumGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
+
+ /* Create a scale widget */
+ minimumScale = new Scale (minimumGroup, SWT.NONE);
+ minimumScale.setMaximum (100);
+ minimumScale.setPageIncrement (10);
+ minimumScale.setIncrement (5);
+
+ GridData data = new GridData (GridData.FILL_HORIZONTAL);
+ data.widthHint = 100;
+ minimumScale.setLayoutData (data);
+
+ /* Add the listeners */
+ minimumScale.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setWidgetMinimum ();
+ };
+ });
+
+ }
+
+ /**
+ * Create a group of widgets to control the selection
+ * attribute of the example widget.
+ */
+ void createSelectionGroup() {
+
+ /* Create the group */
+ Group selectionGroup = new Group(controlGroup, SWT.NONE);
+ selectionGroup.setLayout(new GridLayout());
+ GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
+ selectionGroup.setLayoutData(gridData);
+ selectionGroup.setText(ControlExample.getResourceString("Selection"));
+
+ /* Create a scale widget */
+ selectionScale = new Scale (selectionGroup, SWT.NONE);
+ selectionScale.setMaximum (100);
+ selectionScale.setSelection (50);
+ selectionScale.setPageIncrement (10);
+ selectionScale.setIncrement (5);
+
+ GridData data = new GridData (GridData.FILL_HORIZONTAL);
+ data.widthHint = 100;
+ selectionScale.setLayoutData (data);
+
+ /* Add the listeners */
+ selectionScale.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ setWidgetSelection ();
+ };
+ });
+
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup () {
+ super.createStyleGroup ();
+
+ /* Create the extra widgets */
+ horizontalButton = new Button (styleGroup, SWT.RADIO);
+ horizontalButton.setText ("SWT.HORIZONTAL");
+ verticalButton = new Button (styleGroup, SWT.RADIO);
+ verticalButton.setText ("SWT.VERTICAL");
+ borderButton = new Button (styleGroup, SWT.CHECK);
+ borderButton.setText ("SWT.BORDER");
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ setWidgetMinimum ();
+ setWidgetMaximum ();
+ setWidgetSelection ();
+ Control [] controls = getExampleWidgets ();
+ if (controls.length != 0){
+ horizontalButton.setSelection ((controls [0].getStyle () & SWT.HORIZONTAL) != 0);
+ verticalButton.setSelection ((controls [0].getStyle () & SWT.VERTICAL) != 0);
+ borderButton.setSelection ((controls [0].getStyle () & SWT.BORDER) != 0);
+ }
+ }
+
+ /**
+ * Sets the maximum of the "Example" widgets.
+ */
+ abstract void setWidgetMaximum ();
+
+ /**
+ * Sets the minimim of the "Example" widgets.
+ */
+ abstract void setWidgetMinimum ();
+
+ /**
+ * Sets the selection of the "Example" widgets.
+ */
+ abstract void setWidgetSelection ();
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SashTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SashTab.java
index abb4b5d353..2823ec0728 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SashTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SashTab.java
@@ -1,180 +1,180 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.events.*;
-
-class SashTab extends Tab {
- /* Example widgets and groups that contain them */
- Sash hSash, vSash;
- List list1, list2, list3;
- Text text;
-
- static String [] ListData0 = {ControlExample.getResourceString("ListData0_0"),
- ControlExample.getResourceString("ListData0_1"),
- ControlExample.getResourceString("ListData0_2"),
- ControlExample.getResourceString("ListData0_3"),
- ControlExample.getResourceString("ListData0_4"),
- ControlExample.getResourceString("ListData0_5"),
- ControlExample.getResourceString("ListData0_6"),
- ControlExample.getResourceString("ListData0_7"),
- ControlExample.getResourceString("ListData0_8")};
-
- static String [] ListData1 = {ControlExample.getResourceString("ListData1_0"),
- ControlExample.getResourceString("ListData1_1"),
- ControlExample.getResourceString("ListData1_2"),
- ControlExample.getResourceString("ListData1_3"),
- ControlExample.getResourceString("ListData1_4"),
- ControlExample.getResourceString("ListData1_5"),
- ControlExample.getResourceString("ListData1_6"),
- ControlExample.getResourceString("ListData1_7"),
- ControlExample.getResourceString("ListData1_8")};
-
- /* Constants */
- static final int SASH_WIDTH = 3;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- SashTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the tab folder page.
- */
- Composite createTabFolderPage (TabFolder tabFolder) {
- /*
- * Create the page. This example does not use layouts.
- */
- tabFolderPage = new Composite(tabFolder, SWT.BORDER);
-
- /* Create the list and text widgets */
- list1 = new List (tabFolderPage, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
- list1.setItems (ListData0);
- list2 = new List (tabFolderPage, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
- list2.setItems (ListData1);
- text = new Text (tabFolderPage, SWT.MULTI | SWT.BORDER);
- text.setText (ControlExample.getResourceString("Multi_line"));
-
- /* Create the sashes */
- vSash = new Sash (tabFolderPage, SWT.VERTICAL);
- hSash = new Sash (tabFolderPage, SWT.HORIZONTAL);
-
- /* Add the listeners */
- hSash.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- if (event.detail != SWT.DRAG) {
- hSash.setBounds (event.x, event.y, event.width, event.height);
- layout ();
- }
- }
- });
- vSash.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- if (event.detail != SWT.DRAG) {
- vSash.setBounds(event.x, event.y, event.width, event.height);
- layout ();
- }
- }
- });
- tabFolderPage.addControlListener (new ControlAdapter () {
- public void controlResized (ControlEvent event) {
- shellResized ();
- }
- });
-
- /*
- * Do not set the bounds of the lists, text and sashes here
- * because this method is run before the widget is opened
- * so we do not know how big the tabComposite is going to be.
- * When the widget is opened a resize event will occur
- * and the contained widgets can be sized accordingly.
- */
- return tabFolderPage;
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {hSash, vSash};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Sash";
- }
-
- /**
- * Layout the list and text widgets according to the new
- * positions of the sashes..events.SelectionEvent
- */
- void layout () {
-
- Rectangle tabCompositeBounds = tabFolderPage.getClientArea ();
- Rectangle hSashBounds = hSash.getBounds ();
- Rectangle vSashBounds = vSash.getBounds ();
-
- list1.setBounds (0, 0, vSashBounds.x, hSashBounds.y);
- list2.setBounds (vSashBounds.x + vSashBounds.width, 0, tabCompositeBounds.width - (vSashBounds.x + vSashBounds.width), hSashBounds.y);
- text.setBounds (0, hSashBounds.y + hSashBounds.height, tabCompositeBounds.width, tabCompositeBounds.height - (hSashBounds.y + hSashBounds.height));
-
- /**
- * If the horizontal sash has been moved then the vertical
- * sash is either too long or too short and its size must
- * be adjusted.
- */
- vSashBounds.height = hSashBounds.y;
- vSash.setBounds (vSashBounds);
- }
-
- /**
- * Recreates the "Example" widgets.
- */
- void recreateExampleWidgets () {
- // this tab does not use this framework mechanism
- }
-
- /**
- * Handle the shell resized event.
- */
- void shellResized () {
-
- /* Get the client area for the shell */
- Rectangle tabFolderPageBounds = tabFolderPage.getClientArea ();
-
- /*
- * Make list 1 half the width and half the height of the tab leaving room for the sash.
- * Place list 1 in the top left quadrant of the tab.
- */
- Rectangle list1Bounds = new Rectangle (0, 0, (tabFolderPageBounds.width - SASH_WIDTH) / 2, (tabFolderPageBounds.height - SASH_WIDTH) / 2);
- list1.setBounds (list1Bounds);
-
- /*
- * Make list 2 half the width and half the height of the tab leaving room for the sash.
- * Place list 2 in the top right quadrant of the tab.
- */
- list2.setBounds (list1Bounds.width + SASH_WIDTH, 0, tabFolderPageBounds.width - (list1Bounds.width + SASH_WIDTH), list1Bounds.height);
-
- /*
- * Make the text area the full width and half the height of the tab leaving room for the sash.
- * Place the text area in the bottom half of the tab.
- */
- text.setBounds (0, list1Bounds.height + SASH_WIDTH, tabFolderPageBounds.width, tabFolderPageBounds.height - (list1Bounds.height + SASH_WIDTH));
-
- /* Position the sashes */
- vSash.setBounds (list1Bounds.width, 0, SASH_WIDTH, list1Bounds.height);
- hSash.setBounds (0, list1Bounds.height, tabFolderPageBounds.width, SASH_WIDTH);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.events.*;
+
+class SashTab extends Tab {
+ /* Example widgets and groups that contain them */
+ Sash hSash, vSash;
+ List list1, list2, list3;
+ Text text;
+
+ static String [] ListData0 = {ControlExample.getResourceString("ListData0_0"),
+ ControlExample.getResourceString("ListData0_1"),
+ ControlExample.getResourceString("ListData0_2"),
+ ControlExample.getResourceString("ListData0_3"),
+ ControlExample.getResourceString("ListData0_4"),
+ ControlExample.getResourceString("ListData0_5"),
+ ControlExample.getResourceString("ListData0_6"),
+ ControlExample.getResourceString("ListData0_7"),
+ ControlExample.getResourceString("ListData0_8")};
+
+ static String [] ListData1 = {ControlExample.getResourceString("ListData1_0"),
+ ControlExample.getResourceString("ListData1_1"),
+ ControlExample.getResourceString("ListData1_2"),
+ ControlExample.getResourceString("ListData1_3"),
+ ControlExample.getResourceString("ListData1_4"),
+ ControlExample.getResourceString("ListData1_5"),
+ ControlExample.getResourceString("ListData1_6"),
+ ControlExample.getResourceString("ListData1_7"),
+ ControlExample.getResourceString("ListData1_8")};
+
+ /* Constants */
+ static final int SASH_WIDTH = 3;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ SashTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the tab folder page.
+ */
+ Composite createTabFolderPage (TabFolder tabFolder) {
+ /*
+ * Create the page. This example does not use layouts.
+ */
+ tabFolderPage = new Composite(tabFolder, SWT.BORDER);
+
+ /* Create the list and text widgets */
+ list1 = new List (tabFolderPage, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
+ list1.setItems (ListData0);
+ list2 = new List (tabFolderPage, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
+ list2.setItems (ListData1);
+ text = new Text (tabFolderPage, SWT.MULTI | SWT.BORDER);
+ text.setText (ControlExample.getResourceString("Multi_line"));
+
+ /* Create the sashes */
+ vSash = new Sash (tabFolderPage, SWT.VERTICAL);
+ hSash = new Sash (tabFolderPage, SWT.HORIZONTAL);
+
+ /* Add the listeners */
+ hSash.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ if (event.detail != SWT.DRAG) {
+ hSash.setBounds (event.x, event.y, event.width, event.height);
+ layout ();
+ }
+ }
+ });
+ vSash.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ if (event.detail != SWT.DRAG) {
+ vSash.setBounds(event.x, event.y, event.width, event.height);
+ layout ();
+ }
+ }
+ });
+ tabFolderPage.addControlListener (new ControlAdapter () {
+ public void controlResized (ControlEvent event) {
+ shellResized ();
+ }
+ });
+
+ /*
+ * Do not set the bounds of the lists, text and sashes here
+ * because this method is run before the widget is opened
+ * so we do not know how big the tabComposite is going to be.
+ * When the widget is opened a resize event will occur
+ * and the contained widgets can be sized accordingly.
+ */
+ return tabFolderPage;
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {hSash, vSash};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Sash";
+ }
+
+ /**
+ * Layout the list and text widgets according to the new
+ * positions of the sashes..events.SelectionEvent
+ */
+ void layout () {
+
+ Rectangle tabCompositeBounds = tabFolderPage.getClientArea ();
+ Rectangle hSashBounds = hSash.getBounds ();
+ Rectangle vSashBounds = vSash.getBounds ();
+
+ list1.setBounds (0, 0, vSashBounds.x, hSashBounds.y);
+ list2.setBounds (vSashBounds.x + vSashBounds.width, 0, tabCompositeBounds.width - (vSashBounds.x + vSashBounds.width), hSashBounds.y);
+ text.setBounds (0, hSashBounds.y + hSashBounds.height, tabCompositeBounds.width, tabCompositeBounds.height - (hSashBounds.y + hSashBounds.height));
+
+ /**
+ * If the horizontal sash has been moved then the vertical
+ * sash is either too long or too short and its size must
+ * be adjusted.
+ */
+ vSashBounds.height = hSashBounds.y;
+ vSash.setBounds (vSashBounds);
+ }
+
+ /**
+ * Recreates the "Example" widgets.
+ */
+ void recreateExampleWidgets () {
+ // this tab does not use this framework mechanism
+ }
+
+ /**
+ * Handle the shell resized event.
+ */
+ void shellResized () {
+
+ /* Get the client area for the shell */
+ Rectangle tabFolderPageBounds = tabFolderPage.getClientArea ();
+
+ /*
+ * Make list 1 half the width and half the height of the tab leaving room for the sash.
+ * Place list 1 in the top left quadrant of the tab.
+ */
+ Rectangle list1Bounds = new Rectangle (0, 0, (tabFolderPageBounds.width - SASH_WIDTH) / 2, (tabFolderPageBounds.height - SASH_WIDTH) / 2);
+ list1.setBounds (list1Bounds);
+
+ /*
+ * Make list 2 half the width and half the height of the tab leaving room for the sash.
+ * Place list 2 in the top right quadrant of the tab.
+ */
+ list2.setBounds (list1Bounds.width + SASH_WIDTH, 0, tabFolderPageBounds.width - (list1Bounds.width + SASH_WIDTH), list1Bounds.height);
+
+ /*
+ * Make the text area the full width and half the height of the tab leaving room for the sash.
+ * Place the text area in the bottom half of the tab.
+ */
+ text.setBounds (0, list1Bounds.height + SASH_WIDTH, tabFolderPageBounds.width, tabFolderPageBounds.height - (list1Bounds.height + SASH_WIDTH));
+
+ /* Position the sashes */
+ vSash.setBounds (list1Bounds.width, 0, SASH_WIDTH, list1Bounds.height);
+ hSash.setBounds (0, list1Bounds.height, tabFolderPageBounds.width, SASH_WIDTH);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ScrollableTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ScrollableTab.java
index cf7a40576e..183b207530 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ScrollableTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ScrollableTab.java
@@ -1,59 +1,59 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-
-abstract class ScrollableTab extends Tab {
- /* Style widgets added to the "Style" group */
- Button singleButton, multiButton, horizontalButton, verticalButton, borderButton;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- ScrollableTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup () {
- super.createStyleGroup ();
-
- /* Create the extra widgets */
- singleButton = new Button (styleGroup, SWT.RADIO);
- singleButton.setText ("SWT.SINGLE");
- multiButton = new Button (styleGroup, SWT.RADIO);
- multiButton.setText ("SWT.MULTI");
- horizontalButton = new Button (styleGroup, SWT.CHECK);
- horizontalButton.setText ("SWT.H_SCROLL");
- horizontalButton.setSelection(true);
- verticalButton = new Button (styleGroup, SWT.CHECK);
- verticalButton.setText ("SWT.V_SCROLL");
- verticalButton.setSelection(true);
- borderButton = new Button (styleGroup, SWT.CHECK);
- borderButton.setText ("SWT.BORDER");
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- Control [] controls = getExampleWidgets ();
- if (controls.length != 0){
- singleButton.setSelection ((controls [0].getStyle () & SWT.SINGLE) != 0);
- multiButton.setSelection ((controls [0].getStyle () & SWT.MULTI) != 0);
- horizontalButton.setSelection ((controls [0].getStyle () & SWT.H_SCROLL) != 0);
- verticalButton.setSelection ((controls [0].getStyle () & SWT.V_SCROLL) != 0);
- borderButton.setSelection ((controls [0].getStyle () & SWT.BORDER) != 0);
- }
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+
+abstract class ScrollableTab extends Tab {
+ /* Style widgets added to the "Style" group */
+ Button singleButton, multiButton, horizontalButton, verticalButton, borderButton;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ ScrollableTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup () {
+ super.createStyleGroup ();
+
+ /* Create the extra widgets */
+ singleButton = new Button (styleGroup, SWT.RADIO);
+ singleButton.setText ("SWT.SINGLE");
+ multiButton = new Button (styleGroup, SWT.RADIO);
+ multiButton.setText ("SWT.MULTI");
+ horizontalButton = new Button (styleGroup, SWT.CHECK);
+ horizontalButton.setText ("SWT.H_SCROLL");
+ horizontalButton.setSelection(true);
+ verticalButton = new Button (styleGroup, SWT.CHECK);
+ verticalButton.setText ("SWT.V_SCROLL");
+ verticalButton.setSelection(true);
+ borderButton = new Button (styleGroup, SWT.CHECK);
+ borderButton.setText ("SWT.BORDER");
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ Control [] controls = getExampleWidgets ();
+ if (controls.length != 0){
+ singleButton.setSelection ((controls [0].getStyle () & SWT.SINGLE) != 0);
+ multiButton.setSelection ((controls [0].getStyle () & SWT.MULTI) != 0);
+ horizontalButton.setSelection ((controls [0].getStyle () & SWT.H_SCROLL) != 0);
+ verticalButton.setSelection ((controls [0].getStyle () & SWT.V_SCROLL) != 0);
+ borderButton.setSelection ((controls [0].getStyle () & SWT.BORDER) != 0);
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ShellTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ShellTab.java
index 5f7e90c072..ca73f33a82 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ShellTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ShellTab.java
@@ -1,287 +1,287 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-class ShellTab extends Tab {
- /* Style widgets added to the "Style" group */
- Button noParentButton, parentButton;
- Button noTrimButton, closeButton, titleButton, minButton, maxButton, borderButton, resizeButton, onTopButton;
- Button createButton, closeAllButton;
- Button modelessButton, primaryModalButton, applicationModalButton, systemModalButton;
- Group parentStyleGroup, modalStyleGroup;
-
- /* Variables used to track the open shells */
- int shellCount = 0;
- Shell [] shells = new Shell [4];
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- ShellTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Close all the example shells.
- */
- void closeAllShells() {
- for (int i = 0; i<shellCount; i++) {
- if (shells[i] != null & !shells [i].isDisposed ()) {
- shells [i].dispose();
- }
- }
- shellCount = 0;
- }
-
- /**
- * Handle the Create button selection event.
- *
- * @param event org.eclipse.swt.events.SelectionEvent
- */
- public void createButtonSelected(SelectionEvent event) {
-
- /*
- * Remember the example shells so they
- * can be disposed by the user.
- */
- if (shellCount >= shells.length) {
- Shell [] newShells = new Shell [shells.length + 4];
- System.arraycopy (shells, 0, newShells, 0, shells.length);
- shells = newShells;
- }
-
- /* Compute the shell style */
- int style = SWT.NONE;
- if (noTrimButton.getSelection()) style |= SWT.NO_TRIM;
- if (closeButton.getSelection()) style |= SWT.CLOSE;
- if (titleButton.getSelection()) style |= SWT.TITLE;
- if (minButton.getSelection()) style |= SWT.MIN;
- if (maxButton.getSelection()) style |= SWT.MAX;
- if (borderButton.getSelection()) style |= SWT.BORDER;
- if (resizeButton.getSelection()) style |= SWT.RESIZE;
- if (onTopButton.getSelection()) style |= SWT.ON_TOP;
- if (modelessButton.getSelection()) style |= SWT.MODELESS;
- if (primaryModalButton.getSelection()) style |= SWT.PRIMARY_MODAL;
- if (applicationModalButton.getSelection()) style |= SWT.APPLICATION_MODAL;
- if (systemModalButton.getSelection()) style |= SWT.SYSTEM_MODAL;
-
- /* Create the shell with or without a parent */
- if (noParentButton.getSelection ()) {
- shells [shellCount] = new Shell (style);
- } else {
- Shell shell = tabFolderPage.getShell ();
- shells [shellCount] = new Shell (shell, style);
- }
- final Shell currentShell = shells [shellCount];
- Button button = new Button(currentShell, SWT.PUSH);
- button.setBounds(20, 20, 120, 30);
- Button closeButton = new Button(currentShell, SWT.PUSH);
- closeButton.setBounds(160, 20, 120, 30);
- closeButton.setText(ControlExample.getResourceString("Close"));
- closeButton.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- currentShell.dispose();
- }
- });
-
- /* Set the size, title and open the shell */
- currentShell.setSize (300, 100);
- currentShell.setText (ControlExample.getResourceString("Title") + shellCount);
- currentShell.open ();
- shellCount++;
- }
-
- /**
- * Creates the "Control" group.
- */
- void createControlGroup () {
- /*
- * Create the "Control" group. This is the group on the
- * left half of each example tab. It consists of the
- * style group, the display group and the size group.
- */
- controlGroup = new Group (tabFolderPage, SWT.NONE);
- GridLayout gridLayout= new GridLayout ();
- controlGroup.setLayout (gridLayout);
- gridLayout.numColumns = 1;
- gridLayout.makeColumnsEqualWidth = true;
- controlGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- controlGroup.setText (ControlExample.getResourceString("Parameters"));
-
- /* Create individual groups inside the "Control" group */
- styleGroup = new Group (controlGroup, SWT.NONE);
- gridLayout = new GridLayout ();
- styleGroup.setLayout (gridLayout);
- gridLayout.numColumns = 2;
- gridLayout.makeColumnsEqualWidth = true;
- styleGroup.setLayoutData (new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- styleGroup.setText (ControlExample.getResourceString("Styles"));
-
- /* Create a group for the parent style controls */
- parentStyleGroup = new Group (styleGroup, SWT.NONE);
- parentStyleGroup.setLayout (new GridLayout ());
- GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- parentStyleGroup.setLayoutData (gridData);
- parentStyleGroup.setText (ControlExample.getResourceString("Parent"));
- }
-
- /**
- * Creates the "Control" widget children.
- */
- void createControlWidgets () {
-
- /* Create the parent style buttons */
- noParentButton = new Button (parentStyleGroup, SWT.RADIO);
- noParentButton.setText (ControlExample.getResourceString("No_Parent"));
- parentButton = new Button (parentStyleGroup, SWT.RADIO);
- parentButton.setText (ControlExample.getResourceString("Parent"));
-
- /* Create a group for the decoration style controls */
- Group decorationStyleGroup = new Group(styleGroup, SWT.NONE);
- decorationStyleGroup.setLayout (new GridLayout ());
- GridData gridData = new GridData (GridData.HORIZONTAL_ALIGN_FILL);
- gridData.verticalSpan = 2;
- decorationStyleGroup.setLayoutData (gridData);
- decorationStyleGroup.setText (ControlExample.getResourceString("Decoration_Styles"));
-
- /* Create the decoration style buttons */
- noTrimButton = new Button (decorationStyleGroup, SWT.CHECK);
- noTrimButton.setText ("SWT.NO_TRIM");
- closeButton = new Button (decorationStyleGroup, SWT.CHECK);
- closeButton.setText ("SWT.CLOSE");
- titleButton = new Button (decorationStyleGroup, SWT.CHECK);
- titleButton.setText ("SWT.TITLE");
- minButton = new Button (decorationStyleGroup, SWT.CHECK);
- minButton.setText ("SWT.MIN");
- maxButton = new Button (decorationStyleGroup, SWT.CHECK);
- maxButton.setText ("SWT.MAX");
- borderButton = new Button (decorationStyleGroup, SWT.CHECK);
- borderButton.setText ("SWT.BORDER");
- resizeButton = new Button (decorationStyleGroup, SWT.CHECK);
- resizeButton.setText ("SWT.RESIZE");
- onTopButton = new Button (decorationStyleGroup, SWT.CHECK);
- onTopButton.setText ("SWT.ON_TOP");
-
- /* Create a group for the modal style controls */
- modalStyleGroup = new Group (styleGroup, SWT.NONE);
- modalStyleGroup.setLayout (new GridLayout ());
- modalStyleGroup.setText (ControlExample.getResourceString("Modal_Styles"));
- gridData = new GridData ();
- gridData.verticalAlignment = GridData.FILL;
- modalStyleGroup.setLayoutData(gridData);
-
- /* Create the modal style buttons */
- modelessButton = new Button (modalStyleGroup, SWT.RADIO);
- modelessButton.setText ("SWT.MODELESS");
- primaryModalButton = new Button (modalStyleGroup, SWT.RADIO);
- primaryModalButton.setText ("SWT.PRIMARY_MODAL");
- applicationModalButton = new Button (modalStyleGroup, SWT.RADIO);
- applicationModalButton.setText ("SWT.APPLICATION_MODAL");
- systemModalButton = new Button (modalStyleGroup, SWT.RADIO);
- systemModalButton.setText ("SWT.SYSTEM_MODAL");
-
- /* Create the "create" and "closeAll" buttons */
- createButton = new Button (styleGroup, SWT.NONE);
- gridData = new GridData (GridData.HORIZONTAL_ALIGN_END);
- createButton.setLayoutData (gridData);
- createButton.setText (ControlExample.getResourceString("Create_Shell"));
- closeAllButton = new Button (styleGroup, SWT.NONE);
- gridData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
- closeAllButton.setText (ControlExample.getResourceString("Close_All_Shells"));
- closeAllButton.setLayoutData (gridData);
-
- /* Add the listeners */
- createButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- createButtonSelected(e);
- };
- });
- closeAllButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- closeAllShells ();
- };
- });
- SelectionListener decorationButtonListener = new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- decorationButtonSelected(event);
- };
- };
- noTrimButton.addSelectionListener (decorationButtonListener);
- closeButton.addSelectionListener (decorationButtonListener);
- titleButton.addSelectionListener (decorationButtonListener);
- minButton.addSelectionListener (decorationButtonListener);
- maxButton.addSelectionListener (decorationButtonListener);
- borderButton.addSelectionListener (decorationButtonListener);
- resizeButton.addSelectionListener (decorationButtonListener);
- applicationModalButton.addSelectionListener (decorationButtonListener);
- systemModalButton.addSelectionListener (decorationButtonListener);
-
- /* Set the default state */
- noParentButton.setSelection (true);
- modelessButton.setSelection (true);
- }
-
- /**
- * Handle a decoration button selection event.
- *
- * @param event org.eclipse.swt.events.SelectionEvent
- */
- public void decorationButtonSelected(SelectionEvent event) {
-
- /* Make sure if the modal style is SWT.APPLICATION_MODAL or
- * SWT.SYSTEM_MODAL the style SWT.CLOSE is also selected.
- * This is to make sure the user can close the shell.
- */
- Button widget = (Button) event.widget;
- if (widget == applicationModalButton || widget == systemModalButton) {
- if (widget.getSelection()) {
- closeButton.setSelection (true);
- noTrimButton.setSelection (false);
- }
- return;
- }
- if (widget == closeButton) {
- if (applicationModalButton.getSelection() || systemModalButton.getSelection()) {
- closeButton.setSelection (true);
- }
- }
- /*
- * Make sure if the No Trim button is selected then
- * all other decoration buttons are deselected.
- */
- if (widget.getSelection() && widget != noTrimButton) {
- noTrimButton.setSelection (false);
- return;
- }
- if (widget.getSelection() && widget == noTrimButton) {
- if (applicationModalButton.getSelection() || systemModalButton.getSelection()) {
- noTrimButton.setSelection (false);
- return;
- }
- closeButton.setSelection (false);
- titleButton.setSelection (false);
- minButton.setSelection (false);
- maxButton.setSelection (false);
- borderButton.setSelection (false);
- resizeButton.setSelection (false);
- return;
- }
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Shell";
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+class ShellTab extends Tab {
+ /* Style widgets added to the "Style" group */
+ Button noParentButton, parentButton;
+ Button noTrimButton, closeButton, titleButton, minButton, maxButton, borderButton, resizeButton, onTopButton;
+ Button createButton, closeAllButton;
+ Button modelessButton, primaryModalButton, applicationModalButton, systemModalButton;
+ Group parentStyleGroup, modalStyleGroup;
+
+ /* Variables used to track the open shells */
+ int shellCount = 0;
+ Shell [] shells = new Shell [4];
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ ShellTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Close all the example shells.
+ */
+ void closeAllShells() {
+ for (int i = 0; i<shellCount; i++) {
+ if (shells[i] != null & !shells [i].isDisposed ()) {
+ shells [i].dispose();
+ }
+ }
+ shellCount = 0;
+ }
+
+ /**
+ * Handle the Create button selection event.
+ *
+ * @param event org.eclipse.swt.events.SelectionEvent
+ */
+ public void createButtonSelected(SelectionEvent event) {
+
+ /*
+ * Remember the example shells so they
+ * can be disposed by the user.
+ */
+ if (shellCount >= shells.length) {
+ Shell [] newShells = new Shell [shells.length + 4];
+ System.arraycopy (shells, 0, newShells, 0, shells.length);
+ shells = newShells;
+ }
+
+ /* Compute the shell style */
+ int style = SWT.NONE;
+ if (noTrimButton.getSelection()) style |= SWT.NO_TRIM;
+ if (closeButton.getSelection()) style |= SWT.CLOSE;
+ if (titleButton.getSelection()) style |= SWT.TITLE;
+ if (minButton.getSelection()) style |= SWT.MIN;
+ if (maxButton.getSelection()) style |= SWT.MAX;
+ if (borderButton.getSelection()) style |= SWT.BORDER;
+ if (resizeButton.getSelection()) style |= SWT.RESIZE;
+ if (onTopButton.getSelection()) style |= SWT.ON_TOP;
+ if (modelessButton.getSelection()) style |= SWT.MODELESS;
+ if (primaryModalButton.getSelection()) style |= SWT.PRIMARY_MODAL;
+ if (applicationModalButton.getSelection()) style |= SWT.APPLICATION_MODAL;
+ if (systemModalButton.getSelection()) style |= SWT.SYSTEM_MODAL;
+
+ /* Create the shell with or without a parent */
+ if (noParentButton.getSelection ()) {
+ shells [shellCount] = new Shell (style);
+ } else {
+ Shell shell = tabFolderPage.getShell ();
+ shells [shellCount] = new Shell (shell, style);
+ }
+ final Shell currentShell = shells [shellCount];
+ Button button = new Button(currentShell, SWT.PUSH);
+ button.setBounds(20, 20, 120, 30);
+ Button closeButton = new Button(currentShell, SWT.PUSH);
+ closeButton.setBounds(160, 20, 120, 30);
+ closeButton.setText(ControlExample.getResourceString("Close"));
+ closeButton.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ currentShell.dispose();
+ }
+ });
+
+ /* Set the size, title and open the shell */
+ currentShell.setSize (300, 100);
+ currentShell.setText (ControlExample.getResourceString("Title") + shellCount);
+ currentShell.open ();
+ shellCount++;
+ }
+
+ /**
+ * Creates the "Control" group.
+ */
+ void createControlGroup () {
+ /*
+ * Create the "Control" group. This is the group on the
+ * left half of each example tab. It consists of the
+ * style group, the display group and the size group.
+ */
+ controlGroup = new Group (tabFolderPage, SWT.NONE);
+ GridLayout gridLayout= new GridLayout ();
+ controlGroup.setLayout (gridLayout);
+ gridLayout.numColumns = 1;
+ gridLayout.makeColumnsEqualWidth = true;
+ controlGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ controlGroup.setText (ControlExample.getResourceString("Parameters"));
+
+ /* Create individual groups inside the "Control" group */
+ styleGroup = new Group (controlGroup, SWT.NONE);
+ gridLayout = new GridLayout ();
+ styleGroup.setLayout (gridLayout);
+ gridLayout.numColumns = 2;
+ gridLayout.makeColumnsEqualWidth = true;
+ styleGroup.setLayoutData (new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ styleGroup.setText (ControlExample.getResourceString("Styles"));
+
+ /* Create a group for the parent style controls */
+ parentStyleGroup = new Group (styleGroup, SWT.NONE);
+ parentStyleGroup.setLayout (new GridLayout ());
+ GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
+ parentStyleGroup.setLayoutData (gridData);
+ parentStyleGroup.setText (ControlExample.getResourceString("Parent"));
+ }
+
+ /**
+ * Creates the "Control" widget children.
+ */
+ void createControlWidgets () {
+
+ /* Create the parent style buttons */
+ noParentButton = new Button (parentStyleGroup, SWT.RADIO);
+ noParentButton.setText (ControlExample.getResourceString("No_Parent"));
+ parentButton = new Button (parentStyleGroup, SWT.RADIO);
+ parentButton.setText (ControlExample.getResourceString("Parent"));
+
+ /* Create a group for the decoration style controls */
+ Group decorationStyleGroup = new Group(styleGroup, SWT.NONE);
+ decorationStyleGroup.setLayout (new GridLayout ());
+ GridData gridData = new GridData (GridData.HORIZONTAL_ALIGN_FILL);
+ gridData.verticalSpan = 2;
+ decorationStyleGroup.setLayoutData (gridData);
+ decorationStyleGroup.setText (ControlExample.getResourceString("Decoration_Styles"));
+
+ /* Create the decoration style buttons */
+ noTrimButton = new Button (decorationStyleGroup, SWT.CHECK);
+ noTrimButton.setText ("SWT.NO_TRIM");
+ closeButton = new Button (decorationStyleGroup, SWT.CHECK);
+ closeButton.setText ("SWT.CLOSE");
+ titleButton = new Button (decorationStyleGroup, SWT.CHECK);
+ titleButton.setText ("SWT.TITLE");
+ minButton = new Button (decorationStyleGroup, SWT.CHECK);
+ minButton.setText ("SWT.MIN");
+ maxButton = new Button (decorationStyleGroup, SWT.CHECK);
+ maxButton.setText ("SWT.MAX");
+ borderButton = new Button (decorationStyleGroup, SWT.CHECK);
+ borderButton.setText ("SWT.BORDER");
+ resizeButton = new Button (decorationStyleGroup, SWT.CHECK);
+ resizeButton.setText ("SWT.RESIZE");
+ onTopButton = new Button (decorationStyleGroup, SWT.CHECK);
+ onTopButton.setText ("SWT.ON_TOP");
+
+ /* Create a group for the modal style controls */
+ modalStyleGroup = new Group (styleGroup, SWT.NONE);
+ modalStyleGroup.setLayout (new GridLayout ());
+ modalStyleGroup.setText (ControlExample.getResourceString("Modal_Styles"));
+ gridData = new GridData ();
+ gridData.verticalAlignment = GridData.FILL;
+ modalStyleGroup.setLayoutData(gridData);
+
+ /* Create the modal style buttons */
+ modelessButton = new Button (modalStyleGroup, SWT.RADIO);
+ modelessButton.setText ("SWT.MODELESS");
+ primaryModalButton = new Button (modalStyleGroup, SWT.RADIO);
+ primaryModalButton.setText ("SWT.PRIMARY_MODAL");
+ applicationModalButton = new Button (modalStyleGroup, SWT.RADIO);
+ applicationModalButton.setText ("SWT.APPLICATION_MODAL");
+ systemModalButton = new Button (modalStyleGroup, SWT.RADIO);
+ systemModalButton.setText ("SWT.SYSTEM_MODAL");
+
+ /* Create the "create" and "closeAll" buttons */
+ createButton = new Button (styleGroup, SWT.NONE);
+ gridData = new GridData (GridData.HORIZONTAL_ALIGN_END);
+ createButton.setLayoutData (gridData);
+ createButton.setText (ControlExample.getResourceString("Create_Shell"));
+ closeAllButton = new Button (styleGroup, SWT.NONE);
+ gridData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
+ closeAllButton.setText (ControlExample.getResourceString("Close_All_Shells"));
+ closeAllButton.setLayoutData (gridData);
+
+ /* Add the listeners */
+ createButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ createButtonSelected(e);
+ };
+ });
+ closeAllButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ closeAllShells ();
+ };
+ });
+ SelectionListener decorationButtonListener = new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ decorationButtonSelected(event);
+ };
+ };
+ noTrimButton.addSelectionListener (decorationButtonListener);
+ closeButton.addSelectionListener (decorationButtonListener);
+ titleButton.addSelectionListener (decorationButtonListener);
+ minButton.addSelectionListener (decorationButtonListener);
+ maxButton.addSelectionListener (decorationButtonListener);
+ borderButton.addSelectionListener (decorationButtonListener);
+ resizeButton.addSelectionListener (decorationButtonListener);
+ applicationModalButton.addSelectionListener (decorationButtonListener);
+ systemModalButton.addSelectionListener (decorationButtonListener);
+
+ /* Set the default state */
+ noParentButton.setSelection (true);
+ modelessButton.setSelection (true);
+ }
+
+ /**
+ * Handle a decoration button selection event.
+ *
+ * @param event org.eclipse.swt.events.SelectionEvent
+ */
+ public void decorationButtonSelected(SelectionEvent event) {
+
+ /* Make sure if the modal style is SWT.APPLICATION_MODAL or
+ * SWT.SYSTEM_MODAL the style SWT.CLOSE is also selected.
+ * This is to make sure the user can close the shell.
+ */
+ Button widget = (Button) event.widget;
+ if (widget == applicationModalButton || widget == systemModalButton) {
+ if (widget.getSelection()) {
+ closeButton.setSelection (true);
+ noTrimButton.setSelection (false);
+ }
+ return;
+ }
+ if (widget == closeButton) {
+ if (applicationModalButton.getSelection() || systemModalButton.getSelection()) {
+ closeButton.setSelection (true);
+ }
+ }
+ /*
+ * Make sure if the No Trim button is selected then
+ * all other decoration buttons are deselected.
+ */
+ if (widget.getSelection() && widget != noTrimButton) {
+ noTrimButton.setSelection (false);
+ return;
+ }
+ if (widget.getSelection() && widget == noTrimButton) {
+ if (applicationModalButton.getSelection() || systemModalButton.getSelection()) {
+ noTrimButton.setSelection (false);
+ return;
+ }
+ closeButton.setSelection (false);
+ titleButton.setSelection (false);
+ minButton.setSelection (false);
+ maxButton.setSelection (false);
+ borderButton.setSelection (false);
+ resizeButton.setSelection (false);
+ return;
+ }
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Shell";
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SliderTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SliderTab.java
index 893f0e0bd4..91e9b894fc 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SliderTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/SliderTab.java
@@ -1,249 +1,249 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-class SliderTab extends RangeTab {
- /* Example widgets and groups that contain them */
- Scale scale1;
- Slider slider1;
- Group sliderGroup, scaleGroup;
-
- /* Scale widgets added to the "Control" group */
- Scale incrementScale, pageIncrementScale, thumbScale;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- SliderTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Control" widget children.
- */
- void createControlWidgets () {
- super.createControlWidgets ();
- createThumbGroup ();
- createIncrementGroup ();
- createPageIncrementGroup ();
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for the slider */
- sliderGroup = new Group (exampleGroup, SWT.NONE);
- sliderGroup.setLayout (new GridLayout ());
- sliderGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- sliderGroup.setText ("Slider");
-
- /* Create a group for the scale */
- scaleGroup = new Group (exampleGroup, SWT.NONE);
- scaleGroup.setLayout (new GridLayout ());
- scaleGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- scaleGroup.setText ("Scale");
-
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
-
- /* Compute the widget style */
- int style = SWT.NONE;
- if (horizontalButton.getSelection ()) style |= SWT.HORIZONTAL;
- if (verticalButton.getSelection ()) style |= SWT.VERTICAL;
- if (borderButton.getSelection ()) style |= SWT.BORDER;
-
- /* Create the example widgets */
- scale1 = new Scale (scaleGroup, style);
- scale1.setMaximum (100);
- scale1.setSelection (50);
- scale1.setIncrement (5);
- scale1.setPageIncrement (10);
- slider1 = new Slider(sliderGroup, style);
- slider1.setMaximum (100);
- slider1.setSelection (50);
- slider1.setIncrement(5);
- slider1.setPageIncrement (10);
- slider1.setThumb (10);
- }
-
- /**
- * Create a group of widgets to control the increment
- * attribute of the example widget.
- */
- void createIncrementGroup() {
-
- /* Create the group */
- Group incrementGroup = new Group (controlGroup, SWT.NONE);
- incrementGroup.setLayout (new GridLayout ());
- incrementGroup.setText (ControlExample.getResourceString("Increment"));
- incrementGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
-
- /* Create the scale widget */
- incrementScale = new Scale (incrementGroup, SWT.NONE);
- incrementScale.setMaximum (100);
- incrementScale.setSelection (5);
- incrementScale.setPageIncrement (10);
- incrementScale.setIncrement (5);
-
- GridData data = new GridData (GridData.FILL_HORIZONTAL);
- data.widthHint = 100;
- incrementScale.setLayoutData (data);
-
- /* Add the listeners */
- incrementScale.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent e) {
- setWidgetIncrement ();
- };
- });
- }
-
- /**
- * Create a group of widgets to control the page increment
- * attribute of the example widget.
- */
- void createPageIncrementGroup() {
-
- /* Create the group */
- Group pageIncrementGroup = new Group (controlGroup, SWT.NONE);
- pageIncrementGroup.setLayout (new GridLayout ());
- pageIncrementGroup.setText (ControlExample.getResourceString("Page_Increment"));
- pageIncrementGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
-
- /* Create the scale widget */
- pageIncrementScale = new Scale (pageIncrementGroup, SWT.NONE);
- pageIncrementScale.setMaximum (100);
- pageIncrementScale.setSelection (10);
- pageIncrementScale.setPageIncrement (10);
- pageIncrementScale.setIncrement (5);
-
- GridData data = new GridData (GridData.FILL_HORIZONTAL);
- data.widthHint = 100;
- pageIncrementScale.setLayoutData (data);
-
- /* Add the listeners */
- pageIncrementScale.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setWidgetPageIncrement ();
- }
- });
- }
-
- /**
- * Create a group of widgets to control the thumb
- * attribute of the example widget.
- */
- void createThumbGroup() {
-
- /* Create the group */
- Group thumbGroup = new Group (controlGroup, SWT.NONE);
- thumbGroup.setLayout (new GridLayout ());
- thumbGroup.setText (ControlExample.getResourceString("Thumb"));
- thumbGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
-
- /* Create the scale widget */
- thumbScale = new Scale (thumbGroup, SWT.NONE);
- thumbScale.setMaximum (100);
- thumbScale.setSelection (10);
- thumbScale.setPageIncrement (10);
- thumbScale.setIncrement (5);
-
- GridData data = new GridData (GridData.FILL_HORIZONTAL);
- data.widthHint = 100;
- thumbScale.setLayoutData (data);
-
- /* Add the listeners */
- thumbScale.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setWidgetThumb ();
- };
- });
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {scale1, slider1};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return ControlExample.getResourceString("Slider_and_Scale");
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- setWidgetIncrement ();
- setWidgetPageIncrement ();
- setWidgetThumb ();
- }
-
- /**
- * Sets the increment of the "Example" widgets.
- */
- void setWidgetIncrement () {
- slider1.setIncrement (incrementScale.getSelection ());
- scale1.setIncrement (incrementScale.getSelection ());
- }
-
- /**
- * Sets the minimim of the "Example" widgets.
- */
- void setWidgetMaximum () {
- slider1.setMaximum (maximumScale.getSelection ());
- scale1.setMaximum (maximumScale.getSelection ());
- }
-
- /**
- * Sets the minimim of the "Example" widgets.
- */
- void setWidgetMinimum () {
- slider1.setMinimum (minimumScale.getSelection ());
- scale1.setMinimum (minimumScale.getSelection ());
- }
-
- /**
- * Sets the page increment of the "Example" widgets.
- */
- void setWidgetPageIncrement () {
- slider1.setPageIncrement (pageIncrementScale.getSelection ());
- scale1.setPageIncrement (pageIncrementScale.getSelection ());
- }
-
- /**
- * Sets the selection of the "Example" widgets.
- */
- void setWidgetSelection () {
- slider1.setSelection (selectionScale.getSelection ());
- scale1.setSelection (selectionScale.getSelection ());
- }
-
- /**
- * Sets the thumb of the "Example" widgets.
- */
- void setWidgetThumb () {
- slider1.setThumb (thumbScale.getSelection ());
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+class SliderTab extends RangeTab {
+ /* Example widgets and groups that contain them */
+ Scale scale1;
+ Slider slider1;
+ Group sliderGroup, scaleGroup;
+
+ /* Scale widgets added to the "Control" group */
+ Scale incrementScale, pageIncrementScale, thumbScale;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ SliderTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Control" widget children.
+ */
+ void createControlWidgets () {
+ super.createControlWidgets ();
+ createThumbGroup ();
+ createIncrementGroup ();
+ createPageIncrementGroup ();
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for the slider */
+ sliderGroup = new Group (exampleGroup, SWT.NONE);
+ sliderGroup.setLayout (new GridLayout ());
+ sliderGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ sliderGroup.setText ("Slider");
+
+ /* Create a group for the scale */
+ scaleGroup = new Group (exampleGroup, SWT.NONE);
+ scaleGroup.setLayout (new GridLayout ());
+ scaleGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ scaleGroup.setText ("Scale");
+
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (horizontalButton.getSelection ()) style |= SWT.HORIZONTAL;
+ if (verticalButton.getSelection ()) style |= SWT.VERTICAL;
+ if (borderButton.getSelection ()) style |= SWT.BORDER;
+
+ /* Create the example widgets */
+ scale1 = new Scale (scaleGroup, style);
+ scale1.setMaximum (100);
+ scale1.setSelection (50);
+ scale1.setIncrement (5);
+ scale1.setPageIncrement (10);
+ slider1 = new Slider(sliderGroup, style);
+ slider1.setMaximum (100);
+ slider1.setSelection (50);
+ slider1.setIncrement(5);
+ slider1.setPageIncrement (10);
+ slider1.setThumb (10);
+ }
+
+ /**
+ * Create a group of widgets to control the increment
+ * attribute of the example widget.
+ */
+ void createIncrementGroup() {
+
+ /* Create the group */
+ Group incrementGroup = new Group (controlGroup, SWT.NONE);
+ incrementGroup.setLayout (new GridLayout ());
+ incrementGroup.setText (ControlExample.getResourceString("Increment"));
+ incrementGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
+
+ /* Create the scale widget */
+ incrementScale = new Scale (incrementGroup, SWT.NONE);
+ incrementScale.setMaximum (100);
+ incrementScale.setSelection (5);
+ incrementScale.setPageIncrement (10);
+ incrementScale.setIncrement (5);
+
+ GridData data = new GridData (GridData.FILL_HORIZONTAL);
+ data.widthHint = 100;
+ incrementScale.setLayoutData (data);
+
+ /* Add the listeners */
+ incrementScale.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent e) {
+ setWidgetIncrement ();
+ };
+ });
+ }
+
+ /**
+ * Create a group of widgets to control the page increment
+ * attribute of the example widget.
+ */
+ void createPageIncrementGroup() {
+
+ /* Create the group */
+ Group pageIncrementGroup = new Group (controlGroup, SWT.NONE);
+ pageIncrementGroup.setLayout (new GridLayout ());
+ pageIncrementGroup.setText (ControlExample.getResourceString("Page_Increment"));
+ pageIncrementGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
+
+ /* Create the scale widget */
+ pageIncrementScale = new Scale (pageIncrementGroup, SWT.NONE);
+ pageIncrementScale.setMaximum (100);
+ pageIncrementScale.setSelection (10);
+ pageIncrementScale.setPageIncrement (10);
+ pageIncrementScale.setIncrement (5);
+
+ GridData data = new GridData (GridData.FILL_HORIZONTAL);
+ data.widthHint = 100;
+ pageIncrementScale.setLayoutData (data);
+
+ /* Add the listeners */
+ pageIncrementScale.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setWidgetPageIncrement ();
+ }
+ });
+ }
+
+ /**
+ * Create a group of widgets to control the thumb
+ * attribute of the example widget.
+ */
+ void createThumbGroup() {
+
+ /* Create the group */
+ Group thumbGroup = new Group (controlGroup, SWT.NONE);
+ thumbGroup.setLayout (new GridLayout ());
+ thumbGroup.setText (ControlExample.getResourceString("Thumb"));
+ thumbGroup.setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
+
+ /* Create the scale widget */
+ thumbScale = new Scale (thumbGroup, SWT.NONE);
+ thumbScale.setMaximum (100);
+ thumbScale.setSelection (10);
+ thumbScale.setPageIncrement (10);
+ thumbScale.setIncrement (5);
+
+ GridData data = new GridData (GridData.FILL_HORIZONTAL);
+ data.widthHint = 100;
+ thumbScale.setLayoutData (data);
+
+ /* Add the listeners */
+ thumbScale.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setWidgetThumb ();
+ };
+ });
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {scale1, slider1};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return ControlExample.getResourceString("Slider_and_Scale");
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ setWidgetIncrement ();
+ setWidgetPageIncrement ();
+ setWidgetThumb ();
+ }
+
+ /**
+ * Sets the increment of the "Example" widgets.
+ */
+ void setWidgetIncrement () {
+ slider1.setIncrement (incrementScale.getSelection ());
+ scale1.setIncrement (incrementScale.getSelection ());
+ }
+
+ /**
+ * Sets the minimim of the "Example" widgets.
+ */
+ void setWidgetMaximum () {
+ slider1.setMaximum (maximumScale.getSelection ());
+ scale1.setMaximum (maximumScale.getSelection ());
+ }
+
+ /**
+ * Sets the minimim of the "Example" widgets.
+ */
+ void setWidgetMinimum () {
+ slider1.setMinimum (minimumScale.getSelection ());
+ scale1.setMinimum (minimumScale.getSelection ());
+ }
+
+ /**
+ * Sets the page increment of the "Example" widgets.
+ */
+ void setWidgetPageIncrement () {
+ slider1.setPageIncrement (pageIncrementScale.getSelection ());
+ scale1.setPageIncrement (pageIncrementScale.getSelection ());
+ }
+
+ /**
+ * Sets the selection of the "Example" widgets.
+ */
+ void setWidgetSelection () {
+ slider1.setSelection (selectionScale.getSelection ());
+ scale1.setSelection (selectionScale.getSelection ());
+ }
+
+ /**
+ * Sets the thumb of the "Example" widgets.
+ */
+ void setWidgetThumb () {
+ slider1.setThumb (thumbScale.getSelection ());
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/Tab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/Tab.java
index 349843176d..433a882218 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/Tab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/Tab.java
@@ -1,543 +1,543 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-/**
- * <code>Tab</code> is the abstract superclass of every page
- * in the example's tab folder. Each page in the tab folder
- * describes a control.
- *
- * A Tab itself is not a control but instead provides a
- * hierarchy with which to share code that is common to
- * every page in the folder.
- *
- * A typical page in a Tab contains a two column composite.
- * The left column contains the "Example" group. The right
- * column contains "Control" group. The "Control" group
- * contains controls that allow the user to interact with
- * the example control. The "Control" group typically
- * contains a "Style", "Display" and "Size" group. Subclasses
- * can override these defaults to augment a group or stop
- * a group from being created.
- */
-abstract class Tab {
- /* Common control buttons */
- Button borderButton, enabledButton, visibleButton;
- Button preferredButton, tooSmallButton, smallButton, largeButton, fillButton;
-
- /* Common groups and composites */
- Composite tabFolderPage;
- Group exampleGroup, controlGroup, displayGroup, sizeGroup, styleGroup, colorGroup;
-
- /* Controlling instance */
- final ControlExample instance;
-
- /* Sizing constants for the "Size" group */
- static final int TOO_SMALL_SIZE = 10;
- static final int SMALL_SIZE = 50;
- static final int LARGE_SIZE = 100;
-
- /* Common controls for the "Colors" group */
- Button backgroundButton, foregroundButton, fontButton;
- Color backgroundColor, foregroundColor;
- Font font;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- Tab(ControlExample instance) {
- this.instance = instance;
- }
-
- /**
- * Creates the "Control" group. The "Control" group
- * is typically the right hand column in the tab.
- */
- void createControlGroup () {
-
- /*
- * Create the "Control" group. This is the group on the
- * left half of each example tab. It consists of the
- * style group, the display group and the size group.
- */
- controlGroup = new Group (tabFolderPage, SWT.NONE);
- GridLayout gridLayout= new GridLayout ();
- controlGroup.setLayout (gridLayout);
- gridLayout.numColumns = 2;
- gridLayout.makeColumnsEqualWidth = true;
- controlGroup.setLayoutData (new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- controlGroup.setText (ControlExample.getResourceString("Parameters"));
-
- /* Create individual groups inside the "Control" group */
- createStyleGroup ();
- createDisplayGroup ();
- createSizeGroup ();
- createColorGroup ();
-
- /*
- * For each Button child in the style group, add a selection
- * listener that will recreate the example controls. If the
- * style group button is a RADIO button, ensure that the radio
- * button is selected before recreating the example controls.
- * When the user selects a RADIO button, the current RADIO
- * button in the group is deselected and the new RADIO button
- * is selected automatically. The listeners are notified for
- * both these operations but typically only do work when a RADIO
- * button is selected.
- */
- SelectionListener selectionListener = new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- if ((event.widget.getStyle () & SWT.RADIO) != 0) {
- if (!((Button) event.widget).getSelection ()) return;
- }
- recreateExampleWidgets ();
- };
- };
- Control [] children = styleGroup.getChildren ();
- for (int i=0; i<children.length; i++) {
- if (children [i] instanceof Button) {
- Button button = (Button) children [i];
- button.addSelectionListener (selectionListener);
- }
- }
- }
-
- /**
- * Creates the "Control" widget children.
- * Subclasses override this method to augment
- * the standard controls created in the "Style",
- * "Display" and "Size" groups.
- */
- void createControlWidgets () {
- }
-
- /**
- * Creates the "Color" group. This is typically
- * a child of the "Control" group. Subclasses override
- * this method to customize and set system colors.
- */
- void createColorGroup () {
- /* Create the group */
- colorGroup = new Group(controlGroup, SWT.NONE);
- colorGroup.setLayout (new GridLayout (2, false));
- colorGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- colorGroup.setText (ControlExample.getResourceString ("Colors"));
- new Label (colorGroup, SWT.NONE).setText (ControlExample.getResourceString ("Foreground_Color"));
- foregroundButton = new Button (colorGroup, SWT.PUSH);
- new Label (colorGroup, SWT.NONE).setText (ControlExample.getResourceString ("Background_Color"));
- backgroundButton = new Button (colorGroup, SWT.PUSH);
- fontButton = new Button (colorGroup, SWT.PUSH);
- fontButton.setText(ControlExample.getResourceString("Font"));
-
- Shell shell = backgroundButton.getShell ();
- final ColorDialog backgroundDialog = new ColorDialog (shell);
- final ColorDialog foregroundDialog = new ColorDialog (shell);
- final FontDialog fontDialog = new FontDialog (shell);
-
- /* Create images to display current colors */
- int imageSize = 12;
- Display display = shell.getDisplay ();
- final Image backgroundImage = new Image (display, imageSize, imageSize);
- final Image foregroundImage = new Image (display, imageSize, imageSize);
-
- /* Add listeners to set the colors and font */
- backgroundButton.setImage(backgroundImage);
- backgroundButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- RGB rgb = backgroundDialog.open();
- if (rgb == null) return;
- Color oldColor = backgroundColor;
- backgroundColor = new Color (backgroundButton.getDisplay(), rgb);
- setExampleWidgetBackground ();
- if (oldColor != null) oldColor.dispose ();
- }
- });
- foregroundButton.setImage(foregroundImage);
- foregroundButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- RGB rgb = foregroundDialog.open();
- if (rgb == null) return;
- Color oldColor = foregroundColor;
- foregroundColor = new Color (foregroundButton.getDisplay(), rgb);
- setExampleWidgetForeground ();
- if (oldColor != null) oldColor.dispose ();
- }
- });
- fontButton.addSelectionListener(new SelectionAdapter () {
- public void widgetSelected (SelectionEvent e) {
- FontData fontData = fontDialog.open ();
- if (fontData == null) return;
- Font oldFont = font;
- font = new Font (fontButton.getDisplay(), fontData);
- setExampleWidgetFont ();
- setExampleWidgetSize ();
- if (oldFont != null) oldFont.dispose ();
- }
- });
- backgroundButton.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent event) {
- if (backgroundImage != null) backgroundImage.dispose();
- if (foregroundImage != null) foregroundImage.dispose();
- if (backgroundColor != null) backgroundColor.dispose();
- if (foregroundColor != null) foregroundColor.dispose();
- if (font != null) font.dispose();
- backgroundColor = null;
- foregroundColor = null;
- font = null;
- }
- });
- }
-
- /**
- * Creates the "Display" group. This is typically
- * a child of the "Control" group.
- */
- void createDisplayGroup () {
- /* Create the group */
- displayGroup = new Group (controlGroup, SWT.NONE);
- displayGroup.setLayout (new GridLayout ());
- displayGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- displayGroup.setText (ControlExample.getResourceString("State"));
-
- /* Create the controls */
- enabledButton = new Button(displayGroup, SWT.CHECK);
- enabledButton.setText(ControlExample.getResourceString("Enabled"));
- visibleButton = new Button(displayGroup, SWT.CHECK);
- visibleButton.setText(ControlExample.getResourceString("Visible"));
-
- /* Add the listeners */
- enabledButton.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setExampleWidgetEnabled ();
- }
- });
- visibleButton.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setExampleWidgetVisibility ();
- }
- });
-
- /* Set the default state */
- enabledButton.setSelection(true);
- visibleButton.setSelection(true);
- }
-
- /**
- * Creates the "Example" group. The "Example" group
- * is typically the left hand column in the tab.
- */
- void createExampleGroup () {
- exampleGroup = new Group (tabFolderPage, SWT.NONE);
- GridLayout gridLayout = new GridLayout ();
- exampleGroup.setLayout (gridLayout);
- exampleGroup.setLayoutData (new GridData (GridData.FILL_BOTH));
- }
-
- /**
- * Creates the "Example" widget children of the "Example" group.
- * Subclasses override this method to create the particular
- * example control.
- */
- void createExampleWidgets () {
- /* Do nothing */
- }
-
- /**
- * Creates the "Size" group. The "Size" group contains
- * controls that allow the user to change the size of
- * the example widgets.
- */
- void createSizeGroup () {
- /* Create the group */
- sizeGroup = new Group (controlGroup, SWT.NONE);
- sizeGroup.setLayout (new GridLayout());
- sizeGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- sizeGroup.setText (ControlExample.getResourceString("Size"));
-
- /* Create the controls */
-
- /*
- * The preferred size of a widget is the size returned
- * by widget.computeSize (SWT.DEFAULT, SWT.DEFAULT).
- * This size is defined on a widget by widget basis.
- * Many widgets will attempt to display their contents.
- */
- preferredButton = new Button (sizeGroup, SWT.RADIO);
- preferredButton.setText (ControlExample.getResourceString("Preferred"));
- tooSmallButton = new Button (sizeGroup, SWT.RADIO);
- tooSmallButton.setText (TOO_SMALL_SIZE + " X " + TOO_SMALL_SIZE);
- smallButton = new Button(sizeGroup, SWT.RADIO);
- smallButton.setText (SMALL_SIZE + " X " + SMALL_SIZE);
- largeButton = new Button (sizeGroup, SWT.RADIO);
- largeButton.setText (LARGE_SIZE + " X " + LARGE_SIZE);
- fillButton = new Button (sizeGroup, SWT.RADIO);
- fillButton.setText (ControlExample.getResourceString("Fill"));
-
- /* Add the listeners */
- SelectionAdapter selectionListener = new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- if (!((Button) event.widget).getSelection ()) return;
- setExampleWidgetSize ();
- };
- };
- preferredButton.addSelectionListener(selectionListener);
- tooSmallButton.addSelectionListener(selectionListener);
- smallButton.addSelectionListener(selectionListener);
- largeButton.addSelectionListener(selectionListener);
- fillButton.addSelectionListener(selectionListener);
-
- /* Set the default state */
- preferredButton.setSelection (true);
- }
-
- /**
- * Creates the "Style" group. The "Style" group contains
- * controls that allow the user to change the style of
- * the example widgets. Changing a widget "Style" causes
- * the widget to be destroyed and recreated.
- */
- void createStyleGroup () {
- styleGroup = new Group (controlGroup, SWT.NONE);
- styleGroup.setLayout (new GridLayout ());
- styleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- styleGroup.setText (ControlExample.getResourceString("Styles"));
- }
-
- /**
- * Creates the tab folder page.
- *
- * @param tabFolder org.eclipse.swt.widgets.TabFolder
- * @return the new page for the tab folder
- */
- Composite createTabFolderPage (TabFolder tabFolder) {
- /*
- * Create a two column page.
- */
- tabFolderPage = new Composite (tabFolder, SWT.NONE);
- GridLayout gridLayout = new GridLayout ();
- tabFolderPage.setLayout (gridLayout);
- gridLayout.numColumns = 2;
-
- /* Create the "Example" and "Control" columns */
- createExampleGroup ();
- createControlGroup ();
-
- /* Create the widgets in the two columns */
- createExampleWidgets ();
- hookExampleWidgetListeners ();
- createControlWidgets ();
- setExampleWidgetState ();
-
- return tabFolderPage;
- }
-
- /**
- * Disposes the "Example" widgets.
- */
- void disposeExampleWidgets () {
- Control [] controls = getExampleWidgets ();
- for (int i=0; i<controls.length; i++) {
- controls [i].dispose ();
- }
- }
-
- void drawImage (Image image, Color color) {
- GC gc = new GC(image);
- gc.setBackground(color);
- Rectangle bounds = image.getBounds();
- gc.fillRectangle(0, 0, bounds.width, bounds.height);
- gc.drawRectangle(0, 0, bounds.width - 1, bounds.height - 1);
- gc.dispose();
- }
-
- /**
- * Gets the "Example" widget children.
- *
- * @return an array of example widget children
- */
- Control [] getExampleWidgets () {
- return new Control [0];
- }
-
- /**
- * Gets the text for the tab folder item.
- *
- * @return the text for the tab item
- */
- String getTabText () {
- return "";
- }
-
- /**
- * Hook all listeners to all controls.
- */
- void hookExampleWidgetListeners () {
- if (instance.isLogging()) {
- Control[] exampleControls = getExampleWidgets();
- Listener listener = new Listener() {
- public void handleEvent (Event event) {
- instance.log (event);
- }
- };
- for (int i = 0; i < exampleControls.length; i++) {
- Control control = exampleControls [i];
- for (int j = SWT.KeyDown; j < SWT.HardKeyUp; j++) {
- control.addListener (j, listener);
- }
- }
- }
- }
-
- /**
- * Recreates the "Example" widgets.
- */
- void recreateExampleWidgets () {
- disposeExampleWidgets ();
- createExampleWidgets ();
- hookExampleWidgetListeners ();
- setExampleWidgetState ();
- }
-
- /**
- * Sets the background color of the "Example" widgets.
- */
- void setExampleWidgetBackground () {
- if (backgroundButton == null) return;
- Control [] controls = getExampleWidgets ();
- Color color = backgroundColor;
- if (color == null) color = controls [0].getBackground ();
- Image image = backgroundButton.getImage ();
- drawImage (image, color);
- backgroundButton.setImage (image);
- if (backgroundColor == null) return;
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+/**
+ * <code>Tab</code> is the abstract superclass of every page
+ * in the example's tab folder. Each page in the tab folder
+ * describes a control.
+ *
+ * A Tab itself is not a control but instead provides a
+ * hierarchy with which to share code that is common to
+ * every page in the folder.
+ *
+ * A typical page in a Tab contains a two column composite.
+ * The left column contains the "Example" group. The right
+ * column contains "Control" group. The "Control" group
+ * contains controls that allow the user to interact with
+ * the example control. The "Control" group typically
+ * contains a "Style", "Display" and "Size" group. Subclasses
+ * can override these defaults to augment a group or stop
+ * a group from being created.
+ */
+abstract class Tab {
+ /* Common control buttons */
+ Button borderButton, enabledButton, visibleButton;
+ Button preferredButton, tooSmallButton, smallButton, largeButton, fillButton;
+
+ /* Common groups and composites */
+ Composite tabFolderPage;
+ Group exampleGroup, controlGroup, displayGroup, sizeGroup, styleGroup, colorGroup;
+
+ /* Controlling instance */
+ final ControlExample instance;
+
+ /* Sizing constants for the "Size" group */
+ static final int TOO_SMALL_SIZE = 10;
+ static final int SMALL_SIZE = 50;
+ static final int LARGE_SIZE = 100;
+
+ /* Common controls for the "Colors" group */
+ Button backgroundButton, foregroundButton, fontButton;
+ Color backgroundColor, foregroundColor;
+ Font font;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ Tab(ControlExample instance) {
+ this.instance = instance;
+ }
+
+ /**
+ * Creates the "Control" group. The "Control" group
+ * is typically the right hand column in the tab.
+ */
+ void createControlGroup () {
+
+ /*
+ * Create the "Control" group. This is the group on the
+ * left half of each example tab. It consists of the
+ * style group, the display group and the size group.
+ */
+ controlGroup = new Group (tabFolderPage, SWT.NONE);
+ GridLayout gridLayout= new GridLayout ();
+ controlGroup.setLayout (gridLayout);
+ gridLayout.numColumns = 2;
+ gridLayout.makeColumnsEqualWidth = true;
+ controlGroup.setLayoutData (new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ controlGroup.setText (ControlExample.getResourceString("Parameters"));
+
+ /* Create individual groups inside the "Control" group */
+ createStyleGroup ();
+ createDisplayGroup ();
+ createSizeGroup ();
+ createColorGroup ();
+
+ /*
+ * For each Button child in the style group, add a selection
+ * listener that will recreate the example controls. If the
+ * style group button is a RADIO button, ensure that the radio
+ * button is selected before recreating the example controls.
+ * When the user selects a RADIO button, the current RADIO
+ * button in the group is deselected and the new RADIO button
+ * is selected automatically. The listeners are notified for
+ * both these operations but typically only do work when a RADIO
+ * button is selected.
+ */
+ SelectionListener selectionListener = new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ if ((event.widget.getStyle () & SWT.RADIO) != 0) {
+ if (!((Button) event.widget).getSelection ()) return;
+ }
+ recreateExampleWidgets ();
+ };
+ };
+ Control [] children = styleGroup.getChildren ();
+ for (int i=0; i<children.length; i++) {
+ if (children [i] instanceof Button) {
+ Button button = (Button) children [i];
+ button.addSelectionListener (selectionListener);
+ }
+ }
+ }
+
+ /**
+ * Creates the "Control" widget children.
+ * Subclasses override this method to augment
+ * the standard controls created in the "Style",
+ * "Display" and "Size" groups.
+ */
+ void createControlWidgets () {
+ }
+
+ /**
+ * Creates the "Color" group. This is typically
+ * a child of the "Control" group. Subclasses override
+ * this method to customize and set system colors.
+ */
+ void createColorGroup () {
+ /* Create the group */
+ colorGroup = new Group(controlGroup, SWT.NONE);
+ colorGroup.setLayout (new GridLayout (2, false));
+ colorGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ colorGroup.setText (ControlExample.getResourceString ("Colors"));
+ new Label (colorGroup, SWT.NONE).setText (ControlExample.getResourceString ("Foreground_Color"));
+ foregroundButton = new Button (colorGroup, SWT.PUSH);
+ new Label (colorGroup, SWT.NONE).setText (ControlExample.getResourceString ("Background_Color"));
+ backgroundButton = new Button (colorGroup, SWT.PUSH);
+ fontButton = new Button (colorGroup, SWT.PUSH);
+ fontButton.setText(ControlExample.getResourceString("Font"));
+
+ Shell shell = backgroundButton.getShell ();
+ final ColorDialog backgroundDialog = new ColorDialog (shell);
+ final ColorDialog foregroundDialog = new ColorDialog (shell);
+ final FontDialog fontDialog = new FontDialog (shell);
+
+ /* Create images to display current colors */
+ int imageSize = 12;
+ Display display = shell.getDisplay ();
+ final Image backgroundImage = new Image (display, imageSize, imageSize);
+ final Image foregroundImage = new Image (display, imageSize, imageSize);
+
+ /* Add listeners to set the colors and font */
+ backgroundButton.setImage(backgroundImage);
+ backgroundButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ RGB rgb = backgroundDialog.open();
+ if (rgb == null) return;
+ Color oldColor = backgroundColor;
+ backgroundColor = new Color (backgroundButton.getDisplay(), rgb);
+ setExampleWidgetBackground ();
+ if (oldColor != null) oldColor.dispose ();
+ }
+ });
+ foregroundButton.setImage(foregroundImage);
+ foregroundButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ RGB rgb = foregroundDialog.open();
+ if (rgb == null) return;
+ Color oldColor = foregroundColor;
+ foregroundColor = new Color (foregroundButton.getDisplay(), rgb);
+ setExampleWidgetForeground ();
+ if (oldColor != null) oldColor.dispose ();
+ }
+ });
+ fontButton.addSelectionListener(new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent e) {
+ FontData fontData = fontDialog.open ();
+ if (fontData == null) return;
+ Font oldFont = font;
+ font = new Font (fontButton.getDisplay(), fontData);
+ setExampleWidgetFont ();
+ setExampleWidgetSize ();
+ if (oldFont != null) oldFont.dispose ();
+ }
+ });
+ backgroundButton.addDisposeListener(new DisposeListener() {
+ public void widgetDisposed(DisposeEvent event) {
+ if (backgroundImage != null) backgroundImage.dispose();
+ if (foregroundImage != null) foregroundImage.dispose();
+ if (backgroundColor != null) backgroundColor.dispose();
+ if (foregroundColor != null) foregroundColor.dispose();
+ if (font != null) font.dispose();
+ backgroundColor = null;
+ foregroundColor = null;
+ font = null;
+ }
+ });
+ }
+
+ /**
+ * Creates the "Display" group. This is typically
+ * a child of the "Control" group.
+ */
+ void createDisplayGroup () {
+ /* Create the group */
+ displayGroup = new Group (controlGroup, SWT.NONE);
+ displayGroup.setLayout (new GridLayout ());
+ displayGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ displayGroup.setText (ControlExample.getResourceString("State"));
+
+ /* Create the controls */
+ enabledButton = new Button(displayGroup, SWT.CHECK);
+ enabledButton.setText(ControlExample.getResourceString("Enabled"));
+ visibleButton = new Button(displayGroup, SWT.CHECK);
+ visibleButton.setText(ControlExample.getResourceString("Visible"));
+
+ /* Add the listeners */
+ enabledButton.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setExampleWidgetEnabled ();
+ }
+ });
+ visibleButton.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setExampleWidgetVisibility ();
+ }
+ });
+
+ /* Set the default state */
+ enabledButton.setSelection(true);
+ visibleButton.setSelection(true);
+ }
+
+ /**
+ * Creates the "Example" group. The "Example" group
+ * is typically the left hand column in the tab.
+ */
+ void createExampleGroup () {
+ exampleGroup = new Group (tabFolderPage, SWT.NONE);
+ GridLayout gridLayout = new GridLayout ();
+ exampleGroup.setLayout (gridLayout);
+ exampleGroup.setLayoutData (new GridData (GridData.FILL_BOTH));
+ }
+
+ /**
+ * Creates the "Example" widget children of the "Example" group.
+ * Subclasses override this method to create the particular
+ * example control.
+ */
+ void createExampleWidgets () {
+ /* Do nothing */
+ }
+
+ /**
+ * Creates the "Size" group. The "Size" group contains
+ * controls that allow the user to change the size of
+ * the example widgets.
+ */
+ void createSizeGroup () {
+ /* Create the group */
+ sizeGroup = new Group (controlGroup, SWT.NONE);
+ sizeGroup.setLayout (new GridLayout());
+ sizeGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ sizeGroup.setText (ControlExample.getResourceString("Size"));
+
+ /* Create the controls */
+
+ /*
+ * The preferred size of a widget is the size returned
+ * by widget.computeSize (SWT.DEFAULT, SWT.DEFAULT).
+ * This size is defined on a widget by widget basis.
+ * Many widgets will attempt to display their contents.
+ */
+ preferredButton = new Button (sizeGroup, SWT.RADIO);
+ preferredButton.setText (ControlExample.getResourceString("Preferred"));
+ tooSmallButton = new Button (sizeGroup, SWT.RADIO);
+ tooSmallButton.setText (TOO_SMALL_SIZE + " X " + TOO_SMALL_SIZE);
+ smallButton = new Button(sizeGroup, SWT.RADIO);
+ smallButton.setText (SMALL_SIZE + " X " + SMALL_SIZE);
+ largeButton = new Button (sizeGroup, SWT.RADIO);
+ largeButton.setText (LARGE_SIZE + " X " + LARGE_SIZE);
+ fillButton = new Button (sizeGroup, SWT.RADIO);
+ fillButton.setText (ControlExample.getResourceString("Fill"));
+
+ /* Add the listeners */
+ SelectionAdapter selectionListener = new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ if (!((Button) event.widget).getSelection ()) return;
+ setExampleWidgetSize ();
+ };
+ };
+ preferredButton.addSelectionListener(selectionListener);
+ tooSmallButton.addSelectionListener(selectionListener);
+ smallButton.addSelectionListener(selectionListener);
+ largeButton.addSelectionListener(selectionListener);
+ fillButton.addSelectionListener(selectionListener);
+
+ /* Set the default state */
+ preferredButton.setSelection (true);
+ }
+
+ /**
+ * Creates the "Style" group. The "Style" group contains
+ * controls that allow the user to change the style of
+ * the example widgets. Changing a widget "Style" causes
+ * the widget to be destroyed and recreated.
+ */
+ void createStyleGroup () {
+ styleGroup = new Group (controlGroup, SWT.NONE);
+ styleGroup.setLayout (new GridLayout ());
+ styleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ styleGroup.setText (ControlExample.getResourceString("Styles"));
+ }
+
+ /**
+ * Creates the tab folder page.
+ *
+ * @param tabFolder org.eclipse.swt.widgets.TabFolder
+ * @return the new page for the tab folder
+ */
+ Composite createTabFolderPage (TabFolder tabFolder) {
+ /*
+ * Create a two column page.
+ */
+ tabFolderPage = new Composite (tabFolder, SWT.NONE);
+ GridLayout gridLayout = new GridLayout ();
+ tabFolderPage.setLayout (gridLayout);
+ gridLayout.numColumns = 2;
+
+ /* Create the "Example" and "Control" columns */
+ createExampleGroup ();
+ createControlGroup ();
+
+ /* Create the widgets in the two columns */
+ createExampleWidgets ();
+ hookExampleWidgetListeners ();
+ createControlWidgets ();
+ setExampleWidgetState ();
+
+ return tabFolderPage;
+ }
+
+ /**
+ * Disposes the "Example" widgets.
+ */
+ void disposeExampleWidgets () {
+ Control [] controls = getExampleWidgets ();
+ for (int i=0; i<controls.length; i++) {
+ controls [i].dispose ();
+ }
+ }
+
+ void drawImage (Image image, Color color) {
+ GC gc = new GC(image);
+ gc.setBackground(color);
+ Rectangle bounds = image.getBounds();
+ gc.fillRectangle(0, 0, bounds.width, bounds.height);
+ gc.drawRectangle(0, 0, bounds.width - 1, bounds.height - 1);
+ gc.dispose();
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ *
+ * @return an array of example widget children
+ */
+ Control [] getExampleWidgets () {
+ return new Control [0];
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ *
+ * @return the text for the tab item
+ */
+ String getTabText () {
+ return "";
+ }
+
+ /**
+ * Hook all listeners to all controls.
+ */
+ void hookExampleWidgetListeners () {
+ if (instance.isLogging()) {
+ Control[] exampleControls = getExampleWidgets();
+ Listener listener = new Listener() {
+ public void handleEvent (Event event) {
+ instance.log (event);
+ }
+ };
+ for (int i = 0; i < exampleControls.length; i++) {
+ Control control = exampleControls [i];
+ for (int j = SWT.KeyDown; j < SWT.HardKeyUp; j++) {
+ control.addListener (j, listener);
+ }
+ }
+ }
+ }
+
+ /**
+ * Recreates the "Example" widgets.
+ */
+ void recreateExampleWidgets () {
+ disposeExampleWidgets ();
+ createExampleWidgets ();
+ hookExampleWidgetListeners ();
+ setExampleWidgetState ();
+ }
+
+ /**
+ * Sets the background color of the "Example" widgets.
+ */
+ void setExampleWidgetBackground () {
+ if (backgroundButton == null) return;
+ Control [] controls = getExampleWidgets ();
+ Color color = backgroundColor;
+ if (color == null) color = controls [0].getBackground ();
+ Image image = backgroundButton.getImage ();
+ drawImage (image, color);
+ backgroundButton.setImage (image);
+ if (backgroundColor == null) return;
for (int i = 0; i < controls.length; i++) {
Control control = controls[i];
- control.setBackground (backgroundColor);
- }
- }
-
- /**
- * Sets the enabled state of the "Example" widgets.
- */
- void setExampleWidgetEnabled () {
- Control [] controls = getExampleWidgets ();
- for (int i=0; i<controls.length; i++) {
- controls [i].setEnabled (enabledButton.getSelection ());
- }
- }
-
- /**
- * Sets the font of the "Example" widgets.
- */
- void setExampleWidgetFont () {
- if (font == null) return;
- Control [] controls = getExampleWidgets ();
- for (int i = 0; i < controls.length; i++) {
- Control control = controls[i];
- control.setFont(font);
- }
- }
-
- /**
- * Sets the foreground color of the "Example" widgets.
- */
- void setExampleWidgetForeground () {
- if (foregroundButton == null) return;
- Control [] controls = getExampleWidgets ();
- Color color = foregroundColor;
- if (color == null) color = controls [0].getForeground ();
- Image image = foregroundButton.getImage ();
- drawImage (image, color);
- foregroundButton.setImage (image);
- if (foregroundColor == null) return;
- for (int i = 0; i < controls.length; i++) {
- Control control = controls[i];
- control.setForeground (foregroundColor);
- }
- }
-
- /**
- * Sets the size of the "Example" widgets.
- */
- void setExampleWidgetSize () {
- int size = SWT.DEFAULT;
- if (preferredButton == null) return;
- if (preferredButton.getSelection()) size = SWT.DEFAULT;
- if (tooSmallButton.getSelection()) size = TOO_SMALL_SIZE;
- if (smallButton.getSelection()) size = SMALL_SIZE;
- if (largeButton.getSelection()) size = LARGE_SIZE;
- Control [] controls = getExampleWidgets ();
- for (int i=0; i<controls.length; i++) {
- GridData gridData;
- if (fillButton.getSelection()) {
- gridData = new GridData (GridData.FILL_BOTH);
- } else {
- gridData = new GridData ();
- gridData.widthHint = size;
- gridData.heightHint = size;
- }
- controls [i].setLayoutData (gridData);
- }
- /*
- * Force the entire widget tree to layout,
- * even when the child sizes may not have
- * changed.
- */
- int seenCount = 0;
- Composite [] seen = new Composite [4];
- for (int i=0; i<controls.length; i++) {
- Control control = controls [i];
- while (control != exampleGroup) {
- Composite parent = control.getParent ();
- int index = 0;
- while (index < seenCount) {
- if (seen [index] == parent) break;
- index++;
- }
- if (index == seenCount) parent.layout ();
- if (seenCount == seen.length) {
- Composite [] newSeen = new Composite [seen.length + 4];
- System.arraycopy (seen, 0, newSeen, 0, seen.length);
- seen = newSeen;
- }
- seen [seenCount++] = parent;
- control = control.getParent ();
- }
- }
- }
-
- /**
- * Sets the state of the "Example" widgets. Subclasses
- * reimplement this method to set "Example" widget state
- * that is specific to the widget.
- */
- void setExampleWidgetState () {
- setExampleWidgetEnabled ();
- setExampleWidgetVisibility ();
- setExampleWidgetBackground ();
- setExampleWidgetForeground ();
- setExampleWidgetFont ();
- setExampleWidgetSize ();
- }
-
- /**
- * Sets the visibility of the "Example" widgets.
- */
- void setExampleWidgetVisibility () {
- Control [] controls = getExampleWidgets ();
- for (int i=0; i<controls.length; i++) {
- controls [i].setVisible (visibleButton.getSelection ());
- }
- }
-}
+ control.setBackground (backgroundColor);
+ }
+ }
+
+ /**
+ * Sets the enabled state of the "Example" widgets.
+ */
+ void setExampleWidgetEnabled () {
+ Control [] controls = getExampleWidgets ();
+ for (int i=0; i<controls.length; i++) {
+ controls [i].setEnabled (enabledButton.getSelection ());
+ }
+ }
+
+ /**
+ * Sets the font of the "Example" widgets.
+ */
+ void setExampleWidgetFont () {
+ if (font == null) return;
+ Control [] controls = getExampleWidgets ();
+ for (int i = 0; i < controls.length; i++) {
+ Control control = controls[i];
+ control.setFont(font);
+ }
+ }
+
+ /**
+ * Sets the foreground color of the "Example" widgets.
+ */
+ void setExampleWidgetForeground () {
+ if (foregroundButton == null) return;
+ Control [] controls = getExampleWidgets ();
+ Color color = foregroundColor;
+ if (color == null) color = controls [0].getForeground ();
+ Image image = foregroundButton.getImage ();
+ drawImage (image, color);
+ foregroundButton.setImage (image);
+ if (foregroundColor == null) return;
+ for (int i = 0; i < controls.length; i++) {
+ Control control = controls[i];
+ control.setForeground (foregroundColor);
+ }
+ }
+
+ /**
+ * Sets the size of the "Example" widgets.
+ */
+ void setExampleWidgetSize () {
+ int size = SWT.DEFAULT;
+ if (preferredButton == null) return;
+ if (preferredButton.getSelection()) size = SWT.DEFAULT;
+ if (tooSmallButton.getSelection()) size = TOO_SMALL_SIZE;
+ if (smallButton.getSelection()) size = SMALL_SIZE;
+ if (largeButton.getSelection()) size = LARGE_SIZE;
+ Control [] controls = getExampleWidgets ();
+ for (int i=0; i<controls.length; i++) {
+ GridData gridData;
+ if (fillButton.getSelection()) {
+ gridData = new GridData (GridData.FILL_BOTH);
+ } else {
+ gridData = new GridData ();
+ gridData.widthHint = size;
+ gridData.heightHint = size;
+ }
+ controls [i].setLayoutData (gridData);
+ }
+ /*
+ * Force the entire widget tree to layout,
+ * even when the child sizes may not have
+ * changed.
+ */
+ int seenCount = 0;
+ Composite [] seen = new Composite [4];
+ for (int i=0; i<controls.length; i++) {
+ Control control = controls [i];
+ while (control != exampleGroup) {
+ Composite parent = control.getParent ();
+ int index = 0;
+ while (index < seenCount) {
+ if (seen [index] == parent) break;
+ index++;
+ }
+ if (index == seenCount) parent.layout ();
+ if (seenCount == seen.length) {
+ Composite [] newSeen = new Composite [seen.length + 4];
+ System.arraycopy (seen, 0, newSeen, 0, seen.length);
+ seen = newSeen;
+ }
+ seen [seenCount++] = parent;
+ control = control.getParent ();
+ }
+ }
+ }
+
+ /**
+ * Sets the state of the "Example" widgets. Subclasses
+ * reimplement this method to set "Example" widget state
+ * that is specific to the widget.
+ */
+ void setExampleWidgetState () {
+ setExampleWidgetEnabled ();
+ setExampleWidgetVisibility ();
+ setExampleWidgetBackground ();
+ setExampleWidgetForeground ();
+ setExampleWidgetFont ();
+ setExampleWidgetSize ();
+ }
+
+ /**
+ * Sets the visibility of the "Example" widgets.
+ */
+ void setExampleWidgetVisibility () {
+ Control [] controls = getExampleWidgets ();
+ for (int i=0; i<controls.length; i++) {
+ controls [i].setVisible (visibleButton.getSelection ());
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TableTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TableTab.java
index 74ed69bc63..a45a8509a3 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TableTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TableTab.java
@@ -1,284 +1,284 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-class TableTab extends ScrollableTab {
- /* Example widgets and groups that contain them */
- Table table1;
- Group tableGroup, tableItemGroup;
-
- /* Style widgets added to the "Style" group */
- Button checkButton, fullSelectionButton;
-
- /* Display widgets added to the "Display" group */
- Button headerVisibleButton, linesVisibleButton;
-
- /* Color widgets added to the "Color" group */
- Button itemBackgroundButton, itemForegroundButton;
- Color itemBackgroundColor, itemForegroundColor;
-
- static String [] columnTitles = {ControlExample.getResourceString("TableTitle_0"),
- ControlExample.getResourceString("TableTitle_1"),
- ControlExample.getResourceString("TableTitle_2"),
- ControlExample.getResourceString("TableTitle_3")};
-
- static String [] stringLine0 = {ControlExample.getResourceString("TableLine0_0"),
- ControlExample.getResourceString("TableLine0_1"),
- ControlExample.getResourceString("TableLine0_2"),
- ControlExample.getResourceString("TableLine0_3")};
-
- static String [] stringLine1 = {ControlExample.getResourceString("TableLine1_0"),
- ControlExample.getResourceString("TableLine1_1"),
- ControlExample.getResourceString("TableLine1_2"),
- ControlExample.getResourceString("TableLine1_3")};
-
- static String [] stringLine2 = {ControlExample.getResourceString("TableLine2_0"),
- ControlExample.getResourceString("TableLine2_1"),
- ControlExample.getResourceString("TableLine2_2"),
- ControlExample.getResourceString("TableLine2_3")};
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- TableTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Colors" group.
- */
- void createColorGroup () {
- super.createColorGroup();
-
- tableItemGroup = new Group (colorGroup, SWT.NONE);
- tableItemGroup.setText (ControlExample.getResourceString ("Table_Item_Colors"));
- GridData data = new GridData ();
- data.horizontalSpan = 2;
- tableItemGroup.setLayoutData (data);
- tableItemGroup.setLayout (new GridLayout (2, false));
- new Label (tableItemGroup, SWT.NONE).setText (ControlExample.getResourceString ("Item_Foreground_Color"));
- itemForegroundButton = new Button (tableItemGroup, SWT.PUSH);
- new Label (tableItemGroup, SWT.NONE).setText (ControlExample.getResourceString ("Item_Background_Color"));
- itemBackgroundButton = new Button (tableItemGroup, SWT.PUSH);
-
- Shell shell = itemBackgroundButton.getShell ();
- final ColorDialog backgroundDialog = new ColorDialog (shell);
- final ColorDialog foregroundDialog = new ColorDialog (shell);
-
- int imageSize = 12;
- Display display = shell.getDisplay ();
- final Image itemBackgroundImage = new Image(display, imageSize, imageSize);
- final Image itemForegroundImage = new Image(display, imageSize, imageSize);
-
- /* Add listeners to set the colors and font */
- itemBackgroundButton.setImage(itemBackgroundImage);
- itemBackgroundButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- RGB rgb = backgroundDialog.open();
- if (rgb == null) return;
- Color oldColor = itemBackgroundColor;
- itemBackgroundColor = new Color (itemBackgroundButton.getDisplay(), rgb);
- setItemsBackground ();
- if (oldColor != null) oldColor.dispose ();
- }
- });
- itemForegroundButton.setImage(itemForegroundImage);
- itemForegroundButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- RGB rgb = foregroundDialog.open();
- if (rgb == null) return;
- Color oldColor = itemForegroundColor;
- itemForegroundColor = new Color (itemForegroundButton.getDisplay(), rgb);
- setItemsForeground ();
- if (oldColor != null) oldColor.dispose ();
- }
- });
- itemBackgroundButton.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent event) {
- if (itemBackgroundImage != null) itemBackgroundImage.dispose();
- if (itemForegroundImage != null) itemForegroundImage.dispose();
- if (itemBackgroundColor != null) itemBackgroundColor.dispose();
- if (itemForegroundColor != null) itemForegroundColor.dispose();
- itemBackgroundColor = null;
- itemForegroundColor = null;
- }
- });
- }
-
- /**
- * Creates the "Display" group.
- */
- void createDisplayGroup () {
- super.createDisplayGroup ();
-
- /* Create display controls specific to this example */
- headerVisibleButton = new Button (displayGroup, SWT.CHECK);
- headerVisibleButton.setText (ControlExample.getResourceString("Header_Visible"));
- linesVisibleButton = new Button (displayGroup, SWT.CHECK);
- linesVisibleButton.setText (ControlExample.getResourceString("Lines_Visible"));
-
- /* Add the listeners */
- headerVisibleButton.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setWidgetHeaderVisible ();
- }
- });
- linesVisibleButton.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- setWidgetLinesVisible ();
- };
- });
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for the table */
- tableGroup = new Group (exampleGroup, SWT.NONE);
- tableGroup.setLayout (new GridLayout ());
- tableGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- tableGroup.setText ("Table");
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
- /* Compute the widget style */
- int style = SWT.NONE;
- if (singleButton.getSelection ()) style |= SWT.SINGLE;
- if (multiButton.getSelection ()) style |= SWT.MULTI;
- if (verticalButton.getSelection ()) style |= SWT.V_SCROLL;
- if (horizontalButton.getSelection ()) style |= SWT.H_SCROLL;
- if (checkButton.getSelection ()) style |= SWT.CHECK;
- if (fullSelectionButton.getSelection ()) style |= SWT.FULL_SELECTION;
- if (borderButton.getSelection ()) style |= SWT.BORDER;
-
- /* Create the table widget */
- table1 = new Table (tableGroup, style);
-
- /* Fill the table with data */
- for (int i = 0; i < columnTitles.length; i++) {
- TableColumn tableColumn = new TableColumn(table1, SWT.NONE);
- tableColumn.setText(columnTitles[i]);
- }
- for (int i=0; i<16; i++) {
- TableItem item = new TableItem (table1, SWT.NONE);
- item.setImage (instance.images [i % 3]);
- switch (i % 3) {
- case 0:
- stringLine0 [0] = ControlExample.getResourceString("Index") + i;
- item.setText(stringLine0);
- break;
- case 1:
- stringLine1 [0] = ControlExample.getResourceString("Index") + i;
- item.setText(stringLine1);
- break;
- case 2:
- stringLine2 [0] = ControlExample.getResourceString("Index") + i;
- item.setText(stringLine2);
- break;
- }
- }
- for (int i = 0; i < columnTitles.length; i++) {
- TableColumn tableColumn = table1.getColumn(i);
- tableColumn.pack();
- }
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup () {
- super.createStyleGroup ();
-
- /* Create the extra widgets */
- checkButton = new Button (styleGroup, SWT.CHECK);
- checkButton.setText ("SWT.CHECK");
- fullSelectionButton = new Button (styleGroup, SWT.CHECK);
- fullSelectionButton.setText ("SWT.FULL_SELECTION");
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {table1};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Table";
- }
-
- /**
- * Sets the background color of the TableItems.
- */
- void setItemsBackground () {
- if (itemBackgroundButton == null) return;
- Color color = itemBackgroundColor;
- if (color == null) color = table1.getItem (0).getBackground ();
- Image image = itemBackgroundButton.getImage ();
- drawImage (image, color);
- itemBackgroundButton.setImage (image);
- if (itemBackgroundColor == null) return;
- table1.getItem (0).setBackground (itemBackgroundColor);
- }
-
- /**
- * Sets the foreground color of the TableItems.
- */
- void setItemsForeground () {
- if (itemForegroundButton == null) return;
- Color color = itemForegroundColor;
- if (color == null) color = table1.getItem (0).getForeground ();
- Image image = itemForegroundButton.getImage ();
- drawImage (image, color);
- itemForegroundButton.setImage (image);
- if (itemForegroundColor == null) return;
- table1.getItem (0).setForeground (itemForegroundColor);
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- setItemsBackground ();
- setItemsForeground ();
- setWidgetHeaderVisible ();
- setWidgetLinesVisible ();
- checkButton.setSelection ((table1.getStyle () & SWT.CHECK) != 0);
- fullSelectionButton.setSelection ((table1.getStyle () & SWT.FULL_SELECTION) != 0);
- }
-
- /**
- * Sets the header visible state of the "Example" widgets.
- */
- void setWidgetHeaderVisible () {
- table1.setHeaderVisible (headerVisibleButton.getSelection ());
- }
-
- /**
- * Sets the lines visible state of the "Example" widgets.
- */
- void setWidgetLinesVisible () {
- table1.setLinesVisible (linesVisibleButton.getSelection ());
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+class TableTab extends ScrollableTab {
+ /* Example widgets and groups that contain them */
+ Table table1;
+ Group tableGroup, tableItemGroup;
+
+ /* Style widgets added to the "Style" group */
+ Button checkButton, fullSelectionButton;
+
+ /* Display widgets added to the "Display" group */
+ Button headerVisibleButton, linesVisibleButton;
+
+ /* Color widgets added to the "Color" group */
+ Button itemBackgroundButton, itemForegroundButton;
+ Color itemBackgroundColor, itemForegroundColor;
+
+ static String [] columnTitles = {ControlExample.getResourceString("TableTitle_0"),
+ ControlExample.getResourceString("TableTitle_1"),
+ ControlExample.getResourceString("TableTitle_2"),
+ ControlExample.getResourceString("TableTitle_3")};
+
+ static String [] stringLine0 = {ControlExample.getResourceString("TableLine0_0"),
+ ControlExample.getResourceString("TableLine0_1"),
+ ControlExample.getResourceString("TableLine0_2"),
+ ControlExample.getResourceString("TableLine0_3")};
+
+ static String [] stringLine1 = {ControlExample.getResourceString("TableLine1_0"),
+ ControlExample.getResourceString("TableLine1_1"),
+ ControlExample.getResourceString("TableLine1_2"),
+ ControlExample.getResourceString("TableLine1_3")};
+
+ static String [] stringLine2 = {ControlExample.getResourceString("TableLine2_0"),
+ ControlExample.getResourceString("TableLine2_1"),
+ ControlExample.getResourceString("TableLine2_2"),
+ ControlExample.getResourceString("TableLine2_3")};
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ TableTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Colors" group.
+ */
+ void createColorGroup () {
+ super.createColorGroup();
+
+ tableItemGroup = new Group (colorGroup, SWT.NONE);
+ tableItemGroup.setText (ControlExample.getResourceString ("Table_Item_Colors"));
+ GridData data = new GridData ();
+ data.horizontalSpan = 2;
+ tableItemGroup.setLayoutData (data);
+ tableItemGroup.setLayout (new GridLayout (2, false));
+ new Label (tableItemGroup, SWT.NONE).setText (ControlExample.getResourceString ("Item_Foreground_Color"));
+ itemForegroundButton = new Button (tableItemGroup, SWT.PUSH);
+ new Label (tableItemGroup, SWT.NONE).setText (ControlExample.getResourceString ("Item_Background_Color"));
+ itemBackgroundButton = new Button (tableItemGroup, SWT.PUSH);
+
+ Shell shell = itemBackgroundButton.getShell ();
+ final ColorDialog backgroundDialog = new ColorDialog (shell);
+ final ColorDialog foregroundDialog = new ColorDialog (shell);
+
+ int imageSize = 12;
+ Display display = shell.getDisplay ();
+ final Image itemBackgroundImage = new Image(display, imageSize, imageSize);
+ final Image itemForegroundImage = new Image(display, imageSize, imageSize);
+
+ /* Add listeners to set the colors and font */
+ itemBackgroundButton.setImage(itemBackgroundImage);
+ itemBackgroundButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ RGB rgb = backgroundDialog.open();
+ if (rgb == null) return;
+ Color oldColor = itemBackgroundColor;
+ itemBackgroundColor = new Color (itemBackgroundButton.getDisplay(), rgb);
+ setItemsBackground ();
+ if (oldColor != null) oldColor.dispose ();
+ }
+ });
+ itemForegroundButton.setImage(itemForegroundImage);
+ itemForegroundButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ RGB rgb = foregroundDialog.open();
+ if (rgb == null) return;
+ Color oldColor = itemForegroundColor;
+ itemForegroundColor = new Color (itemForegroundButton.getDisplay(), rgb);
+ setItemsForeground ();
+ if (oldColor != null) oldColor.dispose ();
+ }
+ });
+ itemBackgroundButton.addDisposeListener(new DisposeListener() {
+ public void widgetDisposed(DisposeEvent event) {
+ if (itemBackgroundImage != null) itemBackgroundImage.dispose();
+ if (itemForegroundImage != null) itemForegroundImage.dispose();
+ if (itemBackgroundColor != null) itemBackgroundColor.dispose();
+ if (itemForegroundColor != null) itemForegroundColor.dispose();
+ itemBackgroundColor = null;
+ itemForegroundColor = null;
+ }
+ });
+ }
+
+ /**
+ * Creates the "Display" group.
+ */
+ void createDisplayGroup () {
+ super.createDisplayGroup ();
+
+ /* Create display controls specific to this example */
+ headerVisibleButton = new Button (displayGroup, SWT.CHECK);
+ headerVisibleButton.setText (ControlExample.getResourceString("Header_Visible"));
+ linesVisibleButton = new Button (displayGroup, SWT.CHECK);
+ linesVisibleButton.setText (ControlExample.getResourceString("Lines_Visible"));
+
+ /* Add the listeners */
+ headerVisibleButton.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setWidgetHeaderVisible ();
+ }
+ });
+ linesVisibleButton.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ setWidgetLinesVisible ();
+ };
+ });
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for the table */
+ tableGroup = new Group (exampleGroup, SWT.NONE);
+ tableGroup.setLayout (new GridLayout ());
+ tableGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ tableGroup.setText ("Table");
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (singleButton.getSelection ()) style |= SWT.SINGLE;
+ if (multiButton.getSelection ()) style |= SWT.MULTI;
+ if (verticalButton.getSelection ()) style |= SWT.V_SCROLL;
+ if (horizontalButton.getSelection ()) style |= SWT.H_SCROLL;
+ if (checkButton.getSelection ()) style |= SWT.CHECK;
+ if (fullSelectionButton.getSelection ()) style |= SWT.FULL_SELECTION;
+ if (borderButton.getSelection ()) style |= SWT.BORDER;
+
+ /* Create the table widget */
+ table1 = new Table (tableGroup, style);
+
+ /* Fill the table with data */
+ for (int i = 0; i < columnTitles.length; i++) {
+ TableColumn tableColumn = new TableColumn(table1, SWT.NONE);
+ tableColumn.setText(columnTitles[i]);
+ }
+ for (int i=0; i<16; i++) {
+ TableItem item = new TableItem (table1, SWT.NONE);
+ item.setImage (instance.images [i % 3]);
+ switch (i % 3) {
+ case 0:
+ stringLine0 [0] = ControlExample.getResourceString("Index") + i;
+ item.setText(stringLine0);
+ break;
+ case 1:
+ stringLine1 [0] = ControlExample.getResourceString("Index") + i;
+ item.setText(stringLine1);
+ break;
+ case 2:
+ stringLine2 [0] = ControlExample.getResourceString("Index") + i;
+ item.setText(stringLine2);
+ break;
+ }
+ }
+ for (int i = 0; i < columnTitles.length; i++) {
+ TableColumn tableColumn = table1.getColumn(i);
+ tableColumn.pack();
+ }
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup () {
+ super.createStyleGroup ();
+
+ /* Create the extra widgets */
+ checkButton = new Button (styleGroup, SWT.CHECK);
+ checkButton.setText ("SWT.CHECK");
+ fullSelectionButton = new Button (styleGroup, SWT.CHECK);
+ fullSelectionButton.setText ("SWT.FULL_SELECTION");
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {table1};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Table";
+ }
+
+ /**
+ * Sets the background color of the TableItems.
+ */
+ void setItemsBackground () {
+ if (itemBackgroundButton == null) return;
+ Color color = itemBackgroundColor;
+ if (color == null) color = table1.getItem (0).getBackground ();
+ Image image = itemBackgroundButton.getImage ();
+ drawImage (image, color);
+ itemBackgroundButton.setImage (image);
+ if (itemBackgroundColor == null) return;
+ table1.getItem (0).setBackground (itemBackgroundColor);
+ }
+
+ /**
+ * Sets the foreground color of the TableItems.
+ */
+ void setItemsForeground () {
+ if (itemForegroundButton == null) return;
+ Color color = itemForegroundColor;
+ if (color == null) color = table1.getItem (0).getForeground ();
+ Image image = itemForegroundButton.getImage ();
+ drawImage (image, color);
+ itemForegroundButton.setImage (image);
+ if (itemForegroundColor == null) return;
+ table1.getItem (0).setForeground (itemForegroundColor);
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ setItemsBackground ();
+ setItemsForeground ();
+ setWidgetHeaderVisible ();
+ setWidgetLinesVisible ();
+ checkButton.setSelection ((table1.getStyle () & SWT.CHECK) != 0);
+ fullSelectionButton.setSelection ((table1.getStyle () & SWT.FULL_SELECTION) != 0);
+ }
+
+ /**
+ * Sets the header visible state of the "Example" widgets.
+ */
+ void setWidgetHeaderVisible () {
+ table1.setHeaderVisible (headerVisibleButton.getSelection ());
+ }
+
+ /**
+ * Sets the lines visible state of the "Example" widgets.
+ */
+ void setWidgetLinesVisible () {
+ table1.setLinesVisible (linesVisibleButton.getSelection ());
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TextTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TextTab.java
index ee54acf275..5394f2822a 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TextTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TextTab.java
@@ -1,219 +1,219 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.custom.*;
-
-class TextTab extends ScrollableTab {
- /* Example widgets and groups that contain them */
- Text text;
- StyledText styledText;
- Group textGroup, styledTextGroup, styledTextStyleGroup;
-
- /* Style widgets added to the "Style" group */
- Button wrapButton, readOnlyButton;
-
- /* Buttons for adding StyleRanges to StyledText */
- Button boldButton, redButton, yellowButton;
- Image boldImage, redImage, yellowImage;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- TextTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates a bitmap image.
- */
- Image createBitmapImage (Display display, String name) {
- ImageData source = new ImageData(ControlExample.class.getResourceAsStream(name + ".bmp"));
- ImageData mask = new ImageData(ControlExample.class.getResourceAsStream(name + "_mask.bmp"));
- return new Image (display, source, mask);
- }
-
- /**
- * Creates the "Control" widget children.
- */
- void createControlWidgets () {
- super.createControlWidgets ();
-
- /* Add a group for modifying the StyledText widget */
- createStyledTextStyleGroup ();
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for the text widget */
- textGroup = new Group (exampleGroup, SWT.NONE);
- textGroup.setLayout (new GridLayout ());
- textGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- textGroup.setText ("Text");
-
- /* Create a group for the styled text widget */
- styledTextGroup = new Group (exampleGroup, SWT.NONE);
- styledTextGroup.setLayout (new GridLayout ());
- styledTextGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- styledTextGroup.setText ("StyledText");
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
-
- /* Compute the widget style */
- int style = SWT.NONE;
- if (singleButton.getSelection ()) style |= SWT.SINGLE;
- if (multiButton.getSelection ()) style |= SWT.MULTI;
- if (horizontalButton.getSelection ()) style |= SWT.H_SCROLL;
- if (verticalButton.getSelection ()) style |= SWT.V_SCROLL;
- if (wrapButton.getSelection ()) style |= SWT.WRAP;
- if (readOnlyButton.getSelection ()) style |= SWT.READ_ONLY;
- if (borderButton.getSelection ()) style |= SWT.BORDER;
-
- /* Create the example widgets */
- text = new Text (textGroup, style);
- text.setText (ControlExample.getResourceString("Example_string") + Text.DELIMITER + ControlExample.getResourceString("One_Two_Three"));
- styledText = new StyledText (styledTextGroup, style);
- styledText.setText (ControlExample.getResourceString("Example_string"));
- styledText.append ("\n");
- styledText.append (ControlExample.getResourceString("One_Two_Three"));
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup() {
- super.createStyleGroup();
-
- /* Create the extra widgets */
- wrapButton = new Button (styleGroup, SWT.CHECK);
- wrapButton.setText ("SWT.WRAP");
- readOnlyButton = new Button (styleGroup, SWT.CHECK);
- readOnlyButton.setText ("SWT.READ_ONLY");
- }
-
- /**
- * Creates the "StyledText Style" group.
- */
- void createStyledTextStyleGroup () {
- final Display display = controlGroup.getDisplay ();
- styledTextStyleGroup = new Group (controlGroup, SWT.NONE);
- styledTextStyleGroup.setText (ControlExample.getResourceString ("StyledText_Styles"));
- styledTextStyleGroup.setLayout (new GridLayout(2, false));
- styledTextStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL));
-
- /* Get images */
- boldImage = createBitmapImage (display, "bold");
- redImage = createBitmapImage (display, "red");
- yellowImage = createBitmapImage (display, "yellow");
-
- /* Create controls to modify the StyledText */
- Label label = new Label (styledTextStyleGroup, SWT.NONE);
- label.setText (ControlExample.getResourceString ("StyledText_Style_Instructions"));
- GridData data = new GridData(GridData.FILL_HORIZONTAL);
- data.horizontalSpan = 2;
- label.setLayoutData(data);
- new Label (styledTextStyleGroup, SWT.NONE).setText (ControlExample.getResourceString ("Bold"));
- boldButton = new Button (styledTextStyleGroup, SWT.PUSH);
- boldButton.setImage (boldImage);
- boldButton.addSelectionListener(new SelectionAdapter () {
- public void widgetSelected (SelectionEvent e) {
- Point sel = styledText.getSelectionRange();
- if ((sel == null) || (sel.y == 0)) return;
- StyleRange style;
- for (int i = sel.x; i<sel.x+sel.y; i++) {
- StyleRange range = styledText.getStyleRangeAtOffset(i);
- if (range == null) {style = new StyleRange(i, 1, null, null, SWT.BOLD);}
- else {style = new StyleRange(i, 1, range.foreground, range.background, SWT.BOLD);};
- styledText.setStyleRange(style);
- }
- styledText.setSelectionRange(sel.x + sel.y, 0);
- }
- });
- new Label (styledTextStyleGroup, SWT.NONE).setText (ControlExample.getResourceString ("Foreground_Style"));
- redButton = new Button (styledTextStyleGroup, SWT.PUSH);
- redButton.setImage (redImage);
- new Label (styledTextStyleGroup, SWT.NONE).setText (ControlExample.getResourceString ("Background_Style"));
- yellowButton = new Button (styledTextStyleGroup, SWT.PUSH);
- yellowButton.setImage (yellowImage);
- SelectionListener colorListener = new SelectionAdapter () {
- public void widgetSelected (SelectionEvent e) {
- Point sel = styledText.getSelectionRange();
- if ((sel == null) || (sel.y == 0)) return;
- Color fg, bg;
- if (e.widget == redButton) {
- fg = display.getSystemColor (SWT.COLOR_RED);
- bg = null;
- } else if (e.widget == yellowButton) {
- fg = null;
- bg = display.getSystemColor (SWT.COLOR_YELLOW);
- } else {
- fg = bg = null;
- }
- StyleRange style;
- for (int i = sel.x; i<sel.x+sel.y; i++) {
- StyleRange range = styledText.getStyleRangeAtOffset(i);
- if (range == null) {
- style = new StyleRange(i, 1, fg, bg, SWT.NORMAL);
- }
- else {
- if (range.foreground != null) fg = range.foreground;
- if (range.background != null) bg = range.background;
- style = new StyleRange(i, 1, fg, bg, range.fontStyle);
- };
- styledText.setStyleRange(style);
- }
- styledText.setSelectionRange(sel.x + sel.y, 0);
- };
- };
- redButton.addSelectionListener(colorListener);
- yellowButton.addSelectionListener(colorListener);
- yellowButton.addDisposeListener(new DisposeListener () {
- public void widgetDisposed (DisposeEvent e) {
- boldImage.dispose();
- redImage.dispose();
- yellowImage.dispose();
- }
- });
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {text, styledText};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Text";
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- wrapButton.setSelection ((text.getStyle () & SWT.WRAP) != 0);
- readOnlyButton.setSelection ((text.getStyle () & SWT.READ_ONLY) != 0);
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.custom.*;
+
+class TextTab extends ScrollableTab {
+ /* Example widgets and groups that contain them */
+ Text text;
+ StyledText styledText;
+ Group textGroup, styledTextGroup, styledTextStyleGroup;
+
+ /* Style widgets added to the "Style" group */
+ Button wrapButton, readOnlyButton;
+
+ /* Buttons for adding StyleRanges to StyledText */
+ Button boldButton, redButton, yellowButton;
+ Image boldImage, redImage, yellowImage;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ TextTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates a bitmap image.
+ */
+ Image createBitmapImage (Display display, String name) {
+ ImageData source = new ImageData(ControlExample.class.getResourceAsStream(name + ".bmp"));
+ ImageData mask = new ImageData(ControlExample.class.getResourceAsStream(name + "_mask.bmp"));
+ return new Image (display, source, mask);
+ }
+
+ /**
+ * Creates the "Control" widget children.
+ */
+ void createControlWidgets () {
+ super.createControlWidgets ();
+
+ /* Add a group for modifying the StyledText widget */
+ createStyledTextStyleGroup ();
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for the text widget */
+ textGroup = new Group (exampleGroup, SWT.NONE);
+ textGroup.setLayout (new GridLayout ());
+ textGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ textGroup.setText ("Text");
+
+ /* Create a group for the styled text widget */
+ styledTextGroup = new Group (exampleGroup, SWT.NONE);
+ styledTextGroup.setLayout (new GridLayout ());
+ styledTextGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ styledTextGroup.setText ("StyledText");
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (singleButton.getSelection ()) style |= SWT.SINGLE;
+ if (multiButton.getSelection ()) style |= SWT.MULTI;
+ if (horizontalButton.getSelection ()) style |= SWT.H_SCROLL;
+ if (verticalButton.getSelection ()) style |= SWT.V_SCROLL;
+ if (wrapButton.getSelection ()) style |= SWT.WRAP;
+ if (readOnlyButton.getSelection ()) style |= SWT.READ_ONLY;
+ if (borderButton.getSelection ()) style |= SWT.BORDER;
+
+ /* Create the example widgets */
+ text = new Text (textGroup, style);
+ text.setText (ControlExample.getResourceString("Example_string") + Text.DELIMITER + ControlExample.getResourceString("One_Two_Three"));
+ styledText = new StyledText (styledTextGroup, style);
+ styledText.setText (ControlExample.getResourceString("Example_string"));
+ styledText.append ("\n");
+ styledText.append (ControlExample.getResourceString("One_Two_Three"));
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup() {
+ super.createStyleGroup();
+
+ /* Create the extra widgets */
+ wrapButton = new Button (styleGroup, SWT.CHECK);
+ wrapButton.setText ("SWT.WRAP");
+ readOnlyButton = new Button (styleGroup, SWT.CHECK);
+ readOnlyButton.setText ("SWT.READ_ONLY");
+ }
+
+ /**
+ * Creates the "StyledText Style" group.
+ */
+ void createStyledTextStyleGroup () {
+ final Display display = controlGroup.getDisplay ();
+ styledTextStyleGroup = new Group (controlGroup, SWT.NONE);
+ styledTextStyleGroup.setText (ControlExample.getResourceString ("StyledText_Styles"));
+ styledTextStyleGroup.setLayout (new GridLayout(2, false));
+ styledTextStyleGroup.setLayoutData (new GridData (GridData.HORIZONTAL_ALIGN_FILL));
+
+ /* Get images */
+ boldImage = createBitmapImage (display, "bold");
+ redImage = createBitmapImage (display, "red");
+ yellowImage = createBitmapImage (display, "yellow");
+
+ /* Create controls to modify the StyledText */
+ Label label = new Label (styledTextStyleGroup, SWT.NONE);
+ label.setText (ControlExample.getResourceString ("StyledText_Style_Instructions"));
+ GridData data = new GridData(GridData.FILL_HORIZONTAL);
+ data.horizontalSpan = 2;
+ label.setLayoutData(data);
+ new Label (styledTextStyleGroup, SWT.NONE).setText (ControlExample.getResourceString ("Bold"));
+ boldButton = new Button (styledTextStyleGroup, SWT.PUSH);
+ boldButton.setImage (boldImage);
+ boldButton.addSelectionListener(new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent e) {
+ Point sel = styledText.getSelectionRange();
+ if ((sel == null) || (sel.y == 0)) return;
+ StyleRange style;
+ for (int i = sel.x; i<sel.x+sel.y; i++) {
+ StyleRange range = styledText.getStyleRangeAtOffset(i);
+ if (range == null) {style = new StyleRange(i, 1, null, null, SWT.BOLD);}
+ else {style = new StyleRange(i, 1, range.foreground, range.background, SWT.BOLD);};
+ styledText.setStyleRange(style);
+ }
+ styledText.setSelectionRange(sel.x + sel.y, 0);
+ }
+ });
+ new Label (styledTextStyleGroup, SWT.NONE).setText (ControlExample.getResourceString ("Foreground_Style"));
+ redButton = new Button (styledTextStyleGroup, SWT.PUSH);
+ redButton.setImage (redImage);
+ new Label (styledTextStyleGroup, SWT.NONE).setText (ControlExample.getResourceString ("Background_Style"));
+ yellowButton = new Button (styledTextStyleGroup, SWT.PUSH);
+ yellowButton.setImage (yellowImage);
+ SelectionListener colorListener = new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent e) {
+ Point sel = styledText.getSelectionRange();
+ if ((sel == null) || (sel.y == 0)) return;
+ Color fg, bg;
+ if (e.widget == redButton) {
+ fg = display.getSystemColor (SWT.COLOR_RED);
+ bg = null;
+ } else if (e.widget == yellowButton) {
+ fg = null;
+ bg = display.getSystemColor (SWT.COLOR_YELLOW);
+ } else {
+ fg = bg = null;
+ }
+ StyleRange style;
+ for (int i = sel.x; i<sel.x+sel.y; i++) {
+ StyleRange range = styledText.getStyleRangeAtOffset(i);
+ if (range == null) {
+ style = new StyleRange(i, 1, fg, bg, SWT.NORMAL);
+ }
+ else {
+ if (range.foreground != null) fg = range.foreground;
+ if (range.background != null) bg = range.background;
+ style = new StyleRange(i, 1, fg, bg, range.fontStyle);
+ };
+ styledText.setStyleRange(style);
+ }
+ styledText.setSelectionRange(sel.x + sel.y, 0);
+ };
+ };
+ redButton.addSelectionListener(colorListener);
+ yellowButton.addSelectionListener(colorListener);
+ yellowButton.addDisposeListener(new DisposeListener () {
+ public void widgetDisposed (DisposeEvent e) {
+ boldImage.dispose();
+ redImage.dispose();
+ yellowImage.dispose();
+ }
+ });
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {text, styledText};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Text";
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ wrapButton.setSelection ((text.getStyle () & SWT.WRAP) != 0);
+ readOnlyButton.setSelection ((text.getStyle () & SWT.READ_ONLY) != 0);
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ToolBarTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ToolBarTab.java
index faaaec82a0..605011152c 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ToolBarTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/ToolBarTab.java
@@ -1,248 +1,248 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.events.*;
-
-class ToolBarTab extends Tab {
- /* Example widgets and groups that contain them */
- ToolBar imageToolBar, textToolBar;
- Group imageToolBarGroup, textToolBarGroup;
-
- /* Style widgets added to the "Style" group */
- Button flatButton, wrapButton;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- ToolBarTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for the image tool bar */
- imageToolBarGroup = new Group (exampleGroup, SWT.NONE);
- imageToolBarGroup.setLayout (new GridLayout ());
- imageToolBarGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- imageToolBarGroup.setText (ControlExample.getResourceString("Image_ToolBar"));
-
- /* Create a group for the text tool bar */
- textToolBarGroup = new Group (exampleGroup, SWT.NONE);
- textToolBarGroup.setLayout (new GridLayout ());
- textToolBarGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- textToolBarGroup.setText (ControlExample.getResourceString("Text_ToolBar"));
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
-
- /* Compute the widget style */
- int style = SWT.NONE;
- if (flatButton.getSelection()) style |= SWT.FLAT;
- if (wrapButton.getSelection()) style |= SWT.WRAP;
- if (borderButton.getSelection()) style |= SWT.BORDER;
-
- /*
- * Create the example widgets.
- *
- * A tool bar must consist of all image tool
- * items or all text tool items but not both.
- */
-
- /* Create the image tool bar */
- imageToolBar = new ToolBar (imageToolBarGroup, style);
- ToolItem item = new ToolItem (imageToolBar, SWT.PUSH);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText("SWT.PUSH");
- item = new ToolItem (imageToolBar, SWT.PUSH);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.PUSH");
- item = new ToolItem (imageToolBar, SWT.RADIO);
- item.setImage (instance.images[ControlExample.ciOpenFolder]);
- item.setToolTipText ("SWT.RADIO");
- item = new ToolItem (imageToolBar, SWT.RADIO);
- item.setImage (instance.images[ControlExample.ciOpenFolder]);
- item.setToolTipText ("SWT.RADIO");
- item = new ToolItem (imageToolBar, SWT.CHECK);
- item.setImage (instance.images[ControlExample.ciTarget]);
- item.setToolTipText ("SWT.CHECK");
- item = new ToolItem (imageToolBar, SWT.RADIO);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.RADIO");
- item = new ToolItem (imageToolBar, SWT.RADIO);
- item.setImage (instance.images[ControlExample.ciClosedFolder]);
- item.setToolTipText ("SWT.RADIO");
- item = new ToolItem (imageToolBar, SWT.SEPARATOR);
- item.setToolTipText("SWT.SEPARATOR");
- item = new ToolItem (imageToolBar, SWT.DROP_DOWN);
- item.setImage (instance.images[ControlExample.ciTarget]);
- item.setToolTipText ("SWT.DROP_DOWN");
- item.addSelectionListener(new DropDownSelectionListener());
-
- /* Create the text tool bar */
- textToolBar = new ToolBar (textToolBarGroup, style);
- item = new ToolItem (textToolBar, SWT.PUSH);
- item.setText (ControlExample.getResourceString("Push"));
- item.setToolTipText("SWT.PUSH");
- item = new ToolItem (textToolBar, SWT.PUSH);
- item.setText (ControlExample.getResourceString("Push"));
- item.setToolTipText("SWT.PUSH");
- item = new ToolItem (textToolBar, SWT.RADIO);
- item.setText (ControlExample.getResourceString("Radio"));
- item.setToolTipText("SWT.RADIO");
- item = new ToolItem (textToolBar, SWT.RADIO);
- item.setText (ControlExample.getResourceString("Radio"));
- item.setToolTipText("SWT.RADIO");
- item = new ToolItem (textToolBar, SWT.CHECK);
- item.setText (ControlExample.getResourceString("Check"));
- item.setToolTipText("SWT.CHECK");
- item = new ToolItem (textToolBar, SWT.RADIO);
- item.setText (ControlExample.getResourceString("Radio"));
- item.setToolTipText("SWT.RADIO");
- item = new ToolItem (textToolBar, SWT.RADIO);
- item.setText (ControlExample.getResourceString("Radio"));
- item.setToolTipText("SWT.RADIO");
- item = new ToolItem (textToolBar, SWT.SEPARATOR);
- item.setToolTipText("SWT.SEPARATOR");
- item = new ToolItem (textToolBar, SWT.DROP_DOWN);
- item.setText (ControlExample.getResourceString("Drop_Down"));
- item.setToolTipText("SWT.DROP_DOWN");
- item.addSelectionListener(new DropDownSelectionListener());
-
- /*
- * Do not add the selection event for this drop down
- * tool item. Without hooking the event, the drop down
- * widget does nothing special when the drop down area
- * is selected.
- */
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup() {
- super.createStyleGroup();
-
- /* Create the extra widgets */
- flatButton = new Button (styleGroup, SWT.CHECK);
- flatButton.setText ("SWT.FLAT");
- wrapButton = new Button (styleGroup, SWT.CHECK);
- wrapButton.setText ("SWT.WRAP");
- borderButton = new Button (styleGroup, SWT.CHECK);
- borderButton.setText ("SWT.BORDER");
- }
-
- void disposeExampleWidgets () {
- super.disposeExampleWidgets ();
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {imageToolBar, textToolBar};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "ToolBar";
- }
-
- /**
- * Sets the state of the "Example" widgets.
- */
- void setExampleWidgetState () {
- super.setExampleWidgetState ();
- flatButton.setSelection ((imageToolBar.getStyle () & SWT.FLAT) != 0);
- wrapButton.setSelection ((imageToolBar.getStyle () & SWT.WRAP) != 0);
- borderButton.setSelection ((imageToolBar.getStyle () & SWT.BORDER) != 0);
- }
-
- /**
- * Listens to widgetSelected() events on SWT.DROP_DOWN type ToolItems
- * and opens/closes a menu when appropriate.
- */
- class DropDownSelectionListener extends SelectionAdapter {
- private Menu menu = null;
- private boolean visible = false;
-
- public void widgetSelected(SelectionEvent event) {
- // Create the menu if it has not already been created
- if (menu == null) {
- // Lazy create the menu.
- Shell shell = tabFolderPage.getShell();
- menu = new Menu(shell);
- for (int i = 0; i < 9; ++i) {
- final String text = ControlExample.getResourceString("DropDownData_" + i);
- if (text.length() != 0) {
- MenuItem menuItem = new MenuItem(menu, SWT.NONE);
- menuItem.setText(text);
- /*
- * Add a menu selection listener so that the menu is hidden
- * when the user selects an item from the drop down menu.
- */
- menuItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setMenuVisible(false);
- }
- });
- } else {
- new MenuItem(menu, SWT.SEPARATOR);
- }
- }
- }
-
- /**
- * A selection event will be fired when a drop down tool
- * item is selected in the main area and in the drop
- * down arrow. Examine the event detail to determine
- * where the widget was selected.
- */
- if (event.detail == SWT.ARROW) {
- /*
- * The drop down arrow was selected.
- */
- if (visible) {
- // Hide the menu to give the Arrow the appearance of being a toggle button.
- setMenuVisible(false);
- } else {
- // Position the menu below and vertically aligned with the the drop down tool button.
- final ToolItem toolItem = (ToolItem) event.widget;
- final ToolBar toolBar = toolItem.getParent();
-
- Rectangle toolItemBounds = toolItem.getBounds();
- Point point = toolBar.toDisplay(new Point(toolItemBounds.x, toolItemBounds.y));
- menu.setLocation(point.x, point.y + toolItemBounds.height);
- setMenuVisible(true);
- }
- } else {
- /*
- * Main area of drop down tool item selected.
- * An application would invoke the code to perform the action for the tool item.
- */
- }
- }
- private void setMenuVisible(boolean visible) {
- menu.setVisible(visible);
- this.visible = visible;
- }
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.events.*;
+
+class ToolBarTab extends Tab {
+ /* Example widgets and groups that contain them */
+ ToolBar imageToolBar, textToolBar;
+ Group imageToolBarGroup, textToolBarGroup;
+
+ /* Style widgets added to the "Style" group */
+ Button flatButton, wrapButton;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ ToolBarTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for the image tool bar */
+ imageToolBarGroup = new Group (exampleGroup, SWT.NONE);
+ imageToolBarGroup.setLayout (new GridLayout ());
+ imageToolBarGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ imageToolBarGroup.setText (ControlExample.getResourceString("Image_ToolBar"));
+
+ /* Create a group for the text tool bar */
+ textToolBarGroup = new Group (exampleGroup, SWT.NONE);
+ textToolBarGroup.setLayout (new GridLayout ());
+ textToolBarGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ textToolBarGroup.setText (ControlExample.getResourceString("Text_ToolBar"));
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (flatButton.getSelection()) style |= SWT.FLAT;
+ if (wrapButton.getSelection()) style |= SWT.WRAP;
+ if (borderButton.getSelection()) style |= SWT.BORDER;
+
+ /*
+ * Create the example widgets.
+ *
+ * A tool bar must consist of all image tool
+ * items or all text tool items but not both.
+ */
+
+ /* Create the image tool bar */
+ imageToolBar = new ToolBar (imageToolBarGroup, style);
+ ToolItem item = new ToolItem (imageToolBar, SWT.PUSH);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText("SWT.PUSH");
+ item = new ToolItem (imageToolBar, SWT.PUSH);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.PUSH");
+ item = new ToolItem (imageToolBar, SWT.RADIO);
+ item.setImage (instance.images[ControlExample.ciOpenFolder]);
+ item.setToolTipText ("SWT.RADIO");
+ item = new ToolItem (imageToolBar, SWT.RADIO);
+ item.setImage (instance.images[ControlExample.ciOpenFolder]);
+ item.setToolTipText ("SWT.RADIO");
+ item = new ToolItem (imageToolBar, SWT.CHECK);
+ item.setImage (instance.images[ControlExample.ciTarget]);
+ item.setToolTipText ("SWT.CHECK");
+ item = new ToolItem (imageToolBar, SWT.RADIO);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.RADIO");
+ item = new ToolItem (imageToolBar, SWT.RADIO);
+ item.setImage (instance.images[ControlExample.ciClosedFolder]);
+ item.setToolTipText ("SWT.RADIO");
+ item = new ToolItem (imageToolBar, SWT.SEPARATOR);
+ item.setToolTipText("SWT.SEPARATOR");
+ item = new ToolItem (imageToolBar, SWT.DROP_DOWN);
+ item.setImage (instance.images[ControlExample.ciTarget]);
+ item.setToolTipText ("SWT.DROP_DOWN");
+ item.addSelectionListener(new DropDownSelectionListener());
+
+ /* Create the text tool bar */
+ textToolBar = new ToolBar (textToolBarGroup, style);
+ item = new ToolItem (textToolBar, SWT.PUSH);
+ item.setText (ControlExample.getResourceString("Push"));
+ item.setToolTipText("SWT.PUSH");
+ item = new ToolItem (textToolBar, SWT.PUSH);
+ item.setText (ControlExample.getResourceString("Push"));
+ item.setToolTipText("SWT.PUSH");
+ item = new ToolItem (textToolBar, SWT.RADIO);
+ item.setText (ControlExample.getResourceString("Radio"));
+ item.setToolTipText("SWT.RADIO");
+ item = new ToolItem (textToolBar, SWT.RADIO);
+ item.setText (ControlExample.getResourceString("Radio"));
+ item.setToolTipText("SWT.RADIO");
+ item = new ToolItem (textToolBar, SWT.CHECK);
+ item.setText (ControlExample.getResourceString("Check"));
+ item.setToolTipText("SWT.CHECK");
+ item = new ToolItem (textToolBar, SWT.RADIO);
+ item.setText (ControlExample.getResourceString("Radio"));
+ item.setToolTipText("SWT.RADIO");
+ item = new ToolItem (textToolBar, SWT.RADIO);
+ item.setText (ControlExample.getResourceString("Radio"));
+ item.setToolTipText("SWT.RADIO");
+ item = new ToolItem (textToolBar, SWT.SEPARATOR);
+ item.setToolTipText("SWT.SEPARATOR");
+ item = new ToolItem (textToolBar, SWT.DROP_DOWN);
+ item.setText (ControlExample.getResourceString("Drop_Down"));
+ item.setToolTipText("SWT.DROP_DOWN");
+ item.addSelectionListener(new DropDownSelectionListener());
+
+ /*
+ * Do not add the selection event for this drop down
+ * tool item. Without hooking the event, the drop down
+ * widget does nothing special when the drop down area
+ * is selected.
+ */
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup() {
+ super.createStyleGroup();
+
+ /* Create the extra widgets */
+ flatButton = new Button (styleGroup, SWT.CHECK);
+ flatButton.setText ("SWT.FLAT");
+ wrapButton = new Button (styleGroup, SWT.CHECK);
+ wrapButton.setText ("SWT.WRAP");
+ borderButton = new Button (styleGroup, SWT.CHECK);
+ borderButton.setText ("SWT.BORDER");
+ }
+
+ void disposeExampleWidgets () {
+ super.disposeExampleWidgets ();
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {imageToolBar, textToolBar};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "ToolBar";
+ }
+
+ /**
+ * Sets the state of the "Example" widgets.
+ */
+ void setExampleWidgetState () {
+ super.setExampleWidgetState ();
+ flatButton.setSelection ((imageToolBar.getStyle () & SWT.FLAT) != 0);
+ wrapButton.setSelection ((imageToolBar.getStyle () & SWT.WRAP) != 0);
+ borderButton.setSelection ((imageToolBar.getStyle () & SWT.BORDER) != 0);
+ }
+
+ /**
+ * Listens to widgetSelected() events on SWT.DROP_DOWN type ToolItems
+ * and opens/closes a menu when appropriate.
+ */
+ class DropDownSelectionListener extends SelectionAdapter {
+ private Menu menu = null;
+ private boolean visible = false;
+
+ public void widgetSelected(SelectionEvent event) {
+ // Create the menu if it has not already been created
+ if (menu == null) {
+ // Lazy create the menu.
+ Shell shell = tabFolderPage.getShell();
+ menu = new Menu(shell);
+ for (int i = 0; i < 9; ++i) {
+ final String text = ControlExample.getResourceString("DropDownData_" + i);
+ if (text.length() != 0) {
+ MenuItem menuItem = new MenuItem(menu, SWT.NONE);
+ menuItem.setText(text);
+ /*
+ * Add a menu selection listener so that the menu is hidden
+ * when the user selects an item from the drop down menu.
+ */
+ menuItem.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setMenuVisible(false);
+ }
+ });
+ } else {
+ new MenuItem(menu, SWT.SEPARATOR);
+ }
+ }
+ }
+
+ /**
+ * A selection event will be fired when a drop down tool
+ * item is selected in the main area and in the drop
+ * down arrow. Examine the event detail to determine
+ * where the widget was selected.
+ */
+ if (event.detail == SWT.ARROW) {
+ /*
+ * The drop down arrow was selected.
+ */
+ if (visible) {
+ // Hide the menu to give the Arrow the appearance of being a toggle button.
+ setMenuVisible(false);
+ } else {
+ // Position the menu below and vertically aligned with the the drop down tool button.
+ final ToolItem toolItem = (ToolItem) event.widget;
+ final ToolBar toolBar = toolItem.getParent();
+
+ Rectangle toolItemBounds = toolItem.getBounds();
+ Point point = toolBar.toDisplay(new Point(toolItemBounds.x, toolItemBounds.y));
+ menu.setLocation(point.x, point.y + toolItemBounds.height);
+ setMenuVisible(true);
+ }
+ } else {
+ /*
+ * Main area of drop down tool item selected.
+ * An application would invoke the code to perform the action for the tool item.
+ */
+ }
+ }
+ private void setMenuVisible(boolean visible) {
+ menu.setVisible(visible);
+ this.visible = visible;
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TreeTab.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TreeTab.java
index f3cfece159..87d3719bbc 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TreeTab.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/controlexample/TreeTab.java
@@ -1,135 +1,135 @@
-package org.eclipse.swt.examples.controlexample;
-
-/*
+package org.eclipse.swt.examples.controlexample;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.widgets.*;
-
-class TreeTab extends ScrollableTab {
- /* Example widgets and groups that contain them */
- Tree tree1, tree2;
- Group treeGroup, imageTreeGroup;
-
- /* Style widgets added to the "Style" group */
- Button checkButton;
-
- /**
- * Creates the Tab within a given instance of ControlExample.
- */
- TreeTab(ControlExample instance) {
- super(instance);
- }
-
- /**
- * Creates the "Example" group.
- */
- void createExampleGroup () {
- super.createExampleGroup ();
-
- /* Create a group for the text tree */
- treeGroup = new Group (exampleGroup, SWT.NONE);
- treeGroup.setLayout (new GridLayout ());
- treeGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- treeGroup.setText ("Tree");
-
- /* Create a group for the image tree */
- imageTreeGroup = new Group (exampleGroup, SWT.NONE);
- imageTreeGroup.setLayout (new GridLayout ());
- imageTreeGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
- imageTreeGroup.setText (ControlExample.getResourceString("Tree_With_Images"));
- }
-
- /**
- * Creates the "Example" widgets.
- */
- void createExampleWidgets () {
- /* Compute the widget style */
- int style = SWT.NONE;
- if (singleButton.getSelection()) style |= SWT.SINGLE;
- if (multiButton.getSelection()) style |= SWT.MULTI;
- if (checkButton.getSelection()) style |= SWT.CHECK;
- if (borderButton.getSelection()) style |= SWT.BORDER;
-
- /* Create the text tree */
- tree1 = new Tree (treeGroup, style);
- TreeItem node1 = new TreeItem (tree1, SWT.NONE);
- node1.setText (ControlExample.getResourceString("Node_1"));
- TreeItem node2 = new TreeItem (tree1, SWT.NONE);
- node2.setText (ControlExample.getResourceString("Node_2"));
- TreeItem node3 = new TreeItem (tree1, SWT.NONE);
- node3.setText (ControlExample.getResourceString("Node_3"));
- TreeItem node4 = new TreeItem (tree1, SWT.NONE);
- node4.setText (ControlExample.getResourceString("Node_4"));
- TreeItem node1_1 = new TreeItem (node1, SWT.NONE);
- node1_1.setText (ControlExample.getResourceString("Node_1_1"));
- TreeItem node2_1 = new TreeItem (node2, SWT.NONE);
- node2_1.setText (ControlExample.getResourceString("Node_2_1"));
- TreeItem node3_1 = new TreeItem (node3, SWT.NONE);
- node3_1.setText (ControlExample.getResourceString("Node_3_1"));
- TreeItem node2_2 = new TreeItem (node2, SWT.NONE);
- node2_2.setText (ControlExample.getResourceString("Node_2_2"));
- TreeItem node2_2_1 = new TreeItem (node2_2, SWT.NONE);
- node2_2_1.setText (ControlExample.getResourceString("Node_2_2_1"));
-
- /* Create the image tree */
- tree2 = new Tree (imageTreeGroup, style);
- node1 = new TreeItem (tree2, SWT.NONE);
- node1.setText (ControlExample.getResourceString("Node_1"));
- node1.setImage (instance.images[ControlExample.ciClosedFolder]);
- node2 = new TreeItem (tree2, SWT.NONE);
- node2.setText (ControlExample.getResourceString("Node_2"));
- node2.setImage (instance.images[ControlExample.ciClosedFolder]);
- node3 = new TreeItem (tree2, SWT.NONE);
- node3.setText (ControlExample.getResourceString("Node_3"));
- node3.setImage (instance.images[ControlExample.ciClosedFolder]);
- node4 = new TreeItem (tree2, SWT.NONE);
- node4.setText (ControlExample.getResourceString("Node_4"));
- node4.setImage (instance.images[ControlExample.ciClosedFolder]);
- node1_1 = new TreeItem (node1, SWT.NONE);
- node1_1.setText (ControlExample.getResourceString("Node_1_1"));
- node1_1.setImage (instance.images[ControlExample.ciClosedFolder]);
- node2_1 = new TreeItem (node2, SWT.NONE);
- node2_1.setText (ControlExample.getResourceString("Node_2_1"));
- node2_1.setImage (instance.images[ControlExample.ciClosedFolder]);
- node3_1 = new TreeItem (node3, SWT.NONE);
- node3_1.setText (ControlExample.getResourceString("Node_3_1"));
- node3_1.setImage (instance.images[ControlExample.ciClosedFolder]);
- node2_2 = new TreeItem(node2, SWT.NONE);
- node2_2.setText (ControlExample.getResourceString("Node_2_2"));
- node2_2.setImage (instance.images[ControlExample.ciClosedFolder]);
- node2_2_1 = new TreeItem (node2_2, SWT.NONE);
- node2_2_1.setText (ControlExample.getResourceString("Node_2_2_1"));
- node2_2_1.setImage (instance.images[ControlExample.ciClosedFolder]);
- }
-
- /**
- * Creates the "Style" group.
- */
- void createStyleGroup() {
- super.createStyleGroup();
-
- /* Create the extra widgets */
- checkButton = new Button (styleGroup, SWT.CHECK);
- checkButton.setText ("SWT.CHECK");
- }
-
- /**
- * Gets the "Example" widget children.
- */
- Control [] getExampleWidgets () {
- return new Control [] {tree1, tree2};
- }
-
- /**
- * Gets the text for the tab folder item.
- */
- String getTabText () {
- return "Tree";
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.widgets.*;
+
+class TreeTab extends ScrollableTab {
+ /* Example widgets and groups that contain them */
+ Tree tree1, tree2;
+ Group treeGroup, imageTreeGroup;
+
+ /* Style widgets added to the "Style" group */
+ Button checkButton;
+
+ /**
+ * Creates the Tab within a given instance of ControlExample.
+ */
+ TreeTab(ControlExample instance) {
+ super(instance);
+ }
+
+ /**
+ * Creates the "Example" group.
+ */
+ void createExampleGroup () {
+ super.createExampleGroup ();
+
+ /* Create a group for the text tree */
+ treeGroup = new Group (exampleGroup, SWT.NONE);
+ treeGroup.setLayout (new GridLayout ());
+ treeGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ treeGroup.setText ("Tree");
+
+ /* Create a group for the image tree */
+ imageTreeGroup = new Group (exampleGroup, SWT.NONE);
+ imageTreeGroup.setLayout (new GridLayout ());
+ imageTreeGroup.setLayoutData (new GridData (GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ imageTreeGroup.setText (ControlExample.getResourceString("Tree_With_Images"));
+ }
+
+ /**
+ * Creates the "Example" widgets.
+ */
+ void createExampleWidgets () {
+ /* Compute the widget style */
+ int style = SWT.NONE;
+ if (singleButton.getSelection()) style |= SWT.SINGLE;
+ if (multiButton.getSelection()) style |= SWT.MULTI;
+ if (checkButton.getSelection()) style |= SWT.CHECK;
+ if (borderButton.getSelection()) style |= SWT.BORDER;
+
+ /* Create the text tree */
+ tree1 = new Tree (treeGroup, style);
+ TreeItem node1 = new TreeItem (tree1, SWT.NONE);
+ node1.setText (ControlExample.getResourceString("Node_1"));
+ TreeItem node2 = new TreeItem (tree1, SWT.NONE);
+ node2.setText (ControlExample.getResourceString("Node_2"));
+ TreeItem node3 = new TreeItem (tree1, SWT.NONE);
+ node3.setText (ControlExample.getResourceString("Node_3"));
+ TreeItem node4 = new TreeItem (tree1, SWT.NONE);
+ node4.setText (ControlExample.getResourceString("Node_4"));
+ TreeItem node1_1 = new TreeItem (node1, SWT.NONE);
+ node1_1.setText (ControlExample.getResourceString("Node_1_1"));
+ TreeItem node2_1 = new TreeItem (node2, SWT.NONE);
+ node2_1.setText (ControlExample.getResourceString("Node_2_1"));
+ TreeItem node3_1 = new TreeItem (node3, SWT.NONE);
+ node3_1.setText (ControlExample.getResourceString("Node_3_1"));
+ TreeItem node2_2 = new TreeItem (node2, SWT.NONE);
+ node2_2.setText (ControlExample.getResourceString("Node_2_2"));
+ TreeItem node2_2_1 = new TreeItem (node2_2, SWT.NONE);
+ node2_2_1.setText (ControlExample.getResourceString("Node_2_2_1"));
+
+ /* Create the image tree */
+ tree2 = new Tree (imageTreeGroup, style);
+ node1 = new TreeItem (tree2, SWT.NONE);
+ node1.setText (ControlExample.getResourceString("Node_1"));
+ node1.setImage (instance.images[ControlExample.ciClosedFolder]);
+ node2 = new TreeItem (tree2, SWT.NONE);
+ node2.setText (ControlExample.getResourceString("Node_2"));
+ node2.setImage (instance.images[ControlExample.ciClosedFolder]);
+ node3 = new TreeItem (tree2, SWT.NONE);
+ node3.setText (ControlExample.getResourceString("Node_3"));
+ node3.setImage (instance.images[ControlExample.ciClosedFolder]);
+ node4 = new TreeItem (tree2, SWT.NONE);
+ node4.setText (ControlExample.getResourceString("Node_4"));
+ node4.setImage (instance.images[ControlExample.ciClosedFolder]);
+ node1_1 = new TreeItem (node1, SWT.NONE);
+ node1_1.setText (ControlExample.getResourceString("Node_1_1"));
+ node1_1.setImage (instance.images[ControlExample.ciClosedFolder]);
+ node2_1 = new TreeItem (node2, SWT.NONE);
+ node2_1.setText (ControlExample.getResourceString("Node_2_1"));
+ node2_1.setImage (instance.images[ControlExample.ciClosedFolder]);
+ node3_1 = new TreeItem (node3, SWT.NONE);
+ node3_1.setText (ControlExample.getResourceString("Node_3_1"));
+ node3_1.setImage (instance.images[ControlExample.ciClosedFolder]);
+ node2_2 = new TreeItem(node2, SWT.NONE);
+ node2_2.setText (ControlExample.getResourceString("Node_2_2"));
+ node2_2.setImage (instance.images[ControlExample.ciClosedFolder]);
+ node2_2_1 = new TreeItem (node2_2, SWT.NONE);
+ node2_2_1.setText (ControlExample.getResourceString("Node_2_2_1"));
+ node2_2_1.setImage (instance.images[ControlExample.ciClosedFolder]);
+ }
+
+ /**
+ * Creates the "Style" group.
+ */
+ void createStyleGroup() {
+ super.createStyleGroup();
+
+ /* Create the extra widgets */
+ checkButton = new Button (styleGroup, SWT.CHECK);
+ checkButton.setText ("SWT.CHECK");
+ }
+
+ /**
+ * Gets the "Example" widget children.
+ */
+ Control [] getExampleWidgets () {
+ return new Control [] {tree1, tree2};
+ }
+
+ /**
+ * Gets the text for the tab folder item.
+ */
+ String getTabText () {
+ return "Tree";
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/FileViewer.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/FileViewer.java
index 65b88d39ae..6f51c57a2c 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/FileViewer.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/FileViewer.java
@@ -1,1707 +1,1707 @@
-package org.eclipse.swt.examples.fileviewer;
- /*
+package org.eclipse.swt.examples.fileviewer;
+ /*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.custom.*;
-import org.eclipse.swt.dnd.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.program.*;
-import org.eclipse.swt.widgets.*;
-
-import java.io.*;
-import java.text.*;
-import java.util.*;
- /**
- * File Viewer example
- */
-public class FileViewer {
- private static ResourceBundle resourceBundle = ResourceBundle.getBundle("examples_fileviewer");
- private final static String DRIVE_A = "a:" + File.separator;
- private final static String DRIVE_B = "b:" + File.separator;
-
- /* UI elements */
- private Display display;
- private Shell shell;
- private ToolBar toolBar;
-
- private Label numObjectsLabel;
- private Label diskSpaceLabel;
-
- private File currentDirectory = null;
- private boolean initial = true;
-
- /* Drag and drop optimizations */
- private boolean isDragging = false; // if this app is dragging
- private boolean isDropping = false; // if this app is dropping
-
- private File[] processedDropFiles = null; // so Drag only deletes what it needs to
- private File[] deferredRefreshFiles = null; // to defer notifyRefreshFiles while we do DND
- private boolean deferredRefreshRequested = false; // to defer notifyRefreshFiles while we do DND
- private ProgressDialog progressDialog = null; // progress dialog for locally-initiated operations
-
- /* Combo view */
- private static final String COMBODATA_ROOTS = "Combo.roots";
- // File[]: Array of files whose paths are currently displayed in the combo
- private static final String COMBODATA_LASTTEXT = "Combo.lastText";
- // String: Previous selection text string
-
- private Combo combo;
-
- /* Tree view */
- private IconCache iconCache = new IconCache();
- private static final String TREEITEMDATA_FILE = "TreeItem.file";
- // File: File associated with tree item
- private static final String TREEITEMDATA_IMAGEEXPANDED = "TreeItem.imageExpanded";
- // Image: shown when item is expanded
- private static final String TREEITEMDATA_IMAGECOLLAPSED = "TreeItem.imageCollapsed";
- // Image: shown when item is collapsed
- private static final String TREEITEMDATA_STUB = "TreeItem.stub";
- // Object: if not present or null then the item has not been populated
-
- private Tree tree;
- private Label treeScopeLabel;
-
- /* Table view */
- private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(
- DateFormat.MEDIUM, DateFormat.MEDIUM);
- private static final String TABLEITEMDATA_FILE = "TableItem.file";
- // File: File associated with table row
- private static final String TABLEDATA_DIR = "Table.dir";
- // File: Currently visible directory
- private static final int[] tableWidths = new int[] {150, 60, 75, 150};
- private final String[] tableTitles = new String [] {
- FileViewer.getResourceString("table.Name.title"),
- FileViewer.getResourceString("table.Size.title"),
- FileViewer.getResourceString("table.Type.title"),
- FileViewer.getResourceString("table.Modified.title")
- };
- private Table table;
- private Label tableContentsOfLabel;
-
- /* Table update worker */
- // Control data
- private final Object workerLock = new Object();
- // Lock for all worker control data and state
- private volatile Thread workerThread = null;
- // The worker's thread
- private volatile boolean workerStopped = false;
- // True if the worker must exit on completion of the current cycle
- private volatile boolean workerCancelled = false;
- // True if the worker must cancel its operations prematurely perhaps due to a state update
-
- // Worker state information -- this is what gets synchronized by an update
- private volatile File workerStateDir = null;
-
- // State information to use for the next cycle
- private volatile File workerNextDir = null;
-
- /* Simulate only flag */
- // when true, disables actual filesystem manipulations and outputs results to standard out
- private boolean simulateOnly = true;
-
- /**
- * Runs main program.
- */
- public static void main (String [] args) {
- Display display = new Display ();
- FileViewer application = new FileViewer();
- Shell shell = application.open(display);
- while (! shell.isDisposed()) {
- if (! display.readAndDispatch()) display.sleep();
- }
- application.close();
- display.dispose();
- }
-
- /**
- * Opens the main program.
- */
- public Shell open(Display display) {
- // Create the window
- this.display = display;
- iconCache.initResources(display);
- shell = new Shell();
- createShellContents();
- notifyRefreshFiles(null);
- shell.open();
- return shell;
- }
- /**
- * Closes the main program.
- */
- void close() {
- workerStop();
- iconCache.freeResources();
- }
-
- /**
- * Returns a string from the resource bundle.
- * We don't want to crash because of a missing String.
- * Returns the key if not found.
- */
- static String getResourceString(String key) {
- try {
- return resourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Returns a string from the resource bundle and binds it
- * with the given arguments. If the key is not found,
- * return the key.
- */
- static String getResourceString(String key, Object[] args) {
- try {
- return MessageFormat.format(getResourceString(key), args);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Construct the UI
- *
- * @param container the ShellContainer managing the Shell we are rendering inside
- */
- private void createShellContents() {
- shell.setText(getResourceString("Title", new Object[] { "" }));
- shell.setImage(iconCache.stockImages[iconCache.shellIcon]);
- Menu bar = new Menu(shell, SWT.BAR);
- shell.setMenuBar(bar);
- createFileMenu(bar);
- createHelpMenu(bar);
-
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 3;
- gridLayout.marginHeight = gridLayout.marginWidth = 0;
- shell.setLayout(gridLayout);
-
- GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gridData.widthHint = 185;
- createComboView(shell, gridData);
- gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gridData.horizontalSpan = 2;
- createToolBar(shell, gridData);
-
- SashForm sashForm = new SashForm(shell, SWT.NONE);
- sashForm.setOrientation(SWT.HORIZONTAL);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
- gridData.horizontalSpan = 3;
- sashForm.setLayoutData(gridData);
- createTreeView(sashForm);
- createTableView(sashForm);
- sashForm.setWeights(new int[] { 2, 5 });
-
- numObjectsLabel = new Label(shell, SWT.BORDER);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
- gridData.widthHint = 185;
- numObjectsLabel.setLayoutData(gridData);
-
- diskSpaceLabel = new Label(shell, SWT.BORDER);
- gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
- gridData.horizontalSpan = 2;
- diskSpaceLabel.setLayoutData(gridData);
- }
-
- /**
- * Creates the File Menu.
- *
- * @param parent the parent menu
- */
- private void createFileMenu(Menu parent) {
- Menu menu = new Menu(parent);
- MenuItem header = new MenuItem(parent, SWT.CASCADE);
- header.setText(getResourceString("menu.File.text"));
- header.setMenu(menu);
-
- final MenuItem simulateItem = new MenuItem(menu, SWT.CHECK);
- simulateItem.setText(getResourceString("menu.File.SimulateOnly.text"));
- simulateItem.setSelection(simulateOnly);
- simulateItem.addSelectionListener(new SelectionAdapter () {
- public void widgetSelected(SelectionEvent e) {
- simulateOnly = simulateItem.getSelection();
- }
- });
-
- MenuItem item = new MenuItem(menu, SWT.PUSH);
- item.setText(getResourceString("menu.File.Close.text"));
- item.addSelectionListener(new SelectionAdapter () {
- public void widgetSelected(SelectionEvent e) {
- shell.close();
- }
- });
- }
-
- /**
- * Creates the Help Menu.
- *
- * @param parent the parent menu
- */
- private void createHelpMenu(Menu parent) {
- Menu menu = new Menu(parent);
- MenuItem header = new MenuItem(parent, SWT.CASCADE);
- header.setText(getResourceString("menu.Help.text"));
- header.setMenu(menu);
-
- MenuItem item = new MenuItem(menu, SWT.PUSH);
- item.setText(getResourceString("menu.Help.About.text"));
- item.addSelectionListener(new SelectionAdapter () {
- public void widgetSelected(SelectionEvent e) {
- MessageBox box = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
- box.setText(getResourceString("dialog.About.title"));
- box.setMessage(getResourceString("dialog.About.description",
- new Object[] { System.getProperty("os.name") }));
- box.open();
- }
- });
- }
-
- /**
- * Creates the toolbar
- *
- * @param shell the shell on which to attach the toolbar
- * @param layoutData the layout data
- */
- private void createToolBar(final Shell shell, Object layoutData) {
- toolBar = new ToolBar(shell, SWT.NULL);
- toolBar.setLayoutData(layoutData);
- ToolItem item = new ToolItem(toolBar, SWT.SEPARATOR);
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdParent]);
- item.setToolTipText(getResourceString("tool.Parent.tiptext"));
- item.addSelectionListener(new SelectionAdapter () {
- public void widgetSelected(SelectionEvent e) {
- doParent();
- }
- });
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdRefresh]);
- item.setToolTipText(getResourceString("tool.Refresh.tiptext"));
- item.addSelectionListener(new SelectionAdapter () {
- public void widgetSelected(SelectionEvent e) {
- doRefresh();
- }
- });
- SelectionAdapter unimplementedListener = new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- MessageBox box = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
- box.setText(getResourceString("dialog.NotImplemented.title"));
- box.setMessage(getResourceString("dialog.ActionNotImplemented.description"));
- box.open();
- }
- };
-
- item = new ToolItem(toolBar, SWT.SEPARATOR);
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdCut]);
- item.setToolTipText(getResourceString("tool.Cut.tiptext"));
- item.addSelectionListener(unimplementedListener);
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdCopy]);
- item.setToolTipText(getResourceString("tool.Copy.tiptext"));
- item.addSelectionListener(unimplementedListener);
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdPaste]);
- item.setToolTipText(getResourceString("tool.Paste.tiptext")); item.addSelectionListener(unimplementedListener);
-
- item = new ToolItem(toolBar, SWT.SEPARATOR);
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdDelete]);
- item.setToolTipText(getResourceString("tool.Delete.tiptext"));
- item.addSelectionListener(unimplementedListener);
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdRename]);
- item.setToolTipText(getResourceString("tool.Rename.tiptext"));
- item.addSelectionListener(unimplementedListener);
-
- item = new ToolItem(toolBar, SWT.SEPARATOR);
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdSearch]);
- item.setToolTipText(getResourceString("tool.Search.tiptext"));
- item.addSelectionListener(unimplementedListener);
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(iconCache.stockImages[iconCache.cmdPrint]);
- item.setToolTipText(getResourceString("tool.Print.tiptext"));
- item.addSelectionListener(unimplementedListener);
- }
-
- /**
- * Creates the combo box view.
- *
- * @param parent the parent control
- */
- private void createComboView(Composite parent, Object layoutData) {
- combo = new Combo(parent, SWT.NONE);
- combo.setLayoutData(layoutData);
- combo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- final File[] roots = (File[]) combo.getData(COMBODATA_ROOTS);
- if (roots == null) return;
- int selection = combo.getSelectionIndex();
- if (selection >= 0 && selection < roots.length) {
- notifySelectedDirectory(roots[selection]);
- }
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- final String lastText = (String) combo.getData(COMBODATA_LASTTEXT);
- String text = combo.getText();
- if (text == null) return;
- if (lastText != null && lastText.equals(text)) return;
- combo.setData(COMBODATA_LASTTEXT, text);
- notifySelectedDirectory(new File(text));
- }
- });
- }
-
- /**
- * Creates the file tree view.
- *
- * @param parent the parent control
- */
- private void createTreeView(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 1;
- gridLayout.marginHeight = gridLayout.marginWidth = 2;
- gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
- composite.setLayout(gridLayout);
-
- treeScopeLabel = new Label(composite, SWT.BORDER);
- treeScopeLabel.setText(FileViewer.getResourceString("details.AllFolders.text"));
- treeScopeLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
-
- tree = new Tree(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE);
- tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
-
- tree.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent event) {
- final TreeItem[] selection = tree.getSelection();
- if (selection != null && selection.length != 0) {
- TreeItem item = selection[0];
- File file = (File) item.getData(TREEITEMDATA_FILE);
-
- notifySelectedDirectory(file);
- }
- }
- public void widgetDefaultSelected(SelectionEvent event) {
- final TreeItem[] selection = tree.getSelection();
- if (selection != null && selection.length != 0) {
- TreeItem item = selection[0];
- item.setExpanded(true);
- treeExpandItem(item);
- }
- }
- });
- tree.addTreeListener(new TreeAdapter() {
- public void treeExpanded(TreeEvent event) {
- final TreeItem item = (TreeItem) event.item;
- final Image image = (Image) item.getData(TREEITEMDATA_IMAGEEXPANDED);
- if (image != null) item.setImage(image);
- treeExpandItem(item);
- }
- public void treeCollapsed(TreeEvent event) {
- final TreeItem item = (TreeItem) event.item;
- final Image image = (Image) item.getData(TREEITEMDATA_IMAGECOLLAPSED);
- if (image != null) item.setImage(image);
- }
- });
- createTreeDragSource(tree);
- createTreeDropTarget(tree);
- }
-
- /**
- * Creates the Drag & Drop DragSource for items being dragged from the tree.
- *
- * @return the DragSource for the tree
- */
- private DragSource createTreeDragSource(final Tree tree){
- DragSource dragSource = new DragSource(tree, DND.DROP_MOVE | DND.DROP_COPY);
- dragSource.setTransfer(new Transfer[] { FileTransfer.getInstance() });
- dragSource.addDragListener(new DragSourceListener() {
- TreeItem[] dndSelection = null;
- String[] sourceNames = null;
- public void dragStart(DragSourceEvent event){
- dndSelection = tree.getSelection();
- sourceNames = null;
- event.doit = dndSelection.length > 0;
- isDragging = true;
- processedDropFiles = null;
- }
- public void dragFinished(DragSourceEvent event){
- dragSourceHandleDragFinished(event, sourceNames);
- dndSelection = null;
- sourceNames = null;
- isDragging = false;
- processedDropFiles = null;
- handleDeferredRefresh();
- }
- public void dragSetData(DragSourceEvent event){
- if (dndSelection == null || dndSelection.length == 0) return;
- if (! FileTransfer.getInstance().isSupportedType(event.dataType)) return;
-
- sourceNames = new String[dndSelection.length];
- for (int i = 0; i < dndSelection.length; i++) {
- File file = (File) dndSelection[i].getData(TREEITEMDATA_FILE);
- sourceNames[i] = file.getAbsolutePath();
- }
- event.data = sourceNames;
- }
- });
- return dragSource;
- }
-
- /**
- * Creates the Drag & Drop DropTarget for items being dropped onto the tree.
- *
- * @return the DropTarget for the tree
- */
- private DropTarget createTreeDropTarget(final Tree tree) {
- DropTarget dropTarget = new DropTarget(tree, DND.DROP_MOVE | DND.DROP_COPY);
- dropTarget.setTransfer(new Transfer[] { FileTransfer.getInstance() });
- dropTarget.addDropListener(new DropTargetAdapter() {
- public void dragEnter(DropTargetEvent event) {
- isDropping = true;
- }
- public void dragLeave(DropTargetEvent event) {
- isDropping = false;
- handleDeferredRefresh();
- }
- public void dragOver(DropTargetEvent event) {
- dropTargetValidate(event, getTargetFile(event));
- event.feedback |= DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
- }
- public void drop(DropTargetEvent event) {
- File targetFile = getTargetFile(event);
- if (dropTargetValidate(event, targetFile))
- dropTargetHandleDrop(event, targetFile);
- }
- private File getTargetFile(DropTargetEvent event) {
- // Determine the target File for the drop
- TreeItem item = tree.getItem(tree.toControl(new Point(event.x, event.y)));
- File targetFile = null;
- if (item != null) {
- // We are over a particular item in the tree, use the item's file
- targetFile = (File) item.getData(TREEITEMDATA_FILE);
- }
- return targetFile;
- }
- });
- return dropTarget;
- }
-
- /**
- * Handles expand events on a tree item.
- *
- * @param item the TreeItem to fill in
- */
- private void treeExpandItem(TreeItem item) {
- shell.setCursor(iconCache.stockCursors[iconCache.cursorWait]);
- final Object stub = item.getData(TREEITEMDATA_STUB);
- if (stub == null) treeRefreshItem(item, true);
- shell.setCursor(iconCache.stockCursors[iconCache.cursorDefault]);
- }
-
- /**
- * Traverse the entire tree and update only what has changed.
- *
- * @param roots the root directory listing
- */
- private void treeRefresh(File[] masterFiles) {
- TreeItem[] items = tree.getItems();
- int masterIndex = 0;
- int itemIndex = 0;
- for (int i = 0; i < items.length; ++i) {
- final TreeItem item = items[i];
- final File itemFile = (File) item.getData(TREEITEMDATA_FILE);
- if ((itemFile == null) || (masterIndex == masterFiles.length)) {
- // remove bad item or placeholder
- item.dispose();
- continue;
- }
- final File masterFile = masterFiles[masterIndex];
- int compare = compareFiles(masterFile, itemFile);
- if (compare == 0) {
- // same file, update it
- treeRefreshItem(item, false);
- ++itemIndex;
- ++masterIndex;
- } else if (compare < 0) {
- // should appear before file, insert it
- TreeItem newItem = new TreeItem(tree, SWT.NULL, itemIndex);
- treeInitVolume(newItem, masterFile);
- new TreeItem(newItem, SWT.NULL); // placeholder child item to get "expand" button
- ++itemIndex;
- ++masterIndex;
- --i;
- } else {
- // should appear after file, delete stale item
- item.dispose();
- }
- }
- for (;masterIndex < masterFiles.length; ++masterIndex) {
- final File masterFile = masterFiles[masterIndex];
- TreeItem newItem = new TreeItem(tree, SWT.NULL);
- treeInitVolume(newItem, masterFile);
- new TreeItem(newItem, SWT.NULL); // placeholder child item to get "expand" button
- }
- }
-
- /**
- * Traverse an item in the tree and update only what has changed.
- *
- * @param dirItem the tree item of the directory
- * @param forcePopulate true iff we should populate non-expanded items as well
- */
- private void treeRefreshItem(TreeItem dirItem, boolean forcePopulate) {
- final File dir = (File) dirItem.getData(TREEITEMDATA_FILE);
-
- if (! forcePopulate && ! dirItem.getExpanded()) {
- // Refresh non-expanded item
- if (dirItem.getData(TREEITEMDATA_STUB) != null) {
- treeItemRemoveAll(dirItem);
- new TreeItem(dirItem, SWT.NULL); // placeholder child item to get "expand" button
- dirItem.setData(TREEITEMDATA_STUB, null);
- }
- return;
- }
- // Refresh expanded item
- dirItem.setData(TREEITEMDATA_STUB, this); // clear stub flag
-
- /* Get directory listing */
- File[] subFiles = (dir != null) ? FileViewer.getDirectoryList(dir) : null;
- if (subFiles == null || subFiles.length == 0) {
- /* Error or no contents */
- treeItemRemoveAll(dirItem);
- dirItem.setExpanded(false);
- return;
- }
-
- /* Refresh sub-items */
- TreeItem[] items = dirItem.getItems();
- final File[] masterFiles = subFiles;
- int masterIndex = 0;
- int itemIndex = 0;
- File masterFile = null;
- for (int i = 0; i < items.length; ++i) {
- while ((masterFile == null) && (masterIndex < masterFiles.length)) {
- masterFile = masterFiles[masterIndex++];
- if (! masterFile.isDirectory()) masterFile = null;
- }
-
- final TreeItem item = items[i];
- final File itemFile = (File) item.getData(TREEITEMDATA_FILE);
- if ((itemFile == null) || (masterFile == null)) {
- // remove bad item or placeholder
- item.dispose();
- continue;
- }
- int compare = compareFiles(masterFile, itemFile);
- if (compare == 0) {
- // same file, update it
- treeRefreshItem(item, false);
- masterFile = null;
- ++itemIndex;
- } else if (compare < 0) {
- // should appear before file, insert it
- TreeItem newItem = new TreeItem(dirItem, SWT.NULL, itemIndex);
- treeInitFolder(newItem, masterFile);
- new TreeItem(newItem, SWT.NULL); // add a placeholder child item so we get the "expand" button
- masterFile = null;
- ++itemIndex;
- --i;
- } else {
- // should appear after file, delete stale item
- item.dispose();
- }
- }
- while ((masterFile != null) || (masterIndex < masterFiles.length)) {
- if (masterFile != null) {
- TreeItem newItem = new TreeItem(dirItem, SWT.NULL);
- treeInitFolder(newItem, masterFile);
- new TreeItem(newItem, SWT.NULL); // add a placeholder child item so we get the "expand" button
- if (masterIndex == masterFiles.length) break;
- }
- masterFile = masterFiles[masterIndex++];
- if (! masterFile.isDirectory()) masterFile = null;
- }
- }
-
- /**
- * Foreign method: removes all children of a TreeItem.
- * @param treeItem the TreeItem
- */
- private static void treeItemRemoveAll(TreeItem treeItem) {
- final TreeItem[] children = treeItem.getItems();
- for (int i = 0; i < children.length; ++i) {
- children[i].dispose();
- }
- }
-
- /**
- * Initializes a folder item.
- *
- * @param item the TreeItem to initialize
- * @param folder the File associated with this TreeItem
- */
- private void treeInitFolder(TreeItem item, File folder) {
- item.setText(folder.getName());
- item.setImage(iconCache.stockImages[iconCache.iconClosedFolder]);
- item.setData(TREEITEMDATA_FILE, folder);
- item.setData(TREEITEMDATA_IMAGEEXPANDED, iconCache.stockImages[iconCache.iconOpenFolder]);
- item.setData(TREEITEMDATA_IMAGECOLLAPSED, iconCache.stockImages[iconCache.iconClosedFolder]);
- }
-
- /**
- * Initializes a volume item.
- *
- * @param item the TreeItem to initialize
- * @param volume the File associated with this TreeItem
- */
- private void treeInitVolume(TreeItem item, File volume) {
- item.setText(volume.getPath());
- item.setImage(iconCache.stockImages[iconCache.iconClosedDrive]);
- item.setData(TREEITEMDATA_FILE, volume);
- item.setData(TREEITEMDATA_IMAGEEXPANDED, iconCache.stockImages[iconCache.iconOpenDrive]);
- item.setData(TREEITEMDATA_IMAGECOLLAPSED, iconCache.stockImages[iconCache.iconClosedDrive]);
- }
-
- /**
- * Creates the file details table.
- *
- * @param parent the parent control
- */
- private void createTableView(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 1;
- gridLayout.marginHeight = gridLayout.marginWidth = 2;
- gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
- composite.setLayout(gridLayout);
- tableContentsOfLabel = new Label(composite, SWT.BORDER);
- tableContentsOfLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
-
- table = new Table(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
- table.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
-
- for (int i = 0; i < tableTitles.length; ++i) {
- TableColumn column = new TableColumn(table, SWT.NONE);
- column.setText(tableTitles[i]);
- column.setWidth(tableWidths[i]);
- }
- table.setHeaderVisible(true);
- table.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- notifySelectedFiles(getSelectedFiles());
- }
- public void widgetDefaultSelected(SelectionEvent event) {
- doDefaultFileAction(getSelectedFiles());
- }
- private File[] getSelectedFiles() {
- final TableItem[] items = table.getSelection();
- final File[] files = new File[items.length];
-
- for (int i = 0; i < items.length; ++i) {
- files[i] = (File) items[i].getData(TABLEITEMDATA_FILE);
- }
- return files;
- }
- });
-
- createTableDragSource(table);
- createTableDropTarget(table);
- }
-
- /**
- * Creates the Drag & Drop DragSource for items being dragged from the table.
- *
- * @return the DragSource for the table
- */
- private DragSource createTableDragSource(final Table table) {
- DragSource dragSource = new DragSource(table, DND.DROP_MOVE | DND.DROP_COPY);
- dragSource.setTransfer(new Transfer[] { FileTransfer.getInstance() });
- dragSource.addDragListener(new DragSourceListener() {
- TableItem[] dndSelection = null;
- String[] sourceNames = null;
- public void dragStart(DragSourceEvent event){
- dndSelection = table.getSelection();
- sourceNames = null;
- event.doit = dndSelection.length > 0;
- isDragging = true;
- }
- public void dragFinished(DragSourceEvent event){
- dragSourceHandleDragFinished(event, sourceNames);
- dndSelection = null;
- sourceNames = null;
- isDragging = false;
- handleDeferredRefresh();
- }
- public void dragSetData(DragSourceEvent event){
- if (dndSelection == null || dndSelection.length == 0) return;
- if (! FileTransfer.getInstance().isSupportedType(event.dataType)) return;
-
- sourceNames = new String[dndSelection.length];
- for (int i = 0; i < dndSelection.length; i++) {
- File file = (File) dndSelection[i].getData(TABLEITEMDATA_FILE);
- sourceNames[i] = file.getAbsolutePath();
- }
- event.data = sourceNames;
- }
- });
- return dragSource;
- }
-
- /**
- * Creates the Drag & Drop DropTarget for items being dropped onto the table.
- *
- * @return the DropTarget for the table
- */
- private DropTarget createTableDropTarget(final Table table){
- DropTarget dropTarget = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY);
- dropTarget.setTransfer(new Transfer[] { FileTransfer.getInstance() });
- dropTarget.addDropListener(new DropTargetAdapter() {
- public void dragEnter(DropTargetEvent event) {
- isDropping = true;
- }
- public void dragLeave(DropTargetEvent event) {
- isDropping = false;
- handleDeferredRefresh();
- }
- public void dragOver(DropTargetEvent event) {
- dropTargetValidate(event, getTargetFile(event));
- event.feedback |= DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
- }
- public void drop(DropTargetEvent event) {
- File targetFile = getTargetFile(event);
- if (dropTargetValidate(event, targetFile))
- dropTargetHandleDrop(event, targetFile);
- }
- private File getTargetFile(DropTargetEvent event) {
- // Determine the target File for the drop
- TableItem item = table.getItem(table.toControl(new Point(event.x, event.y)));
- File targetFile = null;
- if (item == null) {
- // We are over an unoccupied area of the table.
- // If it is a COPY, we can use the table's root file.
- if (event.detail == DND.DROP_COPY) {
- targetFile = (File) table.getData(TABLEDATA_DIR);
- }
- } else {
- // We are over a particular item in the table, use the item's file
- targetFile = (File) item.getData(TABLEITEMDATA_FILE);
- }
- return targetFile;
- }
- });
- return dropTarget;
- }
-
- /**
- * Notifies the application components that a new current directory has been selected
- *
- * @param dir the directory that was selected, null is ignored
- */
- void notifySelectedDirectory(File dir) {
- if (dir == null) return;
- if (currentDirectory != null && dir.equals(currentDirectory)) return;
- currentDirectory = dir;
- notifySelectedFiles(null);
-
- /* Shell:
- * Sets the title to indicate the selected directory
- */
- shell.setText(getResourceString("Title", new Object[] { currentDirectory.getPath() }));
- /* Table view:
- * Displays the contents of the selected directory.
- */
- workerUpdate(dir, false);
-
- /* Combo view:
- * Sets the combo box to point to the selected directory.
- */
- final File[] comboRoots = (File[]) combo.getData(COMBODATA_ROOTS);
- int comboEntry = -1;
- if (comboRoots != null) {
- for (int i = 0; i < comboRoots.length; ++i) {
- if (dir.equals(comboRoots[i])) {
- comboEntry = i;
- break;
- }
- }
- }
- if (comboEntry == -1) combo.setText(dir.getPath());
- else combo.select(comboEntry);
-
- /* Tree view:
- * If not already expanded, recursively expands the parents of the specified
- * directory until it is visible.
- */
- Vector /* of File */ path = new Vector();
- // Build a stack of paths from the root of the tree
- while (dir != null) {
- path.add(dir);
- dir = dir.getParentFile();
- }
- // Recursively expand the tree to get to the specified directory
- TreeItem[] items = tree.getItems();
- TreeItem lastItem = null;
- for (int i = path.size() - 1; i >= 0; --i) {
- final File pathElement = (File) path.elementAt(i);
-
- // Search for a particular File in the array of tree items
- // No guarantee that the items are sorted in any recognizable fashion, so we'll
- // just sequential scan. There shouldn't be more than a few thousand entries.
- TreeItem item = null;
- for (int k = 0; k < items.length; ++k) {
- item = items[k];
- if (item.isDisposed()) continue;
- final File itemFile = (File) item.getData(TREEITEMDATA_FILE);
- if (itemFile != null && itemFile.equals(pathElement)) break;
- }
- if (item == null) break;
- lastItem = item;
- if (i != 0 && !item.getExpanded()) {
- treeExpandItem(item);
- item.setExpanded(true);
- }
- items = item.getItems();
- }
- tree.setSelection((lastItem != null) ? new TreeItem[] { lastItem } : new TreeItem[0]);
- }
-
- /**
- * Notifies the application components that files have been selected
- *
- * @param files the files that were selected, null or empty array indicates no active selection
- */
- void notifySelectedFiles(File[] files) {
- /* Details:
- * Update the details that are visible on screen.
- */
- if ((files != null) && (files.length != 0)) {
- numObjectsLabel.setText(getResourceString("details.NumberOfSelectedFiles.text",
- new Object[] { new Integer(files.length) }));
- long fileSize = 0L;
- for (int i = 0; i < files.length; ++i) {
- fileSize += files[i].length();
- }
- diskSpaceLabel.setText(getResourceString("details.FileSize.text",
- new Object[] { new Long(fileSize) }));
- } else {
- // No files selected
- diskSpaceLabel.setText("");
- if (currentDirectory != null) {
- int numObjects = getDirectoryList(currentDirectory).length;
- numObjectsLabel.setText(getResourceString("details.DirNumberOfObjects.text",
- new Object[] { new Integer(numObjects) }));
- } else {
- numObjectsLabel.setText("");
- }
- }
- }
-
- /**
- * Notifies the application components that files must be refreshed
- *
- * @param files the files that need refreshing, empty array is a no-op, null refreshes all
- */
- void notifyRefreshFiles(File[] files) {
- if (files != null && files.length == 0) return;
-
- if ((deferredRefreshRequested) && (deferredRefreshFiles != null) && (files != null)) {
- // merge requests
- File[] newRequest = new File[deferredRefreshFiles.length + files.length];
- System.arraycopy(deferredRefreshFiles, 0, newRequest, 0, deferredRefreshFiles.length);
- System.arraycopy(files, 0, newRequest, deferredRefreshFiles.length, files.length);
- deferredRefreshFiles = newRequest;
- } else {
- deferredRefreshFiles = files;
- deferredRefreshRequested = true;
- }
- handleDeferredRefresh();
- }
-
- /**
- * Handles deferred Refresh notifications (due to Drag & Drop)
- */
- void handleDeferredRefresh() {
- if (isDragging || isDropping || ! deferredRefreshRequested) return;
- if (progressDialog != null) {
- progressDialog.close();
- progressDialog = null;
- }
-
- deferredRefreshRequested = false;
- File[] files = deferredRefreshFiles;
- deferredRefreshFiles = null;
-
- shell.setCursor(iconCache.stockCursors[iconCache.cursorWait]);
-
- /* Table view:
- * Refreshes information about any files in the list and their children.
- */
- boolean refreshTable = false;
- if (files != null) {
- for (int i = 0; i < files.length; ++i) {
- final File file = files[i];
- if (file.equals(currentDirectory)) {
- refreshTable = true;
- break;
- }
- File parentFile = file.getParentFile();
- if ((parentFile != null) && (parentFile.equals(currentDirectory))) {
- refreshTable = true;
- break;
- }
- }
- } else refreshTable = true;
- if (refreshTable) workerUpdate(currentDirectory, true);
-
- /* Combo view:
- * Refreshes the list of roots
- */
- final File[] roots = getRoots();
-
- if (files == null) {
- boolean refreshCombo = false;
- final File[] comboRoots = (File[]) combo.getData(COMBODATA_ROOTS);
-
- if ((comboRoots != null) && (comboRoots.length == roots.length)) {
- for (int i = 0; i < roots.length; ++i) {
- if (! roots[i].equals(comboRoots[i])) {
- refreshCombo = true;
- break;
- }
- }
- } else refreshCombo = true;
-
- if (refreshCombo) {
- combo.removeAll();
- combo.setData(COMBODATA_ROOTS, roots);
- for (int i = 0; i < roots.length; ++i) {
- final File file = roots[i];
- combo.add(file.getPath());
- }
- }
- }
-
- /* Tree view:
- * Refreshes information about any files in the list and their children.
- */
- treeRefresh(roots);
-
- // Remind everyone where we are in the filesystem
- final File dir = currentDirectory;
- currentDirectory = null;
- notifySelectedDirectory(dir);
-
- shell.setCursor(iconCache.stockCursors[iconCache.cursorDefault]);
- }
-
- /**
- * Performs the default action on a set of files.
- *
- * @param files the array of files to process
- */
- void doDefaultFileAction(File[] files) {
- // only uses the 1st file (for now)
- if (files.length == 0) return;
- final File file = files[0];
-
- if (file.isDirectory()) {
- notifySelectedDirectory(file);
- } else {
- final String fileName = file.getAbsolutePath();
- if (! Program.launch(fileName)) {
- MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
- dialog.setMessage(getResourceString("error.FailedLaunch.message", new Object[] { fileName }));
- dialog.setText(shell.getText ());
- dialog.open();
- }
- }
- }
-
- /**
- * Navigates to the parent directory
- */
- void doParent() {
- if (currentDirectory == null) return;
- File parentDirectory = currentDirectory.getParentFile();
- notifySelectedDirectory(parentDirectory);
- }
-
- /**
- * Performs a refresh
- */
- void doRefresh() {
- notifyRefreshFiles(null);
- }
-
- /**
- * Validates a drop target as a candidate for a drop operation.
- * <p>
- * Used in dragOver() and dropAccept().<br>
- * Note event.detail is set to DND.DROP_NONE by this method if the target is not valid.
- * </p>
- * @param event the DropTargetEvent to validate
- * @param targetFile the File representing the drop target location
- * under inspection, or null if none
- */
- private boolean dropTargetValidate(DropTargetEvent event, File targetFile) {
- if (targetFile != null && targetFile.isDirectory()) {
- if (event.detail != DND.DROP_COPY && event.detail != DND.DROP_MOVE) {
- event.detail = DND.DROP_MOVE;
- }
- } else {
- event.detail = DND.DROP_NONE;
- }
- return event.detail != DND.DROP_NONE;
- }
-
- /**
- * Handles a drop on a dropTarget.
- * <p>
- * Used in drop().<br>
- * Note event.detail is modified by this method.
- * </p>
- * @param event the DropTargetEvent passed as parameter to the drop() method
- * @param targetFile the File representing the drop target location
- * under inspection, or null if none
- */
- private void dropTargetHandleDrop(DropTargetEvent event, File targetFile) {
- // Get dropped data (an array of filenames)
- if (! dropTargetValidate(event, targetFile)) return;
- final String[] sourceNames = (String[]) event.data;
- if (sourceNames == null) event.detail = DND.DROP_NONE;
- if (event.detail == DND.DROP_NONE) return;
-
- // Open progress dialog
- progressDialog = new ProgressDialog(shell,
- (event.detail == DND.DROP_MOVE) ? ProgressDialog.MOVE : ProgressDialog.COPY);
- progressDialog.setTotalWorkUnits(sourceNames.length);
- progressDialog.open();
-
- // Copy each file
- Vector /* of File */ processedFiles = new Vector();
- for (int i = 0; (i < sourceNames.length) && (! progressDialog.isCancelled()); i++){
- final File source = new File(sourceNames[i]);
- final File dest = new File(targetFile, source.getName());
- if (source.equals(dest)) continue; // ignore if in same location
-
- progressDialog.setDetailFile(source, ProgressDialog.COPY);
- while (! progressDialog.isCancelled()) {
- if (copyFileStructure(source, dest)) {
- processedFiles.add(source);
- break;
- } else if (! progressDialog.isCancelled()) {
- if (event.detail == DND.DROP_MOVE && (!isDragging)) {
- // It is not possible to notify an external drag source that a drop
- // operation was only partially successful. This is particularly a
- // problem for DROP_MOVE operations since unless the source gets
- // DROP_NONE, it will delete the original data including bits that
- // may not have been transferred successfully.
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
- box.setText(getResourceString("dialog.FailedCopy.title"));
- box.setMessage(getResourceString("dialog.FailedCopy.description",
- new Object[] { source, dest }));
- int button = box.open();
- if (button == SWT.CANCEL) {
- i = sourceNames.length;
- event.detail = DND.DROP_NONE;
- break;
- }
- } else {
- // We can recover gracefully from errors if the drag source belongs
- // to this application since it will look at processedDropFiles.
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.ABORT | SWT.RETRY | SWT.IGNORE);
- box.setText(getResourceString("dialog.FailedCopy.title"));
- box.setMessage(getResourceString("dialog.FailedCopy.description",
- new Object[] { source, dest }));
- int button = box.open();
- if (button == SWT.ABORT) i = sourceNames.length;
- if (button != SWT.RETRY) break;
- }
- }
- progressDialog.addProgress(1);
- }
- }
- if (isDragging) {
- // Remember exactly which files we processed
- processedDropFiles = ((File[]) processedFiles.toArray(new File[processedFiles.size()]));
- } else {
- progressDialog.close();
- progressDialog = null;
- }
- notifyRefreshFiles(new File[] { targetFile });
- }
-
- /**
- * Handles the completion of a drag on a dragSource.
- * <p>
- * Used in dragFinished().<br>
- * </p>
- * @param event the DragSourceEvent passed as parameter to the dragFinished() method
- * @param sourceNames the names of the files that were dragged (event.data is invalid)
- */
- private void dragSourceHandleDragFinished(DragSourceEvent event, String[] sourceNames) {
- if (sourceNames == null) return;
- if (event.detail != DND.DROP_MOVE) return;
-
- // Get array of files that were actually transferred
- final File[] sourceFiles;
- if (processedDropFiles != null) {
- sourceFiles = processedDropFiles;
- } else {
- sourceFiles = new File[sourceNames.length];
- for (int i = 0; i < sourceNames.length; ++i)
- sourceFiles[i] = new File(sourceNames[i]);
- }
- if (progressDialog == null)
- progressDialog = new ProgressDialog(shell, ProgressDialog.MOVE);
- progressDialog.setTotalWorkUnits(sourceFiles.length);
- progressDialog.setProgress(0);
- progressDialog.open();
-
- // Delete each file
- for (int i = 0; (i < sourceFiles.length) && (! progressDialog.isCancelled()); i++){
- final File source = sourceFiles[i];
- progressDialog.setDetailFile(source, ProgressDialog.DELETE);
- while (! progressDialog.isCancelled()) {
- if (deleteFileStructure(source)) {
- break;
- } else if (! progressDialog.isCancelled()) {
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.ABORT | SWT.RETRY | SWT.IGNORE);
- box.setText(getResourceString("dialog.FailedDelete.title"));
- box.setMessage(getResourceString("dialog.FailedDelete.description",
- new Object[] { source }));
- int button = box.open();
- if (button == SWT.ABORT) i = sourceNames.length;
- if (button == SWT.RETRY) break;
- }
- }
- progressDialog.addProgress(1);
- }
- notifyRefreshFiles(sourceFiles);
- progressDialog.close();
- progressDialog = null;
- }
-
- /**
- * Gets filesystem root entries
- *
- * @return an array of Files corresponding to the root directories on the platform,
- * may be empty but not null
- */
- File[] getRoots() {
- /*
- * On JDK 1.22 only...
- */
- // return File.listRoots();
-
- /*
- * On JDK 1.1.7 and beyond...
- * -- PORTABILITY ISSUES HERE --
- */
- if (System.getProperty ("os.name").indexOf ("Windows") != -1) {
- Vector /* of File */ list = new Vector();
- list.add(new File(DRIVE_A));
- list.add(new File(DRIVE_B));
- for (char i = 'c'; i <= 'z'; ++i) {
- File drive = new File(i + ":" + File.separator);
- if (drive.isDirectory() && drive.exists()) {
- list.add(drive);
- if (initial && i == 'c') {
- currentDirectory = drive;
- initial = false;
- }
- }
- }
- File[] roots = (File[]) list.toArray(new File[list.size()]);
- sortFiles(roots);
- return roots;
- } else {
- File root = new File(File.separator);
- if (initial) {
- currentDirectory = root;
- }
- return new File[] { root };
- }
- }
-
- /**
- * Gets a directory listing
- *
- * @param file the directory to be listed
- * @return an array of files this directory contains, may be empty but not null
- */
- static File[] getDirectoryList(File file) {
- File[] list = file.listFiles();
- if (list == null) return new File[0];
- sortFiles(list);
- return list;
- }
-
- /**
- * Copies a file or entire directory structure.
- *
- * @param oldFile the location of the old file or directory
- * @param newFile the location of the new file or directory
- * @return true iff the operation succeeds without errors
- */
- boolean copyFileStructure(File oldFile, File newFile) {
- if (oldFile == null || newFile == null) return false;
-
- // ensure that newFile is not a child of oldFile or a dupe
- File searchFile = newFile;
- do {
- if (oldFile.equals(searchFile)) return false;
- searchFile = searchFile.getParentFile();
- } while (searchFile != null);
-
- if (oldFile.isDirectory()) {
- /*
- * Copy a directory
- */
- if (progressDialog != null) {
- progressDialog.setDetailFile(oldFile, ProgressDialog.COPY);
- }
- if (simulateOnly) {
- //System.out.println(getResourceString("simulate.DirectoriesCreated.text",
- // new Object[] { newFile.getPath() }));
- } else {
- if (! newFile.mkdirs()) return false;
- }
- File[] subFiles = oldFile.listFiles();
- if (subFiles != null) {
- if (progressDialog != null) {
- progressDialog.addWorkUnits(subFiles.length);
- }
- for (int i = 0; i < subFiles.length; i++) {
- File oldSubFile = subFiles[i];
- File newSubFile = new File(newFile, oldSubFile.getName());
- if (! copyFileStructure(oldSubFile, newSubFile)) return false;
- if (progressDialog != null) {
- progressDialog.addProgress(1);
- if (progressDialog.isCancelled()) return false;
- }
- }
- }
- } else {
- /*
- * Copy a file
- */
- if (simulateOnly) {
- //System.out.println(getResourceString("simulate.CopyFromTo.text",
- // new Object[] { oldFile.getPath(), newFile.getPath() }));
- } else {
- FileReader in = null;
- FileWriter out = null;
- try {
- in = new FileReader(oldFile);
- out = new FileWriter(newFile);
-
- int count;
- while ((count = in.read()) != -1) out.write(count);
- } catch (FileNotFoundException e) {
- return false;
- } catch (IOException e) {
- return false;
- } finally {
- try {
- if (in != null) in.close();
- if (out != null) out.close();
- } catch (IOException e) {
- return false;
- }
- }
- }
- }
- return true;
- }
-
- /**
- * Deletes a file or entire directory structure.
- *
- * @param oldFile the location of the old file or directory
- * @return true iff the operation succeeds without errors
- */
- boolean deleteFileStructure(File oldFile) {
- if (oldFile == null) return false;
- if (oldFile.isDirectory()) {
- /*
- * Delete a directory
- */
- if (progressDialog != null) {
- progressDialog.setDetailFile(oldFile, ProgressDialog.DELETE);
- }
- File[] subFiles = oldFile.listFiles();
- if (subFiles != null) {
- if (progressDialog != null) {
- progressDialog.addWorkUnits(subFiles.length);
- }
- for (int i = 0; i < subFiles.length; i++) {
- File oldSubFile = subFiles[i];
- if (! deleteFileStructure(oldSubFile)) return false;
- if (progressDialog != null) {
- progressDialog.addProgress(1);
- if (progressDialog.isCancelled()) return false;
- }
- }
- }
- }
- if (simulateOnly) {
- //System.out.println(getResourceString("simulate.Delete.text",
- // new Object[] { oldFile.getPath(), oldFile.getPath() }));
- return true;
- } else {
- return oldFile.delete();
- }
- }
-
- /**
- * Sorts files lexicographically by name.
- *
- * @param files the array of Files to be sorted
- */
- static void sortFiles(File[] files) {
- /* Very lazy merge sort algorithm */
- sortBlock(files, 0, files.length - 1, new File[files.length]);
- }
- private static void sortBlock(File[] files, int start, int end, File[] mergeTemp) {
- final int length = end - start + 1;
- if (length < 8) {
- for (int i = end; i > start; --i) {
- for (int j = end; j > start; --j) {
- if (compareFiles(files[j - 1], files[j]) > 0) {
- final File temp = files[j];
- files[j] = files[j-1];
- files[j-1] = temp;
- }
- }
- }
- return;
- }
- final int mid = (start + end) / 2;
- sortBlock(files, start, mid, mergeTemp);
- sortBlock(files, mid + 1, end, mergeTemp);
- int x = start;
- int y = mid + 1;
- for (int i = 0; i < length; ++i) {
- if ((x > mid) || ((y <= end) && compareFiles(files[x], files[y]) > 0)) {
- mergeTemp[i] = files[y++];
- } else {
- mergeTemp[i] = files[x++];
- }
- }
- for (int i = 0; i < length; ++i) files[i + start] = mergeTemp[i];
- }
- private static int compareFiles(File a, File b) {
-// boolean aIsDir = a.isDirectory();
-// boolean bIsDir = b.isDirectory();
-// if (aIsDir && ! bIsDir) return -1;
-// if (bIsDir && ! aIsDir) return 1;
-
- // sort case-sensitive files in a case-insensitive manner
- int compare = a.getName().compareToIgnoreCase(b.getName());
- if (compare == 0) compare = a.getName().compareTo(b.getName());
- return compare;
- }
-
- /*
- * This worker updates the table with file information in the background.
- * <p>
- * Implementation notes:
- * <ul>
- * <li> It is designed such that it can be interrupted cleanly.
- * <li> It uses asyncExec() in some places to ensure that SWT Widgets are manipulated in the
- * right thread. Exclusive use of syncExec() would be inappropriate as it would require a pair
- * of context switches between each table update operation.
- * </ul>
- * </p>
- */
-
- /**
- * Stops the worker and waits for it to terminate.
- */
- void workerStop() {
- if (workerThread == null) return;
- synchronized(workerLock) {
- workerCancelled = true;
- workerStopped = true;
- workerLock.notifyAll();
- }
- while (workerThread != null) {
- if (! display.readAndDispatch()) display.sleep();
- }
- }
-
- /**
- * Notifies the worker that it should update itself with new data.
- * Cancels any previous operation and begins a new one.
- *
- * @param dir the new base directory for the table, null is ignored
- * @param force if true causes a refresh even if the data is the same
- */
- void workerUpdate(File dir, boolean force) {
- if (dir == null) return;
- if ((!force) && (workerNextDir != null) && (workerNextDir.equals(dir))) return;
-
- synchronized(workerLock) {
- workerNextDir = dir;
- workerStopped = false;
- workerCancelled = true;
- workerLock.notifyAll();
- }
- if (workerThread == null) {
- workerThread = new Thread(workerRunnable);
- workerThread.start();
- }
- }
-
- /**
- * Manages the worker's thread
- */
- private final Runnable workerRunnable = new Runnable() {
- public void run() {
- while (! workerStopped) {
- synchronized(workerLock) {
- workerCancelled = false;
- workerStateDir = workerNextDir;
- }
- workerExecute();
- synchronized(workerLock) {
- try {
- if ((!workerCancelled) && (workerStateDir == workerNextDir)) workerLock.wait();
- } catch (InterruptedException e) {
- }
- }
- }
- workerThread = null;
- // wake up UI thread in case it is in a modal loop awaiting thread termination
- // (see workerStop())
- display.wake();
- }
- };
-
- /**
- * Updates the table's contents
- */
- private void workerExecute() {
- File[] dirList;
- // Clear existing information
- display.syncExec(new Runnable() {
- public void run() {
- tableContentsOfLabel.setText(FileViewer.getResourceString("details.ContentsOf.text",
- new Object[] { workerStateDir.getPath() }));
- table.removeAll();
- table.setData(TABLEDATA_DIR, workerStateDir);
- }
- });
- dirList = getDirectoryList(workerStateDir);
-
- for (int i = 0; (! workerCancelled) && (i < dirList.length); i++) {
- workerAddFileDetails(dirList[i]);
- }
-
- }
-
- /**
- * Adds a file's detail information to the directory list
- */
- private void workerAddFileDetails(final File file) {
- final String nameString = file.getName();
- final String dateString = dateFormat.format(new Date(file.lastModified()));
- final String sizeString;
- final String typeString;
- final Image iconImage;
-
- if (file.isDirectory()) {
- typeString = getResourceString("filetype.Folder");
- sizeString = "";
- iconImage = iconCache.stockImages[iconCache.iconClosedFolder];
- } else {
- sizeString = getResourceString("filesize.KB",
- new Object[] { new Long((file.length() + 512) / 1024) });
-
- int dot = nameString.lastIndexOf('.');
- if (dot != -1) {
- String extension = nameString.substring(dot);
- Program program = Program.findProgram(extension);
- if (program != null) {
- typeString = program.getName();
- iconImage = iconCache.getIconFromProgram(program);
- } else {
- typeString = getResourceString("filetype.Unknown", new Object[] { extension.toUpperCase() });
- iconImage = iconCache.stockImages[iconCache.iconFile];
- }
- } else {
- typeString = getResourceString("filetype.None");
- iconImage = iconCache.stockImages[iconCache.iconFile];
- }
- }
- final String[] strings = new String[] { nameString, sizeString, typeString, dateString };
-
- display.syncExec(new Runnable() {
- public void run () {
- // guard against the shell being closed before this runs
- if (shell.isDisposed()) return;
- TableItem tableItem = new TableItem(table, 0);
- tableItem.setText(strings);
- tableItem.setImage(iconImage);
- tableItem.setData(TABLEITEMDATA_FILE, file);
- }
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.custom.*;
+import org.eclipse.swt.dnd.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.program.*;
+import org.eclipse.swt.widgets.*;
+
+import java.io.*;
+import java.text.*;
+import java.util.*;
+ /**
+ * File Viewer example
+ */
+public class FileViewer {
+ private static ResourceBundle resourceBundle = ResourceBundle.getBundle("examples_fileviewer");
+ private final static String DRIVE_A = "a:" + File.separator;
+ private final static String DRIVE_B = "b:" + File.separator;
+
+ /* UI elements */
+ private Display display;
+ private Shell shell;
+ private ToolBar toolBar;
+
+ private Label numObjectsLabel;
+ private Label diskSpaceLabel;
+
+ private File currentDirectory = null;
+ private boolean initial = true;
+
+ /* Drag and drop optimizations */
+ private boolean isDragging = false; // if this app is dragging
+ private boolean isDropping = false; // if this app is dropping
+
+ private File[] processedDropFiles = null; // so Drag only deletes what it needs to
+ private File[] deferredRefreshFiles = null; // to defer notifyRefreshFiles while we do DND
+ private boolean deferredRefreshRequested = false; // to defer notifyRefreshFiles while we do DND
+ private ProgressDialog progressDialog = null; // progress dialog for locally-initiated operations
+
+ /* Combo view */
+ private static final String COMBODATA_ROOTS = "Combo.roots";
+ // File[]: Array of files whose paths are currently displayed in the combo
+ private static final String COMBODATA_LASTTEXT = "Combo.lastText";
+ // String: Previous selection text string
+
+ private Combo combo;
+
+ /* Tree view */
+ private IconCache iconCache = new IconCache();
+ private static final String TREEITEMDATA_FILE = "TreeItem.file";
+ // File: File associated with tree item
+ private static final String TREEITEMDATA_IMAGEEXPANDED = "TreeItem.imageExpanded";
+ // Image: shown when item is expanded
+ private static final String TREEITEMDATA_IMAGECOLLAPSED = "TreeItem.imageCollapsed";
+ // Image: shown when item is collapsed
+ private static final String TREEITEMDATA_STUB = "TreeItem.stub";
+ // Object: if not present or null then the item has not been populated
+
+ private Tree tree;
+ private Label treeScopeLabel;
+
+ /* Table view */
+ private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(
+ DateFormat.MEDIUM, DateFormat.MEDIUM);
+ private static final String TABLEITEMDATA_FILE = "TableItem.file";
+ // File: File associated with table row
+ private static final String TABLEDATA_DIR = "Table.dir";
+ // File: Currently visible directory
+ private static final int[] tableWidths = new int[] {150, 60, 75, 150};
+ private final String[] tableTitles = new String [] {
+ FileViewer.getResourceString("table.Name.title"),
+ FileViewer.getResourceString("table.Size.title"),
+ FileViewer.getResourceString("table.Type.title"),
+ FileViewer.getResourceString("table.Modified.title")
+ };
+ private Table table;
+ private Label tableContentsOfLabel;
+
+ /* Table update worker */
+ // Control data
+ private final Object workerLock = new Object();
+ // Lock for all worker control data and state
+ private volatile Thread workerThread = null;
+ // The worker's thread
+ private volatile boolean workerStopped = false;
+ // True if the worker must exit on completion of the current cycle
+ private volatile boolean workerCancelled = false;
+ // True if the worker must cancel its operations prematurely perhaps due to a state update
+
+ // Worker state information -- this is what gets synchronized by an update
+ private volatile File workerStateDir = null;
+
+ // State information to use for the next cycle
+ private volatile File workerNextDir = null;
+
+ /* Simulate only flag */
+ // when true, disables actual filesystem manipulations and outputs results to standard out
+ private boolean simulateOnly = true;
+
+ /**
+ * Runs main program.
+ */
+ public static void main (String [] args) {
+ Display display = new Display ();
+ FileViewer application = new FileViewer();
+ Shell shell = application.open(display);
+ while (! shell.isDisposed()) {
+ if (! display.readAndDispatch()) display.sleep();
+ }
+ application.close();
+ display.dispose();
+ }
+
+ /**
+ * Opens the main program.
+ */
+ public Shell open(Display display) {
+ // Create the window
+ this.display = display;
+ iconCache.initResources(display);
+ shell = new Shell();
+ createShellContents();
+ notifyRefreshFiles(null);
+ shell.open();
+ return shell;
+ }
+ /**
+ * Closes the main program.
+ */
+ void close() {
+ workerStop();
+ iconCache.freeResources();
+ }
+
+ /**
+ * Returns a string from the resource bundle.
+ * We don't want to crash because of a missing String.
+ * Returns the key if not found.
+ */
+ static String getResourceString(String key) {
+ try {
+ return resourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Returns a string from the resource bundle and binds it
+ * with the given arguments. If the key is not found,
+ * return the key.
+ */
+ static String getResourceString(String key, Object[] args) {
+ try {
+ return MessageFormat.format(getResourceString(key), args);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Construct the UI
+ *
+ * @param container the ShellContainer managing the Shell we are rendering inside
+ */
+ private void createShellContents() {
+ shell.setText(getResourceString("Title", new Object[] { "" }));
+ shell.setImage(iconCache.stockImages[iconCache.shellIcon]);
+ Menu bar = new Menu(shell, SWT.BAR);
+ shell.setMenuBar(bar);
+ createFileMenu(bar);
+ createHelpMenu(bar);
+
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 3;
+ gridLayout.marginHeight = gridLayout.marginWidth = 0;
+ shell.setLayout(gridLayout);
+
+ GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
+ gridData.widthHint = 185;
+ createComboView(shell, gridData);
+ gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
+ gridData.horizontalSpan = 2;
+ createToolBar(shell, gridData);
+
+ SashForm sashForm = new SashForm(shell, SWT.NONE);
+ sashForm.setOrientation(SWT.HORIZONTAL);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
+ gridData.horizontalSpan = 3;
+ sashForm.setLayoutData(gridData);
+ createTreeView(sashForm);
+ createTableView(sashForm);
+ sashForm.setWeights(new int[] { 2, 5 });
+
+ numObjectsLabel = new Label(shell, SWT.BORDER);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
+ gridData.widthHint = 185;
+ numObjectsLabel.setLayoutData(gridData);
+
+ diskSpaceLabel = new Label(shell, SWT.BORDER);
+ gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
+ gridData.horizontalSpan = 2;
+ diskSpaceLabel.setLayoutData(gridData);
+ }
+
+ /**
+ * Creates the File Menu.
+ *
+ * @param parent the parent menu
+ */
+ private void createFileMenu(Menu parent) {
+ Menu menu = new Menu(parent);
+ MenuItem header = new MenuItem(parent, SWT.CASCADE);
+ header.setText(getResourceString("menu.File.text"));
+ header.setMenu(menu);
+
+ final MenuItem simulateItem = new MenuItem(menu, SWT.CHECK);
+ simulateItem.setText(getResourceString("menu.File.SimulateOnly.text"));
+ simulateItem.setSelection(simulateOnly);
+ simulateItem.addSelectionListener(new SelectionAdapter () {
+ public void widgetSelected(SelectionEvent e) {
+ simulateOnly = simulateItem.getSelection();
+ }
+ });
+
+ MenuItem item = new MenuItem(menu, SWT.PUSH);
+ item.setText(getResourceString("menu.File.Close.text"));
+ item.addSelectionListener(new SelectionAdapter () {
+ public void widgetSelected(SelectionEvent e) {
+ shell.close();
+ }
+ });
+ }
+
+ /**
+ * Creates the Help Menu.
+ *
+ * @param parent the parent menu
+ */
+ private void createHelpMenu(Menu parent) {
+ Menu menu = new Menu(parent);
+ MenuItem header = new MenuItem(parent, SWT.CASCADE);
+ header.setText(getResourceString("menu.Help.text"));
+ header.setMenu(menu);
+
+ MenuItem item = new MenuItem(menu, SWT.PUSH);
+ item.setText(getResourceString("menu.Help.About.text"));
+ item.addSelectionListener(new SelectionAdapter () {
+ public void widgetSelected(SelectionEvent e) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
+ box.setText(getResourceString("dialog.About.title"));
+ box.setMessage(getResourceString("dialog.About.description",
+ new Object[] { System.getProperty("os.name") }));
+ box.open();
+ }
+ });
+ }
+
+ /**
+ * Creates the toolbar
+ *
+ * @param shell the shell on which to attach the toolbar
+ * @param layoutData the layout data
+ */
+ private void createToolBar(final Shell shell, Object layoutData) {
+ toolBar = new ToolBar(shell, SWT.NULL);
+ toolBar.setLayoutData(layoutData);
+ ToolItem item = new ToolItem(toolBar, SWT.SEPARATOR);
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdParent]);
+ item.setToolTipText(getResourceString("tool.Parent.tiptext"));
+ item.addSelectionListener(new SelectionAdapter () {
+ public void widgetSelected(SelectionEvent e) {
+ doParent();
+ }
+ });
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdRefresh]);
+ item.setToolTipText(getResourceString("tool.Refresh.tiptext"));
+ item.addSelectionListener(new SelectionAdapter () {
+ public void widgetSelected(SelectionEvent e) {
+ doRefresh();
+ }
});
- }
-
- /**
- * Instances of this class manage a progress dialog for file operations.
- */
- class ProgressDialog {
- public final static int COPY = 0;
- public final static int DELETE = 1;
- public final static int MOVE = 2;
-
- Shell shell;
- Label messageLabel, detailLabel;
- ProgressBar progressBar;
- Button cancelButton;
- boolean isCancelled = false;
-
- final String operationKeyName[] = {
- "Copy",
- "Delete",
- "Move"
- };
-
- /**
- * Creates a progress dialog but does not open it immediately.
- *
- * @param parent the parent Shell
- * @param style one of COPY, MOVE
- */
- public ProgressDialog(Shell parent, int style) {
- shell = new Shell(parent, SWT.BORDER | SWT.TITLE | SWT.APPLICATION_MODAL);
- GridLayout gridLayout = new GridLayout();
- shell.setLayout(gridLayout);
- shell.setText(getResourceString("progressDialog." + operationKeyName[style] + ".title"));
- shell.addShellListener(new ShellAdapter() {
- public void shellClosed(ShellEvent e) {
- isCancelled = true;
- }
- });
-
- messageLabel = new Label(shell, SWT.HORIZONTAL);
- messageLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
- messageLabel.setText(getResourceString("progressDialog." + operationKeyName[style] + ".description"));
-
- progressBar = new ProgressBar(shell, SWT.HORIZONTAL | SWT.WRAP);
- progressBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
- progressBar.setMinimum(0);
- progressBar.setMaximum(0);
-
- detailLabel = new Label(shell, SWT.HORIZONTAL);
- GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
- gridData.widthHint = 400;
- detailLabel.setLayoutData(gridData);
-
- cancelButton = new Button(shell, SWT.PUSH);
- cancelButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_FILL));
- cancelButton.setText(getResourceString("progressDialog.cancelButton.text"));
- cancelButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- isCancelled = true;
- cancelButton.setEnabled(false);
- }
- });
- }
- /**
- * Sets the detail text to show the filename along with a string
- * representing the operation being performed on that file.
- *
- * @param file the file to be detailed
- * @param operation one of COPY, DELETE
- */
- public void setDetailFile(File file, int operation) {
- detailLabel.setText(getResourceString("progressDialog." + operationKeyName[operation] + ".operation",
- new Object[] { file }));
- }
- /**
- * Returns true if the Cancel button was been clicked.
- *
- * @return true if the Cancel button was clicked.
- */
- public boolean isCancelled() {
- return isCancelled;
- }
- /**
- * Sets the total number of work units to be performed.
- *
- * @param work the total number of work units
- */
- public void setTotalWorkUnits(int work) {
- progressBar.setMaximum(work);
- }
- /**
- * Adds to the total number of work units to be performed.
- *
- * @param work the number of work units to add
- */
- public void addWorkUnits(int work) {
- setTotalWorkUnits(progressBar.getMaximum() + work);
- }
- /**
- * Sets the progress of completion of the total work units.
- *
- * @param work the total number of work units completed
- */
- public void setProgress(int work) {
- progressBar.setSelection(work);
- while (display.readAndDispatch()); // enable event processing
- }
- /**
- * Adds to the progress of completion of the total work units.
- *
- * @param work the number of work units completed to add
- */
- public void addProgress(int work) {
- setProgress(progressBar.getSelection() + work);
- }
- /**
- * Opens the dialog.
- */
- public void open() {
- shell.pack();
- final Shell parentShell = (Shell) shell.getParent();
- Rectangle rect = parentShell.getBounds();
- Rectangle bounds = shell.getBounds();
- bounds.x = rect.x + (rect.width - bounds.width) / 2;
- bounds.y = rect.y + (rect.height - bounds.height) / 2;
- shell.setBounds(bounds);
- shell.open();
- }
- /**
- * Closes the dialog and disposes its resources.
- */
- public void close() {
- shell.close();
- shell.dispose();
- shell = null;
- messageLabel = null;
- detailLabel = null;
- progressBar = null;
- cancelButton = null;
- }
- }
-}
+ SelectionAdapter unimplementedListener = new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
+ box.setText(getResourceString("dialog.NotImplemented.title"));
+ box.setMessage(getResourceString("dialog.ActionNotImplemented.description"));
+ box.open();
+ }
+ };
+
+ item = new ToolItem(toolBar, SWT.SEPARATOR);
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdCut]);
+ item.setToolTipText(getResourceString("tool.Cut.tiptext"));
+ item.addSelectionListener(unimplementedListener);
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdCopy]);
+ item.setToolTipText(getResourceString("tool.Copy.tiptext"));
+ item.addSelectionListener(unimplementedListener);
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdPaste]);
+ item.setToolTipText(getResourceString("tool.Paste.tiptext")); item.addSelectionListener(unimplementedListener);
+
+ item = new ToolItem(toolBar, SWT.SEPARATOR);
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdDelete]);
+ item.setToolTipText(getResourceString("tool.Delete.tiptext"));
+ item.addSelectionListener(unimplementedListener);
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdRename]);
+ item.setToolTipText(getResourceString("tool.Rename.tiptext"));
+ item.addSelectionListener(unimplementedListener);
+
+ item = new ToolItem(toolBar, SWT.SEPARATOR);
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdSearch]);
+ item.setToolTipText(getResourceString("tool.Search.tiptext"));
+ item.addSelectionListener(unimplementedListener);
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(iconCache.stockImages[iconCache.cmdPrint]);
+ item.setToolTipText(getResourceString("tool.Print.tiptext"));
+ item.addSelectionListener(unimplementedListener);
+ }
+
+ /**
+ * Creates the combo box view.
+ *
+ * @param parent the parent control
+ */
+ private void createComboView(Composite parent, Object layoutData) {
+ combo = new Combo(parent, SWT.NONE);
+ combo.setLayoutData(layoutData);
+ combo.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ final File[] roots = (File[]) combo.getData(COMBODATA_ROOTS);
+ if (roots == null) return;
+ int selection = combo.getSelectionIndex();
+ if (selection >= 0 && selection < roots.length) {
+ notifySelectedDirectory(roots[selection]);
+ }
+ }
+ public void widgetDefaultSelected(SelectionEvent e) {
+ final String lastText = (String) combo.getData(COMBODATA_LASTTEXT);
+ String text = combo.getText();
+ if (text == null) return;
+ if (lastText != null && lastText.equals(text)) return;
+ combo.setData(COMBODATA_LASTTEXT, text);
+ notifySelectedDirectory(new File(text));
+ }
+ });
+ }
+
+ /**
+ * Creates the file tree view.
+ *
+ * @param parent the parent control
+ */
+ private void createTreeView(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 1;
+ gridLayout.marginHeight = gridLayout.marginWidth = 2;
+ gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
+ composite.setLayout(gridLayout);
+
+ treeScopeLabel = new Label(composite, SWT.BORDER);
+ treeScopeLabel.setText(FileViewer.getResourceString("details.AllFolders.text"));
+ treeScopeLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
+
+ tree = new Tree(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE);
+ tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
+
+ tree.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent event) {
+ final TreeItem[] selection = tree.getSelection();
+ if (selection != null && selection.length != 0) {
+ TreeItem item = selection[0];
+ File file = (File) item.getData(TREEITEMDATA_FILE);
+
+ notifySelectedDirectory(file);
+ }
+ }
+ public void widgetDefaultSelected(SelectionEvent event) {
+ final TreeItem[] selection = tree.getSelection();
+ if (selection != null && selection.length != 0) {
+ TreeItem item = selection[0];
+ item.setExpanded(true);
+ treeExpandItem(item);
+ }
+ }
+ });
+ tree.addTreeListener(new TreeAdapter() {
+ public void treeExpanded(TreeEvent event) {
+ final TreeItem item = (TreeItem) event.item;
+ final Image image = (Image) item.getData(TREEITEMDATA_IMAGEEXPANDED);
+ if (image != null) item.setImage(image);
+ treeExpandItem(item);
+ }
+ public void treeCollapsed(TreeEvent event) {
+ final TreeItem item = (TreeItem) event.item;
+ final Image image = (Image) item.getData(TREEITEMDATA_IMAGECOLLAPSED);
+ if (image != null) item.setImage(image);
+ }
+ });
+ createTreeDragSource(tree);
+ createTreeDropTarget(tree);
+ }
+
+ /**
+ * Creates the Drag & Drop DragSource for items being dragged from the tree.
+ *
+ * @return the DragSource for the tree
+ */
+ private DragSource createTreeDragSource(final Tree tree){
+ DragSource dragSource = new DragSource(tree, DND.DROP_MOVE | DND.DROP_COPY);
+ dragSource.setTransfer(new Transfer[] { FileTransfer.getInstance() });
+ dragSource.addDragListener(new DragSourceListener() {
+ TreeItem[] dndSelection = null;
+ String[] sourceNames = null;
+ public void dragStart(DragSourceEvent event){
+ dndSelection = tree.getSelection();
+ sourceNames = null;
+ event.doit = dndSelection.length > 0;
+ isDragging = true;
+ processedDropFiles = null;
+ }
+ public void dragFinished(DragSourceEvent event){
+ dragSourceHandleDragFinished(event, sourceNames);
+ dndSelection = null;
+ sourceNames = null;
+ isDragging = false;
+ processedDropFiles = null;
+ handleDeferredRefresh();
+ }
+ public void dragSetData(DragSourceEvent event){
+ if (dndSelection == null || dndSelection.length == 0) return;
+ if (! FileTransfer.getInstance().isSupportedType(event.dataType)) return;
+
+ sourceNames = new String[dndSelection.length];
+ for (int i = 0; i < dndSelection.length; i++) {
+ File file = (File) dndSelection[i].getData(TREEITEMDATA_FILE);
+ sourceNames[i] = file.getAbsolutePath();
+ }
+ event.data = sourceNames;
+ }
+ });
+ return dragSource;
+ }
+
+ /**
+ * Creates the Drag & Drop DropTarget for items being dropped onto the tree.
+ *
+ * @return the DropTarget for the tree
+ */
+ private DropTarget createTreeDropTarget(final Tree tree) {
+ DropTarget dropTarget = new DropTarget(tree, DND.DROP_MOVE | DND.DROP_COPY);
+ dropTarget.setTransfer(new Transfer[] { FileTransfer.getInstance() });
+ dropTarget.addDropListener(new DropTargetAdapter() {
+ public void dragEnter(DropTargetEvent event) {
+ isDropping = true;
+ }
+ public void dragLeave(DropTargetEvent event) {
+ isDropping = false;
+ handleDeferredRefresh();
+ }
+ public void dragOver(DropTargetEvent event) {
+ dropTargetValidate(event, getTargetFile(event));
+ event.feedback |= DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
+ }
+ public void drop(DropTargetEvent event) {
+ File targetFile = getTargetFile(event);
+ if (dropTargetValidate(event, targetFile))
+ dropTargetHandleDrop(event, targetFile);
+ }
+ private File getTargetFile(DropTargetEvent event) {
+ // Determine the target File for the drop
+ TreeItem item = tree.getItem(tree.toControl(new Point(event.x, event.y)));
+ File targetFile = null;
+ if (item != null) {
+ // We are over a particular item in the tree, use the item's file
+ targetFile = (File) item.getData(TREEITEMDATA_FILE);
+ }
+ return targetFile;
+ }
+ });
+ return dropTarget;
+ }
+
+ /**
+ * Handles expand events on a tree item.
+ *
+ * @param item the TreeItem to fill in
+ */
+ private void treeExpandItem(TreeItem item) {
+ shell.setCursor(iconCache.stockCursors[iconCache.cursorWait]);
+ final Object stub = item.getData(TREEITEMDATA_STUB);
+ if (stub == null) treeRefreshItem(item, true);
+ shell.setCursor(iconCache.stockCursors[iconCache.cursorDefault]);
+ }
+
+ /**
+ * Traverse the entire tree and update only what has changed.
+ *
+ * @param roots the root directory listing
+ */
+ private void treeRefresh(File[] masterFiles) {
+ TreeItem[] items = tree.getItems();
+ int masterIndex = 0;
+ int itemIndex = 0;
+ for (int i = 0; i < items.length; ++i) {
+ final TreeItem item = items[i];
+ final File itemFile = (File) item.getData(TREEITEMDATA_FILE);
+ if ((itemFile == null) || (masterIndex == masterFiles.length)) {
+ // remove bad item or placeholder
+ item.dispose();
+ continue;
+ }
+ final File masterFile = masterFiles[masterIndex];
+ int compare = compareFiles(masterFile, itemFile);
+ if (compare == 0) {
+ // same file, update it
+ treeRefreshItem(item, false);
+ ++itemIndex;
+ ++masterIndex;
+ } else if (compare < 0) {
+ // should appear before file, insert it
+ TreeItem newItem = new TreeItem(tree, SWT.NULL, itemIndex);
+ treeInitVolume(newItem, masterFile);
+ new TreeItem(newItem, SWT.NULL); // placeholder child item to get "expand" button
+ ++itemIndex;
+ ++masterIndex;
+ --i;
+ } else {
+ // should appear after file, delete stale item
+ item.dispose();
+ }
+ }
+ for (;masterIndex < masterFiles.length; ++masterIndex) {
+ final File masterFile = masterFiles[masterIndex];
+ TreeItem newItem = new TreeItem(tree, SWT.NULL);
+ treeInitVolume(newItem, masterFile);
+ new TreeItem(newItem, SWT.NULL); // placeholder child item to get "expand" button
+ }
+ }
+
+ /**
+ * Traverse an item in the tree and update only what has changed.
+ *
+ * @param dirItem the tree item of the directory
+ * @param forcePopulate true iff we should populate non-expanded items as well
+ */
+ private void treeRefreshItem(TreeItem dirItem, boolean forcePopulate) {
+ final File dir = (File) dirItem.getData(TREEITEMDATA_FILE);
+
+ if (! forcePopulate && ! dirItem.getExpanded()) {
+ // Refresh non-expanded item
+ if (dirItem.getData(TREEITEMDATA_STUB) != null) {
+ treeItemRemoveAll(dirItem);
+ new TreeItem(dirItem, SWT.NULL); // placeholder child item to get "expand" button
+ dirItem.setData(TREEITEMDATA_STUB, null);
+ }
+ return;
+ }
+ // Refresh expanded item
+ dirItem.setData(TREEITEMDATA_STUB, this); // clear stub flag
+
+ /* Get directory listing */
+ File[] subFiles = (dir != null) ? FileViewer.getDirectoryList(dir) : null;
+ if (subFiles == null || subFiles.length == 0) {
+ /* Error or no contents */
+ treeItemRemoveAll(dirItem);
+ dirItem.setExpanded(false);
+ return;
+ }
+
+ /* Refresh sub-items */
+ TreeItem[] items = dirItem.getItems();
+ final File[] masterFiles = subFiles;
+ int masterIndex = 0;
+ int itemIndex = 0;
+ File masterFile = null;
+ for (int i = 0; i < items.length; ++i) {
+ while ((masterFile == null) && (masterIndex < masterFiles.length)) {
+ masterFile = masterFiles[masterIndex++];
+ if (! masterFile.isDirectory()) masterFile = null;
+ }
+
+ final TreeItem item = items[i];
+ final File itemFile = (File) item.getData(TREEITEMDATA_FILE);
+ if ((itemFile == null) || (masterFile == null)) {
+ // remove bad item or placeholder
+ item.dispose();
+ continue;
+ }
+ int compare = compareFiles(masterFile, itemFile);
+ if (compare == 0) {
+ // same file, update it
+ treeRefreshItem(item, false);
+ masterFile = null;
+ ++itemIndex;
+ } else if (compare < 0) {
+ // should appear before file, insert it
+ TreeItem newItem = new TreeItem(dirItem, SWT.NULL, itemIndex);
+ treeInitFolder(newItem, masterFile);
+ new TreeItem(newItem, SWT.NULL); // add a placeholder child item so we get the "expand" button
+ masterFile = null;
+ ++itemIndex;
+ --i;
+ } else {
+ // should appear after file, delete stale item
+ item.dispose();
+ }
+ }
+ while ((masterFile != null) || (masterIndex < masterFiles.length)) {
+ if (masterFile != null) {
+ TreeItem newItem = new TreeItem(dirItem, SWT.NULL);
+ treeInitFolder(newItem, masterFile);
+ new TreeItem(newItem, SWT.NULL); // add a placeholder child item so we get the "expand" button
+ if (masterIndex == masterFiles.length) break;
+ }
+ masterFile = masterFiles[masterIndex++];
+ if (! masterFile.isDirectory()) masterFile = null;
+ }
+ }
+
+ /**
+ * Foreign method: removes all children of a TreeItem.
+ * @param treeItem the TreeItem
+ */
+ private static void treeItemRemoveAll(TreeItem treeItem) {
+ final TreeItem[] children = treeItem.getItems();
+ for (int i = 0; i < children.length; ++i) {
+ children[i].dispose();
+ }
+ }
+
+ /**
+ * Initializes a folder item.
+ *
+ * @param item the TreeItem to initialize
+ * @param folder the File associated with this TreeItem
+ */
+ private void treeInitFolder(TreeItem item, File folder) {
+ item.setText(folder.getName());
+ item.setImage(iconCache.stockImages[iconCache.iconClosedFolder]);
+ item.setData(TREEITEMDATA_FILE, folder);
+ item.setData(TREEITEMDATA_IMAGEEXPANDED, iconCache.stockImages[iconCache.iconOpenFolder]);
+ item.setData(TREEITEMDATA_IMAGECOLLAPSED, iconCache.stockImages[iconCache.iconClosedFolder]);
+ }
+
+ /**
+ * Initializes a volume item.
+ *
+ * @param item the TreeItem to initialize
+ * @param volume the File associated with this TreeItem
+ */
+ private void treeInitVolume(TreeItem item, File volume) {
+ item.setText(volume.getPath());
+ item.setImage(iconCache.stockImages[iconCache.iconClosedDrive]);
+ item.setData(TREEITEMDATA_FILE, volume);
+ item.setData(TREEITEMDATA_IMAGEEXPANDED, iconCache.stockImages[iconCache.iconOpenDrive]);
+ item.setData(TREEITEMDATA_IMAGECOLLAPSED, iconCache.stockImages[iconCache.iconClosedDrive]);
+ }
+
+ /**
+ * Creates the file details table.
+ *
+ * @param parent the parent control
+ */
+ private void createTableView(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 1;
+ gridLayout.marginHeight = gridLayout.marginWidth = 2;
+ gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
+ composite.setLayout(gridLayout);
+ tableContentsOfLabel = new Label(composite, SWT.BORDER);
+ tableContentsOfLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
+
+ table = new Table(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
+ table.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
+
+ for (int i = 0; i < tableTitles.length; ++i) {
+ TableColumn column = new TableColumn(table, SWT.NONE);
+ column.setText(tableTitles[i]);
+ column.setWidth(tableWidths[i]);
+ }
+ table.setHeaderVisible(true);
+ table.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ notifySelectedFiles(getSelectedFiles());
+ }
+ public void widgetDefaultSelected(SelectionEvent event) {
+ doDefaultFileAction(getSelectedFiles());
+ }
+ private File[] getSelectedFiles() {
+ final TableItem[] items = table.getSelection();
+ final File[] files = new File[items.length];
+
+ for (int i = 0; i < items.length; ++i) {
+ files[i] = (File) items[i].getData(TABLEITEMDATA_FILE);
+ }
+ return files;
+ }
+ });
+
+ createTableDragSource(table);
+ createTableDropTarget(table);
+ }
+
+ /**
+ * Creates the Drag & Drop DragSource for items being dragged from the table.
+ *
+ * @return the DragSource for the table
+ */
+ private DragSource createTableDragSource(final Table table) {
+ DragSource dragSource = new DragSource(table, DND.DROP_MOVE | DND.DROP_COPY);
+ dragSource.setTransfer(new Transfer[] { FileTransfer.getInstance() });
+ dragSource.addDragListener(new DragSourceListener() {
+ TableItem[] dndSelection = null;
+ String[] sourceNames = null;
+ public void dragStart(DragSourceEvent event){
+ dndSelection = table.getSelection();
+ sourceNames = null;
+ event.doit = dndSelection.length > 0;
+ isDragging = true;
+ }
+ public void dragFinished(DragSourceEvent event){
+ dragSourceHandleDragFinished(event, sourceNames);
+ dndSelection = null;
+ sourceNames = null;
+ isDragging = false;
+ handleDeferredRefresh();
+ }
+ public void dragSetData(DragSourceEvent event){
+ if (dndSelection == null || dndSelection.length == 0) return;
+ if (! FileTransfer.getInstance().isSupportedType(event.dataType)) return;
+
+ sourceNames = new String[dndSelection.length];
+ for (int i = 0; i < dndSelection.length; i++) {
+ File file = (File) dndSelection[i].getData(TABLEITEMDATA_FILE);
+ sourceNames[i] = file.getAbsolutePath();
+ }
+ event.data = sourceNames;
+ }
+ });
+ return dragSource;
+ }
+
+ /**
+ * Creates the Drag & Drop DropTarget for items being dropped onto the table.
+ *
+ * @return the DropTarget for the table
+ */
+ private DropTarget createTableDropTarget(final Table table){
+ DropTarget dropTarget = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY);
+ dropTarget.setTransfer(new Transfer[] { FileTransfer.getInstance() });
+ dropTarget.addDropListener(new DropTargetAdapter() {
+ public void dragEnter(DropTargetEvent event) {
+ isDropping = true;
+ }
+ public void dragLeave(DropTargetEvent event) {
+ isDropping = false;
+ handleDeferredRefresh();
+ }
+ public void dragOver(DropTargetEvent event) {
+ dropTargetValidate(event, getTargetFile(event));
+ event.feedback |= DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
+ }
+ public void drop(DropTargetEvent event) {
+ File targetFile = getTargetFile(event);
+ if (dropTargetValidate(event, targetFile))
+ dropTargetHandleDrop(event, targetFile);
+ }
+ private File getTargetFile(DropTargetEvent event) {
+ // Determine the target File for the drop
+ TableItem item = table.getItem(table.toControl(new Point(event.x, event.y)));
+ File targetFile = null;
+ if (item == null) {
+ // We are over an unoccupied area of the table.
+ // If it is a COPY, we can use the table's root file.
+ if (event.detail == DND.DROP_COPY) {
+ targetFile = (File) table.getData(TABLEDATA_DIR);
+ }
+ } else {
+ // We are over a particular item in the table, use the item's file
+ targetFile = (File) item.getData(TABLEITEMDATA_FILE);
+ }
+ return targetFile;
+ }
+ });
+ return dropTarget;
+ }
+
+ /**
+ * Notifies the application components that a new current directory has been selected
+ *
+ * @param dir the directory that was selected, null is ignored
+ */
+ void notifySelectedDirectory(File dir) {
+ if (dir == null) return;
+ if (currentDirectory != null && dir.equals(currentDirectory)) return;
+ currentDirectory = dir;
+ notifySelectedFiles(null);
+
+ /* Shell:
+ * Sets the title to indicate the selected directory
+ */
+ shell.setText(getResourceString("Title", new Object[] { currentDirectory.getPath() }));
+ /* Table view:
+ * Displays the contents of the selected directory.
+ */
+ workerUpdate(dir, false);
+
+ /* Combo view:
+ * Sets the combo box to point to the selected directory.
+ */
+ final File[] comboRoots = (File[]) combo.getData(COMBODATA_ROOTS);
+ int comboEntry = -1;
+ if (comboRoots != null) {
+ for (int i = 0; i < comboRoots.length; ++i) {
+ if (dir.equals(comboRoots[i])) {
+ comboEntry = i;
+ break;
+ }
+ }
+ }
+ if (comboEntry == -1) combo.setText(dir.getPath());
+ else combo.select(comboEntry);
+
+ /* Tree view:
+ * If not already expanded, recursively expands the parents of the specified
+ * directory until it is visible.
+ */
+ Vector /* of File */ path = new Vector();
+ // Build a stack of paths from the root of the tree
+ while (dir != null) {
+ path.add(dir);
+ dir = dir.getParentFile();
+ }
+ // Recursively expand the tree to get to the specified directory
+ TreeItem[] items = tree.getItems();
+ TreeItem lastItem = null;
+ for (int i = path.size() - 1; i >= 0; --i) {
+ final File pathElement = (File) path.elementAt(i);
+
+ // Search for a particular File in the array of tree items
+ // No guarantee that the items are sorted in any recognizable fashion, so we'll
+ // just sequential scan. There shouldn't be more than a few thousand entries.
+ TreeItem item = null;
+ for (int k = 0; k < items.length; ++k) {
+ item = items[k];
+ if (item.isDisposed()) continue;
+ final File itemFile = (File) item.getData(TREEITEMDATA_FILE);
+ if (itemFile != null && itemFile.equals(pathElement)) break;
+ }
+ if (item == null) break;
+ lastItem = item;
+ if (i != 0 && !item.getExpanded()) {
+ treeExpandItem(item);
+ item.setExpanded(true);
+ }
+ items = item.getItems();
+ }
+ tree.setSelection((lastItem != null) ? new TreeItem[] { lastItem } : new TreeItem[0]);
+ }
+
+ /**
+ * Notifies the application components that files have been selected
+ *
+ * @param files the files that were selected, null or empty array indicates no active selection
+ */
+ void notifySelectedFiles(File[] files) {
+ /* Details:
+ * Update the details that are visible on screen.
+ */
+ if ((files != null) && (files.length != 0)) {
+ numObjectsLabel.setText(getResourceString("details.NumberOfSelectedFiles.text",
+ new Object[] { new Integer(files.length) }));
+ long fileSize = 0L;
+ for (int i = 0; i < files.length; ++i) {
+ fileSize += files[i].length();
+ }
+ diskSpaceLabel.setText(getResourceString("details.FileSize.text",
+ new Object[] { new Long(fileSize) }));
+ } else {
+ // No files selected
+ diskSpaceLabel.setText("");
+ if (currentDirectory != null) {
+ int numObjects = getDirectoryList(currentDirectory).length;
+ numObjectsLabel.setText(getResourceString("details.DirNumberOfObjects.text",
+ new Object[] { new Integer(numObjects) }));
+ } else {
+ numObjectsLabel.setText("");
+ }
+ }
+ }
+
+ /**
+ * Notifies the application components that files must be refreshed
+ *
+ * @param files the files that need refreshing, empty array is a no-op, null refreshes all
+ */
+ void notifyRefreshFiles(File[] files) {
+ if (files != null && files.length == 0) return;
+
+ if ((deferredRefreshRequested) && (deferredRefreshFiles != null) && (files != null)) {
+ // merge requests
+ File[] newRequest = new File[deferredRefreshFiles.length + files.length];
+ System.arraycopy(deferredRefreshFiles, 0, newRequest, 0, deferredRefreshFiles.length);
+ System.arraycopy(files, 0, newRequest, deferredRefreshFiles.length, files.length);
+ deferredRefreshFiles = newRequest;
+ } else {
+ deferredRefreshFiles = files;
+ deferredRefreshRequested = true;
+ }
+ handleDeferredRefresh();
+ }
+
+ /**
+ * Handles deferred Refresh notifications (due to Drag & Drop)
+ */
+ void handleDeferredRefresh() {
+ if (isDragging || isDropping || ! deferredRefreshRequested) return;
+ if (progressDialog != null) {
+ progressDialog.close();
+ progressDialog = null;
+ }
+
+ deferredRefreshRequested = false;
+ File[] files = deferredRefreshFiles;
+ deferredRefreshFiles = null;
+
+ shell.setCursor(iconCache.stockCursors[iconCache.cursorWait]);
+
+ /* Table view:
+ * Refreshes information about any files in the list and their children.
+ */
+ boolean refreshTable = false;
+ if (files != null) {
+ for (int i = 0; i < files.length; ++i) {
+ final File file = files[i];
+ if (file.equals(currentDirectory)) {
+ refreshTable = true;
+ break;
+ }
+ File parentFile = file.getParentFile();
+ if ((parentFile != null) && (parentFile.equals(currentDirectory))) {
+ refreshTable = true;
+ break;
+ }
+ }
+ } else refreshTable = true;
+ if (refreshTable) workerUpdate(currentDirectory, true);
+
+ /* Combo view:
+ * Refreshes the list of roots
+ */
+ final File[] roots = getRoots();
+
+ if (files == null) {
+ boolean refreshCombo = false;
+ final File[] comboRoots = (File[]) combo.getData(COMBODATA_ROOTS);
+
+ if ((comboRoots != null) && (comboRoots.length == roots.length)) {
+ for (int i = 0; i < roots.length; ++i) {
+ if (! roots[i].equals(comboRoots[i])) {
+ refreshCombo = true;
+ break;
+ }
+ }
+ } else refreshCombo = true;
+
+ if (refreshCombo) {
+ combo.removeAll();
+ combo.setData(COMBODATA_ROOTS, roots);
+ for (int i = 0; i < roots.length; ++i) {
+ final File file = roots[i];
+ combo.add(file.getPath());
+ }
+ }
+ }
+
+ /* Tree view:
+ * Refreshes information about any files in the list and their children.
+ */
+ treeRefresh(roots);
+
+ // Remind everyone where we are in the filesystem
+ final File dir = currentDirectory;
+ currentDirectory = null;
+ notifySelectedDirectory(dir);
+
+ shell.setCursor(iconCache.stockCursors[iconCache.cursorDefault]);
+ }
+
+ /**
+ * Performs the default action on a set of files.
+ *
+ * @param files the array of files to process
+ */
+ void doDefaultFileAction(File[] files) {
+ // only uses the 1st file (for now)
+ if (files.length == 0) return;
+ final File file = files[0];
+
+ if (file.isDirectory()) {
+ notifySelectedDirectory(file);
+ } else {
+ final String fileName = file.getAbsolutePath();
+ if (! Program.launch(fileName)) {
+ MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
+ dialog.setMessage(getResourceString("error.FailedLaunch.message", new Object[] { fileName }));
+ dialog.setText(shell.getText ());
+ dialog.open();
+ }
+ }
+ }
+
+ /**
+ * Navigates to the parent directory
+ */
+ void doParent() {
+ if (currentDirectory == null) return;
+ File parentDirectory = currentDirectory.getParentFile();
+ notifySelectedDirectory(parentDirectory);
+ }
+
+ /**
+ * Performs a refresh
+ */
+ void doRefresh() {
+ notifyRefreshFiles(null);
+ }
+
+ /**
+ * Validates a drop target as a candidate for a drop operation.
+ * <p>
+ * Used in dragOver() and dropAccept().<br>
+ * Note event.detail is set to DND.DROP_NONE by this method if the target is not valid.
+ * </p>
+ * @param event the DropTargetEvent to validate
+ * @param targetFile the File representing the drop target location
+ * under inspection, or null if none
+ */
+ private boolean dropTargetValidate(DropTargetEvent event, File targetFile) {
+ if (targetFile != null && targetFile.isDirectory()) {
+ if (event.detail != DND.DROP_COPY && event.detail != DND.DROP_MOVE) {
+ event.detail = DND.DROP_MOVE;
+ }
+ } else {
+ event.detail = DND.DROP_NONE;
+ }
+ return event.detail != DND.DROP_NONE;
+ }
+
+ /**
+ * Handles a drop on a dropTarget.
+ * <p>
+ * Used in drop().<br>
+ * Note event.detail is modified by this method.
+ * </p>
+ * @param event the DropTargetEvent passed as parameter to the drop() method
+ * @param targetFile the File representing the drop target location
+ * under inspection, or null if none
+ */
+ private void dropTargetHandleDrop(DropTargetEvent event, File targetFile) {
+ // Get dropped data (an array of filenames)
+ if (! dropTargetValidate(event, targetFile)) return;
+ final String[] sourceNames = (String[]) event.data;
+ if (sourceNames == null) event.detail = DND.DROP_NONE;
+ if (event.detail == DND.DROP_NONE) return;
+
+ // Open progress dialog
+ progressDialog = new ProgressDialog(shell,
+ (event.detail == DND.DROP_MOVE) ? ProgressDialog.MOVE : ProgressDialog.COPY);
+ progressDialog.setTotalWorkUnits(sourceNames.length);
+ progressDialog.open();
+
+ // Copy each file
+ Vector /* of File */ processedFiles = new Vector();
+ for (int i = 0; (i < sourceNames.length) && (! progressDialog.isCancelled()); i++){
+ final File source = new File(sourceNames[i]);
+ final File dest = new File(targetFile, source.getName());
+ if (source.equals(dest)) continue; // ignore if in same location
+
+ progressDialog.setDetailFile(source, ProgressDialog.COPY);
+ while (! progressDialog.isCancelled()) {
+ if (copyFileStructure(source, dest)) {
+ processedFiles.add(source);
+ break;
+ } else if (! progressDialog.isCancelled()) {
+ if (event.detail == DND.DROP_MOVE && (!isDragging)) {
+ // It is not possible to notify an external drag source that a drop
+ // operation was only partially successful. This is particularly a
+ // problem for DROP_MOVE operations since unless the source gets
+ // DROP_NONE, it will delete the original data including bits that
+ // may not have been transferred successfully.
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
+ box.setText(getResourceString("dialog.FailedCopy.title"));
+ box.setMessage(getResourceString("dialog.FailedCopy.description",
+ new Object[] { source, dest }));
+ int button = box.open();
+ if (button == SWT.CANCEL) {
+ i = sourceNames.length;
+ event.detail = DND.DROP_NONE;
+ break;
+ }
+ } else {
+ // We can recover gracefully from errors if the drag source belongs
+ // to this application since it will look at processedDropFiles.
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.ABORT | SWT.RETRY | SWT.IGNORE);
+ box.setText(getResourceString("dialog.FailedCopy.title"));
+ box.setMessage(getResourceString("dialog.FailedCopy.description",
+ new Object[] { source, dest }));
+ int button = box.open();
+ if (button == SWT.ABORT) i = sourceNames.length;
+ if (button != SWT.RETRY) break;
+ }
+ }
+ progressDialog.addProgress(1);
+ }
+ }
+ if (isDragging) {
+ // Remember exactly which files we processed
+ processedDropFiles = ((File[]) processedFiles.toArray(new File[processedFiles.size()]));
+ } else {
+ progressDialog.close();
+ progressDialog = null;
+ }
+ notifyRefreshFiles(new File[] { targetFile });
+ }
+
+ /**
+ * Handles the completion of a drag on a dragSource.
+ * <p>
+ * Used in dragFinished().<br>
+ * </p>
+ * @param event the DragSourceEvent passed as parameter to the dragFinished() method
+ * @param sourceNames the names of the files that were dragged (event.data is invalid)
+ */
+ private void dragSourceHandleDragFinished(DragSourceEvent event, String[] sourceNames) {
+ if (sourceNames == null) return;
+ if (event.detail != DND.DROP_MOVE) return;
+
+ // Get array of files that were actually transferred
+ final File[] sourceFiles;
+ if (processedDropFiles != null) {
+ sourceFiles = processedDropFiles;
+ } else {
+ sourceFiles = new File[sourceNames.length];
+ for (int i = 0; i < sourceNames.length; ++i)
+ sourceFiles[i] = new File(sourceNames[i]);
+ }
+ if (progressDialog == null)
+ progressDialog = new ProgressDialog(shell, ProgressDialog.MOVE);
+ progressDialog.setTotalWorkUnits(sourceFiles.length);
+ progressDialog.setProgress(0);
+ progressDialog.open();
+
+ // Delete each file
+ for (int i = 0; (i < sourceFiles.length) && (! progressDialog.isCancelled()); i++){
+ final File source = sourceFiles[i];
+ progressDialog.setDetailFile(source, ProgressDialog.DELETE);
+ while (! progressDialog.isCancelled()) {
+ if (deleteFileStructure(source)) {
+ break;
+ } else if (! progressDialog.isCancelled()) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.ABORT | SWT.RETRY | SWT.IGNORE);
+ box.setText(getResourceString("dialog.FailedDelete.title"));
+ box.setMessage(getResourceString("dialog.FailedDelete.description",
+ new Object[] { source }));
+ int button = box.open();
+ if (button == SWT.ABORT) i = sourceNames.length;
+ if (button == SWT.RETRY) break;
+ }
+ }
+ progressDialog.addProgress(1);
+ }
+ notifyRefreshFiles(sourceFiles);
+ progressDialog.close();
+ progressDialog = null;
+ }
+
+ /**
+ * Gets filesystem root entries
+ *
+ * @return an array of Files corresponding to the root directories on the platform,
+ * may be empty but not null
+ */
+ File[] getRoots() {
+ /*
+ * On JDK 1.22 only...
+ */
+ // return File.listRoots();
+
+ /*
+ * On JDK 1.1.7 and beyond...
+ * -- PORTABILITY ISSUES HERE --
+ */
+ if (System.getProperty ("os.name").indexOf ("Windows") != -1) {
+ Vector /* of File */ list = new Vector();
+ list.add(new File(DRIVE_A));
+ list.add(new File(DRIVE_B));
+ for (char i = 'c'; i <= 'z'; ++i) {
+ File drive = new File(i + ":" + File.separator);
+ if (drive.isDirectory() && drive.exists()) {
+ list.add(drive);
+ if (initial && i == 'c') {
+ currentDirectory = drive;
+ initial = false;
+ }
+ }
+ }
+ File[] roots = (File[]) list.toArray(new File[list.size()]);
+ sortFiles(roots);
+ return roots;
+ } else {
+ File root = new File(File.separator);
+ if (initial) {
+ currentDirectory = root;
+ }
+ return new File[] { root };
+ }
+ }
+
+ /**
+ * Gets a directory listing
+ *
+ * @param file the directory to be listed
+ * @return an array of files this directory contains, may be empty but not null
+ */
+ static File[] getDirectoryList(File file) {
+ File[] list = file.listFiles();
+ if (list == null) return new File[0];
+ sortFiles(list);
+ return list;
+ }
+
+ /**
+ * Copies a file or entire directory structure.
+ *
+ * @param oldFile the location of the old file or directory
+ * @param newFile the location of the new file or directory
+ * @return true iff the operation succeeds without errors
+ */
+ boolean copyFileStructure(File oldFile, File newFile) {
+ if (oldFile == null || newFile == null) return false;
+
+ // ensure that newFile is not a child of oldFile or a dupe
+ File searchFile = newFile;
+ do {
+ if (oldFile.equals(searchFile)) return false;
+ searchFile = searchFile.getParentFile();
+ } while (searchFile != null);
+
+ if (oldFile.isDirectory()) {
+ /*
+ * Copy a directory
+ */
+ if (progressDialog != null) {
+ progressDialog.setDetailFile(oldFile, ProgressDialog.COPY);
+ }
+ if (simulateOnly) {
+ //System.out.println(getResourceString("simulate.DirectoriesCreated.text",
+ // new Object[] { newFile.getPath() }));
+ } else {
+ if (! newFile.mkdirs()) return false;
+ }
+ File[] subFiles = oldFile.listFiles();
+ if (subFiles != null) {
+ if (progressDialog != null) {
+ progressDialog.addWorkUnits(subFiles.length);
+ }
+ for (int i = 0; i < subFiles.length; i++) {
+ File oldSubFile = subFiles[i];
+ File newSubFile = new File(newFile, oldSubFile.getName());
+ if (! copyFileStructure(oldSubFile, newSubFile)) return false;
+ if (progressDialog != null) {
+ progressDialog.addProgress(1);
+ if (progressDialog.isCancelled()) return false;
+ }
+ }
+ }
+ } else {
+ /*
+ * Copy a file
+ */
+ if (simulateOnly) {
+ //System.out.println(getResourceString("simulate.CopyFromTo.text",
+ // new Object[] { oldFile.getPath(), newFile.getPath() }));
+ } else {
+ FileReader in = null;
+ FileWriter out = null;
+ try {
+ in = new FileReader(oldFile);
+ out = new FileWriter(newFile);
+
+ int count;
+ while ((count = in.read()) != -1) out.write(count);
+ } catch (FileNotFoundException e) {
+ return false;
+ } catch (IOException e) {
+ return false;
+ } finally {
+ try {
+ if (in != null) in.close();
+ if (out != null) out.close();
+ } catch (IOException e) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Deletes a file or entire directory structure.
+ *
+ * @param oldFile the location of the old file or directory
+ * @return true iff the operation succeeds without errors
+ */
+ boolean deleteFileStructure(File oldFile) {
+ if (oldFile == null) return false;
+ if (oldFile.isDirectory()) {
+ /*
+ * Delete a directory
+ */
+ if (progressDialog != null) {
+ progressDialog.setDetailFile(oldFile, ProgressDialog.DELETE);
+ }
+ File[] subFiles = oldFile.listFiles();
+ if (subFiles != null) {
+ if (progressDialog != null) {
+ progressDialog.addWorkUnits(subFiles.length);
+ }
+ for (int i = 0; i < subFiles.length; i++) {
+ File oldSubFile = subFiles[i];
+ if (! deleteFileStructure(oldSubFile)) return false;
+ if (progressDialog != null) {
+ progressDialog.addProgress(1);
+ if (progressDialog.isCancelled()) return false;
+ }
+ }
+ }
+ }
+ if (simulateOnly) {
+ //System.out.println(getResourceString("simulate.Delete.text",
+ // new Object[] { oldFile.getPath(), oldFile.getPath() }));
+ return true;
+ } else {
+ return oldFile.delete();
+ }
+ }
+
+ /**
+ * Sorts files lexicographically by name.
+ *
+ * @param files the array of Files to be sorted
+ */
+ static void sortFiles(File[] files) {
+ /* Very lazy merge sort algorithm */
+ sortBlock(files, 0, files.length - 1, new File[files.length]);
+ }
+ private static void sortBlock(File[] files, int start, int end, File[] mergeTemp) {
+ final int length = end - start + 1;
+ if (length < 8) {
+ for (int i = end; i > start; --i) {
+ for (int j = end; j > start; --j) {
+ if (compareFiles(files[j - 1], files[j]) > 0) {
+ final File temp = files[j];
+ files[j] = files[j-1];
+ files[j-1] = temp;
+ }
+ }
+ }
+ return;
+ }
+ final int mid = (start + end) / 2;
+ sortBlock(files, start, mid, mergeTemp);
+ sortBlock(files, mid + 1, end, mergeTemp);
+ int x = start;
+ int y = mid + 1;
+ for (int i = 0; i < length; ++i) {
+ if ((x > mid) || ((y <= end) && compareFiles(files[x], files[y]) > 0)) {
+ mergeTemp[i] = files[y++];
+ } else {
+ mergeTemp[i] = files[x++];
+ }
+ }
+ for (int i = 0; i < length; ++i) files[i + start] = mergeTemp[i];
+ }
+ private static int compareFiles(File a, File b) {
+// boolean aIsDir = a.isDirectory();
+// boolean bIsDir = b.isDirectory();
+// if (aIsDir && ! bIsDir) return -1;
+// if (bIsDir && ! aIsDir) return 1;
+
+ // sort case-sensitive files in a case-insensitive manner
+ int compare = a.getName().compareToIgnoreCase(b.getName());
+ if (compare == 0) compare = a.getName().compareTo(b.getName());
+ return compare;
+ }
+
+ /*
+ * This worker updates the table with file information in the background.
+ * <p>
+ * Implementation notes:
+ * <ul>
+ * <li> It is designed such that it can be interrupted cleanly.
+ * <li> It uses asyncExec() in some places to ensure that SWT Widgets are manipulated in the
+ * right thread. Exclusive use of syncExec() would be inappropriate as it would require a pair
+ * of context switches between each table update operation.
+ * </ul>
+ * </p>
+ */
+
+ /**
+ * Stops the worker and waits for it to terminate.
+ */
+ void workerStop() {
+ if (workerThread == null) return;
+ synchronized(workerLock) {
+ workerCancelled = true;
+ workerStopped = true;
+ workerLock.notifyAll();
+ }
+ while (workerThread != null) {
+ if (! display.readAndDispatch()) display.sleep();
+ }
+ }
+
+ /**
+ * Notifies the worker that it should update itself with new data.
+ * Cancels any previous operation and begins a new one.
+ *
+ * @param dir the new base directory for the table, null is ignored
+ * @param force if true causes a refresh even if the data is the same
+ */
+ void workerUpdate(File dir, boolean force) {
+ if (dir == null) return;
+ if ((!force) && (workerNextDir != null) && (workerNextDir.equals(dir))) return;
+
+ synchronized(workerLock) {
+ workerNextDir = dir;
+ workerStopped = false;
+ workerCancelled = true;
+ workerLock.notifyAll();
+ }
+ if (workerThread == null) {
+ workerThread = new Thread(workerRunnable);
+ workerThread.start();
+ }
+ }
+
+ /**
+ * Manages the worker's thread
+ */
+ private final Runnable workerRunnable = new Runnable() {
+ public void run() {
+ while (! workerStopped) {
+ synchronized(workerLock) {
+ workerCancelled = false;
+ workerStateDir = workerNextDir;
+ }
+ workerExecute();
+ synchronized(workerLock) {
+ try {
+ if ((!workerCancelled) && (workerStateDir == workerNextDir)) workerLock.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+ workerThread = null;
+ // wake up UI thread in case it is in a modal loop awaiting thread termination
+ // (see workerStop())
+ display.wake();
+ }
+ };
+
+ /**
+ * Updates the table's contents
+ */
+ private void workerExecute() {
+ File[] dirList;
+ // Clear existing information
+ display.syncExec(new Runnable() {
+ public void run() {
+ tableContentsOfLabel.setText(FileViewer.getResourceString("details.ContentsOf.text",
+ new Object[] { workerStateDir.getPath() }));
+ table.removeAll();
+ table.setData(TABLEDATA_DIR, workerStateDir);
+ }
+ });
+ dirList = getDirectoryList(workerStateDir);
+
+ for (int i = 0; (! workerCancelled) && (i < dirList.length); i++) {
+ workerAddFileDetails(dirList[i]);
+ }
+
+ }
+
+ /**
+ * Adds a file's detail information to the directory list
+ */
+ private void workerAddFileDetails(final File file) {
+ final String nameString = file.getName();
+ final String dateString = dateFormat.format(new Date(file.lastModified()));
+ final String sizeString;
+ final String typeString;
+ final Image iconImage;
+
+ if (file.isDirectory()) {
+ typeString = getResourceString("filetype.Folder");
+ sizeString = "";
+ iconImage = iconCache.stockImages[iconCache.iconClosedFolder];
+ } else {
+ sizeString = getResourceString("filesize.KB",
+ new Object[] { new Long((file.length() + 512) / 1024) });
+
+ int dot = nameString.lastIndexOf('.');
+ if (dot != -1) {
+ String extension = nameString.substring(dot);
+ Program program = Program.findProgram(extension);
+ if (program != null) {
+ typeString = program.getName();
+ iconImage = iconCache.getIconFromProgram(program);
+ } else {
+ typeString = getResourceString("filetype.Unknown", new Object[] { extension.toUpperCase() });
+ iconImage = iconCache.stockImages[iconCache.iconFile];
+ }
+ } else {
+ typeString = getResourceString("filetype.None");
+ iconImage = iconCache.stockImages[iconCache.iconFile];
+ }
+ }
+ final String[] strings = new String[] { nameString, sizeString, typeString, dateString };
+
+ display.syncExec(new Runnable() {
+ public void run () {
+ // guard against the shell being closed before this runs
+ if (shell.isDisposed()) return;
+ TableItem tableItem = new TableItem(table, 0);
+ tableItem.setText(strings);
+ tableItem.setImage(iconImage);
+ tableItem.setData(TABLEITEMDATA_FILE, file);
+ }
+ });
+ }
+
+ /**
+ * Instances of this class manage a progress dialog for file operations.
+ */
+ class ProgressDialog {
+ public final static int COPY = 0;
+ public final static int DELETE = 1;
+ public final static int MOVE = 2;
+
+ Shell shell;
+ Label messageLabel, detailLabel;
+ ProgressBar progressBar;
+ Button cancelButton;
+ boolean isCancelled = false;
+
+ final String operationKeyName[] = {
+ "Copy",
+ "Delete",
+ "Move"
+ };
+
+ /**
+ * Creates a progress dialog but does not open it immediately.
+ *
+ * @param parent the parent Shell
+ * @param style one of COPY, MOVE
+ */
+ public ProgressDialog(Shell parent, int style) {
+ shell = new Shell(parent, SWT.BORDER | SWT.TITLE | SWT.APPLICATION_MODAL);
+ GridLayout gridLayout = new GridLayout();
+ shell.setLayout(gridLayout);
+ shell.setText(getResourceString("progressDialog." + operationKeyName[style] + ".title"));
+ shell.addShellListener(new ShellAdapter() {
+ public void shellClosed(ShellEvent e) {
+ isCancelled = true;
+ }
+ });
+
+ messageLabel = new Label(shell, SWT.HORIZONTAL);
+ messageLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
+ messageLabel.setText(getResourceString("progressDialog." + operationKeyName[style] + ".description"));
+
+ progressBar = new ProgressBar(shell, SWT.HORIZONTAL | SWT.WRAP);
+ progressBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
+ progressBar.setMinimum(0);
+ progressBar.setMaximum(0);
+
+ detailLabel = new Label(shell, SWT.HORIZONTAL);
+ GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
+ gridData.widthHint = 400;
+ detailLabel.setLayoutData(gridData);
+
+ cancelButton = new Button(shell, SWT.PUSH);
+ cancelButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_FILL));
+ cancelButton.setText(getResourceString("progressDialog.cancelButton.text"));
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ isCancelled = true;
+ cancelButton.setEnabled(false);
+ }
+ });
+ }
+ /**
+ * Sets the detail text to show the filename along with a string
+ * representing the operation being performed on that file.
+ *
+ * @param file the file to be detailed
+ * @param operation one of COPY, DELETE
+ */
+ public void setDetailFile(File file, int operation) {
+ detailLabel.setText(getResourceString("progressDialog." + operationKeyName[operation] + ".operation",
+ new Object[] { file }));
+ }
+ /**
+ * Returns true if the Cancel button was been clicked.
+ *
+ * @return true if the Cancel button was clicked.
+ */
+ public boolean isCancelled() {
+ return isCancelled;
+ }
+ /**
+ * Sets the total number of work units to be performed.
+ *
+ * @param work the total number of work units
+ */
+ public void setTotalWorkUnits(int work) {
+ progressBar.setMaximum(work);
+ }
+ /**
+ * Adds to the total number of work units to be performed.
+ *
+ * @param work the number of work units to add
+ */
+ public void addWorkUnits(int work) {
+ setTotalWorkUnits(progressBar.getMaximum() + work);
+ }
+ /**
+ * Sets the progress of completion of the total work units.
+ *
+ * @param work the total number of work units completed
+ */
+ public void setProgress(int work) {
+ progressBar.setSelection(work);
+ while (display.readAndDispatch()); // enable event processing
+ }
+ /**
+ * Adds to the progress of completion of the total work units.
+ *
+ * @param work the number of work units completed to add
+ */
+ public void addProgress(int work) {
+ setProgress(progressBar.getSelection() + work);
+ }
+ /**
+ * Opens the dialog.
+ */
+ public void open() {
+ shell.pack();
+ final Shell parentShell = (Shell) shell.getParent();
+ Rectangle rect = parentShell.getBounds();
+ Rectangle bounds = shell.getBounds();
+ bounds.x = rect.x + (rect.width - bounds.width) / 2;
+ bounds.y = rect.y + (rect.height - bounds.height) / 2;
+ shell.setBounds(bounds);
+ shell.open();
+ }
+ /**
+ * Closes the dialog and disposes its resources.
+ */
+ public void close() {
+ shell.close();
+ shell.dispose();
+ shell = null;
+ messageLabel = null;
+ detailLabel = null;
+ progressBar = null;
+ cancelButton = null;
+ }
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/IconCache.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/IconCache.java
index ac1f2d9acc..911f5d3e62 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/IconCache.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/fileviewer/IconCache.java
@@ -1,149 +1,149 @@
-package org.eclipse.swt.examples.fileviewer;
-/*
+package org.eclipse.swt.examples.fileviewer;
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.program.*;
-import org.eclipse.swt.widgets.*;
-
-import java.io.*;
-import java.util.*;
-
-/**
- * Manages icons for the application.
- * This is necessary as we could easily end up creating thousands of icons
- * bearing the same image.
- */
-class IconCache {
- // Stock images
- public final int
- shellIcon = 0,
- iconClosedDrive = 1,
- iconClosedFolder = 2,
- iconFile = 3,
- iconOpenDrive = 4,
- iconOpenFolder = 5,
- cmdCopy = 6,
- cmdCut = 7,
- cmdDelete = 8,
- cmdParent = 9,
- cmdPaste = 10,
- cmdPrint = 11,
- cmdRefresh = 12,
- cmdRename = 13,
- cmdSearch = 14;
- public final String[] stockImageLocations = {
- "generic_example.gif",
- "icon_ClosedDrive.gif",
- "icon_ClosedFolder.gif",
- "icon_File.gif",
- "icon_OpenDrive.gif",
- "icon_OpenFolder.gif",
- "cmd_Copy.gif",
- "cmd_Cut.gif",
- "cmd_Delete.gif",
- "cmd_Parent.gif",
- "cmd_Paste.gif",
- "cmd_Print.gif",
- "cmd_Refresh.gif",
- "cmd_Rename.gif",
- "cmd_Search.gif"
- };
- public Image stockImages[];
-
- // Stock cursors
- public final int
- cursorDefault = 0,
- cursorWait = 1;
- public Cursor stockCursors[];
- // Cached icons
- private Hashtable iconCache; /* map Program to Image */ public IconCache() { }
- /**
- * Loads the resources
- *
- * @param display the display
- */
- public void initResources(Display display) {
- if (stockImages == null) {
- stockImages = new Image[stockImageLocations.length];
-
- for (int i = 0; i < stockImageLocations.length; ++i) {
- Image image = createStockImage(display, stockImageLocations[i]);
- if (image == null) {
- freeResources();
- throw new IllegalStateException(
- FileViewer.getResourceString("error.CouldNotLoadResources"));
- }
- stockImages[i] = image;
- }
- }
- if (stockCursors == null) {
- stockCursors = new Cursor[] {
- null,
- new Cursor(display, SWT.CURSOR_WAIT)
- };
- }
- iconCache = new Hashtable();
- }
- /**
- * Frees the resources
- */
- public void freeResources() {
- if (stockImages != null) {
- for (int i = 0; i < stockImages.length; ++i) {
- final Image image = stockImages[i];
- if (image != null) image.dispose();
- }
- stockImages = null;
- }
- if (iconCache != null) {
- for (Enumeration it = iconCache.elements(); it.hasMoreElements(); ) {
- Image image = (Image) it.nextElement();
- image.dispose();
- }
- }
- }
- /**
- * Creates a stock image
- *
- * @param display the display
- * @param path the relative path to the icon
- */
- private Image createStockImage(Display display, String path) {
- try {
- InputStream stream = IconCache.class.getResourceAsStream(path);
- if (stream != null) {
- ImageData imageData = new ImageData(stream);
- if (imageData != null) {
- ImageData mask = imageData.getTransparencyMask();
- return new Image(display, imageData, mask);
- }
- }
- } catch (Exception e) {
- }
- return null;
- }
- /**
- * Gets an image for a file associated with a given program
- *
- * @param program the Program
- */
- public Image getIconFromProgram(Program program) {
- Image image = (Image) iconCache.get(program);
- if (image == null) {
- ImageData imageData = program.getImageData();
- if (imageData != null) {
- image = new Image(null, imageData, imageData.getTransparencyMask());
- iconCache.put(program, image);
- } else {
- image = stockImages[iconFile];
- }
- }
- return image;
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.program.*;
+import org.eclipse.swt.widgets.*;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * Manages icons for the application.
+ * This is necessary as we could easily end up creating thousands of icons
+ * bearing the same image.
+ */
+class IconCache {
+ // Stock images
+ public final int
+ shellIcon = 0,
+ iconClosedDrive = 1,
+ iconClosedFolder = 2,
+ iconFile = 3,
+ iconOpenDrive = 4,
+ iconOpenFolder = 5,
+ cmdCopy = 6,
+ cmdCut = 7,
+ cmdDelete = 8,
+ cmdParent = 9,
+ cmdPaste = 10,
+ cmdPrint = 11,
+ cmdRefresh = 12,
+ cmdRename = 13,
+ cmdSearch = 14;
+ public final String[] stockImageLocations = {
+ "generic_example.gif",
+ "icon_ClosedDrive.gif",
+ "icon_ClosedFolder.gif",
+ "icon_File.gif",
+ "icon_OpenDrive.gif",
+ "icon_OpenFolder.gif",
+ "cmd_Copy.gif",
+ "cmd_Cut.gif",
+ "cmd_Delete.gif",
+ "cmd_Parent.gif",
+ "cmd_Paste.gif",
+ "cmd_Print.gif",
+ "cmd_Refresh.gif",
+ "cmd_Rename.gif",
+ "cmd_Search.gif"
+ };
+ public Image stockImages[];
+
+ // Stock cursors
+ public final int
+ cursorDefault = 0,
+ cursorWait = 1;
+ public Cursor stockCursors[];
+ // Cached icons
+ private Hashtable iconCache; /* map Program to Image */ public IconCache() { }
+ /**
+ * Loads the resources
+ *
+ * @param display the display
+ */
+ public void initResources(Display display) {
+ if (stockImages == null) {
+ stockImages = new Image[stockImageLocations.length];
+
+ for (int i = 0; i < stockImageLocations.length; ++i) {
+ Image image = createStockImage(display, stockImageLocations[i]);
+ if (image == null) {
+ freeResources();
+ throw new IllegalStateException(
+ FileViewer.getResourceString("error.CouldNotLoadResources"));
+ }
+ stockImages[i] = image;
+ }
+ }
+ if (stockCursors == null) {
+ stockCursors = new Cursor[] {
+ null,
+ new Cursor(display, SWT.CURSOR_WAIT)
+ };
+ }
+ iconCache = new Hashtable();
}
-}
+ /**
+ * Frees the resources
+ */
+ public void freeResources() {
+ if (stockImages != null) {
+ for (int i = 0; i < stockImages.length; ++i) {
+ final Image image = stockImages[i];
+ if (image != null) image.dispose();
+ }
+ stockImages = null;
+ }
+ if (iconCache != null) {
+ for (Enumeration it = iconCache.elements(); it.hasMoreElements(); ) {
+ Image image = (Image) it.nextElement();
+ image.dispose();
+ }
+ }
+ }
+ /**
+ * Creates a stock image
+ *
+ * @param display the display
+ * @param path the relative path to the icon
+ */
+ private Image createStockImage(Display display, String path) {
+ try {
+ InputStream stream = IconCache.class.getResourceAsStream(path);
+ if (stream != null) {
+ ImageData imageData = new ImageData(stream);
+ if (imageData != null) {
+ ImageData mask = imageData.getTransparencyMask();
+ return new Image(display, imageData, mask);
+ }
+ }
+ } catch (Exception e) {
+ }
+ return null;
+ }
+ /**
+ * Gets an image for a file associated with a given program
+ *
+ * @param program the Program
+ */
+ public Image getIconFromProgram(Program program) {
+ Image image = (Image) iconCache.get(program);
+ if (image == null) {
+ ImageData imageData = program.getImageData();
+ if (imageData != null) {
+ image = new Image(null, imageData, imageData.getTransparencyMask());
+ iconCache.put(program, image);
+ } else {
+ image = stockImages[iconFile];
+ }
+ }
+ return image;
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld1.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld1.java
index 98bcf32e45..e5a7f5d1c7 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld1.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld1.java
@@ -1,32 +1,32 @@
-package org.eclipse.swt.examples.helloworld;
-
-/*
+package org.eclipse.swt.examples.helloworld;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.widgets.*;
-
-/*
- * This example demonstrates the minimum amount of code required
- * to open an SWT Shell and process the events.
- */
-public class HelloWorld1 {
-
-public static void main (String [] args) {
- Display display = new Display ();
- Shell shell = new HelloWorld1 ().open (display);
- while (!shell.isDisposed ()) {
- if (!display.readAndDispatch ()) display.sleep ();
- }
- display.dispose ();
-}
-
-public Shell open (Display display) {
- Shell shell = new Shell (display);
- shell.open ();
- return shell;
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.widgets.*;
+
+/*
+ * This example demonstrates the minimum amount of code required
+ * to open an SWT Shell and process the events.
+ */
+public class HelloWorld1 {
+
+public static void main (String [] args) {
+ Display display = new Display ();
+ Shell shell = new HelloWorld1 ().open (display);
+ while (!shell.isDisposed ()) {
+ if (!display.readAndDispatch ()) display.sleep ();
+ }
+ display.dispose ();
+}
+
+public Shell open (Display display) {
+ Shell shell = new Shell (display);
+ shell.open ();
+ return shell;
+}
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld2.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld2.java
index 454c23e4d1..356f04ea9a 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld2.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld2.java
@@ -1,38 +1,38 @@
-package org.eclipse.swt.examples.helloworld;
-
-/*
+package org.eclipse.swt.examples.helloworld;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import java.util.ResourceBundle;
-
-/*
- * This example builds on HelloWorld1 and demonstrates the minimum amount
- * of code required to open an SWT Shell with a Label and process the events.
- */
-public class HelloWorld2 {
- private static ResourceBundle resHello = ResourceBundle.getBundle("examples_helloworld");
-
-public static void main (String [] args) {
- Display display = new Display ();
- Shell shell = new HelloWorld2 ().open (display);
- while (!shell.isDisposed ()) {
- if (!display.readAndDispatch ()) display.sleep ();
- }
- display.dispose ();
-}
-
-public Shell open (Display display) {
- Shell shell = new Shell (display);
- Label label = new Label (shell, SWT.CENTER);
- label.setText (resHello.getString("Hello_world"));
- label.setBounds (shell.getClientArea ());
- shell.open ();
- return shell;
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import java.util.ResourceBundle;
+
+/*
+ * This example builds on HelloWorld1 and demonstrates the minimum amount
+ * of code required to open an SWT Shell with a Label and process the events.
+ */
+public class HelloWorld2 {
+ private static ResourceBundle resHello = ResourceBundle.getBundle("examples_helloworld");
+
+public static void main (String [] args) {
+ Display display = new Display ();
+ Shell shell = new HelloWorld2 ().open (display);
+ while (!shell.isDisposed ()) {
+ if (!display.readAndDispatch ()) display.sleep ();
+ }
+ display.dispose ();
+}
+
+public Shell open (Display display) {
+ Shell shell = new Shell (display);
+ Label label = new Label (shell, SWT.CENTER);
+ label.setText (resHello.getString("Hello_world"));
+ label.setBounds (shell.getClientArea ());
+ shell.open ();
+ return shell;
+}
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld3.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld3.java
index 59bd7582c7..ee90284016 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld3.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld3.java
@@ -1,45 +1,45 @@
-package org.eclipse.swt.examples.helloworld;
-
-/*
+package org.eclipse.swt.examples.helloworld;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.events.*;
-import java.util.ResourceBundle;
-
-/*
- * This example builds on HelloWorld2 and demonstrates how to resize the
- * Label when the Shell resizes using a Listener mechanism.
- */
-public class HelloWorld3 {
- private static ResourceBundle resHello = ResourceBundle.getBundle("examples_helloworld");
-
-public static void main (String [] args) {
- Display display = new Display ();
- Shell shell = new HelloWorld3 ().open (display);
- while (!shell.isDisposed ()) {
- if (!display.readAndDispatch ()) display.sleep ();
- }
- display.dispose ();
-}
-
-public Shell open (Display display) {
- final Shell shell = new Shell (display);
- final Label label = new Label (shell, SWT.CENTER);
- label.setText (resHello.getString("Hello_world"));
- label.pack();
- shell.addControlListener(new ControlAdapter() {
- public void controlResized(ControlEvent e) {
- label.setBounds (shell.getClientArea ());
- }
- });
- shell.pack();
- shell.open ();
- return shell;
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.events.*;
+import java.util.ResourceBundle;
+
+/*
+ * This example builds on HelloWorld2 and demonstrates how to resize the
+ * Label when the Shell resizes using a Listener mechanism.
+ */
+public class HelloWorld3 {
+ private static ResourceBundle resHello = ResourceBundle.getBundle("examples_helloworld");
+
+public static void main (String [] args) {
+ Display display = new Display ();
+ Shell shell = new HelloWorld3 ().open (display);
+ while (!shell.isDisposed ()) {
+ if (!display.readAndDispatch ()) display.sleep ();
+ }
+ display.dispose ();
+}
+
+public Shell open (Display display) {
+ final Shell shell = new Shell (display);
+ final Label label = new Label (shell, SWT.CENTER);
+ label.setText (resHello.getString("Hello_world"));
+ label.pack();
+ shell.addControlListener(new ControlAdapter() {
+ public void controlResized(ControlEvent e) {
+ label.setBounds (shell.getClientArea ());
+ }
+ });
+ shell.pack();
+ shell.open ();
+ return shell;
+}
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld4.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld4.java
index b8cdde8fa8..73d9110654 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld4.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld4.java
@@ -1,41 +1,41 @@
-package org.eclipse.swt.examples.helloworld;
-
-/*
+package org.eclipse.swt.examples.helloworld;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.layout.*;
-import java.util.ResourceBundle;
-
-/*
- * This example builds on HelloWorld2 and demonstrates how to resize the
- * Label when the Shell resizes using a Layout.
- */
-public class HelloWorld4 {
- private static ResourceBundle resHello = ResourceBundle.getBundle("examples_helloworld");
-
-public static void main (String [] args) {
- Display display = new Display ();
- Shell shell = new HelloWorld4 ().open (display);
- while (!shell.isDisposed ()) {
- if (!display.readAndDispatch ()) display.sleep ();
- }
- display.dispose ();
-}
-
-public Shell open (Display display) {
- Shell shell = new Shell (display);
- shell.setLayout(new FillLayout());
- Label label = new Label (shell, SWT.CENTER);
- label.setText (resHello.getString("Hello_world"));
- shell.pack ();
- shell.open ();
- return shell;
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.layout.*;
+import java.util.ResourceBundle;
+
+/*
+ * This example builds on HelloWorld2 and demonstrates how to resize the
+ * Label when the Shell resizes using a Layout.
+ */
+public class HelloWorld4 {
+ private static ResourceBundle resHello = ResourceBundle.getBundle("examples_helloworld");
+
+public static void main (String [] args) {
+ Display display = new Display ();
+ Shell shell = new HelloWorld4 ().open (display);
+ while (!shell.isDisposed ()) {
+ if (!display.readAndDispatch ()) display.sleep ();
+ }
+ display.dispose ();
+}
+
+public Shell open (Display display) {
+ Shell shell = new Shell (display);
+ shell.setLayout(new FillLayout());
+ Label label = new Label (shell, SWT.CENTER);
+ label.setText (resHello.getString("Hello_world"));
+ shell.pack ();
+ shell.open ();
+ return shell;
+}
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld5.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld5.java
index 71f369d137..4583203094 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld5.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/helloworld/HelloWorld5.java
@@ -1,52 +1,52 @@
-package org.eclipse.swt.examples.helloworld;
-
-/*
+package org.eclipse.swt.examples.helloworld;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.graphics.*;
-import java.util.ResourceBundle;
-
-/*
- * This example builds on HelloWorld1 and demonstrates how to draw directly
- * on an SWT Control.
- */
-public class HelloWorld5 {
- private static ResourceBundle resHello = ResourceBundle.getBundle("examples_helloworld");
-
-public static void main (String [] args) {
- Display display = new Display ();
- Shell shell = new HelloWorld5 ().open (display);
- while (!shell.isDisposed ()) {
- if (!display.readAndDispatch ()) display.sleep ();
- }
- display.dispose ();
-}
-
-public Shell open (Display display) {
- final Color red = new Color(display, 0xFF, 0, 0);
- final Shell shell = new Shell (display);
- shell.addPaintListener(new PaintListener () {
- public void paintControl(PaintEvent event){
- GC gc = event.gc;
- gc.setForeground(red);
- Rectangle rect = shell.getClientArea();
- gc.drawRectangle(rect.x + 10, rect.y + 10, rect.width - 20, rect.height - 20);
- gc.drawString(resHello.getString("Hello_world"), rect.x + 20, rect.y + 20);
- }
- });
- shell.addDisposeListener (new DisposeListener () {
- public void widgetDisposed (DisposeEvent e) {
- red.dispose();
- }
- });
- shell.open ();
- return shell;
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.graphics.*;
+import java.util.ResourceBundle;
+
+/*
+ * This example builds on HelloWorld1 and demonstrates how to draw directly
+ * on an SWT Control.
+ */
+public class HelloWorld5 {
+ private static ResourceBundle resHello = ResourceBundle.getBundle("examples_helloworld");
+
+public static void main (String [] args) {
+ Display display = new Display ();
+ Shell shell = new HelloWorld5 ().open (display);
+ while (!shell.isDisposed ()) {
+ if (!display.readAndDispatch ()) display.sleep ();
+ }
+ display.dispose ();
+}
+
+public Shell open (Display display) {
+ final Color red = new Color(display, 0xFF, 0, 0);
+ final Shell shell = new Shell (display);
+ shell.addPaintListener(new PaintListener () {
+ public void paintControl(PaintEvent event){
+ GC gc = event.gc;
+ gc.setForeground(red);
+ Rectangle rect = shell.getClientArea();
+ gc.drawRectangle(rect.x + 10, rect.y + 10, rect.width - 20, rect.height - 20);
+ gc.drawString(resHello.getString("Hello_world"), rect.x + 20, rect.y + 20);
+ }
+ });
+ shell.addDisposeListener (new DisposeListener () {
+ public void widgetDisposed (DisposeEvent e) {
+ red.dispose();
+ }
+ });
+ shell.open ();
+ return shell;
+}
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/hoverhelp/HoverHelp.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/hoverhelp/HoverHelp.java
index 2d632e0d45..7e633f20a3 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/hoverhelp/HoverHelp.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/hoverhelp/HoverHelp.java
@@ -1,338 +1,338 @@
-package org.eclipse.swt.examples.hoverhelp;
-
-/*
+package org.eclipse.swt.examples.hoverhelp;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import java.io.*; import java.text.*; import java.util.*; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*;
-/**
- * This example demonstrates how to implement hover help feedback
- * using the MouseTrackListener.
- */
-public class HoverHelp {
- private static ResourceBundle resourceBundle = ResourceBundle.getBundle("examples_hoverhelp");;
-
- static final int
- hhiInformation = 0,
- hhiWarning = 1;
- static final String[] imageLocations = {
- "information.gif",
- "warning.gif"
- };
- Image images[];
-
- /**
- * Runs main program.
- */
- public static void main (String [] args) {
- Display display = new Display();
- Shell shell = new HoverHelp().open(display);
- // Event loop
- while (shell != null && ! shell.isDisposed()) {
- if (! display.readAndDispatch()) display.sleep();
- }
- // Cleanup
- display.dispose();
-
- }
-
- /**
- * Opens the main program.
- */
- public Shell open(Display display) {
- // Load the images
- Class clazz = HoverHelp.class;
- try {
- if (images == null) {
- images = new Image[imageLocations.length];
-
- for (int i = 0; i < imageLocations.length; ++i) {
- InputStream stream = clazz.getResourceAsStream(imageLocations[i]);
- ImageData source = new ImageData(stream);
- ImageData mask = source.getTransparencyMask();
- images[i] = new Image(display, source, mask);
- }
- }
- } catch (Exception ex) {
- System.err.println(getResourceString("error.CouldNotLoadResources",
- new Object[] { ex.getMessage() }));
- return null;
- }
-
- // Create the window
- Shell shell = new Shell();
- createPartControl(shell);
- shell.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- /* Free resources */
- if (images != null) {
- for (int i = 0; i < images.length; i++) {
- final Image image = images[i];
- if (image != null) image.dispose();
- }
- images = null;
- }
- }
- });
- shell.pack();
- shell.open();
- return shell;
- }
-
- /**
- * Gets a string from the resource bundle.
- * We don't want to crash because of a missing String.
- * Returns the key if not found.
- */
- public String getResourceString(String key) {
- try {
- return resourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Gets a string from the resource bundle and binds it
- * with the given arguments. If the key is not found,
- * return the key.
- */
- public String getResourceString(String key, Object[] args) {
- try {
- return MessageFormat.format(getResourceString(key), args);
- } catch (MissingResourceException e) {
- return key;
- } catch (NullPointerException e) {
- return "!" + key + "!";
- }
- }
-
- /**
- * Creates the example
- */
- public void createPartControl(Composite frame) {
- final ToolTipHandler tooltip = new ToolTipHandler(frame.getShell());
-
- GridLayout layout = new GridLayout();
- layout.numColumns = 3;
- frame.setLayout(layout);
-
- ToolBar bar = new ToolBar (frame, SWT.BORDER);
- for (int i=0; i<5; i++) {
- ToolItem item = new ToolItem (bar, SWT.PUSH);
- item.setText (getResourceString("ToolItem.text", new Object[] { new Integer(i) }));
- item.setData ("TIP_TEXT", getResourceString("ToolItem.tooltip",
- new Object[] { item.getText() }));
- item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() {
- public String getHelpText(Widget widget) {
- Item item = (Item) widget;
- return getResourceString("ToolItem.help", new Object[] { item.getText() });
- }
- });
- }
- GridData gridData = new GridData();
- gridData.horizontalSpan = 3;
- bar.setLayoutData(gridData);
- tooltip.activateHoverHelp(bar);
-
- Table table = new Table (frame, SWT.BORDER);
- for (int i=0; i<4; i++) {
- TableItem item = new TableItem (table, SWT.PUSH);
- item.setText (getResourceString("Item", new Object[] { new Integer(i) }));
- item.setData ("TIP_IMAGE", images[hhiInformation]);
- item.setText (getResourceString("TableItem.text", new Object[] { new Integer(i) }));
- item.setData ("TIP_TEXT", getResourceString("TableItem.tooltip",
- new Object[] { item.getText() }));
- item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() {
- public String getHelpText(Widget widget) {
- Item item = (Item) widget;
- return getResourceString("TableItem.help", new Object[] { item.getText() });
- }
- });
- }
- table.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL));
- tooltip.activateHoverHelp(table);
-
- Tree tree = new Tree (frame, SWT.BORDER);
- for (int i=0; i<4; i++) {
- TreeItem item = new TreeItem (tree, SWT.PUSH);
- item.setText (getResourceString("Item", new Object[] { new Integer(i) }));
- item.setData ("TIP_IMAGE", images[hhiWarning]);
- item.setText (getResourceString("TreeItem.text", new Object[] { new Integer(i) }));
- item.setData ("TIP_TEXT", getResourceString("TreeItem.tooltip",
- new Object[] { item.getText() }));
- item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() {
- public String getHelpText(Widget widget) {
- Item item = (Item) widget;
- return getResourceString("TreeItem.help", new Object[] { item.getText() });
- }
- });
- }
- tree.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL));
- tooltip.activateHoverHelp(tree);
-
- Button button = new Button (frame, SWT.PUSH);
- button.setText (getResourceString("Hello.text"));
- button.setData ("TIP_TEXT", getResourceString("Hello.tooltip"));
- tooltip.activateHoverHelp(button);
- }
-
- /**
- * Emulated tooltip handler
- * Notice that we could display anything in a tooltip besides text and images.
- * For instance, it might make sense to embed large tables of data or buttons linking
- * data under inspection to material elsewhere, or perform dynamic lookup for creating
- * tooltip text on the fly.
- */
- protected static class ToolTipHandler {
- private Shell parentShell;
- private Shell tipShell;
- private Label tipLabelImage, tipLabelText;
- private Widget tipWidget; // widget this tooltip is hovering over
- private Point tipPosition; // the position being hovered over
-
- /**
- * Creates a new tooltip handler
- *
- * @param parent the parent Shell
- */
- public ToolTipHandler(Shell parent) {
- final Display display = parent.getDisplay();
- this.parentShell = parent;
-
- tipShell = new Shell(parent, SWT.ON_TOP);
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 2;
- gridLayout.marginWidth = 2;
- gridLayout.marginHeight = 2;
- tipShell.setLayout(gridLayout);
-
- tipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
-
- tipLabelImage = new Label(tipShell, SWT.NONE);
- tipLabelImage.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- tipLabelImage.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- tipLabelImage.setLayoutData(new GridData(GridData.FILL_HORIZONTAL |
- GridData.VERTICAL_ALIGN_CENTER));
-
- tipLabelText = new Label(tipShell, SWT.NONE);
- tipLabelText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- tipLabelText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- tipLabelText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL |
- GridData.VERTICAL_ALIGN_CENTER));
- }
-
- /**
- * Enables customized hover help for a specified control
- *
- * @control the control on which to enable hoverhelp
- */
- public void activateHoverHelp(final Control control) {
- /*
- * Get out of the way if we attempt to activate the control underneath the tooltip
- */
- control.addMouseListener(new MouseAdapter () {
- public void mouseDown (MouseEvent e) {
- if (tipShell.isVisible()) tipShell.setVisible(false);
- }
- });
-
- /*
- * Trap hover events to pop-up tooltip
- */
- control.addMouseTrackListener(new MouseTrackAdapter () {
- public void mouseExit(MouseEvent e) {
- if (tipShell.isVisible()) tipShell.setVisible(false);
- tipWidget = null;
- }
- public void mouseHover (MouseEvent event) {
- Point pt = new Point (event.x, event.y);
- Widget widget = event.widget;
- if (widget instanceof ToolBar) {
- ToolBar w = (ToolBar) widget;
- widget = w.getItem (pt);
- }
- if (widget instanceof Table) {
- Table w = (Table) widget;
- widget = w.getItem (pt);
- }
- if (widget instanceof Tree) {
- Tree w = (Tree) widget;
- widget = w.getItem (pt);
- }
- if (widget == null) {
- tipShell.setVisible(false);
- tipWidget = null;
- return;
- }
- if (widget == tipWidget) return;
- tipWidget = widget;
- tipPosition = control.toDisplay(pt);
- String text = (String) widget.getData("TIP_TEXT");
- Image image = (Image) widget.getData("TIP_IMAGE");
- tipLabelText.setText(text != null ? text : "");
- tipLabelImage.setImage(image); // accepts null
- tipShell.pack();
- setHoverLocation(tipShell, tipPosition);
- tipShell.setVisible(true);
- }
- });
-
- /*
- * Trap F1 Help to pop up a custom help box
- */
- control.addHelpListener(new HelpListener () {
- public void helpRequested(HelpEvent event) {
- if (tipWidget == null) return;
- ToolTipHelpTextHandler handler = (ToolTipHelpTextHandler)
- tipWidget.getData("TIP_HELPTEXTHANDLER");
- if (handler == null) return;
- String text = handler.getHelpText(tipWidget);
- if (text == null) return;
-
- if (tipShell.isVisible()) {
- tipShell.setVisible(false);
- Shell helpShell = new Shell(parentShell, SWT.SHELL_TRIM);
- helpShell.setLayout(new FillLayout());
- Label label = new Label(helpShell, SWT.NONE);
- label.setText(text);
- helpShell.pack();
- setHoverLocation(helpShell, tipPosition);
- helpShell.open();
- }
- }
- });
- }
-
- /**
- * Sets the location for a hovering shell
- * @param shell the object that is to hover
- * @param position the position of a widget to hover over
- * @return the top-left location for a hovering box
- */
- private void setHoverLocation(Shell shell, Point position) {
- Rectangle displayBounds = shell.getDisplay().getBounds();
- Rectangle shellBounds = shell.getBounds();
- shellBounds.x = Math.max(Math.min(position.x, displayBounds.width - shellBounds.width), 0);
- shellBounds.y = Math.max(Math.min(position.y + 16, displayBounds.height - shellBounds.height), 0);
- shell.setBounds(shellBounds);
- }
- }
-
- /**
- * ToolTip help handler
- */
- protected interface ToolTipHelpTextHandler {
- /**
- * Get help text
- * @param widget the widget that is under help
- * @return a help text string
- */
- public String getHelpText(Widget widget);
- }
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import java.io.*; import java.text.*; import java.util.*; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*;
+/**
+ * This example demonstrates how to implement hover help feedback
+ * using the MouseTrackListener.
+ */
+public class HoverHelp {
+ private static ResourceBundle resourceBundle = ResourceBundle.getBundle("examples_hoverhelp");;
+
+ static final int
+ hhiInformation = 0,
+ hhiWarning = 1;
+ static final String[] imageLocations = {
+ "information.gif",
+ "warning.gif"
+ };
+ Image images[];
+
+ /**
+ * Runs main program.
+ */
+ public static void main (String [] args) {
+ Display display = new Display();
+ Shell shell = new HoverHelp().open(display);
+ // Event loop
+ while (shell != null && ! shell.isDisposed()) {
+ if (! display.readAndDispatch()) display.sleep();
+ }
+ // Cleanup
+ display.dispose();
+
+ }
+
+ /**
+ * Opens the main program.
+ */
+ public Shell open(Display display) {
+ // Load the images
+ Class clazz = HoverHelp.class;
+ try {
+ if (images == null) {
+ images = new Image[imageLocations.length];
+
+ for (int i = 0; i < imageLocations.length; ++i) {
+ InputStream stream = clazz.getResourceAsStream(imageLocations[i]);
+ ImageData source = new ImageData(stream);
+ ImageData mask = source.getTransparencyMask();
+ images[i] = new Image(display, source, mask);
+ }
+ }
+ } catch (Exception ex) {
+ System.err.println(getResourceString("error.CouldNotLoadResources",
+ new Object[] { ex.getMessage() }));
+ return null;
+ }
+
+ // Create the window
+ Shell shell = new Shell();
+ createPartControl(shell);
+ shell.addDisposeListener(new DisposeListener() {
+ public void widgetDisposed(DisposeEvent e) {
+ /* Free resources */
+ if (images != null) {
+ for (int i = 0; i < images.length; i++) {
+ final Image image = images[i];
+ if (image != null) image.dispose();
+ }
+ images = null;
+ }
+ }
+ });
+ shell.pack();
+ shell.open();
+ return shell;
+ }
+
+ /**
+ * Gets a string from the resource bundle.
+ * We don't want to crash because of a missing String.
+ * Returns the key if not found.
+ */
+ public String getResourceString(String key) {
+ try {
+ return resourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Gets a string from the resource bundle and binds it
+ * with the given arguments. If the key is not found,
+ * return the key.
+ */
+ public String getResourceString(String key, Object[] args) {
+ try {
+ return MessageFormat.format(getResourceString(key), args);
+ } catch (MissingResourceException e) {
+ return key;
+ } catch (NullPointerException e) {
+ return "!" + key + "!";
+ }
+ }
+
+ /**
+ * Creates the example
+ */
+ public void createPartControl(Composite frame) {
+ final ToolTipHandler tooltip = new ToolTipHandler(frame.getShell());
+
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 3;
+ frame.setLayout(layout);
+
+ ToolBar bar = new ToolBar (frame, SWT.BORDER);
+ for (int i=0; i<5; i++) {
+ ToolItem item = new ToolItem (bar, SWT.PUSH);
+ item.setText (getResourceString("ToolItem.text", new Object[] { new Integer(i) }));
+ item.setData ("TIP_TEXT", getResourceString("ToolItem.tooltip",
+ new Object[] { item.getText() }));
+ item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() {
+ public String getHelpText(Widget widget) {
+ Item item = (Item) widget;
+ return getResourceString("ToolItem.help", new Object[] { item.getText() });
+ }
+ });
+ }
+ GridData gridData = new GridData();
+ gridData.horizontalSpan = 3;
+ bar.setLayoutData(gridData);
+ tooltip.activateHoverHelp(bar);
+
+ Table table = new Table (frame, SWT.BORDER);
+ for (int i=0; i<4; i++) {
+ TableItem item = new TableItem (table, SWT.PUSH);
+ item.setText (getResourceString("Item", new Object[] { new Integer(i) }));
+ item.setData ("TIP_IMAGE", images[hhiInformation]);
+ item.setText (getResourceString("TableItem.text", new Object[] { new Integer(i) }));
+ item.setData ("TIP_TEXT", getResourceString("TableItem.tooltip",
+ new Object[] { item.getText() }));
+ item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() {
+ public String getHelpText(Widget widget) {
+ Item item = (Item) widget;
+ return getResourceString("TableItem.help", new Object[] { item.getText() });
+ }
+ });
+ }
+ table.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL));
+ tooltip.activateHoverHelp(table);
+
+ Tree tree = new Tree (frame, SWT.BORDER);
+ for (int i=0; i<4; i++) {
+ TreeItem item = new TreeItem (tree, SWT.PUSH);
+ item.setText (getResourceString("Item", new Object[] { new Integer(i) }));
+ item.setData ("TIP_IMAGE", images[hhiWarning]);
+ item.setText (getResourceString("TreeItem.text", new Object[] { new Integer(i) }));
+ item.setData ("TIP_TEXT", getResourceString("TreeItem.tooltip",
+ new Object[] { item.getText() }));
+ item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() {
+ public String getHelpText(Widget widget) {
+ Item item = (Item) widget;
+ return getResourceString("TreeItem.help", new Object[] { item.getText() });
+ }
+ });
+ }
+ tree.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL));
+ tooltip.activateHoverHelp(tree);
+
+ Button button = new Button (frame, SWT.PUSH);
+ button.setText (getResourceString("Hello.text"));
+ button.setData ("TIP_TEXT", getResourceString("Hello.tooltip"));
+ tooltip.activateHoverHelp(button);
+ }
+
+ /**
+ * Emulated tooltip handler
+ * Notice that we could display anything in a tooltip besides text and images.
+ * For instance, it might make sense to embed large tables of data or buttons linking
+ * data under inspection to material elsewhere, or perform dynamic lookup for creating
+ * tooltip text on the fly.
+ */
+ protected static class ToolTipHandler {
+ private Shell parentShell;
+ private Shell tipShell;
+ private Label tipLabelImage, tipLabelText;
+ private Widget tipWidget; // widget this tooltip is hovering over
+ private Point tipPosition; // the position being hovered over
+
+ /**
+ * Creates a new tooltip handler
+ *
+ * @param parent the parent Shell
+ */
+ public ToolTipHandler(Shell parent) {
+ final Display display = parent.getDisplay();
+ this.parentShell = parent;
+
+ tipShell = new Shell(parent, SWT.ON_TOP);
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 2;
+ gridLayout.marginWidth = 2;
+ gridLayout.marginHeight = 2;
+ tipShell.setLayout(gridLayout);
+
+ tipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+
+ tipLabelImage = new Label(tipShell, SWT.NONE);
+ tipLabelImage.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ tipLabelImage.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ tipLabelImage.setLayoutData(new GridData(GridData.FILL_HORIZONTAL |
+ GridData.VERTICAL_ALIGN_CENTER));
+
+ tipLabelText = new Label(tipShell, SWT.NONE);
+ tipLabelText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ tipLabelText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ tipLabelText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL |
+ GridData.VERTICAL_ALIGN_CENTER));
+ }
+
+ /**
+ * Enables customized hover help for a specified control
+ *
+ * @control the control on which to enable hoverhelp
+ */
+ public void activateHoverHelp(final Control control) {
+ /*
+ * Get out of the way if we attempt to activate the control underneath the tooltip
+ */
+ control.addMouseListener(new MouseAdapter () {
+ public void mouseDown (MouseEvent e) {
+ if (tipShell.isVisible()) tipShell.setVisible(false);
+ }
+ });
+
+ /*
+ * Trap hover events to pop-up tooltip
+ */
+ control.addMouseTrackListener(new MouseTrackAdapter () {
+ public void mouseExit(MouseEvent e) {
+ if (tipShell.isVisible()) tipShell.setVisible(false);
+ tipWidget = null;
+ }
+ public void mouseHover (MouseEvent event) {
+ Point pt = new Point (event.x, event.y);
+ Widget widget = event.widget;
+ if (widget instanceof ToolBar) {
+ ToolBar w = (ToolBar) widget;
+ widget = w.getItem (pt);
+ }
+ if (widget instanceof Table) {
+ Table w = (Table) widget;
+ widget = w.getItem (pt);
+ }
+ if (widget instanceof Tree) {
+ Tree w = (Tree) widget;
+ widget = w.getItem (pt);
+ }
+ if (widget == null) {
+ tipShell.setVisible(false);
+ tipWidget = null;
+ return;
+ }
+ if (widget == tipWidget) return;
+ tipWidget = widget;
+ tipPosition = control.toDisplay(pt);
+ String text = (String) widget.getData("TIP_TEXT");
+ Image image = (Image) widget.getData("TIP_IMAGE");
+ tipLabelText.setText(text != null ? text : "");
+ tipLabelImage.setImage(image); // accepts null
+ tipShell.pack();
+ setHoverLocation(tipShell, tipPosition);
+ tipShell.setVisible(true);
+ }
+ });
+
+ /*
+ * Trap F1 Help to pop up a custom help box
+ */
+ control.addHelpListener(new HelpListener () {
+ public void helpRequested(HelpEvent event) {
+ if (tipWidget == null) return;
+ ToolTipHelpTextHandler handler = (ToolTipHelpTextHandler)
+ tipWidget.getData("TIP_HELPTEXTHANDLER");
+ if (handler == null) return;
+ String text = handler.getHelpText(tipWidget);
+ if (text == null) return;
+
+ if (tipShell.isVisible()) {
+ tipShell.setVisible(false);
+ Shell helpShell = new Shell(parentShell, SWT.SHELL_TRIM);
+ helpShell.setLayout(new FillLayout());
+ Label label = new Label(helpShell, SWT.NONE);
+ label.setText(text);
+ helpShell.pack();
+ setHoverLocation(helpShell, tipPosition);
+ helpShell.open();
+ }
+ }
+ });
+ }
+
+ /**
+ * Sets the location for a hovering shell
+ * @param shell the object that is to hover
+ * @param position the position of a widget to hover over
+ * @return the top-left location for a hovering box
+ */
+ private void setHoverLocation(Shell shell, Point position) {
+ Rectangle displayBounds = shell.getDisplay().getBounds();
+ Rectangle shellBounds = shell.getBounds();
+ shellBounds.x = Math.max(Math.min(position.x, displayBounds.width - shellBounds.width), 0);
+ shellBounds.y = Math.max(Math.min(position.y + 16, displayBounds.height - shellBounds.height), 0);
+ shell.setBounds(shellBounds);
+ }
+ }
+
+ /**
+ * ToolTip help handler
+ */
+ protected interface ToolTipHelpTextHandler {
+ /**
+ * Get help text
+ * @param widget the widget that is under help
+ * @return a help text string
+ */
+ public String getHelpText(Widget widget);
+ }
} \ No newline at end of file
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/imageanalyzer/ImageAnalyzer.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/imageanalyzer/ImageAnalyzer.java
index 27e2f925b6..587498a0c2 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/imageanalyzer/ImageAnalyzer.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/imageanalyzer/ImageAnalyzer.java
@@ -1,2076 +1,2076 @@
-package org.eclipse.swt.examples.imageanalyzer;
-
-/*
+package org.eclipse.swt.examples.imageanalyzer;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.widgets.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.printing.*;
-import org.eclipse.swt.custom.*;
-import java.util.*;
-import java.net.*;
-import java.io.*;
-import java.text.MessageFormat;
-
-public class ImageAnalyzer {
- static ResourceBundle bundle = ResourceBundle.getBundle("examples_images");
- Display display;
- Shell shell;
- Canvas imageCanvas, paletteCanvas;
- Label typeLabel, sizeLabel, depthLabel, transparentPixelLabel,
- timeToLoadLabel, screenSizeLabel, backgroundPixelLabel,
- locationLabel, disposalMethodLabel, delayTimeLabel,
- repeatCountLabel, paletteLabel, dataLabel, statusLabel;
- Combo backgroundCombo, scaleXCombo, scaleYCombo, alphaCombo;
- Button incrementalCheck, transparentCheck, maskCheck, backgroundCheck;
- Button previousButton, nextButton, animateButton;
- StyledText dataText;
- Sash sash;
- Color whiteColor, blackColor, redColor, greenColor, blueColor, canvasBackground;
- Font fixedWidthFont;
- Cursor crossCursor;
- GC imageCanvasGC;
-
- int paletteWidth = 140; // recalculated and used as a width hint
- int ix = 0, iy = 0, py = 0; // used to scroll the image and palette
- float xscale = 1, yscale = 1; // used to scale the image
- int alpha = 255; // used to modify the alpha value of the image
- boolean incremental = false; // used to incrementally display an image
- boolean transparent = true; // used to display an image with transparency
- boolean showMask = false; // used to display an icon mask or transparent image mask
- boolean showBackground = false; // used to display the background of an animated image
- boolean animate = false; // used to animate a multi-image file
- Thread animateThread; // draws animated images
- Thread incrementalThread; // draws incremental images
- String lastPath; // used to seed the file dialog
- String currentName; // the current image file or URL name
- String fileName; // the current image file
- ImageLoader loader; // the loader for the current image file
- ImageData[] imageDataArray; // all image data read from the current file
- int imageDataIndex; // the index of the current image data
- ImageData imageData; // the currently-displayed image data
- Image image; // the currently-displayed image
- Vector incrementalEvents; // incremental image events
- long loadTime = 0; // the time it took to load the current image
-
- static final int INDEX_DIGITS = 4;
- static final int ALPHA_CONSTANT = 0;
- static final int ALPHA_X = 1;
- static final int ALPHA_Y = 2;
-
- class TextPrompter extends Dialog {
- String message = "";
- String result = null;
- Shell dialog;
- Text text;
- public TextPrompter (Shell parent, int style) {
- super (parent, style);
- }
- public TextPrompter (Shell parent) {
- this (parent, SWT.APPLICATION_MODAL);
- }
- public String getMessage () {
- return message;
- }
- public void setMessage (String string) {
- message = string;
- }
- public String open () {
- dialog = new Shell(getParent(), getStyle());
- dialog.setText(getText());
- dialog.setLayout(new GridLayout());
- Label label = new Label(dialog, SWT.NULL);
- label.setText(message);
- label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- text = new Text(dialog, SWT.SINGLE | SWT.BORDER);
- GridData data = new GridData(GridData.FILL_HORIZONTAL);
- data.widthHint = 300;
- text.setLayoutData(data);
- Composite buttons = new Composite(dialog, SWT.NONE);
- GridLayout grid = new GridLayout();
- grid.numColumns = 2;
- buttons.setLayout(grid);
- buttons.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
- Button ok = new Button(buttons, SWT.PUSH);
- ok.setText(bundle.getString("OK"));
- data = new GridData();
- data.widthHint = 75;
- ok.setLayoutData(data);
- ok.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- result = text.getText();
- dialog.dispose();
- }
- });
- Button cancel = new Button(buttons, SWT.PUSH);
- cancel.setText(bundle.getString("Cancel"));
- data = new GridData();
- data.widthHint = 75;
- cancel.setLayoutData(data);
- cancel.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- dialog.dispose();
- }
- });
- dialog.setDefaultButton(ok);
- dialog.pack();
- dialog.open();
- while (!dialog.isDisposed()) {
- if (!display.readAndDispatch()) display.sleep();
- }
- return result;
- }
- }
-
- public static void main(String [] args) {
- Display display = new Display();
- ImageAnalyzer imageAnalyzer = new ImageAnalyzer();
- Shell shell = imageAnalyzer.open(display);
-
- while (!shell.isDisposed())
- if (!display.readAndDispatch()) display.sleep();
- display.dispose();
- }
-
- public Shell open(Display dpy) {
- // Create a window and set its title.
- this.display = dpy;
- shell = new Shell(display);
- shell.setText(bundle.getString("Image_analyzer"));
-
- // Hook resize and dispose listeners.
- shell.addControlListener(new ControlAdapter() {
- public void controlResized(ControlEvent event) {
- resizeShell(event);
- }
- });
- shell.addShellListener(new ShellAdapter() {
- public void shellClosed(ShellEvent e) {
- animate = false; // stop any animation in progress
- if (animateThread != null) {
- // wait for the thread to die before disposing the shell.
- while (animateThread.isAlive()) {
- if (!display.readAndDispatch()) display.sleep();
- }
- }
- e.doit = true;
- }
- });
- shell.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- // Clean up.
- if (image != null)
- image.dispose();
- whiteColor.dispose();
- blackColor.dispose();
- redColor.dispose();
- greenColor.dispose();
- blueColor.dispose();
- fixedWidthFont.dispose();
- crossCursor.dispose();
- }
- });
-
- // Create colors and fonts.
- whiteColor = new Color(display, 255, 255, 255);
- blackColor = new Color(display, 0, 0, 0);
- redColor = new Color(display, 255, 0, 0);
- greenColor = new Color(display, 0, 255, 0);
- blueColor = new Color(display, 0, 0, 255);
- fixedWidthFont = new Font(display, "courier", 10, 0);
- crossCursor = new Cursor(display, SWT.CURSOR_CROSS);
-
- // Add a menu bar and widgets.
- createMenuBar();
- createWidgets();
- shell.pack();
-
- // Create a GC for drawing, and hook the listener to dispose it.
- imageCanvasGC = new GC(imageCanvas);
- imageCanvas.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- imageCanvasGC.dispose();
- }
- });
-
- // Open the window
- shell.open();
- return shell;
- }
-
- void createWidgets() {
- // Add the widgets to the shell in a grid layout.
- GridLayout layout = new GridLayout();
- layout.marginHeight = 0;
- layout.numColumns = 2;
- shell.setLayout(layout);
-
- // Separate the menu bar from the rest of the widgets.
- Label separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gridData = new GridData();
- gridData.horizontalSpan = 2;
- gridData.horizontalAlignment = GridData.FILL;
- separator.setLayoutData(gridData);
-
- // Add a composite to contain some control widgets across the top.
- Composite controls = new Composite(shell, SWT.NULL);
- RowLayout rowLayout = new RowLayout();
- rowLayout.marginTop = 0;
- rowLayout.marginBottom = 5;
- rowLayout.spacing = 8;
- controls.setLayout(rowLayout);
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- controls.setLayoutData(gridData);
-
- // Combo to change the background.
- Group group = new Group(controls, SWT.NULL);
- group.setLayout(new RowLayout());
- group.setText(bundle.getString("Background"));
- backgroundCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
- backgroundCombo.setItems(new String[] {
- bundle.getString("None"),
- bundle.getString("White"),
- bundle.getString("Black"),
- bundle.getString("Red"),
- bundle.getString("Green"),
- bundle.getString("Blue")});
- backgroundCombo.select(backgroundCombo.indexOf(bundle.getString("White")));
- backgroundCombo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- changeBackground();
- }
- });
-
- // Combo to change the x scale.
- String[] values = {
- "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1",
- "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "2",
- "3", "4", "5", "6", "7", "8", "9", "10",};
- group = new Group(controls, SWT.NULL);
- group.setLayout(new RowLayout());
- group.setText(bundle.getString("X_scale"));
- scaleXCombo = new Combo(group, SWT.DROP_DOWN);
- for (int i = 0; i < values.length; i++) {
- scaleXCombo.add(values[i]);
- }
- scaleXCombo.select(scaleXCombo.indexOf("1"));
- scaleXCombo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- scaleX();
- }
- });
-
- // Combo to change the y scale.
- group = new Group(controls, SWT.NULL);
- group.setLayout(new RowLayout());
- group.setText(bundle.getString("Y_scale"));
- scaleYCombo = new Combo(group, SWT.DROP_DOWN);
- for (int i = 0; i < values.length; i++) {
- scaleYCombo.add(values[i]);
- }
- scaleYCombo.select(scaleYCombo.indexOf("1"));
- scaleYCombo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- scaleY();
- }
- });
-
- // Combo to change the alpha value.
- group = new Group(controls, SWT.NULL);
- group.setLayout(new RowLayout());
- group.setText(bundle.getString("Alpha_K"));
- alphaCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
- for (int i = 0; i <= 255; i += 5) {
- alphaCombo.add(String.valueOf(i));
- }
- alphaCombo.select(alphaCombo.indexOf("255"));
- alphaCombo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- alpha();
- }
- });
-
- // Check box to request incremental display.
- group = new Group(controls, SWT.NULL);
- group.setLayout(new RowLayout());
- group.setText(bundle.getString("Display"));
- incrementalCheck = new Button(group, SWT.CHECK);
- incrementalCheck.setText(bundle.getString("Incremental"));
- incrementalCheck.setSelection(incremental);
- incrementalCheck.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- incremental = ((Button)event.widget).getSelection();
- }
- });
-
- // Check box to request transparent display.
- transparentCheck = new Button(group, SWT.CHECK);
- transparentCheck.setText(bundle.getString("Transparent"));
- transparentCheck.setSelection(transparent);
- transparentCheck.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- transparent = ((Button)event.widget).getSelection();
- if (image != null) {
- imageCanvas.redraw();
- }
- }
- });
-
- // Check box to request mask display.
- maskCheck = new Button(group, SWT.CHECK);
- maskCheck.setText(bundle.getString("Mask"));
- maskCheck.setSelection(showMask);
- maskCheck.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- showMask = ((Button)event.widget).getSelection();
- if (image != null) {
- imageCanvas.redraw();
- }
- }
- });
-
- // Check box to request background display.
- backgroundCheck = new Button(group, SWT.CHECK);
- backgroundCheck.setText(bundle.getString("Background"));
- backgroundCheck.setSelection(showBackground);
- backgroundCheck.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- showBackground = ((Button)event.widget).getSelection();
- }
- });
-
- // Group the animation buttons.
- group = new Group(controls, SWT.NULL);
- group.setLayout(new RowLayout());
- group.setText(bundle.getString("Animation"));
-
- // Push button to display the previous image in a multi-image file.
- previousButton = new Button(group, SWT.PUSH);
- previousButton.setText(bundle.getString("Previous"));
- previousButton.setEnabled(false);
- previousButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- previous();
- }
- });
-
- // Push button to display the next image in a multi-image file.
- nextButton = new Button(group, SWT.PUSH);
- nextButton.setText(bundle.getString("Next"));
- nextButton.setEnabled(false);
- nextButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- next();
- }
- });
-
- // Push button to toggle animation of a multi-image file.
- animateButton = new Button(group, SWT.PUSH);
- animateButton.setText(bundle.getString("Animate"));
- animateButton.setEnabled(false);
- animateButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- animate();
- }
- });
-
- // Label to show the image file type.
- typeLabel = new Label(shell, SWT.NULL);
- typeLabel.setText(bundle.getString("Type_initial"));
- typeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Canvas to show the image.
- imageCanvas = new Canvas(shell, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_REDRAW_RESIZE);
- imageCanvas.setBackground(whiteColor);
- imageCanvas.setCursor(crossCursor);
- gridData = new GridData();
- gridData.verticalSpan = 15;
- gridData.horizontalAlignment = GridData.FILL;
- gridData.verticalAlignment = GridData.FILL;
- gridData.grabExcessHorizontalSpace = true;
- gridData.grabExcessVerticalSpace = true;
- imageCanvas.setLayoutData(gridData);
- imageCanvas.addPaintListener(new PaintListener() {
- public void paintControl(PaintEvent event) {
- if (image != null)
- paintImage(event);
- }
- });
- imageCanvas.addMouseMoveListener(new MouseMoveListener() {
- public void mouseMove(MouseEvent event) {
- if (image != null) {
- showColorAt(event.x, event.y);
- }
- }
- });
-
- // Set up the image canvas scroll bars.
- ScrollBar horizontal = imageCanvas.getHorizontalBar();
- horizontal.setVisible(true);
- horizontal.setMinimum(0);
- horizontal.setEnabled(false);
- horizontal.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- scrollHorizontally((ScrollBar)event.widget);
- }
- });
- ScrollBar vertical = imageCanvas.getVerticalBar();
- vertical.setVisible(true);
- vertical.setMinimum(0);
- vertical.setEnabled(false);
- vertical.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- scrollVertically((ScrollBar)event.widget);
- }
- });
-
- // Label to show the image size.
- sizeLabel = new Label(shell, SWT.NULL);
- sizeLabel.setText(bundle.getString("Size_initial"));
- sizeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the image depth.
- depthLabel = new Label(shell, SWT.NULL);
- depthLabel.setText(bundle.getString("Depth_initial"));
- depthLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the transparent pixel.
- transparentPixelLabel = new Label(shell, SWT.NULL);
- transparentPixelLabel.setText(bundle.getString("Transparent_pixel_initial"));
- transparentPixelLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the time to load.
- timeToLoadLabel = new Label(shell, SWT.NULL);
- timeToLoadLabel.setText(bundle.getString("Time_to_load_initial"));
- timeToLoadLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Separate the animation fields from the rest of the fields.
- separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the logical screen size for animation.
- screenSizeLabel = new Label(shell, SWT.NULL);
- screenSizeLabel.setText(bundle.getString("Animation_size_initial"));
- screenSizeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the background pixel.
- backgroundPixelLabel = new Label(shell, SWT.NULL);
- backgroundPixelLabel.setText(bundle.getString("Background_pixel_initial"));
- backgroundPixelLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the image location (x, y).
- locationLabel = new Label(shell, SWT.NULL);
- locationLabel.setText(bundle.getString("Image_location_initial"));
- locationLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the image disposal method.
- disposalMethodLabel = new Label(shell, SWT.NULL);
- disposalMethodLabel.setText(bundle.getString("Disposal_initial"));
- disposalMethodLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the image delay time.
- delayTimeLabel = new Label(shell, SWT.NULL);
- delayTimeLabel.setText(bundle.getString("Delay_initial"));
- delayTimeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show the background pixel.
- repeatCountLabel = new Label(shell, SWT.NULL);
- repeatCountLabel.setText(bundle.getString("Repeats_initial"));
- repeatCountLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Separate the animation fields from the palette.
- separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Label to show if the image has a direct or indexed palette.
- paletteLabel = new Label(shell, SWT.NULL);
- paletteLabel.setText(bundle.getString("Palette_initial"));
- paletteLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // Canvas to show the image's palette.
- paletteCanvas = new Canvas(shell, SWT.BORDER | SWT.V_SCROLL | SWT.NO_REDRAW_RESIZE);
- paletteCanvas.setFont(fixedWidthFont);
- paletteCanvas.getVerticalBar().setVisible(true);
- gridData = new GridData();
- gridData.horizontalAlignment = GridData.FILL;
- gridData.verticalAlignment = GridData.FILL;
- GC gc = new GC(paletteLabel);
- paletteWidth = gc.stringExtent(bundle.getString("Max_length_string")).x;
- gc.dispose();
- gridData.widthHint = paletteWidth;
- gridData.heightHint = 16 * 11; // show at least 16 colors
- paletteCanvas.setLayoutData(gridData);
- paletteCanvas.addPaintListener(new PaintListener() {
- public void paintControl(PaintEvent event) {
- if (image != null)
- paintPalette(event);
- }
- });
-
- // Set up the palette canvas scroll bar.
- vertical = paletteCanvas.getVerticalBar();
- vertical.setVisible(true);
- vertical.setMinimum(0);
- vertical.setIncrement(10);
- vertical.setEnabled(false);
- vertical.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- scrollPalette((ScrollBar)event.widget);
- }
- });
-
- // Sash to see more of image or image data.
- sash = new Sash(shell, SWT.HORIZONTAL);
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- gridData.horizontalAlignment = GridData.FILL;
- sash.setLayoutData(gridData);
- sash.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent event) {
- if (event.detail != SWT.DRAG) {
- ((GridData)paletteCanvas.getLayoutData()).heightHint = SWT.DEFAULT;
- Rectangle paletteCanvasBounds = paletteCanvas.getBounds();
- int minY = paletteCanvasBounds.y + 20;
- Rectangle dataLabelBounds = dataLabel.getBounds();
- int maxY = statusLabel.getBounds().y - dataLabelBounds.height - 20;
- if (event.y > minY && event.y < maxY) {
- Rectangle oldSash = sash.getBounds();
- sash.setBounds(event.x, event.y, event.width, event.height);
- int diff = event.y - oldSash.y;
- Rectangle bounds = imageCanvas.getBounds();
- imageCanvas.setBounds(bounds.x, bounds.y, bounds.width, bounds.height + diff);
- bounds = paletteCanvasBounds;
- paletteCanvas.setBounds(bounds.x, bounds.y, bounds.width, bounds.height + diff);
- bounds = dataLabelBounds;
- dataLabel.setBounds(bounds.x, bounds.y + diff, bounds.width, bounds.height);
- bounds = dataText.getBounds();
- dataText.setBounds(bounds.x, bounds.y + diff, bounds.width, bounds.height - diff);
- //shell.layout(true);
- }
- }
- }
- });
-
- // Label to show data-specific fields.
- dataLabel = new Label(shell, SWT.NULL);
- dataLabel.setText(bundle.getString("Pixel_data_initial"));
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- gridData.horizontalAlignment = GridData.FILL;
- dataLabel.setLayoutData(gridData);
-
- // Text to show a dump of the data.
- dataText = new StyledText(shell, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
- dataText.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
- dataText.setFont(fixedWidthFont);
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- gridData.horizontalAlignment = GridData.FILL;
- gridData.verticalAlignment = GridData.FILL;
- gridData.heightHint = 128;
- gridData.grabExcessVerticalSpace = true;
- dataText.setLayoutData(gridData);
- dataText.addMouseListener(new MouseAdapter() {
- public void mouseDown(MouseEvent event) {
- if (image != null && event.button == 1) {
- showColorForData();
- }
- }
- });
- dataText.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent event) {
- if (image != null) {
- showColorForData();
- }
- }
- });
-
- // Label to show status and cursor location in image.
- statusLabel = new Label(shell, SWT.NULL);
- statusLabel.setText("");
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- gridData.horizontalAlignment = GridData.FILL;
- statusLabel.setLayoutData(gridData);
- }
-
- Menu createMenuBar() {
- // Menu bar.
- Menu menuBar = new Menu(shell, SWT.BAR);
- shell.setMenuBar(menuBar);
- createFileMenu(menuBar);
- createAlphaMenu(menuBar);
- return menuBar;
- }
-
- void createFileMenu(Menu menuBar) {
- // File menu
- MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
- item.setText(bundle.getString("File"));
- Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
- item.setMenu(fileMenu);
-
- // File -> Open File...
- item = new MenuItem(fileMenu, SWT.NULL);
- item.setText(bundle.getString("OpenFile"));
- item.setAccelerator(SWT.MOD1 + 'O');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuOpenFile();
- }
- });
-
- // File -> Open URL...
- item = new MenuItem(fileMenu, SWT.NULL);
- item.setText(bundle.getString("OpenURL"));
- item.setAccelerator(SWT.MOD1 + 'U');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuOpenURL();
- }
- });
-
- // File -> Reopen
- item = new MenuItem(fileMenu, SWT.NULL);
- item.setText(bundle.getString("Reopen"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuReopen();
- }
- });
-
- new MenuItem(fileMenu, SWT.SEPARATOR);
-
- // File -> Save
- item = new MenuItem(fileMenu, SWT.NULL);
- item.setText(bundle.getString("Save"));
- item.setAccelerator(SWT.MOD1 + 'S');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuSave();
- }
- });
-
- // File -> Save As...
- item = new MenuItem(fileMenu, SWT.NULL);
- item.setText(bundle.getString("Save_as"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuSaveAs();
- }
- });
-
- // File -> Save Mask As...
- item = new MenuItem(fileMenu, SWT.NULL);
- item.setText(bundle.getString("Save_mask_as"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuSaveMaskAs();
- }
- });
-
- new MenuItem(fileMenu, SWT.SEPARATOR);
-
- // File -> Print
- item = new MenuItem(fileMenu, SWT.NULL);
- item.setText(bundle.getString("Print"));
- item.setAccelerator(SWT.MOD1 + 'P');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuPrint();
- }
- });
-
- new MenuItem(fileMenu, SWT.SEPARATOR);
-
- // File -> Exit
- item = new MenuItem(fileMenu, SWT.NULL);
- item.setText(bundle.getString("Exit"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- shell.close();
- }
- });
-
- }
-
- void createAlphaMenu(Menu menuBar) {
- // Alpha menu
- MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
- item.setText(bundle.getString("Alpha"));
- Menu alphaMenu = new Menu(shell, SWT.DROP_DOWN);
- item.setMenu(alphaMenu);
-
- // Alpha -> K
- item = new MenuItem(alphaMenu, SWT.NULL);
- item.setText("K");
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuComposeAlpha(ALPHA_CONSTANT);
- }
- });
-
- // Alpha -> (K + x) % 256
- item = new MenuItem(alphaMenu, SWT.NULL);
- item.setText("(K + x) % 256");
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuComposeAlpha(ALPHA_X);
- }
- });
-
- // Alpha -> (K + y) % 256
- item = new MenuItem(alphaMenu, SWT.NULL);
- item.setText("(K + y) % 256");
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- menuComposeAlpha(ALPHA_Y);
- }
- });
- }
-
- void menuComposeAlpha(int alpha_op) {
- if (image == null) return;
- animate = false; // stop any animation in progress
- Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
- imageCanvas.setCursor(waitCursor);
- try {
- if (alpha_op == ALPHA_CONSTANT) {
- imageData.alpha = alpha;
- } else {
- imageData.alpha = -1;
- switch (alpha_op) {
- case ALPHA_X:
- for (int y = 0; y < imageData.height; y++) {
- for (int x = 0; x < imageData.width; x++) {
- imageData.setAlpha(x, y, (x + alpha) % 256);
- }
- }
- break;
- case ALPHA_Y:
- for (int y = 0; y < imageData.height; y++) {
- for (int x = 0; x < imageData.width; x++) {
- imageData.setAlpha(x, y, (y + alpha) % 256);
- }
- }
- break;
- default: break;
- }
- }
- displayImage(imageData);
- } finally {
- shell.setCursor(null);
- imageCanvas.setCursor(crossCursor);
- waitCursor.dispose();
- }
- }
-
- void menuOpenFile() {
- animate = false; // stop any animation in progress
- resetScaleCombos();
-
- // Get the user to choose an image file.
- FileDialog fileChooser = new FileDialog(shell, SWT.OPEN);
- if (lastPath != null)
- fileChooser.setFilterPath(lastPath);
- fileChooser.setFilterExtensions(new String[] { "*.bmp; *.gif; *.ico; *.jpg; *.pcx; *.png; *.tif", "*.bmp", "*.gif", "*.ico", "*.jpg", "*.pcx", "*.png", "*.tif" });
- fileChooser.setFilterNames(new String[] { bundle.getString("All_images") + " (bmp, gif, ico, jpg, pcx, png, tif)",
- "BMP (*.bmp)", "GIF (*.gif)", "ICO (*.ico)", "JPEG (*.jpg)", "PCX (*.pcx)", "PNG (*.png)", "TIFF (*.tif)" });
- String filename = fileChooser.open();
- lastPath = fileChooser.getFilterPath();
- if (filename == null)
- return;
-
- Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
- imageCanvas.setCursor(waitCursor);
- try {
- loader = new ImageLoader();
- if (incremental) {
- // Prepare to handle incremental events.
- loader.addImageLoaderListener(new ImageLoaderListener() {
- public void imageDataLoaded(ImageLoaderEvent event) {
- incrementalDataLoaded(event);
- }
- });
- incrementalThreadStart();
- }
- // Read the new image(s) from the chosen file.
- long startTime = System.currentTimeMillis();
- imageDataArray = loader.load(filename);
- loadTime = System.currentTimeMillis() - startTime;
- if (imageDataArray.length > 0) {
- // Cache the filename.
- currentName = filename;
- fileName = filename;
-
- // If there are multiple images in the file (typically GIF)
- // then enable the Previous, Next and Animate buttons.
- previousButton.setEnabled(imageDataArray.length > 1);
- nextButton.setEnabled(imageDataArray.length > 1);
- animateButton.setEnabled(imageDataArray.length > 1 && loader.logicalScreenWidth > 0 && loader.logicalScreenHeight > 0);
-
- // Display the first image in the file.
- imageDataIndex = 0;
- displayImage(imageDataArray[imageDataIndex]);
- resetScrollBars();
- }
- } catch (SWTException e) {
- showErrorDialog(bundle.getString("Loading_lc"), filename, e);
- } finally {
- shell.setCursor(null);
- imageCanvas.setCursor(crossCursor);
- waitCursor.dispose();
- }
- }
-
- void menuOpenURL() {
- animate = false; // stop any animation in progress
- resetScaleCombos();
-
- // Get the user to choose an image URL.
- TextPrompter textPrompter = new TextPrompter(shell, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
- textPrompter.setText(bundle.getString("OpenURLDialog"));
- textPrompter.setMessage(bundle.getString("EnterURL"));
- String urlname = textPrompter.open();
- if (urlname == null) return;
-
- Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
- imageCanvas.setCursor(waitCursor);
- try {
- URL url = new URL(urlname);
- InputStream stream = url.openStream();
- loader = new ImageLoader();
- if (incremental) {
- // Prepare to handle incremental events.
- loader.addImageLoaderListener(new ImageLoaderListener() {
- public void imageDataLoaded(ImageLoaderEvent event) {
- incrementalDataLoaded(event);
- }
- });
- incrementalThreadStart();
- }
- // Read the new image(s) from the chosen file.
- long startTime = System.currentTimeMillis();
- imageDataArray = loader.load(stream);
- loadTime = System.currentTimeMillis() - startTime;
- if (imageDataArray.length > 0) {
- currentName = urlname;
- fileName = null;
-
- // If there are multiple images in the file (typically GIF)
- // then enable the Previous, Next and Animate buttons.
- previousButton.setEnabled(imageDataArray.length > 1);
- nextButton.setEnabled(imageDataArray.length > 1);
- animateButton.setEnabled(imageDataArray.length > 1 && loader.logicalScreenWidth > 0 && loader.logicalScreenHeight > 0);
-
- // Display the first image in the file.
- imageDataIndex = 0;
- displayImage(imageDataArray[imageDataIndex]);
- resetScrollBars();
- }
- } catch (Exception e) {
- showErrorDialog(bundle.getString("Loading_lc"), urlname, e);
- } finally {
- shell.setCursor(null);
- imageCanvas.setCursor(crossCursor);
- waitCursor.dispose();
- }
- }
-
- /*
- * Called to start a thread that draws incremental images
- * as they are loaded.
- */
- void incrementalThreadStart() {
- incrementalEvents = new Vector();
- incrementalThread = new Thread("Incremental") {
- public void run() {
- // Draw the first ImageData increment.
- while (incrementalEvents != null) {
- // Synchronize so we don't try to remove when the vector is null.
- synchronized (ImageAnalyzer.this) {
- if (incrementalEvents != null) {
- if (incrementalEvents.size() > 0) {
- ImageLoaderEvent event = (ImageLoaderEvent) incrementalEvents.remove(0);
- if (image != null) image.dispose();
- image = new Image(display, event.imageData);
- imageData = event.imageData;
- imageCanvasGC.drawImage(
- image,
- 0,
- 0,
- imageData.width,
- imageData.height,
- imageData.x,
- imageData.y,
- imageData.width,
- imageData.height);
- } else {
- yield();
- }
- }
- }
- }
- display.wake();
- }
- };
- incrementalThread.setDaemon(true);
- incrementalThread.start();
- }
-
- /*
- * Called when incremental image data has been loaded,
- * for example, for interlaced GIF/PNG or progressive JPEG.
- */
- void incrementalDataLoaded(ImageLoaderEvent event) {
- // Synchronize so that we do not try to add while
- // the incremental drawing thread is removing.
- synchronized (this) {
- incrementalEvents.addElement(event);
- }
- }
-
- void menuSave() {
- if (image == null) return;
- animate = false; // stop any animation in progress
-
- // If the image file type is unknown, we can't 'Save',
- // so we have to use 'Save As...'.
- if (imageData.type == SWT.IMAGE_UNDEFINED || fileName == null) {
- menuSaveAs();
- return;
- }
-
- Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
- imageCanvas.setCursor(waitCursor);
- try {
- // Save the current image to the current file.
- loader.data = new ImageData[] {imageData};
- loader.save(fileName, imageData.type);
-
- } catch (SWTException e) {
- showErrorDialog(bundle.getString("Saving_lc"), fileName, e);
- } finally {
- shell.setCursor(null);
- imageCanvas.setCursor(crossCursor);
- waitCursor.dispose();
- }
- }
-
- void menuSaveAs() {
- if (image == null) return;
- animate = false; // stop any animation in progress
-
- // Get the user to choose a file name and type to save.
- FileDialog fileChooser = new FileDialog(shell, SWT.SAVE);
- fileChooser.setFilterPath(lastPath);
- if (fileName != null) fileChooser.setFileName(fileName);
- fileChooser.setFilterExtensions(new String[] { "*.bmp", "*.gif", "*.ico", "*.jpg", "*.png" });
- fileChooser.setFilterNames(new String[] { "BMP (*.bmp)", "GIF (*.gif)", "ICO (*.ico)", "JPEG (*.jpg)", "PNG (*.png)" });
- String filename = fileChooser.open();
- lastPath = fileChooser.getFilterPath();
- if (filename == null)
- return;
-
- // Figure out what file type the user wants saved.
- // We need to rely on the file extension because FileDialog
- // does not have API for asking what filter type was selected.
- int filetype = determineFileType(filename);
- if (filetype == SWT.IMAGE_UNDEFINED) {
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
- box.setMessage(createMsg(bundle.getString("Unknown_extension"),
- filename.substring(filename.lastIndexOf('.') + 1)));
- box.open();
- return;
- }
-
- if (new java.io.File(filename).exists()) {
- MessageBox box = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
- box.setMessage(createMsg(bundle.getString("Overwrite"), filename));
- if (box.open() == SWT.CANCEL)
- return;
- }
-
- Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
- imageCanvas.setCursor(waitCursor);
- try {
- // Save the current image to the specified file.
- loader.data = new ImageData[] {imageData};
- loader.save(filename, filetype);
-
- // Update the shell title and file type label,
- // and use the new file.
- fileName = filename;
- shell.setText(createMsg(bundle.getString("Analyzer_on"), filename));
- typeLabel.setText(createMsg(bundle.getString("Type_string"), fileTypeString(filetype)));
-
- } catch (SWTException e) {
- showErrorDialog(bundle.getString("Saving_lc"), filename, e);
- } finally {
- shell.setCursor(null);
- imageCanvas.setCursor(crossCursor);
- waitCursor.dispose();
- }
- }
-
- void menuSaveMaskAs() {
- if (image == null || !showMask) return;
- if (imageData.getTransparencyType() == SWT.TRANSPARENCY_NONE) return;
- animate = false; // stop any animation in progress
-
- // Get the user to choose a file name and type to save.
- FileDialog fileChooser = new FileDialog(shell, SWT.SAVE);
- fileChooser.setFilterPath(lastPath);
- if (fileName != null) fileChooser.setFileName(fileName);
- fileChooser.setFilterExtensions(new String[] { "*.bmp", "*.gif", "*.ico", "*.jpg", "*.png" });
- fileChooser.setFilterNames(new String[] { "BMP (*.bmp)", "GIF (*.gif)", "ICO (*.ico)", "JPEG (*.jpg)", "PNG (*.png)" });
- String filename = fileChooser.open();
- lastPath = fileChooser.getFilterPath();
- if (filename == null)
- return;
-
- // Figure out what file type the user wants saved.
- // We need to rely on the file extension because FileDialog
- // does not have API for asking what filter type was selected.
- int filetype = determineFileType(filename);
- if (filetype == SWT.IMAGE_UNDEFINED) {
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
- box.setMessage(createMsg(bundle.getString("Unknown_extension"),
- filename.substring(filename.lastIndexOf('.') + 1)));
- box.open();
- return;
- }
-
- if (new java.io.File(filename).exists()) {
- MessageBox box = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
- box.setMessage(createMsg(bundle.getString("Overwrite"), filename));
- if (box.open() == SWT.CANCEL)
- return;
- }
-
- Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
- imageCanvas.setCursor(waitCursor);
- try {
- // Save the mask of the current image to the specified file.
- ImageData maskImageData = imageData.getTransparencyMask();
- loader.data = new ImageData[] {maskImageData};
- loader.save(filename, filetype);
-
- } catch (SWTException e) {
- showErrorDialog(bundle.getString("Saving_lc"), filename, e);
- } finally {
- shell.setCursor(null);
- imageCanvas.setCursor(crossCursor);
- waitCursor.dispose();
- }
- }
-
- void menuPrint() {
- if (image == null) return;
-
- try {
- // Ask the user to specify the printer.
- PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
- PrinterData printerData = dialog.open();
- if (printerData == null) return;
-
- Printer printer = new Printer(printerData);
- Point screenDPI = display.getDPI();
- Point printerDPI = printer.getDPI();
- int scaleFactor = printerDPI.x / screenDPI.x;
- Rectangle trim = printer.computeTrim(0, 0, 0, 0);
- if (printer.startJob(currentName)) {
- if (printer.startPage()) {
- GC gc = new GC(printer);
- int transparentPixel = imageData.transparentPixel;
- if (transparentPixel != -1 && !transparent) {
- imageData.transparentPixel = -1;
- }
- Image printerImage = new Image(printer, imageData);
- gc.drawImage(
- printerImage,
- 0,
- 0,
- imageData.width,
- imageData.height,
- -trim.x,
- -trim.y,
- scaleFactor * imageData.width,
- scaleFactor * imageData.height);
- if (transparentPixel != -1 && !transparent) {
- imageData.transparentPixel = transparentPixel;
- }
- printerImage.dispose();
- gc.dispose();
- printer.endPage();
- }
- printer.endJob();
- }
- printer.dispose();
- } catch (SWTError e) {
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
- box.setMessage(bundle.getString("Printing_error") + e.getMessage());
- box.open();
- }
- }
-
- void menuReopen() {
- if (currentName == null) return;
- animate = false; // stop any animation in progress
- resetScrollBars();
- resetScaleCombos();
- Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
- shell.setCursor(waitCursor);
- imageCanvas.setCursor(waitCursor);
- try {
- loader = new ImageLoader();
- long startTime = System.currentTimeMillis();
- ImageData[] newImageData;
- if (fileName == null) {
- URL url = new URL(currentName);
- InputStream stream = url.openStream();
- newImageData = loader.load(stream);
- } else {
- newImageData = loader.load(fileName);
- }
- loadTime = System.currentTimeMillis() - startTime;
- imageDataIndex = 0;
- displayImage(newImageData[imageDataIndex]);
-
- } catch (Exception e) {
- showErrorDialog(bundle.getString("Reloading_lc"), currentName, e);
- } finally {
- shell.setCursor(null);
- imageCanvas.setCursor(crossCursor);
- waitCursor.dispose();
- }
- }
-
- void changeBackground() {
- String background = backgroundCombo.getText();
- if (background.equals(bundle.getString("White"))) {
- imageCanvas.setBackground(whiteColor);
- } else if (background.equals(bundle.getString("Black"))) {
- imageCanvas.setBackground(blackColor);
- } else if (background.equals(bundle.getString("Red"))) {
- imageCanvas.setBackground(redColor);
- } else if (background.equals(bundle.getString("Green"))) {
- imageCanvas.setBackground(greenColor);
- } else if (background.equals(bundle.getString("Blue"))) {
- imageCanvas.setBackground(blueColor);
- } else {
- imageCanvas.setBackground(null);
- }
- }
-
- /*
- * Called when the ScaleX combo selection changes.
- */
- void scaleX() {
- try {
- xscale = Float.parseFloat(scaleXCombo.getText());
- } catch (NumberFormatException e) {
- xscale = 1;
- scaleXCombo.select(scaleXCombo.indexOf("1"));
- }
- if (image != null) {
- resizeScrollBars();
- imageCanvas.redraw();
- }
- }
-
- /*
- * Called when the ScaleY combo selection changes.
- */
- void scaleY() {
- try {
- yscale = Float.parseFloat(scaleYCombo.getText());
- } catch (NumberFormatException e) {
- yscale = 1;
- scaleYCombo.select(scaleYCombo.indexOf("1"));
- }
- if (image != null) {
- resizeScrollBars();
- imageCanvas.redraw();
- }
- }
-
- /*
- * Called when the Alpha combo selection changes.
- */
- void alpha() {
- try {
- alpha = Integer.parseInt(alphaCombo.getText());
- } catch (NumberFormatException e) {
- alphaCombo.select(alphaCombo.indexOf("255"));
- alpha = 255;
- }
- }
-
- /*
- * Called when the mouse moves in the image canvas.
- * Show the color of the image at the point under the mouse.
- */
- void showColorAt(int mx, int my) {
- int x = mx - imageData.x - ix;
- int y = my - imageData.y - iy;
- showColorForPixel(x, y);
- }
-
- /*
- * Called when a mouse down or key press is detected
- * in the data text. Show the color of the pixel at
- * the caret position in the data text.
- */
- void showColorForData() {
- int delimiterLength = dataText.getLineDelimiter().length();
- int charactersPerLine = 6 + 3 * imageData.bytesPerLine + delimiterLength;
- int position = dataText.getCaretOffset();
- int y = position / charactersPerLine;
- if ((position - y * charactersPerLine) < 6 || ((y + 1) * charactersPerLine - position) <= delimiterLength) {
- statusLabel.setText("");
- return;
- }
- int dataPosition = position - 6 * (y + 1) - delimiterLength * y;
- int byteNumber = dataPosition / 3;
- int where = dataPosition - byteNumber * 3;
- int xByte = byteNumber % imageData.bytesPerLine;
- int x = -1;
- int depth = imageData.depth;
- if (depth == 1) { // 8 pixels per byte (can only show 3 of 8)
- if (where == 0) x = xByte * 8;
- if (where == 1) x = xByte * 8 + 3;
- if (where == 2) x = xByte * 8 + 7;
- }
- if (depth == 2) { // 4 pixels per byte (can only show 3 of 4)
- if (where == 0) x = xByte * 4;
- if (where == 1) x = xByte * 4 + 1;
- if (where == 2) x = xByte * 4 + 3;
- }
- if (depth == 4) { // 2 pixels per byte
- if (where == 0) x = xByte * 2;
- if (where == 1) x = xByte * 2;
- if (where == 2) x = xByte * 2 + 1;
- }
- if (depth == 8) { // 1 byte per pixel
- x = xByte;
- }
- if (depth == 16) { // 2 bytes per pixel
- x = xByte / 2;
- }
- if (depth == 24) { // 3 bytes per pixel
- x = xByte / 3;
- }
- if (depth == 32) { // 4 bytes per pixel
- x = xByte / 4;
- }
- if (x != -1) {
- showColorForPixel(x, y);
- } else {
- statusLabel.setText("");
- }
- }
-
- /*
- * Set the status label to show color information
- * for the specified pixel in the image.
- */
- void showColorForPixel(int x, int y) {
- if (x >= 0 && x < imageData.width && y >= 0 && y < imageData.height) {
- int pixel = imageData.getPixel(x, y);
- RGB rgb = imageData.palette.getRGB(pixel);
-
-
- Object[] args = {new Integer(x),
- new Integer(y),
- new Integer(pixel),
- Integer.toHexString(pixel),
- rgb};
- if (pixel == imageData.transparentPixel) {
- statusLabel.setText(createMsg(bundle.getString("Color_at_trans"), args));
- } else {
- statusLabel.setText(createMsg(bundle.getString("Color_at"), args));
- }
- } else {
- statusLabel.setText("");
- }
- }
-
- /*
- * Called when the Animate button is pressed.
- */
- void animate() {
- animate = !animate;
- if (animate && image != null && imageDataArray.length > 1) {
- animateThread = new Thread(bundle.getString("Animation")) {
- public void run() {
- // Pre-animation widget setup.
- preAnimation();
-
- // Animate.
- try {
- animateLoop();
- } catch (final SWTException e) {
- display.syncExec(new Runnable() {
- public void run() {
- showErrorDialog(createMsg(bundle.getString("Creating_image"),
- new Integer(imageDataIndex+1)),
- currentName, e);
- }
- });
- }
-
- // Post animation widget reset.
- postAnimation();
- }
- };
- animateThread.setDaemon(true);
- animateThread.start();
- }
- }
-
- /*
- * Loop through all of the images in a multi-image file
- * and display them one after another.
- */
- void animateLoop() {
- // Create an off-screen image to draw on, and a GC to draw with.
- // Both are disposed after the animation.
- Image offScreenImage = new Image(display, loader.logicalScreenWidth, loader.logicalScreenHeight);
- GC offScreenImageGC = new GC(offScreenImage);
-
- try {
- // Use syncExec to get the background color of the imageCanvas.
- display.syncExec(new Runnable() {
- public void run() {
- canvasBackground = imageCanvas.getBackground();
- }
- });
-
- // Fill the off-screen image with the background color of the canvas.
- offScreenImageGC.setBackground(canvasBackground);
- offScreenImageGC.fillRectangle(
- 0,
- 0,
- loader.logicalScreenWidth,
- loader.logicalScreenHeight);
-
- // Draw the current image onto the off-screen image.
- offScreenImageGC.drawImage(
- image,
- 0,
- 0,
- imageData.width,
- imageData.height,
- imageData.x,
- imageData.y,
- imageData.width,
- imageData.height);
-
- int repeatCount = loader.repeatCount;
- while (animate && (loader.repeatCount == 0 || repeatCount > 0)) {
- if (imageData.disposalMethod == SWT.DM_FILL_BACKGROUND) {
- // Fill with the background color before drawing.
- Color bgColor = null;
- int backgroundPixel = loader.backgroundPixel;
- if (showBackground && backgroundPixel != -1) {
- // Fill with the background color.
- RGB backgroundRGB = imageData.palette.getRGB(backgroundPixel);
- bgColor = new Color(null, backgroundRGB);
- }
- try {
- offScreenImageGC.setBackground(bgColor != null ? bgColor : canvasBackground);
- offScreenImageGC.fillRectangle(
- imageData.x,
- imageData.y,
- imageData.width,
- imageData.height);
- } finally {
- if (bgColor != null) bgColor.dispose();
- }
- } else if (imageData.disposalMethod == SWT.DM_FILL_PREVIOUS) {
- // Restore the previous image before drawing.
- offScreenImageGC.drawImage(
- image,
- 0,
- 0,
- imageData.width,
- imageData.height,
- imageData.x,
- imageData.y,
- imageData.width,
- imageData.height);
- }
-
- // Get the next image data.
- imageDataIndex = (imageDataIndex + 1) % imageDataArray.length;
- imageData = imageDataArray[imageDataIndex];
- image.dispose();
- image = new Image(display, imageData);
-
- // Draw the new image data.
- offScreenImageGC.drawImage(
- image,
- 0,
- 0,
- imageData.width,
- imageData.height,
- imageData.x,
- imageData.y,
- imageData.width,
- imageData.height);
-
- // Draw the off-screen image to the screen.
- imageCanvasGC.drawImage(offScreenImage, 0, 0);
-
- // Sleep for the specified delay time before drawing again.
- try {
- Thread.sleep(visibleDelay(imageData.delayTime * 10));
- } catch (InterruptedException e) {
- }
-
- // If we have just drawn the last image in the set,
- // then decrement the repeat count.
- if (imageDataIndex == imageDataArray.length - 1) repeatCount--;
- }
- } finally {
- offScreenImage.dispose();
- offScreenImageGC.dispose();
- }
- }
-
- /*
- * Pre animation setup.
- */
- void preAnimation() {
- display.syncExec(new Runnable() {
- public void run() {
- // Change the label of the Animate button to 'Stop'.
- animateButton.setText(bundle.getString("Stop"));
-
- // Disable anything we don't want the user
- // to select during the animation.
- previousButton.setEnabled(false);
- nextButton.setEnabled(false);
- backgroundCombo.setEnabled(false);
- scaleXCombo.setEnabled(false);
- scaleYCombo.setEnabled(false);
- alphaCombo.setEnabled(false);
- incrementalCheck.setEnabled(false);
- transparentCheck.setEnabled(false);
- maskCheck.setEnabled(false);
- // leave backgroundCheck enabled
-
- // Reset the scale combos and scrollbars.
- resetScaleCombos();
- resetScrollBars();
- }
- });
- }
-
- /*
- * Post animation reset.
- */
- void postAnimation() {
- display.syncExec(new Runnable() {
- public void run() {
- // Enable anything we disabled before the animation.
- previousButton.setEnabled(true);
- nextButton.setEnabled(true);
- backgroundCombo.setEnabled(true);
- scaleXCombo.setEnabled(true);
- scaleYCombo.setEnabled(true);
- alphaCombo.setEnabled(true);
- incrementalCheck.setEnabled(true);
- transparentCheck.setEnabled(true);
- maskCheck.setEnabled(true);
-
- // Reset the label of the Animate button.
- animateButton.setText(bundle.getString("Animate"));
-
- if (animate) {
- // If animate is still true, we finished the
- // full number of repeats. Leave the image as-is.
- animate = false;
- } else {
- // Redisplay the current image and its palette.
- displayImage(imageDataArray[imageDataIndex]);
- }
- }
- });
- }
-
- /*
- * Called when the Previous button is pressed.
- * Display the previous image in a multi-image file.
- */
- void previous() {
- if (image != null && imageDataArray.length > 1) {
- if (imageDataIndex == 0) {
- imageDataIndex = imageDataArray.length;
- }
- imageDataIndex = imageDataIndex - 1;
- displayImage(imageDataArray[imageDataIndex]);
- }
- }
-
- /*
- * Called when the Next button is pressed.
- * Display the next image in a multi-image file.
- */
- void next() {
- if (image != null && imageDataArray.length > 1) {
- imageDataIndex = (imageDataIndex + 1) % imageDataArray.length;
- displayImage(imageDataArray[imageDataIndex]);
- }
- }
-
- void displayImage(ImageData newImageData) {
- if (incremental && incrementalThread != null) {
- // Tell the incremental thread to stop drawing.
- synchronized (this) {
- incrementalEvents = null;
- }
-
- // Wait until the incremental thread is done.
- while (incrementalThread.isAlive()) {
- if (!display.readAndDispatch()) display.sleep();
- }
- }
-
- // Dispose of the old image, if there was one.
- if (image != null) image.dispose();
-
- try {
- // Cache the new image and imageData.
- image = new Image(display, newImageData);
- imageData = newImageData;
-
- } catch (SWTException e) {
- showErrorDialog(bundle.getString("Creating_from") + " ", currentName, e);
- image = null;
- return;
- }
-
- // Update the widgets with the new image info.
- String string = createMsg(bundle.getString("Analyzer_on"), currentName);
- shell.setText(string);
-
- if (imageDataArray.length > 1) {
- string = createMsg(bundle.getString("Type_index"),
- new Object[] {fileTypeString(imageData.type),
- new Integer(imageDataIndex + 1),
- new Integer(imageDataArray.length)});
- } else {
- string = createMsg(bundle.getString("Type_string"), fileTypeString(imageData.type));
- }
- typeLabel.setText(string);
-
- string = createMsg(bundle.getString("Size_value"),
- new Object[] {new Integer(imageData.width),
- new Integer(imageData.height)});
- sizeLabel.setText(string);
-
- string = createMsg(bundle.getString("Depth_value"), new Integer(imageData.depth));
- depthLabel.setText(string);
-
- string = createMsg(bundle.getString("Transparent_pixel_value"), pixelInfo(imageData.transparentPixel));
- transparentPixelLabel.setText(string);
-
- string = createMsg(bundle.getString("Time_to_load_value"), new Long(loadTime));
- timeToLoadLabel.setText(string);
-
- string = createMsg(bundle.getString("Animation_size_value"),
- new Object[] {new Integer(loader.logicalScreenWidth),
- new Integer(loader.logicalScreenHeight)});
- screenSizeLabel.setText(string);
-
- string = createMsg(bundle.getString("Background_pixel_value"), pixelInfo(loader.backgroundPixel));
- backgroundPixelLabel.setText(string);
-
- string = createMsg(bundle.getString("Image_location_value"),
- new Object[] {new Integer(imageData.x), new Integer(imageData.y)});
- locationLabel.setText(string);
-
- string = createMsg(bundle.getString("Disposal_value"),
- new Object[] {new Integer(imageData.disposalMethod),
- disposalString(imageData.disposalMethod)});
- disposalMethodLabel.setText(string);
-
- int delay = imageData.delayTime * 10;
- int delayUsed = visibleDelay(delay);
- if (delay != delayUsed) {
- string = createMsg(bundle.getString("Delay_value"),
- new Object[] {new Integer(delay), new Integer(delayUsed)});
- } else {
- string = createMsg(bundle.getString("Delay_used"), new Integer(delay));
- }
- delayTimeLabel.setText(string);
-
- if (loader.repeatCount == 0) {
- string = createMsg( bundle.getString("Repeats_forever"), new Integer(loader.repeatCount));
- } else {
- string = createMsg(bundle.getString("Repeats_value"), new Integer(loader.repeatCount));
- }
- repeatCountLabel.setText(string);
-
-
- if (imageData.palette.isDirect) {
- string = bundle.getString("Palette_direct");
- } else {
- string = createMsg(bundle.getString("Palette_value"), new Integer(imageData.palette.getRGBs().length));
- }
- paletteLabel.setText(string);
-
- string = createMsg(bundle.getString("Pixel_data_value"),
- new Object[] {new Integer(imageData.bytesPerLine),
- new Integer(imageData.scanlinePad),
- depthInfo(imageData.depth)});
- dataLabel.setText(string);
-
- String data = dataHexDump(dataText.getLineDelimiter());
- dataText.setText(data);
-
- // bold the first column all the way down
- int index = 0;
- while((index = data.indexOf(':', index+1)) != -1)
- dataText.setStyleRange(new StyleRange(index - INDEX_DIGITS, INDEX_DIGITS, dataText.getForeground(), dataText.getBackground(), SWT.BOLD));
-
- statusLabel.setText("");
-
- // Redraw both canvases.
- paletteCanvas.redraw();
- imageCanvas.redraw();
- }
-
- void paintImage(PaintEvent event) {
- Image paintImage = image;
- int transparentPixel = imageData.transparentPixel;
- if (transparentPixel != -1 && !transparent) {
- imageData.transparentPixel = -1;
- paintImage = new Image(display, imageData);
- }
- int w = Math.round(imageData.width * xscale);
- int h = Math.round(imageData.height * yscale);
- event.gc.drawImage(
- paintImage,
- 0,
- 0,
- imageData.width,
- imageData.height,
- ix + imageData.x,
- iy + imageData.y,
- w,
- h);
- if (showMask && (imageData.getTransparencyType() != SWT.TRANSPARENCY_NONE)) {
- ImageData maskImageData = imageData.getTransparencyMask();
- Image maskImage = new Image(display, maskImageData);
- event.gc.drawImage(
- maskImage,
- 0,
- 0,
- imageData.width,
- imageData.height,
- w + 10 + ix + imageData.x,
- iy + imageData.y,
- w,
- h);
- maskImage.dispose();
- }
- if (transparentPixel != -1 && !transparent) {
- imageData.transparentPixel = transparentPixel;
- paintImage.dispose();
- }
- }
-
- void paintPalette(PaintEvent event) {
- GC gc = event.gc;
- gc.fillRectangle(paletteCanvas.getClientArea());
- if (imageData.palette.isDirect) {
- // For a direct palette, display the masks.
- int y = py + 10;
- int xTab = 50;
- gc.drawString("rMsk", 10, y, true);
- gc.drawString(toHex4ByteString(imageData.palette.redMask), xTab, y, true);
- gc.drawString("gMsk", 10, y+=12, true);
- gc.drawString(toHex4ByteString(imageData.palette.greenMask), xTab, y, true);
- gc.drawString("bMsk", 10, y+=12, true);
- gc.drawString(toHex4ByteString(imageData.palette.blueMask), xTab, y, true);
- gc.drawString("rShf", 10, y+=12, true);
- gc.drawString(Integer.toString(imageData.palette.redShift), xTab, y, true);
- gc.drawString("gShf", 10, y+=12, true);
- gc.drawString(Integer.toString(imageData.palette.greenShift), xTab, y, true);
- gc.drawString("bShf", 10, y+=12, true);
- gc.drawString(Integer.toString(imageData.palette.blueShift), xTab, y, true);
- } else {
- // For an indexed palette, display the palette colors and indices.
- RGB[] rgbs = imageData.palette.getRGBs();
- if (rgbs != null) {
- int xTab1 = 40, xTab2 = 100;
- for (int i = 0; i < rgbs.length; i++) {
- int y = (i+1) * 10 + py;
- gc.drawString(String.valueOf(i), 10, y, true);
- gc.drawString(toHexByteString(rgbs[i].red) + toHexByteString(rgbs[i].green) + toHexByteString(rgbs[i].blue), xTab1, y, true);
- Color color = new Color(display, rgbs[i]);
- gc.setBackground(color);
- gc.fillRectangle(xTab2, y+2, 10, 10);
- color.dispose();
- }
- }
- }
- }
-
- void resizeShell(ControlEvent event) {
- if (image == null || shell.isDisposed())
- return;
- resizeScrollBars();
- }
-
- // Reset the scale combos to 1.
- void resetScaleCombos() {
- xscale = 1; yscale = 1;
- scaleXCombo.select(scaleXCombo.indexOf("1"));
- scaleYCombo.select(scaleYCombo.indexOf("1"));
- }
-
- // Reset the scroll bars to 0.
- void resetScrollBars() {
- if (image == null) return;
- ix = 0; iy = 0; py = 0;
- resizeScrollBars();
- imageCanvas.getHorizontalBar().setSelection(0);
- imageCanvas.getVerticalBar().setSelection(0);
- paletteCanvas.getVerticalBar().setSelection(0);
- }
-
- void resizeScrollBars() {
- // Set the max and thumb for the image canvas scroll bars.
- ScrollBar horizontal = imageCanvas.getHorizontalBar();
- ScrollBar vertical = imageCanvas.getVerticalBar();
- Rectangle canvasBounds = imageCanvas.getClientArea();
- int width = Math.round(imageData.width * xscale);
- if (width > canvasBounds.width) {
- // The image is wider than the canvas.
- horizontal.setEnabled(true);
- horizontal.setMaximum(width);
- horizontal.setThumb(canvasBounds.width);
- horizontal.setPageIncrement(canvasBounds.width);
- } else {
- // The canvas is wider than the image.
- horizontal.setEnabled(false);
- if (ix != 0) {
- // Make sure the image is completely visible.
- ix = 0;
- imageCanvas.redraw();
- }
- }
- int height = Math.round(imageData.height * yscale);
- if (height > canvasBounds.height) {
- // The image is taller than the canvas.
- vertical.setEnabled(true);
- vertical.setMaximum(height);
- vertical.setThumb(canvasBounds.height);
- vertical.setPageIncrement(canvasBounds.height);
- } else {
- // The canvas is taller than the image.
- vertical.setEnabled(false);
- if (iy != 0) {
- // Make sure the image is completely visible.
- iy = 0;
- imageCanvas.redraw();
- }
- }
-
- // Set the max and thumb for the palette canvas scroll bar.
- vertical = paletteCanvas.getVerticalBar();
- if (imageData.palette.isDirect) {
- vertical.setEnabled(false);
- } else { // indexed palette
- canvasBounds = paletteCanvas.getClientArea();
- int paletteHeight = imageData.palette.getRGBs().length * 10 + 20; // 10 pixels each index + 20 for margins.
- vertical.setEnabled(true);
- vertical.setMaximum(paletteHeight);
- vertical.setThumb(canvasBounds.height);
- vertical.setPageIncrement(canvasBounds.height);
- }
- }
-
- /*
- * Called when the image canvas' horizontal scrollbar is selected.
- */
- void scrollHorizontally(ScrollBar scrollBar) {
- if (image == null) return;
- Rectangle canvasBounds = imageCanvas.getClientArea();
- int width = Math.round(imageData.width * xscale);
- int height = Math.round(imageData.height * yscale);
- if (width > canvasBounds.width) {
- // Only scroll if the image is bigger than the canvas.
- int x = -scrollBar.getSelection();
- if (x + width < canvasBounds.width) {
- // Don't scroll past the end of the image.
- x = canvasBounds.width - width;
- }
- imageCanvas.scroll(x, iy, ix, iy, width, height, false);
- ix = x;
- }
- }
-
- /*
- * Called when the image canvas' vertical scrollbar is selected.
- */
- void scrollVertically(ScrollBar scrollBar) {
- if (image == null) return;
- Rectangle canvasBounds = imageCanvas.getClientArea();
- int width = Math.round(imageData.width * xscale);
- int height = Math.round(imageData.height * yscale);
- if (height > canvasBounds.height) {
- // Only scroll if the image is bigger than the canvas.
- int y = -scrollBar.getSelection();
- if (y + height < canvasBounds.height) {
- // Don't scroll past the end of the image.
- y = canvasBounds.height - height;
- }
- imageCanvas.scroll(ix, y, ix, iy, width, height, false);
- iy = y;
- }
- }
-
- /*
- * Called when the palette canvas' vertical scrollbar is selected.
- */
- void scrollPalette(ScrollBar scrollBar) {
- if (image == null) return;
- Rectangle canvasBounds = paletteCanvas.getClientArea();
- int paletteHeight = imageData.palette.getRGBs().length * 10 + 20;
- if (paletteHeight > canvasBounds.height) {
- // Only scroll if the palette is bigger than the canvas.
- int y = -scrollBar.getSelection();
- if (y + paletteHeight < canvasBounds.height) {
- // Don't scroll past the end of the palette.
- y = canvasBounds.height - paletteHeight;
- }
- paletteCanvas.scroll(0, y, 0, py, paletteWidth, paletteHeight, false);
- py = y;
- }
- }
-
- /*
- * Return a String containing a line-by-line dump of
- * the data in the current imageData. The lineDelimiter
- * parameter must be a string of length 1 or 2.
- */
- String dataHexDump(String lineDelimiter) {
- if (image == null) return "";
- char[] dump = new char[imageData.height * (6 + 3 * imageData.bytesPerLine + lineDelimiter.length())];
- int index = 0;
- for (int i = 0; i < imageData.data.length; i++) {
- if (i % imageData.bytesPerLine == 0) {
- int line = i / imageData.bytesPerLine;
- dump[index++] = Character.forDigit(line / 1000 % 10, 10);
- dump[index++] = Character.forDigit(line / 100 % 10, 10);
- dump[index++] = Character.forDigit(line / 10 % 10, 10);
- dump[index++] = Character.forDigit(line % 10, 10);
- dump[index++] = ':';
- dump[index++] = ' ';
- }
- byte b = imageData.data[i];
- dump[index++] = Character.forDigit((b & 0xF0) >> 4, 16);
- dump[index++] = Character.forDigit(b & 0x0F, 16);
- dump[index++] = ' ';
- if ((i + 1) % imageData.bytesPerLine == 0) {
- dump[index++] = lineDelimiter.charAt(0);
- if (lineDelimiter.length() > 1)
- dump[index++] = lineDelimiter.charAt(1);
- }
- }
- return new String(dump);
- }
-
- /*
- * Open an error dialog displaying the specified information.
- */
- void showErrorDialog(String operation, String filename, Exception e) {
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
- String message = createMsg(bundle.getString("Error"), new String[] {operation, filename});
- String errorMessage = "";
- if (e != null) {
- if (e instanceof SWTException) {
- SWTException swte = (SWTException) e;
- errorMessage = swte.getMessage();
- if (swte.throwable != null) {
- errorMessage += ":\n" + swte.throwable.toString();
- }
- } else {
- errorMessage = e.toString();
- }
- }
- box.setMessage(message + errorMessage);
- box.open();
- }
-
- /*
- * Return a String describing how to analyze the bytes
- * in the hex dump.
- */
- static String depthInfo(int depth) {
- Object[] args = {new Integer(depth), ""};
- switch (depth) {
- case 1:
- args[1] = createMsg(bundle.getString("Multi_pixels"),
- new Object[] {new Integer(8), " [01234567]"});
- break;
- case 2:
- args[1] = createMsg(bundle.getString("Multi_pixels"),
- new Object[] {new Integer(4), "[00112233]"});
- break;
- case 4:
- args[1] = createMsg(bundle.getString("Multi_pixels"),
- new Object[] {new Integer(2), "[00001111]"});
- break;
- case 8:
- args[1] = bundle.getString("One_byte");
- break;
- case 16:
- args[1] = createMsg(bundle.getString("Multi_bytes"), new Integer(2));
- break;
- case 24:
- args[1] = createMsg(bundle.getString("Multi_bytes"), new Integer(3));
- break;
- case 32:
- args[1] = createMsg(bundle.getString("Multi_bytes"), new Integer(4));
- break;
- default:
- args[1] = bundle.getString("Unsupported_lc");
- }
- return createMsg(bundle.getString("Depth_info"), args);
- }
-
- /*
- * Return the specified number of milliseconds.
- * If the specified number of milliseconds is too small
- * to see a visual change, then return a higher number.
- */
- static int visibleDelay(int ms) {
- if (ms < 20) return ms + 30;
- if (ms < 30) return ms + 10;
- return ms;
- }
-
- /*
- * Return the specified byte value as a hex string,
- * preserving leading 0's.
- */
- static String toHexByteString(int i) {
- if (i <= 0x0f)
- return "0" + Integer.toHexString(i);
- return Integer.toHexString(i & 0xff);
- }
-
- /*
- * Return the specified 4-byte value as a hex string,
- * preserving leading 0's.
- * (a bit 'brute force'... should probably use a loop...)
- */
- static String toHex4ByteString(int i) {
- String hex = Integer.toHexString(i);
- if (hex.length() == 1)
- return "0000000" + hex;
- if (hex.length() == 2)
- return "000000" + hex;
- if (hex.length() == 3)
- return "00000" + hex;
- if (hex.length() == 4)
- return "0000" + hex;
- if (hex.length() == 5)
- return "000" + hex;
- if (hex.length() == 6)
- return "00" + hex;
- if (hex.length() == 7)
- return "0" + hex;
- return hex;
- }
-
- /*
- * Return a String describing the specified
- * transparent or background pixel.
- */
- static String pixelInfo(int pixel) {
- if (pixel == -1)
- return pixel + " (" + bundle.getString("None_lc") + ")";
- else
- return pixel + " (0x" + Integer.toHexString(pixel) + ")";
- }
-
- /*
- * Return a String describing the specified disposal method.
- */
- static String disposalString(int disposalMethod) {
- switch (disposalMethod) {
- case SWT.DM_FILL_NONE: return bundle.getString("None_lc");
- case SWT.DM_FILL_BACKGROUND: return bundle.getString("Background_lc");
- case SWT.DM_FILL_PREVIOUS: return bundle.getString("Previous_lc");
- }
- return bundle.getString("Unspecified_lc");
- }
-
- /*
- * Return a String describing the specified image file type.
- */
- static String fileTypeString(int filetype) {
- if (filetype == SWT.IMAGE_BMP)
- return "BMP";
- if (filetype == SWT.IMAGE_GIF)
- return "GIF";
- if (filetype == SWT.IMAGE_ICO)
- return "ICO";
- if (filetype == SWT.IMAGE_JPEG)
- return "JPEG";
- if (filetype == SWT.IMAGE_PNG)
- return "PNG";
- return bundle.getString("Unknown_ac");
- }
-
- /*
- * Return the specified file's image type, based on its extension.
- * Note that this is not a very robust way to determine image type,
- * and it is only to be used in the absence of any better method.
- */
- static int determineFileType(String filename) {
- String ext = filename.substring(filename.lastIndexOf('.') + 1);
- if (ext.equalsIgnoreCase("bmp"))
- return SWT.IMAGE_BMP;
- if (ext.equalsIgnoreCase("gif"))
- return SWT.IMAGE_GIF;
- if (ext.equalsIgnoreCase("ico"))
- return SWT.IMAGE_ICO;
- if (ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg"))
- return SWT.IMAGE_JPEG;
- if (ext.equalsIgnoreCase("png"))
- return SWT.IMAGE_PNG;
- return SWT.IMAGE_UNDEFINED;
- }
-
- static String createMsg(String msg, Object[] args) {
- MessageFormat formatter = new MessageFormat(msg);
- return formatter.format(args);
- }
-
- static String createMsg(String msg, Object arg) {
- MessageFormat formatter = new MessageFormat(msg);
- return formatter.format(new Object[]{arg});
- }
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.widgets.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.printing.*;
+import org.eclipse.swt.custom.*;
+import java.util.*;
+import java.net.*;
+import java.io.*;
+import java.text.MessageFormat;
+
+public class ImageAnalyzer {
+ static ResourceBundle bundle = ResourceBundle.getBundle("examples_images");
+ Display display;
+ Shell shell;
+ Canvas imageCanvas, paletteCanvas;
+ Label typeLabel, sizeLabel, depthLabel, transparentPixelLabel,
+ timeToLoadLabel, screenSizeLabel, backgroundPixelLabel,
+ locationLabel, disposalMethodLabel, delayTimeLabel,
+ repeatCountLabel, paletteLabel, dataLabel, statusLabel;
+ Combo backgroundCombo, scaleXCombo, scaleYCombo, alphaCombo;
+ Button incrementalCheck, transparentCheck, maskCheck, backgroundCheck;
+ Button previousButton, nextButton, animateButton;
+ StyledText dataText;
+ Sash sash;
+ Color whiteColor, blackColor, redColor, greenColor, blueColor, canvasBackground;
+ Font fixedWidthFont;
+ Cursor crossCursor;
+ GC imageCanvasGC;
+
+ int paletteWidth = 140; // recalculated and used as a width hint
+ int ix = 0, iy = 0, py = 0; // used to scroll the image and palette
+ float xscale = 1, yscale = 1; // used to scale the image
+ int alpha = 255; // used to modify the alpha value of the image
+ boolean incremental = false; // used to incrementally display an image
+ boolean transparent = true; // used to display an image with transparency
+ boolean showMask = false; // used to display an icon mask or transparent image mask
+ boolean showBackground = false; // used to display the background of an animated image
+ boolean animate = false; // used to animate a multi-image file
+ Thread animateThread; // draws animated images
+ Thread incrementalThread; // draws incremental images
+ String lastPath; // used to seed the file dialog
+ String currentName; // the current image file or URL name
+ String fileName; // the current image file
+ ImageLoader loader; // the loader for the current image file
+ ImageData[] imageDataArray; // all image data read from the current file
+ int imageDataIndex; // the index of the current image data
+ ImageData imageData; // the currently-displayed image data
+ Image image; // the currently-displayed image
+ Vector incrementalEvents; // incremental image events
+ long loadTime = 0; // the time it took to load the current image
+
+ static final int INDEX_DIGITS = 4;
+ static final int ALPHA_CONSTANT = 0;
+ static final int ALPHA_X = 1;
+ static final int ALPHA_Y = 2;
+
+ class TextPrompter extends Dialog {
+ String message = "";
+ String result = null;
+ Shell dialog;
+ Text text;
+ public TextPrompter (Shell parent, int style) {
+ super (parent, style);
+ }
+ public TextPrompter (Shell parent) {
+ this (parent, SWT.APPLICATION_MODAL);
+ }
+ public String getMessage () {
+ return message;
+ }
+ public void setMessage (String string) {
+ message = string;
+ }
+ public String open () {
+ dialog = new Shell(getParent(), getStyle());
+ dialog.setText(getText());
+ dialog.setLayout(new GridLayout());
+ Label label = new Label(dialog, SWT.NULL);
+ label.setText(message);
+ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ text = new Text(dialog, SWT.SINGLE | SWT.BORDER);
+ GridData data = new GridData(GridData.FILL_HORIZONTAL);
+ data.widthHint = 300;
+ text.setLayoutData(data);
+ Composite buttons = new Composite(dialog, SWT.NONE);
+ GridLayout grid = new GridLayout();
+ grid.numColumns = 2;
+ buttons.setLayout(grid);
+ buttons.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
+ Button ok = new Button(buttons, SWT.PUSH);
+ ok.setText(bundle.getString("OK"));
+ data = new GridData();
+ data.widthHint = 75;
+ ok.setLayoutData(data);
+ ok.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ result = text.getText();
+ dialog.dispose();
+ }
+ });
+ Button cancel = new Button(buttons, SWT.PUSH);
+ cancel.setText(bundle.getString("Cancel"));
+ data = new GridData();
+ data.widthHint = 75;
+ cancel.setLayoutData(data);
+ cancel.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ dialog.dispose();
+ }
+ });
+ dialog.setDefaultButton(ok);
+ dialog.pack();
+ dialog.open();
+ while (!dialog.isDisposed()) {
+ if (!display.readAndDispatch()) display.sleep();
+ }
+ return result;
+ }
+ }
+
+ public static void main(String [] args) {
+ Display display = new Display();
+ ImageAnalyzer imageAnalyzer = new ImageAnalyzer();
+ Shell shell = imageAnalyzer.open(display);
+
+ while (!shell.isDisposed())
+ if (!display.readAndDispatch()) display.sleep();
+ display.dispose();
+ }
+
+ public Shell open(Display dpy) {
+ // Create a window and set its title.
+ this.display = dpy;
+ shell = new Shell(display);
+ shell.setText(bundle.getString("Image_analyzer"));
+
+ // Hook resize and dispose listeners.
+ shell.addControlListener(new ControlAdapter() {
+ public void controlResized(ControlEvent event) {
+ resizeShell(event);
+ }
+ });
+ shell.addShellListener(new ShellAdapter() {
+ public void shellClosed(ShellEvent e) {
+ animate = false; // stop any animation in progress
+ if (animateThread != null) {
+ // wait for the thread to die before disposing the shell.
+ while (animateThread.isAlive()) {
+ if (!display.readAndDispatch()) display.sleep();
+ }
+ }
+ e.doit = true;
+ }
+ });
+ shell.addDisposeListener(new DisposeListener() {
+ public void widgetDisposed(DisposeEvent e) {
+ // Clean up.
+ if (image != null)
+ image.dispose();
+ whiteColor.dispose();
+ blackColor.dispose();
+ redColor.dispose();
+ greenColor.dispose();
+ blueColor.dispose();
+ fixedWidthFont.dispose();
+ crossCursor.dispose();
+ }
+ });
+
+ // Create colors and fonts.
+ whiteColor = new Color(display, 255, 255, 255);
+ blackColor = new Color(display, 0, 0, 0);
+ redColor = new Color(display, 255, 0, 0);
+ greenColor = new Color(display, 0, 255, 0);
+ blueColor = new Color(display, 0, 0, 255);
+ fixedWidthFont = new Font(display, "courier", 10, 0);
+ crossCursor = new Cursor(display, SWT.CURSOR_CROSS);
+
+ // Add a menu bar and widgets.
+ createMenuBar();
+ createWidgets();
+ shell.pack();
+
+ // Create a GC for drawing, and hook the listener to dispose it.
+ imageCanvasGC = new GC(imageCanvas);
+ imageCanvas.addDisposeListener(new DisposeListener() {
+ public void widgetDisposed(DisposeEvent e) {
+ imageCanvasGC.dispose();
+ }
+ });
+
+ // Open the window
+ shell.open();
+ return shell;
+ }
+
+ void createWidgets() {
+ // Add the widgets to the shell in a grid layout.
+ GridLayout layout = new GridLayout();
+ layout.marginHeight = 0;
+ layout.numColumns = 2;
+ shell.setLayout(layout);
+
+ // Separate the menu bar from the rest of the widgets.
+ Label separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
+ GridData gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ gridData.horizontalAlignment = GridData.FILL;
+ separator.setLayoutData(gridData);
+
+ // Add a composite to contain some control widgets across the top.
+ Composite controls = new Composite(shell, SWT.NULL);
+ RowLayout rowLayout = new RowLayout();
+ rowLayout.marginTop = 0;
+ rowLayout.marginBottom = 5;
+ rowLayout.spacing = 8;
+ controls.setLayout(rowLayout);
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ controls.setLayoutData(gridData);
+
+ // Combo to change the background.
+ Group group = new Group(controls, SWT.NULL);
+ group.setLayout(new RowLayout());
+ group.setText(bundle.getString("Background"));
+ backgroundCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
+ backgroundCombo.setItems(new String[] {
+ bundle.getString("None"),
+ bundle.getString("White"),
+ bundle.getString("Black"),
+ bundle.getString("Red"),
+ bundle.getString("Green"),
+ bundle.getString("Blue")});
+ backgroundCombo.select(backgroundCombo.indexOf(bundle.getString("White")));
+ backgroundCombo.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ changeBackground();
+ }
+ });
+
+ // Combo to change the x scale.
+ String[] values = {
+ "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1",
+ "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "2",
+ "3", "4", "5", "6", "7", "8", "9", "10",};
+ group = new Group(controls, SWT.NULL);
+ group.setLayout(new RowLayout());
+ group.setText(bundle.getString("X_scale"));
+ scaleXCombo = new Combo(group, SWT.DROP_DOWN);
+ for (int i = 0; i < values.length; i++) {
+ scaleXCombo.add(values[i]);
+ }
+ scaleXCombo.select(scaleXCombo.indexOf("1"));
+ scaleXCombo.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ scaleX();
+ }
+ });
+
+ // Combo to change the y scale.
+ group = new Group(controls, SWT.NULL);
+ group.setLayout(new RowLayout());
+ group.setText(bundle.getString("Y_scale"));
+ scaleYCombo = new Combo(group, SWT.DROP_DOWN);
+ for (int i = 0; i < values.length; i++) {
+ scaleYCombo.add(values[i]);
+ }
+ scaleYCombo.select(scaleYCombo.indexOf("1"));
+ scaleYCombo.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ scaleY();
+ }
+ });
+
+ // Combo to change the alpha value.
+ group = new Group(controls, SWT.NULL);
+ group.setLayout(new RowLayout());
+ group.setText(bundle.getString("Alpha_K"));
+ alphaCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
+ for (int i = 0; i <= 255; i += 5) {
+ alphaCombo.add(String.valueOf(i));
+ }
+ alphaCombo.select(alphaCombo.indexOf("255"));
+ alphaCombo.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ alpha();
+ }
+ });
+
+ // Check box to request incremental display.
+ group = new Group(controls, SWT.NULL);
+ group.setLayout(new RowLayout());
+ group.setText(bundle.getString("Display"));
+ incrementalCheck = new Button(group, SWT.CHECK);
+ incrementalCheck.setText(bundle.getString("Incremental"));
+ incrementalCheck.setSelection(incremental);
+ incrementalCheck.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ incremental = ((Button)event.widget).getSelection();
+ }
+ });
+
+ // Check box to request transparent display.
+ transparentCheck = new Button(group, SWT.CHECK);
+ transparentCheck.setText(bundle.getString("Transparent"));
+ transparentCheck.setSelection(transparent);
+ transparentCheck.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ transparent = ((Button)event.widget).getSelection();
+ if (image != null) {
+ imageCanvas.redraw();
+ }
+ }
+ });
+
+ // Check box to request mask display.
+ maskCheck = new Button(group, SWT.CHECK);
+ maskCheck.setText(bundle.getString("Mask"));
+ maskCheck.setSelection(showMask);
+ maskCheck.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ showMask = ((Button)event.widget).getSelection();
+ if (image != null) {
+ imageCanvas.redraw();
+ }
+ }
+ });
+
+ // Check box to request background display.
+ backgroundCheck = new Button(group, SWT.CHECK);
+ backgroundCheck.setText(bundle.getString("Background"));
+ backgroundCheck.setSelection(showBackground);
+ backgroundCheck.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ showBackground = ((Button)event.widget).getSelection();
+ }
+ });
+
+ // Group the animation buttons.
+ group = new Group(controls, SWT.NULL);
+ group.setLayout(new RowLayout());
+ group.setText(bundle.getString("Animation"));
+
+ // Push button to display the previous image in a multi-image file.
+ previousButton = new Button(group, SWT.PUSH);
+ previousButton.setText(bundle.getString("Previous"));
+ previousButton.setEnabled(false);
+ previousButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ previous();
+ }
+ });
+
+ // Push button to display the next image in a multi-image file.
+ nextButton = new Button(group, SWT.PUSH);
+ nextButton.setText(bundle.getString("Next"));
+ nextButton.setEnabled(false);
+ nextButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ next();
+ }
+ });
+
+ // Push button to toggle animation of a multi-image file.
+ animateButton = new Button(group, SWT.PUSH);
+ animateButton.setText(bundle.getString("Animate"));
+ animateButton.setEnabled(false);
+ animateButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ animate();
+ }
+ });
+
+ // Label to show the image file type.
+ typeLabel = new Label(shell, SWT.NULL);
+ typeLabel.setText(bundle.getString("Type_initial"));
+ typeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Canvas to show the image.
+ imageCanvas = new Canvas(shell, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_REDRAW_RESIZE);
+ imageCanvas.setBackground(whiteColor);
+ imageCanvas.setCursor(crossCursor);
+ gridData = new GridData();
+ gridData.verticalSpan = 15;
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ imageCanvas.setLayoutData(gridData);
+ imageCanvas.addPaintListener(new PaintListener() {
+ public void paintControl(PaintEvent event) {
+ if (image != null)
+ paintImage(event);
+ }
+ });
+ imageCanvas.addMouseMoveListener(new MouseMoveListener() {
+ public void mouseMove(MouseEvent event) {
+ if (image != null) {
+ showColorAt(event.x, event.y);
+ }
+ }
+ });
+
+ // Set up the image canvas scroll bars.
+ ScrollBar horizontal = imageCanvas.getHorizontalBar();
+ horizontal.setVisible(true);
+ horizontal.setMinimum(0);
+ horizontal.setEnabled(false);
+ horizontal.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ scrollHorizontally((ScrollBar)event.widget);
+ }
+ });
+ ScrollBar vertical = imageCanvas.getVerticalBar();
+ vertical.setVisible(true);
+ vertical.setMinimum(0);
+ vertical.setEnabled(false);
+ vertical.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ scrollVertically((ScrollBar)event.widget);
+ }
+ });
+
+ // Label to show the image size.
+ sizeLabel = new Label(shell, SWT.NULL);
+ sizeLabel.setText(bundle.getString("Size_initial"));
+ sizeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the image depth.
+ depthLabel = new Label(shell, SWT.NULL);
+ depthLabel.setText(bundle.getString("Depth_initial"));
+ depthLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the transparent pixel.
+ transparentPixelLabel = new Label(shell, SWT.NULL);
+ transparentPixelLabel.setText(bundle.getString("Transparent_pixel_initial"));
+ transparentPixelLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the time to load.
+ timeToLoadLabel = new Label(shell, SWT.NULL);
+ timeToLoadLabel.setText(bundle.getString("Time_to_load_initial"));
+ timeToLoadLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Separate the animation fields from the rest of the fields.
+ separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
+ separator.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the logical screen size for animation.
+ screenSizeLabel = new Label(shell, SWT.NULL);
+ screenSizeLabel.setText(bundle.getString("Animation_size_initial"));
+ screenSizeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the background pixel.
+ backgroundPixelLabel = new Label(shell, SWT.NULL);
+ backgroundPixelLabel.setText(bundle.getString("Background_pixel_initial"));
+ backgroundPixelLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the image location (x, y).
+ locationLabel = new Label(shell, SWT.NULL);
+ locationLabel.setText(bundle.getString("Image_location_initial"));
+ locationLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the image disposal method.
+ disposalMethodLabel = new Label(shell, SWT.NULL);
+ disposalMethodLabel.setText(bundle.getString("Disposal_initial"));
+ disposalMethodLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the image delay time.
+ delayTimeLabel = new Label(shell, SWT.NULL);
+ delayTimeLabel.setText(bundle.getString("Delay_initial"));
+ delayTimeLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show the background pixel.
+ repeatCountLabel = new Label(shell, SWT.NULL);
+ repeatCountLabel.setText(bundle.getString("Repeats_initial"));
+ repeatCountLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Separate the animation fields from the palette.
+ separator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
+ separator.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Label to show if the image has a direct or indexed palette.
+ paletteLabel = new Label(shell, SWT.NULL);
+ paletteLabel.setText(bundle.getString("Palette_initial"));
+ paletteLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+
+ // Canvas to show the image's palette.
+ paletteCanvas = new Canvas(shell, SWT.BORDER | SWT.V_SCROLL | SWT.NO_REDRAW_RESIZE);
+ paletteCanvas.setFont(fixedWidthFont);
+ paletteCanvas.getVerticalBar().setVisible(true);
+ gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ GC gc = new GC(paletteLabel);
+ paletteWidth = gc.stringExtent(bundle.getString("Max_length_string")).x;
+ gc.dispose();
+ gridData.widthHint = paletteWidth;
+ gridData.heightHint = 16 * 11; // show at least 16 colors
+ paletteCanvas.setLayoutData(gridData);
+ paletteCanvas.addPaintListener(new PaintListener() {
+ public void paintControl(PaintEvent event) {
+ if (image != null)
+ paintPalette(event);
+ }
+ });
+
+ // Set up the palette canvas scroll bar.
+ vertical = paletteCanvas.getVerticalBar();
+ vertical.setVisible(true);
+ vertical.setMinimum(0);
+ vertical.setIncrement(10);
+ vertical.setEnabled(false);
+ vertical.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ scrollPalette((ScrollBar)event.widget);
+ }
+ });
+
+ // Sash to see more of image or image data.
+ sash = new Sash(shell, SWT.HORIZONTAL);
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ gridData.horizontalAlignment = GridData.FILL;
+ sash.setLayoutData(gridData);
+ sash.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent event) {
+ if (event.detail != SWT.DRAG) {
+ ((GridData)paletteCanvas.getLayoutData()).heightHint = SWT.DEFAULT;
+ Rectangle paletteCanvasBounds = paletteCanvas.getBounds();
+ int minY = paletteCanvasBounds.y + 20;
+ Rectangle dataLabelBounds = dataLabel.getBounds();
+ int maxY = statusLabel.getBounds().y - dataLabelBounds.height - 20;
+ if (event.y > minY && event.y < maxY) {
+ Rectangle oldSash = sash.getBounds();
+ sash.setBounds(event.x, event.y, event.width, event.height);
+ int diff = event.y - oldSash.y;
+ Rectangle bounds = imageCanvas.getBounds();
+ imageCanvas.setBounds(bounds.x, bounds.y, bounds.width, bounds.height + diff);
+ bounds = paletteCanvasBounds;
+ paletteCanvas.setBounds(bounds.x, bounds.y, bounds.width, bounds.height + diff);
+ bounds = dataLabelBounds;
+ dataLabel.setBounds(bounds.x, bounds.y + diff, bounds.width, bounds.height);
+ bounds = dataText.getBounds();
+ dataText.setBounds(bounds.x, bounds.y + diff, bounds.width, bounds.height - diff);
+ //shell.layout(true);
+ }
+ }
+ }
+ });
+
+ // Label to show data-specific fields.
+ dataLabel = new Label(shell, SWT.NULL);
+ dataLabel.setText(bundle.getString("Pixel_data_initial"));
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ gridData.horizontalAlignment = GridData.FILL;
+ dataLabel.setLayoutData(gridData);
+
+ // Text to show a dump of the data.
+ dataText = new StyledText(shell, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL);
+ dataText.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
+ dataText.setFont(fixedWidthFont);
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.heightHint = 128;
+ gridData.grabExcessVerticalSpace = true;
+ dataText.setLayoutData(gridData);
+ dataText.addMouseListener(new MouseAdapter() {
+ public void mouseDown(MouseEvent event) {
+ if (image != null && event.button == 1) {
+ showColorForData();
+ }
+ }
+ });
+ dataText.addKeyListener(new KeyAdapter() {
+ public void keyPressed(KeyEvent event) {
+ if (image != null) {
+ showColorForData();
+ }
+ }
+ });
+
+ // Label to show status and cursor location in image.
+ statusLabel = new Label(shell, SWT.NULL);
+ statusLabel.setText("");
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ gridData.horizontalAlignment = GridData.FILL;
+ statusLabel.setLayoutData(gridData);
+ }
+
+ Menu createMenuBar() {
+ // Menu bar.
+ Menu menuBar = new Menu(shell, SWT.BAR);
+ shell.setMenuBar(menuBar);
+ createFileMenu(menuBar);
+ createAlphaMenu(menuBar);
+ return menuBar;
+ }
+
+ void createFileMenu(Menu menuBar) {
+ // File menu
+ MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
+ item.setText(bundle.getString("File"));
+ Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
+ item.setMenu(fileMenu);
+
+ // File -> Open File...
+ item = new MenuItem(fileMenu, SWT.NULL);
+ item.setText(bundle.getString("OpenFile"));
+ item.setAccelerator(SWT.MOD1 + 'O');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuOpenFile();
+ }
+ });
+
+ // File -> Open URL...
+ item = new MenuItem(fileMenu, SWT.NULL);
+ item.setText(bundle.getString("OpenURL"));
+ item.setAccelerator(SWT.MOD1 + 'U');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuOpenURL();
+ }
+ });
+
+ // File -> Reopen
+ item = new MenuItem(fileMenu, SWT.NULL);
+ item.setText(bundle.getString("Reopen"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuReopen();
+ }
+ });
+
+ new MenuItem(fileMenu, SWT.SEPARATOR);
+
+ // File -> Save
+ item = new MenuItem(fileMenu, SWT.NULL);
+ item.setText(bundle.getString("Save"));
+ item.setAccelerator(SWT.MOD1 + 'S');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuSave();
+ }
+ });
+
+ // File -> Save As...
+ item = new MenuItem(fileMenu, SWT.NULL);
+ item.setText(bundle.getString("Save_as"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuSaveAs();
+ }
+ });
+
+ // File -> Save Mask As...
+ item = new MenuItem(fileMenu, SWT.NULL);
+ item.setText(bundle.getString("Save_mask_as"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuSaveMaskAs();
+ }
+ });
+
+ new MenuItem(fileMenu, SWT.SEPARATOR);
+
+ // File -> Print
+ item = new MenuItem(fileMenu, SWT.NULL);
+ item.setText(bundle.getString("Print"));
+ item.setAccelerator(SWT.MOD1 + 'P');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuPrint();
+ }
+ });
+
+ new MenuItem(fileMenu, SWT.SEPARATOR);
+
+ // File -> Exit
+ item = new MenuItem(fileMenu, SWT.NULL);
+ item.setText(bundle.getString("Exit"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ shell.close();
+ }
+ });
+
+ }
+
+ void createAlphaMenu(Menu menuBar) {
+ // Alpha menu
+ MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
+ item.setText(bundle.getString("Alpha"));
+ Menu alphaMenu = new Menu(shell, SWT.DROP_DOWN);
+ item.setMenu(alphaMenu);
+
+ // Alpha -> K
+ item = new MenuItem(alphaMenu, SWT.NULL);
+ item.setText("K");
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuComposeAlpha(ALPHA_CONSTANT);
+ }
+ });
+
+ // Alpha -> (K + x) % 256
+ item = new MenuItem(alphaMenu, SWT.NULL);
+ item.setText("(K + x) % 256");
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuComposeAlpha(ALPHA_X);
+ }
+ });
+
+ // Alpha -> (K + y) % 256
+ item = new MenuItem(alphaMenu, SWT.NULL);
+ item.setText("(K + y) % 256");
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ menuComposeAlpha(ALPHA_Y);
+ }
+ });
+ }
+
+ void menuComposeAlpha(int alpha_op) {
+ if (image == null) return;
+ animate = false; // stop any animation in progress
+ Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+ imageCanvas.setCursor(waitCursor);
+ try {
+ if (alpha_op == ALPHA_CONSTANT) {
+ imageData.alpha = alpha;
+ } else {
+ imageData.alpha = -1;
+ switch (alpha_op) {
+ case ALPHA_X:
+ for (int y = 0; y < imageData.height; y++) {
+ for (int x = 0; x < imageData.width; x++) {
+ imageData.setAlpha(x, y, (x + alpha) % 256);
+ }
+ }
+ break;
+ case ALPHA_Y:
+ for (int y = 0; y < imageData.height; y++) {
+ for (int x = 0; x < imageData.width; x++) {
+ imageData.setAlpha(x, y, (y + alpha) % 256);
+ }
+ }
+ break;
+ default: break;
+ }
+ }
+ displayImage(imageData);
+ } finally {
+ shell.setCursor(null);
+ imageCanvas.setCursor(crossCursor);
+ waitCursor.dispose();
+ }
+ }
+
+ void menuOpenFile() {
+ animate = false; // stop any animation in progress
+ resetScaleCombos();
+
+ // Get the user to choose an image file.
+ FileDialog fileChooser = new FileDialog(shell, SWT.OPEN);
+ if (lastPath != null)
+ fileChooser.setFilterPath(lastPath);
+ fileChooser.setFilterExtensions(new String[] { "*.bmp; *.gif; *.ico; *.jpg; *.pcx; *.png; *.tif", "*.bmp", "*.gif", "*.ico", "*.jpg", "*.pcx", "*.png", "*.tif" });
+ fileChooser.setFilterNames(new String[] { bundle.getString("All_images") + " (bmp, gif, ico, jpg, pcx, png, tif)",
+ "BMP (*.bmp)", "GIF (*.gif)", "ICO (*.ico)", "JPEG (*.jpg)", "PCX (*.pcx)", "PNG (*.png)", "TIFF (*.tif)" });
+ String filename = fileChooser.open();
+ lastPath = fileChooser.getFilterPath();
+ if (filename == null)
+ return;
+
+ Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+ imageCanvas.setCursor(waitCursor);
+ try {
+ loader = new ImageLoader();
+ if (incremental) {
+ // Prepare to handle incremental events.
+ loader.addImageLoaderListener(new ImageLoaderListener() {
+ public void imageDataLoaded(ImageLoaderEvent event) {
+ incrementalDataLoaded(event);
+ }
+ });
+ incrementalThreadStart();
+ }
+ // Read the new image(s) from the chosen file.
+ long startTime = System.currentTimeMillis();
+ imageDataArray = loader.load(filename);
+ loadTime = System.currentTimeMillis() - startTime;
+ if (imageDataArray.length > 0) {
+ // Cache the filename.
+ currentName = filename;
+ fileName = filename;
+
+ // If there are multiple images in the file (typically GIF)
+ // then enable the Previous, Next and Animate buttons.
+ previousButton.setEnabled(imageDataArray.length > 1);
+ nextButton.setEnabled(imageDataArray.length > 1);
+ animateButton.setEnabled(imageDataArray.length > 1 && loader.logicalScreenWidth > 0 && loader.logicalScreenHeight > 0);
+
+ // Display the first image in the file.
+ imageDataIndex = 0;
+ displayImage(imageDataArray[imageDataIndex]);
+ resetScrollBars();
+ }
+ } catch (SWTException e) {
+ showErrorDialog(bundle.getString("Loading_lc"), filename, e);
+ } finally {
+ shell.setCursor(null);
+ imageCanvas.setCursor(crossCursor);
+ waitCursor.dispose();
+ }
+ }
+
+ void menuOpenURL() {
+ animate = false; // stop any animation in progress
+ resetScaleCombos();
+
+ // Get the user to choose an image URL.
+ TextPrompter textPrompter = new TextPrompter(shell, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
+ textPrompter.setText(bundle.getString("OpenURLDialog"));
+ textPrompter.setMessage(bundle.getString("EnterURL"));
+ String urlname = textPrompter.open();
+ if (urlname == null) return;
+
+ Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+ imageCanvas.setCursor(waitCursor);
+ try {
+ URL url = new URL(urlname);
+ InputStream stream = url.openStream();
+ loader = new ImageLoader();
+ if (incremental) {
+ // Prepare to handle incremental events.
+ loader.addImageLoaderListener(new ImageLoaderListener() {
+ public void imageDataLoaded(ImageLoaderEvent event) {
+ incrementalDataLoaded(event);
+ }
+ });
+ incrementalThreadStart();
+ }
+ // Read the new image(s) from the chosen file.
+ long startTime = System.currentTimeMillis();
+ imageDataArray = loader.load(stream);
+ loadTime = System.currentTimeMillis() - startTime;
+ if (imageDataArray.length > 0) {
+ currentName = urlname;
+ fileName = null;
+
+ // If there are multiple images in the file (typically GIF)
+ // then enable the Previous, Next and Animate buttons.
+ previousButton.setEnabled(imageDataArray.length > 1);
+ nextButton.setEnabled(imageDataArray.length > 1);
+ animateButton.setEnabled(imageDataArray.length > 1 && loader.logicalScreenWidth > 0 && loader.logicalScreenHeight > 0);
+
+ // Display the first image in the file.
+ imageDataIndex = 0;
+ displayImage(imageDataArray[imageDataIndex]);
+ resetScrollBars();
+ }
+ } catch (Exception e) {
+ showErrorDialog(bundle.getString("Loading_lc"), urlname, e);
+ } finally {
+ shell.setCursor(null);
+ imageCanvas.setCursor(crossCursor);
+ waitCursor.dispose();
+ }
+ }
+
+ /*
+ * Called to start a thread that draws incremental images
+ * as they are loaded.
+ */
+ void incrementalThreadStart() {
+ incrementalEvents = new Vector();
+ incrementalThread = new Thread("Incremental") {
+ public void run() {
+ // Draw the first ImageData increment.
+ while (incrementalEvents != null) {
+ // Synchronize so we don't try to remove when the vector is null.
+ synchronized (ImageAnalyzer.this) {
+ if (incrementalEvents != null) {
+ if (incrementalEvents.size() > 0) {
+ ImageLoaderEvent event = (ImageLoaderEvent) incrementalEvents.remove(0);
+ if (image != null) image.dispose();
+ image = new Image(display, event.imageData);
+ imageData = event.imageData;
+ imageCanvasGC.drawImage(
+ image,
+ 0,
+ 0,
+ imageData.width,
+ imageData.height,
+ imageData.x,
+ imageData.y,
+ imageData.width,
+ imageData.height);
+ } else {
+ yield();
+ }
+ }
+ }
+ }
+ display.wake();
+ }
+ };
+ incrementalThread.setDaemon(true);
+ incrementalThread.start();
+ }
+
+ /*
+ * Called when incremental image data has been loaded,
+ * for example, for interlaced GIF/PNG or progressive JPEG.
+ */
+ void incrementalDataLoaded(ImageLoaderEvent event) {
+ // Synchronize so that we do not try to add while
+ // the incremental drawing thread is removing.
+ synchronized (this) {
+ incrementalEvents.addElement(event);
+ }
+ }
+
+ void menuSave() {
+ if (image == null) return;
+ animate = false; // stop any animation in progress
+
+ // If the image file type is unknown, we can't 'Save',
+ // so we have to use 'Save As...'.
+ if (imageData.type == SWT.IMAGE_UNDEFINED || fileName == null) {
+ menuSaveAs();
+ return;
+ }
+
+ Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+ imageCanvas.setCursor(waitCursor);
+ try {
+ // Save the current image to the current file.
+ loader.data = new ImageData[] {imageData};
+ loader.save(fileName, imageData.type);
+
+ } catch (SWTException e) {
+ showErrorDialog(bundle.getString("Saving_lc"), fileName, e);
+ } finally {
+ shell.setCursor(null);
+ imageCanvas.setCursor(crossCursor);
+ waitCursor.dispose();
+ }
+ }
+
+ void menuSaveAs() {
+ if (image == null) return;
+ animate = false; // stop any animation in progress
+
+ // Get the user to choose a file name and type to save.
+ FileDialog fileChooser = new FileDialog(shell, SWT.SAVE);
+ fileChooser.setFilterPath(lastPath);
+ if (fileName != null) fileChooser.setFileName(fileName);
+ fileChooser.setFilterExtensions(new String[] { "*.bmp", "*.gif", "*.ico", "*.jpg", "*.png" });
+ fileChooser.setFilterNames(new String[] { "BMP (*.bmp)", "GIF (*.gif)", "ICO (*.ico)", "JPEG (*.jpg)", "PNG (*.png)" });
+ String filename = fileChooser.open();
+ lastPath = fileChooser.getFilterPath();
+ if (filename == null)
+ return;
+
+ // Figure out what file type the user wants saved.
+ // We need to rely on the file extension because FileDialog
+ // does not have API for asking what filter type was selected.
+ int filetype = determineFileType(filename);
+ if (filetype == SWT.IMAGE_UNDEFINED) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
+ box.setMessage(createMsg(bundle.getString("Unknown_extension"),
+ filename.substring(filename.lastIndexOf('.') + 1)));
+ box.open();
+ return;
+ }
+
+ if (new java.io.File(filename).exists()) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
+ box.setMessage(createMsg(bundle.getString("Overwrite"), filename));
+ if (box.open() == SWT.CANCEL)
+ return;
+ }
+
+ Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+ imageCanvas.setCursor(waitCursor);
+ try {
+ // Save the current image to the specified file.
+ loader.data = new ImageData[] {imageData};
+ loader.save(filename, filetype);
+
+ // Update the shell title and file type label,
+ // and use the new file.
+ fileName = filename;
+ shell.setText(createMsg(bundle.getString("Analyzer_on"), filename));
+ typeLabel.setText(createMsg(bundle.getString("Type_string"), fileTypeString(filetype)));
+
+ } catch (SWTException e) {
+ showErrorDialog(bundle.getString("Saving_lc"), filename, e);
+ } finally {
+ shell.setCursor(null);
+ imageCanvas.setCursor(crossCursor);
+ waitCursor.dispose();
+ }
+ }
+
+ void menuSaveMaskAs() {
+ if (image == null || !showMask) return;
+ if (imageData.getTransparencyType() == SWT.TRANSPARENCY_NONE) return;
+ animate = false; // stop any animation in progress
+
+ // Get the user to choose a file name and type to save.
+ FileDialog fileChooser = new FileDialog(shell, SWT.SAVE);
+ fileChooser.setFilterPath(lastPath);
+ if (fileName != null) fileChooser.setFileName(fileName);
+ fileChooser.setFilterExtensions(new String[] { "*.bmp", "*.gif", "*.ico", "*.jpg", "*.png" });
+ fileChooser.setFilterNames(new String[] { "BMP (*.bmp)", "GIF (*.gif)", "ICO (*.ico)", "JPEG (*.jpg)", "PNG (*.png)" });
+ String filename = fileChooser.open();
+ lastPath = fileChooser.getFilterPath();
+ if (filename == null)
+ return;
+
+ // Figure out what file type the user wants saved.
+ // We need to rely on the file extension because FileDialog
+ // does not have API for asking what filter type was selected.
+ int filetype = determineFileType(filename);
+ if (filetype == SWT.IMAGE_UNDEFINED) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
+ box.setMessage(createMsg(bundle.getString("Unknown_extension"),
+ filename.substring(filename.lastIndexOf('.') + 1)));
+ box.open();
+ return;
+ }
+
+ if (new java.io.File(filename).exists()) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
+ box.setMessage(createMsg(bundle.getString("Overwrite"), filename));
+ if (box.open() == SWT.CANCEL)
+ return;
+ }
+
+ Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+ imageCanvas.setCursor(waitCursor);
+ try {
+ // Save the mask of the current image to the specified file.
+ ImageData maskImageData = imageData.getTransparencyMask();
+ loader.data = new ImageData[] {maskImageData};
+ loader.save(filename, filetype);
+
+ } catch (SWTException e) {
+ showErrorDialog(bundle.getString("Saving_lc"), filename, e);
+ } finally {
+ shell.setCursor(null);
+ imageCanvas.setCursor(crossCursor);
+ waitCursor.dispose();
+ }
+ }
+
+ void menuPrint() {
+ if (image == null) return;
+
+ try {
+ // Ask the user to specify the printer.
+ PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
+ PrinterData printerData = dialog.open();
+ if (printerData == null) return;
+
+ Printer printer = new Printer(printerData);
+ Point screenDPI = display.getDPI();
+ Point printerDPI = printer.getDPI();
+ int scaleFactor = printerDPI.x / screenDPI.x;
+ Rectangle trim = printer.computeTrim(0, 0, 0, 0);
+ if (printer.startJob(currentName)) {
+ if (printer.startPage()) {
+ GC gc = new GC(printer);
+ int transparentPixel = imageData.transparentPixel;
+ if (transparentPixel != -1 && !transparent) {
+ imageData.transparentPixel = -1;
+ }
+ Image printerImage = new Image(printer, imageData);
+ gc.drawImage(
+ printerImage,
+ 0,
+ 0,
+ imageData.width,
+ imageData.height,
+ -trim.x,
+ -trim.y,
+ scaleFactor * imageData.width,
+ scaleFactor * imageData.height);
+ if (transparentPixel != -1 && !transparent) {
+ imageData.transparentPixel = transparentPixel;
+ }
+ printerImage.dispose();
+ gc.dispose();
+ printer.endPage();
+ }
+ printer.endJob();
+ }
+ printer.dispose();
+ } catch (SWTError e) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
+ box.setMessage(bundle.getString("Printing_error") + e.getMessage());
+ box.open();
+ }
+ }
+
+ void menuReopen() {
+ if (currentName == null) return;
+ animate = false; // stop any animation in progress
+ resetScrollBars();
+ resetScaleCombos();
+ Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
+ shell.setCursor(waitCursor);
+ imageCanvas.setCursor(waitCursor);
+ try {
+ loader = new ImageLoader();
+ long startTime = System.currentTimeMillis();
+ ImageData[] newImageData;
+ if (fileName == null) {
+ URL url = new URL(currentName);
+ InputStream stream = url.openStream();
+ newImageData = loader.load(stream);
+ } else {
+ newImageData = loader.load(fileName);
+ }
+ loadTime = System.currentTimeMillis() - startTime;
+ imageDataIndex = 0;
+ displayImage(newImageData[imageDataIndex]);
+
+ } catch (Exception e) {
+ showErrorDialog(bundle.getString("Reloading_lc"), currentName, e);
+ } finally {
+ shell.setCursor(null);
+ imageCanvas.setCursor(crossCursor);
+ waitCursor.dispose();
+ }
+ }
+
+ void changeBackground() {
+ String background = backgroundCombo.getText();
+ if (background.equals(bundle.getString("White"))) {
+ imageCanvas.setBackground(whiteColor);
+ } else if (background.equals(bundle.getString("Black"))) {
+ imageCanvas.setBackground(blackColor);
+ } else if (background.equals(bundle.getString("Red"))) {
+ imageCanvas.setBackground(redColor);
+ } else if (background.equals(bundle.getString("Green"))) {
+ imageCanvas.setBackground(greenColor);
+ } else if (background.equals(bundle.getString("Blue"))) {
+ imageCanvas.setBackground(blueColor);
+ } else {
+ imageCanvas.setBackground(null);
+ }
+ }
+
+ /*
+ * Called when the ScaleX combo selection changes.
+ */
+ void scaleX() {
+ try {
+ xscale = Float.parseFloat(scaleXCombo.getText());
+ } catch (NumberFormatException e) {
+ xscale = 1;
+ scaleXCombo.select(scaleXCombo.indexOf("1"));
+ }
+ if (image != null) {
+ resizeScrollBars();
+ imageCanvas.redraw();
+ }
+ }
+
+ /*
+ * Called when the ScaleY combo selection changes.
+ */
+ void scaleY() {
+ try {
+ yscale = Float.parseFloat(scaleYCombo.getText());
+ } catch (NumberFormatException e) {
+ yscale = 1;
+ scaleYCombo.select(scaleYCombo.indexOf("1"));
+ }
+ if (image != null) {
+ resizeScrollBars();
+ imageCanvas.redraw();
+ }
+ }
+
+ /*
+ * Called when the Alpha combo selection changes.
+ */
+ void alpha() {
+ try {
+ alpha = Integer.parseInt(alphaCombo.getText());
+ } catch (NumberFormatException e) {
+ alphaCombo.select(alphaCombo.indexOf("255"));
+ alpha = 255;
+ }
+ }
+
+ /*
+ * Called when the mouse moves in the image canvas.
+ * Show the color of the image at the point under the mouse.
+ */
+ void showColorAt(int mx, int my) {
+ int x = mx - imageData.x - ix;
+ int y = my - imageData.y - iy;
+ showColorForPixel(x, y);
+ }
+
+ /*
+ * Called when a mouse down or key press is detected
+ * in the data text. Show the color of the pixel at
+ * the caret position in the data text.
+ */
+ void showColorForData() {
+ int delimiterLength = dataText.getLineDelimiter().length();
+ int charactersPerLine = 6 + 3 * imageData.bytesPerLine + delimiterLength;
+ int position = dataText.getCaretOffset();
+ int y = position / charactersPerLine;
+ if ((position - y * charactersPerLine) < 6 || ((y + 1) * charactersPerLine - position) <= delimiterLength) {
+ statusLabel.setText("");
+ return;
+ }
+ int dataPosition = position - 6 * (y + 1) - delimiterLength * y;
+ int byteNumber = dataPosition / 3;
+ int where = dataPosition - byteNumber * 3;
+ int xByte = byteNumber % imageData.bytesPerLine;
+ int x = -1;
+ int depth = imageData.depth;
+ if (depth == 1) { // 8 pixels per byte (can only show 3 of 8)
+ if (where == 0) x = xByte * 8;
+ if (where == 1) x = xByte * 8 + 3;
+ if (where == 2) x = xByte * 8 + 7;
+ }
+ if (depth == 2) { // 4 pixels per byte (can only show 3 of 4)
+ if (where == 0) x = xByte * 4;
+ if (where == 1) x = xByte * 4 + 1;
+ if (where == 2) x = xByte * 4 + 3;
+ }
+ if (depth == 4) { // 2 pixels per byte
+ if (where == 0) x = xByte * 2;
+ if (where == 1) x = xByte * 2;
+ if (where == 2) x = xByte * 2 + 1;
+ }
+ if (depth == 8) { // 1 byte per pixel
+ x = xByte;
+ }
+ if (depth == 16) { // 2 bytes per pixel
+ x = xByte / 2;
+ }
+ if (depth == 24) { // 3 bytes per pixel
+ x = xByte / 3;
+ }
+ if (depth == 32) { // 4 bytes per pixel
+ x = xByte / 4;
+ }
+ if (x != -1) {
+ showColorForPixel(x, y);
+ } else {
+ statusLabel.setText("");
+ }
+ }
+
+ /*
+ * Set the status label to show color information
+ * for the specified pixel in the image.
+ */
+ void showColorForPixel(int x, int y) {
+ if (x >= 0 && x < imageData.width && y >= 0 && y < imageData.height) {
+ int pixel = imageData.getPixel(x, y);
+ RGB rgb = imageData.palette.getRGB(pixel);
+
+
+ Object[] args = {new Integer(x),
+ new Integer(y),
+ new Integer(pixel),
+ Integer.toHexString(pixel),
+ rgb};
+ if (pixel == imageData.transparentPixel) {
+ statusLabel.setText(createMsg(bundle.getString("Color_at_trans"), args));
+ } else {
+ statusLabel.setText(createMsg(bundle.getString("Color_at"), args));
+ }
+ } else {
+ statusLabel.setText("");
+ }
+ }
+
+ /*
+ * Called when the Animate button is pressed.
+ */
+ void animate() {
+ animate = !animate;
+ if (animate && image != null && imageDataArray.length > 1) {
+ animateThread = new Thread(bundle.getString("Animation")) {
+ public void run() {
+ // Pre-animation widget setup.
+ preAnimation();
+
+ // Animate.
+ try {
+ animateLoop();
+ } catch (final SWTException e) {
+ display.syncExec(new Runnable() {
+ public void run() {
+ showErrorDialog(createMsg(bundle.getString("Creating_image"),
+ new Integer(imageDataIndex+1)),
+ currentName, e);
+ }
+ });
+ }
+
+ // Post animation widget reset.
+ postAnimation();
+ }
+ };
+ animateThread.setDaemon(true);
+ animateThread.start();
+ }
+ }
+
+ /*
+ * Loop through all of the images in a multi-image file
+ * and display them one after another.
+ */
+ void animateLoop() {
+ // Create an off-screen image to draw on, and a GC to draw with.
+ // Both are disposed after the animation.
+ Image offScreenImage = new Image(display, loader.logicalScreenWidth, loader.logicalScreenHeight);
+ GC offScreenImageGC = new GC(offScreenImage);
+
+ try {
+ // Use syncExec to get the background color of the imageCanvas.
+ display.syncExec(new Runnable() {
+ public void run() {
+ canvasBackground = imageCanvas.getBackground();
+ }
+ });
+
+ // Fill the off-screen image with the background color of the canvas.
+ offScreenImageGC.setBackground(canvasBackground);
+ offScreenImageGC.fillRectangle(
+ 0,
+ 0,
+ loader.logicalScreenWidth,
+ loader.logicalScreenHeight);
+
+ // Draw the current image onto the off-screen image.
+ offScreenImageGC.drawImage(
+ image,
+ 0,
+ 0,
+ imageData.width,
+ imageData.height,
+ imageData.x,
+ imageData.y,
+ imageData.width,
+ imageData.height);
+
+ int repeatCount = loader.repeatCount;
+ while (animate && (loader.repeatCount == 0 || repeatCount > 0)) {
+ if (imageData.disposalMethod == SWT.DM_FILL_BACKGROUND) {
+ // Fill with the background color before drawing.
+ Color bgColor = null;
+ int backgroundPixel = loader.backgroundPixel;
+ if (showBackground && backgroundPixel != -1) {
+ // Fill with the background color.
+ RGB backgroundRGB = imageData.palette.getRGB(backgroundPixel);
+ bgColor = new Color(null, backgroundRGB);
+ }
+ try {
+ offScreenImageGC.setBackground(bgColor != null ? bgColor : canvasBackground);
+ offScreenImageGC.fillRectangle(
+ imageData.x,
+ imageData.y,
+ imageData.width,
+ imageData.height);
+ } finally {
+ if (bgColor != null) bgColor.dispose();
+ }
+ } else if (imageData.disposalMethod == SWT.DM_FILL_PREVIOUS) {
+ // Restore the previous image before drawing.
+ offScreenImageGC.drawImage(
+ image,
+ 0,
+ 0,
+ imageData.width,
+ imageData.height,
+ imageData.x,
+ imageData.y,
+ imageData.width,
+ imageData.height);
+ }
+
+ // Get the next image data.
+ imageDataIndex = (imageDataIndex + 1) % imageDataArray.length;
+ imageData = imageDataArray[imageDataIndex];
+ image.dispose();
+ image = new Image(display, imageData);
+
+ // Draw the new image data.
+ offScreenImageGC.drawImage(
+ image,
+ 0,
+ 0,
+ imageData.width,
+ imageData.height,
+ imageData.x,
+ imageData.y,
+ imageData.width,
+ imageData.height);
+
+ // Draw the off-screen image to the screen.
+ imageCanvasGC.drawImage(offScreenImage, 0, 0);
+
+ // Sleep for the specified delay time before drawing again.
+ try {
+ Thread.sleep(visibleDelay(imageData.delayTime * 10));
+ } catch (InterruptedException e) {
+ }
+
+ // If we have just drawn the last image in the set,
+ // then decrement the repeat count.
+ if (imageDataIndex == imageDataArray.length - 1) repeatCount--;
+ }
+ } finally {
+ offScreenImage.dispose();
+ offScreenImageGC.dispose();
+ }
+ }
+
+ /*
+ * Pre animation setup.
+ */
+ void preAnimation() {
+ display.syncExec(new Runnable() {
+ public void run() {
+ // Change the label of the Animate button to 'Stop'.
+ animateButton.setText(bundle.getString("Stop"));
+
+ // Disable anything we don't want the user
+ // to select during the animation.
+ previousButton.setEnabled(false);
+ nextButton.setEnabled(false);
+ backgroundCombo.setEnabled(false);
+ scaleXCombo.setEnabled(false);
+ scaleYCombo.setEnabled(false);
+ alphaCombo.setEnabled(false);
+ incrementalCheck.setEnabled(false);
+ transparentCheck.setEnabled(false);
+ maskCheck.setEnabled(false);
+ // leave backgroundCheck enabled
+
+ // Reset the scale combos and scrollbars.
+ resetScaleCombos();
+ resetScrollBars();
+ }
+ });
+ }
+
+ /*
+ * Post animation reset.
+ */
+ void postAnimation() {
+ display.syncExec(new Runnable() {
+ public void run() {
+ // Enable anything we disabled before the animation.
+ previousButton.setEnabled(true);
+ nextButton.setEnabled(true);
+ backgroundCombo.setEnabled(true);
+ scaleXCombo.setEnabled(true);
+ scaleYCombo.setEnabled(true);
+ alphaCombo.setEnabled(true);
+ incrementalCheck.setEnabled(true);
+ transparentCheck.setEnabled(true);
+ maskCheck.setEnabled(true);
+
+ // Reset the label of the Animate button.
+ animateButton.setText(bundle.getString("Animate"));
+
+ if (animate) {
+ // If animate is still true, we finished the
+ // full number of repeats. Leave the image as-is.
+ animate = false;
+ } else {
+ // Redisplay the current image and its palette.
+ displayImage(imageDataArray[imageDataIndex]);
+ }
+ }
+ });
+ }
+
+ /*
+ * Called when the Previous button is pressed.
+ * Display the previous image in a multi-image file.
+ */
+ void previous() {
+ if (image != null && imageDataArray.length > 1) {
+ if (imageDataIndex == 0) {
+ imageDataIndex = imageDataArray.length;
+ }
+ imageDataIndex = imageDataIndex - 1;
+ displayImage(imageDataArray[imageDataIndex]);
+ }
+ }
+
+ /*
+ * Called when the Next button is pressed.
+ * Display the next image in a multi-image file.
+ */
+ void next() {
+ if (image != null && imageDataArray.length > 1) {
+ imageDataIndex = (imageDataIndex + 1) % imageDataArray.length;
+ displayImage(imageDataArray[imageDataIndex]);
+ }
+ }
+
+ void displayImage(ImageData newImageData) {
+ if (incremental && incrementalThread != null) {
+ // Tell the incremental thread to stop drawing.
+ synchronized (this) {
+ incrementalEvents = null;
+ }
+
+ // Wait until the incremental thread is done.
+ while (incrementalThread.isAlive()) {
+ if (!display.readAndDispatch()) display.sleep();
+ }
+ }
+
+ // Dispose of the old image, if there was one.
+ if (image != null) image.dispose();
+
+ try {
+ // Cache the new image and imageData.
+ image = new Image(display, newImageData);
+ imageData = newImageData;
+
+ } catch (SWTException e) {
+ showErrorDialog(bundle.getString("Creating_from") + " ", currentName, e);
+ image = null;
+ return;
+ }
+
+ // Update the widgets with the new image info.
+ String string = createMsg(bundle.getString("Analyzer_on"), currentName);
+ shell.setText(string);
+
+ if (imageDataArray.length > 1) {
+ string = createMsg(bundle.getString("Type_index"),
+ new Object[] {fileTypeString(imageData.type),
+ new Integer(imageDataIndex + 1),
+ new Integer(imageDataArray.length)});
+ } else {
+ string = createMsg(bundle.getString("Type_string"), fileTypeString(imageData.type));
+ }
+ typeLabel.setText(string);
+
+ string = createMsg(bundle.getString("Size_value"),
+ new Object[] {new Integer(imageData.width),
+ new Integer(imageData.height)});
+ sizeLabel.setText(string);
+
+ string = createMsg(bundle.getString("Depth_value"), new Integer(imageData.depth));
+ depthLabel.setText(string);
+
+ string = createMsg(bundle.getString("Transparent_pixel_value"), pixelInfo(imageData.transparentPixel));
+ transparentPixelLabel.setText(string);
+
+ string = createMsg(bundle.getString("Time_to_load_value"), new Long(loadTime));
+ timeToLoadLabel.setText(string);
+
+ string = createMsg(bundle.getString("Animation_size_value"),
+ new Object[] {new Integer(loader.logicalScreenWidth),
+ new Integer(loader.logicalScreenHeight)});
+ screenSizeLabel.setText(string);
+
+ string = createMsg(bundle.getString("Background_pixel_value"), pixelInfo(loader.backgroundPixel));
+ backgroundPixelLabel.setText(string);
+
+ string = createMsg(bundle.getString("Image_location_value"),
+ new Object[] {new Integer(imageData.x), new Integer(imageData.y)});
+ locationLabel.setText(string);
+
+ string = createMsg(bundle.getString("Disposal_value"),
+ new Object[] {new Integer(imageData.disposalMethod),
+ disposalString(imageData.disposalMethod)});
+ disposalMethodLabel.setText(string);
+
+ int delay = imageData.delayTime * 10;
+ int delayUsed = visibleDelay(delay);
+ if (delay != delayUsed) {
+ string = createMsg(bundle.getString("Delay_value"),
+ new Object[] {new Integer(delay), new Integer(delayUsed)});
+ } else {
+ string = createMsg(bundle.getString("Delay_used"), new Integer(delay));
+ }
+ delayTimeLabel.setText(string);
+
+ if (loader.repeatCount == 0) {
+ string = createMsg( bundle.getString("Repeats_forever"), new Integer(loader.repeatCount));
+ } else {
+ string = createMsg(bundle.getString("Repeats_value"), new Integer(loader.repeatCount));
+ }
+ repeatCountLabel.setText(string);
+
+
+ if (imageData.palette.isDirect) {
+ string = bundle.getString("Palette_direct");
+ } else {
+ string = createMsg(bundle.getString("Palette_value"), new Integer(imageData.palette.getRGBs().length));
+ }
+ paletteLabel.setText(string);
+
+ string = createMsg(bundle.getString("Pixel_data_value"),
+ new Object[] {new Integer(imageData.bytesPerLine),
+ new Integer(imageData.scanlinePad),
+ depthInfo(imageData.depth)});
+ dataLabel.setText(string);
+
+ String data = dataHexDump(dataText.getLineDelimiter());
+ dataText.setText(data);
+
+ // bold the first column all the way down
+ int index = 0;
+ while((index = data.indexOf(':', index+1)) != -1)
+ dataText.setStyleRange(new StyleRange(index - INDEX_DIGITS, INDEX_DIGITS, dataText.getForeground(), dataText.getBackground(), SWT.BOLD));
+
+ statusLabel.setText("");
+
+ // Redraw both canvases.
+ paletteCanvas.redraw();
+ imageCanvas.redraw();
+ }
+
+ void paintImage(PaintEvent event) {
+ Image paintImage = image;
+ int transparentPixel = imageData.transparentPixel;
+ if (transparentPixel != -1 && !transparent) {
+ imageData.transparentPixel = -1;
+ paintImage = new Image(display, imageData);
+ }
+ int w = Math.round(imageData.width * xscale);
+ int h = Math.round(imageData.height * yscale);
+ event.gc.drawImage(
+ paintImage,
+ 0,
+ 0,
+ imageData.width,
+ imageData.height,
+ ix + imageData.x,
+ iy + imageData.y,
+ w,
+ h);
+ if (showMask && (imageData.getTransparencyType() != SWT.TRANSPARENCY_NONE)) {
+ ImageData maskImageData = imageData.getTransparencyMask();
+ Image maskImage = new Image(display, maskImageData);
+ event.gc.drawImage(
+ maskImage,
+ 0,
+ 0,
+ imageData.width,
+ imageData.height,
+ w + 10 + ix + imageData.x,
+ iy + imageData.y,
+ w,
+ h);
+ maskImage.dispose();
+ }
+ if (transparentPixel != -1 && !transparent) {
+ imageData.transparentPixel = transparentPixel;
+ paintImage.dispose();
+ }
+ }
+
+ void paintPalette(PaintEvent event) {
+ GC gc = event.gc;
+ gc.fillRectangle(paletteCanvas.getClientArea());
+ if (imageData.palette.isDirect) {
+ // For a direct palette, display the masks.
+ int y = py + 10;
+ int xTab = 50;
+ gc.drawString("rMsk", 10, y, true);
+ gc.drawString(toHex4ByteString(imageData.palette.redMask), xTab, y, true);
+ gc.drawString("gMsk", 10, y+=12, true);
+ gc.drawString(toHex4ByteString(imageData.palette.greenMask), xTab, y, true);
+ gc.drawString("bMsk", 10, y+=12, true);
+ gc.drawString(toHex4ByteString(imageData.palette.blueMask), xTab, y, true);
+ gc.drawString("rShf", 10, y+=12, true);
+ gc.drawString(Integer.toString(imageData.palette.redShift), xTab, y, true);
+ gc.drawString("gShf", 10, y+=12, true);
+ gc.drawString(Integer.toString(imageData.palette.greenShift), xTab, y, true);
+ gc.drawString("bShf", 10, y+=12, true);
+ gc.drawString(Integer.toString(imageData.palette.blueShift), xTab, y, true);
+ } else {
+ // For an indexed palette, display the palette colors and indices.
+ RGB[] rgbs = imageData.palette.getRGBs();
+ if (rgbs != null) {
+ int xTab1 = 40, xTab2 = 100;
+ for (int i = 0; i < rgbs.length; i++) {
+ int y = (i+1) * 10 + py;
+ gc.drawString(String.valueOf(i), 10, y, true);
+ gc.drawString(toHexByteString(rgbs[i].red) + toHexByteString(rgbs[i].green) + toHexByteString(rgbs[i].blue), xTab1, y, true);
+ Color color = new Color(display, rgbs[i]);
+ gc.setBackground(color);
+ gc.fillRectangle(xTab2, y+2, 10, 10);
+ color.dispose();
+ }
+ }
+ }
+ }
+
+ void resizeShell(ControlEvent event) {
+ if (image == null || shell.isDisposed())
+ return;
+ resizeScrollBars();
+ }
+
+ // Reset the scale combos to 1.
+ void resetScaleCombos() {
+ xscale = 1; yscale = 1;
+ scaleXCombo.select(scaleXCombo.indexOf("1"));
+ scaleYCombo.select(scaleYCombo.indexOf("1"));
+ }
+
+ // Reset the scroll bars to 0.
+ void resetScrollBars() {
+ if (image == null) return;
+ ix = 0; iy = 0; py = 0;
+ resizeScrollBars();
+ imageCanvas.getHorizontalBar().setSelection(0);
+ imageCanvas.getVerticalBar().setSelection(0);
+ paletteCanvas.getVerticalBar().setSelection(0);
+ }
+
+ void resizeScrollBars() {
+ // Set the max and thumb for the image canvas scroll bars.
+ ScrollBar horizontal = imageCanvas.getHorizontalBar();
+ ScrollBar vertical = imageCanvas.getVerticalBar();
+ Rectangle canvasBounds = imageCanvas.getClientArea();
+ int width = Math.round(imageData.width * xscale);
+ if (width > canvasBounds.width) {
+ // The image is wider than the canvas.
+ horizontal.setEnabled(true);
+ horizontal.setMaximum(width);
+ horizontal.setThumb(canvasBounds.width);
+ horizontal.setPageIncrement(canvasBounds.width);
+ } else {
+ // The canvas is wider than the image.
+ horizontal.setEnabled(false);
+ if (ix != 0) {
+ // Make sure the image is completely visible.
+ ix = 0;
+ imageCanvas.redraw();
+ }
+ }
+ int height = Math.round(imageData.height * yscale);
+ if (height > canvasBounds.height) {
+ // The image is taller than the canvas.
+ vertical.setEnabled(true);
+ vertical.setMaximum(height);
+ vertical.setThumb(canvasBounds.height);
+ vertical.setPageIncrement(canvasBounds.height);
+ } else {
+ // The canvas is taller than the image.
+ vertical.setEnabled(false);
+ if (iy != 0) {
+ // Make sure the image is completely visible.
+ iy = 0;
+ imageCanvas.redraw();
+ }
+ }
+
+ // Set the max and thumb for the palette canvas scroll bar.
+ vertical = paletteCanvas.getVerticalBar();
+ if (imageData.palette.isDirect) {
+ vertical.setEnabled(false);
+ } else { // indexed palette
+ canvasBounds = paletteCanvas.getClientArea();
+ int paletteHeight = imageData.palette.getRGBs().length * 10 + 20; // 10 pixels each index + 20 for margins.
+ vertical.setEnabled(true);
+ vertical.setMaximum(paletteHeight);
+ vertical.setThumb(canvasBounds.height);
+ vertical.setPageIncrement(canvasBounds.height);
+ }
+ }
+
+ /*
+ * Called when the image canvas' horizontal scrollbar is selected.
+ */
+ void scrollHorizontally(ScrollBar scrollBar) {
+ if (image == null) return;
+ Rectangle canvasBounds = imageCanvas.getClientArea();
+ int width = Math.round(imageData.width * xscale);
+ int height = Math.round(imageData.height * yscale);
+ if (width > canvasBounds.width) {
+ // Only scroll if the image is bigger than the canvas.
+ int x = -scrollBar.getSelection();
+ if (x + width < canvasBounds.width) {
+ // Don't scroll past the end of the image.
+ x = canvasBounds.width - width;
+ }
+ imageCanvas.scroll(x, iy, ix, iy, width, height, false);
+ ix = x;
+ }
+ }
+
+ /*
+ * Called when the image canvas' vertical scrollbar is selected.
+ */
+ void scrollVertically(ScrollBar scrollBar) {
+ if (image == null) return;
+ Rectangle canvasBounds = imageCanvas.getClientArea();
+ int width = Math.round(imageData.width * xscale);
+ int height = Math.round(imageData.height * yscale);
+ if (height > canvasBounds.height) {
+ // Only scroll if the image is bigger than the canvas.
+ int y = -scrollBar.getSelection();
+ if (y + height < canvasBounds.height) {
+ // Don't scroll past the end of the image.
+ y = canvasBounds.height - height;
+ }
+ imageCanvas.scroll(ix, y, ix, iy, width, height, false);
+ iy = y;
+ }
+ }
+
+ /*
+ * Called when the palette canvas' vertical scrollbar is selected.
+ */
+ void scrollPalette(ScrollBar scrollBar) {
+ if (image == null) return;
+ Rectangle canvasBounds = paletteCanvas.getClientArea();
+ int paletteHeight = imageData.palette.getRGBs().length * 10 + 20;
+ if (paletteHeight > canvasBounds.height) {
+ // Only scroll if the palette is bigger than the canvas.
+ int y = -scrollBar.getSelection();
+ if (y + paletteHeight < canvasBounds.height) {
+ // Don't scroll past the end of the palette.
+ y = canvasBounds.height - paletteHeight;
+ }
+ paletteCanvas.scroll(0, y, 0, py, paletteWidth, paletteHeight, false);
+ py = y;
+ }
+ }
+
+ /*
+ * Return a String containing a line-by-line dump of
+ * the data in the current imageData. The lineDelimiter
+ * parameter must be a string of length 1 or 2.
+ */
+ String dataHexDump(String lineDelimiter) {
+ if (image == null) return "";
+ char[] dump = new char[imageData.height * (6 + 3 * imageData.bytesPerLine + lineDelimiter.length())];
+ int index = 0;
+ for (int i = 0; i < imageData.data.length; i++) {
+ if (i % imageData.bytesPerLine == 0) {
+ int line = i / imageData.bytesPerLine;
+ dump[index++] = Character.forDigit(line / 1000 % 10, 10);
+ dump[index++] = Character.forDigit(line / 100 % 10, 10);
+ dump[index++] = Character.forDigit(line / 10 % 10, 10);
+ dump[index++] = Character.forDigit(line % 10, 10);
+ dump[index++] = ':';
+ dump[index++] = ' ';
+ }
+ byte b = imageData.data[i];
+ dump[index++] = Character.forDigit((b & 0xF0) >> 4, 16);
+ dump[index++] = Character.forDigit(b & 0x0F, 16);
+ dump[index++] = ' ';
+ if ((i + 1) % imageData.bytesPerLine == 0) {
+ dump[index++] = lineDelimiter.charAt(0);
+ if (lineDelimiter.length() > 1)
+ dump[index++] = lineDelimiter.charAt(1);
+ }
+ }
+ return new String(dump);
+ }
+
+ /*
+ * Open an error dialog displaying the specified information.
+ */
+ void showErrorDialog(String operation, String filename, Exception e) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
+ String message = createMsg(bundle.getString("Error"), new String[] {operation, filename});
+ String errorMessage = "";
+ if (e != null) {
+ if (e instanceof SWTException) {
+ SWTException swte = (SWTException) e;
+ errorMessage = swte.getMessage();
+ if (swte.throwable != null) {
+ errorMessage += ":\n" + swte.throwable.toString();
+ }
+ } else {
+ errorMessage = e.toString();
+ }
+ }
+ box.setMessage(message + errorMessage);
+ box.open();
+ }
+
+ /*
+ * Return a String describing how to analyze the bytes
+ * in the hex dump.
+ */
+ static String depthInfo(int depth) {
+ Object[] args = {new Integer(depth), ""};
+ switch (depth) {
+ case 1:
+ args[1] = createMsg(bundle.getString("Multi_pixels"),
+ new Object[] {new Integer(8), " [01234567]"});
+ break;
+ case 2:
+ args[1] = createMsg(bundle.getString("Multi_pixels"),
+ new Object[] {new Integer(4), "[00112233]"});
+ break;
+ case 4:
+ args[1] = createMsg(bundle.getString("Multi_pixels"),
+ new Object[] {new Integer(2), "[00001111]"});
+ break;
+ case 8:
+ args[1] = bundle.getString("One_byte");
+ break;
+ case 16:
+ args[1] = createMsg(bundle.getString("Multi_bytes"), new Integer(2));
+ break;
+ case 24:
+ args[1] = createMsg(bundle.getString("Multi_bytes"), new Integer(3));
+ break;
+ case 32:
+ args[1] = createMsg(bundle.getString("Multi_bytes"), new Integer(4));
+ break;
+ default:
+ args[1] = bundle.getString("Unsupported_lc");
+ }
+ return createMsg(bundle.getString("Depth_info"), args);
+ }
+
+ /*
+ * Return the specified number of milliseconds.
+ * If the specified number of milliseconds is too small
+ * to see a visual change, then return a higher number.
+ */
+ static int visibleDelay(int ms) {
+ if (ms < 20) return ms + 30;
+ if (ms < 30) return ms + 10;
+ return ms;
+ }
+
+ /*
+ * Return the specified byte value as a hex string,
+ * preserving leading 0's.
+ */
+ static String toHexByteString(int i) {
+ if (i <= 0x0f)
+ return "0" + Integer.toHexString(i);
+ return Integer.toHexString(i & 0xff);
+ }
+
+ /*
+ * Return the specified 4-byte value as a hex string,
+ * preserving leading 0's.
+ * (a bit 'brute force'... should probably use a loop...)
+ */
+ static String toHex4ByteString(int i) {
+ String hex = Integer.toHexString(i);
+ if (hex.length() == 1)
+ return "0000000" + hex;
+ if (hex.length() == 2)
+ return "000000" + hex;
+ if (hex.length() == 3)
+ return "00000" + hex;
+ if (hex.length() == 4)
+ return "0000" + hex;
+ if (hex.length() == 5)
+ return "000" + hex;
+ if (hex.length() == 6)
+ return "00" + hex;
+ if (hex.length() == 7)
+ return "0" + hex;
+ return hex;
+ }
+
+ /*
+ * Return a String describing the specified
+ * transparent or background pixel.
+ */
+ static String pixelInfo(int pixel) {
+ if (pixel == -1)
+ return pixel + " (" + bundle.getString("None_lc") + ")";
+ else
+ return pixel + " (0x" + Integer.toHexString(pixel) + ")";
+ }
+
+ /*
+ * Return a String describing the specified disposal method.
+ */
+ static String disposalString(int disposalMethod) {
+ switch (disposalMethod) {
+ case SWT.DM_FILL_NONE: return bundle.getString("None_lc");
+ case SWT.DM_FILL_BACKGROUND: return bundle.getString("Background_lc");
+ case SWT.DM_FILL_PREVIOUS: return bundle.getString("Previous_lc");
+ }
+ return bundle.getString("Unspecified_lc");
+ }
+
+ /*
+ * Return a String describing the specified image file type.
+ */
+ static String fileTypeString(int filetype) {
+ if (filetype == SWT.IMAGE_BMP)
+ return "BMP";
+ if (filetype == SWT.IMAGE_GIF)
+ return "GIF";
+ if (filetype == SWT.IMAGE_ICO)
+ return "ICO";
+ if (filetype == SWT.IMAGE_JPEG)
+ return "JPEG";
+ if (filetype == SWT.IMAGE_PNG)
+ return "PNG";
+ return bundle.getString("Unknown_ac");
+ }
+
+ /*
+ * Return the specified file's image type, based on its extension.
+ * Note that this is not a very robust way to determine image type,
+ * and it is only to be used in the absence of any better method.
+ */
+ static int determineFileType(String filename) {
+ String ext = filename.substring(filename.lastIndexOf('.') + 1);
+ if (ext.equalsIgnoreCase("bmp"))
+ return SWT.IMAGE_BMP;
+ if (ext.equalsIgnoreCase("gif"))
+ return SWT.IMAGE_GIF;
+ if (ext.equalsIgnoreCase("ico"))
+ return SWT.IMAGE_ICO;
+ if (ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg"))
+ return SWT.IMAGE_JPEG;
+ if (ext.equalsIgnoreCase("png"))
+ return SWT.IMAGE_PNG;
+ return SWT.IMAGE_UNDEFINED;
+ }
+
+ static String createMsg(String msg, Object[] args) {
+ MessageFormat formatter = new MessageFormat(msg);
+ return formatter.format(args);
+ }
+
+ static String createMsg(String msg, Object arg) {
+ MessageFormat formatter = new MessageFormat(msg);
+ return formatter.format(new Object[]{arg});
+ }
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaLineStyler.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaLineStyler.java
index dee3142e48..c5d74c2aad 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaLineStyler.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaLineStyler.java
@@ -1,374 +1,374 @@
-package org.eclipse.swt.examples.javaviewer;
-
-/*
+package org.eclipse.swt.examples.javaviewer;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.custom.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-import java.util.*;
-import java.io.*;
-
-class JavaLineStyler implements LineStyleListener {
- JavaScanner scanner = new JavaScanner();
- int[] tokenColors;
- Color[] colors;
- Vector blockComments = new Vector();
-
- public static final int EOF= -1;
- public static final int EOL= 10;
-
- public static final int WORD= 0;
- public static final int WHITE= 1;
- public static final int KEY= 2;
- public static final int COMMENT= 3;
- public static final int STRING= 5;
- public static final int OTHER= 6;
- public static final int NUMBER= 7;
-
- public static final int MAXIMUM_TOKEN= 8;
-
-public JavaLineStyler() {
- initializeColors();
- scanner = new JavaScanner();
-}
-
-Color getColor(int type) {
- if (type < 0 || type >= tokenColors.length) {
- return null;
- }
- return colors[tokenColors[type]];
-}
-
-boolean inBlockComment(int start, int end) {
- for (int i=0; i<blockComments.size(); i++) {
- int[] offsets = (int[])blockComments.elementAt(i);
- // start of comment in the line
- if ((offsets[0] >= start) && (offsets[0] <= end)) return true;
- // end of comment in the line
- if ((offsets[1] >= start) && (offsets[1] <= end)) return true;
- if ((offsets[0] <= start) && (offsets[1] >= end)) return true;
- }
- return false;
-}
-
-void initializeColors() {
- Display display = Display.getDefault();
- colors= new Color[] {
- new Color(display, new RGB(0, 0, 0)), // black
- new Color(display, new RGB(255, 0, 0)), // red
- new Color(display, new RGB(0, 255, 0)), // green
- new Color(display, new RGB(0, 0, 255)) // blue
- };
- tokenColors= new int[MAXIMUM_TOKEN];
- tokenColors[WORD]= 0;
- tokenColors[WHITE]= 0;
- tokenColors[KEY]= 3;
- tokenColors[COMMENT]= 1;
- tokenColors[STRING]= 2;
- tokenColors[OTHER]= 0;
- tokenColors[NUMBER]= 0;
-}
-
-void disposeColors() {
- for (int i=0;i<colors.length;i++) {
- colors[i].dispose();
- }
-}
-
-/**
- * Event.detail line start offset (input)
- * Event.text line text (input)
- * LineStyleEvent.styles Enumeration of StyleRanges, need to be in order. (output)
- * LineStyleEvent.background line background color (output)
- */
-public void lineGetStyle(LineStyleEvent event) {
- Vector styles = new Vector();
- int token;
- StyleRange lastStyle;
- // If the line is part of a block comment, create one style for the entire line.
- if (inBlockComment(event.lineOffset, event.lineOffset + event.lineText.length())) {
- styles.addElement(new StyleRange(event.lineOffset, event.lineText.length(), getColor(COMMENT), null));
- event.styles = new StyleRange[styles.size()];
- styles.copyInto(event.styles);
- return;
- }
- Color defaultFgColor = ((Control)event.widget).getForeground();
- scanner.setRange(event.lineText);
- token = scanner.nextToken();
- while (token != EOF) {
- if (token == OTHER) {
- // do nothing for non-colored tokens
- } else if (token != WHITE) {
- Color color = getColor(token);
- // Only create a style if the token color is different than the
- // widget's default foreground color and the token's style is not
- // bold. Keywords are bolded.
- if ((!color.equals(defaultFgColor)) || (token == KEY)) {
- StyleRange style = new StyleRange(scanner.getStartOffset() + event.lineOffset, scanner.getLength(), color, null);
- if (token == KEY) {
- style.fontStyle = SWT.BOLD;
- }
- if (styles.isEmpty()) {
- styles.addElement(style);
- } else {
- // Merge similar styles. Doing so will improve performance.
- lastStyle = (StyleRange)styles.lastElement();
- if (lastStyle.similarTo(style) && (lastStyle.start + lastStyle.length == style.start)) {
- lastStyle.length += style.length;
- } else {
- styles.addElement(style);
- }
- }
- }
- } else if ((!styles.isEmpty()) && ((lastStyle=(StyleRange)styles.lastElement()).fontStyle == SWT.BOLD)) {
- int start = scanner.getStartOffset() + event.lineOffset;
- lastStyle = (StyleRange)styles.lastElement();
- // A font style of SWT.BOLD implies that the last style
- // represents a java keyword.
- if (lastStyle.start + lastStyle.length == start) {
- // Have the white space take on the style before it to
- // minimize the number of style ranges created and the
- // number of font style changes during rendering.
- lastStyle.length += scanner.getLength();
- }
- }
- token= scanner.nextToken();
- }
- event.styles = new StyleRange[styles.size()];
- styles.copyInto(event.styles);
-}
-public void parseBlockComments(String text) {
- blockComments = new Vector();
- StringReader buffer = new StringReader(text);
- int ch;
- boolean blkComment = false;
- int cnt = 0;
- int[] offsets = new int[2];
- boolean done = false;
-
- try {
- while (!done) {
- switch (ch = buffer.read()) {
- case -1 : {
- if (blkComment) {
- offsets[1] = cnt;
- blockComments.addElement(offsets);
- }
- done = true;
- break;
- }
- case '/' : {
- ch = buffer.read();
- if ((ch == '*') && (!blkComment)) {
- offsets = new int[2];
- offsets[0] = cnt;
- blkComment = true;
- cnt++;
- } else {
- cnt++;
- }
- cnt++;
- break;
- }
- case '*' : {
- if (blkComment) {
- ch = buffer.read();
- cnt++;
- if (ch == '/') {
- blkComment = false;
- offsets[1] = cnt;
- blockComments.addElement(offsets);
- }
- }
- cnt++;
- break;
- }
- default : {
- cnt++;
- break;
- }
- }
- }
- } catch(IOException e) {
- // ignore errors
- }
-}
-
-/**
- * A simple fuzzy scanner for Java
- */
-public class JavaScanner {
-
- protected Hashtable fgKeys= null;
- protected StringBuffer fBuffer= new StringBuffer();
- protected String fDoc;
- protected int fPos;
- protected int fEnd;
- protected int fStartToken;
- protected boolean fEofSeen= false;
-
- private String[] fgKeywords= {
- "abstract",
- "boolean", "break", "byte",
- "case", "catch", "char", "class", "continue",
- "default", "do", "double",
- "else", "extends",
- "false", "final", "finally", "float", "for",
- "if", "implements", "import", "instanceof", "int", "interface",
- "long",
- "native", "new", "null",
- "package", "private", "protected", "public",
- "return",
- "short", "static", "super", "switch", "synchronized",
- "this", "throw", "throws", "transient", "true", "try",
- "void", "volatile",
- "while"
- };
-
- public JavaScanner() {
- initialize();
- }
-
- /**
- * Returns the ending location of the current token in the document.
- */
- public final int getLength() {
- return fPos - fStartToken;
- }
-
- /**
- * Initialize the lookup table.
- */
- void initialize() {
- fgKeys= new Hashtable();
- Integer k= new Integer(KEY);
- for (int i= 0; i < fgKeywords.length; i++)
- fgKeys.put(fgKeywords[i], k);
- }
-
- /**
- * Returns the starting location of the current token in the document.
- */
- public final int getStartOffset() {
- return fStartToken;
- }
-
- /**
- * Returns the next lexical token in the document.
- */
- public int nextToken() {
- int c;
- fStartToken= fPos;
- while (true) {
- switch (c= read()) {
- case EOF:
- return EOF;
- case '/': // comment
- c= read();
- if (c == '/') {
- while (true) {
- c= read();
- if ((c == EOF) || (c == EOL)) {
- unread(c);
- return COMMENT;
- }
- }
- } else {
- unread(c);
- }
- return OTHER;
- case '\'': // char const
- character: for(;;) {
- c= read();
- switch (c) {
- case '\'':
- return STRING;
- case EOF:
- unread(c);
- return STRING;
- case '\\':
- c= read();
- break;
- }
- }
-
- case '"': // string
- string: for (;;) {
- c= read();
- switch (c) {
- case '"':
- return STRING;
- case EOF:
- unread(c);
- return STRING;
- case '\\':
- c= read();
- break;
- }
- }
-
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- do {
- c= read();
- } while(Character.isDigit((char)c));
- unread(c);
- return NUMBER;
- default:
- if (Character.isWhitespace((char)c)) {
- do {
- c= read();
- } while(Character.isWhitespace((char)c));
- unread(c);
- return WHITE;
- }
- if (Character.isJavaIdentifierStart((char)c)) {
- fBuffer.setLength(0);
- do {
- fBuffer.append((char)c);
- c= read();
- } while(Character.isJavaIdentifierPart((char)c));
- unread(c);
- Integer i= (Integer) fgKeys.get(fBuffer.toString());
- if (i != null)
- return i.intValue();
- return WORD;
- }
- return OTHER;
- }
- }
- }
-
- /**
- * Returns next character.
- */
- protected int read() {
- if (fPos <= fEnd) {
- return fDoc.charAt(fPos++);
- }
- return EOF;
- }
-
- public void setRange(String text) {
- fDoc= text;
- fPos= 0;
- fEnd= fDoc.length() -1;
- }
-
- protected void unread(int c) {
- if (c != EOF)
- fPos--;
- }
-}
-
-
-
-
-
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.custom.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+import java.util.*;
+import java.io.*;
+
+class JavaLineStyler implements LineStyleListener {
+ JavaScanner scanner = new JavaScanner();
+ int[] tokenColors;
+ Color[] colors;
+ Vector blockComments = new Vector();
+
+ public static final int EOF= -1;
+ public static final int EOL= 10;
+
+ public static final int WORD= 0;
+ public static final int WHITE= 1;
+ public static final int KEY= 2;
+ public static final int COMMENT= 3;
+ public static final int STRING= 5;
+ public static final int OTHER= 6;
+ public static final int NUMBER= 7;
+
+ public static final int MAXIMUM_TOKEN= 8;
+
+public JavaLineStyler() {
+ initializeColors();
+ scanner = new JavaScanner();
+}
+
+Color getColor(int type) {
+ if (type < 0 || type >= tokenColors.length) {
+ return null;
+ }
+ return colors[tokenColors[type]];
+}
+
+boolean inBlockComment(int start, int end) {
+ for (int i=0; i<blockComments.size(); i++) {
+ int[] offsets = (int[])blockComments.elementAt(i);
+ // start of comment in the line
+ if ((offsets[0] >= start) && (offsets[0] <= end)) return true;
+ // end of comment in the line
+ if ((offsets[1] >= start) && (offsets[1] <= end)) return true;
+ if ((offsets[0] <= start) && (offsets[1] >= end)) return true;
+ }
+ return false;
+}
+
+void initializeColors() {
+ Display display = Display.getDefault();
+ colors= new Color[] {
+ new Color(display, new RGB(0, 0, 0)), // black
+ new Color(display, new RGB(255, 0, 0)), // red
+ new Color(display, new RGB(0, 255, 0)), // green
+ new Color(display, new RGB(0, 0, 255)) // blue
+ };
+ tokenColors= new int[MAXIMUM_TOKEN];
+ tokenColors[WORD]= 0;
+ tokenColors[WHITE]= 0;
+ tokenColors[KEY]= 3;
+ tokenColors[COMMENT]= 1;
+ tokenColors[STRING]= 2;
+ tokenColors[OTHER]= 0;
+ tokenColors[NUMBER]= 0;
+}
+
+void disposeColors() {
+ for (int i=0;i<colors.length;i++) {
+ colors[i].dispose();
+ }
+}
+
+/**
+ * Event.detail line start offset (input)
+ * Event.text line text (input)
+ * LineStyleEvent.styles Enumeration of StyleRanges, need to be in order. (output)
+ * LineStyleEvent.background line background color (output)
+ */
+public void lineGetStyle(LineStyleEvent event) {
+ Vector styles = new Vector();
+ int token;
+ StyleRange lastStyle;
+ // If the line is part of a block comment, create one style for the entire line.
+ if (inBlockComment(event.lineOffset, event.lineOffset + event.lineText.length())) {
+ styles.addElement(new StyleRange(event.lineOffset, event.lineText.length(), getColor(COMMENT), null));
+ event.styles = new StyleRange[styles.size()];
+ styles.copyInto(event.styles);
+ return;
+ }
+ Color defaultFgColor = ((Control)event.widget).getForeground();
+ scanner.setRange(event.lineText);
+ token = scanner.nextToken();
+ while (token != EOF) {
+ if (token == OTHER) {
+ // do nothing for non-colored tokens
+ } else if (token != WHITE) {
+ Color color = getColor(token);
+ // Only create a style if the token color is different than the
+ // widget's default foreground color and the token's style is not
+ // bold. Keywords are bolded.
+ if ((!color.equals(defaultFgColor)) || (token == KEY)) {
+ StyleRange style = new StyleRange(scanner.getStartOffset() + event.lineOffset, scanner.getLength(), color, null);
+ if (token == KEY) {
+ style.fontStyle = SWT.BOLD;
+ }
+ if (styles.isEmpty()) {
+ styles.addElement(style);
+ } else {
+ // Merge similar styles. Doing so will improve performance.
+ lastStyle = (StyleRange)styles.lastElement();
+ if (lastStyle.similarTo(style) && (lastStyle.start + lastStyle.length == style.start)) {
+ lastStyle.length += style.length;
+ } else {
+ styles.addElement(style);
+ }
+ }
+ }
+ } else if ((!styles.isEmpty()) && ((lastStyle=(StyleRange)styles.lastElement()).fontStyle == SWT.BOLD)) {
+ int start = scanner.getStartOffset() + event.lineOffset;
+ lastStyle = (StyleRange)styles.lastElement();
+ // A font style of SWT.BOLD implies that the last style
+ // represents a java keyword.
+ if (lastStyle.start + lastStyle.length == start) {
+ // Have the white space take on the style before it to
+ // minimize the number of style ranges created and the
+ // number of font style changes during rendering.
+ lastStyle.length += scanner.getLength();
+ }
+ }
+ token= scanner.nextToken();
+ }
+ event.styles = new StyleRange[styles.size()];
+ styles.copyInto(event.styles);
+}
+public void parseBlockComments(String text) {
+ blockComments = new Vector();
+ StringReader buffer = new StringReader(text);
+ int ch;
+ boolean blkComment = false;
+ int cnt = 0;
+ int[] offsets = new int[2];
+ boolean done = false;
+
+ try {
+ while (!done) {
+ switch (ch = buffer.read()) {
+ case -1 : {
+ if (blkComment) {
+ offsets[1] = cnt;
+ blockComments.addElement(offsets);
+ }
+ done = true;
+ break;
+ }
+ case '/' : {
+ ch = buffer.read();
+ if ((ch == '*') && (!blkComment)) {
+ offsets = new int[2];
+ offsets[0] = cnt;
+ blkComment = true;
+ cnt++;
+ } else {
+ cnt++;
+ }
+ cnt++;
+ break;
+ }
+ case '*' : {
+ if (blkComment) {
+ ch = buffer.read();
+ cnt++;
+ if (ch == '/') {
+ blkComment = false;
+ offsets[1] = cnt;
+ blockComments.addElement(offsets);
+ }
+ }
+ cnt++;
+ break;
+ }
+ default : {
+ cnt++;
+ break;
+ }
+ }
+ }
+ } catch(IOException e) {
+ // ignore errors
+ }
+}
+
+/**
+ * A simple fuzzy scanner for Java
+ */
+public class JavaScanner {
+
+ protected Hashtable fgKeys= null;
+ protected StringBuffer fBuffer= new StringBuffer();
+ protected String fDoc;
+ protected int fPos;
+ protected int fEnd;
+ protected int fStartToken;
+ protected boolean fEofSeen= false;
+
+ private String[] fgKeywords= {
+ "abstract",
+ "boolean", "break", "byte",
+ "case", "catch", "char", "class", "continue",
+ "default", "do", "double",
+ "else", "extends",
+ "false", "final", "finally", "float", "for",
+ "if", "implements", "import", "instanceof", "int", "interface",
+ "long",
+ "native", "new", "null",
+ "package", "private", "protected", "public",
+ "return",
+ "short", "static", "super", "switch", "synchronized",
+ "this", "throw", "throws", "transient", "true", "try",
+ "void", "volatile",
+ "while"
+ };
+
+ public JavaScanner() {
+ initialize();
+ }
+
+ /**
+ * Returns the ending location of the current token in the document.
+ */
+ public final int getLength() {
+ return fPos - fStartToken;
+ }
+
+ /**
+ * Initialize the lookup table.
+ */
+ void initialize() {
+ fgKeys= new Hashtable();
+ Integer k= new Integer(KEY);
+ for (int i= 0; i < fgKeywords.length; i++)
+ fgKeys.put(fgKeywords[i], k);
+ }
+
+ /**
+ * Returns the starting location of the current token in the document.
+ */
+ public final int getStartOffset() {
+ return fStartToken;
+ }
+
+ /**
+ * Returns the next lexical token in the document.
+ */
+ public int nextToken() {
+ int c;
+ fStartToken= fPos;
+ while (true) {
+ switch (c= read()) {
+ case EOF:
+ return EOF;
+ case '/': // comment
+ c= read();
+ if (c == '/') {
+ while (true) {
+ c= read();
+ if ((c == EOF) || (c == EOL)) {
+ unread(c);
+ return COMMENT;
+ }
+ }
+ } else {
+ unread(c);
+ }
+ return OTHER;
+ case '\'': // char const
+ character: for(;;) {
+ c= read();
+ switch (c) {
+ case '\'':
+ return STRING;
+ case EOF:
+ unread(c);
+ return STRING;
+ case '\\':
+ c= read();
+ break;
+ }
+ }
+
+ case '"': // string
+ string: for (;;) {
+ c= read();
+ switch (c) {
+ case '"':
+ return STRING;
+ case EOF:
+ unread(c);
+ return STRING;
+ case '\\':
+ c= read();
+ break;
+ }
+ }
+
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ do {
+ c= read();
+ } while(Character.isDigit((char)c));
+ unread(c);
+ return NUMBER;
+ default:
+ if (Character.isWhitespace((char)c)) {
+ do {
+ c= read();
+ } while(Character.isWhitespace((char)c));
+ unread(c);
+ return WHITE;
+ }
+ if (Character.isJavaIdentifierStart((char)c)) {
+ fBuffer.setLength(0);
+ do {
+ fBuffer.append((char)c);
+ c= read();
+ } while(Character.isJavaIdentifierPart((char)c));
+ unread(c);
+ Integer i= (Integer) fgKeys.get(fBuffer.toString());
+ if (i != null)
+ return i.intValue();
+ return WORD;
+ }
+ return OTHER;
+ }
+ }
+ }
+
+ /**
+ * Returns next character.
+ */
+ protected int read() {
+ if (fPos <= fEnd) {
+ return fDoc.charAt(fPos++);
+ }
+ return EOF;
+ }
+
+ public void setRange(String text) {
+ fDoc= text;
+ fPos= 0;
+ fEnd= fDoc.length() -1;
+ }
+
+ protected void unread(int c) {
+ if (c != EOF)
+ fPos--;
+ }
+}
+
+
+
+
+
}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaViewer.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaViewer.java
index ffa2664893..88c4b2a069 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaViewer.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaViewer.java
@@ -1,176 +1,176 @@
-package org.eclipse.swt.examples.javaviewer;
-
-/*
+package org.eclipse.swt.examples.javaviewer;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.custom.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.widgets.*;
-import java.util.*;
-import java.io.*;
-import java.text.*;
-
-/**
- */
-public class JavaViewer {
- Shell shell;
- StyledText text;
- JavaLineStyler lineStyler = new JavaLineStyler();
- FileDialog fileDialog;
- static ResourceBundle resources = ResourceBundle.getBundle("examples_javaviewer");
-
-Menu createFileMenu() {
- Menu bar = shell.getMenuBar ();
- Menu menu = new Menu (bar);
- MenuItem item;
-
- // Open
- item = new MenuItem (menu, SWT.CASCADE);
- item.setText (resources.getString("Open_menuitem"));
- item.setAccelerator(SWT.MOD1 + 'O');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- openFile();
- }
- });
-
- // Exit
- item = new MenuItem (menu, SWT.PUSH);
- item.setText (resources.getString("Exit_menuitem"));
- item.addSelectionListener (new SelectionAdapter () {
- public void widgetSelected (SelectionEvent e) {
- menuFileExit ();
- }
- });
- return menu;
-}
-
-void createMenuBar () {
- Menu bar = new Menu (shell, SWT.BAR);
- shell.setMenuBar (bar);
-
- MenuItem fileItem = new MenuItem (bar, SWT.CASCADE);
- fileItem.setText (resources.getString("File_menuitem"));
- fileItem.setMenu (createFileMenu ());
-
-}
-
-void createShell (Display display) {
- shell = new Shell (display);
- shell.setText (resources.getString("Window_title"));
- GridLayout layout = new GridLayout();
- layout.numColumns = 1;
- shell.setLayout(layout);
- shell.addShellListener (new ShellAdapter () {
- public void shellClosed (ShellEvent e) {
- lineStyler.disposeColors();
- text.removeLineStyleListener(lineStyler);
- }
- });
-}
-void createStyledText() {
- text = new StyledText (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
- GridData spec = new GridData();
- spec.horizontalAlignment = GridData.FILL;
- spec.grabExcessHorizontalSpace = true;
- spec.verticalAlignment = GridData.FILL;
- spec.grabExcessVerticalSpace = true;
- text.setLayoutData(spec);
- text.addLineStyleListener(lineStyler);
- text.setEditable(false);
- Color bg = Display.getDefault().getSystemColor(SWT.COLOR_GRAY);
- text.setBackground(bg);
-}
-
-void displayError(String msg) {
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
- box.setMessage(msg);
- box.open();
-}
-
-public static void main (String [] args) {
- Display display = new Display();
- JavaViewer example = new JavaViewer ();
- Shell shell = example.open (display);
- while (!shell.isDisposed ())
- if (!display.readAndDispatch ()) display.sleep ();
- display.dispose ();
-}
-
-public Shell open (Display display) {
- createShell (display);
- createMenuBar ();
- createStyledText ();
- shell.setSize(500, 400);
- shell.open ();
- return shell;
-}
-
-void openFile() {
- final String textString;
- if (fileDialog == null) {
- fileDialog = new FileDialog(shell, SWT.OPEN);
- }
-
- fileDialog.setFilterExtensions(new String[] {"*.java", "*.*"});
- fileDialog.open();
- String name = fileDialog.getFileName();
-
- if ((name == null) || (name.length() == 0)) return;
-
- File file = new File(fileDialog.getFilterPath(), name);
- if (!file.exists()) {
- String message = MessageFormat.format(resources.getString("Err_file_no_exist"), new String[] {file.getName()});
- displayError(message);
- return;
- }
-
- try {
- FileInputStream stream= new FileInputStream(file.getPath());
- try {
- Reader in = new BufferedReader(new InputStreamReader(stream));
- char[] readBuffer= new char[2048];
- StringBuffer buffer= new StringBuffer((int) file.length());
- int n;
- while ((n = in.read(readBuffer)) > 0) {
- buffer.append(readBuffer, 0, n);
- }
- textString = buffer.toString();
- stream.close();
- }
- catch (IOException e) {
- // Err_file_io
- String message = MessageFormat.format(resources.getString("Err_file_io"), new String[] {file.getName()});
- displayError(message);
- return;
- }
- }
- catch (FileNotFoundException e) {
- String message = MessageFormat.format(resources.getString("Err_not_found"), new String[] {file.getName()});
- displayError(message);
- return;
- }
- // Guard against superfluous mouse move events -- defer action until later
- Display display = text.getDisplay();
- display.asyncExec(new Runnable() {
- public void run() {
- text.setText(textString);
- }
- });
-
- // parse the block comments up front since block comments can go across
- // lines - inefficient way of doing this
- lineStyler.parseBlockComments(textString);
-}
-
-void menuFileExit () {
- shell.close ();
-}
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.custom.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.widgets.*;
+import java.util.*;
+import java.io.*;
+import java.text.*;
+
+/**
+ */
+public class JavaViewer {
+ Shell shell;
+ StyledText text;
+ JavaLineStyler lineStyler = new JavaLineStyler();
+ FileDialog fileDialog;
+ static ResourceBundle resources = ResourceBundle.getBundle("examples_javaviewer");
+
+Menu createFileMenu() {
+ Menu bar = shell.getMenuBar ();
+ Menu menu = new Menu (bar);
+ MenuItem item;
+
+ // Open
+ item = new MenuItem (menu, SWT.CASCADE);
+ item.setText (resources.getString("Open_menuitem"));
+ item.setAccelerator(SWT.MOD1 + 'O');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ openFile();
+ }
+ });
+
+ // Exit
+ item = new MenuItem (menu, SWT.PUSH);
+ item.setText (resources.getString("Exit_menuitem"));
+ item.addSelectionListener (new SelectionAdapter () {
+ public void widgetSelected (SelectionEvent e) {
+ menuFileExit ();
+ }
+ });
+ return menu;
+}
+
+void createMenuBar () {
+ Menu bar = new Menu (shell, SWT.BAR);
+ shell.setMenuBar (bar);
+
+ MenuItem fileItem = new MenuItem (bar, SWT.CASCADE);
+ fileItem.setText (resources.getString("File_menuitem"));
+ fileItem.setMenu (createFileMenu ());
+
+}
+
+void createShell (Display display) {
+ shell = new Shell (display);
+ shell.setText (resources.getString("Window_title"));
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 1;
+ shell.setLayout(layout);
+ shell.addShellListener (new ShellAdapter () {
+ public void shellClosed (ShellEvent e) {
+ lineStyler.disposeColors();
+ text.removeLineStyleListener(lineStyler);
+ }
+ });
+}
+void createStyledText() {
+ text = new StyledText (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
+ GridData spec = new GridData();
+ spec.horizontalAlignment = GridData.FILL;
+ spec.grabExcessHorizontalSpace = true;
+ spec.verticalAlignment = GridData.FILL;
+ spec.grabExcessVerticalSpace = true;
+ text.setLayoutData(spec);
+ text.addLineStyleListener(lineStyler);
+ text.setEditable(false);
+ Color bg = Display.getDefault().getSystemColor(SWT.COLOR_GRAY);
+ text.setBackground(bg);
+}
+
+void displayError(String msg) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
+ box.setMessage(msg);
+ box.open();
+}
+
+public static void main (String [] args) {
+ Display display = new Display();
+ JavaViewer example = new JavaViewer ();
+ Shell shell = example.open (display);
+ while (!shell.isDisposed ())
+ if (!display.readAndDispatch ()) display.sleep ();
+ display.dispose ();
+}
+
+public Shell open (Display display) {
+ createShell (display);
+ createMenuBar ();
+ createStyledText ();
+ shell.setSize(500, 400);
+ shell.open ();
+ return shell;
+}
+
+void openFile() {
+ final String textString;
+ if (fileDialog == null) {
+ fileDialog = new FileDialog(shell, SWT.OPEN);
+ }
+
+ fileDialog.setFilterExtensions(new String[] {"*.java", "*.*"});
+ fileDialog.open();
+ String name = fileDialog.getFileName();
+
+ if ((name == null) || (name.length() == 0)) return;
+
+ File file = new File(fileDialog.getFilterPath(), name);
+ if (!file.exists()) {
+ String message = MessageFormat.format(resources.getString("Err_file_no_exist"), new String[] {file.getName()});
+ displayError(message);
+ return;
+ }
+
+ try {
+ FileInputStream stream= new FileInputStream(file.getPath());
+ try {
+ Reader in = new BufferedReader(new InputStreamReader(stream));
+ char[] readBuffer= new char[2048];
+ StringBuffer buffer= new StringBuffer((int) file.length());
+ int n;
+ while ((n = in.read(readBuffer)) > 0) {
+ buffer.append(readBuffer, 0, n);
+ }
+ textString = buffer.toString();
+ stream.close();
+ }
+ catch (IOException e) {
+ // Err_file_io
+ String message = MessageFormat.format(resources.getString("Err_file_io"), new String[] {file.getName()});
+ displayError(message);
+ return;
+ }
+ }
+ catch (FileNotFoundException e) {
+ String message = MessageFormat.format(resources.getString("Err_not_found"), new String[] {file.getName()});
+ displayError(message);
+ return;
+ }
+ // Guard against superfluous mouse move events -- defer action until later
+ Display display = text.getDisplay();
+ display.asyncExec(new Runnable() {
+ public void run() {
+ text.setText(textString);
+ }
+ });
+
+ // parse the block comments up front since block comments can go across
+ // lines - inefficient way of doing this
+ lineStyler.parseBlockComments(textString);
+}
+
+void menuFileExit () {
+ shell.close ();
+}
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/Images.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/Images.java
index 49c7b59e40..6f15995ce3 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/Images.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/Images.java
@@ -1,54 +1,54 @@
-package org.eclipse.swt.examples.texteditor;
-
-/*
+package org.eclipse.swt.examples.texteditor;
+
+/*
* (c) Copyright IBM Corp. 2000, 2002.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.widgets.*;
-
-public class Images {
-
- // Bitmap Images
- public Image Bold;
- public Image Red;
- public Image Green;
- public Image Blue;
- public Image Erase;
-
- Image [] AllBitmaps;
-
-Images () {
-}
-
-public void freeAll () {
- for (int i=0; i<AllBitmaps.length; i++) AllBitmaps [i].dispose ();
- AllBitmaps = null;
-}
-
-Image createBitmapImage(Display display, String fileName) {
- ImageData source = new ImageData(Images.class.getResourceAsStream(fileName+".bmp"));
- ImageData mask = new ImageData(Images.class.getResourceAsStream(fileName+"_mask"+".bmp"));
- return new Image (display, source, mask);
-}
-
-public void loadAll (Display display) {
- // Bitmap Images
- Bold = createBitmapImage (display, "bold");
- Red = createBitmapImage (display, "red");
- Green = createBitmapImage (display, "green");
- Blue = createBitmapImage (display, "blue");
- Erase = createBitmapImage (display, "erase");
-
- AllBitmaps = new Image [] {
- Bold,
- Red,
- Green,
- Blue,
- Erase,
- };
-}
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.widgets.*;
+
+public class Images {
+
+ // Bitmap Images
+ public Image Bold;
+ public Image Red;
+ public Image Green;
+ public Image Blue;
+ public Image Erase;
+
+ Image [] AllBitmaps;
+
+Images () {
+}
+
+public void freeAll () {
+ for (int i=0; i<AllBitmaps.length; i++) AllBitmaps [i].dispose ();
+ AllBitmaps = null;
+}
+
+Image createBitmapImage(Display display, String fileName) {
+ ImageData source = new ImageData(Images.class.getResourceAsStream(fileName+".bmp"));
+ ImageData mask = new ImageData(Images.class.getResourceAsStream(fileName+"_mask"+".bmp"));
+ return new Image (display, source, mask);
+}
+
+public void loadAll (Display display) {
+ // Bitmap Images
+ Bold = createBitmapImage (display, "bold");
+ Red = createBitmapImage (display, "red");
+ Green = createBitmapImage (display, "green");
+ Blue = createBitmapImage (display, "blue");
+ Erase = createBitmapImage (display, "erase");
+
+ AllBitmaps = new Image [] {
+ Bold,
+ Red,
+ Green,
+ Blue,
+ Erase,
+ };
+}
+}
diff --git a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/TextEditor.java b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/TextEditor.java
index af67c24c30..64ac40c733 100755
--- a/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/TextEditor.java
+++ b/examples/org.eclipse.swt.examples/src/org/eclipse/swt/examples/texteditor/TextEditor.java
@@ -1,344 +1,344 @@
-package org.eclipse.swt.examples.texteditor;
-
-/*
+package org.eclipse.swt.examples.texteditor;
+
+/*
* Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- */
-
-import org.eclipse.swt.*;
-import org.eclipse.swt.custom.*;
-import org.eclipse.swt.events.*;
-import org.eclipse.swt.graphics.*;
-import org.eclipse.swt.layout.*;
-import org.eclipse.swt.widgets.*;
-import java.util.*;
-
-/**
- */
-public class TextEditor {
- Shell shell;
- ToolBar toolBar;
- StyledText text;
-
- Images images = new Images();
- Vector cachedStyles = new Vector();
- Color RED = null;
- Color BLUE = null;
- Color GREEN = null;
- Font font = null;
-
- boolean isBold = false;
-
- ExtendedModifyListener extendedModifyListener;
- static ResourceBundle resources = ResourceBundle.getBundle("examples_texteditor");
-
-Menu createEditMenu() {
- Menu bar = shell.getMenuBar ();
- Menu menu = new Menu (bar);
-
- MenuItem item = new MenuItem (menu, SWT.PUSH);
- item.setText (resources.getString("Cut_menuitem"));
- item.setAccelerator(SWT.MOD1 + 'X');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- handleCutCopy();
- text.cut();
- }
- });
-
- item = new MenuItem (menu, SWT.PUSH);
- item.setText (resources.getString("Copy_menuitem"));
- item.setAccelerator(SWT.MOD1 + 'C');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- handleCutCopy();
- text.copy();
- }
- });
-
- item = new MenuItem (menu, SWT.PUSH);
- item.setText (resources.getString("Paste_menuitem"));
- item.setAccelerator(SWT.MOD1 + 'V');
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- text.paste();
- }
- });
-
- new MenuItem (menu, SWT.SEPARATOR);
-
- item = new MenuItem (menu, SWT.PUSH);
- item.setText (resources.getString("Font_menuitem"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- setFont();
- }
- });
- return menu;
-}
-
-Menu createFileMenu() {
- Menu bar = shell.getMenuBar ();
- Menu menu = new Menu (bar);
-
- MenuItem item = new MenuItem (menu, SWT.PUSH);
- item.setText (resources.getString("Exit_menuitem"));
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- shell.close ();
- }
- });
-
- return menu;
-}
-
-/*
- * Set the text state to bold.
- */
-void bold(boolean bold) {
- isBold = bold;
- Point sel = text.getSelectionRange();
- if ((sel != null) && (sel.y != 0)) {
- StyleRange style;
- int fontStyle = SWT.NORMAL;
- if (isBold) fontStyle = SWT.BOLD;
- style = new StyleRange(sel.x, sel.y, null, null, fontStyle);
- text.setStyleRange(style);
- }
- text.setSelectionRange(sel.x + sel.y, 0);
-}
-/*
- * Clear all style data for the selected text.
- */
-void clear() {
- Point sel = text.getSelectionRange();
- if ((sel != null) && (sel.y != 0)) {
- StyleRange style;
- style = new StyleRange(sel.x, sel.y, null, null, SWT.NORMAL);
- text.setStyleRange(style);
- }
- text.setSelectionRange(sel.x + sel.y, 0);
-}
-/*
- * Set the foreground color for the selected text.
- */
-void fgColor(int color) {
- Point sel = text.getSelectionRange();
- if ((sel == null) || (sel.y == 0)) return;
- Color fg;
- if (color == SWT.COLOR_RED) {
- fg = RED;
- } else if (color == SWT.COLOR_GREEN) {
- fg = GREEN;
- } else if (color == SWT.COLOR_BLUE) {
- fg = BLUE;
- } else {
- fg = null;
- }
- StyleRange style;
- for (int i = sel.x; i<sel.x+sel.y; i++) {
- StyleRange range = text.getStyleRangeAtOffset(i);
- if (range == null) {style = new StyleRange(i, 1, fg, null, SWT.NORMAL);}
- else {style = new StyleRange(i, 1, fg, null, range.fontStyle);};
- text.setStyleRange(style);
- }
- text.setSelectionRange(sel.x + sel.y, 0);
-}
-void createMenuBar () {
- Menu bar = new Menu (shell, SWT.BAR);
- shell.setMenuBar (bar);
-
- MenuItem fileItem = new MenuItem (bar, SWT.CASCADE);
- fileItem.setText (resources.getString("File_menuitem"));
- fileItem.setMenu (createFileMenu ());
-
- MenuItem editItem = new MenuItem (bar, SWT.CASCADE);
- editItem.setText (resources.getString("Edit_menuitem"));
- editItem.setMenu (createEditMenu ());
-}
-
-void createShell (Display display) {
- shell = new Shell (display);
- shell.setText (resources.getString("Window_title"));
- images.loadAll (display);
- GridLayout layout = new GridLayout();
- layout.numColumns = 1;
- shell.setLayout(layout);
- shell.addDisposeListener (new DisposeListener () {
- public void widgetDisposed (DisposeEvent e) {
- if (font != null) font.dispose();
- images.freeAll ();
- RED.dispose();
- GREEN.dispose();
- BLUE.dispose();
- }
- });
-}
-void createStyledText() {
- initializeColors();
- text = new StyledText (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
- GridData spec = new GridData();
- spec.horizontalAlignment = GridData.FILL;
- spec.grabExcessHorizontalSpace = true;
- spec.verticalAlignment = GridData.FILL;
- spec.grabExcessVerticalSpace = true;
- text.setLayoutData(spec);
- extendedModifyListener = new ExtendedModifyListener() {
- public void modifyText(ExtendedModifyEvent e) {
- handleExtendedModify(e);
- }
- };
- text.addExtendedModifyListener(extendedModifyListener);
-}
-
-void createToolBar() {
- toolBar = new ToolBar(shell, SWT.NULL);
-
- ToolItem item = new ToolItem(toolBar, SWT.CHECK);
- item.setImage(images.Bold);
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- bold(((ToolItem)event.widget).getSelection());
- }
- });
-
- item = new ToolItem(toolBar, SWT.SEPARATOR);
-
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(images.Red);
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fgColor(SWT.COLOR_RED);
- }
- });
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(images.Green);
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fgColor(SWT.COLOR_GREEN);
- }
- });
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(images.Blue);
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fgColor(SWT.COLOR_BLUE);
- }
- });
-
- item = new ToolItem(toolBar, SWT.SEPARATOR);
-
- item = new ToolItem(toolBar, SWT.PUSH);
- item.setImage(images.Erase);
- item.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- clear();
- }
- });
-}
-void displayError(String msg) {
- MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
- box.setMessage(msg);
- box.open();
-}
-/*
- * Cache the style information for text that has been cut or copied.
- */
-void handleCutCopy() {
- // Save the cut/copied style info so that during paste we will maintain
- // the style information. Cut/copied text is put in the clipboard in
- // RTF format, but is not pasted in RTF format. The other way to
- // handle the pasting of styles would be to access the Clipboard directly and
- // parse the RTF text.
- cachedStyles = new Vector();
- Point sel = text.getSelectionRange();
- int startX = sel.x;
- for (int i=sel.x; i<=sel.x+sel.y-1; i++) {
- StyleRange style = text.getStyleRangeAtOffset(i);
- if (style != null) {
- style.start = style.start - startX;
- if (!cachedStyles.isEmpty()) {
- StyleRange lastStyle = (StyleRange)cachedStyles.lastElement();
- if (lastStyle.similarTo(style) && lastStyle.start + lastStyle.length == style.start) {
- lastStyle.length++;
- } else {
- cachedStyles.addElement(style);
- }
- } else {
- cachedStyles.addElement(style);
- }
- }
- }
-}
-void handleExtendedModify(ExtendedModifyEvent event) {
- if (event.length == 0) return;
- StyleRange style;
- if (event.length == 1 || text.getTextRange(event.start, event.length).equals(text.getLineDelimiter())) {
- // Have the new text take on the style of the text to its right (during
- // typing) if no style information is active.
- int caretOffset = text.getCaretOffset();
- style = null;
- if (caretOffset < text.getCharCount()) style = text.getStyleRangeAtOffset(caretOffset);
- if (style != null) {
- style.start = event.start;
- style.length = event.length;
- int fontStyle = SWT.NORMAL;
- if (isBold) fontStyle = SWT.BOLD;
- style.fontStyle = fontStyle;
- text.setStyleRange(style);
- } else if (isBold) {
- StyleRange newStyle = new StyleRange(event.start, event.length, null, null, SWT.BOLD);
- text.setStyleRange(newStyle);
- }
- } else {
- // paste occurring, have text take on the styles it had when it was
- // cut/copied
- for (int i=0; i<cachedStyles.size(); i++) {
- style = (StyleRange)cachedStyles.elementAt(i);
- StyleRange newStyle = (StyleRange)style.clone();
- newStyle.start = style.start + event.start;
- text.setStyleRange(newStyle);
- }
- }
-}
-
-public static void main (String [] args) {
- Display display = new Display ();
- TextEditor example = new TextEditor ();
- Shell shell = example.open (display);
- while (!shell.isDisposed ())
- if (!display.readAndDispatch ()) display.sleep ();
- display.dispose ();
-}
-
-public Shell open (Display display) {
- createShell (display);
- createMenuBar ();
- createToolBar ();
- createStyledText ();
- shell.setSize(500, 300);
- shell.open ();
- return shell;
-}
-
-void setFont() {
- FontDialog fontDialog = new FontDialog(shell);
- fontDialog.setFontData((text.getFont()).getFontData()[0]);
- FontData fontData = fontDialog.open();
- if(fontData != null) {
- if(font != null)
- font.dispose();
- font = new Font(shell.getDisplay(), fontData);
- text.setFont(font);
- }
-}
-
-void initializeColors() {
- Display display = Display.getDefault();
- RED = new Color (display, new RGB(255,0,0));
- BLUE = new Color (display, new RGB(0,0,255));
- GREEN = new Color (display, new RGB(0,255,0));
-}
-}
+ * http://www.eclipse.org/legal/cpl-v10.html
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.custom.*;
+import org.eclipse.swt.events.*;
+import org.eclipse.swt.graphics.*;
+import org.eclipse.swt.layout.*;
+import org.eclipse.swt.widgets.*;
+import java.util.*;
+
+/**
+ */
+public class TextEditor {
+ Shell shell;
+ ToolBar toolBar;
+ StyledText text;
+
+ Images images = new Images();
+ Vector cachedStyles = new Vector();
+ Color RED = null;
+ Color BLUE = null;
+ Color GREEN = null;
+ Font font = null;
+
+ boolean isBold = false;
+
+ ExtendedModifyListener extendedModifyListener;
+ static ResourceBundle resources = ResourceBundle.getBundle("examples_texteditor");
+
+Menu createEditMenu() {
+ Menu bar = shell.getMenuBar ();
+ Menu menu = new Menu (bar);
+
+ MenuItem item = new MenuItem (menu, SWT.PUSH);
+ item.setText (resources.getString("Cut_menuitem"));
+ item.setAccelerator(SWT.MOD1 + 'X');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ handleCutCopy();
+ text.cut();
+ }
+ });
+
+ item = new MenuItem (menu, SWT.PUSH);
+ item.setText (resources.getString("Copy_menuitem"));
+ item.setAccelerator(SWT.MOD1 + 'C');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ handleCutCopy();
+ text.copy();
+ }
+ });
+
+ item = new MenuItem (menu, SWT.PUSH);
+ item.setText (resources.getString("Paste_menuitem"));
+ item.setAccelerator(SWT.MOD1 + 'V');
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ text.paste();
+ }
+ });
+
+ new MenuItem (menu, SWT.SEPARATOR);
+
+ item = new MenuItem (menu, SWT.PUSH);
+ item.setText (resources.getString("Font_menuitem"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ setFont();
+ }
+ });
+ return menu;
+}
+
+Menu createFileMenu() {
+ Menu bar = shell.getMenuBar ();
+ Menu menu = new Menu (bar);
+
+ MenuItem item = new MenuItem (menu, SWT.PUSH);
+ item.setText (resources.getString("Exit_menuitem"));
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ shell.close ();
+ }
+ });
+
+ return menu;
+}
+
+/*
+ * Set the text state to bold.
+ */
+void bold(boolean bold) {
+ isBold = bold;
+ Point sel = text.getSelectionRange();
+ if ((sel != null) && (sel.y != 0)) {
+ StyleRange style;
+ int fontStyle = SWT.NORMAL;
+ if (isBold) fontStyle = SWT.BOLD;
+ style = new StyleRange(sel.x, sel.y, null, null, fontStyle);
+ text.setStyleRange(style);
+ }
+ text.setSelectionRange(sel.x + sel.y, 0);
+}
+/*
+ * Clear all style data for the selected text.
+ */
+void clear() {
+ Point sel = text.getSelectionRange();
+ if ((sel != null) && (sel.y != 0)) {
+ StyleRange style;
+ style = new StyleRange(sel.x, sel.y, null, null, SWT.NORMAL);
+ text.setStyleRange(style);
+ }
+ text.setSelectionRange(sel.x + sel.y, 0);
+}
+/*
+ * Set the foreground color for the selected text.
+ */
+void fgColor(int color) {
+ Point sel = text.getSelectionRange();
+ if ((sel == null) || (sel.y == 0)) return;
+ Color fg;
+ if (color == SWT.COLOR_RED) {
+ fg = RED;
+ } else if (color == SWT.COLOR_GREEN) {
+ fg = GREEN;
+ } else if (color == SWT.COLOR_BLUE) {
+ fg = BLUE;
+ } else {
+ fg = null;
+ }
+ StyleRange style;
+ for (int i = sel.x; i<sel.x+sel.y; i++) {
+ StyleRange range = text.getStyleRangeAtOffset(i);
+ if (range == null) {style = new StyleRange(i, 1, fg, null, SWT.NORMAL);}
+ else {style = new StyleRange(i, 1, fg, null, range.fontStyle);};
+ text.setStyleRange(style);
+ }
+ text.setSelectionRange(sel.x + sel.y, 0);
+}
+void createMenuBar () {
+ Menu bar = new Menu (shell, SWT.BAR);
+ shell.setMenuBar (bar);
+
+ MenuItem fileItem = new MenuItem (bar, SWT.CASCADE);
+ fileItem.setText (resources.getString("File_menuitem"));
+ fileItem.setMenu (createFileMenu ());
+
+ MenuItem editItem = new MenuItem (bar, SWT.CASCADE);
+ editItem.setText (resources.getString("Edit_menuitem"));
+ editItem.setMenu (createEditMenu ());
+}
+
+void createShell (Display display) {
+ shell = new Shell (display);
+ shell.setText (resources.getString("Window_title"));
+ images.loadAll (display);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 1;
+ shell.setLayout(layout);
+ shell.addDisposeListener (new DisposeListener () {
+ public void widgetDisposed (DisposeEvent e) {
+ if (font != null) font.dispose();
+ images.freeAll ();
+ RED.dispose();
+ GREEN.dispose();
+ BLUE.dispose();
+ }
+ });
+}
+void createStyledText() {
+ initializeColors();
+ text = new StyledText (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
+ GridData spec = new GridData();
+ spec.horizontalAlignment = GridData.FILL;
+ spec.grabExcessHorizontalSpace = true;
+ spec.verticalAlignment = GridData.FILL;
+ spec.grabExcessVerticalSpace = true;
+ text.setLayoutData(spec);
+ extendedModifyListener = new ExtendedModifyListener() {
+ public void modifyText(ExtendedModifyEvent e) {
+ handleExtendedModify(e);
+ }
+ };
+ text.addExtendedModifyListener(extendedModifyListener);
+}
+
+void createToolBar() {
+ toolBar = new ToolBar(shell, SWT.NULL);
+
+ ToolItem item = new ToolItem(toolBar, SWT.CHECK);
+ item.setImage(images.Bold);
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ bold(((ToolItem)event.widget).getSelection());
+ }
+ });
+
+ item = new ToolItem(toolBar, SWT.SEPARATOR);
+
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(images.Red);
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ fgColor(SWT.COLOR_RED);
+ }
+ });
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(images.Green);
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ fgColor(SWT.COLOR_GREEN);
+ }
+ });
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(images.Blue);
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ fgColor(SWT.COLOR_BLUE);
+ }
+ });
+
+ item = new ToolItem(toolBar, SWT.SEPARATOR);
+
+ item = new ToolItem(toolBar, SWT.PUSH);
+ item.setImage(images.Erase);
+ item.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ clear();
+ }
+ });
+}
+void displayError(String msg) {
+ MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
+ box.setMessage(msg);
+ box.open();
+}
+/*
+ * Cache the style information for text that has been cut or copied.
+ */
+void handleCutCopy() {
+ // Save the cut/copied style info so that during paste we will maintain
+ // the style information. Cut/copied text is put in the clipboard in
+ // RTF format, but is not pasted in RTF format. The other way to
+ // handle the pasting of styles would be to access the Clipboard directly and
+ // parse the RTF text.
+ cachedStyles = new Vector();
+ Point sel = text.getSelectionRange();
+ int startX = sel.x;
+ for (int i=sel.x; i<=sel.x+sel.y-1; i++) {
+ StyleRange style = text.getStyleRangeAtOffset(i);
+ if (style != null) {
+ style.start = style.start - startX;
+ if (!cachedStyles.isEmpty()) {
+ StyleRange lastStyle = (StyleRange)cachedStyles.lastElement();
+ if (lastStyle.similarTo(style) && lastStyle.start + lastStyle.length == style.start) {
+ lastStyle.length++;
+ } else {
+ cachedStyles.addElement(style);
+ }
+ } else {
+ cachedStyles.addElement(style);
+ }
+ }
+ }
+}
+void handleExtendedModify(ExtendedModifyEvent event) {
+ if (event.length == 0) return;
+ StyleRange style;
+ if (event.length == 1 || text.getTextRange(event.start, event.length).equals(text.getLineDelimiter())) {
+ // Have the new text take on the style of the text to its right (during
+ // typing) if no style information is active.
+ int caretOffset = text.getCaretOffset();
+ style = null;
+ if (caretOffset < text.getCharCount()) style = text.getStyleRangeAtOffset(caretOffset);
+ if (style != null) {
+ style.start = event.start;
+ style.length = event.length;
+ int fontStyle = SWT.NORMAL;
+ if (isBold) fontStyle = SWT.BOLD;
+ style.fontStyle = fontStyle;
+ text.setStyleRange(style);
+ } else if (isBold) {
+ StyleRange newStyle = new StyleRange(event.start, event.length, null, null, SWT.BOLD);
+ text.setStyleRange(newStyle);
+ }
+ } else {
+ // paste occurring, have text take on the styles it had when it was
+ // cut/copied
+ for (int i=0; i<cachedStyles.size(); i++) {
+ style = (StyleRange)cachedStyles.elementAt(i);
+ StyleRange newStyle = (StyleRange)style.clone();
+ newStyle.start = style.start + event.start;
+ text.setStyleRange(newStyle);
+ }
+ }
+}
+
+public static void main (String [] args) {
+ Display display = new Display ();
+ TextEditor example = new TextEditor ();
+ Shell shell = example.open (display);
+ while (!shell.isDisposed ())
+ if (!display.readAndDispatch ()) display.sleep ();
+ display.dispose ();
+}
+
+public Shell open (Display display) {
+ createShell (display);
+ createMenuBar ();
+ createToolBar ();
+ createStyledText ();
+ shell.setSize(500, 300);
+ shell.open ();
+ return shell;
+}
+
+void setFont() {
+ FontDialog fontDialog = new FontDialog(shell);
+ fontDialog.setFontData((text.getFont()).getFontData()[0]);
+ FontData fontData = fontDialog.open();
+ if(fontData != null) {
+ if(font != null)
+ font.dispose();
+ font = new Font(shell.getDisplay(), fontData);
+ text.setFont(font);
+ }
+}
+
+void initializeColors() {
+ Display display = Display.getDefault();
+ RED = new Color (display, new RGB(255,0,0));
+ BLUE = new Color (display, new RGB(0,0,255));
+ GREEN = new Color (display, new RGB(0,255,0));
+}
+}