001: /*
002: *******************************************************************************
003: * Copyright (C) 1996-2005, International Business Machines Corporation and *
004: * others. All Rights Reserved. *
005: *******************************************************************************
006: */
007: package com.ibm.icu.dev.demo.rbbi;
008:
009: import java.awt.*;
010: import java.awt.event.WindowEvent;
011: import java.awt.event.KeyAdapter;
012: import java.awt.event.KeyEvent;
013: import java.awt.event.ItemListener;
014: import java.awt.event.ItemEvent;
015: import javax.swing.JTextArea;
016: import javax.swing.JScrollPane;
017: import javax.swing.BorderFactory;
018: import java.util.*;
019: import com.ibm.icu.dev.demo.impl.*;
020: import com.ibm.icu.text.BreakIterator;
021:
022: public class DBBIDemo extends DemoApplet {
023: public static void main(String argv[]) {
024: Locale.setDefault(new Locale("en", "US", "DEMO"));
025: new DBBIDemo().showDemo();
026: }
027:
028: public Frame createDemoFrame(DemoApplet applet) {
029: return new DBBIFrame(applet);
030: }
031: }
032:
033: class DBBIFrame extends Frame implements ItemListener {
034: private static final String creditString = "v1.1a9, Demo";
035:
036: private static final int FIELD_COLUMNS = 45;
037: private static final Font choiceFont = null;
038: private static final boolean DEBUG = false;
039: private DemoApplet applet;
040:
041: final String right = "-->";
042: final String left = "<--";
043:
044: private BreakIterator iter;
045: private static boolean isctrldown_ = false;
046:
047: JTextArea text;
048: // TextArea text;
049: Choice bound;
050:
051: public DBBIFrame(DemoApplet applet) {
052: this .applet = applet;
053: init();
054: start();
055: }
056:
057: public void run() {
058: /*
059: while (true) {
060: try {
061: checkChange();
062: Thread.sleep(250);
063: }
064: catch (InterruptedException e) {
065: }
066: catch (Exception e) {
067: }
068: catch (Throwable e) {
069: }
070: }
071: */
072: }
073:
074: int s, e;
075: int ts, te;
076:
077: public void checkChange() {
078: // System.out.println("checkChange...");
079: if ((text.getSelectionStart() & 0x7FFF) != ts
080: || (text.getSelectionEnd() & 0x7FFF) != te) {
081:
082: // not used int tempS = text.getSelectionStart() & 0x7FFF;
083: // not used int tempE = text.getSelectionEnd() & 0x7FFF;
084:
085: // System.out.println(">");
086: // select(0, 0);
087: // select(tempS, tempE);
088: //select(tempS - (ts - s), tempE - (te - e));
089: // System.out.println("<");
090:
091: // if (s != ts || e != te) System.out.println(" s("+s+") ts("+ts+") e("+e+") te("+te+")");
092: // if (tempS != ts || tempE != te) System.out.println(">s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
093: // select(s - (ts - s), e - (te - e));
094: // if (tempS != ts || tempE != te) System.out.println("s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
095:
096: // System.out.println("lkdslksj");
097: }
098: }
099:
100: public void select(int sIn, int eIn) {
101: s = sIn;
102: e = eIn;
103: text.select(s, e);
104: ts = text.getSelectionStart() & 0x7FFF;
105: te = text.getSelectionEnd() & 0x7FFF;
106: // if (s != ts || e != te) {
107: // System.out.println(">s("+s+") ts("+ts+") e("+e+") te("+te+")");
108: // System.out.println(" "+(ts-s)+","+(te-e));
109: // }
110: }
111:
112: public int getSelectionStart() {
113: checkChange();
114: // return s;
115: return text.getSelectionStart() & 0x7FFF;
116: }
117:
118: public int getSelectionEnd() {
119: checkChange();
120: // return e;
121: return text.getSelectionEnd() & 0x7FFF;
122: }
123:
124: public final synchronized void selectRange(int s, int e) {
125: try {
126: //if (getSelectionStart() != s || getSelectionEnd() != e) {
127: //text.select(s, e);
128: select(s, e);
129: //}
130: // if (getSelectionStart() != s || getSelectionEnd() != e) {
131: // System.out.println("AGH! select("+s+","+e+") -> ("+
132: // getSelectionStart()+","+getSelectionEnd()+")");
133: // text.select(s - (getSelectionStart() - s), e - (getSelectionEnd() - e));
134: // }
135: } catch (Exception exp) {
136: errorText(exp.toString());
137: }
138: }
139:
140: public void init() {
141: buildGUI();
142: }
143:
144: public void start() {
145: }
146:
147: void addWithFont(Container container, Component foo, Font font) {
148: if (font != null)
149: foo.setFont(font);
150: container.add(foo);
151: }
152:
153: public void buildGUI() {
154: setBackground(DemoUtility.bgColor);
155: setLayout(new BorderLayout());
156:
157: Panel topPanel = new Panel();
158:
159: Label titleLabel = new Label("Text Boundary Demo", Label.CENTER);
160: titleLabel.setFont(DemoUtility.titleFont);
161: topPanel.add(titleLabel);
162:
163: //Label demo=new Label(creditString, Label.CENTER);
164: //demo.setFont(DemoUtility.creditFont);
165: //topPanel.add(demo);
166:
167: Panel choicePanel = new Panel();
168:
169: Label demo1 = new Label("Boundaries", Label.LEFT);
170: demo1.setFont(DemoUtility.labelFont);
171: choicePanel.add(demo1);
172:
173: bound = new Choice();
174: bound.setBackground(DemoUtility.choiceColor);
175: bound.addItem("Sentence");
176: bound.addItem("Line Break");
177: bound.addItem("Word");
178: bound.addItem("Char");
179:
180: bound.addItemListener(this );
181: if (choiceFont != null)
182: bound.setFont(choiceFont);
183:
184: choicePanel.add(bound);
185: topPanel.add(choicePanel);
186:
187: DemoUtility.fixGrid(topPanel, 1);
188:
189: add("North", topPanel);
190:
191: int ROWS = 15;
192: int COLUMNS = 50;
193: // text = new TextArea(getInitialText(), ROWS, COLUMNS);
194: text = new JTextArea(getInitialText(), ROWS, COLUMNS);
195: text.setLineWrap(true);
196: text.setWrapStyleWord(true);
197: text.setEditable(true);
198: text.selectAll();
199: text.setFont(DemoUtility.editFont);
200: text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
201:
202: add("Center", new JScrollPane(text,
203: JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
204: JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
205:
206: Panel copyrightPanel = new Panel();
207: addWithFont(copyrightPanel, new Label(DemoUtility.copyright1,
208: Label.LEFT), DemoUtility.creditFont);
209: DemoUtility.fixGrid(copyrightPanel, 1);
210: add("South", copyrightPanel);
211:
212: //layout();
213: handleEnumChanged();
214:
215: enableEvents(WindowEvent.WINDOW_CLOSING);
216: enableEvents(KeyEvent.KEY_PRESSED);
217: enableEvents(KeyEvent.KEY_RELEASED);
218:
219: text.addKeyListener(new KeyAdapter() {
220: public void keyPressed(KeyEvent e) {
221: if (e.isControlDown()) {
222: int kc = e.getKeyCode();
223: switch (e.getKeyCode()) {
224: case KeyEvent.VK_N:
225: case KeyEvent.VK_RIGHT:
226: handleForward();
227: break;
228: case KeyEvent.VK_P:
229: case KeyEvent.VK_LEFT:
230: handleBackward();
231: break;
232: default:
233: break;
234: }
235: e.consume();
236: }
237: }
238:
239: public void keyReleased(KeyEvent e) {
240: if (e.isControlDown()) {
241: e.consume();
242: }
243: }
244:
245: public void keyTyped(KeyEvent e) {
246: if (e.isControlDown()) {
247: e.consume();
248: }
249: }
250: });
251:
252: // (new Thread(this)).start();
253: }
254:
255: public String getInitialText() {
256: return "When,inthecourseofhumanevents,itbecomesnecessaryforonepeopletodissolvethepoliticalbondswhichhave"
257: + "connectedthemwithanother,andtoassumeamongthepowersoftheearth,theseparateandequalstationtowhichthelaws"
258: + "ofnatureandofnature'sGodentitlethem,adecentrespecttotheopinionsofmankindrequiresthattheyshoulddeclarethe"
259: + "causeswhichimpelthemtotheseparation.\n"
260: + "Weholdthesetruthstobeself-evident,thatallmenarecreatedequal,thattheyareendowedbytheirCreatorwithcertain"
261: + "unalienablerights,thatamongthesearelife,libertyandthepursuitofhappiness.Thattosecuretheserights,governmentsare"
262: + "institutedamongmen,derivingtheirjustpowersfromtheconsentofthegoverned.Thatwheneveranyformofgovernment"
263: + "becomesdestructivetotheseends,itistherightofthepeopletoalterortoabolishit,andtoinstitutenewgovernment,laying"
264: + "itsfoundationonsuchprinciplesandorganizingitspowersinsuchform,astothemshallseemmostlikelytoeffecttheirsafety"
265: + "andhappiness.Prudence,indeed,willdictatethatgovernmentslongestablishedshouldnotbechangedforlightandtransient"
266: + "causes;andaccordinglyallexperiencehathshownthatmankindaremoredisposedtosuffer,whileevilsaresufferable,than"
267: + "torightthemselvesbyabolishingtheformstowhichtheyareaccustomed.Butwhenalongtrainofabusesandusurpations,"
268: + "pursuinginvariablythesameobjectevincesadesigntoreducethemunderabsolutedespotism,itistheirright,itistheirduty,"
269: + "tothrowoffsuchgovernment,andtoprovidenewguardsfortheirfuturesecurity.--Suchhasbeenthepatientsufferanceof"
270: + "thesecolonies;andsuchisnowthenecessitywhichconstrainsthemtoaltertheirformersystemsofgovernment.Thehistory"
271: + "ofthepresentKingofGreatBritainisahistoryofrepeatedinjuriesandusurpations,allhavingindirectobjectthe"
272: + "establishmentofanabsolutetyrannyoverthesestates.Toprovethis,letfactsbesubmittedtoacandidworld.\n"
273: + "Hehasrefusedhisassenttolaws,themostwholesomeandnecessaryforthepublicgood.\n"
274: + "Hehasforbiddenhisgovernorstopasslawsofimmediateandpressingimportance,unlesssuspendedintheiroperationtill"
275: + "hisassentshouldbeobtained;andwhensosuspended,hehasutterlyneglectedtoattendtothem.\n"
276: + "Hehasrefusedtopassotherlawsfortheaccommodationoflargedistrictsofpeople,unlessthosepeoplewouldrelinquish"
277: + "therightofrepresentationinthelegislature,arightinestimabletothemandformidabletotyrantsonly.\n"
278: + "Hehascalledtogetherlegislativebodiesatplacesunusual,uncomfortable,anddistantfromthedepositoryoftheirpublic"
279: + "records,forthesolepurposeoffatiguingthemintocompliancewithhismeasures.\n"
280: + "Hehasdissolvedrepresentativehousesrepeatedly,foropposingwithmanlyfirmnesshisinvasionsontherightsofthepeople.\n"
281: + "Hehasrefusedforalongtime,aftersuchdissolutions,tocauseotherstobeelected;wherebythelegislativepowers,"
282: + "incapableofannihilation,havereturnedtothepeopleatlargefortheirexercise;thestateremaininginthemeantimeexposed"
283: + "toallthedangersofinvasionfromwithout,andconvulsionswithin.\n"
284: + "Hehasendeavoredtopreventthepopulationofthesestates;forthatpurposeobstructingthelawsfornaturalizationof"
285: + "foreigners;refusingtopassotherstoencouragetheirmigrationhither,andraisingtheconditionsofnewappropriationsof"
286: + "lands.\n"
287: + "Hehasobstructedtheadministrationofjustice,byrefusinghisassenttolawsforestablishingjudiciarypowers.\n"
288: + "Hehasmadejudgesdependentonhiswillalone,forthetenureoftheiroffices,andtheamountandpaymentoftheirsalaries.\n"
289: + "Hehaserectedamultitudeofnewoffices,andsenthitherswarmsofofficerstoharassourpeople,andeatouttheir"
290: + "substance.\n"
291: + "Hehaskeptamongus,intimesofpeace,standingarmieswithouttheconsentofourlegislature.\n"
292: + "Hehasaffectedtorenderthemilitaryindependentofandsuperiortocivilpower.\n"
293: + "Hehascombinedwithotherstosubjectustoajurisdictionforeigntoourconstitution,andunacknowledgedbyourlaws;"
294: + "givinghisassenttotheiractsofpretendedlegislation:\n"
295: + "Forquarteringlargebodiesofarmedtroopsamongus:\n"
296: + "Forprotectingthem,bymocktrial,frompunishmentforanymurderswhichtheyshouldcommitontheinhabitantsofthese"
297: + "states:\n"
298: + "Forcuttingoffourtradewithallpartsoftheworld:\n"
299: + "Forimposingtaxesonuswithoutourconsent:\n"
300: + "Fordeprivingusinmanycases,ofthebenefitsoftrialbyjury:\n"
301: + "Fortransportingusbeyondseastobetriedforpretendedoffenses:\n"
302: + "ForabolishingthefreesystemofEnglishlawsinaneighboringprovince,establishingthereinanarbitrarygovernment,and"
303: + "enlargingitsboundariessoastorenderitatonceanexampleandfitinstrumentforintroducingthesameabsoluteruleinthese"
304: + "colonies:\n"
305: + "Fortakingawayourcharters,abolishingourmostvaluablelaws,andalteringfundamentallytheformsofourgovernments:\n"
306: + "Forsuspendingourownlegislatures,anddeclaringthemselvesinvestedwithpowertolegislateforusinallcaseswhatsoever.\n"
307: + "Hehasabdicatedgovernmenthere,bydeclaringusoutofhisprotectionandwagingwaragainstus.\n"
308: + "Hehasplunderedourseas,ravagedourcoasts,burnedourtowns,anddestroyedthelivesofourpeople.\n"
309: + "Heisatthistimetransportinglargearmiesofforeignmercenariestocompletetheworksofdeath,desolationandtyranny,"
310: + "alreadybegunwithcircumstancesofcrueltyandperfidyscarcelyparalleledinthemostbarbarousages,andtotallyunworthy"
311: + "theheadofacivilizednation.\n"
312: + "Hehasconstrainedourfellowcitizenstakencaptiveonthehighseastobeararmsagainsttheircountry,tobecomethe"
313: + "executionersoftheirfriendsandbrethren,ortofallthemselvesbytheirhands.\n"
314: + "Hehasexciteddomesticinsurrectionsamongstus,andhasendeavoredtobringontheinhabitantsofourfrontiers,the"
315: + "mercilessIndiansavages,whoseknownruleofwarfare,isundistinguisheddestructionofallages,sexesandconditions.\n"
316: + "Ineverystageoftheseoppressionswehavepetitionedforredressinthemosthumbleterms:ourrepeatedpetitionshave"
317: + "beenansweredonlybyrepeatedinjury.Aprince,whosecharacteristhusmarkedbyeveryactwhichmaydefineatyrant,is"
318: + "unfittobetherulerofafreepeople.\n"
319: + "NorhavewebeenwantinginattentiontoourBritishbrethren.Wehavewarnedthemfromtimetotimeofattemptsbytheir"
320: + "legislaturetoextendanunwarrantablejurisdictionoverus.Wehaveremindedthemofthecircumstancesofouremigration"
321: + "andsettlementhere.Wehaveappealedtotheirnativejusticeandmagnanimity,andwehaveconjuredthembythetiesofour"
322: + "commonkindredtodisavowtheseusurpations,which,wouldinevitablyinterruptourconnectionsandcorrespondence.We"
323: + "must,therefore,acquiesceinthenecessity,whichdenouncesourseparation,andholdthem,asweholdtherestofmankind,"
324: + "enemiesinwar,inpeacefriends.\n"
325: + "We,therefore,therepresentativesoftheUnitedStatesofAmerica,inGeneralCongress,assembled,appealingtothe"
326: + "SupremeJudgeoftheworldfortherectitudeofourintentions,do,inthename,andbytheauthorityofthegoodpeopleof"
327: + "thesecolonies,solemnlypublishanddeclare,thattheseunitedcoloniesare,andofrightoughttobefreeandindependent"
328: + "states;thattheyareabsolvedfromallallegiancetotheBritishCrown,andthatallpoliticalconnectionbetweenthemandthe"
329: + "stateofGreatBritain,isandoughttobetotallydissolved;andthatasfreeandindependentstates,theyhavefullpowerto"
330: + "leveywar,concludepeace,contractalliances,establishcommerce,andtodoallotheractsandthingswhichindependent"
331: + "statesmayofrightdo.Andforthesupportofthisdeclaration,withafirmrelianceontheprotectionofDivineProvidence,we"
332: + "mutuallypledgetoeachotherourlives,ourfortunesandoursacredhonor.\n";
333: }
334:
335: public void handleEnumChanged() {
336: String s = bound.getSelectedItem();
337: if (s.equals("Char")) {
338: errorText("getCharacterInstance");
339: iter = BreakIterator.getCharacterInstance();
340: } else if (s.equals("Word")) {
341: errorText("getWordInstance");
342: iter = BreakIterator.getWordInstance();
343: } else if (s.equals("Line Break")) {
344: errorText("getLineInstance");
345: iter = BreakIterator.getLineInstance();
346: } else /* if (s.equals("Sentence")) */{
347: errorText("getSentenceInstance");
348: iter = BreakIterator.getSentenceInstance();
349: }
350: iter.setText(text.getText());
351: selectRange(0, 0);
352: //text.select(0,0);
353: }
354:
355: public void handleForward() {
356: try {
357: // System.out.println("entering handleForward");
358: iter.setText(text.getText());
359: int oldStart = getSelectionStart();
360: int oldEnd = getSelectionEnd();
361:
362: // System.out.println("handleForward: oldStart=" + oldStart + ", oldEnd=" + oldEnd);
363:
364: if (oldEnd < 1) {
365: selectRange(0, iter.following(0));
366: } else {
367: int s = iter.following(oldEnd - 1);
368: int e = iter.next();
369: if (e == -1) {
370: e = s;
371: }
372: selectRange(s, e);
373: }
374: //text.select(s, e);
375: errorText("<" + oldStart + "," + oldEnd + "> -> <" + s
376: + "," + e + ">");
377: } catch (Exception exp) {
378: errorText(exp.toString());
379: }
380: }
381:
382: public void handleBackward() {
383: try {
384: iter.setText(text.getText());
385: int oldStart = getSelectionStart();
386: int oldEnd = getSelectionEnd();
387: if (oldStart < 1) {
388: selectRange(0, 0);
389: } else {
390: int e = iter.following(oldStart - 1);
391: int s = iter.previous();
392: selectRange(s, e);
393: }
394: //text.select(s, e);
395: errorText("<" + oldStart + "," + oldEnd + "> -> <" + s
396: + "," + e + ">");
397: } catch (Exception exp) {
398: errorText(exp.toString());
399: }
400: }
401:
402: public void itemStateChanged(ItemEvent evt) {
403: if (evt.getSource() instanceof Choice) {
404: handleEnumChanged();
405: }
406: }
407:
408: public void errorText(String s) {
409: if (DEBUG)
410: System.out.println(s);
411: }
412:
413: protected void processWindowEvent(WindowEvent evt) {
414: if (evt.getID() == WindowEvent.WINDOW_CLOSING
415: && evt.getWindow() == this ) {
416: hide();
417: dispose();
418: if (applet != null) {
419: applet.demoClosed();
420: } else
421: System.exit(0);
422: }
423: }
424:
425: protected void processKeyEvent(KeyEvent evt) {
426: switch (evt.getID()) {
427: case KeyEvent.KEY_PRESSED:
428: if (evt.getKeyCode() == KeyEvent.VK_CONTROL) {
429: isctrldown_ = true;
430: }
431: break;
432: case KeyEvent.KEY_RELEASED:
433: // key detection for left and right buttons are removed
434: // to emulate the old release behaviour
435: int key = evt.getKeyCode();
436: if (key == KeyEvent.VK_N && isctrldown_) {
437: handleForward();
438: } else if (key == KeyEvent.VK_P && isctrldown_) {
439: handleBackward();
440: } else if (key == KeyEvent.VK_CONTROL) {
441: isctrldown_ = false;
442: }
443: break;
444: }
445: }
446: }
|