1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
|
/*
* $Id$
*
* Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.javatest.exec;
import com.sun.javatest.tool.UIFactory;
import com.sun.javatest.util.HTMLWriter;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiFileFormat;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.RepaintManager;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
import javax.swing.text.rtf.RTFEditorKit;
/**
*
* @author Sergey Borodin
*/
public class MultiFormatPane extends JPanel implements Printable {
public MultiFormatPane(UIFactory uif) {
this.uif = uif;
listener = new Listener();
initGUI();
modesToPanes = new HashMap();
addMediaPane(TEXT, textPane);
addMediaPane(AUDIO, musicPane);
addMediaPane(IMAGE, imagePane);
addMediaPane(ERROR, errorPane);
}
public void setNoteField(JTextField noteField) {
this.noteField = noteField;
}
public void setNavigationPane(NavigationPane navPane) {
this.navPane = navPane;
}
public void addMediaPane(int mode, MediaPane pane) {
modesToPanes.put(mode, pane);
}
public MediaPane getMediaPane(int mode) {
return (MediaPane)modesToPanes.get(mode);
}
public void clear() {
currURL = null;
if(navPane != null) {
navPane.clear();
}
musicPane.stopAudio();
}
public URL getPage() {
return currURL;
}
public int getCurrentMode() {
return getCurrentPane().getMode();
}
public MediaPane getCurrentPane() {
return (MediaPane)scrllBody.getViewport().getComponent(0);
}
// Base directory is root directory for displayable content
// if it set, all filenames will be relative to this directory
void setBaseDirectory(File base) {
baseDir = base;
}
File getBaseDirectory() {
return baseDir;
}
void setDefaultView() {
textPane.setDocument(new HTMLDocument());
textPane.showTextArea();
}
private void initGUI() {
uif.initPanel(this, "mfp", false);
textPane = new TextPane(uif, "mfp.textPane", null);
textPane.addHyperlinkListener(listener);
scrllBody = uif.createScrollPane(textPane,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textPane.setParent(scrllBody);
musicPane = new MusicPane(uif, "mfp.audioPane", scrllBody);
imagePane = new ImagePane(uif, "mfp.imagePanelbl", scrllBody);
errorPane = new ErrorFormatPane(uif, "mfp.errorPane", scrllBody);
scrllBody.setViewportView(textPane);
setLayout(new BorderLayout());
add(scrllBody, BorderLayout.CENTER);
}
//Loads everything by URL
public void loadPage(URL url) {
// avoid recursive callbacks from updating combo
if (url.equals(currURL))
return;
currURL = url;
String protocol = url.getProtocol();
File file = new File(url.getFile());
if (protocol.equals("file") && file.isDirectory()) {
String list = listLocalDirectory(file);
textPane.showText(list, "text/html");
((HTMLDocument)textPane.getDocument()).setBase(url);
}
else if (ImagePane.isImageResource(url)) {
imagePane.showImage(url);
}
else if(MusicPane.isAudioResource(url)) {
musicPane.showAudio(url);
}
else if(isMediaResourceCorrupted(url)) {
errorPane.showError(uif.getI18NString("mfp.errorPaneLbl.corrupted"));
}
else if(TextPane.isTextResource(url)){
textPane.showText(url);
}
else {
int response = uif.showYesNoDialog("mfp.unknownTypeDlg");
if(response == JOptionPane.YES_OPTION) {
textPane.showText(url);
}
else {
errorPane.showError(uif.getI18NString("mfp.errorPaneLbl.unsupported"));
}
}
if(navPane != null) {
navPane.processURL(url);
}
}
public void showText(String text, String MIME) {
textPane.showText(text, MIME);
currURL = null;
}
public void showText(URL url) {
textPane.showText(url);
}
public void showAudio(URL url) {
musicPane.showAudio(url);
}
public void stopAudio() {
musicPane.stopAudio();
}
public void showImage(URL url) {
imagePane.showImage(url);
}
public void showError(String errorMessage) {
errorPane.showError(errorMessage);
}
private boolean isMediaResourceSupported(URL url) {
return ImagePane.isImageResource(url) || MusicPane.isAudioResource(url);
}
private boolean isMediaResourceCorrupted(URL url) {
String filename = url.getFile();
String ext = filename.substring(filename.lastIndexOf('.') + 1);
ext = ext.toLowerCase();
return (SUPPORTED_MEDIA_RESOURCE_EXTENSIONS.indexOf(ext) != -1) &&
!isMediaResourceSupported(url);
}
private String listLocalDirectory(File dir) {
if (!dir.isAbsolute())
dir = dir.getAbsoluteFile();
String displayPath = dir.getPath();
// if contains base dir, only show path relative to baseDir
if (baseDir != null) {
String p = baseDir.getParent();
if (p != null
&& displayPath.startsWith(p) &&
(displayPath.length() > p.length())) {
displayPath = displayPath.substring(p.length());
// in case of Unix
if (displayPath.startsWith(File.separator)) {
displayPath = displayPath.substring(1);
}
}
}
String[] filelist = dir.list();
StringWriter sw = new StringWriter();
try {
HTMLWriter out = new HTMLWriter(sw, uif.getI18NResourceBundle());
out.startTag(HTMLWriter.HTML);
out.startTag(HTMLWriter.HEAD);
out.startTag(HTMLWriter.TITLE);
out.write(displayPath);
out.endTag(HTMLWriter.TITLE);
out.endTag(HTMLWriter.HEAD);
out.startTag(HTMLWriter.BODY);
out.writeStyleAttr("font-family: SansSerif; font-size: 12pt");
out.startTag(HTMLWriter.H3);
out.writeI18N("mfp.head", displayPath);
out.endTag(HTMLWriter.H3);
out.startTag(HTMLWriter.UL);
out.writeStyleAttr("margin-left:0");
File parent = dir.getParentFile();
if (parent != null) {
out.startTag(HTMLWriter.LI);
out.startTag(HTMLWriter.OBJECT);
out.writeAttr(HTMLWriter.CLASSID, "com.sun.javatest.tool.IconLabel");
out.writeParam("type", "up");
out.endTag(HTMLWriter.OBJECT);
out.writeEntity(" ");
try {
out.startTag(HTMLWriter.A);
out.writeAttr(HTMLWriter.HREF, parent.toURL().toString());
out.writeI18N("mfp.parent");
out.endTag(HTMLWriter.A);
}
catch (MalformedURLException e) {
out.writeI18N("mfp.parent");
}
}
for (int i = 0; i < filelist.length; i++) {
File file = new File(dir, filelist[i]);
out.startTag(HTMLWriter.LI);
out.startTag(HTMLWriter.OBJECT);
out.writeAttr(HTMLWriter.CLASSID, "com.sun.javatest.tool.IconLabel");
out.writeParam("type", (file.isDirectory() ? "folder" : "file"));
out.endTag(HTMLWriter.OBJECT);
out.writeEntity(" ");
try {
out.writeLink(file.toURL(), file.getName());
}
catch (MalformedURLException e) {
out.write(file.getName());
}
}
out.endTag(HTMLWriter.UL);
out.endTag(HTMLWriter.BODY);
out.endTag(HTMLWriter.HTML);
out.close();
}
catch (IOException e) {
// should not happen, writing to StringWriter
}
return sw.toString();
}
public interface MediaPane {
public int getMode();
public void changeURL(URL url);
public void setParent(JScrollPane pane);
}
// Print this panel
public int print (Graphics g, PageFormat pf, int pageIndex) {
int response = NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
Component componentToBePrinted = scrllBody.getComponent(0);
int mode = getCurrentMode();
switch(mode) {
case TEXT:
componentToBePrinted = textPane;
break;
case IMAGE:
componentToBePrinted = imagePane;
break;
default:
break;
}
// for faster printing, turn off double buffering
disableDoubleBuffering(componentToBePrinted);
Dimension d = componentToBePrinted.getSize();
double panelWidth = d.width;
double panelHeight = d.height;
double pageHeight = pf.getImageableHeight();
double pageWidth = pf.getImageableWidth();
double scale = pageWidth / panelWidth;
int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
if (pageIndex >= totalNumPages) {
response = NO_SUCH_PAGE;
}
else {
// shift Graphic to line up with beginning of print-imageable region
g2.translate(pf.getImageableX(), pf.getImageableY());
// shift Graphic to line up with beginning of next page to print
g2.translate(0f, -pageIndex * pageHeight);
g2.scale(scale, scale);
componentToBePrinted.paint(g2);
enableDoubleBuffering(componentToBePrinted);
response = Printable.PAGE_EXISTS;
}
return response;
}
private void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
private void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
// END of printing
private class Listener implements HyperlinkListener {
public void hyperlinkUpdate(HyperlinkEvent e) {
HyperlinkEvent.EventType et = e.getEventType();
if (et == HyperlinkEvent.EventType.ACTIVATED) {
if (e instanceof HTMLFrameHyperlinkEvent) {
// HTMLDocument doc = (HTMLDocument)
// ((JEditorPane) e.getSource()).getDocument();
// doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) e);
processFrameLink(e);
}
else {
musicPane.stopAudio();
// String s = e.getDescription();
// URL correctURL = e.getURL();
// HTMLDocument doc = (HTMLDocument)((JEditorPane)e.getSource()).getDocument();
// if(doc != null && currURL != null && !doc.getBase().equals(currURL))
// currURL = doc.getBase();
// // JEditorPane doesn't allows javascript, so we delete this parameter and load
// // root page of help package
// if(correctURL.getProtocol().equals("file")) {
// int pos = correctURL.toString().indexOf("?");
// if (pos >= 0) {
// try {
// correctURL = new URL(correctURL.toString().substring(0, pos));
// } catch (MalformedURLException ex) {
// // NONE
// }
// }
// }
// // end of fix
// loadPage(correctURL);
if(e.getURL() == null && e.getDescription().startsWith("#")) {
processSharpLink(e);
}
else {
processGeneralLink(e);
}
}
}
else if (et == HyperlinkEvent.EventType.ENTERED) {
URL u = e.getURL();
if (u != null) {
textPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
if(noteField != null) {
noteField.setText(u.toString());
}
}
}
else if (et == HyperlinkEvent.EventType.EXITED) {
textPane.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
if(noteField != null) {
noteField.setText("");
}
}
}
private void processFrameLink(HyperlinkEvent e) {
HTMLDocument doc = (HTMLDocument)
((JEditorPane) e.getSource()).getDocument();
doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent) e);
}
private void processSharpLink(HyperlinkEvent e) {
String desc = e.getDescription();
if (!(desc.startsWith("#")))
return;
textPane.scrollToReference(desc.substring(1));
}
private void processGeneralLink(HyperlinkEvent e) {
URL correctURL = e.getURL();
HTMLDocument doc = (HTMLDocument)((JEditorPane)e.getSource()).getDocument();
if(doc != null && currURL != null && !doc.getBase().equals(currURL))
currURL = doc.getBase();
// fix of CR 6451318, CR 6442782 and CR 6447246
// JDTS use '?' notation to pass parameter (currently loaded page of one of frames)
// to javascript.
// JEditorPane doesn't allows javascript, so we delete this parameter and load
// root page of help package
if(correctURL.getProtocol().equals("file")) {
int pos = correctURL.toString().indexOf("?");
if (pos >= 0) {
try {
correctURL = new URL(correctURL.toString().substring(0, pos));
} catch (MalformedURLException ex) {
// NONE
}
}
}
// end of fix
loadPage(correctURL);
}
}
private static final String SUPPORTED_MEDIA_RESOURCE_EXTENSIONS =
".wav .au .aif .mid .midi .rmf .jpeg .jpg .gif .png";
private JScrollPane scrllBody;
public static final int TEXT = 0;
public static final int IMAGE = 1;
public static final int AUDIO = 2;
public static final int ERROR = 3;
private File baseDir;
private URL currURL;
private TextPane textPane;
private MusicPane musicPane;
private ImagePane imagePane;
private ErrorFormatPane errorPane;
private UIFactory uif;
private String uiKey;
private Listener listener;
private JTextField noteField;
private NavigationPane navPane;
private HashMap modesToPanes;
}
class TextPane extends JEditorPane implements MultiFormatPane.MediaPane {
public TextPane(UIFactory uif, String uiKey, JScrollPane owner) {
super();
this.uif = uif;
this.owner = owner;
setName("text");
setEditable(false);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
uif.setAccessibleInfo(this, uiKey);
htmlKit = new HTMLEditorKit();
defaultKit = new DefaultEditorKit();
rtfKit = new RTFEditorKit();
}
public void changeURL(URL url) {}
public void setParent(JScrollPane owner) {
this.owner = owner;
}
public int getMode() {
return MultiFormatPane.TEXT;
}
public void showText(String text, String MIME) {
setContentType(MIME);
EditorKit kit = getKitByMIME(MIME);
Document doc = kit.createDefaultDocument();
setDocument(doc);
setText(text);
showTextArea();
}
public void showText(URL url) {
try {
URL loaded = getPage();
String mimeType = getMIMEType(url);
if (mimeType == null) {
mimeType = "text/plain";
}
boolean loadManually = false;
if (mimeType.indexOf("plain") != -1) {
loadManually = true;
}
EditorKit kit = getKitByMIME(mimeType);
setContentType(mimeType);
if (loaded == null || !loaded.sameFile(url)) {
Document doc = kit.createDefaultDocument();
setDocument(doc);
}
if (loadManually && "file".equals(url.getProtocol())) {
File file = new File(url.getFile());
try {
Reader r = new BufferedReader(new FileReader(file));
read(r, url);
r.close();
}
catch (IOException e) {
uif.showError("mfp.load.error", new Object[] { url, e });
}
} else {
setPage(url);
}
showTextArea();
}
catch (IOException e) {
uif.showError("mfp.load.error", new Object[] { url, e });
}
}
public static boolean isTextResource(URL url) {
String mimeType = getMIMEType(url);
if (mimeType == null)
return false;
return (mimeType.equals("text/plain") || mimeType.equals("text/html") ||
mimeType.equals("text/rtf"));
}
public static String getMIMEType(URL url) {
String filename = url.getFile();
String ext = filename.substring(filename.lastIndexOf('.') + 1);
ext = ext.toLowerCase();
return (String)extensionsToMIME.get(ext);
}
public void showTextArea() {
owner.setViewportView(this);
owner.revalidate();
owner.repaint();
}
private EditorKit getKitByMIME(String mime) {
if(mime.indexOf("rtf") != -1)
return rtfKit;
else if(mime.indexOf("html") != -1)
return htmlKit;
else {
return defaultKit;
}
}
private JScrollPane owner;
private UIFactory uif;
private HTMLEditorKit htmlKit;
private DefaultEditorKit defaultKit;
private RTFEditorKit rtfKit;
private static HashMap extensionsToMIME;
static {
extensionsToMIME = new HashMap();
extensionsToMIME.put("html", "text/html");
extensionsToMIME.put("htm", "text/html");
extensionsToMIME.put("htmls", "text/html");
extensionsToMIME.put("htx", "text/html");
extensionsToMIME.put("shtml", "text/html");
extensionsToMIME.put("stm", "text/html");
extensionsToMIME.put("text", "text/plain");
extensionsToMIME.put("txt", "text/plain");
extensionsToMIME.put("log", "text/plain");
extensionsToMIME.put("list", "text/plain");
extensionsToMIME.put("lst", "text/plain");
extensionsToMIME.put("java", "text/plain");
extensionsToMIME.put("xml", "text/plain");
extensionsToMIME.put("jtr", "text/plain");
extensionsToMIME.put("jti", "text/plain");
extensionsToMIME.put("jtm", "text/plain");
extensionsToMIME.put("css", "text/plain");
extensionsToMIME.put("rtf", "text/rtf");
extensionsToMIME.put("rtx", "text/rtf");
}
}
class MusicPane extends JPanel implements MultiFormatPane.MediaPane {
public MusicPane(UIFactory uif, String uiKey, JScrollPane owner) {
super();
this.uif = uif;
this.owner = owner;
initGUI(uiKey);
}
private void initGUI(String uiKey) {
setName(uiKey);
uif.setAccessibleInfo(this, uiKey);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
btnStart = uif.createButton(uiKey + ".btnStart");
btnStop = uif.createButton(uiKey + ".btnStop");
btnLoop = uif.createButton(uiKey + ".btnLoop");
add(btnStart, gbc);
add(btnStop, gbc);
add(btnLoop, gbc);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(isSampledAudioResource(currURL)) {
loadSample(currURL);
clip.start();
}
else if(isMidiAudioResource(currURL)) {
loadSequence(currURL);
sequencer.start();
}
}
});
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stopAudio();
}
});
btnLoop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(isSampledAudioResource(currURL)) {
loadSample(currURL);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
}
});
}
public void showAudio(URL url) {
changeURL(url);
owner.setViewportView(this);
owner.revalidate();
owner.repaint();
}
public void changeURL(URL url) {
currURL = url;
if(isMidiAudioResource(url)) {
btnLoop.setEnabled(false);
}
else if(isSampledAudioResource(url)) {
btnLoop.setEnabled(true);
}
}
public void setParent(JScrollPane owner) {
this.owner = owner;
}
public int getMode() {
return MultiFormatPane.AUDIO;
}
public static boolean isAudioResource(URL url) {
return isSampledAudioResource(url) || isMidiAudioResource(url);
}
public void stopAudio() {
if(clip != null && clip.isRunning()) {
clip.stop();
clip.flush();
clip.close();
}
if(sequencer != null && sequencer.isRunning())
sequencer.stop();
}
private void loadSample(URL url) {
try {
AudioInputStream stream = AudioSystem.getAudioInputStream(url);
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(
Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize()));
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.addLineListener(new LineListener() {
public void update(LineEvent e) {
if(e.getType() == LineEvent.Type.STOP) {
clip.stop();
}
}
});
} catch (Exception e) {
clip.close();
}
}
private void loadSequence(URL url) {
try {
Sequence sequence = MidiSystem.getSequence(url);
// Create a sequencer for the sequence
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);
} catch (Exception e) {}
}
private static boolean isSampledAudioResource(URL url) {
try{
AudioFileFormat fformat = AudioSystem.getAudioFileFormat(url);
return AudioSystem.isFileTypeSupported(fformat.getType());
} catch (UnsupportedAudioFileException unsuppExc) {
return false;
} catch (IOException ioExc) {
return false;
}
}
private static boolean isMidiAudioResource(URL url) {
try {
MidiFileFormat fformat = MidiSystem.getMidiFileFormat(url);
Sequence sequence = MidiSystem.getSequence(url);
return MidiSystem.isFileTypeSupported(fformat.getType());
} catch (InvalidMidiDataException invalidDataExc) {
return false;
} catch (IOException ioExc) {
return false;
}
catch (Exception exc) {
return false;
}
}
private UIFactory uif;
private JScrollPane owner;
private JButton btnStart;
private JButton btnStop;
private JButton btnLoop;
private URL currURL;
private Clip clip;
private Sequencer sequencer;
}
class ImagePane extends JLabel implements MultiFormatPane.MediaPane {
public ImagePane(UIFactory uif, String uiKey, JScrollPane owner) {
super(uif.getI18NString(uiKey + ".lbl"));
// setName(uiKey);
this.owner = owner;
}
public void changeURL(URL url) {}
public void setParent(JScrollPane owner) {
this.owner = owner;
}
public int getMode() {
return MultiFormatPane.IMAGE;
}
public void showImage(URL url) {
if(isImageFormatSupported(url)) {
ImageIcon img = new ImageIcon(url);
setIcon(img);
owner.setViewportView(this);
owner.revalidate();
owner.repaint();
}
}
public static boolean isImageResource(URL url) {
String file = url.getFile();
String ext = file.substring(file.lastIndexOf('.')+1);
Iterator iter = ImageIO.getImageReadersBySuffix(ext);
return iter.hasNext();
}
public static boolean isImageFormatSupported(URL url) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(new File(url.getFile()));
Iterator iter = ImageIO.getImageReaders(iis);
if(!iter.hasNext())
return false;
} catch (IOException exc) {
exc.printStackTrace();
return false;
}
return true;
}
private JScrollPane owner;
}
class ErrorFormatPane extends JPanel implements MultiFormatPane.MediaPane {
public ErrorFormatPane(UIFactory uif, String uiKey, JScrollPane owner) {
super();
uif.initPanel(this, uiKey, true);
this.owner = owner;
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = gbc.CENTER;
errorLabel = uif.createLabel("mfp.errorPaneLbl", true);
add(errorLabel, gbc);
}
public void changeURL(URL url) {}
public void setParent(JScrollPane owner) {
this.owner = owner;
}
public int getMode() {
return MultiFormatPane.ERROR;
}
public void showError(String errorMessage) {
errorLabel.setText(errorMessage);
owner.setViewportView(this);
owner.revalidate();
owner.repaint();
}
private JLabel errorLabel;
private JScrollPane owner;
}
|