ICU-5542 Tagging icu4j 3.4.5 eclipse plug-in updates shipped for eclipse 3.2.2

X-SVN-Rev: 21075
This commit is contained in:
Yoshito Umaoka 2007-02-21 22:28:45 +00:00
commit 8cc31ed18f
983 changed files with 960210 additions and 0 deletions

5
.cvsignore Normal file
View file

@ -0,0 +1,5 @@
doc
classes
.classpath
.externalToolBuilders
.project

118
.gitattributes vendored Normal file
View file

@ -0,0 +1,118 @@
* text=auto !eol
*.c text !eol
*.cc text !eol
*.classpath text !eol
*.cpp text !eol
*.css text !eol
*.dsp text !eol
*.dsw text !eol
*.filters text !eol
*.h text !eol
*.htm text !eol
*.html text !eol
*.in text !eol
*.java text !eol
*.launch text !eol
*.mak text !eol
*.md text !eol
*.MF text !eol
*.mk text !eol
*.pl text !eol
*.pm text !eol
*.project text !eol
*.properties text !eol
*.py text !eol
*.rc text !eol
*.sh text eol=lf
*.sln text !eol
*.stub text !eol
*.txt text !eol
*.ucm text !eol
*.vcproj text !eol
*.vcxproj text !eol
*.xml text !eol
*.xsl text !eol
*.xslt text !eol
Makefile text !eol
configure text !eol
LICENSE text !eol
README text !eol
*.bin -text
*.brk -text
*.cnv -text
*.icu -text
*.res -text
*.nrm -text
*.spp -text
*.tri2 -text
/ee.foundation.jar -text
src/com/ibm/icu/dev/data/rbbi/english.dict -text
src/com/ibm/icu/dev/data/testdata.jar -text
src/com/ibm/icu/dev/data/thai6.ucs -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Asian.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Chinese.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Japanese.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Japanese_h.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Japanese_k.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Korean.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Latin.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Russian.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_SerbianSH.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_SerbianSR.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Simplified_Chinese.txt -text
src/com/ibm/icu/dev/test/perf/data/collation/TestNames_Thai.txt -text
src/com/ibm/icu/dev/test/rbbi/rbbitst.txt -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.impl.JDKTimeZone.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.impl.OlsonTimeZone.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.impl.TimeZoneAdapter.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.math.BigDecimal.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.math.MathContext.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.ArabicShapingException.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.ChineseDateFormat.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.ChineseDateFormatSymbols.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.DateFormat.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.DateFormatSymbols.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.DecimalFormat.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.DecimalFormatSymbols.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.MessageFormat.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.NumberFormat.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.RuleBasedNumberFormat.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.SimpleDateFormat.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.text.StringPrepParseException.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.BuddhistCalendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.Calendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.ChineseCalendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.CopticCalendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.Currency.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.EthiopicCalendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.GregorianCalendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.HebrewCalendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.IslamicCalendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.JapaneseCalendar.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.SimpleTimeZone.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.TimeZone.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.ULocale.dat -text
src/com/ibm/icu/dev/test/serializable/data/ICU_3.6/com.ibm.icu.util.UResourceTypeMismatchException.dat -text
src/com/ibm/icu/dev/tool/docs/icu4j28.api.gz -text
src/com/ibm/icu/dev/tool/docs/icu4j30.api.gz -text
src/com/ibm/icu/dev/tool/docs/icu4j32.api.gz -text
src/com/ibm/icu/dev/tool/docs/icu4j34.api.gz -text
src/com/ibm/icu/dev/tool/docs/icu4j341.api.gz -text
src/com/ibm/icu/dev/tool/docs/icu4j342.api.gz -text
src/com/ibm/icu/dev/tool/docs/icu4j343.api.gz -text
src/com/ibm/icu/impl/data/icudata.jar -text
src/com/ibm/icu/impl/data/th.brk -text
src/com/ibm/richtext/textapps/resources/unicode.arabic.red -text
src/com/ibm/richtext/textapps/resources/unicode.hebrew.red -text
# The following file types are stored in Git-LFS.
*.jar filter=lfs diff=lfs merge=lfs -text
*.dat filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.gif filter=lfs diff=lfs merge=lfs -text

5
.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
/.classpath
/.externalToolBuilders
/.project
/classes
/doc

38
APIChangeReport.html Normal file
View file

@ -0,0 +1,38 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ICU4J API Comparison: ICU4J 3.4.2 with ICU4J 3.4.3</title>
<!-- Copyright 2006, IBM, All Rights Reserved. -->
</head>
<body>
<h1>ICU4J API Comparison: ICU4J 3.4.2 with ICU4J 3.4.3</h1>
<hr/>
<h2>Removed from ICU4J 3.4.2</h2>
<p>(no API removed)</p>
<hr/>
<h2>Deprecated or Obsoleted in ICU4J 3.4.3</h2>
<p>(no API obsoleted)</p>
<hr/>
<h2>Changed in ICU4J 3.4.3 (old, new)</h2>
<p>(no API changed)</p>
<hr/>
<h2>Promoted to stable in ICU4J 3.4.3</h2>
<h3>Package com.ibm.icu.text</h3>
<ul>
<li>(stable) public class <i>MessageFormat</i></li>
</ul>
<hr/>
<h2>Added in ICU4J 3.4.3</h2>
<p>(no API added)</p>
<hr/>
<p><i><font size="-1">Contents generated by ReportAPI tool on Thu Feb 23 08:36:05 PST 2006<br/>Copyright (C) 2006, International Business Machines Corporation, All Rights Reserved.</font></i></p>
</body>
</html>

1484
build.xml Normal file

File diff suppressed because it is too large Load diff

17
eclipseCoreArgs.txt Normal file
View file

@ -0,0 +1,17 @@
# Copyright (C) 2005-2006, International Business Machines Corporation and
# others. All Rights Reserved.
src/com/ibm/icu/impl/CollectionUtilities.java
src/com/ibm/icu/impl/ICUResourceBundle.java
src/com/ibm/icu/impl/ICUResourceBundleImpl.java
src/com/ibm/icu/impl/ICUResourceBundleReader.java
src/com/ibm/icu/impl/LRUMap.java
src/com/ibm/icu/impl/Utility.java
src/com/ibm/icu/lang/UCharacter.java
src/com/ibm/icu/math/BigDecimal.java
src/com/ibm/icu/text/DecimalFormat.java
src/com/ibm/icu/text/DigitList.java
src/com/ibm/icu/text/NumberFormat.java
src/com/ibm/icu/text/RuleBasedCollator.java
src/com/ibm/icu/text/RuleBasedNumberFormat.java
src/com/ibm/icu/util/ByteArrayWrapper.java
src/com/ibm/icu/util/GlobalizationPreferences.java

34
eclipseTestArgs.txt Normal file
View file

@ -0,0 +1,34 @@
# Copyright (C) 2005-2006, International Business Machines Corporation and
# others. All Rights Reserved.
src/com/ibm/icu/dev/test/bigdec/DiagBigDecimal.java
src/com/ibm/icu/dev/test/cldr/TestCLDRVsICU.java
src/com/ibm/icu/dev/test/charsetdet/TestCharsetDetector.java
src/com/ibm/icu/dev/test/collator/RandomCollator.java
src/com/ibm/icu/dev/test/collator/TestAll.java
src/com/ibm/icu/dev/test/format/BigNumberFormatTest.java
src/com/ibm/icu/dev/test/format/GlobalizationPreferencesTest.java
src/com/ibm/icu/dev/test/format/NumberFormatRegressionTest.java
src/com/ibm/icu/dev/test/format/NumberFormatTest.java
src/com/ibm/icu/dev/test/format/NumberRegression.java
src/com/ibm/icu/dev/test/format/RbnfTest.java
src/com/ibm/icu/dev/test/timezone/TimeZoneAliasTest.java
src/com/ibm/icu/dev/test/timezone/TimeZoneRegression.java
src/com/ibm/icu/dev/test/util/ICUResourceBundleTest.java
src/com/ibm/icu/dev/test/util/UtilityTest.java
src/com/ibm/icu/dev/test/util/UnicodeMap.java
src/com/ibm/icu/dev/test/util/UnicodeProperty.java
src/com/ibm/icu/dev/test/util/BagFormatter.java
src/com/ibm/icu/dev/test/util/ICUPropertyFactory.java
src/com/ibm/icu/dev/test/util/TestBagFormatter.java
src/com/ibm/icu/dev/test/util/CollectionUtilities.java
src/com/ibm/icu/dev/test/util/FileUtilities.java
src/com/ibm/icu/dev/test/util/TransliteratorUtilities.java
src/com/ibm/icu/dev/test/util/DataInputCompressor.java
src/com/ibm/icu/dev/test/util/DataOutputCompressor.java
src/com/ibm/icu/dev/test/util/TestUtilities.java
src/com/ibm/icu/dev/test/util/Tokenizer.java
src/com/ibm/icu/dev/test/util/BNF.java
src/com/ibm/icu/dev/test/util/TestBNF.java
src/com/ibm/icu/dev/test/TestAll.java
src/com/ibm/icu/dev/test/TestFmwk.java
src/com/ibm/icu/dev/test/TestUtil.java

3
ee.foundation.jar Normal file
View file

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7f730fd4a8ca71fcddc61a4f62490cea7805efffc7eb2b8669942f6d123f7249
size 1059077

34
license.html Normal file
View file

@ -0,0 +1,34 @@
<html>
<head>
<title>ICU4J license - ICU4J 1.3.1 and later</title>
</head>
<body BGCOLOR="#ffffff">
<h2>ICU4J license - ICU4J 1.3.1 and later</h2>
<p>COPYRIGHT AND PERMISSION NOTICE</p>
<p>
Copyright (c) 1995-2006 International Business Machines Corporation and others
</p>
<p>
All rights reserved.
</p>
<p>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
</p>
<p>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
</p>
<p>
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
</p>
<hr>
<small>
All trademarks and registered trademarks mentioned herein are the property of their respective owners.
</small>
</body>
</html>

1366
readme.html Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,104 @@
/**
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.data;
import com.ibm.icu.impl.ICUListResourceBundle;
public class TestDataElements_testaliases extends ICUListResourceBundle {
public TestDataElements_testaliases () {
super.contents = data;
}
static final Object[][] data = new Object[][] {
{
"collations",
new ICUListResourceBundle.Alias("/ICUDATA/uk"),
},
// Circular aliases test moved to TestCircularAliases
// {
// "aaa",
// new ICUListResourceBundle.Alias("testaliases/aab"),
// },
// {
// "aab",
// new ICUListResourceBundle.Alias("testaliases/aaa"),
// },
{
"anotheralias",
new ICUListResourceBundle.Alias("/ICUDATA/uk/collations/standard"),
},
// Moved to TestNonExisting
// {
// "nonexisting",
// new ICUListResourceBundle.Alias("/ICUDATA/uk"),
// },
{
"referencingalias",
new ICUListResourceBundle.Alias("testaliases/anotheralias/Sequence"),
},
{
"simplealias",
new ICUListResourceBundle.Alias("testtypes/menu/file/open"),
},
{
"testGetStringByIndexAliasing",
new Object[]{
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/0/0"),
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/0/1"),
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/0/4"),
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/0/5"),
},
},
{
"testGetStringByKeyAliasing",
new Object[][]{
{
"KeyAlias0PST",
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/0/0"),
},
{
"KeyAlias1PacificStandardTime",
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/0/1"),
},
{
"KeyAlias2PDT",
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/0/4"),
},
{
"KeyAlias3LosAngeles",
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/0/5"),
},
},
},
{
"zoneStrings",
new Object[]{
new ICUListResourceBundle.Alias("/ICUDATA/en"),
new ICUListResourceBundle.Alias("/ICUDATA/en"),
},
},
{
"zoneTests",
new Object[][]{
{
"zoneAlias",
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings"),
},
{
"zoneAlias1",
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/3"),
},
{
"zoneAlias2",
new ICUListResourceBundle.Alias("/ICUDATA/en/zoneStrings/3/0"),
},
},
},
};
}

View file

@ -0,0 +1,37 @@
/**
*******************************************************************************
* Copyright (C) 2001-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.data;
import com.ibm.icu.impl.ICUListResourceBundle;
/**
* @author Ram
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
public class TestDataElements_testcircularalias extends ICUListResourceBundle {
public TestDataElements_testcircularalias() {
super.contents = data;
}
private static Object[][] data = new Object[][] {
{
"aaa",
new ICUListResourceBundle.Alias("testcircularalias/aab"),
},
{
"aab",
new ICUListResourceBundle.Alias("testcircularalias/aac"),
},
{
"aac",
new ICUListResourceBundle.Alias("testcircularalias/aaa"),
}
};
}

View file

@ -0,0 +1,138 @@
/**
*******************************************************************************
* Copyright (C) 2001-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.data;
import com.ibm.icu.impl.ICUListResourceBundle;
public class TestDataElements_testtypes extends ICUListResourceBundle {
public TestDataElements_testtypes () {
super.contents = data;
}
private static Object[][] data = new Object[][] {
{
"binarytest",
new ICUListResourceBundle.CompressedBinary(
"\u0000\u000F\u0001\u0203\u0405\u0607\u0809\u0A0B" +
"\u0C0D\u0E00"),
},
{
"emptyarray",
new String[] {
},
},
{
"emptybin",
new ICUListResourceBundle.CompressedBinary(null),
},
{
"emptyexplicitstring",
"",
},
{
"emptyint",
new Integer(0),
},
{
"emptyintv",
new Integer[] {
},
},
{
"emptystring",
"",
},
{
"emptytable",
new Object[][]{
},
},
{
"importtest",
new ICUListResourceBundle.CompressedBinary(
"\u0000\u000F\u0001\u0203\u0405\u0607\u0809\u0A0B" +
"\u0C0D\u0E00"),
},
{
"integerarray",
new Integer[] {
new Integer(1),
new Integer(2),
new Integer(3),
new Integer(-3),
new Integer(4),
new Integer(5),
new Integer(6),
new Integer(7),
},
},
{
"menu",
new Object[][]{
{
"file",
new Object[][]{
{
"exit",
"Exit",
},
{
"open",
"Open",
},
{
"save",
"Save",
},
},
},
},
},
{
"minusone",
new Integer(-1),
},
{
"one",
new Integer(1),
},
{
"onehundredtwentythree",
new Integer(123),
},
{
"plusone",
new Integer(1),
},
{
"string",
new String[] {
},
},
{
"stringTable",
new Object[]{
new String[] {
},
},
},
{
"test_underscores",
"test message ....",
},
{
"testescape",
"tab:\u0009 cr:\f ff:\u000C newline:\n backslash:\\" +
" quote=\\\' doubleQuote=\\\" singlequoutes=''",
},
{
"zerotest",
"abc\u0000def",
},
};
}

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,34 @@
/*
*******************************************************************************
* Copyright (C) 2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.data.resources;
import java.util.ListResourceBundle;
public class TestDataElements extends ListResourceBundle {
private static Object[][] data = new Object[][] {
{
"from_root",
"This data comes from root"
},
{
"from_en",
"In root should be overridden"
},
{
"from_en_Latn",
"In root should be overridden"
},
{
"from_en_Latn_US",
"In root should be overridden"
}
};
protected Object[][] getContents() {
return data;
}
}

View file

@ -0,0 +1,10 @@
# *
# *******************************************************************************
# * Copyright (C) 2005-2006, International Business Machines Corporation and *
# * others. All Rights Reserved. *
# *******************************************************************************
# *
# TestDataElements_en.properties
from_en=This data comes from en
from_en_Latn=In en should be overridden
from_en_Latn_US=In en should be overridden

View file

@ -0,0 +1,9 @@
# *
# *******************************************************************************
# * Copyright (C) 2005-2006, International Business Machines Corporation and *
# * others. All Rights Reserved. *
# *******************************************************************************
# *
# TestDataElements_en_Latn.properties
from_en_Latn=This data comes from en_Latn
from_en_Latn_US=In en_Latn should be overridden

View file

@ -0,0 +1,22 @@
/*
*******************************************************************************
* Copyright (C) 2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.data.resources;
import java.util.ListResourceBundle;
public class TestDataElements_en_Latn_US extends ListResourceBundle {
private static Object[][] data = new Object[][] {
{
"from_en_Latn_US",
"This data comes from en_Latn_US"
}
};
protected Object[][] getContents() {
return data;
}
}

View file

@ -0,0 +1,23 @@
/*
*******************************************************************************
* Copyright (C) 2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.data.resources;
import java.util.ListResourceBundle;
public class TestDataElements_en_US extends ListResourceBundle {
private static Object[][] data = new Object[][] {
{
"from_en_US",
"This data comes from en_US"
}
};
protected Object[][] getContents() {
return data;
}
}

View file

@ -0,0 +1,24 @@
/*
*******************************************************************************
* Copyright (C) 2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.data.resources;
import java.util.ListResourceBundle;
public class TestDataElments_fr_Latn_FR extends ListResourceBundle {
private static Object[][] data = new Object[][] {
{
"from_fr_Latn_FR",
"This data comes from fr_Latn_FR"
}
};
protected Object[][] getContents() {
return data;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:722bec50ab151f4ce21c1983eb607fd0ee51f15a70845f57aaef01b521973a77
size 656372

File diff suppressed because it is too large Load diff

Binary file not shown.

View file

@ -0,0 +1,179 @@
# CompositionExclusions-4.1.0.txt
# Date: 2005-03-17, 15:21:00 PST [KW]
#
# This file lists the characters from the UAX #15 Composition Exclusion Table.
#
# This file is a normative contributory data file in the
# Unicode Character Database.
#
# Copyright (c) 1991-2005 Unicode, Inc.
# For terms of use, see http://www.unicode.org/terms_of_use.html
#
# For more information, see
# http://www.unicode.org/unicode/reports/tr15/#Primary Exclusion List Table
# ================================================
# (1) Script Specifics
# This list of characters cannot be derived from the UnicodeData file.
# ================================================
0958 # DEVANAGARI LETTER QA
0959 # DEVANAGARI LETTER KHHA
095A # DEVANAGARI LETTER GHHA
095B # DEVANAGARI LETTER ZA
095C # DEVANAGARI LETTER DDDHA
095D # DEVANAGARI LETTER RHA
095E # DEVANAGARI LETTER FA
095F # DEVANAGARI LETTER YYA
09DC # BENGALI LETTER RRA
09DD # BENGALI LETTER RHA
09DF # BENGALI LETTER YYA
0A33 # GURMUKHI LETTER LLA
0A36 # GURMUKHI LETTER SHA
0A59 # GURMUKHI LETTER KHHA
0A5A # GURMUKHI LETTER GHHA
0A5B # GURMUKHI LETTER ZA
0A5E # GURMUKHI LETTER FA
0B5C # ORIYA LETTER RRA
0B5D # ORIYA LETTER RHA
0F43 # TIBETAN LETTER GHA
0F4D # TIBETAN LETTER DDHA
0F52 # TIBETAN LETTER DHA
0F57 # TIBETAN LETTER BHA
0F5C # TIBETAN LETTER DZHA
0F69 # TIBETAN LETTER KSSA
0F76 # TIBETAN VOWEL SIGN VOCALIC R
0F78 # TIBETAN VOWEL SIGN VOCALIC L
0F93 # TIBETAN SUBJOINED LETTER GHA
0F9D # TIBETAN SUBJOINED LETTER DDHA
0FA2 # TIBETAN SUBJOINED LETTER DHA
0FA7 # TIBETAN SUBJOINED LETTER BHA
0FAC # TIBETAN SUBJOINED LETTER DZHA
0FB9 # TIBETAN SUBJOINED LETTER KSSA
FB1D # HEBREW LETTER YOD WITH HIRIQ
FB1F # HEBREW LIGATURE YIDDISH YOD YOD PATAH
FB2A # HEBREW LETTER SHIN WITH SHIN DOT
FB2B # HEBREW LETTER SHIN WITH SIN DOT
FB2C # HEBREW LETTER SHIN WITH DAGESH AND SHIN DOT
FB2D # HEBREW LETTER SHIN WITH DAGESH AND SIN DOT
FB2E # HEBREW LETTER ALEF WITH PATAH
FB2F # HEBREW LETTER ALEF WITH QAMATS
FB30 # HEBREW LETTER ALEF WITH MAPIQ
FB31 # HEBREW LETTER BET WITH DAGESH
FB32 # HEBREW LETTER GIMEL WITH DAGESH
FB33 # HEBREW LETTER DALET WITH DAGESH
FB34 # HEBREW LETTER HE WITH MAPIQ
FB35 # HEBREW LETTER VAV WITH DAGESH
FB36 # HEBREW LETTER ZAYIN WITH DAGESH
FB38 # HEBREW LETTER TET WITH DAGESH
FB39 # HEBREW LETTER YOD WITH DAGESH
FB3A # HEBREW LETTER FINAL KAF WITH DAGESH
FB3B # HEBREW LETTER KAF WITH DAGESH
FB3C # HEBREW LETTER LAMED WITH DAGESH
FB3E # HEBREW LETTER MEM WITH DAGESH
FB40 # HEBREW LETTER NUN WITH DAGESH
FB41 # HEBREW LETTER SAMEKH WITH DAGESH
FB43 # HEBREW LETTER FINAL PE WITH DAGESH
FB44 # HEBREW LETTER PE WITH DAGESH
FB46 # HEBREW LETTER TSADI WITH DAGESH
FB47 # HEBREW LETTER QOF WITH DAGESH
FB48 # HEBREW LETTER RESH WITH DAGESH
FB49 # HEBREW LETTER SHIN WITH DAGESH
FB4A # HEBREW LETTER TAV WITH DAGESH
FB4B # HEBREW LETTER VAV WITH HOLAM
FB4C # HEBREW LETTER BET WITH RAFE
FB4D # HEBREW LETTER KAF WITH RAFE
FB4E # HEBREW LETTER PE WITH RAFE
# Total code points: 67
# ================================================
# (2) Post Composition Version precomposed characters
# These characters cannot be derived solely from the UnicodeData.txt file
# in this version of Unicode.
# ================================================
2ADC # FORKING
1D15E # MUSICAL SYMBOL HALF NOTE
1D15F # MUSICAL SYMBOL QUARTER NOTE
1D160 # MUSICAL SYMBOL EIGHTH NOTE
1D161 # MUSICAL SYMBOL SIXTEENTH NOTE
1D162 # MUSICAL SYMBOL THIRTY-SECOND NOTE
1D163 # MUSICAL SYMBOL SIXTY-FOURTH NOTE
1D164 # MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE
1D1BB # MUSICAL SYMBOL MINIMA
1D1BC # MUSICAL SYMBOL MINIMA BLACK
1D1BD # MUSICAL SYMBOL SEMIMINIMA WHITE
1D1BE # MUSICAL SYMBOL SEMIMINIMA BLACK
1D1BF # MUSICAL SYMBOL FUSA WHITE
1D1C0 # MUSICAL SYMBOL FUSA BLACK
# Total code points: 14
# ================================================
# (3) Singleton Decompositions
# These characters can be derived from the UnicodeData file
# by including all characters whose canonical decomposition
# consists of a single character.
# These characters are simply quoted here for reference.
# ================================================
# 0340..0341 [2] COMBINING GRAVE TONE MARK..COMBINING ACUTE TONE MARK
# 0343 COMBINING GREEK KORONIS
# 0374 GREEK NUMERAL SIGN
# 037E GREEK QUESTION MARK
# 0387 GREEK ANO TELEIA
# 1F71 GREEK SMALL LETTER ALPHA WITH OXIA
# 1F73 GREEK SMALL LETTER EPSILON WITH OXIA
# 1F75 GREEK SMALL LETTER ETA WITH OXIA
# 1F77 GREEK SMALL LETTER IOTA WITH OXIA
# 1F79 GREEK SMALL LETTER OMICRON WITH OXIA
# 1F7B GREEK SMALL LETTER UPSILON WITH OXIA
# 1F7D GREEK SMALL LETTER OMEGA WITH OXIA
# 1FBB GREEK CAPITAL LETTER ALPHA WITH OXIA
# 1FBE GREEK PROSGEGRAMMENI
# 1FC9 GREEK CAPITAL LETTER EPSILON WITH OXIA
# 1FCB GREEK CAPITAL LETTER ETA WITH OXIA
# 1FD3 GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
# 1FDB GREEK CAPITAL LETTER IOTA WITH OXIA
# 1FE3 GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA
# 1FEB GREEK CAPITAL LETTER UPSILON WITH OXIA
# 1FEE..1FEF [2] GREEK DIALYTIKA AND OXIA..GREEK VARIA
# 1FF9 GREEK CAPITAL LETTER OMICRON WITH OXIA
# 1FFB GREEK CAPITAL LETTER OMEGA WITH OXIA
# 1FFD GREEK OXIA
# 2000..2001 [2] EN QUAD..EM QUAD
# 2126 OHM SIGN
# 212A..212B [2] KELVIN SIGN..ANGSTROM SIGN
# 2329 LEFT-POINTING ANGLE BRACKET
# 232A RIGHT-POINTING ANGLE BRACKET
# F900..FA0D [270] CJK COMPATIBILITY IDEOGRAPH-F900..CJK COMPATIBILITY IDEOGRAPH-FA0D
# FA10 CJK COMPATIBILITY IDEOGRAPH-FA10
# FA12 CJK COMPATIBILITY IDEOGRAPH-FA12
# FA15..FA1E [10] CJK COMPATIBILITY IDEOGRAPH-FA15..CJK COMPATIBILITY IDEOGRAPH-FA1E
# FA20 CJK COMPATIBILITY IDEOGRAPH-FA20
# FA22 CJK COMPATIBILITY IDEOGRAPH-FA22
# FA25..FA26 [2] CJK COMPATIBILITY IDEOGRAPH-FA25..CJK COMPATIBILITY IDEOGRAPH-FA26
# FA2A..FA2D [4] CJK COMPATIBILITY IDEOGRAPH-FA2A..CJK COMPATIBILITY IDEOGRAPH-FA2D
# FA30..FA6A [59] CJK COMPATIBILITY IDEOGRAPH-FA30..CJK COMPATIBILITY IDEOGRAPH-FA6A
# FA70..FAD9 [106] CJK COMPATIBILITY IDEOGRAPH-FA70..CJK COMPATIBILITY IDEOGRAPH-FAD9
# 2F800..2FA1D [542] CJK COMPATIBILITY IDEOGRAPH-2F800..CJK COMPATIBILITY IDEOGRAPH-2FA1D
# Total code points: 924
# ================================================
# (4) Non-Starter Decompositions
# These characters can be derived from the UnicodeData file
# by including all characters whose canonical decomposition consists
# of a sequence of characters, the first of which has a non-zero
# combining class.
# These characters are simply quoted here for reference.
# ================================================
# 0344 COMBINING GREEK DIALYTIKA TONOS
# 0F73 TIBETAN VOWEL SIGN II
# 0F75 TIBETAN VOWEL SIGN UU
# 0F81 TIBETAN VOWEL SIGN REVERSED II
# Total code points: 4

View file

@ -0,0 +1,48 @@
# NormalizationCorrections-4.1.0.txt
# Date: 2005-03-17, 15:21:00 PST [KW]
#
# This file is a normative contributory data file in the
# Unicode Character Database.
#
# Copyright (c) 1991-2005 Unicode, Inc.
# For terms of use, see http://www.unicode.org/terms_of_use.html
#
# The normalization stabilization policy of the Unicode
# Consortium ordinarily precludes any change to the decomposition
# for any character, once established in a relevant version
# of the UnicodeData.txt data file. However, under certain
# exceptional (and rare) conditions, an error in a decomposition
# mapping may be discovered that is truly just an unintended
# typo in the data, and not a matter of dubious interpretation.
#
# Whenever such an error may be found, and if it meets the
# requirements for possible exceptions to normalization
# stability, the correction is entered in this data file,
# so that any implementation depending on absolute stability
# of normalization, *including* any errors in the data, can
# safely reconstruct the exact state of the data tables at
# any given version of Unicode.
#
# Currently this list has exactly six entries in it, one for the
# typo found and corrected in Corrigendum #3, and five for
# the typos and misidentifications found and corrected in
# Corrigendum #4. All efforts
# will be made to keep the entries limited to just those fixes.
#
# Interpretation of the fields:
# Field 1: Unicode code point
# Field 2: Original (erroneous) decomposition
# Field 3: Corrected decomposition
# Field 4: Version of Unicode for which the correction was
# entered into UnicodeData.txt, in n.n.n format.
# Comment: Indicates the Unicode Corrigendum which documents
# the correction
#
# For more information, see UAX #15, Unicode Normalization Forms.
#
F951;96FB;964B;3.2.0 # Corrigendum 3
2F868;2136A;36FC;4.0.0 # Corrigendum 4
2F874;5F33;5F53;4.0.0 # Corrigendum 4
2F91F;43AB;243AB;4.0.0 # Corrigendum 4
2F95F;7AAE;7AEE;4.0.0 # Corrigendum 4
2F9BF;4D57;45D7;4.0.0 # Corrigendum 4

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,260 @@
# SpecialCasing-4.1.0.txt
# Date: 2005-03-26, 00:35:45 GMT [MD]
#
# Unicode Character Database
# Copyright (c) 1991-2005 Unicode, Inc.
# For terms of use, see http://www.unicode.org/terms_of_use.html
# For documentation, see UCD.html
#
# Special Casing Properties
#
# This file is a supplement to the UnicodeData file.
# It contains additional information about the casing of Unicode characters.
# (For compatibility, the UnicodeData.txt file only contains case mappings for
# characters where they are 1-1, and does not have locale-specific mappings.)
# For more information, see the discussion of Case Mappings in the Unicode Standard.
#
# All code points not listed in this file that do not have a simple case mappings
# in UnicodeData.txt map to themselves.
# ================================================================================
# Format
# ================================================================================
# The entries in this file are in the following machine-readable format:
#
# <code>; <lower> ; <title> ; <upper> ; (<condition_list> ;)? # <comment>
#
# <code>, <lower>, <title>, and <upper> provide character values in hex. If there is more
# than one character, they are separated by spaces. Other than as used to separate
# elements, spaces are to be ignored.
#
# The <condition_list> is optional. Where present, it consists of one or more locale IDs
# or contexts, separated by spaces. In these conditions:
# - A condition list overrides the normal behavior if all of the listed conditions are true.
# - The context is always the context of the characters in the original string,
# NOT in the resulting string.
# - Case distinctions in the condition list are not significant.
# - Conditions preceded by "Not_" represent the negation of the condition.
#
# A locale ID is defined by taking any language tag as defined by
# RFC 3066 (or its successor), and replacing '-' by '_'.
#
# A context for a character C is defined by Section 3.13 Default Case Operations,
# on p. 89-90 of The Unicode Standard, Version 4.0, as amended by Unicode 4.1.0,
# as specified in http://www.unicode.org/versions/Unicode4.1.0/
#
# Parsers of this file must be prepared to deal with future additions to this format:
# * Additional contexts
# * Additional fields
# ================================================================================
# ================================================================================
# Unconditional mappings
# ================================================================================
# The German es-zed is special--the normal mapping is to SS.
# Note: the titlecase should never occur in practice. It is equal to titlecase(uppercase(<es-zed>))
00DF; 00DF; 0053 0073; 0053 0053; # LATIN SMALL LETTER SHARP S
# Preserve canonical equivalence for I with dot. Turkic is handled below.
0130; 0069 0307; 0130; 0130; # LATIN CAPITAL LETTER I WITH DOT ABOVE
# Ligatures
FB00; FB00; 0046 0066; 0046 0046; # LATIN SMALL LIGATURE FF
FB01; FB01; 0046 0069; 0046 0049; # LATIN SMALL LIGATURE FI
FB02; FB02; 0046 006C; 0046 004C; # LATIN SMALL LIGATURE FL
FB03; FB03; 0046 0066 0069; 0046 0046 0049; # LATIN SMALL LIGATURE FFI
FB04; FB04; 0046 0066 006C; 0046 0046 004C; # LATIN SMALL LIGATURE FFL
FB05; FB05; 0053 0074; 0053 0054; # LATIN SMALL LIGATURE LONG S T
FB06; FB06; 0053 0074; 0053 0054; # LATIN SMALL LIGATURE ST
0587; 0587; 0535 0582; 0535 0552; # ARMENIAN SMALL LIGATURE ECH YIWN
FB13; FB13; 0544 0576; 0544 0546; # ARMENIAN SMALL LIGATURE MEN NOW
FB14; FB14; 0544 0565; 0544 0535; # ARMENIAN SMALL LIGATURE MEN ECH
FB15; FB15; 0544 056B; 0544 053B; # ARMENIAN SMALL LIGATURE MEN INI
FB16; FB16; 054E 0576; 054E 0546; # ARMENIAN SMALL LIGATURE VEW NOW
FB17; FB17; 0544 056D; 0544 053D; # ARMENIAN SMALL LIGATURE MEN XEH
# No corresponding uppercase precomposed character
0149; 0149; 02BC 004E; 02BC 004E; # LATIN SMALL LETTER N PRECEDED BY APOSTROPHE
0390; 0390; 0399 0308 0301; 0399 0308 0301; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
03B0; 03B0; 03A5 0308 0301; 03A5 0308 0301; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
01F0; 01F0; 004A 030C; 004A 030C; # LATIN SMALL LETTER J WITH CARON
1E96; 1E96; 0048 0331; 0048 0331; # LATIN SMALL LETTER H WITH LINE BELOW
1E97; 1E97; 0054 0308; 0054 0308; # LATIN SMALL LETTER T WITH DIAERESIS
1E98; 1E98; 0057 030A; 0057 030A; # LATIN SMALL LETTER W WITH RING ABOVE
1E99; 1E99; 0059 030A; 0059 030A; # LATIN SMALL LETTER Y WITH RING ABOVE
1E9A; 1E9A; 0041 02BE; 0041 02BE; # LATIN SMALL LETTER A WITH RIGHT HALF RING
1F50; 1F50; 03A5 0313; 03A5 0313; # GREEK SMALL LETTER UPSILON WITH PSILI
1F52; 1F52; 03A5 0313 0300; 03A5 0313 0300; # GREEK SMALL LETTER UPSILON WITH PSILI AND VARIA
1F54; 1F54; 03A5 0313 0301; 03A5 0313 0301; # GREEK SMALL LETTER UPSILON WITH PSILI AND OXIA
1F56; 1F56; 03A5 0313 0342; 03A5 0313 0342; # GREEK SMALL LETTER UPSILON WITH PSILI AND PERISPOMENI
1FB6; 1FB6; 0391 0342; 0391 0342; # GREEK SMALL LETTER ALPHA WITH PERISPOMENI
1FC6; 1FC6; 0397 0342; 0397 0342; # GREEK SMALL LETTER ETA WITH PERISPOMENI
1FD2; 1FD2; 0399 0308 0300; 0399 0308 0300; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND VARIA
1FD3; 1FD3; 0399 0308 0301; 0399 0308 0301; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
1FD6; 1FD6; 0399 0342; 0399 0342; # GREEK SMALL LETTER IOTA WITH PERISPOMENI
1FD7; 1FD7; 0399 0308 0342; 0399 0308 0342; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND PERISPOMENI
1FE2; 1FE2; 03A5 0308 0300; 03A5 0308 0300; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND VARIA
1FE3; 1FE3; 03A5 0308 0301; 03A5 0308 0301; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA
1FE4; 1FE4; 03A1 0313; 03A1 0313; # GREEK SMALL LETTER RHO WITH PSILI
1FE6; 1FE6; 03A5 0342; 03A5 0342; # GREEK SMALL LETTER UPSILON WITH PERISPOMENI
1FE7; 1FE7; 03A5 0308 0342; 03A5 0308 0342; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND PERISPOMENI
1FF6; 1FF6; 03A9 0342; 03A9 0342; # GREEK SMALL LETTER OMEGA WITH PERISPOMENI
# IMPORTANT-when capitalizing iota-subscript (0345)
# It MUST be in normalized form--moved to the end of any sequence of combining marks.
# This is because logically it represents a following base character!
# E.g. <iota_subscript> (<Mn> | <Mc> | <Me>)+ => (<Mn> | <Mc> | <Me>)+ <iota_subscript>
# It should never be the first character in a word, so in titlecasing it can be left as is.
# The following cases are already in the UnicodeData file, so are only commented here.
# 0345; 0345; 0345; 0399; # COMBINING GREEK YPOGEGRAMMENI
# All letters with YPOGEGRAMMENI (iota-subscript) or PROSGEGRAMMENI (iota adscript)
# have special uppercases.
# Note: characters with PROSGEGRAMMENI are actually titlecase, not uppercase!
1F80; 1F80; 1F88; 1F08 0399; # GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI
1F81; 1F81; 1F89; 1F09 0399; # GREEK SMALL LETTER ALPHA WITH DASIA AND YPOGEGRAMMENI
1F82; 1F82; 1F8A; 1F0A 0399; # GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA AND YPOGEGRAMMENI
1F83; 1F83; 1F8B; 1F0B 0399; # GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA AND YPOGEGRAMMENI
1F84; 1F84; 1F8C; 1F0C 0399; # GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA AND YPOGEGRAMMENI
1F85; 1F85; 1F8D; 1F0D 0399; # GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA AND YPOGEGRAMMENI
1F86; 1F86; 1F8E; 1F0E 0399; # GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI
1F87; 1F87; 1F8F; 1F0F 0399; # GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
1F88; 1F80; 1F88; 1F08 0399; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI
1F89; 1F81; 1F89; 1F09 0399; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI
1F8A; 1F82; 1F8A; 1F0A 0399; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI
1F8B; 1F83; 1F8B; 1F0B 0399; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI
1F8C; 1F84; 1F8C; 1F0C 0399; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI
1F8D; 1F85; 1F8D; 1F0D 0399; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI
1F8E; 1F86; 1F8E; 1F0E 0399; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
1F8F; 1F87; 1F8F; 1F0F 0399; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
1F90; 1F90; 1F98; 1F28 0399; # GREEK SMALL LETTER ETA WITH PSILI AND YPOGEGRAMMENI
1F91; 1F91; 1F99; 1F29 0399; # GREEK SMALL LETTER ETA WITH DASIA AND YPOGEGRAMMENI
1F92; 1F92; 1F9A; 1F2A 0399; # GREEK SMALL LETTER ETA WITH PSILI AND VARIA AND YPOGEGRAMMENI
1F93; 1F93; 1F9B; 1F2B 0399; # GREEK SMALL LETTER ETA WITH DASIA AND VARIA AND YPOGEGRAMMENI
1F94; 1F94; 1F9C; 1F2C 0399; # GREEK SMALL LETTER ETA WITH PSILI AND OXIA AND YPOGEGRAMMENI
1F95; 1F95; 1F9D; 1F2D 0399; # GREEK SMALL LETTER ETA WITH DASIA AND OXIA AND YPOGEGRAMMENI
1F96; 1F96; 1F9E; 1F2E 0399; # GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI
1F97; 1F97; 1F9F; 1F2F 0399; # GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
1F98; 1F90; 1F98; 1F28 0399; # GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI
1F99; 1F91; 1F99; 1F29 0399; # GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI
1F9A; 1F92; 1F9A; 1F2A 0399; # GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI
1F9B; 1F93; 1F9B; 1F2B 0399; # GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI
1F9C; 1F94; 1F9C; 1F2C 0399; # GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI
1F9D; 1F95; 1F9D; 1F2D 0399; # GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI
1F9E; 1F96; 1F9E; 1F2E 0399; # GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
1F9F; 1F97; 1F9F; 1F2F 0399; # GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
1FA0; 1FA0; 1FA8; 1F68 0399; # GREEK SMALL LETTER OMEGA WITH PSILI AND YPOGEGRAMMENI
1FA1; 1FA1; 1FA9; 1F69 0399; # GREEK SMALL LETTER OMEGA WITH DASIA AND YPOGEGRAMMENI
1FA2; 1FA2; 1FAA; 1F6A 0399; # GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA AND YPOGEGRAMMENI
1FA3; 1FA3; 1FAB; 1F6B 0399; # GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA AND YPOGEGRAMMENI
1FA4; 1FA4; 1FAC; 1F6C 0399; # GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA AND YPOGEGRAMMENI
1FA5; 1FA5; 1FAD; 1F6D 0399; # GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA AND YPOGEGRAMMENI
1FA6; 1FA6; 1FAE; 1F6E 0399; # GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI
1FA7; 1FA7; 1FAF; 1F6F 0399; # GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
1FA8; 1FA0; 1FA8; 1F68 0399; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI
1FA9; 1FA1; 1FA9; 1F69 0399; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI
1FAA; 1FA2; 1FAA; 1F6A 0399; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI
1FAB; 1FA3; 1FAB; 1F6B 0399; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI
1FAC; 1FA4; 1FAC; 1F6C 0399; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI
1FAD; 1FA5; 1FAD; 1F6D 0399; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI
1FAE; 1FA6; 1FAE; 1F6E 0399; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
1FAF; 1FA7; 1FAF; 1F6F 0399; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
1FB3; 1FB3; 1FBC; 0391 0399; # GREEK SMALL LETTER ALPHA WITH YPOGEGRAMMENI
1FBC; 1FB3; 1FBC; 0391 0399; # GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
1FC3; 1FC3; 1FCC; 0397 0399; # GREEK SMALL LETTER ETA WITH YPOGEGRAMMENI
1FCC; 1FC3; 1FCC; 0397 0399; # GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
1FF3; 1FF3; 1FFC; 03A9 0399; # GREEK SMALL LETTER OMEGA WITH YPOGEGRAMMENI
1FFC; 1FF3; 1FFC; 03A9 0399; # GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
# Some characters with YPOGEGRAMMENI also have no corresponding titlecases
1FB2; 1FB2; 1FBA 0345; 1FBA 0399; # GREEK SMALL LETTER ALPHA WITH VARIA AND YPOGEGRAMMENI
1FB4; 1FB4; 0386 0345; 0386 0399; # GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI
1FC2; 1FC2; 1FCA 0345; 1FCA 0399; # GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI
1FC4; 1FC4; 0389 0345; 0389 0399; # GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI
1FF2; 1FF2; 1FFA 0345; 1FFA 0399; # GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI
1FF4; 1FF4; 038F 0345; 038F 0399; # GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI
1FB7; 1FB7; 0391 0342 0345; 0391 0342 0399; # GREEK SMALL LETTER ALPHA WITH PERISPOMENI AND YPOGEGRAMMENI
1FC7; 1FC7; 0397 0342 0345; 0397 0342 0399; # GREEK SMALL LETTER ETA WITH PERISPOMENI AND YPOGEGRAMMENI
1FF7; 1FF7; 03A9 0342 0345; 03A9 0342 0399; # GREEK SMALL LETTER OMEGA WITH PERISPOMENI AND YPOGEGRAMMENI
# ================================================================================
# Conditional mappings
# ================================================================================
# Special case for final form of sigma
03A3; 03C2; 03A3; 03A3; Final_Sigma; # GREEK CAPITAL LETTER SIGMA
# Note: the following cases for non-final are already in the UnicodeData file.
# 03A3; 03C3; 03A3; 03A3; # GREEK CAPITAL LETTER SIGMA
# 03C3; 03C3; 03A3; 03A3; # GREEK SMALL LETTER SIGMA
# 03C2; 03C2; 03A3; 03A3; # GREEK SMALL LETTER FINAL SIGMA
# Note: the following cases are not included, since they would case-fold in lowercasing
# 03C3; 03C2; 03A3; 03A3; Final_Sigma; # GREEK SMALL LETTER SIGMA
# 03C2; 03C3; 03A3; 03A3; Not_Final_Sigma; # GREEK SMALL LETTER FINAL SIGMA
# ================================================================================
# Locale-sensitive mappings
# ================================================================================
# Lithuanian
# Lithuanian retains the dot in a lowercase i when followed by accents.
# Remove DOT ABOVE after "i" with upper or titlecase
0307; 0307; ; ; lt After_Soft_Dotted; # COMBINING DOT ABOVE
# Introduce an explicit dot above when lowercasing capital I's and J's
# whenever there are more accents above.
# (of the accents used in Lithuanian: grave, acute, tilde above, and ogonek)
0049; 0069 0307; 0049; 0049; lt More_Above; # LATIN CAPITAL LETTER I
004A; 006A 0307; 004A; 004A; lt More_Above; # LATIN CAPITAL LETTER J
012E; 012F 0307; 012E; 012E; lt More_Above; # LATIN CAPITAL LETTER I WITH OGONEK
00CC; 0069 0307 0300; 00CC; 00CC; lt; # LATIN CAPITAL LETTER I WITH GRAVE
00CD; 0069 0307 0301; 00CD; 00CD; lt; # LATIN CAPITAL LETTER I WITH ACUTE
0128; 0069 0307 0303; 0128; 0128; lt; # LATIN CAPITAL LETTER I WITH TILDE
# ================================================================================
# Turkish and Azeri
# I and i-dotless; I-dot and i are case pairs in Turkish and Azeri
# The following rules handle those cases.
0130; 0069; 0130; 0130; tr; # LATIN CAPITAL LETTER I WITH DOT ABOVE
0130; 0069; 0130; 0130; az; # LATIN CAPITAL LETTER I WITH DOT ABOVE
# When lowercasing, remove dot_above in the sequence I + dot_above, which will turn into i.
# This matches the behavior of the canonically equivalent I-dot_above
0307; ; 0307; 0307; tr After_I; # COMBINING DOT ABOVE
0307; ; 0307; 0307; az After_I; # COMBINING DOT ABOVE
# When lowercasing, unless an I is before a dot_above, it turns into a dotless i.
0049; 0131; 0049; 0049; tr Not_Before_Dot; # LATIN CAPITAL LETTER I
0049; 0131; 0049; 0049; az Not_Before_Dot; # LATIN CAPITAL LETTER I
# When uppercasing, i turns into a dotted capital I
0069; 0069; 0130; 0130; tr; # LATIN SMALL LETTER I
0069; 0069; 0130; 0130; az; # LATIN SMALL LETTER I
# Note: the following case is already in the UnicodeData file.
# 0131; 0131; 0049; 0049; tr; # LATIN SMALL LETTER DOTLESS I

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,45 @@
UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
Unicode Data Files include all data files under the directories
http://www.unicode.org/Public/ and http://www.unicode.org/reports/.
Unicode Software includes any source code under the directories
http://www.unicode.org/Public/ and http://www.unicode.org/reports/.
NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING,
INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES ("DATA FILES"),
AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND
BY, ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE,
DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 1991-2004 Unicode, Inc. All rights reserved. Distributed under the
Terms of Use in http://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining a copy of
the Unicode data files and associated documentation (the "Data Files") or
Unicode software and associated documentation (the "Software") to deal in the
Data Files or Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, and/or sell copies of
the Data Files or Software, and to permit persons to whom the Data Files or
Software are furnished to do so, provided that (a) the above copyright notice(s)
and this permission notice appear in all copies of the Data Files or Software,
(b) both the above copyright notice(s) and this permission notice appear in
associated documentation, and (c) there is clear notice in each modified Data
File or in the Software as well as in the documentation associated with the Data
File(s) or Software that the data or software has been modified.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD
PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR
SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be
used in advertising or otherwise to promote the sale, use or other dealings in
these Data Files or Software without prior written authorization of the
copyright holder.

View file

@ -0,0 +1,32 @@
/*
*******************************************************************************
* Copyright (C) 1997-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.calendar;
import java.awt.Frame;
import com.ibm.icu.dev.demo.impl.*;
/**
* CalendarApp demonstrates how Calendar works.
*/
public class CalendarApp extends DemoApplet
{
/**
* The main function which defines the behavior of the CalendarDemo
* applet when an applet is started.
*/
public static void main(String argv[]) {
new CalendarApp().showDemo();
}
/* This creates a CalendarFrame for the demo applet. */
public Frame createDemoFrame(DemoApplet applet) {
return new CalendarFrame(applet);
}
}

View file

@ -0,0 +1,586 @@
/*
*******************************************************************************
* Copyright (C) 1997-2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.calendar;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Locale;
import javax.swing.JTextField;
import com.ibm.icu.dev.demo.impl.DemoApplet;
import com.ibm.icu.dev.demo.impl.DemoUtility;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.SimpleDateFormat;
import com.ibm.icu.util.BuddhistCalendar;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.GregorianCalendar;
import com.ibm.icu.util.HebrewCalendar;
import com.ibm.icu.util.IslamicCalendar;
import com.ibm.icu.util.JapaneseCalendar;
import com.ibm.icu.util.TimeZone;
/**
* CalendarCalc demonstrates how Date/Time formatter works.
*/
public class CalendarCalc extends DemoApplet
{
/**
* The main function which defines the behavior of the MultiCalendarDemo
* applet when an applet is started.
*/
public static void main(String argv[]) {
new CalendarCalc().showDemo();
}
/**
* This creates a CalendarCalcFrame for the demo applet.
*/
public Frame createDemoFrame(DemoApplet applet) {
return new CalendarCalcFrame(applet);
}
}
/**
* A Frame is a top-level window with a title. The default layout for a frame
* is BorderLayout. The CalendarCalcFrame class defines the window layout of
* MultiCalendarDemo.
*/
class CalendarCalcFrame extends Frame implements ActionListener
{
static final Locale[] locales = DemoUtility.getG7Locales();
private DemoApplet applet;
private long time = System.currentTimeMillis();
private static final RollAddField kRollAddFields[] = {
new RollAddField(Calendar.YEAR, "Year" ),
new RollAddField(Calendar.MONTH, "Month" ),
new RollAddField(Calendar.WEEK_OF_MONTH, "Week of Month" ),
new RollAddField(Calendar.WEEK_OF_YEAR, "Week of Year" ),
new RollAddField(Calendar.DAY_OF_MONTH, "Day of Month" ),
new RollAddField(Calendar.DAY_OF_WEEK, "Day of Week" ),
new RollAddField(Calendar.DAY_OF_WEEK_IN_MONTH, "Day of Week in Month" ),
new RollAddField(Calendar.DAY_OF_YEAR, "Day of Year" ),
new RollAddField(Calendar.AM_PM, "AM/PM" ),
new RollAddField(Calendar.HOUR_OF_DAY, "Hour of day" ),
new RollAddField(Calendar.HOUR, "Hour" ),
new RollAddField(Calendar.MINUTE, "Minute" ),
new RollAddField(Calendar.SECOND, "Second" ),
};
/**
* Constructs a new CalendarCalcFrame that is initially invisible.
*/
public CalendarCalcFrame(DemoApplet applet)
{
super("Multiple Calendar Demo");
this.applet = applet;
init();
start();
}
/**
* Initializes the applet. You never need to call this directly, it
* is called automatically by the system once the applet is created.
*/
public void init()
{
buildGUI();
patternText.setText( calendars[0].toPattern() );
// Force an update of the display
cityChanged();
millisFormat();
enableEvents(KeyEvent.KEY_RELEASED);
enableEvents(WindowEvent.WINDOW_CLOSING);
}
//------------------------------------------------------------
// package private
//------------------------------------------------------------
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
/**
* Called to start the applet. You never need to call this method
* directly, it is called when the applet's document is visited.
*/
public void start()
{
// do nothing
}
TextField patternText;
Choice dateMenu;
Choice localeMenu;
Button up;
Button down;
Checkbox getRoll;
Checkbox getAdd;
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new FlowLayout()); // shouldn't be necessary, but it is.
// TITLE
Label label1=new Label("Calendar Converter", Label.CENTER);
label1.setFont(DemoUtility.titleFont);
add(label1);
add(DemoUtility.createSpacer());
// IO Panel
Panel topPanel = new Panel();
topPanel.setLayout(new FlowLayout());
CheckboxGroup group1= new CheckboxGroup();
// Set up the controls for each calendar we're demonstrating
for (int i = 0; i < calendars.length; i++)
{
Label label = new Label(calendars[i].name, Label.RIGHT);
label.setFont(DemoUtility.labelFont);
topPanel.add(label);
topPanel.add(calendars[i].text);
final int j = i;
calendars[i].text.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
textChanged(j);
}
} );
calendars[i].rollAdd.setCheckboxGroup(group1);
topPanel.add(calendars[i].rollAdd);
}
calendars[0].rollAdd.setState(true); // Make the first one selected
Label label4=new Label("Pattern", Label.RIGHT);
label4.setFont(DemoUtility.labelFont);
topPanel.add(label4);
patternText=new TextField(FIELD_COLUMNS);
patternText.setFont(DemoUtility.editFont);
topPanel.add(patternText);
topPanel.add(new Label(""));
DemoUtility.fixGrid(topPanel,3);
add(topPanel);
add(DemoUtility.createSpacer());
// ROLL / ADD
Panel rollAddPanel=new Panel();
{
rollAddPanel.setLayout(new FlowLayout());
Panel rollAddBoxes = new Panel();
{
rollAddBoxes.setLayout(new GridLayout(2,1));
CheckboxGroup group2= new CheckboxGroup();
getRoll = new Checkbox("Roll",group2, false);
getAdd = new Checkbox("Add",group2, true);
rollAddBoxes.add(getRoll);
rollAddBoxes.add(getAdd);
}
Label dateLabel=new Label("Date Fields");
dateLabel.setFont(DemoUtility.labelFont);
dateMenu= new Choice();
dateMenu.setBackground(DemoUtility.choiceColor);
for (int i = 0; i < kRollAddFields.length; i++) {
dateMenu.addItem(kRollAddFields[i].name);
if (kRollAddFields[i].field == Calendar.MONTH) {
dateMenu.select(i);
}
}
Panel upDown = new Panel();
{
upDown.setLayout(new GridLayout(2,1));
// *** If the images are not found, we use the label.
up = new Button("^");
down = new Button("v");
up.setBackground(DemoUtility.bgColor);
down.setBackground(DemoUtility.bgColor);
upDown.add(up);
upDown.add(down);
up.addActionListener(this);
down.addActionListener(this);
}
rollAddPanel.add(dateLabel);
rollAddPanel.add(dateMenu);
rollAddPanel.add(rollAddBoxes);
rollAddPanel.add(upDown);
}
Panel localePanel = new Panel();
{
// Make the locale popup menus
localeMenu= new Choice();
Locale defaultLocale = Locale.getDefault();
int bestMatch = -1, thisMatch = -1;
int selectMe = 0;
for (int i = 0; i < locales.length; i++) {
if (i > 0 && locales[i].getLanguage().equals(locales[i-1].getLanguage()) ||
i < locales.length - 1 &&
locales[i].getLanguage().equals(locales[i+1].getLanguage()))
{
localeMenu.addItem( locales[i].getDisplayName() );
} else {
localeMenu.addItem( locales[i].getDisplayLanguage());
}
thisMatch = DemoUtility.compareLocales(locales[i], defaultLocale);
if (thisMatch >= bestMatch) {
bestMatch = thisMatch;
selectMe = i;
}
}
localeMenu.setBackground(DemoUtility.choiceColor);
localeMenu.select(selectMe);
Label localeLabel =new Label("Display Locale");
localeLabel.setFont(DemoUtility.labelFont);
localePanel.add(localeLabel);
localePanel.add(localeMenu);
DemoUtility.fixGrid(localePanel,2);
localeMenu.addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Locale loc = locales[localeMenu.getSelectedIndex()];
System.out.println("Change locale to " + loc.getDisplayName());
for (int i = 0; i < calendars.length; i++) {
calendars[i].setLocale(loc);
}
millisFormat();
}
} );
}
add(rollAddPanel);
add(DemoUtility.createSpacer());
add(localePanel);
add(DemoUtility.createSpacer());
// COPYRIGHT
Panel copyrightPanel = new Panel();
addWithFont (copyrightPanel,new Label(DemoUtility.copyright1, Label.LEFT),
DemoUtility.creditFont);
DemoUtility.fixGrid(copyrightPanel,1);
add(copyrightPanel);
}
/**
* This function is called when users change the pattern text.
*/
public void setFormatFromPattern() {
String timePattern = patternText.getText();
for (int i = 0; i < calendars.length; i++) {
calendars[i].applyPattern(timePattern);
}
millisFormat();
}
/**
* This function is called when it is necessary to parse the time
* string in one of the formatted date fields
*/
public void textChanged(int index) {
String rightString = calendars[index].text.getText();
ParsePosition status = new ParsePosition(0);
if (rightString.length() == 0)
{
errorText("Error: no input to parse!");
return;
}
try {
Date date = calendars[index].format.parse(rightString, status);
time = date.getTime();
}
catch (Exception e) {
for (int i = 0; i < calendars.length; i++) {
if (i != index) {
calendars[i].text.setText("ERROR");
}
}
errorText("Exception: " + e.getClass().toString() + " parsing: "+rightString);
return;
}
int start = calendars[index].text.getSelectionStart();
int end = calendars[index].text.getSelectionEnd();
millisFormat();
calendars[index].text.select(start,end);
}
/**
* This function is called when it is necessary to format the time
* in the "Millis" text field.
*/
public void millisFormat() {
String out = "";
for (int i = 0; i < calendars.length; i++) {
try {
out = calendars[i].format.format(new Date(time));
calendars[i].text.setText(out);
}
catch (Exception e) {
calendars[i].text.setText("ERROR");
errorText("Exception: " + e.getClass().toString() + " formatting "
+ calendars[i].name + " " + time);
}
}
}
/**
* This function is called when users change the pattern text.
*/
public void patternTextChanged() {
setFormatFromPattern();
}
/**
* This function is called when users select a new representative city.
*/
public void cityChanged() {
TimeZone timeZone = TimeZone.getDefault();
for (int i = 0; i < calendars.length; i++) {
calendars[i].format.setTimeZone(timeZone);
}
millisFormat();
}
/**
* This function is called when users select a new time field
* to add or roll its value.
*/
public void dateFieldChanged(boolean up) {
int field = kRollAddFields[dateMenu.getSelectedIndex()].field;
for (int i = 0; i < calendars.length; i++)
{
if (calendars[i].rollAdd.getState())
{
Calendar c = calendars[i].calendar;
c.setTime(new Date(time));
if (getAdd.getState()) {
c.add(field, up ? 1 : -1);
} else {
c.roll(field, up);
}
time = c.getTime().getTime();
millisFormat();
break;
}
}
}
/**
* Print out the error message while debugging this program.
*/
public void errorText(String s)
{
if (true) {
System.out.println(s);
}
}
/**
* Called if an action occurs in the CalendarCalcFrame object.
*/
public void actionPerformed(ActionEvent evt)
{
// *** Button events are handled here.
Object obj = evt.getSource();
System.out.println("action " + obj);
if (obj instanceof Button) {
if (evt.getSource() == up) {
dateFieldChanged(false);
} else
if (evt.getSource() == down) {
dateFieldChanged(true);
}
}
}
/**
* Handles the event. Returns true if the event is handled and should not
* be passed to the parent of this component. The default event handler
* calls some helper methods to make life easier on the programmer.
*/
protected void processKeyEvent(KeyEvent evt)
{
System.out.println("key " + evt);
if (evt.getID() == KeyEvent.KEY_RELEASED) {
if (evt.getSource() == patternText) {
patternTextChanged();
}
else {
for (int i = 0; i < calendars.length; i++) {
if (evt.getSource() == calendars[i].text) {
textChanged(i);
}
}
}
}
}
protected void processWindowEvent(WindowEvent evt)
{
System.out.println("window " + evt);
if (evt.getID() == WindowEvent.WINDOW_CLOSING &&
evt.getSource() == this) {
this.hide();
this.dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
}
/*
protected void processEvent(AWTEvent evt)
{
if (evt.getID() == AWTEvent. Event.ACTION_EVENT && evt.target == up) {
dateFieldChanged(true);
return true;
}
else if (evt.id == Event.ACTION_EVENT && evt.target == down) {
dateFieldChanged(false);
return true;
}
}
*/
private static final int FIELD_COLUMNS = 35;
class CalendarRec {
public CalendarRec(String nameStr, Calendar cal)
{
name = nameStr;
calendar = cal;
rollAdd = new Checkbox();
text = new JTextField("",FIELD_COLUMNS);
text.setFont(DemoUtility.editFont);
format = DateFormat.getDateInstance(cal, DateFormat.FULL,
Locale.getDefault());
//format.applyPattern(DEFAULT_FORMAT);
}
public void setLocale(Locale loc) {
String pattern = toPattern();
format = DateFormat.getDateInstance(calendar, DateFormat.FULL,
loc);
applyPattern(pattern);
}
public void applyPattern(String pattern) {
if (format instanceof SimpleDateFormat) {
((SimpleDateFormat)format).applyPattern(pattern);
//hey {al} -
// } else if (format instanceof java.text.SimpleDateFormat) {
// ((java.text.SimpleDateFormat)format).applyPattern(pattern);
}
}
private String toPattern() {
if (format instanceof SimpleDateFormat) {
return ((SimpleDateFormat)format).toPattern();
//hey {al} -
// } else if (format instanceof java.text.SimpleDateFormat) {
// return ((java.text.SimpleDateFormat)format).toPattern();
} else {
return "";
}
}
Calendar calendar;
DateFormat format;
String name;
JTextField text;
Checkbox rollAdd;
}
private final CalendarRec[] calendars = {
new CalendarRec("Gregorian", new GregorianCalendar()),
new CalendarRec("Hebrew", new HebrewCalendar()),
new CalendarRec("Islamic (civil)", makeIslamic(true)),
new CalendarRec("Islamic (true)", makeIslamic(false)),
new CalendarRec("Buddhist", new BuddhistCalendar()),
new CalendarRec("Japanese", new JapaneseCalendar()),
// new CalendarRec("Chinese", new ChineseCalendar()),
};
static private final Calendar makeIslamic(boolean civil) {
IslamicCalendar cal = new IslamicCalendar();
cal.setCivil(civil);
return cal;
}
}
class RollAddField {
RollAddField(int field, String name) {
this.field = field;
this.name = name;
}
int field;
String name;
}

View file

@ -0,0 +1,433 @@
/*
*******************************************************************************
* Copyright (C) 1997-2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.calendar;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.dev.demo.impl.DemoApplet;
import com.ibm.icu.dev.demo.impl.DemoUtility;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.util.BuddhistCalendar;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.GregorianCalendar;
import com.ibm.icu.util.HebrewCalendar;
import com.ibm.icu.util.IslamicCalendar;
import com.ibm.icu.util.JapaneseCalendar;
import com.ibm.icu.util.SimpleTimeZone;
/**
* A Frame is a top-level window with a title. The default layout for a frame
* is BorderLayout. The CalendarFrame class defines the window layout of
* CalendarDemo.
*/
class CalendarFrame extends Frame
{
private static final boolean DEBUG = false;
private DemoApplet applet;
/**
* Constructs a new CalendarFrame that is initially invisible.
*/
public CalendarFrame(DemoApplet myApplet)
{
super("Calendar Demo");
this.applet = myApplet;
init();
// When the window is closed, we want to shut down the applet or application
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
} );
}
private Choice displayMenu;
private Locale[] locales = DemoUtility.getG7Locales();
private Calendar calendars[] = new Calendar[2];
private Choice calMenu[] = new Choice[2];
private ColoredLabel monthLabel[] = new ColoredLabel[2];
private DateFormat monthFormat[] = new DateFormat[2];
private Button prevYear;
private Button prevMonth;
private Button gotoToday;
private Button nextMonth;
private Button nextYear;
private CalendarPanel calendarPanel;
private static void add(Container container, Component component,
GridBagLayout g, GridBagConstraints c,
int gridwidth, int weightx)
{
c.gridwidth = gridwidth;
c.weightx = weightx;
g.setConstraints(component, c);
container.add(component);
}
/**
* Initializes the applet. You never need to call this directly, it
* is called automatically by the system once the applet is created.
*/
public void init() {
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout(10,10));
Panel topPanel = new Panel();
GridBagLayout g = new GridBagLayout();
topPanel.setLayout(g);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
// Build the two menus for selecting which calendar is displayed,
// plus the month/year label for each calendar
for (int i = 0; i < 2; i++) {
calMenu[i] = new Choice();
for (int j = 0; j < CALENDARS.length; j++) {
calMenu[i].addItem(CALENDARS[j].name);
}
calMenu[i].setBackground(DemoUtility.choiceColor);
calMenu[i].select(i);
calMenu[i].addItemListener(new CalMenuListener());
// Label for the current month name
monthLabel[i] = new ColoredLabel("", COLORS[i]);
monthLabel[i].setFont(DemoUtility.titleFont);
// And the default calendar to use for this slot
calendars[i] = CALENDARS[i].calendar;
add(topPanel, calMenu[i], g, c, 5, 0);
add(topPanel, monthLabel[i], g, c, GridBagConstraints.REMAINDER, 1);
}
// Now add the next/previous year/month buttons:
prevYear = new Button("<<");
prevYear.addActionListener(new AddAction(Calendar.YEAR, -1));
prevMonth = new Button("<");
prevMonth.addActionListener(new AddAction(Calendar.MONTH, -1));
gotoToday = new Button("Today");
gotoToday.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e) {
calendarPanel.setDate( new Date() );
updateMonthName();
}
} );
nextMonth = new Button(">");
nextMonth.addActionListener(new AddAction(Calendar.MONTH, 1));
nextYear = new Button(">>");
nextYear.addActionListener(new AddAction(Calendar.YEAR, 1));
c.fill = GridBagConstraints.NONE;
add(topPanel, prevYear, g, c, 1, 0);
add(topPanel, prevMonth, g, c, 1, 0);
add(topPanel, gotoToday, g, c, 1, 0);
add(topPanel, nextMonth, g, c, 1, 0);
add(topPanel, nextYear, g, c, 1, 0);
// Now add the menu for selecting the display language
Panel displayPanel = new Panel();
{
displayMenu = new Choice();
Locale defaultLocale = Locale.getDefault();
int bestMatch = -1, thisMatch = -1;
int selectMe = 0;
for (int i = 0; i < locales.length; i++) {
if (i > 0 &&
locales[i].getLanguage().equals(locales[i-1].getLanguage()) ||
i < locales.length - 1 &&
locales[i].getLanguage().equals(locales[i+1].getLanguage()))
{
displayMenu.addItem( locales[i].getDisplayName() );
} else {
displayMenu.addItem( locales[i].getDisplayLanguage());
}
thisMatch = DemoUtility.compareLocales(locales[i], defaultLocale);
if (thisMatch >= bestMatch) {
bestMatch = thisMatch;
selectMe = i;
}
}
displayMenu.setBackground(DemoUtility.choiceColor);
displayMenu.select(selectMe);
displayMenu.addItemListener( new ItemListener()
{
public void itemStateChanged(ItemEvent e) {
Locale loc = locales[displayMenu.getSelectedIndex()];
calendarPanel.setLocale( loc );
monthFormat[0] = monthFormat[1] = null;
updateMonthName();
repaint();
}
} );
Label l1 = new Label("Display Language:", Label.RIGHT);
l1.setFont(DemoUtility.labelFont);
displayPanel.setLayout(new FlowLayout());
displayPanel.add(l1);
displayPanel.add(displayMenu);
}
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
add(topPanel, displayPanel, g, c, GridBagConstraints.REMAINDER, 0);
// The title, buttons, etc. go in a panel at the top of the window
add("North", topPanel);
// The copyright notice goes at the bottom of the window
Label copyright = new Label(DemoUtility.copyright1, Label.LEFT);
copyright.setFont(DemoUtility.creditFont);
add("South", copyright);
// Now create the big calendar panel and stick it in the middle
calendarPanel = new CalendarPanel( locales[displayMenu.getSelectedIndex()] );
add("Center", calendarPanel);
for (int i = 0; i < 2; i++) {
calendarPanel.setCalendar(i, calendars[i]);
calendarPanel.setColor(i, COLORS[i]);
}
updateMonthName();
}
private void updateMonthName()
{
for (int i = 0; i < 2; i++) {
try {
if (monthFormat[i] == null) { // TODO: optimize
DateFormat f = DateFormat.getDateTimeInstance(
calendars[i], DateFormat.MEDIUM, -1,
locales[displayMenu.getSelectedIndex()]);
if (f instanceof com.ibm.icu.text.SimpleDateFormat) {
com.ibm.icu.text.SimpleDateFormat f1 = (com.ibm.icu.text.SimpleDateFormat) f;
f1.applyPattern("MMMM, yyyy G");
f1.setTimeZone(new SimpleTimeZone(0, "UTC"));
}
monthFormat[i] = f;
}
} catch (ClassCastException e) {
//hey {lw} - there's something wrong in this routine that cuases exceptions.
System.out.println(e);
}
monthLabel[i].setText( monthFormat[i].format( calendarPanel.firstOfMonth() ));
}
}
/**
* CalMenuListener responds to events in the two popup menus that select
* the calendar systems to be used in the display. It figures out which
* of the two menus the event occurred in and updates the corresponding
* element of the calendars[] array to match the new selection.
*/
private class CalMenuListener implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
for (int i = 0; i < calMenu.length; i++)
{
if (e.getItemSelectable() == calMenu[i])
{
// We found the menu that the event happened in.
// Figure out which new calendar they selected.
Calendar newCal = CALENDARS[ calMenu[i].getSelectedIndex() ].calendar;
if (newCal != calendars[i])
{
// If any of the other menus are set to the same new calendar
// we're about to use for this menu, set them to the current
// calendar from *this* menu so we won't have two the same
for (int j = 0; j < calendars.length; j++) {
if (j != i && calendars[j] == newCal) {
calendars[j] = calendars[i];
calendarPanel.setCalendar(j, calendars[j]);
monthFormat[j] = null;
for (int k = 0; k < CALENDARS.length; k++) {
if (calendars[j] == CALENDARS[k].calendar) {
calMenu[j].select(k);
break;
}
}
}
}
// Now update this menu to use the new calendar the user selected
calendars[i] = newCal;
calendarPanel.setCalendar(i, newCal);
monthFormat[i] = null;
updateMonthName();
}
break;
}
}
}
}
/**
* AddAction handles the next/previous year/month buttons...
*/
private class AddAction implements ActionListener {
AddAction(int field, int amount) {
this.field = field;
this.amount = amount;
}
public void actionPerformed(ActionEvent e) {
calendarPanel.add(field, amount);
updateMonthName();
}
private int field, amount;
}
/**
* ColoredLabel is similar to java.awt.Label, with two differences:
*
* - You can set its text color
*
* - It draws text using drawString rather than using a host-specific
* "Peer" object like AWT does. On 1.2, using drawString gives
* us Bidi reordering for free.
*/
static private class ColoredLabel extends Component {
public ColoredLabel(String label) {
text = label;
}
public ColoredLabel(String label, Color c) {
text = label;
color = c;
}
public void setText(String label) {
text = label;
repaint();
}
public void setFont(Font f) {
font = f;
repaint();
}
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetrics(font);
Rectangle bounds = getBounds();
g.setColor(color);
g.setFont(font);
g.drawString(text, fm.stringWidth("\u00a0"),
bounds.height/2 + fm.getHeight()
- fm.getAscent() + fm.getLeading()/2);
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
public Dimension getMinimumSize() {
FontMetrics fm = getFontMetrics(font);
return new Dimension( fm.stringWidth(text) + 2*fm.stringWidth("\u00a0"),
fm.getHeight() + fm.getLeading()*2);
}
String text;
Color color = Color.black;
Font font = DemoUtility.labelFont;
}
/**
* Print out the error message while debugging this program.
*/
public void errorText(String s)
{
if (DEBUG)
{
System.out.println(s);
}
}
class CalendarRec {
public CalendarRec(String nameStr, Calendar cal)
{
name = nameStr;
calendar = cal;
}
Calendar calendar;
String name;
}
private final CalendarRec[] CALENDARS = {
new CalendarRec("Gregorian Calendar", new GregorianCalendar()),
new CalendarRec("Hebrew Calendar", new HebrewCalendar()),
new CalendarRec("Islamic Calendar", makeIslamic(false)),
new CalendarRec("Islamic Civil Calendar ", makeIslamic(true)),
new CalendarRec("Buddhist Calendar", new BuddhistCalendar()),
new CalendarRec("Japanese Calendar", new JapaneseCalendar()),
};
static private final Calendar makeIslamic(boolean civil) {
IslamicCalendar cal = new IslamicCalendar();
cal.setCivil(civil);
return cal;
}
static final Color[] COLORS = { Color.blue, Color.black };
}

View file

@ -0,0 +1,360 @@
/*
*******************************************************************************
* Copyright (C) 1997-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.calendar;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.dev.demo.impl.DemoUtility;
import com.ibm.icu.text.DateFormatSymbols;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.SimpleTimeZone;
class CalendarPanel extends Canvas {
public CalendarPanel( Locale locale ) {
setLocale(locale);
}
public void setLocale(Locale locale) {
if (fDisplayLocale == null || !fDisplayLocale.equals(locale)) {
fDisplayLocale = locale;
dirty = true;
for (int i = 0; i < fCalendar.length; i++) {
if (fCalendar[i] != null) {
fSymbols[i] = new DateFormatSymbols(fCalendar[i],
fDisplayLocale);
}
}
String lang = locale.getLanguage();
leftToRight = !(lang.equals("iw") || lang.equals("ar"));
repaint();
}
}
public void setDate(Date date) {
fStartOfMonth = date;
dirty = true;
repaint();
}
public void add(int field, int delta)
{
synchronized(fCalendar) {
fCalendar[0].setTime(fStartOfMonth);
fCalendar[0].add(field, delta);
fStartOfMonth = fCalendar[0].getTime();
}
dirty = true;
repaint();
}
public void setColor(int index, Color c) {
fColor[index] = c;
repaint();
}
public void setCalendar(int index, Calendar c) {
Date date = (fCalendar[index] == null) ? new Date()
: fCalendar[index].getTime();
fCalendar[index] = c;
fCalendar[index].setTime(date);
fSymbols[index] = new DateFormatSymbols(c, fDisplayLocale);
dirty = true;
repaint();
}
public Calendar getCalendar(int index) {
return fCalendar[index];
}
public Locale getDisplayLocale() {
return fDisplayLocale;
}
public Date firstOfMonth() {
return fStartOfMonth;
}
private Date startOfMonth(Date dateInMonth)
{
synchronized(fCalendar) {
fCalendar[0].setTime(dateInMonth);
int era = fCalendar[0].get(Calendar.ERA);
int year = fCalendar[0].get(Calendar.YEAR);
int month = fCalendar[0].get(Calendar.MONTH);
fCalendar[0].clear();
fCalendar[0].set(Calendar.ERA, era);
fCalendar[0].set(Calendar.YEAR, year);
fCalendar[0].set(Calendar.MONTH, month);
fCalendar[0].set(Calendar.DATE, 1);
return fCalendar[0].getTime();
}
}
private void calculate()
{
//
// As a workaround for JDK 1.1.3 and below, where Calendars and time
// zones are a bit goofy, always set my calendar's time zone to UTC.
// You would think I would want to do this in the "set" function above,
// but if I do that, the program hangs when this class is loaded,
// perhaps due to some sort of static initialization ordering problem.
// So I do it here instead.
//
fCalendar[0].setTimeZone(new SimpleTimeZone(0, "UTC"));
Calendar c = (Calendar)fCalendar[0].clone(); // Temporary copy
fStartOfMonth = startOfMonth(fStartOfMonth);
// Stash away a few useful constants for this calendar and display
minDay = c.getMinimum(Calendar.DAY_OF_WEEK);
daysInWeek = c.getMaximum(Calendar.DAY_OF_WEEK) - minDay + 1;
firstDayOfWeek = Calendar.getInstance(fDisplayLocale).getFirstDayOfWeek();
// Stash away a Date for the start of this month
// Find the day of week of the first day in this month
c.setTime(fStartOfMonth);
firstDayInMonth = c.get(Calendar.DAY_OF_WEEK);
int firstWeek = c.get(Calendar.WEEK_OF_MONTH);
// Now find the # of days in the month
c.roll(Calendar.DATE, false);
daysInMonth = c.get(Calendar.DATE);
// Finally, find the end of the month, i.e. the start of the next one
c.roll(Calendar.DATE, true);
c.add(Calendar.MONTH, 1);
c.getTime(); // JDK 1.1.2 bug workaround
c.add(Calendar.SECOND, -1);
Date endOfMonth = c.getTime();
if(endOfMonth==null){
//do nothing
}
endOfMonth = null;
int lastWeek = c.get(Calendar.WEEK_OF_MONTH);
// Calculate the number of full or partial weeks in this month.
numWeeks = lastWeek - firstWeek + 1;
dirty = false;
}
static final int XINSET = 4;
static final int YINSET = 2;
/*
* Convert from the day number within a month (1-based)
* to the cell coordinates on the calendar (0-based)
*/
private void dateToCell(int date, Point pos)
{
int cell = (date + firstDayInMonth - firstDayOfWeek - minDay);
if (firstDayInMonth < firstDayOfWeek) {
cell += daysInWeek;
}
pos.x = cell % daysInWeek;
pos.y = cell / daysInWeek;
}
//private Point dateToCell(int date) {
// Point p = new Point(0,0);
// dateToCell(date, p);
// return p;
//}
public void paint(Graphics g) {
if (dirty) {
calculate();
}
Point cellPos = new Point(0,0); // Temporary variable
Dimension d = this.getSize();
g.setColor(Color.lightGray);
g.fillRect(0,0,d.width,d.height);
// Draw the day names at the top
g.setColor(Color.black);
g.setFont(DemoUtility.labelFont);
FontMetrics fm = g.getFontMetrics();
int labelHeight = fm.getHeight() + YINSET * 2;
int v = fm.getAscent() + YINSET;
for (int i = 0; i < daysInWeek; i++) {
int dayNum = (i + minDay + firstDayOfWeek - 2) % daysInWeek + 1;
String dayName = fSymbols[0].getWeekdays()[dayNum];
double h;
if (leftToRight) {
h = d.width*(i + 0.5) / daysInWeek;
} else {
h = d.width*(daysInWeek - i - 0.5) / daysInWeek;
}
h -= fm.stringWidth(dayName) / 2;
g.drawString(dayName, (int)h, v);
}
double cellHeight = (d.height - labelHeight - 1) / numWeeks;
double cellWidth = (double)(d.width - 1) / daysInWeek;
// Draw a white background in the part of the calendar
// that displays this month.
// First figure out how much of the first week should be shaded.
{
g.setColor(Color.white);
dateToCell(1, cellPos);
int width = (int)(cellPos.x*cellWidth); // Width of unshaded area
if (leftToRight) {
g.fillRect((int)(width), labelHeight ,
d.width - width, (int)cellHeight);
} else {
g.fillRect(0, labelHeight ,
d.width - width, (int)cellHeight);
}
// All of the intermediate weeks get shaded completely
g.fillRect(0, (int)(labelHeight + cellHeight),
d.width, (int)(cellHeight * (numWeeks - 2)));
// Now figure out the last week.
dateToCell(daysInMonth, cellPos);
width = (int)((cellPos.x+1)*cellWidth); // Width of shaded area
if (leftToRight) {
g.fillRect(0, (int)(labelHeight + (numWeeks-1) * cellHeight),
width, (int)cellHeight);
} else {
g.fillRect(d.width - width, (int)(labelHeight + (numWeeks-1) * cellHeight),
width, (int)cellHeight);
}
}
// Draw the X/Y grid lines
g.setColor(Color.black);
for (int i = 0; i <= numWeeks; i++) {
int y = (int)(labelHeight + i * cellHeight);
g.drawLine(0, y, d.width - 1, y);
}
for (int i = 0; i <= daysInWeek; i++) {
int x = (int)(i * cellWidth);
g.drawLine(x, labelHeight, x, d.height - 1);
}
// Now loop through all of the days in the month, figure out where
// they go in the grid, and draw the day # for each one
// Figure out the date of the first cell in the calendar display
int cell = (1 + firstDayInMonth - firstDayOfWeek - minDay);
if (firstDayInMonth < firstDayOfWeek) {
cell += daysInWeek;
}
Calendar c = (Calendar)fCalendar[0].clone();
c.setTime(fStartOfMonth);
c.add(Calendar.DATE, -cell);
StringBuffer buffer = new StringBuffer();
for (int row = 0; row < numWeeks; row++) {
for (int col = 0; col < daysInWeek; col++) {
g.setFont(DemoUtility.numberFont);
g.setColor(Color.black);
fm = g.getFontMetrics();
int cellx;
if (leftToRight) {
cellx = (int)((col) * cellWidth);
} else {
cellx = (int)((daysInWeek - col - 1) * cellWidth);
}
int celly = (int)(row * cellHeight + labelHeight);
for (int i = 0; i < 2; i++) {
fCalendar[i].setTime(c.getTime());
int date = fCalendar[i].get(Calendar.DATE);
buffer.setLength(0);
buffer.append(date);
String dayNum = buffer.toString();
int x;
if (leftToRight) {
x = cellx + (int)cellWidth - XINSET - fm.stringWidth(dayNum);
} else {
x = cellx + XINSET;
}
int y = celly + + fm.getAscent() + YINSET + i * fm.getHeight();
if (fColor[i] != null) {
g.setColor(fColor[i]);
}
g.drawString(dayNum, x, y);
if (date == 1 || row == 0 && col == 0) {
g.setFont(DemoUtility.numberFont);
String month = fSymbols[i].getMonths()[
fCalendar[i].get(Calendar.MONTH)];
if (leftToRight) {
x = cellx + XINSET;
} else {
x = cellx + (int)cellWidth - XINSET - fm.stringWidth(month);
}
g.drawString(month, x, y);
}
}
c.add(Calendar.DATE, 1);
}
}
}
// Important state variables
private Calendar[] fCalendar = new Calendar[4];
private Color[] fColor = new Color[4];
private Locale fDisplayLocale;
private DateFormatSymbols[] fSymbols = new DateFormatSymbols[4];
private Date fStartOfMonth = new Date(); // 00:00:00 on first day of month
// Cached calculations to make drawing faster.
private transient int minDay; // Minimum legal day #
private transient int daysInWeek; // # of days in a week
private transient int firstDayOfWeek; // First day to display in week
private transient int numWeeks; // # full or partial weeks in month
private transient int daysInMonth; // # days in this month
private transient int firstDayInMonth; // Day of week of first day in month
private transient boolean leftToRight;
private transient boolean dirty = true;
}

View file

@ -0,0 +1,12 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000-2004, International Business Machines Corporation and
others. All Rights Reserved.
-->
</head>
<body bgcolor="white">
Calendar demo applications including date/time arithmetic.
</body>
</html>

View file

@ -0,0 +1,373 @@
/*
**************************************************************************
* Copyright (C) 2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
**************************************************************************
*
*/
package com.ibm.icu.dev.demo.charsetdet;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.net.URL;
import javax.swing.*;
import com.ibm.icu.impl.UTF32;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
/**
* This simple application demonstrates how to use the CharsetDetector API. It
* opens a file or web page, detects the encoding, and then displays it using that
* encoding.
*/
public class DetectingViewer extends JFrame implements ActionListener
{
private JTextPane text;
private JFileChooser fileChooser;
/**
* @throws java.awt.HeadlessException
*/
public DetectingViewer()
{
super();
fileChooser = new JFileChooser();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 800);
setJMenuBar(makeMenus());
text = new JTextPane();
text.setContentType("text/plain");
text.setText("");
text.setSize(800, 800);
Font font = new Font("Arial Unicode MS", Font.PLAIN, 24);
text.setFont(font);
JScrollPane scrollPane = new JScrollPane(text);
getContentPane().add(scrollPane);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
String cmd = event.getActionCommand();
if (cmd.equals("New...")) {
doNew();
} else if (cmd.equals("Open File...")) {
doOpenFile();
} else if (cmd.equals("Open URL...")) {
doOpenURL();
} else if (cmd.equals("Quit")) {
doQuit();
}
}
public static void main(String[] args)
{
new DetectingViewer();
}
private void errorDialog(String title, String msg)
{
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
}
private BufferedInputStream openFile(File file)
{
FileInputStream fileStream = null;
try {
fileStream = new FileInputStream(file);
} catch (Exception e) {
errorDialog("Error Opening File", e.getMessage());
return null;
}
return new BufferedInputStream(fileStream);
}
private void openFile(String directory, String filename)
{
openFile(new File(directory, filename));
}
private BufferedInputStream openURL(String url)
{
InputStream s = null;
try {
URL aURL = new URL(url);
s = aURL.openStream();
} catch (Exception e) {
errorDialog("Error Opening URL", e.getMessage());
return null;
}
return new BufferedInputStream(s);
}
private String encodingName(CharsetMatch match)
{
return match.getName() + " (" + match.getLanguage() + ")";
}
private void setMatchMenu(CharsetMatch[] matches)
{
JMenu menu = getJMenuBar().getMenu(1);
JMenuItem menuItem;
menu.removeAll();
for (int i = 0; i < matches.length; i += 1) {
CharsetMatch match = matches[i];
menuItem = new JMenuItem(encodingName(match) + " " + match.getConfidence());
menu.add(menuItem);
}
}
private byte[] scriptTag = {(byte) 's', (byte) 'c', (byte) 'r', (byte) 'i', (byte) 'p', (byte) 't'};
private byte[] styleTag = {(byte) 's', (byte) 't', (byte) 'y', (byte) 'l', (byte) 'e'};
private static int BUFFER_SIZE = 100000;
private boolean openTag(byte[] buffer, int offset, int length, byte[] tag)
{
int tagLen = tag.length;
int bufRem = length - offset;
int b;
for (b = 0; b < tagLen && b < bufRem; b += 1) {
if (buffer[b + offset] != tag[b]) {
return false;
}
}
return b == tagLen;
}
private boolean closedTag(byte[] buffer, int offset, int length, byte[] tag)
{
if (buffer[offset] != (byte) '/') {
return false;
}
return openTag(buffer, offset + 1, length, tag);
}
private byte[] filter(InputStream in)
{
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRemaining = BUFFER_SIZE;
int bufLen = 0;
in.mark(BUFFER_SIZE);
try {
while (bytesRemaining > 0) {
int bytesRead = in.read(buffer, bufLen, bytesRemaining);
if (bytesRead <= 0) {
break;
}
bufLen += bytesRead;
bytesRemaining -= bytesRead;
}
} catch (Exception e) {
// TODO: error handling?
return null;
}
boolean inTag = false;
boolean skip = false;
int out = 0;
for (int i = 0; i < bufLen; i += 1) {
byte b = buffer[i];
if (b == (byte) '<') {
inTag = true;
if (openTag(buffer, i + 1, bufLen, scriptTag) ||
openTag(buffer, i + 1, bufLen, styleTag)) {
skip = true;
} else if (closedTag(buffer, i + 1, bufLen, scriptTag) ||
closedTag(buffer, i + 1, bufLen, styleTag)) {
skip = false;
}
} else if (b == (byte) '>') {
inTag = false;
} else if (! (inTag || skip)) {
buffer[out++] = b;
}
}
byte[] filtered = new byte[out];
System.arraycopy(buffer, 0, filtered, 0, out);
return filtered;
}
private CharsetMatch[] detect(byte[] bytes)
{
CharsetDetector det = new CharsetDetector();
det.setText(bytes);
return det.detectAll();
}
private CharsetMatch[] detect(BufferedInputStream inputStream)
{
CharsetDetector det = new CharsetDetector();
try {
det.setText(inputStream);
return det.detectAll();
} catch (Exception e) {
// TODO: error message?
return null;
}
}
private void show(InputStream inputStream, CharsetMatch[] matches, String title)
{
InputStreamReader isr;
char[] buffer = new char[1024];
int bytesRead = 0;
if (matches == null || matches.length == 0) {
errorDialog("Match Error", "No matches!");
return;
}
try {
StringBuffer sb = new StringBuffer();
String encoding = matches[0].getName();
inputStream.reset();
if (encoding.startsWith("UTF-32")) {
byte[] bytes = new byte[1024];
int offset = 0;
int chBytes = 0;
UTF32 utf32 = UTF32.getInstance(encoding);
while ((bytesRead = inputStream.read(bytes, offset, 1024)) >= 0) {
offset = bytesRead % 4;
chBytes = bytesRead - offset;
sb.append(utf32.fromBytes(bytes, 0, chBytes));
if (offset != 0) {
for (int i = 0; i < offset; i += 1) {
bytes[i] = bytes[chBytes + i];
}
}
}
} else {
isr = new InputStreamReader(inputStream, encoding);
while ((bytesRead = isr.read(buffer, 0, 1024)) >= 0) {
sb.append(buffer, 0, bytesRead);
}
isr.close();
}
this.setTitle(title + " - " + encodingName(matches[0]));
setMatchMenu(matches);
text.setText(sb.toString());
} catch (IOException e) {
errorDialog("IO Error", e.getMessage());
} catch (Exception e) {
errorDialog("Internal Error", e.getMessage());
}
}
private void doNew()
{
// open a new window...
}
private void doOpenFile()
{
int retVal = fileChooser.showOpenDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
BufferedInputStream inputStream = openFile(file);
if (inputStream != null) {
CharsetMatch[] matches = detect(inputStream);
show(inputStream, matches, file.getName());
}
}
}
private void doOpenURL()
{
String url = (String) JOptionPane.showInputDialog(this, "URL to open:", "Open URL", JOptionPane.PLAIN_MESSAGE,
null, null, null);
if (url != null && url.length() > 0) {
BufferedInputStream inputStream = openURL(url);
if (inputStream != null) {
byte[] filtered = filter(inputStream);
CharsetMatch[] matches = detect(filtered);
show(inputStream, matches, url);
}
}
}
private void doQuit()
{
System.exit(0);
}
private JMenuBar makeMenus()
{
JMenu menu = new JMenu("File");
JMenuItem mi;
mi = new JMenuItem("Open File...");
mi.setAccelerator((KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)));
mi.addActionListener(this);
menu.add(mi);
mi = new JMenuItem("Open URL...");
mi.setAccelerator((KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK)));
mi.addActionListener(this);
menu.add(mi);
mi = new JMenuItem("Quit");
mi.setAccelerator((KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)));
mi.addActionListener(this);
menu.add(mi);
JMenuBar mbar = new JMenuBar();
mbar.add(menu);
menu = new JMenu("Detected Encodings");
mbar.add(menu);
return mbar;
}
}

View file

@ -0,0 +1,22 @@
/*
* Copyright (c) 2003-2004, International Business Machines Corporation
* and others. All rights reserved.
*
*/
th { font-size: 60%; text-align: Center;
width: 0.39%; font-family: monospace;
border: 1px solid black; margin: 0; padding: 1px }
td { font-size: 60%; text-align: Center;
border-right: 1px solid #9999FF; border-top: 1px solid #9999FF; margin: 0; padding: 1px }
table { border-spacing: 0; border-collapse: collapse;
border: 1px solid black; margin: 0; padding: 0 }
.d { border-top: 2px double blue }
.u { background-color: #DDDDDD }
.du { background-color: #DDDDDD; border-top: 2px double blue }
.n { background-color: black }
.dn { background-color: black; border-top: 2px double blue }
.i { background-color: yellow }
.di { background-color: yellow; border-top: 2px double blue }
p { font-size: 50%; text-align: Right }
.left { font-size: 75%; text-align: Left }

View file

@ -0,0 +1,164 @@
/*
*******************************************************************************
* Copyright (C) 1997-2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.chart;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.ibm.icu.dev.test.util.*;
import com.ibm.icu.impl.UCharacterProperty;
import com.ibm.icu.lang.*;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.VersionInfo;
public class UnicodeChart {
static int surrogateType = UCharacter.getType('\ud800');
static int privateUseType = UCharacter.getType('\ue000');
public static void main(String[] args) throws IOException {
//int rowWidth = 256;
VersionInfo vi = UCharacter.getUnicodeVersion();
String version = vi.getMajor() + "." + vi.getMinor() + "." + vi.getMilli();
PrintWriter pw = BagFormatter.openUTF8Writer("C:\\DATA\\GEN\\", "UnicodeChart.html");
pw.println("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
pw.println("<script type='text/javascript' src='UnicodeChart.js'></script>");
pw.println("<link rel='stylesheet' type='text/css' href='UnicodeChart.css'>");
pw.println("<title>Unicode " + version + " Chart</title>");
pw.println("</head><body bgcolor='#FFFFFF'>");
pw.println("<table border='1' cellspacing='0'><caption><h1>Unicode " + version + " Chart</h1></caption>");
/*pw.println("<tr><th></th>");
for (int j = 0; j < rowWidth; ++j) {
pw.print("<th>" + hex(j,2) + "</th>");
}
pw.println("</tr>");
*/
// TODO: fix Utility to take ints
System.out.println("//Surrogate Type: Java=" + Character.SURROGATE + ", ICU=" + surrogateType);
System.out.println("//Private-Use Type: Java=" + Character.PRIVATE_USE + ", ICU=" + privateUseType);
//boolean gotOne = true;
int columns = 0;
int limit = 0x110000/16;
char lastType = 'x';
int lastCount = 0;
pw.println("<script>");
pw.print("top();");
int itemCount = 1;
// an array that maps String (containing column information) to UnicodeSet (containing column numbers)
Map info_number = new TreeMap();
List number_info = new ArrayList();
StringBuffer sb = new StringBuffer();
int lastInfo = -1;
int sameCount = 0;
System.out.println("var charRanges = [");
for (int i = 0; i < limit; ++i) {
// get the string of info, and get its number
sb.setLength(0);
for (int j = 0; j < 16; ++j) {
int cp = i*16+j;
char type = getType(cp);
sb.append(type);
}
String info = sb.toString();
Integer s = (Integer) info_number.get(info);
if (s == null) {
info_number.put(info, s=new Integer(number_info.size()));
number_info.add(info);
}
// write a line whenever the value changes
if (lastInfo == s.intValue()) {
sameCount++;
} else {
if (lastInfo != -1) System.out.println(sameCount + "," + lastInfo + ",");
sameCount = 1;
lastInfo = s.intValue();
}
}
// write last line
System.out.println(sameCount + "," + lastInfo);
System.out.println("];");
// now write out array
int count = 0;
UnicodeMap um = new UnicodeMap();
System.out.println("var charInfo = [");
for (Iterator it = number_info.iterator(); it.hasNext();) {
String info = (String) it.next();
System.out.println("'" + info + "',");
}
System.out.println("];");
// write out blocks
Map blockMap = new TreeMap();
int startValue = -1;
int lastEnum = -1;
for (int i = 0; i <= 0x10FFFF; ++i) {
int prop = UCharacter.getIntPropertyValue(i,UProperty.BLOCK);
if (prop == lastEnum) continue;
if (lastEnum != -1) {
String s = UCharacter.getPropertyValueName(UProperty.BLOCK, lastEnum, UProperty.NameChoice.LONG);
blockMap.put(s, hex(startValue,0) + "/" + hex(i - startValue,0));
System.out.println(s + ": " + blockMap.get(s));
}
lastEnum = prop;
startValue = i;
}
String s = UCharacter.getPropertyValueName(UProperty.BLOCK, lastEnum, UProperty.NameChoice.LONG);
blockMap.put(s, hex(startValue,0) + "/" + hex(0x110000 - startValue,0));
blockMap.remove("No_Block");
for (Iterator it = blockMap.keySet().iterator(); it.hasNext();) {
String blockName = (String)it.next();
String val = (String) blockMap.get(blockName);
System.out.println("<option value='" + val + "'>" + blockName + "</option>");
}
// <option value="4DC0">Yijing Hexagram Symbols</option>
pw.println("</script></tr></table><p></p>");
pw.println("<table><caption>Key</caption>");
pw.println("<tr><td>X</td><td class='left'>Graphic characters</td></tr>");
pw.println("<tr><td>\u00A0</td><td class='left'>Whitespace</td></tr>");
pw.println("<tr><td class='i'>\u00A0</td><td class='left'>Other Default Ignorable</td></tr>");
pw.println("<tr><td class='u'>\u00A0</td><td class='left'>Undefined, Private Use, or Surrogates</td></tr>");
pw.println("<tr><td class='n'>\u00A0</td><td class='left'>Noncharacter</td></tr>");
pw.println("</table>");
pw.println("<p>Copyright \u00A9 2003, Mark Davis. All Rights Reserved.</body></html>");
pw.close();
System.out.println("//columns: " + columns);
}
private static char getType(int i) {
char type = 'v';
int cat = UCharacter.getType(i);
if (UCharacter.hasBinaryProperty(i, UProperty.NONCHARACTER_CODE_POINT)) {
type = 'n';
} else if (cat == Character.UNASSIGNED || cat == surrogateType || cat == privateUseType) {
type = 'u';
} else if (UCharacter.isUWhiteSpace(i)) {
type = 'w';
} else if (UCharacter.hasBinaryProperty(i, UProperty.DEFAULT_IGNORABLE_CODE_POINT)) {
type = 'i';
} else {
type = 'v';
}
return type;
}
static String hex(int i, int padTo) {
String result = Integer.toHexString(i).toUpperCase(java.util.Locale.ENGLISH);
while (result.length() < padTo) result = "0" + result;
return result;
}
}

View file

@ -0,0 +1,93 @@
//**************************************************************************
// Copyright (C) 1997-2004, International Business Machines Corporation and
// others. All Rights Reserved.
//**************************************************************************
var columnBits = 8; // 8
var columnCount = Math.pow(2,columnBits);
var columnMask = columnCount-1;
var columnShift = Math.floor(columnBits/4);
var columnGap = repeat('_', columnShift);
var columnPad = 4-columnShift;
var gotLast = true;
var current = 0;
var haveFirst = false;
function top(count) {
document.writeln("<th></th>");
for (var i = 0; i < columnCount; ++i) {
document.writeln("<th>", hex(i,2), "</th>");
}
}
function writeCell(cellclass, value) {
if (!gotLast) cellclass = 'd' + cellclass;
if (value) {
value = current <= 0xFFFF
? String.fromCharCode(current)
: String.fromCharCode(0xD800 + (current >> 10), 0xDC00 + (current & 0x3FF));
} else {
value = '\u00A0'
}
if (cellclass!="") cellclass = " class='" + cellclass + "'";
document.writeln("<td", cellclass, ">", value, "</td>");
++current;
}
function writeCells(count,cellclass,value) {
for (var i = 0; i < count; ++i) {
if ((current & columnMask) == 0) {
if (cellclass!='u' || count - i < columnCount) {
gotLast = true
} else {
gotLast = false;
var rem = (count - i) & ~columnMask;
current += rem;
i += rem;
if (i == count) break;
}
newRow();
}
writeCell(cellclass,value);
}
}
function newRow() {
if (haveFirst) document.write("</tr>");
else haveFirst = true;
var hclass = (gotLast) ? "" : " class='d'";
document.writeln("<tr><th", hclass, ">", hex(current>>(columnShift*4),columnPad), columnGap, "</th>");
}
// Utilities
function hex(value, pad) {
var result = value.toString(16).toUpperCase();
while (result.length < pad) result = '0' + result;
return result;
}
function repeat(str, count) {
var result = "";
for (var i = 0; i < count; ++i) result += str;
return result;
}
// used in the body. single letters to save bytes.
function u(count) { // undefined, private use, or surrogates
writeCells(count,'u',false);
}
function n(count) { // noncharacter
writeCells(count,'n',false);
}
function i(count) { // ignorable
writeCells(count,'i',false);
}
function w(count) { // whitespace
writeCells(count,'',false);
}
function v(count) { // normal visible graphic
writeCells(count,'',true);
}

View file

@ -0,0 +1,544 @@
/*
*******************************************************************************
* Copyright (C) 1997-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.holiday;
import java.awt.*;
/**
* Various graphical borders. The border itself is a Panel so that it can
* contain other Components (i.e. it borders something). You use the
* HolidayBorderPanel like any other Panel: you set the layout that you prefer and
* add Components to it. Beware that a null layout does not obey the insets
* of the panel so if you use null layouts, adjust your measurements to
* handle the border by calling insets().
*
* @author Andy Clark, Taligent Inc.
* @version 1.0
*/
public class HolidayBorderPanel extends Panel {
// Constants
/** Solid border. */
public final static int SOLID = 0;
/** A raised border. */
public final static int RAISED = 1;
/** A lowered border. */
public final static int LOWERED = 2;
/** An etched in border. */
public final static int IN = 3;
/** An etched out border. */
public final static int OUT = 4;
/** Left alignment. */
public final static int LEFT = 0;
/** Center alignment. */
public final static int CENTER = 1;
/** Right alignment. */
public final static int RIGHT = 2;
/** Default style (IN). */
public final static int DEFAULT_STYLE = IN;
/** Default thickness (10). */
public final static int DEFAULT_THICKNESS = 10;
/** Default thickness for solid borders (4). */
public final static int DEFAULT_SOLID_THICKNESS = 4;
/** Default thickness for raised borders (2). */
public final static int DEFAULT_RAISED_THICKNESS = 2;
/** Default thickness for lowered borders (2). */
public final static int DEFAULT_LOWERED_THICKNESS = 2;
/** Default thickness for etched-in borders (10). */
public final static int DEFAULT_IN_THICKNESS = 10;
/** Default thickness for etched-out borders (10). */
public final static int DEFAULT_OUT_THICKNESS = 10;
/** Default gap between border and contained component (5). */
public final static int DEFAULT_GAP = 5;
/** Default color (black). Applies to SOLID and etched borders. */
public final static Color DEFAULT_COLOR = Color.black;
/** Default font (TimesRoman,PLAIN,14). Only applies to etched borders. */
public final static Font DEFAULT_FONT = new Font("TimesRoman", Font.PLAIN, 14);
/** Default alignment (LEFT). Only applies to etched borders. */
public final static int DEFAULT_ALIGNMENT = LEFT;
// Data
private int style;
private int thickness;
private int gap;
private Color color;
private Font font;
private String text;
private int alignment;
/**
* Constructor. Makes default border.
*/
public HolidayBorderPanel() {
// initialize data
style = DEFAULT_STYLE;
thickness = DEFAULT_THICKNESS;
gap = DEFAULT_GAP;
color = DEFAULT_COLOR;
text = null;
font = DEFAULT_FONT;
alignment = DEFAULT_ALIGNMENT;
}
/**
* Constructor. Makes an etched IN border with given text caption.
*
* @param text Text caption
*/
public HolidayBorderPanel(String text) {
this();
style = IN;
this.text = text;
}
/**
* Constructor. Makes SOLID border with color and thickness given.
*
* @param color The color for the border.
* @param thickness The thickness of the border.
*/
public HolidayBorderPanel(Color color, int thickness) {
this();
style = SOLID;
this.color = color;
this.thickness = thickness;
}
/**
* Constructor. Makes a border of the given style with the default
* thickness for that style.
*
* @param style The style for this border.
*/
public HolidayBorderPanel(int style) {
this();
// set thickness appropriate to this style
int thickness;
switch (style) {
case SOLID: thickness = DEFAULT_SOLID_THICKNESS; break;
case RAISED: thickness = DEFAULT_RAISED_THICKNESS; break;
case LOWERED: thickness = DEFAULT_LOWERED_THICKNESS; break;
case IN: thickness = DEFAULT_IN_THICKNESS; break;
case OUT: thickness = DEFAULT_OUT_THICKNESS; break;
default:
thickness = DEFAULT_THICKNESS;
}
this.style = style;
this.thickness = thickness;
}
/**
* Constructor. Makes border with given style and thickness.
*
* @param style The style for this border.
* @param thickness The thickness for this border.
*/
public HolidayBorderPanel(int style, int thickness) {
this();
this.style = style;
this.thickness = thickness;
}
/**
* Returns the insets of this panel..
*/
public Insets getInsets() {
int adjustment = 0;
// adjust for text string
if (style == IN || style == OUT) {
if (text != null && text.length() > 0) {
try {
// set font and get info
int height = getGraphics().getFontMetrics(font).getHeight();
if (height > thickness)
adjustment = height - thickness;
}
catch (Exception e) {
// nothing: just in case there is no graphics context
// at the beginning.
System.out.print("");
}
}
}
// return appropriate insets
int dist = thickness + gap;
return new Insets(dist + adjustment, dist, dist, dist);
}
/**
* Sets the style of the border
*
* @param style The new style.
*/
public HolidayBorderPanel setStyle(int style) {
// set the style and re-layout the panel
this.style = style;
doLayout();
repaint();
return this;
}
/**
* Gets the style of the border
*/
public int getStyle() {
return style;
}
/**
* Sets the thickness of the border.
*
* @param thickness The new thickness
*/
public HolidayBorderPanel setThickness(int thickness) {
if (thickness > 0) {
this.thickness = thickness;
doLayout();
repaint();
}
return this;
}
/**
* Gets the thickness of the border.
*/
public int getThickness() {
return thickness;
}
/**
* Sets the gap between the border and the contained Component.
*
* @param gap The new gap, in pixels.
*/
public HolidayBorderPanel setGap(int gap) {
if (gap > -1) {
this.gap = gap;
doLayout();
repaint();
}
return this;
}
/**
* Gets the gap between the border and the contained Component.
*/
public int getGap() {
return gap;
}
/**
* Sets the current color for SOLID borders and the caption text
* color for etched borders.
*
* @param color The new color.
*/
public HolidayBorderPanel setColor(Color color) {
this.color = color;
if (style == SOLID || style == IN || style == OUT)
repaint();
return this;
}
/**
* Gets the current color for SOLID borders and the caption
* text color for etched borders.
*/
public Color getColor() {
return color;
}
/**
* Sets the font. Only applies to etched borders.
*/
public HolidayBorderPanel setTextFont(Font font) {
// set font
if (font != null) {
this.font = font;
if (style == IN || style == OUT) {
doLayout();
repaint();
}
}
return this;
}
/**
* Gets the font of the text. Only applies to etched borders.
*/
public Font getTextFont() {
return font;
}
/**
* Sets the text. Only applies to etched borders.
*
* @param text The new text.
*/
public HolidayBorderPanel setText(String text) {
this.text = text;
if (style == IN || style == OUT) {
doLayout();
repaint();
}
return this;
}
/**
* Gets the text. Only applies to etched borders.
*/
public String getText() {
return text;
}
/**
* Sets the text alignment. Only applies to etched borders.
*
* @param alignment The new alignment.
*/
public HolidayBorderPanel setAlignment(int alignment) {
this.alignment = alignment;
if (style == IN || style == OUT) {
doLayout();
repaint();
}
return this;
}
/**
* Gets the text alignment.
*/
public int getAlignment() {
return alignment;
}
/**
* Repaints the border.
*
* @param g The graphics context.
*/
public void paint(Graphics g) {
// get current dimensions
Dimension size = getSize();
int width = size.width;
int height = size.height;
// set colors
Color light = getBackground().brighter().brighter().brighter();
Color dark = getBackground().darker().darker().darker();
// Draw border
switch (style) {
case RAISED: // 3D Border (in or out)
case LOWERED:
Color topleft = null;
Color bottomright = null;
// set colors
if (style == RAISED) {
topleft = light;
bottomright = dark;
}
else {
topleft = dark;
bottomright = light;
}
// draw border
g.setColor(topleft);
for (int i = 0; i < thickness; i++) {
g.drawLine(i, i, width - i - 2, i);
g.drawLine(i, i + 1, i, height - i - 1);
}
g.setColor(bottomright);
for (int i = 0; i < thickness; i++) {
g.drawLine(i + 1, height - i - 1, width - i - 1, height - i - 1);
g.drawLine(width - i - 1, i, width - i - 1, height - i - 2);
}
break;
case IN: // Etched Border (in or out)
case OUT:
int adjust1 = 0;
int adjust2 = 0;
// set font and get info
Font oldfont = g.getFont();
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int ascent = fm.getAscent();
// set adjustment
if (style == IN)
adjust1 = 1;
else
adjust2 = 1;
// Calculate adjustment for text
int adjustment = 0;
if (text != null && text.length() > 0) {
if (ascent > thickness)
adjustment = (ascent - thickness) / 2;
}
// The adjustment is there so that we always draw the
// light rectangle first. Otherwise, your eye picks up
// the discrepancy where the light rect. passes over
// the darker rect.
int x = thickness / 2;
int y = thickness / 2 + adjustment;
int w = width - thickness - 1;
int h = height - thickness - 1 - adjustment;
// draw rectangles
g.setColor(light);
g.drawRect(x + adjust1, y + adjust1, w, h);
g.setColor(dark);
g.drawRect(x + adjust2, y + adjust2, w, h);
// draw text, if applicable
if (text != null && text.length() > 0) {
// calculate drawing area
int fontheight = fm.getHeight();
int strwidth = fm.stringWidth(text);
int textwidth = width - 2 * (thickness + 5);
if (strwidth > textwidth)
strwidth = textwidth;
// calculate offset for alignment
int offset;
switch (alignment) {
case CENTER:
offset = (width - strwidth) / 2;
break;
case RIGHT:
offset = width - strwidth - thickness - 5;
break;
case LEFT:
default: // assume left alignment if invalid
offset = thickness + 5;
break;
}
// clear drawing area and set clipping region
g.clearRect(offset - 5, 0, strwidth + 10, fontheight);
g.clipRect(offset, 0, strwidth, fontheight);
// draw text
g.setColor(color);
g.drawString(text, offset, ascent);
// restore old clipping area
g.clipRect(0, 0, width, height);
}
g.setFont(oldfont);
break;
case SOLID:
default: // assume SOLID
g.setColor(color);
for (int i = 0; i < thickness; i++)
g.drawRect(i, i, width - 2 * i - 1, height - 2 * i - 1);
}
}
/**
* Returns the settings of this HolidayBorderPanel instance as a string.
*/
public String toString() {
StringBuffer str = new StringBuffer("HolidayBorderPanel[");
// style
str.append("style=");
switch (style) {
case SOLID: str.append("SOLID"); break;
case RAISED: str.append("RAISED"); break;
case LOWERED: str.append("LOWERED"); break;
case IN: str.append("IN"); break;
case OUT: str.append("OUT"); break;
default: str.append("unknown");
}
str.append(",");
// thickness
str.append("thickness=");
str.append(thickness);
str.append(",");
// gap
str.append("gap=");
str.append(gap);
str.append(",");
// color
str.append(color);
str.append(",");
// font
str.append(font);
str.append(",");
// text
str.append("text=");
str.append(text);
str.append(",");
// alignment
str.append("alignment=");
switch (alignment) {
case LEFT: str.append("LEFT"); break;
case CENTER: str.append("CENTER"); break;
case RIGHT: str.append("RIGHT"); break;
default: str.append("unknown");
}
str.append("]");
return str.toString();
}
}

View file

@ -0,0 +1,731 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.holiday;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.text.DateFormatSymbols;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
import com.ibm.icu.dev.demo.impl.DemoApplet;
import com.ibm.icu.dev.demo.impl.DemoTextBox;
import com.ibm.icu.dev.demo.impl.DemoUtility;
import com.ibm.icu.text.SimpleDateFormat;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.Holiday;
import com.ibm.icu.util.SimpleTimeZone;
/**
* CalendarDemo demonstrates how Calendar works.
*/
public class HolidayCalendarDemo extends DemoApplet
{
/**
* The main function which defines the behavior of the CalendarDemo
* applet when an applet is started.
*/
public static void main(String argv[]) {
new HolidayCalendarDemo().showDemo();
}
/* This creates a CalendarFrame for the demo applet. */
public Frame createDemoFrame(DemoApplet applet) {
return new CalendarFrame(applet);
}
/**
* A Frame is a top-level window with a title. The default layout for a frame
* is BorderLayout. The CalendarFrame class defines the window layout of
* CalendarDemo.
*/
private static class CalendarFrame extends Frame implements ActionListener,
ItemListener
{
//private static final String creditString = ""; // unused
private static final boolean DEBUG = false;
//private Locale curLocale = Locale.US; // unused
private DemoApplet applet;
private static final Locale[] calendars = {
//new Locale("de","AT"),
Locale.CANADA,
Locale.CANADA_FRENCH,
Locale.FRANCE,
Locale.GERMANY,
new Locale("iw","IL"),
new Locale("el","GR"),
//new Locale("es","MX"),
Locale.UK,
Locale.US,
};
private static final Locale[] displays = {
Locale.CANADA,
Locale.UK,
Locale.US,
Locale.FRANCE,
Locale.CANADA_FRENCH,
//new Locale("de","AT"),
Locale.GERMAN,
new Locale("el","GR"),
//new Locale("iw","IL"),
new Locale("es","MX"),
};
/**
* Constructs a new CalendarFrame that is initially invisible.
*/
public CalendarFrame(DemoApplet applet)
{
super("Calendar Demo");
this.applet = applet;
init();
start();
enableEvents(WindowEvent.WINDOW_CLOSING);
}
/**
* Initializes the applet. You never need to call this directly, it
* is called automatically by the system once the applet is created.
*/
public void init()
{
// Get G7 locales only for demo purpose. To get all the locales
// supported, switch to calling Calendar.getAvailableLocales().
// commented
locales = displays;
buildGUI();
}
//------------------------------------------------------------
// package private
//------------------------------------------------------------
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
/**
* Called to start the applet. You never need to call this method
* directly, it is called when the applet's document is visited.
*/
public void start()
{
// do nothing
}
private Choice localeMenu;
private Choice displayMenu;
private Locale[] locales;
private Label monthLabel;
private Button prevYear;
private Button prevMonth;
private Button gotoToday;
private Button nextMonth;
private Button nextYear;
private CalendarPanel calendarPanel;
private static final Locale kFirstLocale = Locale.US;
private static void add(Container container, Component component,
GridBagLayout g, GridBagConstraints c)
{
g.setConstraints(component, c);
container.add(component);
}
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout(10,10));
// Label for the demo's title
Label titleLabel = new Label("Calendar Demo", Label.CENTER);
titleLabel.setFont(DemoUtility.titleFont);
// Label for the current month name
monthLabel = new Label("", Label.LEFT);
monthLabel.setFont(new Font(DemoUtility.titleFont.getName(),
DemoUtility.titleFont.getStyle(),
(DemoUtility.titleFont.getSize() * 3)/2));
// Make the locale popup menus
localeMenu= new Choice();
localeMenu.addItemListener(this);
int selectMe = 0;
for (int i = 0; i < calendars.length; i++) {
if (i > 0 &&
calendars[i].getCountry().equals(calendars[i-1].getCountry()) ||
i < calendars.length - 1 &&
calendars[i].getCountry().equals(calendars[i+1].getCountry()))
{
localeMenu.addItem(calendars[i].getDisplayCountry() + " (" +
calendars[i].getDisplayLanguage() + ")");
} else {
localeMenu.addItem( calendars[i].getDisplayCountry() );
}
if (calendars[i].equals(kFirstLocale)) {
selectMe = i;
}
}
localeMenu.setBackground(DemoUtility.choiceColor);
localeMenu.select(selectMe);
displayMenu = new Choice();
displayMenu.addItemListener(this);
selectMe = 0;
for (int i = 0; i < locales.length; i++) {
if (i > 0 &&
locales[i].getLanguage().equals(locales[i-1].getLanguage()) ||
i < locales.length - 1 &&
locales[i].getLanguage().equals(locales[i+1].getLanguage()))
{
displayMenu.addItem( locales[i].getDisplayName() );
} else {
displayMenu.addItem( locales[i].getDisplayLanguage());
}
if (locales[i].equals(kFirstLocale)) {
selectMe = i;
}
}
displayMenu.setBackground(DemoUtility.choiceColor);
displayMenu.select(selectMe);
// Make all the next/previous/today buttons
prevYear = new Button("<<");
prevYear.addActionListener(this);
prevMonth = new Button("<");
prevMonth.addActionListener(this);
gotoToday = new Button("Today");
gotoToday.addActionListener(this);
nextMonth = new Button(">");
nextMonth.addActionListener(this);
nextYear = new Button(">>");
nextYear.addActionListener(this);
// The month name and the control buttons are bunched together
Panel monthPanel = new Panel();
{
GridBagLayout g = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
monthPanel.setLayout(g);
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.REMAINDER;
add(monthPanel, monthLabel, g, c);
c.gridwidth = 1;
add(monthPanel, prevYear, g, c);
add(monthPanel, prevMonth, g, c);
add(monthPanel, gotoToday, g, c);
add(monthPanel, nextMonth, g, c);
c.gridwidth = GridBagConstraints.REMAINDER;
add(monthPanel, nextYear, g, c);
}
// Stick the menu and buttons in a little "control panel"
Panel menuPanel = new Panel();
{
GridBagLayout g = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
menuPanel.setLayout(g);
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.RELATIVE;
Label l1 = new Label("Holidays");
l1.setFont(DemoUtility.labelFont);
add(menuPanel, l1, g, c);
c.gridwidth = GridBagConstraints.REMAINDER;
add(menuPanel, localeMenu, g, c);
c.gridwidth = GridBagConstraints.RELATIVE;
Label l2 = new Label("Display:");
l2.setFont(DemoUtility.labelFont);
add(menuPanel, l2, g, c);
c.gridwidth = GridBagConstraints.REMAINDER;
add(menuPanel, displayMenu, g, c);
}
// The title, buttons, etc. go in a panel at the top of the window
Panel topPanel = new Panel();
{
topPanel.setLayout(new BorderLayout());
//topPanel.add("North", titleLabel);
topPanel.add("Center", monthPanel);
topPanel.add("East", menuPanel);
}
add("North", topPanel);
// The copyright notice goes at the bottom of the window
Label copyright = new Label(DemoUtility.copyright1, Label.LEFT);
copyright.setFont(DemoUtility.creditFont);
add("South", copyright);
// Now create the big calendar panel and stick it in the middle
calendarPanel = new CalendarPanel( kFirstLocale );
add("Center", calendarPanel);
updateMonthName();
}
private void updateMonthName()
{
SimpleDateFormat f = new SimpleDateFormat("MMMM yyyyy",
calendarPanel.getDisplayLocale());
f.setCalendar(calendarPanel.getCalendar());
f.setTimeZone(new SimpleTimeZone(0, "UTC")); // JDK 1.1.2 workaround
monthLabel.setText( f.format( calendarPanel.firstOfMonth() ));
}
/**
* Handles the event. Returns true if the event is handled and should not
* be passed to the parent of this component. The default event handler
* calls some helper methods to make life easier on the programmer.
*/
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
// *** Button events are handled here.
if (obj instanceof Button) {
if (obj == nextMonth) {
calendarPanel.add(Calendar.MONTH, +1);
}
else
if (obj == prevMonth) {
calendarPanel.add(Calendar.MONTH, -1);
}
else
if (obj == prevYear) {
calendarPanel.add(Calendar.YEAR, -1);
}
else
if (obj == nextYear) {
calendarPanel.add(Calendar.YEAR, +1);
}
else
if (obj == gotoToday) {
calendarPanel.set( new Date() );
}
updateMonthName();
}
}
public void itemStateChanged(ItemEvent e)
{
Object obj = e.getSource();
if (obj == localeMenu) {
calendarPanel.setCalendarLocale(calendars[localeMenu.getSelectedIndex()]);
updateMonthName();
}
else
if (obj == displayMenu) {
calendarPanel.setDisplayLocale(locales[displayMenu.getSelectedIndex()]);
updateMonthName();
}
}
/**
* Print out the error message while debugging this program.
*/
public void errorText(String s)
{
if (DEBUG)
{
System.out.println(s);
}
}
protected void processWindowEvent(WindowEvent e)
{
System.out.println("event " + e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
this.hide();
this.dispose();
if (applet != null) {
applet.demoClosed();
} else {
System.exit(0);
}
}
}
}
private static class CalendarPanel extends Canvas {
public CalendarPanel( Locale locale ) {
set(locale, locale, new Date());
}
public void setCalendarLocale(Locale locale) {
set(locale, fDisplayLocale, fCalendar.getTime());
}
public void setDisplayLocale(Locale locale) {
set(fCalendarLocale, locale, fCalendar.getTime());
}
public void set(Date date) {
set(fCalendarLocale, fDisplayLocale, date);
}
public void set(Locale loc, Locale display, Date date)
{
if (fCalendarLocale == null || !loc.equals(fCalendarLocale)) {
fCalendarLocale = loc;
fCalendar = Calendar.getInstance(fCalendarLocale);
fAllHolidays = Holiday.getHolidays(fCalendarLocale);
}
if (fDisplayLocale == null || !display.equals(fDisplayLocale)) {
fDisplayLocale = display;
fSymbols = new DateFormatSymbols(fDisplayLocale);
}
fStartOfMonth = date;
dirty = true;
repaint();
}
public void add(int field, int delta)
{
synchronized(fCalendar) {
fCalendar.setTime(fStartOfMonth);
fCalendar.add(field, delta);
fStartOfMonth = fCalendar.getTime();
}
dirty = true;
repaint();
}
public com.ibm.icu.util.Calendar getCalendar() {
return fCalendar;
}
public Locale getCalendarLocale() {
return fCalendarLocale;
}
public Locale getDisplayLocale() {
return fDisplayLocale;
}
public Date firstOfMonth() {
return fStartOfMonth;
}
private Date startOfMonth(Date dateInMonth)
{
synchronized(fCalendar) {
fCalendar.setTime(dateInMonth); // TODO: synchronization
int era = fCalendar.get(Calendar.ERA);
int year = fCalendar.get(Calendar.YEAR);
int month = fCalendar.get(Calendar.MONTH);
fCalendar.clear();
fCalendar.set(Calendar.ERA, era);
fCalendar.set(Calendar.YEAR, year);
fCalendar.set(Calendar.MONTH, month);
fCalendar.set(Calendar.DATE, 1);
return fCalendar.getTime();
}
}
private void calculate()
{
//
// As a workaround for JDK 1.1.3 and below, where Calendars and time
// zones are a bit goofy, always set my calendar's time zone to UTC.
// You would think I would want to do this in the "set" function above,
// but if I do that, the program hangs when this class is loaded,
// perhaps due to some sort of static initialization ordering problem.
// So I do it here instead.
//
fCalendar.setTimeZone(new SimpleTimeZone(0, "UTC"));
Calendar c = (Calendar)fCalendar.clone(); // Temporary copy
fStartOfMonth = startOfMonth(fStartOfMonth);
// Stash away a few useful constants for this calendar and display
minDay = c.getMinimum(Calendar.DAY_OF_WEEK);
daysInWeek = c.getMaximum(Calendar.DAY_OF_WEEK) - minDay + 1;
firstDayOfWeek = Calendar.getInstance(fDisplayLocale).getFirstDayOfWeek();
// Stash away a Date for the start of this month
// Find the day of week of the first day in this month
c.setTime(fStartOfMonth);
firstDayInMonth = c.get(Calendar.DAY_OF_WEEK);
// Now find the # of days in the month
c.roll(Calendar.DATE, false);
daysInMonth = c.get(Calendar.DATE);
// Finally, find the end of the month, i.e. the start of the next one
c.roll(Calendar.DATE, true);
c.add(Calendar.MONTH, 1);
c.getTime(); // JDK 1.1.2 bug workaround
c.add(Calendar.SECOND, -1);
Date endOfMonth = c.getTime();
//
// Calculate the number of full or partial weeks in this month.
// To do this I can just reuse the code that calculates which
// calendar cell contains a given date.
//
numWeeks = dateToCell(daysInMonth).y - dateToCell(1).y + 1;
// Remember which holidays fall on which days in this month,
// to save the trouble of having to do it later
fHolidays.setSize(0);
for (int h = 0; h < fAllHolidays.length; h++)
{
Date d = fStartOfMonth;
while ( (d = fAllHolidays[h].firstBetween(d, endOfMonth) ) != null)
{
c.setTime(d);
fHolidays.addElement( new HolidayInfo(c.get(Calendar.DATE),
fAllHolidays[h],
fAllHolidays[h].getDisplayName(fDisplayLocale) ));
d.setTime( d.getTime() + 1000 ); // "d++"
}
}
dirty = false;
}
static final int INSET = 2;
/*
* Convert from the day number within a month (1-based)
* to the cell coordinates on the calendar (0-based)
*/
private void dateToCell(int date, Point pos)
{
int cell = (date + firstDayInMonth - firstDayOfWeek - minDay);
if (firstDayInMonth < firstDayOfWeek) {
cell += daysInWeek;
}
pos.x = cell % daysInWeek;
pos.y = cell / daysInWeek;
}
private Point dateToCell(int date) {
Point p = new Point(0,0);
dateToCell(date, p);
return p;
}
public void paint(Graphics g) {
if (dirty) {
calculate();
}
Point cellPos = new Point(0,0); // Temporary variable
Dimension d = getSize();
g.setColor(DemoUtility.bgColor);
g.fillRect(0,0,d.width,d.height);
// Draw the day names at the top
g.setColor(Color.black);
g.setFont(DemoUtility.labelFont);
FontMetrics fm = g.getFontMetrics();
int labelHeight = fm.getHeight() + INSET * 2;
int v = fm.getAscent() + INSET;
for (int i = 0; i < daysInWeek; i++) {
int dayNum = (i + minDay + firstDayOfWeek - 2) % daysInWeek + 1;
String dayName = fSymbols.getWeekdays()[dayNum];
int h = (int) (d.width * (i + 0.5)) / daysInWeek;
h -= fm.stringWidth(dayName) / 2;
g.drawString(dayName, h, v);
}
double cellHeight = (d.height - labelHeight - 1) / numWeeks;
double cellWidth = (double)(d.width - 1) / daysInWeek;
// Draw a white background in the part of the calendar
// that displays this month.
// First figure out how much of the first week should be shaded.
{
g.setColor(Color.white);
dateToCell(1, cellPos);
int width = (int)(cellPos.x*cellWidth); // Width of unshaded area
g.fillRect((int)(width), labelHeight ,
(int)(d.width - width), (int)cellHeight);
// All of the intermediate weeks get shaded completely
g.fillRect(0, (int)(labelHeight + cellHeight),
d.width, (int)(cellHeight * (numWeeks - 2)));
// Now figure out the last week.
dateToCell(daysInMonth, cellPos);
width = (int)((cellPos.x+1)*cellWidth); // Width of shaded area
g.fillRect(0, (int)(labelHeight + (numWeeks-1) * cellHeight),
width, (int)(cellHeight));
}
// Draw the X/Y grid lines
g.setColor(Color.black);
for (int i = 0; i <= numWeeks; i++) {
int y = (int)(labelHeight + i * cellHeight);
g.drawLine(0, y, d.width - 1, y);
}
for (int i = 0; i <= daysInWeek; i++) {
int x = (int)(i * cellWidth);
g.drawLine(x, labelHeight, x, d.height - 1);
}
// Now loop through all of the days in the month, figure out where
// they go in the grid, and draw the day # for each one
Font numberFont = new Font("Helvetica",Font.PLAIN,12);
// not used Font holidayFont = DemoUtility.creditFont;
Calendar c = (Calendar)fCalendar.clone();
c.setTime(fStartOfMonth);
for (int i = 1, h = 0; i <= daysInMonth; i++) {
g.setFont(numberFont);
g.setColor(Color.black);
fm = g.getFontMetrics();
dateToCell(i, cellPos);
int x = (int)((cellPos.x + 1) * cellWidth);
int y = (int)(cellPos.y * cellHeight + labelHeight);
StringBuffer buffer = new StringBuffer();
buffer.append(i);
String dayNum = buffer.toString();
x = x - INSET - fm.stringWidth(dayNum);
y = y + fm.getAscent() + INSET;
g.drawString(dayNum, x, y);
// See if any of the holidays land on this day....
HolidayInfo info = null;
int count = 0;
// Coordinates of lower-left corner of cell.
x = (int)((cellPos.x) * cellWidth);
y = (int)((cellPos.y+1) * cellHeight) + labelHeight;
while (h < fHolidays.size() &&
(info = (HolidayInfo)fHolidays.elementAt(h)).date <= i)
{
if (info.date == i) {
// Draw the holiday here.
g.setFont(numberFont);
g.setColor(Color.red);
DemoTextBox box = new DemoTextBox(g, info.name, (int)(cellWidth - INSET));
box.draw(g, x + INSET, y - INSET - box.getHeight());
y -= (box.getHeight() + INSET);
count++;
}
h++;
}
}
}
// Important state variables
private Locale fCalendarLocale; // Whose calendar
private Calendar fCalendar; // Calendar for calculations
private Locale fDisplayLocale; // How to display it
private DateFormatSymbols fSymbols; // Symbols for drawing
private Date fStartOfMonth; // 00:00:00 on first day of month
// Cached calculations to make drawing faster.
private transient int minDay; // Minimum legal day #
private transient int daysInWeek; // # of days in a week
private transient int firstDayOfWeek; // First day to display in week
private transient int numWeeks; // # full or partial weeks in month
private transient int daysInMonth; // # days in this month
private transient int firstDayInMonth; // Day of week of first day in month
private transient Holiday[] fAllHolidays;
private transient Vector fHolidays = new Vector(5,5);
private transient boolean dirty = true;
}
private static class HolidayInfo {
public HolidayInfo(int date, Holiday holiday, String name) {
this.date = date;
this.holiday = holiday;
this.name = name;
}
public Holiday holiday;
public int date;
public String name;
}
}

View file

@ -0,0 +1,12 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000-2004, International Business Machines Corporation and
others. All Rights Reserved.
-->
</head>
<body bgcolor="white">
Holiday demo application.
</body>
</html>

View file

@ -0,0 +1,145 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.impl;
import java.applet.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.awt.*;
import java.awt.event.*;
import java.io.InputStream;
import java.io.IOException;
/**
* <p>A Frame that runs an Applet within itself, making it possible
* for an applet to run as an application. Usage:
*
* <pre>
* public class MyApplet extends Applet {
* public static void main(String args[]) {
* MyApplet applet = new MyApplet();
* new AppletFrame("My Applet Running As An App", applet, 640, 480);
* }
* ...
* }
* <pre>
*
* <p>Copyright &copy; IBM Corporation 1999. All rights reserved.
*
* @author Alan Liu
*/
public class AppletFrame extends Frame implements AppletStub, AppletContext {
Applet applet;
private static final String COPYRIGHT =
"\u00A9 IBM Corporation 1999. All rights reserved.";
/**
* Construct a Frame running the given Applet with the default size
* of 640 by 480.
* When the Frame is closed, the applet's stop() method is called,
* the Frame is dispose()d of, and System.exit(0) is called.
*
* @param name the Frame title
* @param applet the applet to be run
*/
public AppletFrame(String name, Applet applet) {
this(name, applet, 640, 480);
}
/**
* Construct a Frame running the given Applet with the given size.
* When the Frame is closed, the applet's stop() method is called,
* the Frame is dispose()d of, and System.exit(0) is called.
*
* @param name the Frame title
* @param applet the applet to be run
* @param width width of the Frame
* @param height height of the Frame
*/
public AppletFrame(String name, Applet applet, int width, int height) {
super(name);
this.applet = applet;
applet.setStub(this);
setSize(width, height);
add("Center", applet);
show();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
AppletFrame.this.applet.stop();
dispose();
System.exit(0);
}
});
applet.init();
applet.start();
}
// AppletStub API
public void appletResize(int width, int height) {
setSize(width, height);
}
public AppletContext getAppletContext() {
return this;
}
public URL getCodeBase() {
return null;
}
public URL getDocumentBase() {
return null;
}
public String getParameter(String name) {
return "PARAMETER";
}
public boolean isActive() {
return true;
}
// AppletContext API
public Applet getApplet(String name) {
return applet;
}
public Enumeration getApplets() {
return null;
}
public AudioClip getAudioClip(URL url) {
return null;
}
public Image getImage(URL url) {
return null;
}
public void showDocument(URL url) {}
public void showDocument(URL url, String target) {}
public void showStatus(String status) {
System.out.println(status);
}
public void setStream(String key, InputStream stream) throws IOException {
}
public InputStream getStream(String key) {
return null;
}
public Iterator getStreamKeys() {
return null;
}
}

View file

@ -0,0 +1,72 @@
/*
*******************************************************************************
* Copyright (C) 1997-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.impl;
import java.awt.*;
import java.awt.event.*;
public abstract class DemoApplet extends java.applet.Applet {
private Button demoButton;
private Frame demoFrame;
private static int demoFrameCount = 0;
protected abstract Frame createDemoFrame(DemoApplet applet);
protected Dimension getDefaultFrameSize(DemoApplet applet, Frame f) {
return new Dimension(700, 550);
}
//Create a button that will display the demo
public void init()
{
setBackground(Color.white);
demoButton = new Button("Demo");
demoButton.setBackground(Color.yellow);
add( demoButton );
demoButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getID() == ActionEvent.ACTION_PERFORMED) {
demoButton.setLabel("loading");
if (demoFrame == null) {
demoFrame = createDemoFrame(DemoApplet.this);
showDemo();
}
demoButton.setLabel("Demo");
}
}
} );
}
public void showDemo()
{
demoFrame = createDemoFrame(this);
demoFrame.doLayout();
Dimension d = getDefaultFrameSize(this, demoFrame);
demoFrame.setSize(d.width, d.height);
demoFrame.show();
demoFrameOpened();
}
public void demoClosed()
{
demoFrame = null;
demoFrameClosed();
}
protected static void demoFrameOpened() {
demoFrameCount++;
}
protected static void demoFrameClosed() {
if (--demoFrameCount == 0) {
System.exit(0);
}
}
}

View file

@ -0,0 +1,95 @@
/*
*******************************************************************************
* Copyright (C) 1997-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.impl;
import java.text.BreakIterator;
import java.awt.*;
public class DemoTextBox {
public DemoTextBox(Graphics g, String text, int width)
{
this.text = text;
this.chars = new char[text.length()];
text.getChars(0, text.length(), chars, 0);
this.width = width;
this.port = g;
this.metrics = g.getFontMetrics();
breakText();
}
public int getHeight() {
return (nbreaks + 1) * metrics.getHeight();
}
public void draw(Graphics g, int x, int y)
{
int index = 0;
y += metrics.getAscent();
for (int i = 0; i < nbreaks; i++)
{
g.drawChars(chars, index, breakPos[i] - index, x, y);
index = breakPos[i];
y += metrics.getHeight();
}
g.drawChars(chars, index, chars.length - index, x, y);
}
private void breakText()
{
if (metrics.charsWidth(chars, 0, chars.length) > width)
{
BreakIterator iter = BreakIterator.getWordInstance();
iter.setText(text);
int start = iter.first();
int end = start;
int pos;
while ( (pos = iter.next()) != BreakIterator.DONE )
{
int w = metrics.charsWidth(chars, start, pos - start);
if (w > width)
{
// We've gone past the maximum width, so break the line
if (end > start) {
// There was at least one break position before this point
breakPos[nbreaks++] = end;
start = end;
end = pos;
} else {
// There weren't any break positions before this one, so
// let this word overflow the margin (yuck)
breakPos[nbreaks++] = pos;
start = end = pos;
}
} else {
// the current position still fits on the line; it's the best
// tentative break position we have so far.
end = pos;
}
}
}
}
private String text;
private char[] chars;
private Graphics port;
private FontMetrics metrics;
private int width;
private int[] breakPos = new int[10]; // TODO: get real
private int nbreaks = 0;
}

View file

@ -0,0 +1,127 @@
/*
*******************************************************************************
* Copyright (C) 1997-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.impl;
import java.awt.*;
import java.util.*;
public class DemoUtility
{
public static final Font titleFont = new Font("TimesRoman",Font.BOLD,18);
public static final Font labelFont = new Font("TimesRoman",Font.BOLD,14);
public static final Font choiceFont = new Font("Helvetica",Font.BOLD,12);
public static final Font editFont = new Font("Helvetica",Font.PLAIN,14);
public static final Font creditFont = new Font("Helvetica",Font.PLAIN,10);
public static final Font numberFont = new Font("sansserif", Font.PLAIN, 14);
public static final Color bgColor = Color.lightGray;
public static final Color choiceColor = Color.white;
public static final String copyright1 =
"Copyright (C) IBM Corp and others. 1997 - 2002 All Rights Reserved";
/**
Provides easy way to use basic functions of GridBagLayout, without
the complications. After building a panel, and inserting all the
* subcomponents, call this to lay it out in the desired number of columns.
*/
public static void fixGrid(Container cont, int columns) {
GridBagLayout gridbag = new GridBagLayout();
cont.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 1.0;
c.insets = new Insets(2,2,2,2);
Component[] components = cont.getComponents();
for (int i = 0; i < components.length; ++i) {
// not used int colNumber = i%columns;
c.gridwidth = 1; // default
if ((i%columns) == columns - 1)
c.gridwidth = GridBagConstraints.REMAINDER; // last in grid
if (components[i] instanceof Label) {
switch (((Label)components[i]).getAlignment()) {
case Label.CENTER: c.anchor = GridBagConstraints.CENTER; break;
case Label.LEFT: c.anchor = GridBagConstraints.WEST; break;
case Label.RIGHT: c.anchor = GridBagConstraints.EAST; break;
}
}
gridbag.setConstraints(components[i], c);
}
}
/**
Provides easy way to change the spacing around an object in a GridBagLayout.
Call AFTER fixGridBag, passing in the container, the component, and the
new insets.
*/
public static void setInsets(Container cont, Component comp, Insets insets) {
GridBagLayout gbl = (GridBagLayout)cont.getLayout();
GridBagConstraints g = gbl.getConstraints(comp);
g.insets = insets;
gbl.setConstraints(comp,g);
}
public static Panel createSpacer() {
Panel spacer = new Panel();
spacer.setLayout(null);
spacer.setSize(1000, 1);
return spacer;
}
// to avoid goofy updates and misplaced cursors
public static void setText(TextComponent area, String newText) {
String foo = area.getText();
if (foo.equals(newText)) return;
area.setText(newText);
}
/**
* Compares two locals. Return value is negative
* if they're different, and more positive the more
* fields that match.
*/
public static int compareLocales(Locale l1, Locale l2)
{
int result = -1;
if (l1.getLanguage().equals(l2.getLanguage())) {
result += 1;
if (l1.getCountry().equals(l2.getCountry())) {
result += 1;
if (l1.getVariant().equals(l2.getVariant())) {
result += 1;
}
}
}
return result;
}
/**
* Get the G7 locale list for demos.
*/
public static Locale[] getG7Locales() {
return localeList;
}
private static Locale[] localeList = {
new Locale("DA", "DK", ""),
new Locale("EN", "US", ""),
new Locale("EN", "GB", ""),
new Locale("EN", "CA", ""),
new Locale("FR", "FR", ""),
new Locale("FR", "CA", ""),
new Locale("DE", "DE", ""),
new Locale("IT", "IT", ""),
//new Locale("JA", "JP", ""),
};
}

View file

@ -0,0 +1,798 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.impl;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.awt.datatransfer.*;
// LIU: Changed from final to non-final
public class DumbTextComponent extends Canvas
implements KeyListener, MouseListener, MouseMotionListener, FocusListener
{
private transient static final String copyright =
"Copyright \u00A9 1998, Mark Davis. All Rights Reserved.";
private transient static boolean DEBUG = false;
private String contents = "";
private Selection selection = new Selection();
private int activeStart = -1;
private boolean editable = true;
private transient Selection tempSelection = new Selection();
private transient boolean focus;
private transient BreakIterator lineBreaker = BreakIterator.getLineInstance();
private transient BreakIterator wordBreaker = BreakIterator.getWordInstance();
private transient BreakIterator charBreaker = BreakIterator.getCharacterInstance();
private transient int lineAscent;
private transient int lineHeight;
private transient int lineLeading;
private transient int lastHeight = 10;
private transient int lastWidth = 50;
private static final int MAX_LINES = 200; // LIU: Use symbolic name
private transient int[] lineStarts = new int[MAX_LINES]; // LIU
private transient int lineCount = 1;
private transient boolean valid = false;
private transient FontMetrics fm;
private transient boolean redoLines = true;
private transient boolean doubleClick = false;
private transient TextListener textListener;
private transient ActionListener selectionListener;
private transient Image cacheImage;
private transient Dimension mySize;
private transient int xInset = 5;
private transient int yInset = 5;
private transient Point startPoint = new Point();
private transient Point endPoint = new Point();
private transient Point caretPoint = new Point();
private transient Point activePoint = new Point();
//private transient static String clipBoard;
private static final char CR = '\015'; // LIU
// ============================================
public DumbTextComponent() {
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
addFocusListener(this);
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
}
// ================ Events ====================
// public boolean isFocusTraversable() { return true; }
public void addActionListener(ActionListener l) {
selectionListener = AWTEventMulticaster.add(selectionListener, l);
}
public void removeActionListener(ActionListener l) {
selectionListener = AWTEventMulticaster.remove(selectionListener, l);
}
public void addTextListener(TextListener l) {
textListener = AWTEventMulticaster.add(textListener, l);
}
public void removeTextListener(TextListener l) {
textListener = AWTEventMulticaster.remove(textListener, l);
}
private transient boolean pressed;
public void mousePressed(MouseEvent e) {
if (DEBUG) System.out.println("mousePressed");
if (pressed) {
select(e,false);
} else {
doubleClick = e.getClickCount() > 1;
requestFocus();
select(e, true);
pressed = true;
}
}
public void mouseDragged(MouseEvent e) {
if (DEBUG) System.out.println("mouseDragged");
select(e, false);
}
public void mouseReleased(MouseEvent e) {
if (DEBUG) System.out.println("mouseReleased");
pressed = false;
}
public void mouseEntered(MouseEvent e) {
//if (pressed) select(e, false);
}
public void mouseExited(MouseEvent e){
//if (pressed) select(e, false);
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void focusGained(FocusEvent e) {
if (DEBUG) System.out.println("focusGained");
focus = true;
valid = false;
repaint(16);
}
public void focusLost(FocusEvent e) {
if (DEBUG) System.out.println("focusLost");
focus = false;
valid = false;
repaint(16);
}
public void select(MouseEvent e, boolean first) {
setKeyStart(-1);
point2Offset(e.getPoint(), tempSelection);
if (first) {
if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) {
tempSelection.anchor = tempSelection.caret;
}
}
// fix words
if (doubleClick) {
tempSelection.expand(wordBreaker);
}
select(tempSelection);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (DEBUG) System.out.println("keyPressed "
+ hex((char)code) + ", " + hex((char)e.getModifiers()));
int start = selection.getStart();
int end = selection.getEnd();
boolean shift = (e.getModifiers() & KeyEvent.SHIFT_MASK) != 0;
boolean ctrl = (e.getModifiers() & KeyEvent.CTRL_MASK) != 0;
switch (code) {
case KeyEvent.VK_Q:
if (!ctrl || !editable) break;
setKeyStart(-1);
fixHex();
break;
case KeyEvent.VK_V:
if (!ctrl) break;
if (!editable) {
this.getToolkit().beep();
} else {
paste();
}
break;
case KeyEvent.VK_C:
if (!ctrl) break;
copy();
break;
case KeyEvent.VK_X:
if (!ctrl) break;
if (!editable) {
this.getToolkit().beep();
} else {
copy();
insertText("");
}
break;
case KeyEvent.VK_A:
if (!ctrl) break;
setKeyStart(-1);
select(Integer.MAX_VALUE, 0, false);
break;
case KeyEvent.VK_RIGHT:
setKeyStart(-1);
tempSelection.set(selection);
tempSelection.nextBound(ctrl ? wordBreaker : charBreaker, +1, shift);
select(tempSelection);
break;
case KeyEvent.VK_LEFT:
setKeyStart(-1);
tempSelection.set(selection);
tempSelection.nextBound(ctrl ? wordBreaker : charBreaker, -1, shift);
select(tempSelection);
break;
case KeyEvent.VK_UP: // LIU: Add support for up arrow
setKeyStart(-1);
tempSelection.set(selection);
tempSelection.caret = lineDelta(tempSelection.caret, -1);
if (!shift) {
tempSelection.anchor = tempSelection.caret;
}
select(tempSelection);
break;
case KeyEvent.VK_DOWN: // LIU: Add support for down arrow
setKeyStart(-1);
tempSelection.set(selection);
tempSelection.caret = lineDelta(tempSelection.caret, +1);
if (!shift) {
tempSelection.anchor = tempSelection.caret;
}
select(tempSelection);
break;
case KeyEvent.VK_DELETE: // LIU: Add delete key support
if (!editable) break;
setKeyStart(-1);
if (contents.length() == 0) break;
start = selection.getStart();
end = selection.getEnd();
if (start == end) {
++end;
if (end > contents.length()) {
getToolkit().beep();
return;
}
}
replaceRange("", start, end);
break;
}
}
void copy() {
Clipboard cb = this.getToolkit().getSystemClipboard();
StringSelection ss = new StringSelection(
contents.substring(selection.getStart(), selection.getEnd()));
cb.setContents(ss, ss);
}
void paste () {
Clipboard cb = this.getToolkit().getSystemClipboard();
Transferable t = cb.getContents(this);
if (t == null) {
this.getToolkit().beep();
return;
}
try {
String temp = (String) t.getTransferData(DataFlavor.stringFlavor);
insertText(temp);
} catch (Exception e) {
this.getToolkit().beep();
}
}
/**
* LIU: Given an offset into contents, moves up or down by lines,
* according to lineStarts[].
* @param off the offset into contents
* @param delta how many lines to move up (< 0) or down (> 0)
* @return the new offset into contents
*/
private int lineDelta(int off, int delta) {
int line = findLine(off, false);
int posInLine = off - lineStarts[line];
// System.out.println("off=" + off + " at " + line + ":" + posInLine);
line += delta;
if (line < 0) {
line = posInLine = 0;
} else if (line >= lineCount) {
return contents.length();
}
off = lineStarts[line] + posInLine;
if (off >= lineStarts[line+1]) {
off = lineStarts[line+1] - 1;
}
return off;
}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if (DEBUG) System.out.println("keyReleased "
+ hex((char)code) + ", " + hex((char)e.getModifiers()));
}
public void keyTyped(KeyEvent e) {
char ch = e.getKeyChar();
if (DEBUG) System.out.println("keyTyped "
+ hex((char)ch) + ", " + hex((char)e.getModifiers()));
if ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0) return;
int start, end;
switch (ch) {
case KeyEvent.CHAR_UNDEFINED:
break;
case KeyEvent.VK_BACK_SPACE:
//setKeyStart(-1);
if (!editable) break;
if (contents.length() == 0) break;
start = selection.getStart();
end = selection.getEnd();
if (start == end) {
--start;
if (start < 0) {
getToolkit().beep(); // LIU: Add audio feedback of NOP
return;
}
}
replaceRange("", start, end);
break;
case KeyEvent.VK_DELETE:
//setKeyStart(-1);
if (!editable) break;
if (contents.length() == 0) break;
start = selection.getStart();
end = selection.getEnd();
if (start == end) {
++end;
if (end > contents.length()) {
getToolkit().beep(); // LIU: Add audio feedback of NOP
return;
}
}
replaceRange("", start, end);
break;
default:
if (!editable) break;
// LIU: Dispatch to subclass API
handleKeyTyped(e);
break;
}
}
// LIU: Subclass API for handling of key typing
protected void handleKeyTyped(KeyEvent e) {
insertText(String.valueOf(e.getKeyChar()));
}
protected void setKeyStart(int keyStart) {
if (activeStart != keyStart) {
activeStart = keyStart;
repaint(10);
}
}
protected void validateKeyStart() {
if (activeStart > selection.getStart()) {
activeStart = selection.getStart();
repaint(10);
}
}
protected int getKeyStart() {
return activeStart;
}
// ===================== Control ======================
public synchronized void setEditable(boolean b) {
editable = b;
}
public boolean isEditable() {
return editable;
}
public void select(Selection newSelection) {
newSelection.pin(contents);
if (!selection.equals(newSelection)) {
selection.set(newSelection);
if (selectionListener != null) {
selectionListener.actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
"Selection Changed", 0));
}
repaint(10);
valid = false;
}
}
public void select(int start, int end) {
select(start, end, false);
}
public void select(int start, int end, boolean clickAfter) {
tempSelection.set(start, end, clickAfter);
select(tempSelection);
}
public int getSelectionStart() {
return selection.getStart();
}
public int getSelectionEnd() {
return selection.getEnd();
}
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x,y,w,h);
redoLines = true;
}
public Dimension getPreferredSize() {
return new Dimension(lastWidth,lastHeight);
}
public Dimension getMaximumSize() {
return new Dimension(lastWidth,lastHeight);
}
public Dimension getMinimumSize() {
return new Dimension(lastHeight,lastHeight);
}
public void setText(String text) {
setText2(text);
select(tempSelection.set(selection).pin(contents));
}
public void setText2(String text) {
contents = text;
charBreaker.setText(text);
wordBreaker.setText(text);
lineBreaker.setText(text);
redoLines = true;
if (textListener != null)
textListener.textValueChanged(
new TextEvent(this, TextEvent.TEXT_VALUE_CHANGED));
repaint(16);
}
public void insertText(String text) {
if (activeStart == -1) activeStart = selection.getStart();
replaceRange(text, selection.getStart(), selection.getEnd());
}
public void replaceRange(String s, int start, int end) {
setText2(contents.substring(0,start) + s
+ contents.substring(end));
select(tempSelection.set(selection).
fixAfterReplace(start, end, s.length()));
validateKeyStart();
}
public String getText() {
return contents;
}
public void setFont(Font font) {
super.setFont(font);
redoLines = true;
repaint(16);
}
// ================== Graphics ======================
public void update(Graphics g) {
if (DEBUG) System.out.println("update");
paint(g);
}
public void paint(Graphics g) {
mySize = getSize();
if (cacheImage == null
|| cacheImage.getHeight(this) != mySize.height
|| cacheImage.getWidth(this) != mySize.width) {
cacheImage = createImage(mySize.width, mySize.height);
valid = false;
}
if (!valid || redoLines) {
if (DEBUG) System.out.println("painting");
paint2(cacheImage.getGraphics());
valid = true;
}
//getToolkit().sync();
if (DEBUG) System.out.println("copying");
g.drawImage(cacheImage,
0, 0, mySize.width, mySize.height,
0, 0, mySize.width, mySize.height,
this);
}
public void paint2(Graphics g) {
g.clearRect(0, 0, mySize.width, mySize.height);
if (DEBUG) System.out.println("print");
if (focus) g.setColor(Color.black);
else g.setColor(Color.gray);
g.drawRect(0,0,mySize.width-1,mySize.height-1);
g.setClip(1,1,
mySize.width-2,mySize.height-2);
g.setColor(Color.black);
g.setFont(getFont());
fm = g.getFontMetrics();
lineAscent = fm.getAscent();
lineLeading = fm.getLeading();
lineHeight = lineAscent + fm.getDescent() + lineLeading;
int y = yInset + lineAscent;
String lastSubstring = "";
if (redoLines) fixLineStarts(mySize.width-xInset-xInset);
for (int i = 0; i < lineCount; y += lineHeight, ++i) {
// LIU: Don't display terminating ^M characters
int lim = lineStarts[i+1];
if (lim > 0 && contents.length() > 0 &&
contents.charAt(lim-1) == CR) --lim;
lastSubstring = contents.substring(lineStarts[i],lim);
g.drawString(lastSubstring, xInset, y);
}
drawSelection(g, lastSubstring);
lastHeight = y + yInset - lineHeight + yInset;
lastWidth = mySize.width-xInset-xInset;
}
void paintRect(Graphics g, int x, int y, int w, int h) {
if (focus) {
g.fillRect(x, y, w, h);
} else {
g.drawRect(x, y, w-1, h-1);
}
}
public void drawSelection(Graphics g, String lastSubstring) {
g.setXORMode(Color.black);
if (activeStart != -1) {
offset2Point(activeStart, false, activePoint);
g.setColor(Color.magenta);
int line = activePoint.x - 1;
g.fillRect(line, activePoint.y, 1, lineHeight);
}
if (selection.isCaret()) {
offset2Point(selection.caret, selection.clickAfter, caretPoint);
} else {
if (focus) g.setColor(Color.blue);
else g.setColor(Color.yellow);
offset2Point(selection.getStart(), true, startPoint);
offset2Point(selection.getEnd(), false, endPoint);
if (selection.getStart() == selection.caret)
caretPoint.setLocation(startPoint);
else caretPoint.setLocation(endPoint);
if (startPoint.y == endPoint.y) {
paintRect(g, startPoint.x, startPoint.y,
Math.max(1,endPoint.x-startPoint.x), lineHeight);
} else {
paintRect(g, startPoint.x, startPoint.y,
(mySize.width-xInset)-startPoint.x, lineHeight);
if (startPoint.y + lineHeight < endPoint.y)
paintRect(g, xInset, startPoint.y + lineHeight,
(mySize.width-xInset)-xInset, endPoint.y - startPoint.y - lineHeight);
paintRect(g, xInset, endPoint.y, endPoint.x-xInset, lineHeight);
}
}
if (focus || selection.isCaret()) {
if (focus) g.setColor(Color.green);
else g.setColor(Color.red);
int line = caretPoint.x - (selection.clickAfter ? 0 : 1);
g.fillRect(line, caretPoint.y, 1, lineHeight);
int w = lineHeight/12 + 1;
int braces = line - (selection.clickAfter ? -1 : w);
g.fillRect(braces, caretPoint.y, w, 1);
g.fillRect(braces, caretPoint.y + lineHeight - 1, w, 1);
}
}
public Point offset2Point(int off, boolean start, Point p) {
int line = findLine(off, start);
int width = 0;
try {
width = fm.stringWidth(
contents.substring(lineStarts[line], off));
} catch (Exception e) {
System.out.println(e);
}
p.x = width + xInset;
if (p.x > mySize.width - xInset)
p.x = mySize.width - xInset;
p.y = lineHeight * line + yInset;
return p;
}
private int findLine(int off, boolean start) {
// if it is start, then go to the next line!
if (start) ++off;
for (int i = 1; i < lineCount; ++i) {
// LIU: This was <= ; changed to < to make caret after
// final CR in line appear at START of next line.
if (off < lineStarts[i]) return i-1;
}
// LIU: Check for special case; after CR at end of the last line
if (off == lineStarts[lineCount] &&
off > 0 && contents.length() > 0 && contents.charAt(off-1) == CR) {
return lineCount;
}
return lineCount-1;
}
// offsets on any line will go from start,true to end,false
// excluding start,false and end,true
public Selection point2Offset(Point p, Selection o) {
if (p.y < yInset) {
o.caret = 0;
o.clickAfter = true;
return o;
}
int line = (p.y - yInset)/lineHeight;
if (line >= lineCount) {
o.caret = contents.length();
o.clickAfter = false;
return o;
}
int target = p.x - xInset;
if (target <= 0) {
o.caret = lineStarts[line];
o.clickAfter = true;
return o;
}
int lowGuess = lineStarts[line];
int lowWidth = 0;
int highGuess = lineStarts[line+1];
int highWidth = fm.stringWidth(contents.substring(lineStarts[line],highGuess));
if (target >= highWidth) {
o.caret = lineStarts[line+1];
o.clickAfter = false;
return o;
}
while (lowGuess < highGuess - 1) {
int guess = (lowGuess + highGuess)/2;
int width = fm.stringWidth(contents.substring(lineStarts[line],guess));
if (width <= target) {
lowGuess = guess;
lowWidth = width;
if (width == target) break;
} else {
highGuess = guess;
highWidth = width;
}
}
// at end, either lowWidth < target < width(low+1), or lowWidth = target
int highBound = charBreaker.following(lowGuess);
int lowBound = charBreaker.previous();
// we are now at character boundaries
if (lowBound != lowGuess)
lowWidth = fm.stringWidth(contents.substring(lineStarts[line],lowBound));
if (highBound != highGuess)
highWidth = fm.stringWidth(contents.substring(lineStarts[line],highBound));
// we now have the right widths
if (target - lowWidth < highWidth - target) {
o.caret = lowBound;
o.clickAfter = true;
} else {
o.caret = highBound;
o.clickAfter = false;
}
// we now have the closest!
return o;
}
private void fixLineStarts(int width) {
lineCount = 1;
lineStarts[0] = 0;
if (contents.length() == 0) {
lineStarts[1] = 0;
return;
}
int end = 0;
// LIU: Add check for MAX_LINES
for (int start = 0; start < contents.length() && lineCount < MAX_LINES;
start = end) {
end = nextLine(fm, start, width);
lineStarts[lineCount++] = end;
if (end == start) { // LIU: Assertion
throw new RuntimeException("nextLine broken");
}
}
--lineCount;
redoLines = false;
}
// LIU: Enhanced to wrap long lines. Bug with return of start fixed.
public int nextLine(FontMetrics fm, int start, int width) {
int len = contents.length();
for (int i = start; i < len; ++i) {
// check for line separator
char ch = (contents.charAt(i));
if (ch >= 0x000A && ch <= 0x000D || ch == 0x2028 || ch == 0x2029) {
len = i + 1;
if (ch == 0x000D && i+1 < len && contents.charAt(i+1) == 0x000A) // crlf
++len; // grab extra char
break;
}
}
String subject = contents.substring(start,len);
if (visibleWidth(fm, subject) <= width)
return len;
// LIU: Remainder of this method rewritten to accomodate lines
// longer than the component width by first trying to break
// into lines; then words; finally chars.
int n = findFittingBreak(fm, subject, width, lineBreaker);
if (n == 0) {
n = findFittingBreak(fm, subject, width, wordBreaker);
}
if (n == 0) {
n = findFittingBreak(fm, subject, width, charBreaker);
}
return n > 0 ? start + n : len;
}
/**
* LIU: Finds the longest substring that fits a given width
* composed of subunits returned by a BreakIterator. If the smallest
* subunit is too long, returns 0.
* @param fm metrics to use
* @param line the string to be fix into width
* @param width line.substring(0, result) must be <= width
* @param breaker the BreakIterator that will be used to find subunits
* @return maximum characters, at boundaries returned by breaker,
* that fit into width, or zero on failure
*/
private int findFittingBreak(FontMetrics fm, String line, int width,
BreakIterator breaker) {
breaker.setText(line);
int last = breaker.first();
int end = breaker.next();
while (end != BreakIterator.DONE &&
visibleWidth(fm, line.substring(0, end)) <= width) {
last = end;
end = breaker.next();
}
return last;
}
public int visibleWidth(FontMetrics fm, String s) {
int i;
for (i = s.length()-1; i >= 0; --i) {
char ch = s.charAt(i);
if (!(ch == ' ' || ch >= 0x000A && ch <= 0x000D || ch == 0x2028 || ch == 0x2029))
return fm.stringWidth(s.substring(0,i+1));;
}
return 0;
}
// =============== Utility ====================
private void fixHex() {
if (selection.getEnd() == 0) return;
int store = 0;
int places = 1;
int count = 0;
int min = Math.min(8,selection.getEnd());
for (int i = 0; i < min; ++i) {
char ch = contents.charAt(selection.getEnd()-1-i);
int value = Character.getNumericValue(ch);
if (value < 0 || value > 15) break;
store += places * value;
++count;
places *= 16;
}
String add = "";
int bottom = store & 0xFFFF;
if (store >= 0xD8000000 && store < 0xDC000000
&& bottom >= 0xDC00 && bottom < 0xE000) { // surrogates
add = "" + (char)(store >> 16) + (char)bottom;
} else if (store > 0xFFFF && store <= 0x10FFFF) {
store -= 0x10000;
add = "" + (char)(((store >> 10) & 0x3FF) + 0xD800)
+ (char)((store & 0x3FF) + 0xDC00);
} else if (count >= 4) {
count = 4;
add = ""+(char)(store & 0xFFFF);
} else {
count = 1;
char ch = contents.charAt(selection.getEnd()-1);
add = hex(ch);
if (ch >= 0xDC00 && ch <= 0xDFFF && selection.getEnd() > 1) {
ch = contents.charAt(selection.getEnd()-2);
if (ch >= 0xD800 && ch <= 0xDBFF) {
count = 2;
add = hex(ch) + add;
}
}
}
replaceRange(add, selection.getEnd()-count, selection.getEnd());
}
public static String hex(char ch) {
String result = Integer.toString(ch,16).toUpperCase();
result = "0000".substring(result.length(),4) + result;
return result;
}
}

View file

@ -0,0 +1,161 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.impl;
import java.text.*;
public final class Selection {
public int anchor;
public int caret;
public boolean clickAfter;
public int getStart() {
return anchor < caret ? anchor : caret;
}
public int getEnd() {
return anchor > caret ? anchor : caret;
}
public boolean isCaret() {
return anchor == caret;
}
public Selection set(Selection other) {
anchor = other.anchor;
caret = other.caret;
clickAfter = other.clickAfter;
return this;
}
public Selection set(int anchor, int caret, boolean clickAfter) {
this.anchor = anchor;
this.caret = caret;
this.clickAfter = clickAfter;
return this;
}
public boolean equals(Object other) {
Selection other2 = (Selection)other;
return anchor == other2.anchor
&& caret == other2.caret
&& clickAfter == other2.clickAfter;
}
public boolean isLessThan(Selection other) {
return getStart() < other.getEnd();
}
public Selection pin(String text) {
if (anchor > text.length()) {
anchor = text.length();
} else if (anchor < 0) {
anchor = 0;
}
if (caret > text.length()) {
caret = text.length();
clickAfter = true;
} else if (caret < 0) {
caret = 0;
clickAfter = false;
}
return this;
}
public Selection swap(Selection after) {
int temp = anchor;
anchor = after.anchor;
after.anchor = temp;
temp = caret;
caret = after.caret;
after.caret = temp;
boolean b = clickAfter;
clickAfter = after.clickAfter;
after.clickAfter = b;
return this;
}
public Selection fixAfterReplace(int start, int end, int len) {
if (anchor >= start) {
if (anchor < end) anchor = end;
anchor = start + len + anchor - end;
}
if (caret >= start) {
if (caret < end) caret = end;
caret = start + len + caret - end;
}
return this;
}
// Mac & Windows considerably different
// Mac: end++. If start!=end, start=end
// SHIFT: move end right
// CTL: no different
// Windows:
// UNSHIFTED: if start!=end, start = end, else start=end=end+1;
// anchor = tip = start
// SHIFT: tip++
// CTL: if start!=end, start = end = nextbound(end-1),
// else start=end=nextbound(end)
// anchor = tip = start
// CTL/SHIFT: tip = nextbound(tip)
public Selection nextBound(BreakIterator breaker,
int direction, boolean extend) {
if (!extend && anchor != caret) caret -= direction;
caret = next(caret, breaker, direction, true);
if (!extend) anchor = caret;
clickAfter = false;
return this;
}
// expand start and end to word breaks--if they are not already on one
public void expand(BreakIterator breaker) {
if (anchor <= caret) {
anchor = next(anchor,breaker,-1,false);
caret = next(caret,breaker,1,false);
/*
try {
breaker.following(anchor);
anchor = breaker.previous();
} catch (Exception e) {}
try {
caret = breaker.following(caret-1);
} catch (Exception e) {}
*/
} else {
anchor = next(anchor,breaker,1,false);
caret = next(caret,breaker,-1,false);
/*
try {
breaker.following(caret);
caret = breaker.previous();
} catch (Exception e) {}
try {
anchor = breaker.following(anchor-1);
} catch (Exception e) {}
*/
}
}
// different = false - move to next boundary, unless on one
// true - move to next boundary, even if on one
public static int next(int position, BreakIterator breaker,
int direction, boolean different) {
if (!different) position -= direction;
try {
if (direction > 0) {
position = breaker.following(position);
} else {
breaker.following(position-1);
position = breaker.previous();
}
} catch (Exception e) {}
return position;
}
}

View file

@ -0,0 +1,12 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000-2004, International Business Machines Corporation and
others. All Rights Reserved.
-->
</head>
<body bgcolor="white">
Shared utilities for demo applications and Applets.
</body>
</html>

View file

@ -0,0 +1,113 @@
/*
**********************************************************************
* Copyright (c) 2003, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Mark Davis
* Created: May 22 2003
* Since: ICU 2.6
**********************************************************************
*/
package com.ibm.icu.dev.demo.number;
import com.ibm.icu.util.Currency;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.DecimalFormat;
import com.ibm.icu.text.DecimalFormatSymbols;
import com.ibm.icu.impl.Utility;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
/**
* Demonstration code to illustrate how to obtain ICU 2.6-like currency
* behavior using pre-ICU 2.6 ICU4J.
* @author Mark Davis
*/
public class CurrencyDemo {
public static void main(String[] args) {
testFormatHack(true);
}
static NumberFormat getCurrencyFormat(Currency currency,
Locale displayLocale,
boolean ICU26) {
// code for ICU 2.6
if (ICU26) {
NumberFormat result = NumberFormat.getCurrencyInstance(displayLocale);
result.setCurrency(currency);
return result;
}
// ugly work-around for 2.4
DecimalFormat result = (DecimalFormat)NumberFormat.getCurrencyInstance(displayLocale);
HackCurrencyInfo hack = (HackCurrencyInfo)(hackData.get(currency.getCurrencyCode()));
result.setMinimumFractionDigits(hack.decimals);
result.setMaximumFractionDigits(hack.decimals);
result.setRoundingIncrement(hack.rounding);
DecimalFormatSymbols symbols = result.getDecimalFormatSymbols();
symbols.setCurrencySymbol(hack.symbol);
result.setDecimalFormatSymbols(symbols);
return result;
}
static Map hackData = new HashMap();
static class HackCurrencyInfo {
int decimals;
double rounding;
String symbol;
HackCurrencyInfo(int decimals, double rounding, String symbol) {
this.decimals = decimals;
this.rounding = rounding;
this.symbol = symbol;
}
}
static {
hackData.put("USD", new HackCurrencyInfo(2, 0, "$"));
hackData.put("GBP", new HackCurrencyInfo(2, 0, "\u00A3"));
hackData.put("JPY", new HackCurrencyInfo(0, 0, "\u00A5"));
hackData.put("EUR", new HackCurrencyInfo(2, 0, "\u20AC"));
}
/**
* Walk through all locales and compare the output of the ICU26
* currency format with the "hacked" currency format.
* @param quiet if true, only display discrepancies. Otherwise,
* display all results.
*/
static void testFormatHack(boolean quiet) {
String[] testCurrencies = {"USD","GBP","JPY","EUR"};
Locale[] testLocales = NumberFormat.getAvailableLocales();
for (int i = 0; i < testLocales.length; ++i) {
// since none of this should vary by country, we'll just do by language
if (!testLocales[i].getCountry().equals("")) continue;
boolean noOutput = true;
if (!quiet) {
System.out.println(testLocales[i].getDisplayName());
noOutput = false;
}
for (int j = 0; j < testCurrencies.length; ++j) {
NumberFormat nf26 = getCurrencyFormat(Currency.getInstance(testCurrencies[j]), testLocales[i], true);
String str26 = nf26.format(1234.567);
if (!quiet) {
System.out.print("\t" + Utility.escape(str26));
}
NumberFormat nf24 = getCurrencyFormat(Currency.getInstance(testCurrencies[j]), testLocales[i], false);
String str24 = nf24.format(1234.567);
if (!str24.equals(str26)) {
if (noOutput) {
System.out.println(testLocales[i].getDisplayName());
noOutput = false;
}
if (quiet) {
System.out.print("\t" + Utility.escape(str26));
}
System.out.print(" (" + Utility.escape(str24) + ")");
}
}
if (!noOutput) {
System.out.println();
}
}
}
}

View file

@ -0,0 +1,225 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.rbbi;
import java.util.ListResourceBundle;
import com.ibm.icu.impl.ICUData;
/**
* This resource bundle is included for testing and demonstration purposes only.
* It applies the dictionary-based algorithm to English text that has had all the
* spaces removed. Once we have good test cases for Thai, we will replace this
* with good resource data (and a good dictionary file) for Thai
*/
public class BreakIteratorRules_en_US_DEMO extends ListResourceBundle {
private static final String DATA_NAME = "/com/ibm/data/misc/english.dict";
public Object[][] getContents() {
final boolean exists = ICUData.exists(DATA_NAME);
if (!exists) {
return new Object[0][0];
}
return new Object[][] {
// names of classes to instantiate for the different kinds of break
// iterator. Notice we're now using DictionaryBasedBreakIterator
// for word and line breaking.
{ "BreakIteratorClasses",
new String[] {
"RuleBasedBreakIterator",
// character-break iterator class
"DictionaryBasedBreakIterator",
// word-break iterator class
"DictionaryBasedBreakIterator",
// line-break iterator class
"RuleBasedBreakIterator" } // sentence-break iterator class
},
// These are the same word-breaking rules as are specified in the default
// resource, except that the Latin letters, apostrophe, and hyphen are
// specified as dictionary characters
{
"WordBreakRules",
// ignore non-spacing marks, enclosing marks, and format characters,
// all of which should not influence the algorithm
"$_ignore_=[[:Mn:][:Me:][:Cf:]];"
// lower and upper case Roman letters, apostrophy and dash are
// in the English dictionary
+"$_dictionary_=[a-zA-Z\\'\\-];"
// Hindi phrase separator, kanji, katakana, hiragana, CJK diacriticals,
// other letters, and digits
+"$danda=[\u0964\u0965];"
+ "$kanji=[\u3005\u4e00-\u9fa5\uf900-\ufa2d];"
+ "$kata=[\u3099-\u309c\u30a1-\u30fe];"
+ "$hira=[\u3041-\u309e\u30fc];"
+ "$let=[[[:L:][:Mc:]]-[$kanji$kata$hira]];"
+ "$dgt=[:N:];"
// punctuation that can occur in the middle of a word: currently
// dashes, apostrophes, and quotation marks
+"$mid_word=[[:Pd:]\u00ad\u2027\\\"\\\'];"
// punctuation that can occur in the middle of a number: currently
// apostrophes, qoutation marks, periods, commas, and the Arabic
// decimal point
+"$mid_num=[\\\"\\\'\\,\u066b\\.];"
// punctuation that can occur at the beginning of a number: currently
// the period, the number sign, and all currency symbols except the cents sign
+"$pre_num=[[[:Sc:]-[\u00a2]]\\#\\.];"
// punctuation that can occur at the end of a number: currently
// the percent, per-thousand, per-ten-thousand, and Arabic percent
// signs, the cents sign, and the ampersand
+"$post_num=[\\%\\&\u00a2\u066a\u2030\u2031];"
// line separators: currently LF, FF, PS, and LS
+"$ls=[\n\u000c\u2028\u2029];"
// whitespace: all space separators and the tab character
+"$ws=[[:Zs:]\t];"
// a word is a sequence of letters that may contain internal
// punctuation, as long as it begins and ends with a letter and
// never contains two punctuation marks in a row
+"$word=($let+($mid_word$let+)*$danda?);"
// a number is a sequence of digits that may contain internal
// punctuation, as long as it begins and ends with a digit and
// never contains two punctuation marks in a row.
+"$number=($dgt+($mid_num$dgt+)*);"
// break after every character, with the following exceptions
// (this will cause punctuation marks that aren't considered
// part of words or numbers to be treated as words unto themselves)
+".;"
// keep together any sequence of contiguous words and numbers
// (including just one of either), plus an optional trailing
// number-suffix character
+"$word?($number$word)*($number$post_num?)?;"
// keep together and sequence of contiguous words and numbers
// that starts with a number-prefix character and a number,
// and may end with a number-suffix character
+"$pre_num($number$word)*($number$post_num?)?;"
// keep together runs of whitespace (optionally with a single trailing
// line separator or CRLF sequence)
+"$ws*\r?$ls?;"
// keep together runs of Katakana
+"$kata*;"
// keep together runs of Hiragana
+"$hira*;"
// keep together runs of Kanji
+"$kanji*;" },
// These are the same line-breaking rules as are specified in the default
// resource, except that the Latin letters, apostrophe, and hyphen are
// specified as dictionary characters
{ "LineBreakRules",
// ignore non-spacing marks, enclosing marks, and format characters
"$_ignore_=[[:Mn:][:Me:][:Cf:]];"
// lower and upper case Roman letters, apostrophy and dash
// are in the English dictionary
+"$_dictionary_=[a-zA-Z\\'\\-];"
// Hindi phrase separators
+"$danda=[\u0964\u0965];"
// characters that always cause a break: ETX, tab, LF, FF, LS, and PS
+"$break=[\u0003\t\n\f\u2028\u2029];"
// characters that always prevent a break: the non-breaking space
// and similar characters
+"$nbsp=[\u00a0\u2007\u2011\ufeff];"
// whitespace: space separators and control characters, except for
// CR and the other characters mentioned above
+"$space=[[[:Zs:][:Cc:]]-[$nbsp$break\r]];"
// dashes: dash punctuation and the discretionary hyphen, except for
// non-breaking hyphens
+"$dash=[[[:Pd:]\u00ad]-[$nbsp]];"
// characters that stick to a word if they precede it: currency symbols
// (except the cents sign) and starting punctuation
+"$pre_word=[[[:Sc:]-[\u00a2]][:Ps:]\\\"\\\'];"
// characters that stick to a word if they follow it: ending punctuation,
// other punctuation that usually occurs at the end of a sentence,
// small Kana characters, some CJK diacritics, etc.
+"$post_word=[[:Pe:]\\!\\\"\\\'\\%\\.\\,\\:\\;\\?\u00a2\u00b0\u066a\u2030-\u2034"
+ "\u2103\u2105\u2109\u3001\u3002\u3005\u3041\u3043\u3045\u3047\u3049\u3063"
+ "\u3083\u3085\u3087\u308e\u3099-\u309e\u30a1\u30a3\u30a5\u30a7\u30a9"
+ "\u30c3\u30e3\u30e5\u30e7\u30ee\u30f5\u30f6\u30fc-\u30fe\uff01\uff0c"
+ "\uff0e\uff1f];"
// Kanji: actually includes both Kanji and Kana, except for small Kana and
// CJK diacritics
+"$kanji=[[\u4e00-\u9fa5\uf900-\ufa2d\u3041-\u3094\u30a1-\u30fa]-[$post_word$_ignore_]];"
// digits
+"$digit=[[:Nd:][:No:]];"
// punctuation that can occur in the middle of a number: periods and commas
+"$mid_num=[\\.\\,];"
// everything not mentioned above, plus the quote marks (which are both
// <pre-word>, <post-word>, and <char>)
+"$char=[^$break$space$dash$kanji$nbsp$_ignore_$pre_word$post_word$mid_num$danda\r\\\"\\\'];"
// a "number" is a run of prefix characters and dashes, followed by one or
// more digits with isolated number-punctuation characters interspersed
+"$number=([$pre_word$dash]*$digit+($mid_num$digit+)*);"
// the basic core of a word can be either a "number" as defined above, a single
// "Kanji" character, or a run of any number of not-explicitly-mentioned
// characters (this includes Latin letters)
+"$word_core=([$pre_word$char]*|$kanji|$number);"
// a word may end with an optional suffix that be either a run of one or
// more dashes or a run of word-suffix characters, followed by an optional
// run of whitespace
+"$word_suffix=(($dash+|$post_word*)$space*);"
// a word, thus, is an optional run of word-prefix characters, followed by
// a word core and a word suffix (the syntax of <word-core> and <word-suffix>
// actually allows either of them to match the empty string, putting a break
// between things like ")(" or "aaa(aaa"
+"$word=($pre_word*$word_core$word_suffix);"
// finally, the rule that does the work: Keep together any run of words that
// are joined by runs of one of more non-spacing mark. Also keep a trailing
// line-break character or CRLF combination with the word. (line separators
// "win" over nbsp's)
+"$word($nbsp+$word)*\r?$break?;" },
// these two resources specify the pathnames of the dictionary files to
// use for word breaking and line breaking. Both currently refer to
// a file called english.dict placed in com.ibm.icu.impl.data
// somewhere in the class path. It's important to note that
// english.dict was created for testing purposes only, and doesn't
// come anywhere close to being an exhaustive dictionary of English
// words (basically, it contains all the words in the Declaration of
// Independence, and the Revised Standard Version of the book of Genesis,
// plus a few other words thrown in to show more interesting cases).
// { "WordBreakDictionary", "com\\ibm\\text\\resources\\english.dict" },
// { "LineBreakDictionary", "com\\ibm\\text\\resources\\english.dict" }
{ "WordBreakDictionary", DATA_NAME },
{ "LineBreakDictionary", DATA_NAME }
};
}
}

View file

@ -0,0 +1,492 @@
/*
*******************************************************************************
* Copyright (C) 1996-2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.rbbi;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
import java.util.*;
import com.ibm.icu.dev.demo.impl.*;
import com.ibm.icu.text.BreakIterator;
public class DBBIDemo extends DemoApplet
{
public static void main(String argv[]) {
Locale.setDefault(new Locale("en", "US", "DEMO"));
new DBBIDemo().showDemo();
}
public Frame createDemoFrame(DemoApplet applet) {
return new DBBIFrame(applet);
}
}
class DBBIFrame extends Frame implements ItemListener
{
private static final String creditString =
"v1.1a9, Demo";
private static final int FIELD_COLUMNS = 45;
private static final Font choiceFont = null;
private static final boolean DEBUG = false;
private DemoApplet applet;
final String right = "-->";
final String left = "<--";
private BreakIterator iter;
private static boolean isctrldown_ = false;
JTextArea text;
// TextArea text;
Choice bound;
public DBBIFrame(DemoApplet applet)
{
this.applet = applet;
init();
start();
}
public void run()
{
/*
while (true) {
try {
checkChange();
Thread.sleep(250);
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
catch (Throwable e) {
}
}
*/
}
int s, e;
int ts, te;
public void checkChange()
{
// System.out.println("checkChange...");
if ((text.getSelectionStart() & 0x7FFF) != ts ||
(text.getSelectionEnd() & 0x7FFF) != te) {
// not used int tempS = text.getSelectionStart() & 0x7FFF;
// not used int tempE = text.getSelectionEnd() & 0x7FFF;
// System.out.println(">");
// select(0, 0);
// select(tempS, tempE);
//select(tempS - (ts - s), tempE - (te - e));
// System.out.println("<");
// if (s != ts || e != te) System.out.println(" s("+s+") ts("+ts+") e("+e+") te("+te+")");
// if (tempS != ts || tempE != te) System.out.println(">s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// select(s - (ts - s), e - (te - e));
// if (tempS != ts || tempE != te) System.out.println("s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// System.out.println("lkdslksj");
}
}
public void select(int sIn, int eIn)
{
s = sIn;
e = eIn;
text.select(s, e);
ts = text.getSelectionStart() & 0x7FFF;
te = text.getSelectionEnd() & 0x7FFF;
// if (s != ts || e != te) {
// System.out.println(">s("+s+") ts("+ts+") e("+e+") te("+te+")");
// System.out.println(" "+(ts-s)+","+(te-e));
// }
}
public int getSelectionStart()
{
checkChange();
// return s;
return text.getSelectionStart() & 0x7FFF;
}
public int getSelectionEnd()
{
checkChange();
// return e;
return text.getSelectionEnd() & 0x7FFF;
}
public final synchronized void selectRange(int s, int e)
{
try {
//if (getSelectionStart() != s || getSelectionEnd() != e) {
//text.select(s, e);
select(s,e);
//}
// if (getSelectionStart() != s || getSelectionEnd() != e) {
// System.out.println("AGH! select("+s+","+e+") -> ("+
// getSelectionStart()+","+getSelectionEnd()+")");
// text.select(s - (getSelectionStart() - s), e - (getSelectionEnd() - e));
// }
} catch (Exception exp) {
errorText(exp.toString());
}
}
public void init()
{
buildGUI();
}
public void start()
{
}
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout());
Panel topPanel = new Panel();
Label titleLabel =
new Label("Text Boundary Demo", Label.CENTER);
titleLabel.setFont(DemoUtility.titleFont);
topPanel.add(titleLabel);
//Label demo=new Label(creditString, Label.CENTER);
//demo.setFont(DemoUtility.creditFont);
//topPanel.add(demo);
Panel choicePanel = new Panel();
Label demo1=new Label("Boundaries", Label.LEFT);
demo1.setFont(DemoUtility.labelFont);
choicePanel.add(demo1);
bound = new Choice();
bound.setBackground(DemoUtility.choiceColor);
bound.addItem("Sentence");
bound.addItem("Line Break");
bound.addItem("Word");
bound.addItem("Char");
bound.addItemListener(this);
if (choiceFont != null)
bound.setFont(choiceFont);
choicePanel.add(bound);
topPanel.add(choicePanel);
DemoUtility.fixGrid(topPanel,1);
add("North", topPanel);
int ROWS = 15;
int COLUMNS = 50;
// text = new TextArea(getInitialText(), ROWS, COLUMNS);
text = new JTextArea(getInitialText(), ROWS, COLUMNS);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setEditable(true);
text.selectAll();
text.setFont(DemoUtility.editFont);
text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
add("Center", new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
Panel copyrightPanel = new Panel();
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright1, Label.LEFT),DemoUtility.creditFont);
DemoUtility.fixGrid(copyrightPanel,1);
add("South", copyrightPanel);
//layout();
handleEnumChanged();
enableEvents(WindowEvent.WINDOW_CLOSING);
enableEvents(KeyEvent.KEY_PRESSED);
enableEvents(KeyEvent.KEY_RELEASED);
text.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.isControlDown()) {
int kc = e.getKeyCode();
switch (e.getKeyCode()) {
case KeyEvent.VK_N:
case KeyEvent.VK_RIGHT:
handleForward();
break;
case KeyEvent.VK_P:
case KeyEvent.VK_LEFT:
handleBackward();
break;
default:
break;
}
e.consume();
}
}
public void keyReleased(KeyEvent e) {
if (e.isControlDown()) {
e.consume();
}
}
public void keyTyped(KeyEvent e) {
if (e.isControlDown()) {
e.consume();
}
}
});
// (new Thread(this)).start();
}
public String getInitialText()
{
return
"When,inthecourseofhumanevents,itbecomesnecessaryforonepeopletodissolvethepoliticalbondswhichhave"
+ "connectedthemwithanother,andtoassumeamongthepowersoftheearth,theseparateandequalstationtowhichthelaws"
+ "ofnatureandofnature'sGodentitlethem,adecentrespecttotheopinionsofmankindrequiresthattheyshoulddeclarethe"
+ "causeswhichimpelthemtotheseparation.\n"
+ "Weholdthesetruthstobeself-evident,thatallmenarecreatedequal,thattheyareendowedbytheirCreatorwithcertain"
+ "unalienablerights,thatamongthesearelife,libertyandthepursuitofhappiness.Thattosecuretheserights,governmentsare"
+ "institutedamongmen,derivingtheirjustpowersfromtheconsentofthegoverned.Thatwheneveranyformofgovernment"
+ "becomesdestructivetotheseends,itistherightofthepeopletoalterortoabolishit,andtoinstitutenewgovernment,laying"
+ "itsfoundationonsuchprinciplesandorganizingitspowersinsuchform,astothemshallseemmostlikelytoeffecttheirsafety"
+ "andhappiness.Prudence,indeed,willdictatethatgovernmentslongestablishedshouldnotbechangedforlightandtransient"
+ "causes;andaccordinglyallexperiencehathshownthatmankindaremoredisposedtosuffer,whileevilsaresufferable,than"
+ "torightthemselvesbyabolishingtheformstowhichtheyareaccustomed.Butwhenalongtrainofabusesandusurpations,"
+ "pursuinginvariablythesameobjectevincesadesigntoreducethemunderabsolutedespotism,itistheirright,itistheirduty,"
+ "tothrowoffsuchgovernment,andtoprovidenewguardsfortheirfuturesecurity.--Suchhasbeenthepatientsufferanceof"
+ "thesecolonies;andsuchisnowthenecessitywhichconstrainsthemtoaltertheirformersystemsofgovernment.Thehistory"
+ "ofthepresentKingofGreatBritainisahistoryofrepeatedinjuriesandusurpations,allhavingindirectobjectthe"
+ "establishmentofanabsolutetyrannyoverthesestates.Toprovethis,letfactsbesubmittedtoacandidworld.\n"
+ "Hehasrefusedhisassenttolaws,themostwholesomeandnecessaryforthepublicgood.\n"
+ "Hehasforbiddenhisgovernorstopasslawsofimmediateandpressingimportance,unlesssuspendedintheiroperationtill"
+ "hisassentshouldbeobtained;andwhensosuspended,hehasutterlyneglectedtoattendtothem.\n"
+ "Hehasrefusedtopassotherlawsfortheaccommodationoflargedistrictsofpeople,unlessthosepeoplewouldrelinquish"
+ "therightofrepresentationinthelegislature,arightinestimabletothemandformidabletotyrantsonly.\n"
+ "Hehascalledtogetherlegislativebodiesatplacesunusual,uncomfortable,anddistantfromthedepositoryoftheirpublic"
+ "records,forthesolepurposeoffatiguingthemintocompliancewithhismeasures.\n"
+ "Hehasdissolvedrepresentativehousesrepeatedly,foropposingwithmanlyfirmnesshisinvasionsontherightsofthepeople.\n"
+ "Hehasrefusedforalongtime,aftersuchdissolutions,tocauseotherstobeelected;wherebythelegislativepowers,"
+ "incapableofannihilation,havereturnedtothepeopleatlargefortheirexercise;thestateremaininginthemeantimeexposed"
+ "toallthedangersofinvasionfromwithout,andconvulsionswithin.\n"
+ "Hehasendeavoredtopreventthepopulationofthesestates;forthatpurposeobstructingthelawsfornaturalizationof"
+ "foreigners;refusingtopassotherstoencouragetheirmigrationhither,andraisingtheconditionsofnewappropriationsof"
+ "lands.\n"
+ "Hehasobstructedtheadministrationofjustice,byrefusinghisassenttolawsforestablishingjudiciarypowers.\n"
+ "Hehasmadejudgesdependentonhiswillalone,forthetenureoftheiroffices,andtheamountandpaymentoftheirsalaries.\n"
+ "Hehaserectedamultitudeofnewoffices,andsenthitherswarmsofofficerstoharassourpeople,andeatouttheir"
+ "substance.\n"
+ "Hehaskeptamongus,intimesofpeace,standingarmieswithouttheconsentofourlegislature.\n"
+ "Hehasaffectedtorenderthemilitaryindependentofandsuperiortocivilpower.\n"
+ "Hehascombinedwithotherstosubjectustoajurisdictionforeigntoourconstitution,andunacknowledgedbyourlaws;"
+ "givinghisassenttotheiractsofpretendedlegislation:\n"
+ "Forquarteringlargebodiesofarmedtroopsamongus:\n"
+ "Forprotectingthem,bymocktrial,frompunishmentforanymurderswhichtheyshouldcommitontheinhabitantsofthese"
+ "states:\n"
+ "Forcuttingoffourtradewithallpartsoftheworld:\n"
+ "Forimposingtaxesonuswithoutourconsent:\n"
+ "Fordeprivingusinmanycases,ofthebenefitsoftrialbyjury:\n"
+ "Fortransportingusbeyondseastobetriedforpretendedoffenses:\n"
+ "ForabolishingthefreesystemofEnglishlawsinaneighboringprovince,establishingthereinanarbitrarygovernment,and"
+ "enlargingitsboundariessoastorenderitatonceanexampleandfitinstrumentforintroducingthesameabsoluteruleinthese"
+ "colonies:\n"
+ "Fortakingawayourcharters,abolishingourmostvaluablelaws,andalteringfundamentallytheformsofourgovernments:\n"
+ "Forsuspendingourownlegislatures,anddeclaringthemselvesinvestedwithpowertolegislateforusinallcaseswhatsoever.\n"
+ "Hehasabdicatedgovernmenthere,bydeclaringusoutofhisprotectionandwagingwaragainstus.\n"
+ "Hehasplunderedourseas,ravagedourcoasts,burnedourtowns,anddestroyedthelivesofourpeople.\n"
+ "Heisatthistimetransportinglargearmiesofforeignmercenariestocompletetheworksofdeath,desolationandtyranny,"
+ "alreadybegunwithcircumstancesofcrueltyandperfidyscarcelyparalleledinthemostbarbarousages,andtotallyunworthy"
+ "theheadofacivilizednation.\n"
+ "Hehasconstrainedourfellowcitizenstakencaptiveonthehighseastobeararmsagainsttheircountry,tobecomethe"
+ "executionersoftheirfriendsandbrethren,ortofallthemselvesbytheirhands.\n"
+ "Hehasexciteddomesticinsurrectionsamongstus,andhasendeavoredtobringontheinhabitantsofourfrontiers,the"
+ "mercilessIndiansavages,whoseknownruleofwarfare,isundistinguisheddestructionofallages,sexesandconditions.\n"
+ "Ineverystageoftheseoppressionswehavepetitionedforredressinthemosthumbleterms:ourrepeatedpetitionshave"
+ "beenansweredonlybyrepeatedinjury.Aprince,whosecharacteristhusmarkedbyeveryactwhichmaydefineatyrant,is"
+ "unfittobetherulerofafreepeople.\n"
+ "NorhavewebeenwantinginattentiontoourBritishbrethren.Wehavewarnedthemfromtimetotimeofattemptsbytheir"
+ "legislaturetoextendanunwarrantablejurisdictionoverus.Wehaveremindedthemofthecircumstancesofouremigration"
+ "andsettlementhere.Wehaveappealedtotheirnativejusticeandmagnanimity,andwehaveconjuredthembythetiesofour"
+ "commonkindredtodisavowtheseusurpations,which,wouldinevitablyinterruptourconnectionsandcorrespondence.We"
+ "must,therefore,acquiesceinthenecessity,whichdenouncesourseparation,andholdthem,asweholdtherestofmankind,"
+ "enemiesinwar,inpeacefriends.\n"
+ "We,therefore,therepresentativesoftheUnitedStatesofAmerica,inGeneralCongress,assembled,appealingtothe"
+ "SupremeJudgeoftheworldfortherectitudeofourintentions,do,inthename,andbytheauthorityofthegoodpeopleof"
+ "thesecolonies,solemnlypublishanddeclare,thattheseunitedcoloniesare,andofrightoughttobefreeandindependent"
+ "states;thattheyareabsolvedfromallallegiancetotheBritishCrown,andthatallpoliticalconnectionbetweenthemandthe"
+ "stateofGreatBritain,isandoughttobetotallydissolved;andthatasfreeandindependentstates,theyhavefullpowerto"
+ "leveywar,concludepeace,contractalliances,establishcommerce,andtodoallotheractsandthingswhichindependent"
+ "statesmayofrightdo.Andforthesupportofthisdeclaration,withafirmrelianceontheprotectionofDivineProvidence,we"
+ "mutuallypledgetoeachotherourlives,ourfortunesandoursacredhonor.\n";
}
public void handleEnumChanged()
{
String s = bound.getSelectedItem();
if (s.equals("Char")) {
errorText("getCharacterInstance");
iter = BreakIterator.getCharacterInstance();
}
else if (s.equals("Word")) {
errorText("getWordInstance");
iter = BreakIterator.getWordInstance();
}
else if (s.equals("Line Break")) {
errorText("getLineInstance");
iter = BreakIterator.getLineInstance();
}
else /* if (s.equals("Sentence")) */ {
errorText("getSentenceInstance");
iter = BreakIterator.getSentenceInstance();
}
iter.setText(text.getText());
selectRange(0, 0);
//text.select(0,0);
}
public void handleForward()
{
try {
// System.out.println("entering handleForward");
iter.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
// System.out.println("handleForward: oldStart=" + oldStart + ", oldEnd=" + oldEnd);
if (oldEnd < 1) {
selectRange(0, iter.following(0));
}
else {
int s = iter.following(oldEnd-1);
int e = iter.next();
if (e == -1) {
e = s;
}
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" +
s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void handleBackward()
{
try {
iter.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
if (oldStart < 1) {
selectRange(0, 0);
}
else {
int e = iter.following(oldStart-1);
int s = iter.previous();
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" + s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void itemStateChanged(ItemEvent evt)
{
if (evt.getSource() instanceof Choice) {
handleEnumChanged();
}
}
public void errorText(String s)
{
if (DEBUG)
System.out.println(s);
}
protected void processWindowEvent(WindowEvent evt)
{
if (evt.getID() == WindowEvent.WINDOW_CLOSING &&
evt.getWindow() == this) {
hide();
dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
}
protected void processKeyEvent(KeyEvent evt)
{
switch (evt.getID()) {
case KeyEvent.KEY_PRESSED :
if (evt.getKeyCode() == KeyEvent.VK_CONTROL) {
isctrldown_ = true;
}
break;
case KeyEvent.KEY_RELEASED :
// key detection for left and right buttons are removed
// to emulate the old release behaviour
int key = evt.getKeyCode();
if (key == KeyEvent.VK_N && isctrldown_) {
handleForward();
}
else
if (key == KeyEvent.VK_P && isctrldown_) {
handleBackward();
}
else
if (key == KeyEvent.VK_CONTROL) {
isctrldown_ = false;
}
break;
}
}
}

View file

@ -0,0 +1,476 @@
/*
*******************************************************************************
* Copyright (C) 1996-2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.rbbi;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
import java.util.*;
import com.ibm.icu.dev.demo.impl.*;
import com.ibm.icu.text.BreakIterator;
public class RBBIDemo extends DemoApplet
{
public static void main(String argv[]) {
Locale.setDefault(new Locale("en", "US"));
new RBBIDemo().showDemo();
}
public Frame createDemoFrame(DemoApplet applet) {
return new RBBIFrame(applet);
}
}
class RBBIFrame extends Frame implements ItemListener
{
private static final String creditString =
"v1.1a9, Demo";
private static final int FIELD_COLUMNS = 45;
private static final Font choiceFont = null;
private static final boolean DEBUG = false;
private DemoApplet applet;
final String right = "-->";
final String left = "<--";
private BreakIterator iter;
private boolean isctrldown_ = false;
JTextArea text;
// TextArea text;
Choice bound;
public RBBIFrame(DemoApplet applet)
{
this.applet = applet;
init();
start();
}
public void run()
{
/*
while (true) {
try {
checkChange();
Thread.sleep(250);
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
catch (Throwable e) {
}
}
*/
}
int s, e;
int ts, te;
public void checkChange()
{
// System.out.println("checkChange...");
if ((text.getSelectionStart() & 0x7FFF) != ts ||
(text.getSelectionEnd() & 0x7FFF) != te) {
// not used int tempS = text.getSelectionStart() & 0x7FFF;
// not used int tempE = text.getSelectionEnd() & 0x7FFF;
// System.out.println(">");
// select(0, 0);
// select(tempS, tempE);
//select(tempS - (ts - s), tempE - (te - e));
// System.out.println("<");
// if (s != ts || e != te) System.out.println(" s("+s+") ts("+ts+") e("+e+") te("+te+")");
// if (tempS != ts || tempE != te) System.out.println(">s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// select(s - (ts - s), e - (te - e));
// if (tempS != ts || tempE != te) System.out.println("s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// System.out.println("lkdslksj");
}
}
public void select(int sIn, int eIn)
{
s = sIn;
e = eIn;
text.select(s, e);
ts = text.getSelectionStart() & 0x7FFF;
te = text.getSelectionEnd() & 0x7FFF;
// if (s != ts || e != te) {
// System.out.println(">s("+s+") ts("+ts+") e("+e+") te("+te+")");
// System.out.println(" "+(ts-s)+","+(te-e));
// }
}
public int getSelectionStart()
{
checkChange();
// return s;
return text.getSelectionStart() & 0x7FFF;
}
public int getSelectionEnd()
{
checkChange();
// return e;
return text.getSelectionEnd() & 0x7FFF;
}
public final synchronized void selectRange(int s, int e)
{
try {
//if (getSelectionStart() != s || getSelectionEnd() != e) {
//text.select(s, e);
select(s,e);
//}
// if (getSelectionStart() != s || getSelectionEnd() != e) {
// System.out.println("AGH! select("+s+","+e+") -> ("+
// getSelectionStart()+","+getSelectionEnd()+")");
// text.select(s - (getSelectionStart() - s), e - (getSelectionEnd() - e));
// }
} catch (Exception exp) {
errorText(exp.toString());
}
}
public void init()
{
buildGUI();
}
public void start()
{
}
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout());
Panel topPanel = new Panel();
Label titleLabel =
new Label("Deva Text Boundary Demo", Label.CENTER);
titleLabel.setFont(DemoUtility.titleFont);
topPanel.add(titleLabel);
//Label demo=new Label(creditString, Label.CENTER);
//demo.setFont(DemoUtility.creditFont);
//topPanel.add(demo);
Panel choicePanel = new Panel();
Label demo1=new Label("Boundaries", Label.LEFT);
demo1.setFont(DemoUtility.labelFont);
choicePanel.add(demo1);
bound = new Choice();
bound.setBackground(DemoUtility.choiceColor);
bound.addItem("Sentence");
bound.addItem("Line Break");
bound.addItem("Word");
bound.addItem("Char");
bound.addItemListener(this);
if (choiceFont != null)
bound.setFont(choiceFont);
choicePanel.add(bound);
topPanel.add(choicePanel);
DemoUtility.fixGrid(topPanel,1);
add("North", topPanel);
int ROWS = 15;
int COLUMNS = 50;
// text = new TextArea(getInitialText(), ROWS, COLUMNS);
text = new JTextArea(getInitialText(), ROWS, COLUMNS);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setEditable(true);
text.selectAll();
text.setFont(new Font("Devanagari MT for IBM", Font.PLAIN, 48));
text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
add("Center", new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
Panel copyrightPanel = new Panel();
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright1, Label.LEFT),DemoUtility.creditFont);
DemoUtility.fixGrid(copyrightPanel,1);
add("South", copyrightPanel);
//layout();
handleEnumChanged();
enableEvents(WindowEvent.WINDOW_CLOSING);
enableEvents(KeyEvent.KEY_PRESSED);
enableEvents(KeyEvent.KEY_RELEASED);
text.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.isControlDown()) {
int kc = e.getKeyCode();
switch (e.getKeyCode()) {
case KeyEvent.VK_N:
case KeyEvent.VK_RIGHT:
handleForward();
break;
case KeyEvent.VK_P:
case KeyEvent.VK_LEFT:
handleBackward();
break;
default:
break;
}
e.consume();
}
}
public void keyReleased(KeyEvent e) {
if (e.isControlDown()) {
e.consume();
}
}
public void keyTyped(KeyEvent e) {
if (e.isControlDown()) {
e.consume();
}
}
});
// (new Thread(this)).start();
}
public String getInitialText()
{
return
"\u0936\u094d\u0930\u0940\u092e\u0926\u094d " +
"\u092d\u0917\u0935\u0926\u094d\u0917\u0940\u0924\u093e " +
"\u0905\u0927\u094d\u092f\u093e\u092f " +
"\u0905\u0930\u094d\u091c\u0941\u0928 " +
"\u0935\u093f\u0937\u093e\u0926 " +
"\u092f\u094b\u0917 " +
"\u0927\u0943\u0924\u0930\u093e\u0937\u094d\u091f\u094d\u0930 " +
"\u0909\u0935\u093E\u091A\u0964 " +
"\u0927\u0930\u094d\u092e\u0915\u094d\u0937\u0947\u0924\u094d\u0930\u0947 " +
"\u0915\u0941\u0930\u0941\u0915\u094d\u0937\u0947\u0924\u094d\u0930\u0947 " +
"\u0938\u092e\u0935\u0947\u0924\u093e " +
"\u092f\u0941\u092f\u0941\u0924\u094d\u0938\u0935\u0903 " +
"\u092e\u093e\u092e\u0915\u093e\u0903 " +
"\u092a\u093e\u0923\u094d\u0921\u0935\u093e\u0936\u094d\u091a\u0948\u0935 " +
"\u0915\u093f\u092e\u0915\u0941\u0930\u094d\u0935\u0924 " +
"\u0938\u0902\u091c\u092F";
}
public void handleEnumChanged()
{
String s = bound.getSelectedItem();
if (s.equals("Char")) {
errorText("getCharacterInstance");
iter = BreakIterator.getCharacterInstance();
}
else if (s.equals("Word")) {
errorText("tWordBreak");
iter = BreakIterator.getWordInstance();
}
else if (s.equals("Line Break")) {
errorText("getLineInstance");
iter = BreakIterator.getLineInstance();
}
else /* if (s.equals("Sentence")) */ {
errorText("getSentenceInstance");
iter = BreakIterator.getSentenceInstance();
}
iter.setText(text.getText());
selectRange(0, 0);
//text.select(0,0);
}
public void handleForward()
{
try {
// System.out.println("entering handleForward");
iter.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
// System.out.println("handleForward: oldStart=" + oldStart + ", oldEnd=" + oldEnd);
if (oldEnd < 1) {
selectRange(0, iter.following(0));
}
else {
int s = iter.following(oldEnd-1);
int e = iter.next();
if (e == -1) {
e = s;
}
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" +
s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void handleBackward()
{
try {
iter.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
if (oldStart < 1) {
selectRange(0, 0);
}
else {
int e = iter.following(oldStart-1);
int s = iter.previous();
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" + s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
/*
public boolean action(Event evt, Object obj)
{
if(evt.target instanceof Button && left.equals(obj))
{
handleBackward();
return true;
}
else if(evt.target instanceof Button && right.equals(obj))
{
handleForward();
return true;
}
else if(evt.target instanceof Choice)
{
handleEnumChanged();
return true;
}
return false;
}
public boolean handleEvent(Event evt)
{
if (evt.id == Event.KEY_PRESS || evt.id == Event.KEY_ACTION) {
if (evt.key == Event.RIGHT || (evt.key == 0x0E && evt.controlDown())) {
handleForward();
return true;
}
else if (evt.key == Event.LEFT || (evt.key == 0x10 && evt.controlDown())) {
handleBackward();
return true;
}
}
else
if (evt.id == Event.WINDOW_DESTROY && evt.target == this) {
this.hide();
this.dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
return true;
}
return super.handleEvent(evt);
}*/
public void itemStateChanged(ItemEvent evt)
{
if (evt.getSource() instanceof Choice) {
handleEnumChanged();
}
}
public void errorText(String s)
{
if (DEBUG)
System.out.println(s);
}
protected void processWindowEvent(WindowEvent evt)
{
if (evt.getID() == WindowEvent.WINDOW_CLOSING &&
evt.getWindow() == this) {
hide();
dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
}
protected void processKeyEvent(KeyEvent evt)
{
switch (evt.getID()) {
case KeyEvent.KEY_PRESSED :
if (evt.getKeyCode() == KeyEvent.VK_CONTROL) {
isctrldown_ = true;
}
break;
case KeyEvent.KEY_RELEASED :
// key detection for left and right buttons are removed
// to emulate the old release behaviour
int key = evt.getKeyCode();
if (key == KeyEvent.VK_N && isctrldown_) {
handleForward();
}
else
if (key == KeyEvent.VK_P && isctrldown_) {
handleBackward();
}
else
if (key == KeyEvent.VK_CONTROL) {
isctrldown_ = false;
}
break;
}
}
}

View file

@ -0,0 +1,456 @@
/*
*******************************************************************************
* Copyright (C) 1996-2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.rbbi;
import java.awt.*;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
import com.ibm.icu.dev.demo.impl.*;
import com.ibm.icu.text.BreakIterator;
public class TextBoundDemo extends DemoApplet
{
public static void main(String argv[]) {
new TextBoundDemo().showDemo();
}
public Frame createDemoFrame(DemoApplet applet) {
return new TextBoundFrame(applet);
}
}
class TextBoundFrame extends Frame implements ItemListener
{
private static final String creditString =
"v1.1a9, Demo";
private static final int FIELD_COLUMNS = 45;
private static final Font choiceFont = null;
private static final boolean DEBUG = false;
private DemoApplet applet;
final String right = "-->";
final String left = "<--";
private BreakIterator iter;
private boolean isctrldown_ = false;
JTextArea text;
// TextArea text;
Choice bound;
public TextBoundFrame(DemoApplet applet)
{
this.applet = applet;
init();
start();
}
public void run()
{
/*
while (true) {
try {
checkChange();
Thread.sleep(250);
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
catch (Throwable e) {
}
}
*/
}
int s, e;
int ts, te;
public void checkChange()
{
// System.out.println("checkChange...");
if ((text.getSelectionStart() & 0x7FFF) != ts ||
(text.getSelectionEnd() & 0x7FFF) != te) {
// not used int tempS = text.getSelectionStart() & 0x7FFF;
// not used int tempE = text.getSelectionEnd() & 0x7FFF;
// System.out.println(">");
// select(0, 0);
// select(tempS, tempE);
//select(tempS - (ts - s), tempE - (te - e));
// System.out.println("<");
// if (s != ts || e != te) System.out.println(" s("+s+") ts("+ts+") e("+e+") te("+te+")");
// if (tempS != ts || tempE != te) System.out.println(">s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// select(s - (ts - s), e - (te - e));
// if (tempS != ts || tempE != te) System.out.println("s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// System.out.println("lkdslksj");
}
}
public void select(int sIn, int eIn)
{
s = sIn;
e = eIn;
text.select(s, e);
ts = text.getSelectionStart() & 0x7FFF;
te = text.getSelectionEnd() & 0x7FFF;
// if (s != ts || e != te) {
// System.out.println(">s("+s+") ts("+ts+") e("+e+") te("+te+")");
// System.out.println(" "+(ts-s)+","+(te-e));
// }
}
public int getSelectionStart()
{
checkChange();
// return s;
return text.getSelectionStart() & 0x7FFF;
}
public int getSelectionEnd()
{
checkChange();
// return e;
return text.getSelectionEnd() & 0x7FFF;
}
public final synchronized void selectRange(int s, int e)
{
try {
//if (getSelectionStart() != s || getSelectionEnd() != e) {
//text.select(s, e);
select(s,e);
//}
// if (getSelectionStart() != s || getSelectionEnd() != e) {
// System.out.println("AGH! select("+s+","+e+") -> ("+
// getSelectionStart()+","+getSelectionEnd()+")");
// text.select(s - (getSelectionStart() - s), e - (getSelectionEnd() - e));
// }
} catch (Exception exp) {
errorText(exp.toString());
}
}
public void init()
{
buildGUI();
}
public void start()
{
}
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout());
Panel topPanel = new Panel();
Label titleLabel =
new Label("Text Boundary Demo", Label.CENTER);
titleLabel.setFont(DemoUtility.titleFont);
topPanel.add(titleLabel);
//Label demo=new Label(creditString, Label.CENTER);
//demo.setFont(DemoUtility.creditFont);
//topPanel.add(demo);
Panel choicePanel = new Panel();
Label demo1=new Label("Boundaries", Label.LEFT);
demo1.setFont(DemoUtility.labelFont);
choicePanel.add(demo1);
bound = new Choice();
bound.setBackground(DemoUtility.choiceColor);
bound.addItem("Sentence");
bound.addItem("Line Break");
bound.addItem("Word");
bound.addItem("Char");
bound.addItemListener(this);
if (choiceFont != null)
bound.setFont(choiceFont);
choicePanel.add(bound);
topPanel.add(choicePanel);
DemoUtility.fixGrid(topPanel,1);
add("North", topPanel);
int ROWS = 15;
int COLUMNS = 50;
// text = new TextArea(getInitialText(), ROWS, COLUMNS);
text = new JTextArea(getInitialText(), ROWS, COLUMNS);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setEditable(true);
text.selectAll();
text.setFont(DemoUtility.editFont);
text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
add("Center", new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
Panel copyrightPanel = new Panel();
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright1, Label.LEFT),DemoUtility.creditFont);
DemoUtility.fixGrid(copyrightPanel,1);
add("South", copyrightPanel);
//layout();
handleEnumChanged();
enableEvents(WindowEvent.WINDOW_CLOSING);
enableEvents(KeyEvent.KEY_PRESSED);
enableEvents(KeyEvent.KEY_RELEASED);
text.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.isControlDown()) {
int kc = e.getKeyCode();
switch (e.getKeyCode()) {
case KeyEvent.VK_N:
case KeyEvent.VK_RIGHT:
handleForward();
break;
case KeyEvent.VK_P:
case KeyEvent.VK_LEFT:
handleBackward();
break;
default:
break;
}
e.consume();
}
}
public void keyReleased(KeyEvent e) {
if (e.isControlDown()) {
e.consume();
}
}
public void keyTyped(KeyEvent e) {
if (e.isControlDown()) {
e.consume();
}
}
});
// (new Thread(this)).start();
}
public String getInitialText()
{
return
/*
"\"This is a sentence.\" This is not.\" \"because. And go. " +
"This is a simple 012.566,5 sample sentence. \n"+
"It does not have to make any sense as you can see. \n"+
"Nel mezzo del cammin di nostra vita, mi ritrovai in "+
"una selva oscura. \n"+
"Che la dritta via aveo smarrita. \n"+
"He said, that I said, that you said!! \n"+
"Don't rock the boat.\n\n"+
"Because I am the daddy, that is why. \n"+
"Not on my time (el timo.)! \n"+
"Tab\tTab\rTab\tWow."+
"So what!!\n\n"+
"Is this a question??? " +
"I wonder...Hmm.\n" +
"Harris thumbed down several, including \"Away We Go\" "+
"(which became the huge success Oklahoma!). \n"+
"One species, B. anthracis, is highly virulent.\n"+
"Wolf said about Sounder: \"Beautifully thought-out and "+
"directed.\"\n"+
"Have you ever said, \"This is where I shall live\"? \n"+
"He 1000,233,456.000 answered, \"You may not!\" \n"+
"Another popular saying is: \"How do you do?\". \n"+
"What is the proper use of the abbreviation pp.? \n"+
"Yes, I am 1,23.322% definatelly 12\" tall!!";
*/
"(\"This is a complete sentence.\") This is (\"not.\") also. "
+"An abbreviation in the middle, etc. and one at the end, etc. "+
"This "
+"is a simple sample 012.566,5 sentence. It doesn't "
+"have to make any sense, as you can see. Nel mezzo del c"
+"ammin di nostra vita, mi ritrovai in una selva oscura. Che "
+"la dritta via aveo smarrita. Not on my time (el timo.)! And "
+"tabulated columns: \tCol1\tCol2\t3,456%.\t "
+"Is this a question??? I wonder... Hmm. Harris thumbed "
+"down several, including \"Away We Go\" (which became the "
+"huge success Oklahoma!). One species, B. anthracis, is "
+"highly virulent. Wolf said about Sounder: \"Beautifully "
+"thought-out and directed.\" Have you ever said, \"This is "+
"where I "
+"shall live\"? He said 1000,233,456.000 and answered, \"You "+
"may not!\" "
+"Another popular saying is: \"How do you do?\". What is the "
+"proper use of the abbreviation pp.? Yes, I am 12\' 3\" tall!!";
}
public void handleEnumChanged()
{
String s = bound.getSelectedItem();
if (s.equals("Char")) {
errorText("getCharacterInstance");
iter = BreakIterator.getCharacterInstance();
}
else if (s.equals("Word")) {
errorText("tWordBreak");
iter = BreakIterator.getWordInstance();
}
else if (s.equals("Line Break")) {
errorText("getLineInstance");
iter = BreakIterator.getLineInstance();
}
else /* if (s.equals("Sentence")) */ {
errorText("getSentenceInstance");
iter = BreakIterator.getSentenceInstance();
}
iter.setText(text.getText());
selectRange(0, 0);
//text.select(0,0);
}
public void handleForward()
{
try {
// System.out.println("entering handleForward");
iter.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
// System.out.println("handleForward: oldStart=" + oldStart + ", oldEnd=" + oldEnd);
if (oldEnd < 1) {
selectRange(0, iter.following(0));
}
else {
int s = iter.following(oldEnd-1);
int e = iter.next();
if (e == -1) {
e = s;
}
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" +
s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void handleBackward()
{
try {
iter.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
if (oldStart < 1) {
selectRange(0, 0);
}
else {
int e = iter.following(oldStart-1);
int s = iter.previous();
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" + s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void itemStateChanged(ItemEvent evt)
{
if (evt.getSource() instanceof Choice) {
handleEnumChanged();
}
}
public void errorText(String s)
{
if (DEBUG)
System.out.println(s);
}
protected void processWindowEvent(WindowEvent evt)
{
if (evt.getID() == WindowEvent.WINDOW_CLOSING &&
evt.getWindow() == this) {
hide();
dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
}
protected void processKeyEvent(KeyEvent evt)
{
switch (evt.getID()) {
case KeyEvent.KEY_PRESSED :
if (evt.getKeyCode() == KeyEvent.VK_CONTROL) {
isctrldown_ = true;
}
break;
case KeyEvent.KEY_RELEASED :
// key detection for left and right buttons are removed
// to emulate the old release behaviour
int key = evt.getKeyCode();
if (key == KeyEvent.VK_N && isctrldown_) {
handleForward();
}
else
if (key == KeyEvent.VK_P && isctrldown_) {
handleBackward();
}
else
if (key == KeyEvent.VK_CONTROL) {
isctrldown_ = false;
}
break;
}
}
}

View file

@ -0,0 +1,12 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000-2004, International Business Machines Corporation and
others. All Rights Reserved.
-->
</head>
<body bgcolor="white">
RuleBasedBreakIterator and DictionaryBasedBreakIterator demo applications.
</body>
</html>

View file

@ -0,0 +1,525 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.rbnf;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.text.BreakIterator;
import java.text.ParsePosition;
import java.util.Locale;
import com.ibm.icu.dev.demo.impl.*;
import com.ibm.icu.text.RuleBasedNumberFormat;
public class RbnfDemo extends DemoApplet {
/**
* Puts a copyright in the .class file
*/
private static final String copyrightNotice
= "Copyright \u00a91997-1998 IBM Corp. All rights reserved.";
/*
* code to run the demo as an application
*/
public static void main(String[] argv) {
new RbnfDemo().showDemo();
}
protected Dimension getDefaultFrameSize(DemoApplet applet, Frame f) {
return new Dimension(430,270);
}
protected Frame createDemoFrame(DemoApplet applet) {
final Frame window = new Frame("Number Spellout Demo");
window.setSize(800, 600);
window.setLayout(new BorderLayout());
Panel mainPanel = new Panel();
mainPanel.setLayout(new GridLayout(1,2));
commentaryField = new TextArea("", 0, 0, TextArea.SCROLLBARS_VERTICAL_ONLY);
commentaryField.setSize(800, 50);
commentaryField.setText(RbnfSampleRuleSets.sampleRuleSetCommentary[0]);
commentaryField.setEditable(false);
commentaryField.setFont(new Font("Helvetica", Font.PLAIN, 14));
spelloutFormatter = new RuleBasedNumberFormat(RbnfSampleRuleSets.usEnglish, Locale.US);
spelloutFormatter.setLenientParseMode(lenientParse);
populateRuleSetMenu();
numberFormatter = new DecimalFormat("#,##0.##########");
parsePosition = new ParsePosition(0);
theNumber = 0;
numberField = new TextField();
numberField.setFont(new Font("Serif", Font.PLAIN, 24));
textField = new DemoTextFieldHolder();
textField.setFont(new Font("Serif", Font.PLAIN, 24));
rulesField = new DemoTextFieldHolder();
rulesField.setFont(new Font("Serif", Font.PLAIN, 14));
lenientParseButton = new Checkbox("Lenient parse", lenientParse);
numberField.addTextListener(new TextListener() {
public void textValueChanged(TextEvent e) {
if (!numberFieldHasFocus)
return;
String fieldText = ((TextComponent)(e.getSource())).getText();
parsePosition.setIndex(0);
Number temp = numberFormatter.parse(fieldText, parsePosition);
if (temp == null || parsePosition.getIndex() == 0) {
theNumber = 0;
textField.setText("PARSE ERROR");
}
else {
theNumber = temp.doubleValue();
textField.setText(spelloutFormatter.format(theNumber, ruleSetName));
}
}
} );
numberField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
numberFieldHasFocus = false;
numberField.setText(numberFormatter.format(theNumber));
}
public void focusGained(FocusEvent e) {
numberFieldHasFocus = true;
numberField.selectAll();
}
} );
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\t') {
String fieldText = ((TextComponent)(e.getSource())).getText();
parsePosition.setIndex(0);
theNumber = spelloutFormatter.parse(fieldText, parsePosition)
.doubleValue();
if (parsePosition.getIndex() == 0) {
theNumber = 0;
numberField.setText("PARSE ERROR");
textField.selectAll();
}
else if (parsePosition.getIndex() < fieldText.length()) {
textField.select(parsePosition.getIndex(), fieldText.length());
numberField.setText(numberFormatter.format(theNumber));
}
else {
textField.selectAll();
numberField.setText(numberFormatter.format(theNumber));
}
e.consume();
}
}
} );
textField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
String fieldText = ((TextComponent)(e.getSource())).getText();
parsePosition.setIndex(0);
theNumber = spelloutFormatter.parse(fieldText, parsePosition)
.doubleValue();
if (parsePosition.getIndex() == 0)
numberField.setText("PARSE ERROR");
else
numberField.setText(numberFormatter.format(theNumber));
textField.setText(textField.getText()); // textField.repaint() didn't work right
}
public void focusGained(FocusEvent e) {
textField.selectAll();
}
} );
rulesField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\t') {
String fieldText = ((TextComponent)(e.getSource())).getText();
if (formatterMenu.getSelectedItem().equals("Custom") || !fieldText.equals(
RbnfSampleRuleSets.sampleRuleSets[formatterMenu.getSelectedIndex()])) {
try {
RuleBasedNumberFormat temp = new RuleBasedNumberFormat(fieldText);
temp.setLenientParseMode(lenientParse);
populateRuleSetMenu();
spelloutFormatter = temp;
customRuleSet = fieldText;
formatterMenu.select("Custom");
commentaryField.setText(RbnfSampleRuleSets.
sampleRuleSetCommentary[RbnfSampleRuleSets.
sampleRuleSetCommentary.length - 1]);
redisplay();
}
catch (Exception x) {
textField.setText(x.toString());
}
}
e.consume();
}
}
} );
rulesField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
String fieldText = ((TextComponent)(e.getSource())).getText();
if (formatterMenu.getSelectedItem().equals("Custom") || !fieldText.equals(
RbnfSampleRuleSets.sampleRuleSets[formatterMenu.getSelectedIndex()])) {
try {
RuleBasedNumberFormat temp = new RuleBasedNumberFormat(fieldText);
temp.setLenientParseMode(lenientParse);
populateRuleSetMenu();
spelloutFormatter = temp;
customRuleSet = fieldText;
formatterMenu.select("Custom");
redisplay();
}
catch (Exception x) {
textField.setText(x.toString());
}
}
rulesField.setText(rulesField.getText()); // rulesField.repaint() didn't work right
}
} );
lenientParseButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
lenientParse = lenientParseButton.getState();
spelloutFormatter.setLenientParseMode(lenientParse);
}
} );
numberField.setText(numberFormatter.format(theNumber));
numberField.selectAll();
textField.setText(spelloutFormatter.format(theNumber, ruleSetName));
Panel leftPanel = new Panel();
leftPanel.setLayout(new BorderLayout());
Panel panel = new Panel();
panel.setLayout(new BorderLayout());
Panel panel1 = new Panel();
panel1.setLayout(new GridLayout(3, 1));
panel1.add(new Panel());
panel1.add(numberField, "Center");
panel1.add(lenientParseButton);
panel.add(panel1, "Center");
Panel panel2 = new Panel();
panel2.setLayout(new GridLayout(3, 3));
Button button = new Button("+100");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(100);
}
} );
panel2.add(button);
button = new Button("+10");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(10);
}
} );
panel2.add(button);
button = new Button("+1");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(1);
}
} );
panel2.add(button);
button = new Button("<");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
theNumber *= 10;
redisplay();
}
} );
panel2.add(button);
panel2.add(new Panel());
button = new Button(">");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
theNumber /= 10;
redisplay();
}
} );
panel2.add(button);
button = new Button("-100");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(-100);
}
} );
panel2.add(button);
button = new Button("-10");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(-10);
}
} );
panel2.add(button);
button = new Button("-1");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(-1);
}
} );
panel2.add(button);
panel.add(panel2, "East");
leftPanel.add(panel, "North");
leftPanel.add(textField, "Center");
Panel rightPanel = new Panel();
rightPanel.setLayout(new BorderLayout());
formatterMenu = new Choice();
for (int i = 0; i < RbnfSampleRuleSets.sampleRuleSetNames.length; i++)
formatterMenu.addItem(RbnfSampleRuleSets.sampleRuleSetNames[i]);
formatterMenu.addItem("Custom");
formatterMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Choice source = (Choice)(e.getSource());
int item = source.getSelectedIndex();
Locale locale = RbnfSampleRuleSets.sampleRuleSetLocales[item];
commentaryField.setText(RbnfSampleRuleSets.
sampleRuleSetCommentary[item]);
if (locale != null && (locale.getLanguage().equals("iw")
|| locale.getLanguage().equals("ru") || locale.getLanguage().equals("ja")
|| locale.getLanguage().equals("el")
|| locale.getLanguage().equals("zh"))) {
textField.togglePanes(false);
rulesField.togglePanes(false);
}
else {
textField.togglePanes(true);
rulesField.togglePanes(true);
}
makeNewSpelloutFormatter();
redisplay();
}
} );
ruleSetMenu = new Choice();
populateRuleSetMenu();
ruleSetMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
ruleSetName = ruleSetMenu.getSelectedItem();
redisplay();
}
} );
Panel menuPanel = new Panel();
menuPanel.setLayout(new GridLayout(1, 2));
menuPanel.add(formatterMenu);
menuPanel.add(ruleSetMenu);
rightPanel.add(menuPanel, "North");
rulesField.setText(RbnfSampleRuleSets.sampleRuleSets[formatterMenu.getSelectedIndex()]);
rightPanel.add(rulesField, "Center");
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
window.add(mainPanel, "Center");
window.add(commentaryField, "South");
window.doLayout();
window.show();
return window;
}
void roll(int delta) {
theNumber += delta;
redisplay();
}
void redisplay() {
numberField.setText(numberFormatter.format(theNumber));
textField.setText(spelloutFormatter.format(theNumber, ruleSetName));
}
void makeNewSpelloutFormatter() {
int item = formatterMenu.getSelectedIndex();
String formatterMenuItem = formatterMenu.getSelectedItem();
if (formatterMenuItem.equals("Custom")) {
rulesField.setText(customRuleSet);
spelloutFormatter = new RuleBasedNumberFormat(customRuleSet);
}
else {
rulesField.setText(RbnfSampleRuleSets.sampleRuleSets[item]);
Locale locale = RbnfSampleRuleSets.sampleRuleSetLocales[item];
if (locale == null)
locale = Locale.getDefault();
spelloutFormatter = new RuleBasedNumberFormat(RbnfSampleRuleSets.
sampleRuleSets[item], locale);
}
spelloutFormatter.setLenientParseMode(lenientParse);
populateRuleSetMenu();
}
void populateRuleSetMenu() {
String[] ruleSetNames = spelloutFormatter.getRuleSetNames();
if (ruleSetMenu != null) {
ruleSetMenu.removeAll();
for (int i = 0; i < ruleSetNames.length; i++)
ruleSetMenu.addItem(ruleSetNames[i]);
ruleSetName = ruleSetMenu.getSelectedItem();
}
else
ruleSetName = ruleSetNames[0];
}
private Frame demoWindow = null;
private TextComponent numberField;
private DemoTextFieldHolder textField;
private DemoTextFieldHolder rulesField;
private TextComponent commentaryField;
private Checkbox lenientParseButton;
private boolean numberFieldHasFocus = true;
private RuleBasedNumberFormat spelloutFormatter;
private DecimalFormat numberFormatter;
private ParsePosition parsePosition;
private boolean lenientParse = true;
private double theNumber = 0;
private boolean canEdit = true;
private Choice formatterMenu;
private Choice ruleSetMenu;
private String ruleSetName;
private String customRuleSet = "NO RULES!";
}
class DemoTextField extends Component {
public DemoTextField() {
}
public void setText(String text) {
this.text = text;
this.repaint();
}
public String getText() {
return text;
}
public void paint(Graphics g) {
Font font = getFont();
FontMetrics fm = g.getFontMetrics();
g.setFont(font);
String text = getText();
BreakIterator bi = BreakIterator.getLineInstance();
bi.setText(text);
int lineHeight = fm.getHeight();
int width = getSize().width;
int penY = fm.getAscent();
int lineStart = 0;
int tempLineEnd = bi.first();
int lineEnd = 0;
int maxLineEnd = 0;
totalHeight = 0;
while (lineStart < text.length()) {
maxLineEnd = text.indexOf('\n', lineStart);
if (maxLineEnd == -1)
maxLineEnd = Integer.MAX_VALUE;
while (tempLineEnd != BreakIterator.DONE && fm.stringWidth(text.substring(
lineStart, tempLineEnd)) < width) {
lineEnd = tempLineEnd;
tempLineEnd = bi.next();
}
if (lineStart >= lineEnd) {
if (tempLineEnd == BreakIterator.DONE)
lineEnd = text.length();
else
lineEnd = tempLineEnd;
}
if (lineEnd > maxLineEnd)
lineEnd = maxLineEnd;
g.drawString(text.substring(lineStart, lineEnd), 0, penY);
penY += lineHeight;
totalHeight += lineHeight;
lineStart = lineEnd;
if (lineStart < text.length() && text.charAt(lineStart) == '\n')
++lineStart;
}
}
/*
public Dimension getPreferredSize() {
Dimension size = getParent().getSize();
return new Dimension(size.width, totalHeight);
}
*/
private String text;
private int totalHeight;
}
class DemoTextFieldHolder extends Panel {
public DemoTextFieldHolder() {
tf1 = new TextArea("", 0, 0, TextArea.SCROLLBARS_VERTICAL_ONLY);
tf2 = new DemoTextField();
sp = new ScrollPane();
setLayout(new CardLayout());
sp.add(tf2, "TextField1");
sp.setVisible(false);
add(tf1, "TestField2");
add(sp, "ScrollPane");
}
public void addFocusListener(FocusListener l) {
tf1.addFocusListener(l);
}
public void addKeyListener(KeyListener l) {
tf1.addKeyListener(l);
}
public void setText(String text) {
tf1.setText(text);
tf2.setText(text);
}
public String getText() {
return tf1.getText();
}
public void select(int start, int end) {
tf1.select(start, end);
}
public void selectAll() {
tf1.selectAll();
}
public void togglePanes(boolean canShowRealTextField) {
if (canShowRealTextField != showingRealTextField) {
CardLayout layout = (CardLayout)(getLayout());
layout.next(this);
showingRealTextField = canShowRealTextField;
}
}
private TextArea tf1 = null;
private DemoTextField tf2 = null;
private ScrollPane sp = null;
private boolean showingRealTextField = true;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,12 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000-2004, International Business Machines Corporation and
others. All Rights Reserved.
-->
</head>
<body bgcolor="white">
RuleBasedNumberFormat demo appliation.
</body>
</html>

View file

@ -0,0 +1,84 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
*/
package com.ibm.icu.dev.demo.timescale;
import java.util.Locale;
import com.ibm.icu.text.MessageFormat;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.SimpleTimeZone;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.UniversalTimeScale;
/**
* This class demonstrates how to use <code>UniversalTimeScale</code> to
* convert from one local time scale to another.
*
* @see UniversalTimeScale
*
* @draft ICU 3.2
*/
public class PivotDemo {
/**
* The default constructor.
*
* @draft ICU 3.2
*/
public PivotDemo()
{
}
/**
* The <code>main()</code> method uses <code>UniversalTimeScale</code> to
* convert from the Java and Unix time scales to the ICU time scale. It uses
* a <code>Calendar</code> object to display the ICU time values.
*
* @param args the command line arguments.
*
* @draft ICU 3.2
*/
public static void main(String[] args)
{
TimeZone utc = new SimpleTimeZone(0, "UTC");
Calendar cal = Calendar.getInstance(utc, Locale.ENGLISH);
MessageFormat fmt = new MessageFormat("{1} = {0, date, full} {0, time, full}");
Object arguments[] = {cal, null};
arguments[0] = cal;
System.out.println("\nJava test:");
cal.setTimeInMillis(UniversalTimeScale.toLong(UniversalTimeScale.from(0, UniversalTimeScale.JAVA_TIME), UniversalTimeScale.ICU4C_TIME));
arguments[1] = " 000000000000000";
System.out.println(fmt.format(arguments));
cal.setTimeInMillis(UniversalTimeScale.toLong(UniversalTimeScale.from(-62164684800000L, UniversalTimeScale.JAVA_TIME), UniversalTimeScale.ICU4C_TIME));
arguments[1] = "-62164684800000L";
System.out.println(fmt.format(arguments));
cal.setTimeInMillis(UniversalTimeScale.toLong(UniversalTimeScale.from(-62135769600000L, UniversalTimeScale.JAVA_TIME), UniversalTimeScale.ICU4C_TIME));
arguments[1] = "-62135769600000L";
System.out.println(fmt.format(arguments));
System.out.println("\nUnix test:");
cal.setTimeInMillis(UniversalTimeScale.toLong(UniversalTimeScale.from(0x80000000, UniversalTimeScale.UNIX_TIME), UniversalTimeScale.ICU4C_TIME));
arguments[1] = "0x80000000";
System.out.println(fmt.format(arguments));
cal.setTimeInMillis(UniversalTimeScale.toLong(UniversalTimeScale.from(0, UniversalTimeScale.UNIX_TIME), UniversalTimeScale.ICU4C_TIME));
arguments[1] = "0x00000000";
System.out.println(fmt.format(arguments));
cal.setTimeInMillis(UniversalTimeScale.toLong(UniversalTimeScale.from(0x7FFFFFFF, UniversalTimeScale.UNIX_TIME), UniversalTimeScale.ICU4C_TIME));
arguments[1] = "0x7FFFFFFF";
System.out.println(fmt.format(arguments));
}
}

View file

@ -0,0 +1,299 @@
/**
*******************************************************************************
* Copyright (C) 2001-2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.translit;
import com.ibm.icu.lang.*;
import com.ibm.icu.text.*;
import java.util.*;
public class AnyTransliterator extends Transliterator {
static final boolean DEBUG = false;
private String targetName;
private RunIterator it;
private Position run;
public AnyTransliterator(String targetName, UnicodeFilter filter, RunIterator it){
super("Any-" + targetName, filter);
this.targetName = targetName;
this.it = it;
run = new Position();
}
public AnyTransliterator(String targetName, UnicodeFilter filter){
this(targetName, filter, new ScriptRunIterator());
}
static private Transliterator hex = Transliterator.getInstance("[^\\u0020-\\u007E] hex");
protected void handleTransliterate(Replaceable text,
Position offsets, boolean isIncremental) {
if (DEBUG) {
System.out.println("- handleTransliterate " + hex.transliterate(text.toString())
+ ", " + toString(offsets));
}
it.reset(text, offsets);
while (it.next(run)) {
if (targetName.equalsIgnoreCase(it.getName())) {
if (DEBUG) System.out.println("Skipping identical: " + targetName);
run.start = run.limit; // show we processed
continue; // skip if same
}
Transliterator t;
String id = it.getName() + '-' + targetName;
try {
t = Transliterator.getInstance(id);
} catch (IllegalArgumentException ex) {
if (DEBUG) System.out.println("Couldn't find: " + id + ", Trying Latin as Pivot");
id = it.getName() + "-Latin; Latin-" + targetName;
try {
t = Transliterator.getInstance(id);
} catch (IllegalArgumentException ex2) {
if (DEBUG) System.out.println("Couldn't find: " + id);
continue;
}
}
// TODO catch error later!!
if (DEBUG) {
System.out.println(t.getID());
System.out.println("input: " + hex.transliterate(text.toString())
+ ", " + toString(run));
}
if (isIncremental && it.atEnd()) {
t.transliterate(text, run);
} else {
t.finishTransliteration(text, run);
}
// adjust the offsets in line with the changes
it.adjust(run.limit);
if (DEBUG) {
System.out.println("output: " + hex.transliterate(text.toString())
+ ", " + toString(run));
}
}
// show how far we got!
it.getExpanse(offsets);
if (run.start == run.limit) offsets.start = offsets.limit;
else offsets.start = run.start;
if (DEBUG) {
System.out.println("+ handleTransliterate: " + ", " + toString(offsets));
System.out.println();
}
}
// should be method on Position
public static String toString(Position offsets) {
return "[cs: " + offsets.contextStart
+ ", s: " + offsets.start
+ ", l: " + offsets.limit
+ ", cl: " + offsets.contextLimit
+ "]";
}
public interface RunIterator {
public void reset(Replaceable text, Position expanse);
public void getExpanse(Position run);
public void reset();
public boolean next(Position run);
public void getCurrent(Position run);
public String getName();
public void adjust(int newCurrentLimit);
public boolean atEnd();
}
/**
* Returns a series of ranges corresponding to scripts. They will be of the form:
* ccccSScSSccccTTcTcccc - where c is common, S is the first script and T is the second
*| | - first run
* | | - second run
* That is, the runs will overlap. The reason for this is so that a transliterator can
* consider common characters both before and after the scripts.
* The only time that contextStart != start is for the first run
* (the context is the start context of the entire expanse)
* The only time that contextLimit != limit is for the last run
* (the context is the end context of the entire expanse)
*/
public static class ScriptRunIterator implements RunIterator {
private Replaceable text;
private Position expanse = new Position();
private Position current = new Position();
private int script;
private boolean done = true;
public void reset(Replaceable text, Position expanse) {
set(this.expanse, expanse);
this.text = text;
reset();
}
public void reset() {
done = false;
//this.expanse = expanse;
script = UScript.INVALID_CODE;
// set up first range to be empty, at beginning
current.contextStart = expanse.contextStart;
current.start = current.limit = current.contextLimit = expanse.start;
}
public boolean next(Position run) {
if (done) return false;
if (DEBUG) {
System.out.println("+cs: " + current.contextStart
+ ", s: " + current.start
+ ", l: " + current.limit
+ ", cl: " + current.contextLimit);
}
// reset start context run to the last end
current.start = current.limit;
// Phase 1. Backup the START value through COMMON until we get to expanse.start or a real script.
int i, cp;
int limit = expanse.start;
for (i = current.start; i > limit; i -= UTF16.getCharCount(cp)) {
cp = text.char32At(i);
int script = UScript.getScript(cp);
if (script != UScript.COMMON && script != UScript.INHERITED) break;
}
current.start = i;
current.contextStart = (i == limit) ? expanse.contextStart : i; // extend at start
// PHASE 2. Move up the LIMIT value through COMMON or single script until we get to expanse.limit
int lastScript = UScript.COMMON;
//int veryLastScript = UScript.COMMON;
limit = expanse.limit;
for (i = current.limit; i < limit; i += UTF16.getCharCount(cp)) {
cp = text.char32At(i);
int script = UScript.getScript(cp);
if (script == UScript.INHERITED) script = UScript.COMMON;
if (script != UScript.COMMON) {
// if we find a real script:
// if we already had a script, bail
// otherwise set our script
if (lastScript == UScript.COMMON) lastScript = script;
else if (lastScript != script) break;
}
}
current.limit = i;
current.contextLimit = (i == limit) ? expanse.contextLimit : i; // extend at end
done = (i == limit);
script = lastScript;
if (DEBUG) {
System.out.println("-cs: " + current.contextStart
+ ", s: " + current.start
+ ", l: " + current.limit
+ ", cl: " + current.contextLimit);
}
set(run, current);
return true;
}
// SHOULD BE METHOD ON POSITION
public static void set(Position run, Position current) {
run.contextStart = current.contextStart;
run.start = current.start;
run.limit = current.limit;
run.contextLimit = current.contextLimit;
}
public boolean atEnd() {
return current.limit == expanse.limit;
}
public void getCurrent(Position run) {
set(run, current);
}
public void getExpanse(Position run) {
set(run, expanse);
}
public String getName() {
return UScript.getName(script);
}
public void adjust(int newCurrentLimit) {
if (expanse == null) {
throw new IllegalArgumentException("Must reset() before calling");
}
int delta = newCurrentLimit - current.limit;
current.limit += delta;
current.contextLimit += delta;
expanse.limit += delta;
expanse.contextLimit += delta;
}
// register Any-Script for every script.
private static Set scriptList = new HashSet();
public static void registerAnyToScript() {
synchronized (scriptList) {
Enumeration sources = Transliterator.getAvailableSources();
while(sources.hasMoreElements()) {
String source = (String) sources.nextElement();
if (source.equals("Any")) continue; // to keep from looping
Enumeration targets = Transliterator.getAvailableTargets(source);
while(targets.hasMoreElements()) {
String target = (String) targets.nextElement();
if (UScript.getCode(target) == null) continue; // SKIP unless we have a script (or locale)
if (scriptList.contains(target)) continue; // already encountered
scriptList.add(target); // otherwise add for later testing
Set variantSet = add(new TreeSet(), Transliterator.getAvailableVariants(source, target));
if (variantSet.size() < 2) {
AnyTransliterator at = new AnyTransliterator(target, null);
DummyFactory.add(at.getID(), at);
} else {
Iterator variants = variantSet.iterator();
while(variants.hasNext()) {
String variant = (String) variants.next();
AnyTransliterator at = new AnyTransliterator(
(variant.length() > 0) ? target + "/" + variant : target, null);
DummyFactory.add(at.getID(), at);
}
}
}
}
}
}
static class DummyFactory implements Transliterator.Factory {
static DummyFactory singleton = new DummyFactory();
static HashMap m = new HashMap();
// Since Transliterators are immutable, we don't have to clone on set & get
static void add(String ID, Transliterator t) {
m.put(ID, t);
System.out.println("Registering: " + ID + ", " + t.toRules(true));
Transliterator.registerFactory(ID, singleton);
}
public Transliterator getInstance(String ID) {
return (Transliterator) m.get(ID);
}
}
// Nice little Utility for converting Enumeration to collection
static Set add(Set s, Enumeration enumeration) {
while(enumeration.hasMoreElements()) {
s.add(enumeration.nextElement());
}
return s;
}
}
}

View file

@ -0,0 +1,555 @@
/**
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.translit;
import java.util.*;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UnicodeSet;
/**
* Incrementally returns the set of all strings that case-fold to the same value.
*/
public class CaseIterator {
// testing stuff
private static final boolean DEBUG = true;
static Transliterator toName = Transliterator.getInstance("[:^ascii:] Any-Name");
static Transliterator toHex = Transliterator.getInstance("[:^ascii:] Any-Hex");
static Transliterator toHex2 = Transliterator.getInstance("[[^\u0021-\u007F]-[,]] Any-Hex");
// global tables (could be precompiled)
private static Map fromCaseFold = new HashMap();
private static Map toCaseFold = new HashMap();
private static int maxLength = 0;
// This exception list is generated on the console by turning on the GENERATED flag,
// which MUST be false for normal operation.
// Once the list is generated, it is pasted in here.
// A bit of a cludge, but this bootstrapping is the easiest way
// to get around certain complications in the data.
private static final boolean GENERATE = false;
private static final boolean DUMP = false;
private static String[][] exceptionList = {
// a\N{MODIFIER LETTER RIGHT HALF RING}
{"a\u02BE","A\u02BE","a\u02BE",},
// ff
{"ff","FF","Ff","fF","ff",},
// ffi
{"ffi","FFI","FFi","FfI","Ffi","F\uFB01","fFI","fFi","ffI","ffi","f\uFB01","\uFB00I","\uFB00i",},
// ffl
{"ffl","FFL","FFl","FfL","Ffl","F\uFB02","fFL","fFl","ffL","ffl","f\uFB02","\uFB00L","\uFB00l",},
// fi
{"fi","FI","Fi","fI","fi",},
// fl
{"fl","FL","Fl","fL","fl",},
// h\N{COMBINING MACRON BELOW}
{"h\u0331","H\u0331","h\u0331",},
// i\N{COMBINING DOT ABOVE}
{"i\u0307","I\u0307","i\u0307",},
// j\N{COMBINING CARON}
{"j\u030C","J\u030C","j\u030C",},
// ss
{"ss","SS","Ss","S\u017F","sS","ss","s\u017F","\u017FS","\u017Fs","\u017F\u017F",},
// st
{"st","ST","St","sT","st","\u017FT","\u017Ft",},
// t\N{COMBINING DIAERESIS}
{"t\u0308","T\u0308","t\u0308",},
// w\N{COMBINING RING ABOVE}
{"w\u030A","W\u030A","w\u030A",},
// y\N{COMBINING RING ABOVE}
{"y\u030A","Y\u030A","y\u030A",},
// \N{MODIFIER LETTER APOSTROPHE}n
{"\u02BCn","\u02BCN","\u02BCn",},
// \N{GREEK SMALL LETTER ALPHA WITH TONOS}\N{GREEK SMALL LETTER IOTA}
{"\u03AC\u03B9","\u0386\u0345","\u0386\u0399","\u0386\u03B9","\u0386\u1FBE","\u03AC\u0345","\u03AC\u0399","\u03AC\u03B9","\u03AC\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH TONOS}\N{GREEK SMALL LETTER IOTA}
{"\u03AE\u03B9","\u0389\u0345","\u0389\u0399","\u0389\u03B9","\u0389\u1FBE","\u03AE\u0345","\u03AE\u0399","\u03AE\u03B9","\u03AE\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA}\N{COMBINING GREEK PERISPOMENI}
{"\u03B1\u0342","\u0391\u0342","\u03B1\u0342",},
// \N{GREEK SMALL LETTER ALPHA}\N{COMBINING GREEK PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u03B1\u0342\u03B9","\u0391\u0342\u0345","\u0391\u0342\u0399","\u0391\u0342\u03B9","\u0391\u0342\u1FBE",
"\u03B1\u0342\u0345","\u03B1\u0342\u0399","\u03B1\u0342\u03B9","\u03B1\u0342\u1FBE","\u1FB6\u0345",
"\u1FB6\u0399","\u1FB6\u03B9","\u1FB6\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA}\N{GREEK SMALL LETTER IOTA}
{"\u03B1\u03B9","\u0391\u0345","\u0391\u0399","\u0391\u03B9","\u0391\u1FBE","\u03B1\u0345","\u03B1\u0399","\u03B1\u03B9","\u03B1\u1FBE",},
// \N{GREEK SMALL LETTER ETA}\N{COMBINING GREEK PERISPOMENI}
{"\u03B7\u0342","\u0397\u0342","\u03B7\u0342",},
// \N{GREEK SMALL LETTER ETA}\N{COMBINING GREEK PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u03B7\u0342\u03B9","\u0397\u0342\u0345","\u0397\u0342\u0399","\u0397\u0342\u03B9","\u0397\u0342\u1FBE",
"\u03B7\u0342\u0345","\u03B7\u0342\u0399","\u03B7\u0342\u03B9","\u03B7\u0342\u1FBE","\u1FC6\u0345","\u1FC6\u0399",
"\u1FC6\u03B9","\u1FC6\u1FBE",},
// \N{GREEK SMALL LETTER ETA}\N{GREEK SMALL LETTER IOTA}
{"\u03B7\u03B9","\u0397\u0345","\u0397\u0399","\u0397\u03B9","\u0397\u1FBE","\u03B7\u0345","\u03B7\u0399","\u03B7\u03B9","\u03B7\u1FBE",},
// \N{GREEK SMALL LETTER IOTA}\N{COMBINING DIAERESIS}\N{COMBINING GRAVE ACCENT}
{"\u03B9\u0308\u0300","\u0345\u0308\u0300","\u0399\u0308\u0300","\u03B9\u0308\u0300","\u1FBE\u0308\u0300",},
// \N{GREEK SMALL LETTER IOTA}\N{COMBINING DIAERESIS}\N{COMBINING ACUTE ACCENT}
{"\u03B9\u0308\u0301","\u0345\u0308\u0301","\u0399\u0308\u0301","\u03B9\u0308\u0301","\u1FBE\u0308\u0301",},
// \N{GREEK SMALL LETTER IOTA}\N{COMBINING DIAERESIS}\N{COMBINING GREEK PERISPOMENI}
{"\u03B9\u0308\u0342","\u0345\u0308\u0342","\u0399\u0308\u0342","\u03B9\u0308\u0342","\u1FBE\u0308\u0342",},
// \N{GREEK SMALL LETTER IOTA}\N{COMBINING GREEK PERISPOMENI}
{"\u03B9\u0342","\u0345\u0342","\u0399\u0342","\u03B9\u0342","\u1FBE\u0342",},
// \N{GREEK SMALL LETTER RHO}\N{COMBINING COMMA ABOVE}
{"\u03C1\u0313","\u03A1\u0313","\u03C1\u0313","\u03F1\u0313",},
// \N{GREEK SMALL LETTER UPSILON}\N{COMBINING DIAERESIS}\N{COMBINING GRAVE ACCENT}
{"\u03C5\u0308\u0300","\u03A5\u0308\u0300","\u03C5\u0308\u0300",},
// \N{GREEK SMALL LETTER UPSILON}\N{COMBINING DIAERESIS}\N{COMBINING ACUTE ACCENT}
{"\u03C5\u0308\u0301","\u03A5\u0308\u0301","\u03C5\u0308\u0301",},
// \N{GREEK SMALL LETTER UPSILON}\N{COMBINING DIAERESIS}\N{COMBINING GREEK PERISPOMENI}
{"\u03C5\u0308\u0342","\u03A5\u0308\u0342","\u03C5\u0308\u0342",},
// \N{GREEK SMALL LETTER UPSILON}\N{COMBINING COMMA ABOVE}
{"\u03C5\u0313","\u03A5\u0313","\u03C5\u0313",},
// \N{GREEK SMALL LETTER UPSILON}\N{COMBINING COMMA ABOVE}\N{COMBINING GRAVE ACCENT}
{"\u03C5\u0313\u0300","\u03A5\u0313\u0300","\u03C5\u0313\u0300","\u1F50\u0300",},
// \N{GREEK SMALL LETTER UPSILON}\N{COMBINING COMMA ABOVE}\N{COMBINING ACUTE ACCENT}
{"\u03C5\u0313\u0301","\u03A5\u0313\u0301","\u03C5\u0313\u0301","\u1F50\u0301",},
// \N{GREEK SMALL LETTER UPSILON}\N{COMBINING COMMA ABOVE}\N{COMBINING GREEK PERISPOMENI}
{"\u03C5\u0313\u0342","\u03A5\u0313\u0342","\u03C5\u0313\u0342","\u1F50\u0342",},
// \N{GREEK SMALL LETTER UPSILON}\N{COMBINING GREEK PERISPOMENI}
{"\u03C5\u0342","\u03A5\u0342","\u03C5\u0342",},
// \N{GREEK SMALL LETTER OMEGA}\N{COMBINING GREEK PERISPOMENI}
{"\u03C9\u0342","\u03A9\u0342","\u03C9\u0342","\u2126\u0342",},
// \N{GREEK SMALL LETTER OMEGA}\N{COMBINING GREEK PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u03C9\u0342\u03B9","\u03A9\u0342\u0345","\u03A9\u0342\u0399","\u03A9\u0342\u03B9","\u03A9\u0342\u1FBE","\u03C9\u0342\u0345","\u03C9\u0342\u0399","\u03C9\u0342\u03B9","\u03C9\u0342\u1FBE","\u1FF6\u0345",
"\u1FF6\u0399","\u1FF6\u03B9","\u1FF6\u1FBE","\u2126\u0342\u0345","\u2126\u0342\u0399","\u2126\u0342\u03B9","\u2126\u0342\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA}\N{GREEK SMALL LETTER IOTA}
{"\u03C9\u03B9","\u03A9\u0345","\u03A9\u0399","\u03A9\u03B9","\u03A9\u1FBE","\u03C9\u0345","\u03C9\u0399","\u03C9\u03B9","\u03C9\u1FBE","\u2126\u0345","\u2126\u0399","\u2126\u03B9","\u2126\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH TONOS}\N{GREEK SMALL LETTER IOTA}
{"\u03CE\u03B9","\u038F\u0345","\u038F\u0399","\u038F\u03B9","\u038F\u1FBE","\u03CE\u0345","\u03CE\u0399","\u03CE\u03B9","\u03CE\u1FBE",},
// \N{ARMENIAN SMALL LETTER ECH}\N{ARMENIAN SMALL LETTER YIWN}
{"\u0565\u0582","\u0535\u0552","\u0535\u0582","\u0565\u0552","\u0565\u0582",},
// \N{ARMENIAN SMALL LETTER MEN}\N{ARMENIAN SMALL LETTER ECH}
{"\u0574\u0565","\u0544\u0535","\u0544\u0565","\u0574\u0535","\u0574\u0565",},
// \N{ARMENIAN SMALL LETTER MEN}\N{ARMENIAN SMALL LETTER INI}
{"\u0574\u056B","\u0544\u053B","\u0544\u056B","\u0574\u053B","\u0574\u056B",},
// \N{ARMENIAN SMALL LETTER MEN}\N{ARMENIAN SMALL LETTER XEH}
{"\u0574\u056D","\u0544\u053D","\u0544\u056D","\u0574\u053D","\u0574\u056D",},
// \N{ARMENIAN SMALL LETTER MEN}\N{ARMENIAN SMALL LETTER NOW}
{"\u0574\u0576","\u0544\u0546","\u0544\u0576","\u0574\u0546","\u0574\u0576",},
// \N{ARMENIAN SMALL LETTER VEW}\N{ARMENIAN SMALL LETTER NOW}
{"\u057E\u0576","\u054E\u0546","\u054E\u0576","\u057E\u0546","\u057E\u0576",},
// \N{GREEK SMALL LETTER ALPHA WITH PSILI}\N{GREEK SMALL LETTER IOTA}
{"\u1F00\u03B9","\u1F00\u0345","\u1F00\u0399","\u1F00\u03B9","\u1F00\u1FBE","\u1F08\u0345","\u1F08\u0399","\u1F08\u03B9","\u1F08\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA WITH DASIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F01\u03B9","\u1F01\u0345","\u1F01\u0399","\u1F01\u03B9","\u1F01\u1FBE","\u1F09\u0345","\u1F09\u0399","\u1F09\u03B9","\u1F09\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F02\u03B9","\u1F02\u0345","\u1F02\u0399","\u1F02\u03B9","\u1F02\u1FBE","\u1F0A\u0345","\u1F0A\u0399","\u1F0A\u03B9","\u1F0A\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F03\u03B9","\u1F03\u0345","\u1F03\u0399","\u1F03\u03B9","\u1F03\u1FBE","\u1F0B\u0345","\u1F0B\u0399","\u1F0B\u03B9","\u1F0B\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F04\u03B9","\u1F04\u0345","\u1F04\u0399","\u1F04\u03B9","\u1F04\u1FBE","\u1F0C\u0345","\u1F0C\u0399","\u1F0C\u03B9","\u1F0C\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F05\u03B9","\u1F05\u0345","\u1F05\u0399","\u1F05\u03B9","\u1F05\u1FBE","\u1F0D\u0345","\u1F0D\u0399","\u1F0D\u03B9","\u1F0D\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u1F06\u03B9","\u1F06\u0345","\u1F06\u0399","\u1F06\u03B9","\u1F06\u1FBE","\u1F0E\u0345","\u1F0E\u0399","\u1F0E\u03B9","\u1F0E\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u1F07\u03B9","\u1F07\u0345","\u1F07\u0399","\u1F07\u03B9","\u1F07\u1FBE","\u1F0F\u0345","\u1F0F\u0399","\u1F0F\u03B9","\u1F0F\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH PSILI}\N{GREEK SMALL LETTER IOTA}
{"\u1F20\u03B9","\u1F20\u0345","\u1F20\u0399","\u1F20\u03B9","\u1F20\u1FBE","\u1F28\u0345","\u1F28\u0399","\u1F28\u03B9","\u1F28\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH DASIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F21\u03B9","\u1F21\u0345","\u1F21\u0399","\u1F21\u03B9","\u1F21\u1FBE","\u1F29\u0345","\u1F29\u0399","\u1F29\u03B9","\u1F29\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH PSILI AND VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F22\u03B9","\u1F22\u0345","\u1F22\u0399","\u1F22\u03B9","\u1F22\u1FBE","\u1F2A\u0345","\u1F2A\u0399","\u1F2A\u03B9","\u1F2A\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH DASIA AND VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F23\u03B9","\u1F23\u0345","\u1F23\u0399","\u1F23\u03B9","\u1F23\u1FBE","\u1F2B\u0345","\u1F2B\u0399","\u1F2B\u03B9","\u1F2B\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH PSILI AND OXIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F24\u03B9","\u1F24\u0345","\u1F24\u0399","\u1F24\u03B9","\u1F24\u1FBE","\u1F2C\u0345","\u1F2C\u0399","\u1F2C\u03B9","\u1F2C\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH DASIA AND OXIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F25\u03B9","\u1F25\u0345","\u1F25\u0399","\u1F25\u03B9","\u1F25\u1FBE","\u1F2D\u0345","\u1F2D\u0399","\u1F2D\u03B9","\u1F2D\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u1F26\u03B9","\u1F26\u0345","\u1F26\u0399","\u1F26\u03B9","\u1F26\u1FBE","\u1F2E\u0345","\u1F2E\u0399","\u1F2E\u03B9","\u1F2E\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u1F27\u03B9","\u1F27\u0345","\u1F27\u0399","\u1F27\u03B9","\u1F27\u1FBE","\u1F2F\u0345","\u1F2F\u0399","\u1F2F\u03B9","\u1F2F\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH PSILI}\N{GREEK SMALL LETTER IOTA}
{"\u1F60\u03B9","\u1F60\u0345","\u1F60\u0399","\u1F60\u03B9","\u1F60\u1FBE","\u1F68\u0345","\u1F68\u0399","\u1F68\u03B9","\u1F68\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH DASIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F61\u03B9","\u1F61\u0345","\u1F61\u0399","\u1F61\u03B9","\u1F61\u1FBE","\u1F69\u0345","\u1F69\u0399","\u1F69\u03B9","\u1F69\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F62\u03B9","\u1F62\u0345","\u1F62\u0399","\u1F62\u03B9","\u1F62\u1FBE","\u1F6A\u0345","\u1F6A\u0399","\u1F6A\u03B9","\u1F6A\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F63\u03B9","\u1F63\u0345","\u1F63\u0399","\u1F63\u03B9","\u1F63\u1FBE","\u1F6B\u0345","\u1F6B\u0399","\u1F6B\u03B9","\u1F6B\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F64\u03B9","\u1F64\u0345","\u1F64\u0399","\u1F64\u03B9","\u1F64\u1FBE","\u1F6C\u0345","\u1F6C\u0399","\u1F6C\u03B9","\u1F6C\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F65\u03B9","\u1F65\u0345","\u1F65\u0399","\u1F65\u03B9","\u1F65\u1FBE","\u1F6D\u0345","\u1F6D\u0399","\u1F6D\u03B9","\u1F6D\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u1F66\u03B9","\u1F66\u0345","\u1F66\u0399","\u1F66\u03B9","\u1F66\u1FBE","\u1F6E\u0345","\u1F6E\u0399","\u1F6E\u03B9","\u1F6E\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI}\N{GREEK SMALL LETTER IOTA}
{"\u1F67\u03B9","\u1F67\u0345","\u1F67\u0399","\u1F67\u03B9","\u1F67\u1FBE","\u1F6F\u0345","\u1F6F\u0399","\u1F6F\u03B9","\u1F6F\u1FBE",},
// \N{GREEK SMALL LETTER ALPHA WITH VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F70\u03B9","\u1F70\u0345","\u1F70\u0399","\u1F70\u03B9","\u1F70\u1FBE","\u1FBA\u0345","\u1FBA\u0399","\u1FBA\u03B9","\u1FBA\u1FBE",},
// \N{GREEK SMALL LETTER ETA WITH VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F74\u03B9","\u1F74\u0345","\u1F74\u0399","\u1F74\u03B9","\u1F74\u1FBE","\u1FCA\u0345","\u1FCA\u0399","\u1FCA\u03B9","\u1FCA\u1FBE",},
// \N{GREEK SMALL LETTER OMEGA WITH VARIA}\N{GREEK SMALL LETTER IOTA}
{"\u1F7C\u03B9","\u1F7C\u0345","\u1F7C\u0399","\u1F7C\u03B9","\u1F7C\u1FBE","\u1FFA\u0345","\u1FFA\u0399","\u1FFA\u03B9","\u1FFA\u1FBE",},
};
// this initializes the data used to generated the case-equivalents
static {
// Gather up the exceptions in a form we can use
if (!GENERATE) {
for (int i = 0; i < exceptionList.length; ++i) {
String[] exception = exceptionList[i];
Set s = new HashSet();
// there has to be some method to do the following, but I can't find it in the collections
for (int j = 0; j < exception.length; ++j) {
s.add(exception[j]);
}
fromCaseFold.put(exception[0], s);
}
}
// walk through all the characters, and at every case fold result,
// put a set of all the characters that map to that result
boolean defaultmapping = true; // false for turkish
for (int i = 0; i <= 0x10FFFF; ++i) {
int cat = UCharacter.getType(i);
if (cat == Character.UNASSIGNED || cat == Character.PRIVATE_USE) continue;
String cp = UTF16.valueOf(i);
String mapped = UCharacter.foldCase(cp, defaultmapping);
if (mapped.equals(cp)) continue;
if (maxLength < mapped.length()) maxLength = mapped.length();
// at this point, have different case folding
Set s = (Set) fromCaseFold.get(mapped);
if (s == null) {
s = new HashSet();
s.add(mapped); // add the case fold result itself
fromCaseFold.put(mapped, s);
}
s.add(cp);
toCaseFold.put(cp, mapped);
toCaseFold.put(mapped, mapped); // add mapping to self
}
// Emit the final data
if (DUMP) {
System.out.println("maxLength = " + maxLength);
System.out.println("\nfromCaseFold:");
Iterator it = fromCaseFold.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
System.out.print(" " + toHex2.transliterate((String)key) + ": ");
Set s = (Set) fromCaseFold.get(key);
Iterator it2 = s.iterator();
boolean first = true;
while (it2.hasNext()) {
if (first) {
first = false;
} else {
System.out.print(", ");
}
System.out.print(toHex2.transliterate((String)it2.next()));
}
System.out.println("");
}
System.out.println("\ntoCaseFold:");
it = toCaseFold.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
String value = (String) toCaseFold.get(key);
System.out.println(" " + toHex2.transliterate(key) + ": " + toHex2.transliterate(value));
}
}
// Now convert all those sets into linear arrays
// We can't do this in place in Java, so make a temporary target array
// Note: This could be transformed into a single array, with offsets into it.
// Might be best choice in C.
Map fromCaseFold2 = new HashMap();
Iterator it = fromCaseFold.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
Set s = (Set) fromCaseFold.get(key);
String[] temp = new String[s.size()];
s.toArray(temp);
fromCaseFold2.put(key, temp);
}
fromCaseFold = fromCaseFold2;
// We have processed everything, so the iterator will now work
// The following is normally OFF.
// It is here to generate (under the GENERATE flag) the static exception list.
// It must be at the very end of initialization, so that the iterator is functional.
// (easiest to do it that way)
if (GENERATE) {
// first get small set of items that have multiple characters
Set multichars = new TreeSet();
it = fromCaseFold.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
if (UTF16.countCodePoint(key) < 2) continue;
multichars.add(key);
}
// now we will go through each of them.
CaseIterator ci = new CaseIterator();
it = multichars.iterator();
while (it.hasNext()) {
String key = (String) it.next();
// here is a nasty complication. Take 'ffi' ligature. We
// can't just close it, since we would miss the combination
// that includes the 'fi' => "fi" ligature
// so first do a pass through, and add substring combinations
// we call this a 'partial closure'
Set partialClosure = new TreeSet();
partialClosure.add(key);
if (UTF16.countCodePoint(key) > 2) {
Iterator multiIt2 = multichars.iterator();
while (multiIt2.hasNext()) {
String otherKey = (String) multiIt2.next();
if (otherKey.length() >= key.length()) continue;
int pos = -1;
while (true) {
// The following is not completely general
// but works for the actual cased stuff,
// and should work for future characters, since we won't have
// more ligatures & other oddities.
pos = key.indexOf(otherKey, pos+1);
if (pos < 0) break;
int endPos = pos + otherKey.length();
// we know we have a proper substring,
// so get the combinations
String[] choices = (String[]) fromCaseFold.get(otherKey);
for (int ii = 0; ii < choices.length; ++ii) {
String patchwork = key.substring(0, pos)
+ choices[ii]
+ key.substring(endPos);
partialClosure.add(patchwork);
}
}
}
}
// now, for each thing in the partial closure, get its
// case closure and add it to the final result.
Set closure = new TreeSet(); // this will be the real closure
Iterator partialIt = partialClosure.iterator();
while (partialIt.hasNext()) {
String key2 = (String) partialIt.next();
ci.reset(key2);
for (String temp = ci.next(); temp != null; temp = ci.next()) {
closure.add(temp);
}
// form closure
/*String[] choices = (String[]) fromCaseFold.get(key2);
for (int i = 0; i < choices.length; ++i) {
ci.reset(choices[i]);
String temp;
while (null != (temp = ci.next())) {
closure.add(temp);
}
}
*/
}
// print it out, so that it can be cut and pasted back into this document.
Iterator it2 = closure.iterator();
System.out.println("\t// " + toName.transliterate(key));
System.out.print("\t{\"" + toHex.transliterate(key) + "\",");
while (it2.hasNext()) {
String item = (String)it2.next();
System.out.print("\"" + toHex.transliterate(item) + "\",");
}
System.out.println("},");
}
}
}
// ============ PRIVATE CLASS DATA ============
// pieces that we will put together
// is not changed during iteration
private int count = 0;
private String[][] variants;
// state information, changes during iteration
private boolean done = false;
private int[] counts;
// internal buffer for efficiency
private StringBuffer nextBuffer = new StringBuffer();
// ========================
/**
* Reset to different source. Once reset, the iteration starts from the beginning.
* @param source The string to get case variants for
*/
public void reset(String source) {
// allocate arrays to store pieces
// using length might be slightly too long, but we don't care much
counts = new int[source.length()];
variants = new String[source.length()][];
// walk through the source, and break up into pieces
// each piece becomes an array of equivalent values
// TODO: could optimized this later to coalesce all single string pieces
String piece = null;
count = 0;
for (int i = 0; i < source.length(); i += piece.length()) {
// find *longest* matching piece
String caseFold = null;
if (GENERATE) {
// do exactly one CP
piece = UTF16.valueOf(source, i);
caseFold = (String) toCaseFold.get(piece);
} else {
int max = i + maxLength;
if (max > source.length()) max = source.length();
for (int j = max; j > i; --j) {
piece = source.substring(i, j);
caseFold = (String) toCaseFold.get(piece);
if (caseFold != null) break;
}
}
// if we fail, pick one code point
if (caseFold == null) {
piece = UTF16.valueOf(source, i);
variants[count++] = new String[] {piece}; // single item string
} else {
variants[count++] = (String[])fromCaseFold.get(caseFold);
}
}
reset();
}
/**
* Restart the iteration from the beginning, but with same source
*/
public void reset() {
done = false;
for (int i = 0; i < count; ++i) {
counts[i] = 0;
}
}
/**
* Iterates through the case variants.
* @return next case variant. Each variant will case-fold to the same value as the source will.
* When the iteration is done, null is returned.
*/
public String next() {
if (done) return null;
int i;
// TODO Optimize so we keep the piece before and after the current position
// so we don't have so much concatenation
// get the result, a concatenation
nextBuffer.setLength(0);
for (i = 0; i < count; ++i) {
nextBuffer.append(variants[i][counts[i]]);
}
// find the next right set of pieces to concatenate
for (i = count-1; i >= 0; --i) {
counts[i]++;
if (counts[i] < variants[i].length) break;
counts[i] = 0;
}
// if we go too far, bail
if (i < 0) {
done = true;
}
return nextBuffer.toString();
}
/**
* Temporary test, just to see how the stuff works.
*/
static public void main(String[] args) {
String[] testCases = {"fiss", "h\u03a3"};
CaseIterator ci = new CaseIterator();
for (int i = 0; i < testCases.length; ++i) {
String item = testCases[i];
System.out.println();
System.out.println("Testing: " + toName.transliterate(item));
System.out.println();
ci.reset(item);
int count = 0;
for (String temp = ci.next(); temp != null; temp = ci.next()) {
System.out.println(toName.transliterate(temp));
count++;
}
System.out.println("Total: " + count);
}
// generate a list of all caseless characters -- characters whose
// case closure is themselves.
UnicodeSet caseless = new UnicodeSet();
for (int i = 0; i <= 0x10FFFF; ++i) {
String cp = UTF16.valueOf(i);
ci.reset(cp);
int count = 0;
String fold = null;
for (String temp = ci.next(); temp != null; temp = ci.next()) {
fold = temp;
if (++count > 1) break;
}
if (count==1 && fold.equals(cp)) {
caseless.add(i);
}
}
System.out.println("caseless = " + caseless.toPattern(true));
UnicodeSet not_lc = new UnicodeSet("[:^lc:]");
UnicodeSet a = new UnicodeSet();
a.set(not_lc);
a.removeAll(caseless);
System.out.println("[:^lc:] - caseless = " + a.toPattern(true));
a.set(caseless);
a.removeAll(not_lc);
System.out.println("caseless - [:^lc:] = " + a.toPattern(true));
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,67 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.translit;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import com.ibm.icu.dev.demo.impl.AppletFrame;
/**
* A simple Applet that shows a button. When pressed, the button
* shows the DemoAppletFrame. This Applet is meant to be embedded
* in a web page.
*
* <p>Copyright (c) IBM Corporation 1999. All rights reserved.
*
* @author Alan Liu
*/
public class DemoApplet extends Applet {
Demo frame = null;
private static final String COPYRIGHT =
"\u00A9 IBM Corporation 1999. All rights reserved.";
public static void main(String args[]) {
final DemoApplet applet = new DemoApplet();
new AppletFrame("Transliteration Demo", applet, 640, 480);
}
public void init() {
Button button = new Button("Transliteration Demo");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (frame == null) {
frame = new Demo(600, 200);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
frame = null;
}
});
}
frame.setVisible(true);
frame.toFront();
}
});
add(button);
Dimension size = button.getPreferredSize();
size.width += 10;
size.height += 10;
resize(size);
}
public void stop() {
if (frame != null) {
frame.dispose();
}
frame = null;
}
}

View file

@ -0,0 +1,171 @@
/**
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.translit;
/** VERY Basic Diff program. Compares two sequences of objects fed into it, and
* lets you know where they are different.
* @author Mark Davis
* @version 1.0
*/
final public class Differ {
public static final String copyright =
"Copyright (C) 2000, International Business Machines Corporation and others. All Rights Reserved.";
/**
* @param stackSize The size of the largest difference you expect.
* @param matchCount The number of items that have to be the same to count as a match
*/
public Differ(int stackSize, int matchCount) {
this.STACKSIZE = stackSize;
this.EQUALSIZE = matchCount;
a = new Object[stackSize+matchCount];
b = new Object[stackSize+matchCount];
}
public void add (Object aStr, Object bStr) {
addA(aStr);
addB(bStr);
}
public void addA (Object aStr) {
flush();
a[aCount++] = aStr;
}
public void addB (Object bStr) {
flush();
b[bCount++] = bStr;
}
public int getALine(int offset) {
return aLine + maxSame + offset;
}
public Object getA(int offset) {
if (offset < 0) return last;
if (offset > aTop-maxSame) return next;
return a[offset];
}
public int getACount() {
return aTop-maxSame;
}
public int getBCount() {
return bTop-maxSame;
}
public int getBLine(int offset) {
return bLine + maxSame + offset;
}
public Object getB(int offset) {
if (offset < 0) return last;
if (offset > bTop-maxSame) return next;
return b[offset];
}
public void checkMatch(boolean finalPass) {
// find the initial strings that are the same
int max = aCount;
if (max > bCount) max = bCount;
int i;
for (i = 0; i < max; ++i) {
if (!a[i].equals(b[i])) break;
}
// at this point, all items up to i are equal
maxSame = i;
aTop = bTop = maxSame;
if (maxSame > 0) last = a[maxSame-1];
next = "";
if (finalPass) {
aTop = aCount;
bTop = bCount;
next = "";
return;
}
if (aCount - maxSame < EQUALSIZE || bCount - maxSame < EQUALSIZE) return;
// now see if the last few a's occur anywhere in the b's, or vice versa
int match = find (a, aCount-EQUALSIZE, aCount, b, maxSame, bCount);
if (match != -1) {
aTop = aCount-EQUALSIZE;
bTop = match;
next = a[aTop];
return;
}
match = find (b, bCount-EQUALSIZE, bCount, a, maxSame, aCount);
if (match != -1) {
bTop = bCount-EQUALSIZE;
aTop = match;
next = b[bTop];
return;
}
if (aCount >= STACKSIZE || bCount >= STACKSIZE) {
// flush some of them
aCount = (aCount + maxSame) / 2;
bCount = (bCount + maxSame) / 2;
next = "";
}
}
/** Convenient utility
* finds a segment of the first array in the second array.
* @return -1 if not found, otherwise start position in b
*/
public int find (Object[] a, int aStart, int aEnd, Object[] b, int bStart, int bEnd) {
int len = aEnd - aStart;
int bEndMinus = bEnd - len;
tryA:
for (int i = bStart; i <= bEndMinus; ++i) {
for (int j = 0; j < len; ++j) {
if (!b[i + j].equals(a[aStart + j])) continue tryA;
}
return i; // we have a match!
}
return -1;
}
// ====================== PRIVATES ======================
private void flush() {
if (aTop != 0) {
int newCount = aCount-aTop;
System.arraycopy(a, aTop, a, 0, newCount);
aCount = newCount;
aLine += aTop;
aTop = 0;
}
if (bTop != 0) {
int newCount = bCount-bTop;
System.arraycopy(b, bTop, b, 0, newCount);
bCount = newCount;
bLine += bTop;
bTop = 0;
}
}
private int STACKSIZE;
private int EQUALSIZE;
private Object [] a;
private Object [] b;
private Object last = "";
private Object next = "";
private int aCount = 0;
private int bCount = 0;
private int aLine = 1;
private int bLine = 1;
private int maxSame = 0, aTop = 0, bTop = 0;
}

View file

@ -0,0 +1,52 @@
/**
*******************************************************************************
* Copyright (C) 2001-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.translit;
import java.awt.event.*;
import java.awt.*;
public class InfoDialog extends Dialog {
protected Button button;
protected TextArea area;
protected Dialog me;
protected Panel bottom;
public TextArea getArea() {
return area;
}
public Panel getBottom() {
return bottom;
}
InfoDialog(Frame parent, String title, String label, String message) {
super(parent, title, false);
me = this;
this.setLayout(new BorderLayout());
if (label.length() != 0) {
this.add("North", new Label(label));
}
area = new TextArea(message, 8, 80, TextArea.SCROLLBARS_VERTICAL_ONLY);
this.add("Center", area);
button = new Button("Hide");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
me.hide();
}
});
bottom = new Panel();
bottom.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
bottom.add(button);
this.add("South", bottom);
this.pack();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
me.hide();
}
});
}
}

View file

@ -0,0 +1,24 @@
#--------------------------------------------------------------------
# Copyright (c) 1999-2004, International Business Machines
# Corporation and others. All Rights Reserved.
#--------------------------------------------------------------------
@UPPERFILTER@
ما هي الشفرة الموحدة "يونِكود" ؟
أساسًا، تتعامل الحواسيب فقط مع الأرقام، وتقوم بتخزين الأحرف والمحارف الأخرى بعد أن تُعطي رقما معينا لكل واحد منها. وقبل اختراع "يونِكود"، كان هناك مئات الأنظمة للتشفير وتخصيص هذه الأرقام للمحارف، ولم يوجد نظام تشفير واحد يحتوي على جميع المحارف الضرورية. وعلى سبيل المثال، فإن الاتحاد الأوروبي لوحده، احتوى العديد من الشفرات المختلفة ليغطي جميع اللغات المستخدمة في الاتحاد. وحتى لو اعتبرنا لغة واحدة، كاللغة الإنجليزية، فإن جدول شفرة واحد لم يكف لاستيعاب جميع الأحرف وعلامات الترقيم والرموز الفنية والعلمية الشائعة الاستعمال.
وتجدر الملاحظة أن أنظمة التشفير المختلفة تتعارض مع بعضها البعض. وبعبارة أخرى، يمكن أن يستخدِم جدولي شفرة نفس الرقم لتمثيل محرفين مختلفين، أو رقمين مختلفين لتمثيل نفس المحرف. ولو أخذنا أي جهاز حاسوب، وبخاصة جهاز النادل (server)، فيجب أن تكون لديه القدرة على التعامل مع عدد كبير من الشفرات المختلفة، ويتم تصميمه على هذا الأساس. ومع ذلك، فعندما تمر البيانات عبر أنظمة مختلفة، توجد هناك خطورة لضياع أو تحريف بعض هذه البيانات.
"يونِكود" تغير هذا كليا !
تخصص الشفرة الموحدة "يونِكود" رقما وحيدا لكل محرف في جميع اللغات العالمية، وذلك بغض النظر عن نوع الحاسوب أو البرامج المستخدمة. وقد تم تبني مواصفة "يونِكود" من قبل قادة الصانعين لأنظمة الحواسيب في العالم، مثل شركات آي.بي.إم. (IBM)، أبل (APPLE)، هِيْولِت باكرد (Hewlett-Packard) ، مايكروسوفت (Microsoft)، أوراكِل (Oracle) ، صن (Sun) وغيرها. كما أن المواصفات والمقاييس الحديثة (مثل لغة البرمجة "جافا" "JAVA" ولغة "إكس إم إل" "XML" التي تستخدم لبرمجة الانترنيت) تتطلب استخدام "يونِكود". علاوة على ذلك ، فإن "يونِكود" هي الطريقة الرسمية لتطبيق المقياس العالمي إيزو ١٠٦٤٦ (ISO 10646) .
إن بزوغ مواصفة "يونِكود" وتوفُّر الأنظمة التي تستخدمه وتدعمه، يعتبر من أهم الاختراعات الحديثة في عولمة البرمجيات لجميع اللغات في العالم. وإن استخدام "يونِكود" في عالم الانترنيت سيؤدي إلى توفير كبير مقارنة مع استخدام المجموعات التقليدية للمحارف المشفرة. كما أن استخدام "يونِكود" سيُمكِّن المبرمج من كتابة البرنامج مرة واحدة، واستخدامه على أي نوع من الأجهزة أو الأنظمة، ولأي لغة أو دولة في العالم أينما كانت، دون الحاجة لإعادة البرمجة أو إجراء أي تعديل. وأخيرا، فإن استخدام "يونِكود" سيمكن البيانات من الانتقال عبر الأنظمة والأجهزة المختلفة دون أي خطورة لتحريفها، مهما تعددت الشركات الصانعة للأنظمة واللغات، والدول التي تمر من خلالها هذه البيانات.
@SET [[[:Arabic:] & [\u0600-\u06FF]] [\u060C\u061B\u061F\u0640\u064B-\u0655\u0660-\u066C\u06F0-\u06F9]]

View file

@ -0,0 +1,73 @@
#--------------------------------------------------------------------
# Copyright (c) 1999-2004, International Business Machines
# Corporation and others. All Rights Reserved.
#--------------------------------------------------------------------
Τι είναι το Unicode?
Η κωδικοσελίδα Unicode προτείνει έναν και μοναδικό αριθμό για κάθε χαρακτήρα, ανεξάρτητα από το λειτουργικό σύστημα, ανεξάρτητα από το λογισμικό, ανεξάρτητα από την γλώσσα.
Οι ηλεκτρονικοί υπολογιστές, σε τελική ανάλυση, χειρίζονται απλώς αριθμούς. Αποθηκεύουν γράμματα και άλλους χαρακτήρες αντιστοιχώντας στο καθένα τους από έναν αριθμό (ονομάζουμε μία τέτοια αντιστοιχία κωδικοσελίδα). Πριν την εφεύρεση του Unicode, υπήρχαν εκατοντάδες διαφορετικές κωδικοσελίδες. Λόγω περιορισμών μεγέθους όμως, σε καμία κωδικοσελίδα δεν χωρούσαν αρκετοί χαρακτήρες: λόγου χάριν, η Ευρωπαϊκή Ένωση χρειαζόταν πλήθος διαφορετικών κωδικοσελίδων για να καλύψει όλες τις γλώσσες των χωρών-μελών της. Ακόμα και για μία και μόνη γλώσσα, όπως π.χ. τα Αγγλικά, μία κωδικοσελίδα δεν επαρκούσε για να καλύψει όλα τα γράμματα, σημεία στίξης και τεχνικά σύμβολα ευρείας χρήσης.
Εκτός αυτού, οι κωδικοσελίδες αυτές διαφωνούσαν μεταξύ τους. Έτσι, δύο κωδικοσελίδες μπορούσαν κάλλιστα να χρησιμοποιούν τον ίδιο αριθμό για δύο διαφορετικούς χαρακτήρες, ή να χρησιμοποιούν διαφορετικούς αριθμούς για τον ίδιο χαρακτήρα. Κάθε υπολογιστής (και ιδίως εάν ήταν διακομιστής) έπρεπε να υποστηρίζει πλήθος διαφορετικών κωδικοσελίδων· ταυτόχρονα κάθε φορά που δεδομένα μεταφέρονταν μεταξύ διαφορετικών κωδικοσελίδων ή λειτουργικών συστημάτων, τα δεδομένα αυτά κινδύνευαν να αλλοιωθούν.
Το Unicode αλλάζει αυτή την κατάσταση!
Το Unicode προτείνει έναν μοναδικό αριθμό για κάθε χαρακτήρα, ανεξάρτητα από το λειτουργικό σύστημα, ανεξάρτητα από το λογισμικό, ανεξάρτητα από την γλώσσα. Την κωδικοσελίδα Unicode έχουν ασπασθεί κορυφαίοι παράγοντες του χώρου των λογισμικών όπως οι: Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys και πολλοί άλλοι. Το Unicode απαιτούν πολλές σύγχρονες τυποποιήσεις όπως οι: XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML, κ.λπ., και είναι η επίσημη μέθοδος εφαρμογής της τυποποίησης ISO/IEC 10646. Υποστηρίζεται από πολλά λειτουργικά συστήματα, όλους τους σύχρονους περιηγητές Διαδικτύου, και πολλά άλλα προϊόντα. Η εμφάνιση της κωδικοσελίδας Unicode, και η διαθεσιμότητα εργαλείων που να την υποστηρίζουν είναι από τις σημαντικότερες εξελίξεις της πρόσφατης τεχνολογίας λογισμικών.
Η ενσωμάτωση του Unicode σε εφαρμογές πελάτη-διακομιστή ή "multi-tiered" προσφέρει σημαντικές οικονομίες σε σχέση με τις ως τώρα υπάρχουσες κωδικοσελίδες. Χάρις στο Unicode ένα και μόνο προϊόν ή μία και μόνη τοποθεσία Διαδικτύου μπορεί να επικοινωνεί με διάφορα λειτουργικά συστήματα, σε διάφορες γλώσσες και χώρες, χωρίς την ανάγκη επαναπρογραμματισμού. Γίνεται έτσι δυνατή η μεταφορά δεδομένων ανάμεσα σε πλήθος διαφορετικών συστημάτων δίχως κίνδυνο αλλοίωσης.
Σχετικά με το Κονσόρτιουμ Unicode
Tο Κονσόρτιουμ Unicode είναι ένας κοινωφελής οργανισμός· ιδρύθηκε για να αναπτύξει, να επεκτείνει και να μεταδώσει την χρήση της κωδικοσελίδας Unicode που καθορίζει την αναπαράσταση κειμένου σε σύγχρονα λογισμικά προϊόντα και τυποποιήσεις. Μεγάλος αριθμός εταιρειών και οργανισμών της διεθνούς βιομηχανίας υπολογιστών και λογισμικών είναι μέλη του Κονσόρτιουμ Unicode. Το Κονσόρτιουμ χρηματοδοτείται μόνο από τις συνδρομές των μελών του. Μέλος του κονσόρτιουμ Unicode μπορεί να γίνει οιοσδήποτε (οργανισμός, εταιρεία ή ιδιώτης, οπουδήποτε στον κόσμο) που να υποστηρίζει την κωδικοσελίδα Unicode και να επιθυμεί να συνδράμει στην επέκταση και στην εφαρμογή της.
Για περαιτέρω πληροφορίες, βλέπε τις εξής ιστοσελίδες: Γλωσσάρι, Δείγματα προϊόντων συμβατών με το Unicode, Τεχνική Εισαγωγή και Χρήσιμες πηγές πληροφοριών.
(ANCIENT)
ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν:
πολλῶν δ’ ἀνθρώπων ἴδεν ἄστεα καὶ νόον ἔγνω,
πολλὰ δ’ ὅ γ ἐν πόντῳ πάθεν ἄλγεα ὃν κατὰ θυμόν,
ἀρνύμενος ἥν τε ψυχὴν καὶ νόστον ἑταίρων.
ἀλλ’ οὐδ’ ὣς ἑτάρους ἐρρύσατο, ἱέμενός περ:
αὐτῶν γὰρ σφετέρῃσιν ἀτασθαλίῃσιν ὄλοντο,
νήπιοι, οἳ κατὰ βοῦς Ὑπερίονος Ἠελίοιο
ἤσθιον: αὐτὰρ ὁ τοῖσιν ἀφείλετο νόστιμον ἦμαρ.
τῶν ἁμόθεν γε, θεά, θύγατερ Διός, εἰπὲ καὶ ἡμῖν.
*
ἔνθ’ ἄλλοι μὲν πάντες, ὅσοι φύγον αἰπὺν ὄλεθρον,
οἴκοι ἔσαν, πόλεμόν τε πεφευγότες ἠδὲ θάλασσαν:
τὸν δ’ οἶον νόστου κεχρημένον ἠδὲ γυναικὸς
νύμφη πότνι’ ἔρυκε Καλυψὼ δῖα θεάων
ἐν σπέσσι γλαφυροῖσι, λιλαιομένη πόσιν εἶναι.
ἀλλ’ ὅτε δὴ ἔτος ἦλθε περιπλομένων ἐνιαυτῶν,
τῷ οἱ ἐπεκλώσαντο θεοὶ οἶκόνδε νέεσθαι
εἰς Ἰθάκην, οὐδ’ ἔνθα πεφυγμένος ἦεν ἀέθλων
καὶ μετὰ οἷσι φίλοισι. θεοὶ δ’ ἐλέαιρον ἅπαντες
νόσφι Ποσειδάωνος: ὁ δ’ ἀσπερχὲς μενέαινεν
ἀντιθέῳ Ὀδυσῆι πάρος ἣν γαῖαν ἱκέσθαι.
*
ἀλλ’ ὁ μὲν Αἰθίοπας μετεκίαθε τηλόθ’ ἐόντας,
Αἰθίοπας τοὶ διχθὰ δεδαίαται, ἔσχατοι ἀνδρῶν,
οἱ μὲν δυσομένου Ὑπερίονος οἱ δ’ ἀνιόντος,
ἀντιόων ταύρων τε καὶ ἀρνειῶν ἑκατόμβης.
ἔνθ’ ὅ γ ἐτέρπετο δαιτὶ παρήμενος: οἱ δὲ δὴ ἄλλοι
Ζηνὸς ἐνὶ μεγάροισιν Ὀλυμπίου ἁθρόοι ἦσαν.
τοῖσι δὲ μύθων ἦρχε πατὴρ ἀνδρῶν τε θεῶν τε:
μνήσατο γὰρ κατὰ θυμὸν ἀμύμονος Αἰγίσθοιο,
τόν ῥ’ Ἀγαμεμνονίδης τηλεκλυτὸς ἔκταν’ Ὀρέστης:
τοῦ ὅ γ ἐπιμνησθεὶς ἔπε’ ἀθανάτοισι μετηύδα:
*
“ὢ πόποι, οἷον δή νυ θεοὺς βροτοὶ αἰτιόωνται:
ἐξ ἡμέων γάρ φασι κάκ’ ἔμμεναι, οἱ δὲ καὶ αὐτοὶ
σφῇσιν ἀτασθαλίῃσιν ὑπὲρ μόρον ἄλγε’ ἔχουσιν,
ὡς καὶ νῦν Αἴγισθος ὑπὲρ μόρον Ἀτρεί̈δαο
γῆμ’ ἄλοχον μνηστήν, τὸν δ’ ἔκτανε νοστήσαντα,
εἰδὼς αἰπὺν ὄλεθρον, ἐπεὶ πρό οἱ εἴπομεν ἡμεῖς,
Ἑρμείαν πέμψαντες, ἐύσκοπον ἀργεϊφόντην,
μήτ’ αὐτὸν κτείνειν μήτε μνάασθαι ἄκοιτιν:
ἐκ γὰρ Ὀρέσταο τίσις ἔσσεται Ἀτρεί̈δαο,
ὁππότ’ ἂν ἡβήσῃ τε καὶ ἧς ἱμείρεται αἴης.
ὣς ἔφαθ’ Ἑρμείας, ἀλλ’ οὐ φρένας Αἰγίσθοιο
πεῖθ’ ἀγαθὰ φρονέων: νῦν δ’ ἁθρόα πάντ’ ἀπέτισεν.”
@SET [[[:Greek:]&[\u0370-\u03E1 \u03F0-\u03FF]] [\:-;?\u00B7\u037E\u0387]]

View file

@ -0,0 +1,26 @@
#--------------------------------------------------------------------
# Copyright (c) 1999-2004, International Business Machines
# Corporation and others. All Rights Reserved.
#--------------------------------------------------------------------
@UPPERFILTER@
什么是Unicode(统一码)?
Unicode给每个字符提供了一个唯一的数字
不论是什么平台,
不论是什么程序,
不论是什么语言。
基本上计算机只是处理数字。它们指定一个数字来储存字母或其他字符。在创造Unicode之前有数百种指定这些数字的编码系统。没有一个编码可以包含足够的字符例如单单欧州共同体就需要好几种不同的编码来包括所有的语言。即使是单一种语言例如英语也没有哪一个编码可以适用于所有的字母标点符号和常用的技术符号。
这些编码系统也会互相冲突。也就是说,两种编码可能使用相同的数字代表两个不同的字符,或使用不同的数字代表相同的字符。任何一台特定的计算机(特别是服务器)都需要支持许多不同的编码,但是,不论什么时候数据通过不同的编码或平台之间,那些数据总会有损坏的危险。
Unicode正在改变所有这一切
Unicode给每个字符提供了一个唯一的数字不论是什么平台不论是什么程序不论什么语言。Unicode标准已经被这些工业界的领导们所采用例如Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys和其它许多公司。最新的标准都需要Unicode例如XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML等等并且Unicode是实现ISO/IEC 10646的正规方式。许多操作系统所有最新的浏览器和许多其他产品都支持它。Unicode标准的出现和支持它工具的存在是近来全球软件技术最重要的发展趋势。
将Unicode与客户服务器或多层应用程序和网站结合比使用传统字符集节省费用。Unicode使单一软件产品或单一网站能够贯穿多个平台语言和国家而不需要重建。它可将数据传输到许多不同的系统而无损坏。
关于Unicode学术学会
Unicode学术学会是一个非盈利的组织是为发展扩展和推广使用Unicode标准而建立的Unicode学术学会设立了现代软件产品和标准文本的表示法。学术学会的会员代表了广泛领域的计算机和资讯工业的公司和组织。学术学会只由会员提供资金。Unicode学术学会的会员资格开放给世界上任何支持Unicode标准和希望协助其扩展和执行的组织及个人。
欲知更多信息请参阅术语词汇表Unicode产品样本技术简介和参考资料。
Chinese translation by 黎國珍, Xerox

View file

@ -0,0 +1,26 @@
#--------------------------------------------------------------------
# Copyright (c) 1999-2004, International Business Machines
# Corporation and others. All Rights Reserved.
#--------------------------------------------------------------------
@UPPERFILTER@
מה זה יוניקוד (Unicode)?
יוניקוד מקצה מספר ייחודי לכל תו,
לא משנה על איזו פלטפורמה,
לא משנה באיזו תוכנית,
ולא משנה באיזו שפה.
באופן בסיסי, מחשבים עוסקים רק במספרים. הם מאחסנים אותיות ותווים אחרים על-ידי הקצאת מספר לכל אחד מהם. בטרם הומצא היוניקוד, היו מאות מערכות קידוד שונות להקצאת המספרים הללו. אף לא אחת מהן יכלה להכיל כמות תווים מספקת. לדוגמא: רק לאיחוד האירופאי נדרשים כמה סוגי קידודים שונים על מנת לכסות את כל השפות המדוברות בו. יתירה מזאת אף לשפה בודדת, כמו אנגלית למשל, לא היה די במערכת קידוד אחת בעבור כל האותיות, סימני הפיסוק והסמלים הטכניים שבשימוש שוטף.
מערכות קידוד אלו אף סותרות זו את זו. כלומר, שני קידודים יכולים להשתמש באותו מספר לשני תוים נבדלים, או להשתמש במספרים שונים לאותו תו. על כל מחשב (ובמיוחד שרתים) לתמוך במספר רב של מערכות קידוד שונות; אולם כל אימת שנתונים עוברים בין מערכות קידוד או פלטפורמות שונות קיים הסיכון שייפגמו.
יוניקוד משנה את כל זה!
יוניקוד מקצה מספר ייחודי לכל תו, ללא תלות בפלטפורמה, בתוכנית, או בשפה. תקן היוניקוד אומץ על-ידי המובילים בתעשייה כמו Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys ורבים אחרים. יוניקוד נדרש על-ידי תקנים מודרניים כמו XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML וכדומה, ומהווה למעשה את היישום הרשמי של תקן ISO/IEC 10646. הוא נתמך על ידי מערכות הפעלה רבות, כל הדפדפנים החדישים, ומוצרים רבים אחרים. הופעת תקן היוניקוד וזמינות הכלים התומכים בו נמנות עם המגמות הכלל-עולמיות החשובות ביותר, אשר מסתמנות לאחרונה בטכנולוגיית התוכנה.
שילוב יוניקוד ביישומי שרת-לקוח או ביישומים רבי-שכבות ובאתרי אינטרנט מאפשר חיסכון ניכר בעלויות לעומת השימוש בסדרות התווים המסורתיות. הודות ליוניקוד, מוצר תוכנה אחד או אתר יחיד ברשת יכול להרחיב את יעדיו למגוון פלטפורמות, ארצות ושפות ללא צורך בשינויים מרחיקים. יוניקוד מאפשר מעבר נתונים דרך מערכות רבות ושונות מבלי שייפגמו.
פרטים אודות הקונסורציום של יוניקוד (Unicode Consortium)
הקונסורציום של יוניקוד הוא ארגון ללא מטרת רווח שנוסד כדי לפתח, להרחיב ולקדם את השימוש בתקן יוניקוד, אשר מגדיר את ייצוג הטקסט במוצרי תוכנה ותקנים מודרניים. חברים בקונסורציום מגוון רחב של תאגידים וארגונים בתעשיית המחשבים ועיבוד המידע. הקונסורציום ממומן על-ידי דמי-חבר בלבד. החברות בקונסורציום יוניקוד פתוחה לארגונים ולאנשים פרטיים, בכל רחבי העולם, אשר תומכים בתקן יוניקוד ומעוניינים לסייע בהתפתחותו והטמעתו.
למידע נוסף, ראה מילון מונחים, רשימה חלקית של מוצרים מותאמים ליוניקוד, מבוא טכני ו- חומרי עזר [קישורים באנגלית].
@SET [[:Hebrew:] [\u05B0-\u05B9\u05BB-\u05BC\u05C1-\u05C2\u2135-\u2138]]

View file

@ -0,0 +1,163 @@
<!--
/**
*******************************************************************************
* Copyright (C) 2002-2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
-->
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>New Transliteration Test Files</title>
</head>
<body bgcolor="#FFFFFF">
<h2>New Transliteration Test Files</h2>
<p>The Test_*.html files show the transliteration of characters for given
languages. The sample for each language consists of &quot;What Is Unicode&quot;
in Thai, followed by other available text. The text is broken apart into
sentences for ease of viewing (note: we know of some problems with the sentence
rules for Japanese and Chinese). The left column is the original, and the right
is the romanization. The program also converts back to the original script. If
there is a discrepancy between the source and the reverse transformation, that
is indicated by making the background <font color="#FF0000"><b>red</b></font>
from that point on.</p>
<blockquote>
<p><i><b>Note: </b>If you have some more text that you would like added to the
sample, just let me know. I am particularly interested in name lists, since
they are the typical source.</i></p>
</blockquote>
<h3>Standards</h3>
<p>The goal is to follow a given standard, such as ISO* or UNGEGN wherever
possible. We also need to round-trip, so in some cases, that means adding some
additional accent marks to disambiguate characters. And often the source
standards are missing some characters, such as characters with combining Hamzas
in Arabic. Remember that the goal for these is transliteration (unambiguously
representing all the letters in the original), not transcription (representing
the best pronunciation).</p>
<ul>
<li><b><a href="Test_Thai-Latin.html">Thai</a>:</b> ISO 11940 &lt; <a href="http://homepage.mac.com/sirbinks/pdf/Thai.r2.pdf">http://homepage.mac.com/sirbinks/pdf/Thai.r2.pdf</a>
&gt; plus a few items:
<ul>
<li>Accents may be added to the Latin for disambiguation.</li>
<li>In the next release, we'd like to do the UNGEGN version &lt; <a href="http://www.eki.ee/wgrs/rom1_th.pdf">http://www.eki.ee/wgrs/rom1_th.pdf</a>
&gt; which is probably more useful (and readable), and follows more
closely the Thai standard.</li>
<li>Spaces are provided at word-breaks, using the Thai BreakIterator.</li>
<li>An inherent vowel (&#7885;) is added, as in UNGEGN. The dot is for
disambiguation.
<ul>
<li><i>Note: if the inherent vowel positions cannot be algorithmically
determined, let me know and I will remove them.</i></li>
</ul>
</li>
</ul>
</li>
<li><b><a href="Test_Arabic-Latin.html">Arabic</a>: </b>Generally follows
UNGEGN &lt; <a href="http://www.eki.ee/wgrs/rom1_ar.pdf">http://www.eki.ee/wgrs/rom1_ar.pdf</a>
&gt;
<ul>
<li>Accents may be added to the Latin for disambiguation.</li>
<li>Occasionally deviates in the direction of ISO 233 &lt; <a href="http://homepage.mac.com/sirbinks/pdf/Arabic.pdf">http://homepage.mac.com/sirbinks/pdf/Arabic.pdf</a>
&gt;
<ul>
<li>with underdot instead of cedilla for letter like SAD, since those
are explicitly in Unicode for transliteration of Arabic</li>
<li>adding extra non-Arabic-language letters, like PEH. Note: not all
extended Arabic characters are handled yet.</li>
</ul>
</li>
<li>Does <i>not</i> do assimilation of &quot;al&quot;, nor hyphenation of
it.
<ul>
<li>While it could be done, we need to determine whether a prefix
&quot;al&quot; could occur other than as the definite article (since
no space is used).</li>
</ul>
</li>
<li>This is transliteration. For <i>transcription</i> one would want an
engine that added points appropriately to the Hebrew.</li>
</ul>
</li>
<li><b><a href="Test_Hebrew-Latin.html">Hebrew</a></b><b>: </b>Generally
follows UNGEGN &lt; <a href="http://www.eki.ee/wgrs/rom1_he.pdf">http://www.eki.ee/wgrs/rom1_he.pdf</a>
&gt;, with some exceptions:
<ul>
<li>Accents may be added to the Latin for disambiguation.</li>
<li>Combinations of dagesh, shin/sin dot that would produce different
letters are not yet called out.</li>
<li>Note that the final forms are not preserved. Thus, when going from
Latin to Hebrew, a character is given final form depending on its
position.
<ul>
<li>E.g. &#1502;&#1501;&#1502;&#1501; =&gt; mmmm =&gt;
&#1502;&#1502;&#1502;&#1501;</li>
</ul>
</li>
<li>This is transliteration. For <i>transcription</i> one would want an
engine that added points appropriately to the Hebrew.</li>
<li>See also &lt; <a href="http://homepage.mac.com/sirbinks/pdf/Hebrew.r1.pdf">http://homepage.mac.com/sirbinks/pdf/Hebrew.r1.pdf</a>
&gt; for the ISO version. The Chicago Manual of Style has a clear table
of mappings for the vowel marks.</li>
</ul>
</li>
<li><b><a href="Test_Han-Latin.html">Han</a>:</b> Uses the <a href="http://www.mandarintools.com/cedict.html">CEDICT</a>
data plus Unicode Unihan <i>kMandarin</i> values for pinyin. Doesn't
roundtrip!
<ul>
<li><i>Note: </i>the Chinese pronunciation of Han characters varies by
context and grammar, though nowhere near as much a Japanese.
<ul>
<li>Ideally we'd have an underlying engine for this. In 2.4 we will
have a plug-in interface so that people could add one, such as the
IBM engine.</li>
<li>The data from CEDICT and Unihan don't list the most frequent
choice first, so we will be updating that.</li>
</ul>
</li>
</ul>
</li>
<li><a href="Test_Greek-Latin_UNGEGN.html"><b>Greek/UNGEGN</b></a>: Uses a
modern Greek transliteration, based on the UNGEGN rules at &lt; <a href="http://www.eki.ee/wgrs/rom1_el.pdf">http://www.eki.ee/wgrs/rom1_el.pdf</a>
&gt;. This version will not roundtrip ancient Greek.</li>
<li><a href="Test_Greek-Latin.html"><b>Greek</b></a>: Uses a classic Greek
transliteration. This version will not roundtrip modern Greek.</li>
</ul>
<h3><b>Notes</b></h3>
<ol>
<li>For readability, the files have a few other things besides just the
transliteration:
<ul>
<li>The first word of the sentences are titlecased, as are names (where we
have a name-list, such as in Thai).</li>
<li>The Latin in the original is mapped to the private-use zone before
conversion, and then again after conversion. This does have the downside
that any rules (such as in Han) that need to know the context (e.g. for
inserting spaces or capitalization) will gum up a little bit. This is
just an artifact of the test display.</li>
</ul>
</li>
<li>I don't think that ISO 11940 is a particularly good way to romanize, but
it is at least complete and a standard. So what I am interested in just for
now is whether the samples in the file follow it (with the above
exceptions).</li>
<li>Some of the files also have a set of characters at the end, one character
per row, with a following row listing the hex and name.</li>
<li>The source rules for all of these is in the following URL. So if you want
to know the details of how the characters are handled, that is the place to
look.
<ul>
<li><a href="http://dev.icu-project.org/cgi-bin/viewcvs.cgi/icu/source/data/translit/">http://dev.icu-project.org/cgi-bin/viewcvs.cgi/icu/source/data/translit/</a></li>
</ul>
</li>
</ol>
</body>
</html>

View file

@ -0,0 +1,69 @@
#--------------------------------------------------------------------
# Copyright (c) 1999-2004, International Business Machines
# Corporation and others. All Rights Reserved.
#--------------------------------------------------------------------
@UPPERFILTER@
Unicode คืออะไร?
Unicode กำหนดหมายเลขเฉพาะสำหรับทุกอักขระ
โดยไม่สนใจว่าเป็นแพล็ตฟอร์มใด
ไม่ขึ้นกับว่าจะเป็นโปรแกรมใด
และไม่ว่าจะเป็นภาษาใด
โดยพื้นฐานแล้ว, คอมพิวเตอร์จะเกี่ยวข้องกับเรื่องของตัวเลข. คอมพิวเตอร์จัดเก็บตัวอักษรและอักขระอื่นๆ โดยการกำหนดหมายเลขให้สำหรับแต่ละตัว. ก่อนหน้าที่๊ Unicode จะถูกสร้างขึ้น, ได้มีระบบ encoding อยู่หลายร้อยระบบสำหรับการกำหนดหมายเลขเหล่านี้. ไม่มี encoding ใดที่มีจำนวนตัวอักขระมากเพียงพอ: ยกตัวอย่างเช่น, เฉพาะในกลุ่มสหภาพยุโรปเพียงแห่งเดียว ก็ต้องการหลาย encoding ในการครอบคลุมทุกภาษาในกลุ่ม. หรือแม้แต่ในภาษาเดี่ยว เช่น ภาษาอังกฤษ ก็ไม่มี encoding ใดที่เพียงพอสำหรับทุกตัวอักษร, เครื่องหมายวรรคตอน และสัญลักษณ์ทางเทคนิคที่ใช้กันอยู่ทั่วไป.
ระบบ encoding เหล่านี้ยังขัดแย้งซึ่งกันและกัน. นั่นก็คือ, ในสอง encoding สามารถใช้หมายเลขเดียวกันสำหรับตัวอักขระสองตัวที่แตกต่างกัน,หรือใช้หมายเลขต่างกันสำหรับอักขระตัวเดียวกัน. ในระบบคอมพิวเตอร์ (โดยเฉพาะเซิร์ฟเวอร์) ต้องมีการสนับสนุนหลาย encoding; และเมื่อข้อมูลที่ผ่านไปมาระหว่างการเข้ารหัสหรือแพล็ตฟอร์มที่ต่างกัน, ข้อมูลนั้นจะเสี่ยงต่อการผิดพลาดเสียหาย.
Unicode จะเปลี่ยนแปลงสิ่งเหล่านั้นทั้งหมด!
Unicode กำหนดหมายเลขเฉพาะสำหรับแต่ละอักขระ, โดยไม่สนใจว่าเป็นแพล็ตฟอร์มใด, ไม่ขึ้นกับว่าจะเป็นโปรแกรมใดและไม่ว่าจะเป็นภาษาใด. มาตรฐาน Unicode ได้ถูกนำไปใช้โดยผู้นำในอุตสาหกรรม เช่น Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys และอื่นๆ อีกมาก. Unicode เป็นสิ่งที่จำเป็นสำหรับมาตรฐานใหม่ๆ เช่น XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML ฯลฯ., และเป็นแนวทางอย่างเป็นทางการในการทำ ISO/IEC 10646. Unicode ได้รับการสนับสนุนในระบบปฏิบัติการจำนวนมาก, บราวเซอร์ใหม่ๆ ทกตัว, และผลิตภัณฑ์อื่นๆ อีกมาก. การเกิดขึ้นของ Unicode Standard และทูลส์ต่างๆ ที่มีในการสนับสนุน Unicode, เป็นหนึ่งในแนวโน้มทางเทคโนโลยีซอฟต์แวร์ระดับโลกที่มีความสำคัญที่สุด.
การรวม Unicode เข้าไปในระบบไคลเอ็นต์-เซิร์ฟเวอร์ หรือแอ็พพลิเคชันแบบ multi-tiered และเว็บไซต์ จะทำให้เกิดการประหยัดค่าใช้จ่ายมากกว่าการใช้ชุดอักขระแบบเดิม. Unicode ทำให้ผลิตภัณฑ์ซอฟต์แวร์หนึ่งเดียว หรือเว็บไซต์แห่งเดียว รองรับได้หลายแพล็ตฟอร์ม, หลายภาษาและหลายประเทศโดยไม่ต้องทำการรื้อปรับระบบ. Unicode ยังทำให้ข้อมูลสามารถเคลื่อนย้ายไปมาในหลายๆ ระบบโดยไม่เกิดความผิดพลาดเสียหาย.
เกี่ยวกับ Unicode Consortium
Unicode Consortium เป็นองค์กรไม่แสวงหากำไรที่ก่อตั้งขึ้นเพื่อพัฒนา, ขยายและส่งเสริมการใช้ Unicode Standard, ซึ่งกำหนดรูปแบบการแทนค่าของข้อความในผลิตภัณฑ์ซอฟต์แวร์และมาตรฐานใหม่ๆ. สมาชิกของสมาคมเป็นตัวแทนจากบริษัทและองค์กรในอุตสาหกรรมคอมพิวเตอร์และการประมวลผลสารสนเทศ. สมาคมได้รับการสนับสนุนทางการเงินผ่านทางค่าธรรมเนียมของการเป็นสมาชิกเท่านั้น. สมาชิกภาพของ Unicode Consortium เปิดกว้างสำหรับองค์กรหรือบุคคลใดๆ ในโลกที่ต้องการสนับสนุน Unicode Standard และช่วยเหลือการขยายตัวและการนำ Unicode ไปใช้งาน.
สำหรับข้อมูลเพิ่มเติม, ให้ดูที่ Glossary, Sample Unicode-Enabled Products, Technical Introduction และ Useful Resources.
เป็นมนุษย์สุดประเสริฐเลิศคุณค่า
กว่าบรรดาฝูงสัตว์เดรัจฉาน
จงฝ่าฟันพัฒนาวิชาการ
อย่าล้างผลาญฤๅเข่นฆ่าบีฑาใคร
ไม่ถือโทษโกรธแช่งซัดฮึดฮัดด่า
หัดอภัยเหมือนกีฬาอัชฌาสัย
ปฏิบัติประพฤติกฎกำหนดใจ
พูดจาให้จ๊ะ ๆ จ๋า ๆ น่าฟังเอยฯ
แหล่งที่มา : สมาคมคอมพิวเตอร์แห่งประเทศไทย
ฅนฃวด kho khuat and kho khon
@TITLECASE@
ก๊กเฮง แซ่แต้
กชกร ศราทธทัต
กติกา อังคสุภณ
กนก ธรรมประทีป
กนก วงศ์ทองศรี
กนกกร ช้างเย็นฉ่ำ
กนกฉัตร์ ถาวรนันท์
กนกนวล โปษยะนันทน์
กนกพร คมคาย
กนกพร ตีรเลิศพานิช
กนกพร พันทร
กนกพร ศรีบัณฑิต
กนกพร อติวรรณาพัฒน์
กนกพรรณ ศรีวนาภิรมย์
กนกรัตน์ เกียรติยิ่งอังศุลี
กนกรัตน์ สุธรรมพิทักษ์
กนกวรรณ คงคาประเสริฐ
กนกวรรณ แซ่เตียว
กนกวรรณ บุญประเสริฐ
กนกวรรณ รักทรัพย์
กนกวรรณ สัจจพงษ์
กนกวรรณ อุ้ยวงศ์ไพศาล
กนกศักดิ์ ยิ่งยง
กนกแก้ว กรสมิต
กนิษฐา ทนุถนอมราษฎร์
กนิษฐา หวังวิบูลย์กิจ
กมล กาญจนโรจน์
กมล คัมภีร์
กมล เจตน์มงคลรัตน์
กมล ชูตระกูลธรรม
@SET [[:thai:] \u0E01-\u0E3A\u0E40-\u0E5B]

View file

@ -0,0 +1,252 @@
/*
*******************************************************************************
* Copyright (C) 1996-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.translit;
import java.awt.event.*;
import com.ibm.icu.text.*;
import com.ibm.icu.dev.demo.impl.*;
/**
* A subclass of {@link DumbTextComponent} that passes key events through
* a {@link com.ibm.icu.text.Transliterator}.
*
* <p>Copyright &copy; IBM Corporation 1999. All rights reserved.
*
* @author Alan Liu
*/
public class TransliteratingTextComponent extends DumbTextComponent {
private static boolean DEBUG = false;
private Transliterator translit = null;
// NOTE: DISABLE THE START AND CURSOR UNTIL WE CAN GET IT TO WORK AT ALL
// Index into getText() where the start of transliteration is.
// As we commit text during transliteration, we advance
// this.
//private int start = 0;
// Index into getText() where the cursor is; cursor >= start
//private int cursor = 0;
private static final String COPYRIGHT =
"\u00A9 IBM Corporation 1999. All rights reserved.";
/**
* Constructor.
*/
public TransliteratingTextComponent() {
super();
/*
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// We get an ActionEvent only when the selection changes
resetTransliterationStart();
}
});
*/
}
/**
* {@link DumbTextComponent} API. Framework method that is called
* when a <code>KeyEvent</code> is received. This implementation
* runs the new character through the current
* <code>Transliterator</code>, if one is set, and inserts the
* transliterated text into the buffer.
*/
protected void handleKeyTyped(KeyEvent e) {
char ch = e.getKeyChar();
if (translit == null) {
setKeyStart(-1);
super.handleKeyTyped(e);
return;
}
transliterate(ch, false);
}
public void flush() {
if (translit != null) transliterate('\uFFFF', true);
}
protected void transliterate(char ch, boolean flush) {
// ------------------------------------------------------------
// The following case motivates the two lines that recompute
// start and cursor below.
// " "
// a b c q r|s t u m m
// 0 1 2 3 4 5 6 7 8 9
// 0 1 2
// start 3, cursor 5, sel 6 -> { 0, 3, 2 }
// : new int[] { 0, sel - start, cursor - start };
// sz>99|9
// " { "
// a b c q r 9 9|9 t u m m
// 0 1 2 3 4 5 6 7 8 9 a b
// 0 1 2 3 4
// { 3, 5, 4 } -> start 6, cursor 7, sel 8
// : start += index[0];
// : cursor = start + index[2] - index[0];
// ------------------------------------------------------------
// Need to save start because calls to replaceRange will update
// start and cursor.
//int saveStart = start;
int end = flush ? getSelectionEnd() : getSelectionStart();
String sourceText = getText().substring(0,end);
ReplaceableString buf = new ReplaceableString(sourceText);
/*buf.replace(0, 1, getText().substring(start,
getSelectionStart()));*/
Transliterator.Position index = new Transliterator.Position();
index.contextLimit = buf.length();
index.contextStart = 0;
index.start = getKeyStart();
if (index.start == -1) index.start = getSelectionStart();
index.limit = buf.length();
// StringBuffer log = null;
if (DEBUG) {
System.out.println("Transliterator: " + translit.getID());
System.out.println("From:\t" + '"' + buf.toString() + '"'
+ "; {cs: " + index.contextStart
+ ", s: " + index.start
+ ", l: " + index.limit
+ ", cl: " + index.contextLimit
+ "}" + "; '" + ch + "'"
+ " " + getKeyStart()
);
}
if (flush) {
translit.finishTransliteration(buf, index);
} else {
translit.transliterate(buf, index, ch);
}
if (DEBUG) {
System.out.println("To:\t" + '"' + buf.toString() + '"'
+ "; {cs: " + index.contextStart
+ ", s: " + index.start
+ ", l: " + index.limit
+ ", cl: " + index.contextLimit
+ "}"
);
System.out.println();
}
/*
buf.replace(buf.length(), buf.length(), String.valueOf(ch));
translit.transliterate(buf);
*/
String result = buf.toString();
//if (result.equals(sourceText + ch)) return;
replaceRange(result, 0, getSelectionEnd());
setKeyStart(index.start);
// At this point start has been changed by the callback to
// resetTransliteratorStart() via replaceRange() -- so use our
// local copy, saveStart.
// The START index is zero-based. On entry to transliterate(),
// it was zero. We can therefore just add it to our original
// getText()-based index value of start (in saveStart) to get
// the new getText()-based start.
// start = saveStart + index.contextStart;
// Make the cursor getText()-based. The CURSOR index is zero-based.
// cursor = start + index.start - index.contextStart;
/*
if (DEBUG) {
String out = buf.toString();
log.append(out.substring(0, index.contextStart)).
append('{').
append(out.substring(index.contextStart, index.start)).
append('|').
append(out.substring(index.start)).
append('"');
log.append(", {" + index.contextStart + ", " + index.contextLimit + ", " + index.start + "}, ");
// log.append("start " + start + ", cursor " + cursor);
log.append(", sel " + getSelectionStart());
System.out.println(escape(log.toString()));
}
*/
}
/**
* Set the {@link com.ibm.icu.text.Transliterator} and direction to
* use to process incoming <code>KeyEvent</code>s.
* @param t the {@link com.ibm.icu.text.Transliterator} to use
*/
public void setTransliterator(Transliterator t) {
/*
if (translit != t) { // [sic] pointer compare ok; singletons
resetTransliterationStart();
}
*/
translit = t;
}
public Transliterator getTransliterator() {
return translit;
}
/**
* Reset the start point at which transliteration begins. This
* needs to be done when the user moves the cursor or when the
* current {@link com.ibm.icu.text.Transliterator} is changed.
*/
/*
private void resetTransliterationStart() {
start = getSelectionStart();
cursor = start;
}
*/
/**
* Escape non-ASCII characters as Unicode.
* JUST FOR DEBUGGING OUTPUT.
*/
public static final String escape(String s) {
StringBuffer buf = new StringBuffer();
for (int i=0; i<s.length(); ++i) {
char c = s.charAt(i);
if (c >= ' ' && c <= 0x007F) {
if (c == '\\') {
buf.append("\\\\"); // That is, "\\"
} else {
buf.append(c);
}
} else {
buf.append("\\u");
if (c < 0x1000) {
buf.append('0');
if (c < 0x100) {
buf.append('0');
if (c < 0x10) {
buf.append('0');
}
}
}
buf.append(Integer.toHexString(c));
}
}
return buf.toString();
}
}

View file

@ -0,0 +1,285 @@
/**
*******************************************************************************
* Copyright (C) 2001-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.demo.translit;
import com.ibm.icu.lang.UScript;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.text.UnicodeSetIterator;
import com.ibm.icu.text.Normalizer;
import com.ibm.icu.impl.Utility;
import java.util.*;
import java.io.*;
public class TransliterationChart {
public static void main(String[] args) throws IOException {
System.out.println("Start");
UnicodeSet lengthMarks = new UnicodeSet("[\u09D7\u0B56-\u0B57\u0BD7\u0C56\u0CD5-\u0CD6\u0D57\u0C55\u0CD5]");
int[] indicScripts = {
UScript.LATIN,
UScript.DEVANAGARI,
UScript.BENGALI,
UScript.GURMUKHI,
UScript.GUJARATI,
UScript.ORIYA,
UScript.TAMIL,
UScript.TELUGU,
UScript.KANNADA,
UScript.MALAYALAM,
};
String[] names = new String[indicScripts.length];
UnicodeSet[] sets = new UnicodeSet[indicScripts.length];
Transliterator[] fallbacks = new Transliterator[indicScripts.length];
for (int i = 0; i < indicScripts.length; ++i) {
names[i] = UScript.getName(indicScripts[i]);
sets[i] = new UnicodeSet("[[:" + names[i] + ":]&[[:L:][:M:]]&[:age=3.1:]]");
fallbacks[i] = Transliterator.getInstance("any-" + names[i]);
}
EquivClass eq = new EquivClass(new ReverseComparator());
PrintWriter pw = openPrintWriter("transChart.html");
pw.println("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
pw.println("<title>Indic Transliteration Chart</title><style>");
pw.println("td { text-align: Center; font-size: 200% }");
pw.println("tt { font-size: 50% }");
pw.println("td.miss { background-color: #CCCCFF }");
pw.println("</style></head><body bgcolor='#FFFFFF'>");
Transliterator anyToLatin = Transliterator.getInstance("any-latin");
String testString = "\u0946\u093E";
UnicodeSet failNorm = new UnicodeSet();
Set latinFail = new TreeSet();
for (int i = 0; i < indicScripts.length; ++i) {
if (indicScripts[i] == UScript.LATIN) continue;
String source = names[i];
System.out.println(source);
UnicodeSet sourceChars = sets[i];
for (int j = 0; j < indicScripts.length; ++j) {
if (i == j) continue;
String target = names[j];
Transliterator forward = Transliterator.getInstance(source + '-' + target);
Transliterator backward = forward.getInverse();
UnicodeSetIterator it = new UnicodeSetIterator(sourceChars);
while (it.next()) {
if (lengthMarks.contains(it.codepoint)) continue;
String s = Normalizer.normalize(it.codepoint,Normalizer.NFC,0);
//if (!Normalizer.isNormalized(s,Normalizer.NFC,0)) continue;
if (!s.equals(Normalizer.normalize(s,Normalizer.NFD,0))) {
failNorm.add(it.codepoint);
}
String t = fix(forward.transliterate(s));
if (t.equals(testString)) {
System.out.println("debug");
}
String r = fix(backward.transliterate(t));
if (Normalizer.compare(s,r,0) == 0) {
if (indicScripts[j] != UScript.LATIN) eq.add(s,t);
} else {
if (indicScripts[j] == UScript.LATIN) {
latinFail.add(s + " - " + t + " - " + r);
}
}
}
}
}
// collect equivalents
pw.println("<table border='1' cellspacing='0'><tr>");
for (int i = 0; i < indicScripts.length; ++i) {
pw.print("<th width='10%'>" + names[i].substring(0,3) + "</th>");
}
pw.println("</tr>");
Iterator rit = eq.getSetIterator(new MyComparator());
while(rit.hasNext()) {
Set equivs = (Set)rit.next();
pw.print("<tr>");
Iterator sit = equivs.iterator();
String source = (String)sit.next();
String item = anyToLatin.transliterate(source);
if (item.equals("") || source.equals(item)) item = "&nbsp;";
pw.print("<td>" + item + "</td>");
for (int i = 1; i < indicScripts.length; ++i) {
sit = equivs.iterator();
item = "";
while (sit.hasNext()) {
String trial = (String)sit.next();
if (!sets[i].containsAll(trial)) continue;
item = trial;
break;
}
String classString = "";
if (item.equals("")) {
classString = " class='miss'";
String temp = fallbacks[i].transliterate(source);
if (!temp.equals("") && !temp.equals(source)) item = temp;
}
String backup = item.equals("") ? "&nbsp;" : item;
pw.print("<td" + classString + " title='" + getName(item, "; ") + "'>"
+ backup + "<br><tt>" + Utility.hex(item) + "</tt></td>");
}
/*
Iterator sit = equivs.iterator();
while (sit.hasNext()) {
String item = (String)sit.next();
pw.print("<td>" + item + "</td>");
}
*/
pw.println("</tr>");
}
pw.println("</table>");
if (true) {
pw.println("<h2>Failed Normalization</h2>");
UnicodeSetIterator it = new UnicodeSetIterator(failNorm);
UnicodeSet pieces = new UnicodeSet();
while (it.next()) {
String s = UTF16.valueOf(it.codepoint);
String d = Normalizer.normalize(s,Normalizer.NFD,0);
pw.println("Norm:" + s + ", " + Utility.hex(s) + " " + UCharacter.getName(it.codepoint)
+ "; " + d + ", " + Utility.hex(d) + ", ");
pw.println(UCharacter.getName(d.charAt(1)) + "<br>");
if (UCharacter.getName(d.charAt(1)).indexOf("LENGTH") >= 0) pieces.add(d.charAt(1));
}
pw.println(pieces);
pw.println("<h2>Failed Round-Trip</h2>");
Iterator cit = latinFail.iterator();
while (cit.hasNext()) {
pw.println(cit.next() + "<br>");
}
}
pw.println("</table></body></html>");
pw.close();
System.out.println("Done");
}
public static String fix(String s) {
if (s.equals("\u0946\u093E")) return "\u094A";
if (s.equals("\u0C46\u0C3E")) return "\u0C4A";
if (s.equals("\u0CC6\u0CBE")) return "\u0CCA";
if (s.equals("\u0947\u093E")) return "\u094B";
if (s.equals("\u0A47\u0A3E")) return "\u0A4B";
if (s.equals("\u0AC7\u0ABE")) return "\u0ACB";
if (s.equals("\u0C47\u0C3E")) return "\u0C4B";
if (s.equals("\u0CC7\u0CBE")) return "\u0CCB";
//return Normalizer.normalize(s,Normalizer.NFD,0);
return s;
}
public static PrintWriter openPrintWriter(String fileName) throws IOException {
File lf = new File(fileName);
System.out.println("Creating file: " + lf.getAbsoluteFile());
return new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(fileName), "UTF8"), 4*1024));
}
public static String getName(String s, String separator) {
int cp;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i += UTF16.getCharCount(cp)) {
cp = UTF16.charAt(s,i);
if (i != 0) sb.append(separator);
sb.append(UCharacter.getName(cp));
}
return sb.toString();
}
static class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
Iterator i1 = ((TreeSet) o1).iterator();
Iterator i2 = ((TreeSet) o2).iterator();
while (i1.hasNext() && i2.hasNext()) {
String a = (String)i1.next();
String b = (String)i2.next();
int result = a.compareTo(b);
if (result != 0) return result;
}
if (i1.hasNext()) return 1;
if (i2.hasNext()) return -1;
return 0;
}
}
static class ReverseComparator implements Comparator {
public int compare(Object o1, Object o2) {
String a = o1.toString();
char a1 = a.charAt(0);
String b = o2.toString();
char b1 = b.charAt(0);
if (a1 < 0x900 && b1 > 0x900) return -1;
if (a1 > 0x900 && b1 < 0x900) return +1;
return a.compareTo(b);
}
}
static class EquivClass {
EquivClass(Comparator c) {
comparator = c;
}
private HashMap itemToSet = new HashMap();
private Comparator comparator;
void add(Object a, Object b) {
Set sa = (Set)itemToSet.get(a);
Set sb = (Set)itemToSet.get(b);
if (sa == null && sb == null) { // new set!
Set s = new TreeSet(comparator);
s.add(a);
s.add(b);
itemToSet.put(a, s);
itemToSet.put(b, s);
} else if (sa == null) {
sb.add(a);
} else if (sb == null) {
sa.add(b);
} else { // merge sets, dumping sb
sa.addAll(sb);
Iterator it = sb.iterator();
while (it.hasNext()) {
itemToSet.put(it.next(), sa);
}
}
}
private class MyIterator implements Iterator {
private Iterator it;
MyIterator (Comparator comp) {
TreeSet values = new TreeSet(comp);
values.addAll(itemToSet.values());
it = values.iterator();
}
public boolean hasNext() {
return it.hasNext();
}
public Object next() {
return it.next();
}
public void remove() {
throw new IllegalArgumentException("can't remove");
}
}
public Iterator getSetIterator (Comparator comp) {
return new MyIterator(comp);
}
}
}

View file

@ -0,0 +1,13 @@
REM /*
REM *******************************************************************************
REM * Copyright (C) 1996-2004, International Business Machines Corporation and *
REM * others. All Rights Reserved. *
REM *******************************************************************************
REM */
REM For best results, run the demo as an applet inside of Netscape
REM with Bitstream Cyberbit installed.
REM setup your JDK 1.1.x path and classpath here:
call JDK11
set CLASSPATH=../translit.jar;%CLASSPATH%
javaw Demo

View file

@ -0,0 +1,34 @@
<!--
/**
*******************************************************************************
* Copyright (C) 1999-2004, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
-->
<HTML>
<HEAD>
<TITLE>Transliteration Demo</TITLE>
</HEAD>
<BODY>
<APPLET CODE="com.ibm.demo.translit.DemoApplet.class" WIDTH=140 HEIGHT=33></APPLET>
<HR>
If you don't see a button above, then your browser is failing to
locate the necessary Java class files.
<P>
One way to make this work is to copy this HTML file to
<code>icu4j/src</code>, and make sure the Java files in the directories
under <code>icu4j/src/com</code> are built. Then open this HTML file
using a browser or appletviewer.
<P>
For best results, run this demo as an applet within Netscape with
Bitstream Cyberbit installed.
</BODY>
</HTML>

View file

@ -0,0 +1,12 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000-2004, International Business Machines Corporation and
others. All Rights Reserved.
-->
</head>
<body bgcolor="white">
Transliterator demo appliation.
</body>
</html>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,55 @@
#--------------------------------------------------------------------
# Copyright (c) 1999-2004, International Business Machines
# Corporation and others. All Rights Reserved.
#--------------------------------------------------------------------
@UPPERFILTER@
Unicode คืออะไร?
Unicode กำหนดหมายเลขเฉพาะสำหรับทุกอักขระ
โดยไม่สนใจว่าเป็นแพล็ตฟอร์มใด
ไม่ขึ้นกับว่าจะเป็นโปรแกรมใด
และไม่ว่าจะเป็นภาษาใด
โดยพื้นฐานแล้ว, คอมพิวเตอร์จะเกี่ยวข้องกับเรื่องของตัวเลข. คอมพิวเตอร์จัดเก็บตัวอักษรและอักขระอื่นๆ โดยการกำหนดหมายเลขให้สำหรับแต่ละตัว. ก่อนหน้าที่๊ Unicode จะถูกสร้างขึ้น, ได้มีระบบ encoding อยู่หลายร้อยระบบสำหรับการกำหนดหมายเลขเหล่านี้. ไม่มี encoding ใดที่มีจำนวนตัวอักขระมากเพียงพอ: ยกตัวอย่างเช่น, เฉพาะในกลุ่มสหภาพยุโรปเพียงแห่งเดียว ก็ต้องการหลาย encoding ในการครอบคลุมทุกภาษาในกลุ่ม. หรือแม้แต่ในภาษาเดี่ยว เช่น ภาษาอังกฤษ ก็ไม่มี encoding ใดที่เพียงพอสำหรับทุกตัวอักษร, เครื่องหมายวรรคตอน และสัญลักษณ์ทางเทคนิคที่ใช้กันอยู่ทั่วไป.
ระบบ encoding เหล่านี้ยังขัดแย้งซึ่งกันและกัน. นั่นก็คือ, ในสอง encoding สามารถใช้หมายเลขเดียวกันสำหรับตัวอักขระสองตัวที่แตกต่างกัน,หรือใช้หมายเลขต่างกันสำหรับอักขระตัวเดียวกัน. ในระบบคอมพิวเตอร์ (โดยเฉพาะเซิร์ฟเวอร์) ต้องมีการสนับสนุนหลาย encoding; และเมื่อข้อมูลที่ผ่านไปมาระหว่างการเข้ารหัสหรือแพล็ตฟอร์มที่ต่างกัน, ข้อมูลนั้นจะเสี่ยงต่อการผิดพลาดเสียหาย.
Unicode จะเปลี่ยนแปลงสิ่งเหล่านั้นทั้งหมด!
Unicode กำหนดหมายเลขเฉพาะสำหรับแต่ละอักขระ, โดยไม่สนใจว่าเป็นแพล็ตฟอร์มใด, ไม่ขึ้นกับว่าจะเป็นโปรแกรมใดและไม่ว่าจะเป็นภาษาใด. มาตรฐาน Unicode ได้ถูกนำไปใช้โดยผู้นำในอุตสาหกรรม เช่น Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys และอื่นๆ อีกมาก. Unicode เป็นสิ่งที่จำเป็นสำหรับมาตรฐานใหม่ๆ เช่น XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML ฯลฯ., และเป็นแนวทางอย่างเป็นทางการในการทำ ISO/IEC 10646. Unicode ได้รับการสนับสนุนในระบบปฏิบัติการจำนวนมาก, บราวเซอร์ใหม่ๆ ทกตัว, และผลิตภัณฑ์อื่นๆ อีกมาก. การเกิดขึ้นของ Unicode Standard และทูลส์ต่างๆ ที่มีในการสนับสนุน Unicode, เป็นหนึ่งในแนวโน้มทางเทคโนโลยีซอฟต์แวร์ระดับโลกที่มีความสำคัญที่สุด.
การรวม Unicode เข้าไปในระบบไคลเอ็นต์-เซิร์ฟเวอร์ หรือแอ็พพลิเคชันแบบ multi-tiered และเว็บไซต์ จะทำให้เกิดการประหยัดค่าใช้จ่ายมากกว่าการใช้ชุดอักขระแบบเดิม. Unicode ทำให้ผลิตภัณฑ์ซอฟต์แวร์หนึ่งเดียว หรือเว็บไซต์แห่งเดียว รองรับได้หลายแพล็ตฟอร์ม, หลายภาษาและหลายประเทศโดยไม่ต้องทำการรื้อปรับระบบ. Unicode ยังทำให้ข้อมูลสามารถเคลื่อนย้ายไปมาในหลายๆ ระบบโดยไม่เกิดความผิดพลาดเสียหาย.
เกี่ยวกับ Unicode Consortium
Unicode Consortium เป็นองค์กรไม่แสวงหากำไรที่ก่อตั้งขึ้นเพื่อพัฒนา, ขยายและส่งเสริมการใช้ Unicode Standard, ซึ่งกำหนดรูปแบบการแทนค่าของข้อความในผลิตภัณฑ์ซอฟต์แวร์และมาตรฐานใหม่ๆ. สมาชิกของสมาคมเป็นตัวแทนจากบริษัทและองค์กรในอุตสาหกรรมคอมพิวเตอร์และการประมวลผลสารสนเทศ. สมาคมได้รับการสนับสนุนทางการเงินผ่านทางค่าธรรมเนียมของการเป็นสมาชิกเท่านั้น. สมาชิกภาพของ Unicode Consortium เปิดกว้างสำหรับองค์กรหรือบุคคลใดๆ ในโลกที่ต้องการสนับสนุน Unicode Standard และช่วยเหลือการขยายตัวและการนำ Unicode ไปใช้งาน.
สำหรับข้อมูลเพิ่มเติม, ให้ดูที่ Glossary, Sample Unicode-Enabled Products, Technical Introduction และ Useful Resources.
@TITLECASE@
ก๊กเฮง แซ่แต้
กชกร ศราทธทัต
กติกา อังคสุภณ
กนก ธรรมประทีป
กนก วงศ์ทองศรี
กนกกร ช้างเย็นฉ่ำ
กนกฉัตร์ ถาวรนันท์
กนกนวล โปษยะนันทน์
กนกพร คมคาย
กนกพร ตีรเลิศพานิช
กนกพร พันทร
กนกพร ศรีบัณฑิต
กนกพร อติวรรณาพัฒน์
กนกพรรณ ศรีวนาภิรมย์
กนกรัตน์ เกียรติยิ่งอังศุลี
กนกรัตน์ สุธรรมพิทักษ์
กนกวรรณ คงคาประเสริฐ
กนกวรรณ แซ่เตียว
กนกวรรณ บุญประเสริฐ
กนกวรรณ รักทรัพย์
กนกวรรณ สัจจพงษ์
กนกวรรณ อุ้ยวงศ์ไพศาล
กนกศักดิ์ ยิ่งยง
กนกแก้ว กรสมิต
กนิษฐา ทนุถนอมราษฎร์
กนิษฐา หวังวิบูลย์กิจ
กมล กาญจนโรจน์
กมล คัมภีร์
กมล เจตน์มงคลรัตน์
กมล ชูตระกูลธรรม

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.ibm.icu-feature</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.pde.FeatureBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.FeatureNature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,20 @@
###############################################################################
# Copyright (c) 2000, 2005 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
bin.includes =\
epl-v10.html,\
eclipse_update_120.jpg,\
feature.xml,\
feature.properties,\
license.html
outputUpdateJars = true
generate.plugin@com.ibm.icu.source=com.ibm.icu

View file

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
id="com.ibm.icu"
label="com.ibm.icu"
version="@BUILD_VERSION@">
<description url="http://www.example.com/description">
[Enter Feature Description here.]
</description>
<copyright url="http://www.example.com/copyright">
[Enter Copyright Description here.]
</copyright>
<license url="http://www.example.com/license">
[Enter License Description here.]
</license>
<plugin
id="com.ibm.icu"
download-size="0"
install-size="0"
version="@BUILD_VERSION@"
unpack="false"/>
<plugin
id="com.ibm.icu.source"
download-size="0"
install-size="0"
version="@BUILD_VERSION@"/>
</feature>

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
bin.includes = about.html, plugin.properties, plugin.xml, src/**,META-INF/
sourcePlugin = true

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
pluginName = International Components for Unicode for Java (ICU4J) source plug-in
providerName = IBM Corporation

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.ibm.icu.base-feature</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.pde.FeatureBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.FeatureNature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,9 @@
bin.includes =\
epl-v10.html,\
eclipse_update_120.jpg,\
feature.xml,\
feature.properties,\
license.html
outputUpdateJars = true
generate.plugin@com.ibm.icu.base.source=com.ibm.icu.base

View file

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
id="com.ibm.icu.base"
label="com.ibm.icu.base"
version="@BUILD_VERSION@"
provider-name="IBM">
<description url="http://www.example.com/description">
[Enter Feature Description here.]
</description>
<copyright url="http://www.example.com/copyright">
[Enter Copyright Description here.]
</copyright>
<license url="http://www.example.com/license">
[Enter License Description here.]
</license>
<plugin
id="com.ibm.icu.base"
download-size="0"
install-size="0"
version="@BUILD_VERSION@"
unpack="false"/>
<plugin
id="com.ibm.icu.base.source"
download-size="0"
install-size="0"
version="@BUILD_VERSION@"/>
</feature>

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
bin.includes = about.html, plugin.properties, plugin.xml, src/**,META-INF/
sourcePlugin = true

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
pluginName = International Components for Unicode for Java (ICU4J) Replacement source plug-in
providerName = IBM Corporation

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.ibm.icu.base.tests</name>
<comment></comment>
<projects>
</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.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,14 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: ICU4J Base test fragment
Bundle-SymbolicName: com.ibm.icu.base.tests
Bundle-Version: 1.0.0
Bundle-Vendor: IBM
Bundle-Copyright: Licensed Materials - Property of IBM
(C) Copyright IBM Corp. 2006. All Rights Reserved.
IBM is a registered trademark of IBM Corp.
Fragment-Host: com.ibm.icu.base;bundle-version="[3.4.3,3.5.0)"
Bundle-Localization: plugin
Bundle-RequiredExecutionEnvironment: J2SE-1.3,
CDC-1.0/Foundation-1.0
Require-Bundle: org.junit

View file

@ -0,0 +1,4 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.

View file

@ -0,0 +1,359 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Locale;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.util.ULocale;
public class BreakIteratorTest extends ICUTestCase {
// ICU behaves a bit differently with this text, but the tested values aren't
// affected. If Java changes behavior they might need to change.
private static final String text = "Mr. and Mrs. Mumblety-Peg paid $35.97 for a new 12\" cockatoo. " +
"When they got home they both cooed \"Isn't it lovely?\" and sighed softly. " +
"\"Let's name it u\u0308\u5098!\" they said with glee.";
private static int pos = text.indexOf("sn't");
private static BreakIterator cbr;
private static BreakIterator wbr;
private static BreakIterator lbr;
private static BreakIterator sbr;
static {
cbr = BreakIterator.getCharacterInstance();
cbr.setText(text);
wbr = BreakIterator.getWordInstance();
wbr.setText(text);
lbr = BreakIterator.getLineInstance();
lbr.setText(text);
sbr = BreakIterator.getSentenceInstance();
sbr.setText(text);
// diagnostic
// dump(cbr);
// dump(wbr);
// dump(lbr);
// dump(sbr);
}
// private static void dump(BreakIterator bi) {
// for (int ix = bi.first(), lim = text.length(); ix != lim;) {
// int nx = bi.next();
// if (nx < 0) nx = lim;
// System.out.println(Integer.toString(ix) + ": " + text.substring(ix, nx));
// ix = nx;
// }
// }
/*
* Test method for 'com.ibm.icu.text.BreakIterator.hashCode()'
*/
public void testHashCode() {
BreakIterator br = BreakIterator.getWordInstance();
br.setText(text);
BreakIterator brne = BreakIterator.getWordInstance();
brne.setText(text + "X");
wbr.first();
testEHCS(br, wbr, brne);
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.BreakIterator(BreakIterator)'
*/
public void testBreakIterator() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.first()'
*/
public void testFirst() {
assertEquals(0, cbr.first());
assertEquals(0, wbr.first());
assertEquals(0, lbr.first());
assertEquals(0, sbr.first());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.last()'
*/
public void testLast() {
assertEquals(text.length(), cbr.last());
assertEquals(text.length(), wbr.last());
assertEquals(text.length(), lbr.last());
assertEquals(text.length(), sbr.last());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.next(int)'
*/
public void testNextInt() {
cbr.first();
wbr.first();
lbr.first();
sbr.first();
assertEquals(2, cbr.next(2));
assertEquals(3, wbr.next(2));
assertEquals(8, lbr.next(2));
assertEquals(62, sbr.next(2));
cbr.last();
wbr.last();
lbr.last();
sbr.last();
assertEquals(174, cbr.next(-2));
assertEquals(171, wbr.next(-2));
assertEquals(166, lbr.next(-2));
assertEquals(135, sbr.next(-2));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.next()'
*/
public void testNext() {
cbr.first();
wbr.first();
lbr.first();
sbr.first();
assertEquals(1, cbr.next());
assertEquals(2, wbr.next());
assertEquals(4, lbr.next());
assertEquals(13, sbr.next());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.previous()'
*/
public void testPrevious() {
cbr.last();
wbr.last();
lbr.last();
sbr.last();
assertEquals(175, cbr.previous());
assertEquals(175, wbr.previous());
assertEquals(171, lbr.previous());
assertEquals(156, sbr.previous());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.following(int)'
*/
public void testFollowing() {
assertEquals(100, cbr.following(pos));
assertEquals(103, wbr.following(pos));
assertEquals(104, lbr.following(pos));
assertEquals(116, sbr.following(pos));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.preceding(int)'
*/
public void testPreceding() {
assertEquals(98, cbr.preceding(pos));
assertEquals(98, wbr.preceding(pos));
assertEquals(97, lbr.preceding(pos));
assertEquals(62, sbr.preceding(pos));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.isBoundary(int)'
*/
public void testIsBoundary() {
assertTrue(cbr.isBoundary(pos));
assertFalse(wbr.isBoundary(pos));
assertFalse(lbr.isBoundary(pos));
assertFalse(sbr.isBoundary(pos));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.current()'
*/
public void testCurrent() {
cbr.following(pos);
wbr.following(pos);
lbr.following(pos);
sbr.following(pos);
assertEquals(100, cbr.current());
assertEquals(103, wbr.current());
assertEquals(104, lbr.current());
assertEquals(116, sbr.current());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getText()'
*/
public void testGetText() {
CharacterIterator ci = cbr.getText();
StringBuffer buf = new StringBuffer(ci.getEndIndex() - ci.getBeginIndex());
for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
buf.append(c);
}
String result = buf.toString();
assertEquals(text, result);
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.setText(String)'
*/
public void testSetTextString() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.setText(CharacterIterator)'
*/
public void testSetTextCharacterIterator() {
CharacterIterator ci = new StringCharacterIterator(text, pos);
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(ci);
assertEquals(2, bi.next());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getWordInstance()'
*/
public void testGetWordInstance() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getWordInstance(Locale)'
*/
public void testGetWordInstanceLocale() {
assertNotNull(BreakIterator.getWordInstance(Locale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getWordInstance(ULocale)'
*/
public void testGetWordInstanceULocale() {
assertNotNull(BreakIterator.getWordInstance(ULocale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getLineInstance()'
*/
public void testGetLineInstance() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getLineInstance(Locale)'
*/
public void testGetLineInstanceLocale() {
assertNotNull(BreakIterator.getLineInstance(Locale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getLineInstance(ULocale)'
*/
public void testGetLineInstanceULocale() {
assertNotNull(BreakIterator.getLineInstance(ULocale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getCharacterInstance()'
*/
public void testGetCharacterInstance() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getCharacterInstance(Locale)'
*/
public void testGetCharacterInstanceLocale() {
assertNotNull(BreakIterator.getCharacterInstance(Locale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getCharacterInstance(ULocale)'
*/
public void testGetCharacterInstanceULocale() {
assertNotNull(BreakIterator.getCharacterInstance(ULocale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getSentenceInstance()'
*/
public void testGetSentenceInstance() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getSentenceInstance(Locale)'
*/
public void testGetSentenceInstanceLocale() {
assertNotNull(BreakIterator.getSentenceInstance(Locale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getSentenceInstance(ULocale)'
*/
public void testGetSentenceInstanceULocale() {
assertNotNull(BreakIterator.getSentenceInstance(ULocale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getTitleInstance()'
*/
public void testGetTitleInstance() {
// not implemented
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getTitleInstance(Locale)'
*/
public void testGetTitleInstanceLocale() {
// not implemented
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getTitleInstance(ULocale)'
*/
public void testGetTitleInstanceULocale() {
// not implemented
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getAvailableLocales()'
*/
public void testGetAvailableLocales() {
assertNotNull(BreakIterator.getAvailableLocales());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getAvailableULocales()'
*/
public void testGetAvailableULocales() {
assertNotNull(BreakIterator.getAvailableULocales());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.toString()'
*/
public void testToString() {
assertNotNull(cbr.toString());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.clone()'
*/
public void testClone() {
// see testHashCode
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.equals(Object)'
*/
public void testEqualsObject() {
// see testHashCode
}
}

Some files were not shown because too many files have changed in this diff Show more