0001: package com.xoetrope.carousel.langed;
0002:
0003: import com.dawidweiss.util.lang.AdaptiveClassLoader;
0004: import java.beans.PropertyChangeEvent;
0005: import java.beans.PropertyChangeListener;
0006: import java.io.BufferedReader;
0007: import java.io.File;
0008: import java.io.FileInputStream;
0009: import java.io.IOException;
0010: import java.io.InputStreamReader;
0011: import java.net.MalformedURLException;
0012: import java.net.URL;
0013: import java.util.Comparator;
0014: import java.util.Vector;
0015: import java.util.prefs.Preferences;
0016: import java.util.zip.ZipInputStream;
0017:
0018: import java.awt.BorderLayout;
0019: import java.awt.Color;
0020: import java.awt.Component;
0021: import java.awt.Dimension;
0022: import java.awt.Font;
0023: import java.awt.FontMetrics;
0024: import java.awt.Graphics;
0025: import java.awt.Toolkit;
0026: import java.awt.datatransfer.Clipboard;
0027: import java.awt.datatransfer.DataFlavor;
0028: import java.awt.datatransfer.StringSelection;
0029: import java.awt.datatransfer.Transferable;
0030: import java.awt.datatransfer.UnsupportedFlavorException;
0031: import java.awt.event.ActionEvent;
0032: import java.awt.event.ActionListener;
0033: import java.awt.event.FocusEvent;
0034: import java.awt.event.FocusListener;
0035: import java.awt.event.ItemEvent;
0036: import java.awt.event.ItemListener;
0037: import java.awt.event.KeyEvent;
0038: import java.awt.event.KeyListener;
0039: import javax.swing.BoxLayout;
0040: import javax.swing.ImageIcon;
0041: import javax.swing.JCheckBoxMenuItem;
0042: import javax.swing.JComboBox;
0043: import javax.swing.JFileChooser;
0044: import javax.swing.JFrame;
0045: import javax.swing.JLabel;
0046: import javax.swing.JList;
0047: import javax.swing.JMenu;
0048: import javax.swing.JMenuBar;
0049: import javax.swing.JMenuItem;
0050: import javax.swing.JOptionPane;
0051: import javax.swing.JPanel;
0052: import javax.swing.JScrollPane;
0053: import javax.swing.JSplitPane;
0054: import javax.swing.JTextArea;
0055: import javax.swing.JTextField;
0056: import javax.swing.JTextPane;
0057: import javax.swing.KeyStroke;
0058: import javax.swing.ListCellRenderer;
0059: import javax.swing.SwingConstants;
0060: import javax.swing.border.EmptyBorder;
0061: import javax.swing.event.ListSelectionEvent;
0062: import javax.swing.event.ListSelectionListener;
0063: import javax.swing.text.BadLocationException;
0064: import javax.swing.text.DefaultStyledDocument;
0065: import javax.swing.text.MutableAttributeSet;
0066: import javax.swing.text.SimpleAttributeSet;
0067: import javax.swing.text.StyleConstants;
0068:
0069: import com.swabunga.spell.engine.SpellDictionary;
0070: import com.xoetrope.carousel.build.BuildProperties;
0071: import com.xoetrope.util.XTextDefaults;
0072: import java.lang.reflect.Method;
0073: import java.net.URISyntaxException;
0074: import java.net.URLDecoder;
0075: import javax.swing.SwingUtilities;
0076: import net.xoetrope.debug.DebugLogger;
0077: import net.xoetrope.editor.XEditorDefaults;
0078: import net.xoetrope.editor.project.XEditorProject;
0079: import net.xoetrope.editor.project.pages.IEditorUtility;
0080: import net.xoetrope.xui.XApplicationContext;
0081: import net.xoetrope.xui.XProjectManager;
0082:
0083: /**
0084: * <p> Copyright (c) Xoetrope Ltd., 2001-2006, This software is licensed under
0085: * the GNU Public License (GPL), please see license.txt for more details. If
0086: * you make commercial use of this software you must purchase a commercial
0087: * license from Xoetrope.</p>
0088: * <p> $Revision: 1.15 $</p>
0089: */
0090: class IdCellRenderer extends JLabel implements ListCellRenderer {
0091: private boolean cellHasFocus = false;
0092:
0093: public IdCellRenderer() {
0094: setOpaque(true);
0095: }
0096:
0097: public Component getListCellRendererComponent(JList list,
0098: Object value, int index, boolean isSelected,
0099: boolean _cellHasFocus) {
0100: setText(value.toString());
0101:
0102: cellHasFocus = _cellHasFocus;
0103: if (isSelected) {
0104: setBackground(list.getSelectionBackground());
0105: setForeground(list.getSelectionForeground());
0106: } else {
0107: setBackground(list.getBackground());
0108: setForeground(list.getForeground());
0109: }
0110:
0111: return this ;
0112: }
0113:
0114: public void paintComponent(Graphics g) {
0115: int w = getWidth();
0116: int h = getHeight();
0117:
0118: g.setFont(getFont());
0119: FontMetrics fm = g.getFontMetrics();
0120: g.setColor(getBackground());
0121: g.fillRect(0, 0, w, h);
0122:
0123: int idWidth = (int) fm.getStringBounds("9999", g).getWidth();
0124: String text = getText();
0125: int pos = text.indexOf('|');
0126: g.setColor(new Color(236, 245, 255));
0127: g.fillRect(0, 0, idWidth, h);
0128: g.setColor(Color.gray);
0129: g.drawLine(idWidth, 0, idWidth++, h);
0130:
0131: int textOffset = h - fm.getDescent() - 1;
0132: if (pos < 0) {
0133: g.setColor(getForeground());
0134: g.drawString(text, 0, textOffset);
0135: } else {
0136: int id = Integer.parseInt(text.substring(0, pos));
0137: g.drawString(Integer.toString(id), 1, textOffset);
0138: g.setColor(getForeground());
0139: g.drawString(text.substring(pos + 1), idWidth + 3,
0140: textOffset);
0141: }
0142:
0143: if (cellHasFocus) {
0144: /**
0145: * @todo fix the colour
0146: */
0147: g.setColor(Color.red);
0148: g.drawRect(0, 0, w - 1, h - 1);
0149: }
0150: }
0151:
0152: public Dimension getPreferredSize() {
0153: Dimension dim = super .getPreferredSize();
0154: return new Dimension(dim.width, dim.height + 2);
0155: }
0156: }
0157:
0158: /**
0159: * The main panel of the language editor
0160: * <p>Copyright: Xoetrope Ltd. (c) 2001-2006. All Rights Reserved.
0161: * This software is licensed under the GNU Public License (GPL) see license.txt
0162: * for more details on licensing</p>
0163: */
0164: public class LangEdPanel extends JPanel implements ItemListener {
0165: JComboBox sourceLangList, targetLangList;
0166: JSplitPane splitPane;
0167: JSplitPane leftSplitPane;
0168: JSplitPane rightSplitPane;
0169: JLabel previewTitle, sourceTranslationLabel,
0170: targetTranslationCaption;
0171: JList sourceList;
0172: JList targetList;
0173: JTextArea targetEdit;
0174: JTextArea hintArea;
0175: JTextPane previewArea;
0176: JScrollPane leftScroller;
0177: JScrollPane rightScroller;
0178: LangListModel sourceLangModel;
0179: LangListModel targetLangModel;
0180: EdLanguage refLang;
0181: EdLanguage sourceLang;
0182: EdLanguage targetLang;
0183: EdLanguage hintsLang;
0184: EdLangMgr langMgr;
0185: JMenuBar mainMenuBar;
0186: JMenu mainMenu;
0187: JMenu sourceMenu, targetMenu;
0188: JMenu langMenu;
0189: JMenu helpMenu;
0190: String targetString, hintString;
0191: boolean usesDatabaseSource = false;
0192: boolean previewUsingSource = false;
0193: boolean previewStringLength = false;
0194:
0195: private boolean useUpperCase = true;
0196: private boolean bIsStandalone = false;
0197: private boolean isPlugin = false;
0198: private URL url;
0199: public static Font defaultFont = XEditorDefaults.defaultFont;
0200: private JFrame frame;
0201: private boolean sourceListChanging = false;
0202:
0203: private char delimiterStartChar = '{';
0204: private char delimiterEndChar = '}';
0205: private Preferences prefs;
0206: private JTextComponentSpellChecker spellChecker;
0207:
0208: private static String dictionaryFile = "/english.zip";
0209: private SpellDictionary dictionary;
0210: private MutableAttributeSet normal, bold;
0211:
0212: private XEditorProject currentProject;
0213:
0214: public LangEdPanel(XEditorProject proj, boolean _bIsStandalone,
0215: boolean _isPlugin, URL _url, EdLangMgr lm,
0216: JComboBox sourceList, JComboBox targetList,
0217: JMenuBar _mainMenuBar) {
0218: currentProject = proj;
0219: prefs = Preferences.userNodeForPackage(LangEdDesktop.class);
0220: setBorder(null);
0221: bIsStandalone = _bIsStandalone;
0222: isPlugin = _isPlugin;
0223: url = _url;
0224: langMgr = lm;
0225: mainMenuBar = _mainMenuBar;
0226: sourceLangList = sourceList;
0227: targetLangList = targetList;
0228: sourceLangList.addItemListener(this );
0229: targetLangList.addItemListener(this );
0230:
0231: setDoubleBuffered(true);
0232: setLayout(new BorderLayout());
0233:
0234: delimiterStartChar = prefs.get("delimiterStartChar",
0235: "" + delimiterStartChar).charAt(0);
0236: delimiterEndChar = prefs.get("delimiterEndChar",
0237: "" + delimiterEndChar).charAt(0);
0238: dictionaryFile = prefs.get("dictionaryFile", ""
0239: + dictionaryFile);
0240: previewUsingSource = (prefs.get("previewUsingSource", "0")
0241: .charAt(0) == '1');
0242: previewStringLength = (prefs.get("previewStringLength", "1")
0243: .charAt(0) == '1');
0244:
0245: try {
0246: jbInit();
0247: } catch (Exception ex) {
0248: ex.printStackTrace();
0249: }
0250: }
0251:
0252: void jbInit() throws Exception {
0253: normal = new SimpleAttributeSet();
0254: StyleConstants.setFontFamily(normal, "Tahoma");
0255: StyleConstants.setBold(normal, false);
0256: StyleConstants.setFontSize(normal, 11);
0257:
0258: bold = new SimpleAttributeSet();
0259: StyleConstants.setFontFamily(bold, "Tahoma");
0260: StyleConstants.setFontSize(bold, 11);
0261: StyleConstants.setBackground(normal, new Color(228, 228, 228));
0262:
0263: if (langMgr == null) {
0264: if (currentProject != null)
0265: langMgr = (EdLangMgr) currentProject
0266: .getObject("LanguageManager");
0267:
0268: if (langMgr == null) {
0269: langMgr = new EdLangMgr(bIsStandalone, url);
0270: if (currentProject != null)
0271: currentProject
0272: .setObject("LanguageManager", langMgr);
0273: }
0274: }
0275: if (langMgr.getNumLangs() > 0)
0276: refLang = langMgr.getLang(0);
0277: else
0278: refLang = null;
0279: updateHints(langMgr);
0280:
0281: setupSpelling(false);
0282: createSplitPane();
0283: sourceList.setSelectedIndex(0);
0284:
0285: if (LangFrame.isStandalone)
0286: setupMenus();
0287: }
0288:
0289: void setupLangMenu() {
0290: if (langMenu == null) {
0291: langMenu = new JMenu("Language");
0292: if (LanguageEditorApplication.defaultFont != null)
0293: langMenu.setFont(LanguageEditorApplication.defaultFont);
0294: langMenu.setMnemonic('L');
0295: if (mainMenu != null)
0296: mainMenu.add(langMenu);
0297: else if (mainMenuBar != null)
0298: mainMenuBar.add(langMenu);
0299: } else
0300: langMenu.removeAll();
0301:
0302: boolean wasExported = langMgr.isLoadedFromExportedFiles();
0303:
0304: JMenuItem mi = new JMenuItem("New Language...");
0305: if (LanguageEditorApplication.defaultFont != null)
0306: mi.setFont(LanguageEditorApplication.defaultFont);
0307: mi.setMnemonic('N');
0308: mi
0309: .setEnabled(((langMgr.getUrl() != null) || usesDatabaseSource)
0310: && !wasExported);
0311: mi.addActionListener(new ActionListener() {
0312: public void actionPerformed(ActionEvent e) {
0313: newLanguage();
0314: }
0315: });
0316: langMenu.add(mi);
0317:
0318: langMenu.addSeparator();
0319:
0320: boolean langsAvailable = (langMgr.getNumLangs() > 0);
0321: mi = new JMenuItem("New string");
0322: if (LanguageEditorApplication.defaultFont != null)
0323: mi.setFont(LanguageEditorApplication.defaultFont);
0324: mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
0325: java.awt.event.InputEvent.CTRL_MASK));
0326: mi.setMnemonic('s');
0327: mi.setEnabled(langsAvailable && !wasExported);
0328: mi.addActionListener(new ActionListener() {
0329: public void actionPerformed(ActionEvent e) {
0330: newString();
0331: }
0332: });
0333: langMenu.add(mi);
0334:
0335: mi = new JMenuItem("Delete string");
0336: if (LanguageEditorApplication.defaultFont != null)
0337: mi.setFont(LanguageEditorApplication.defaultFont);
0338: mi.setMnemonic('D');
0339: mi.setEnabled(langsAvailable && !wasExported);
0340: mi.addActionListener(new ActionListener() {
0341: public void actionPerformed(ActionEvent e) {
0342: deleteString();
0343: }
0344: });
0345: langMenu.add(mi);
0346:
0347: langMenu.addSeparator();
0348:
0349: mi = new JMenuItem("Add missing strings");
0350: if (LanguageEditorApplication.defaultFont != null)
0351: mi.setFont(LanguageEditorApplication.defaultFont);
0352: mi.setMnemonic('D');
0353: mi.setEnabled(langsAvailable);
0354: mi.addActionListener(new ActionListener() {
0355: public void actionPerformed(ActionEvent e) {
0356: addMissingStrings(false);
0357: }
0358: });
0359:
0360: langMenu.add(mi);
0361:
0362: mi = new JMenuItem("Machine Translation...");
0363: if (LanguageEditorApplication.defaultFont != null)
0364: mi.setFont(LanguageEditorApplication.defaultFont);
0365: mi.setMnemonic('M');
0366: mi.setEnabled(langsAvailable);
0367: mi.addActionListener(new ActionListener() {
0368: public void actionPerformed(ActionEvent e) {
0369: machineTranslation();
0370: }
0371: });
0372: langMenu.add(mi);
0373:
0374: mi = new JMenuItem("Strip delimiter symbols");
0375: if (LanguageEditorApplication.defaultFont != null)
0376: mi.setFont(LanguageEditorApplication.defaultFont);
0377: mi.setMnemonic('S');
0378: mi.setEnabled(langsAvailable);
0379: mi.addActionListener(new ActionListener() {
0380: public void actionPerformed(ActionEvent e) {
0381: stripSymbols();
0382: }
0383: });
0384: langMenu.add(mi);
0385:
0386: langMenu.addSeparator();
0387:
0388: mi = new JMenuItem("Set delimiter start symbol...");
0389: if (LanguageEditorApplication.defaultFont != null)
0390: mi.setFont(LanguageEditorApplication.defaultFont);
0391: mi.setMnemonic('D');
0392: mi.setEnabled(langsAvailable);
0393: mi.addActionListener(new ActionListener() {
0394: public void actionPerformed(ActionEvent e) {
0395: setDelimiters(true);
0396: }
0397: });
0398: langMenu.add(mi);
0399:
0400: mi = new JMenuItem("Set delimiter end symbol...");
0401: if (LanguageEditorApplication.defaultFont != null)
0402: mi.setFont(LanguageEditorApplication.defaultFont);
0403: mi.setMnemonic('D');
0404: mi.setEnabled(langsAvailable);
0405: mi.addActionListener(new ActionListener() {
0406: public void actionPerformed(ActionEvent e) {
0407: setDelimiters(false);
0408: }
0409: });
0410: langMenu.add(mi);
0411:
0412: langMenu.addSeparator();
0413:
0414: mi = new JMenuItem("Spell check setup...");
0415: if (LanguageEditorApplication.defaultFont != null)
0416: mi.setFont(LanguageEditorApplication.defaultFont);
0417: mi.setMnemonic('t');
0418: mi.setEnabled(langsAvailable);
0419: mi.addActionListener(new ActionListener() {
0420: public void actionPerformed(ActionEvent e) {
0421: setupSpelling(true);
0422: }
0423: });
0424: langMenu.add(mi);
0425:
0426: mi = new JMenuItem("Check spelling...");
0427: if (LanguageEditorApplication.defaultFont != null)
0428: mi.setFont(LanguageEditorApplication.defaultFont);
0429: mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
0430: java.awt.event.InputEvent.CTRL_MASK));
0431: mi.setMnemonic('L');
0432: mi.setEnabled(langsAvailable);
0433: mi.addActionListener(new ActionListener() {
0434: public void actionPerformed(ActionEvent e) {
0435: checkSpelling();
0436: }
0437: });
0438: langMenu.add(mi);
0439:
0440: langMenu.addSeparator();
0441:
0442: mi = new JMenuItem("Swap preview language");
0443: if (LanguageEditorApplication.defaultFont != null)
0444: mi.setFont(LanguageEditorApplication.defaultFont);
0445: mi.setMnemonic('P');
0446: mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
0447: java.awt.event.InputEvent.CTRL_MASK));
0448: mi.setEnabled(langsAvailable);
0449: mi.addActionListener(new ActionListener() {
0450: public void actionPerformed(ActionEvent e) {
0451: swapPreviewLanguage();
0452: }
0453: });
0454: langMenu.add(mi);
0455:
0456: JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
0457: "Preview source length");
0458: if (LanguageEditorApplication.defaultFont != null)
0459: cbmi.setFont(LanguageEditorApplication.defaultFont);
0460: cbmi.setHorizontalTextPosition(SwingConstants.LEADING);
0461: cbmi.setState(previewStringLength);
0462: mi = cbmi;
0463: mi.setMnemonic('w');
0464: mi.setEnabled(langsAvailable);
0465: mi.addActionListener(new ActionListener() {
0466: public void actionPerformed(ActionEvent e) {
0467: swapPreviewLength();
0468: }
0469: });
0470: langMenu.add(mi);
0471: }
0472:
0473: String getTargetCode() {
0474: if (targetLang != null)
0475: return targetLang.getLangCode();
0476:
0477: return "en";
0478: }
0479:
0480: void setupTargetLangList() {
0481: targetLangList.removeAllItems();
0482:
0483: int numLangs = langMgr.getNumLangs();
0484: for (int iLang = 0; iLang < numLangs; iLang++) {
0485: String langName = langMgr.getLangName(iLang);
0486: targetLangList.addItem(langName);
0487: if ((targetLang != null)
0488: && (langName.compareTo(targetLang.getLangName()) == 0))
0489: targetLangList.setSelectedIndex(iLang);
0490: }
0491: }
0492:
0493: private void setTargetLang(String langName) {
0494: EdLanguage tempLang = langMgr.getLang(langName);
0495: if (targetLang != tempLang) {
0496: targetLang = tempLang;
0497: targetLangModel = new LangListModel(targetLang, false,
0498: false);
0499: targetList.setModel(targetLangModel);
0500: }
0501: }
0502:
0503: void setupSourceLangList() {
0504: sourceLangList.removeAllItems();
0505:
0506: int numLangs = langMgr.getNumLangs();
0507: for (int iLang = 0; iLang < numLangs; iLang++) {
0508: String langName = langMgr.getLangName(iLang);
0509: sourceLangList.addItem(langName);
0510: if ((targetLang != null)
0511: && (langName.compareTo(sourceLang.getLangName()) == 0))
0512: sourceLangList.setSelectedIndex(iLang);
0513: }
0514: }
0515:
0516: private void setSourceLang(String langName) {
0517: EdLanguage tempLang = langMgr.getLang(langName);
0518: if (sourceLang != tempLang) {
0519: sourceLang = tempLang;
0520: sourceLangModel = new LangListModel(sourceLang, true,
0521: sourceLang == refLang);
0522: sourceList.setModel(sourceLangModel);
0523: }
0524: }
0525:
0526: public void openFile(File theFile) {
0527: if (theFile.getName().indexOf(".xls") > 0) {
0528: importFile(theFile, false);
0529: return;
0530: }
0531:
0532: usesDatabaseSource = false;
0533: try {
0534: String prefix = "file:"
0535: + System.getProperty("file.separator")
0536: + theFile.toString();
0537:
0538: langMgr.setProjectPath(theFile.getParent());
0539: langMgr.init(new URL(prefix));
0540: update(langMgr);
0541: } catch (MalformedURLException ex1) {
0542: System.out.println("Malformed URL ="
0543: + theFile.getAbsolutePath() + ": "
0544: + ex1.getMessage());
0545: } catch (IOException ex2) {
0546: System.out.println("IOException reading( "
0547: + theFile.getAbsolutePath() + ": "
0548: + ex2.getMessage());
0549: }
0550:
0551: setupMenus();
0552: }
0553:
0554: public void importFile(File theFile, boolean isPropertiesFile) {
0555: usesDatabaseSource = false;
0556: try {
0557: if (isPropertiesFile) {
0558: String code = theFile.getName();
0559: code = code.substring(0, code.indexOf('.'));
0560: langMgr.importPropertiesFile(theFile, code, code);
0561: } else if (theFile.getPath().indexOf(".xls") > 0)
0562: langMgr.importExcel(this , theFile);
0563: else
0564: langMgr.importFile(this , theFile);
0565: update(langMgr);
0566: updateHints(langMgr);
0567: } catch (Exception ex2) {
0568: System.out.println("Exception: " + ex2);
0569: }
0570:
0571: setupMenus();
0572: setSourceLang((String) sourceLangList.getSelectedItem());
0573: setTargetLang((String) targetLangList.getSelectedItem());
0574: }
0575:
0576: public void exportFile(File theFile, String[] languageList,
0577: boolean exportExcel) {
0578: try {
0579: if (exportExcel)
0580: langMgr.exportExcel(theFile, languageList);
0581: else
0582: langMgr.exportFile(theFile, delimiterStartChar,
0583: delimiterEndChar, languageList);
0584: } catch (Exception ex2) {
0585: System.out.println("Exception: " + ex2);
0586: }
0587: }
0588:
0589: public void openFile(Vector languages, Vector translations) {
0590: usesDatabaseSource = true;
0591: try {
0592: langMgr.init(languages, translations);
0593: update(langMgr);
0594: } catch (IOException ex) {
0595: ex.printStackTrace();
0596: }
0597: setupMenus();
0598: }
0599:
0600: private void setupMenus() {
0601: setupSourceLangList();
0602: setupTargetLangList();
0603: setupLangMenu();
0604: }
0605:
0606: private void updateHints(EdLangMgr lm) {
0607: // Try to pick the hints language
0608: int numLangs = langMgr.getNumLangs();
0609: if (usesDatabaseSource)
0610: hintsLang = langMgr.getLang(1);
0611: else {
0612: for (int i = 0; i < numLangs; i++) {
0613: EdLanguage lang = langMgr.getLang(i);
0614: if (lang.getLangCode().toLowerCase().equals("ht")) {
0615: hintsLang = lang;
0616: break;
0617: }
0618: }
0619: }
0620: }
0621:
0622: private void update(EdLangMgr lm) {
0623: langMgr = lm;
0624: refLang = langMgr.getLang(0);
0625: sourceLang = langMgr.getCurrentLang();
0626:
0627: updateHints(lm);
0628: int numLangs = langMgr.getNumLangs();
0629: if (numLangs > 1) {
0630: // This should be ENGLISH
0631: if (!usesDatabaseSource && (hintsLang == null))
0632: targetLang = langMgr.getLang(1);
0633: else
0634: targetLang = langMgr.getLang(2);
0635:
0636: if (targetLang == null)
0637: targetLang = sourceLang;
0638: } else
0639: targetLang = sourceLang;
0640:
0641: sourceLangModel = new LangListModel(sourceLang, true,
0642: sourceLang == refLang);
0643: targetLangModel = new LangListModel(targetLang, false, false);
0644: sourceList.setModel(sourceLangModel);
0645: targetList.setModel(targetLangModel);
0646: sourceList.setSelectedIndex(0);
0647: sourceList.doLayout();
0648:
0649: setupSourceLangList();
0650: setupTargetLangList();
0651: }
0652:
0653: public void newFile(String file) {
0654: try {
0655: if (langMgr == null) {
0656: langMgr = (EdLangMgr) currentProject
0657: .getObject("LanguageManager");
0658: if (langMgr == null) {
0659: String prefix = "file:"
0660: + System.getProperty("file.separator")
0661: + file;
0662: langMgr = new EdLangMgr(bIsStandalone, new URL(
0663: prefix));
0664: currentProject
0665: .setObject("LanguageManager", langMgr);
0666: }
0667: } else
0668: return;
0669:
0670: targetLang = null;
0671:
0672: addLanguage("cm", "Reference", null);
0673: refLang = langMgr.getLang(0);
0674:
0675: langMgr.saveFile(delimiterStartChar, delimiterEndChar);
0676: } catch (MalformedURLException ex1) {
0677: System.out.println("Malformed URL =" + file + ": "
0678: + ex1.getMessage());
0679: } catch (IOException ex2) {
0680: System.out.println("IOException reading " + file + ": "
0681: + ex2.getMessage());
0682: }
0683: }
0684:
0685: /**
0686: *
0687: * @param prompt prompt for the save directory if none is present
0688: */
0689: public void saveFile(boolean prompt) {
0690: if (prompt && (url == null)) {
0691: Preferences prefs = Preferences
0692: .userNodeForPackage(LangEdDesktop.class);
0693: String fileName = prefs.get("lastSaveName", "c:\\");
0694: JFileChooser fileDialog = new JFileChooser();
0695: fileDialog
0696: .setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
0697: fileDialog.setFileHidingEnabled(false);
0698: fileDialog.setCurrentDirectory(new File(fileName));
0699:
0700: int retval = fileDialog.showSaveDialog(this );
0701: if (retval == JFileChooser.APPROVE_OPTION) {
0702: File theFile = fileDialog.getSelectedFile();
0703: if (theFile == null)
0704: return;
0705:
0706: try {
0707: theFile = new File(
0708: theFile.getCanonicalPath()
0709: + (System
0710: .getProperty("file.separator") + "exportedLang.lst"));
0711: prefs.put("lastSaveName", theFile
0712: .getCanonicalPath());
0713: url = theFile.toURL();
0714: langMgr.setUrl(url);
0715: } catch (Exception ex) {
0716: }
0717: } else
0718: JOptionPane.showMessageDialog(this ,
0719: "No file was chosen.");
0720: }
0721:
0722: langMgr.saveFile(delimiterStartChar, delimiterEndChar);
0723: }
0724:
0725: public void setCurrentLang() {
0726: int numLangs = langMgr.getNumLangs();
0727: String[] langs = new String[numLangs];
0728: int currentLangIndex = 0;
0729: for (int i = 0; i < numLangs; i++) {
0730: EdLanguage lang = langMgr.getLangFromList(i);
0731: langs[i] = lang.getLangName();
0732: }
0733:
0734: JComboBox langCombo = new JComboBox(langs);
0735: langCombo.setSelectedItem(langMgr.getCurrentLang()
0736: .getLangName());
0737:
0738: Object[] content = new Object[2];
0739: content[0] = "Code";
0740: content[1] = langCombo;
0741:
0742: String[] options = { "OK", "Cancel" };
0743: int rc = 1;
0744: rc = JOptionPane
0745: .showOptionDialog((JFrame) null, content,
0746: "Set Current Language",
0747: JOptionPane.DEFAULT_OPTION,
0748: JOptionPane.QUESTION_MESSAGE, null, options,
0749: options[1]);
0750:
0751: if (rc == 0) {
0752: String langName = (String) langCombo.getSelectedItem();
0753: langMgr.setCurrentLang(langName);
0754: }
0755: }
0756:
0757: public void newLanguage() {
0758: String[] encodings = { "Default", "UTF8", "UTF16" };
0759: JComboBox encodingCombo = new JComboBox(encodings);
0760: encodingCombo.setEditable(true);
0761:
0762: Object[] message = new Object[6];
0763: message[0] = "Code";
0764: message[1] = new JTextField("EN");
0765: message[2] = "Name";
0766: message[3] = new JTextField("English");
0767: message[4] = "Encoding";
0768: message[5] = encodingCombo;
0769:
0770: String[] options = { "Cancel", "OK" };
0771: int rc = 0;
0772: rc = JOptionPane.showOptionDialog(this , message,
0773: "New Language", JOptionPane.DEFAULT_OPTION,
0774: JOptionPane.INFORMATION_MESSAGE, null, options,
0775: options[1]);
0776: if (rc == 1) {
0777: Object encoding = encodingCombo.getSelectedItem();
0778: String encodingStr = null;
0779: if ((encoding == null) || "Default".equals(encoding))
0780: ;
0781: else
0782: encodingStr = encoding.toString();
0783:
0784: addLanguage(((JTextField) message[1]).getText(),
0785: ((JTextField) message[3]).getText(), encodingStr);
0786: updateHints(langMgr);
0787: }
0788: }
0789:
0790: /**
0791: * Add a new 'blank' string
0792: * @return the new key or null if no string is added
0793: */
0794: public String newString() {
0795: if (langMgr.isLoadedFromExportedFiles())
0796: return null;
0797:
0798: int srcId, targetIdx;
0799: String key = null;
0800: try {
0801: int numItems = sourceLang.getSize();
0802: int maxId = 0;
0803: for (int iItem = 0; iItem < numItems; iItem++) {
0804: srcId = sourceLang.getStringId(iItem);
0805: if (srcId > maxId)
0806: maxId = srcId;
0807: }
0808: key = "Str_" + new Integer(maxId).toString();
0809: targetIdx = sourceLang.addString(++maxId, key, key);
0810: sourceLangModel = new LangListModel(sourceLang, true,
0811: sourceLang == refLang);
0812: sourceList.setModel(sourceLangModel);
0813: //sourceList.setSelectedIndex( targetIdx );
0814: sourceList.ensureIndexIsVisible(targetIdx);
0815: if (sourceLang != targetLang)
0816: targetIdx = targetLang.addString(maxId, key, key);
0817:
0818: targetLangModel = new LangListModel(targetLang, false,
0819: false);
0820: targetList.setModel(targetLangModel);
0821: targetList.setSelectedIndex(targetIdx);
0822: targetList.ensureIndexIsVisible(targetIdx);
0823:
0824: if ((sourceLang != refLang) && (targetLang != refLang))
0825: refLang.addString(maxId, key, key);
0826: } catch (Exception ex) {
0827: }
0828:
0829: if (currentProject != null)
0830: currentProject.setModified(true);
0831: return key;
0832: }
0833:
0834: /**
0835: * Add a new string
0836: * @param newText
0837: * @return the key if the string was added or null if it already exists or was not added
0838: */
0839: String newString(String newText) {
0840: int srcId, targetIdx;
0841: String key = null;
0842: try {
0843: int numItems = sourceLang.getSize();
0844: int maxId = 0;
0845: for (int iItem = 0; iItem < numItems; iItem++) {
0846: srcId = sourceLang.getStringId(iItem);
0847: if (srcId > maxId)
0848: maxId = srcId;
0849: }
0850:
0851: String keyText = "";
0852: int strLen = newText.length();
0853: for (int i = 0; i < strLen; i++) {
0854: char c = newText.charAt(i);
0855: if (Character.isJavaIdentifierPart(c))
0856: keyText += c;
0857: else
0858: keyText += "_";
0859: }
0860: keyText = keyText.toUpperCase();
0861:
0862: // Check for the existance of the string
0863: if (refLang.findString(keyText) == -1) {
0864: targetIdx = sourceLang.addString(++maxId, keyText,
0865: (sourceLang == refLang) ? keyText : newText);
0866: sourceLangModel = new LangListModel(sourceLang, true,
0867: sourceLang == refLang);
0868: sourceList.setModel(sourceLangModel);
0869: sourceList.ensureIndexIsVisible(targetIdx);
0870:
0871: if (sourceLang != targetLang)
0872: targetIdx = targetLang
0873: .addString(maxId, keyText,
0874: (targetLang == refLang) ? keyText
0875: : newText);
0876: targetLangModel = new LangListModel(targetLang, false,
0877: false);
0878: targetList.setModel(targetLangModel);
0879: targetList.setSelectedIndex(targetIdx);
0880: targetList.ensureIndexIsVisible(targetIdx);
0881:
0882: if ((sourceLang != refLang) && (targetLang != refLang))
0883: refLang.addString(maxId, keyText, keyText);
0884:
0885: key = keyText;
0886: }
0887: } catch (Exception ex) {
0888: }
0889:
0890: if (currentProject != null)
0891: currentProject.setModified(true);
0892: return key;
0893: }
0894:
0895: /**
0896: * Find the key that matches this text
0897: * @param text the master string
0898: * @return the key or null if it is not found
0899: */
0900: public String findKey(String text) {
0901: int id = refLang.findString(text);
0902: if (id < 0)
0903: return null;
0904:
0905: return "str_" + Integer.toString(id);
0906: }
0907:
0908: void deleteString() {
0909: if (langMgr.isLoadedFromExportedFiles())
0910: return;
0911:
0912: int srcIdx, srcId, targetIdx;
0913: try {
0914: srcIdx = sourceList.getSelectedIndex();
0915: srcId = sourceLang.getStringId(srcIdx);
0916: targetIdx = targetLang.getStringIndex(srcId);
0917: boolean sameLangs = (targetLang == sourceLang);
0918: if (targetIdx >= 0) {
0919: targetLang.removeString(targetIdx);
0920: targetLangModel = new LangListModel(targetLang, false,
0921: false);
0922: targetList.setModel(targetLangModel);
0923: }
0924: if (srcIdx >= 0) {
0925: if (!sameLangs)
0926: sourceLang.removeString(srcIdx);
0927: sourceLangModel = new LangListModel(sourceLang, true,
0928: sourceLang == refLang);
0929: sourceList.setModel(sourceLangModel);
0930: }
0931: sourceList.setSelectedIndex(0);
0932: sourceList.ensureIndexIsVisible(0);
0933: } catch (Exception ex) {
0934: }
0935: if (currentProject != null)
0936: currentProject.setModified(true);
0937: }
0938:
0939: public void addMissingStrings(boolean useMachineTranslation) {
0940: try {
0941: StringAdder sa = new StringAdder(this , sourceLang,
0942: targetLang);
0943: // if ( useMachineTranslation )
0944: // sa.showMTDialog();
0945: sa.start();
0946: } catch (Exception ex) {
0947: }
0948: if (currentProject != null)
0949: currentProject.setModified(true);
0950: }
0951:
0952: void stringAdderComplete() {
0953: targetLangModel = new LangListModel(targetLang, false, false);
0954: targetList.setModel(targetLangModel);
0955:
0956: sourceList.setSelectedIndex(0);
0957: }
0958:
0959: public void machineTranslation() {
0960: addMissingStrings(true);
0961: }
0962:
0963: public void liveTranslation() {
0964: final XEditorProject editorProject = (XEditorProject) XProjectManager
0965: .getCurrentProject();
0966: IEditorUtility editor = editorProject.getEditorUtility();
0967:
0968: final URL[] urls = editor.getProjectURLs(editorProject);
0969: final String mainClass = "net.xoetrope.swing.XApplet";
0970: final String arguments = "startup.properties";
0971:
0972: SwingUtilities.invokeLater(new Runnable() {
0973: public void run() {
0974: try {
0975: Object o = null;
0976: Vector files = new Vector();
0977: for (int i = 0; i < urls.length; i++) {
0978: // String u = URLDecoder.decode( urls[ i ].getFile(), System.getProperty( "file.encoding" ));
0979: // File f = new File( u );
0980:
0981: // File f = null;
0982: // try {
0983: // f = new File( urls[ i ].toURI() );
0984: // }
0985: // catch( URISyntaxException e ) {
0986: // f = new File( urls[ i ].getPath());
0987: // }
0988:
0989: String u = urls[i].getFile();
0990: if (u.startsWith("file:"))
0991: u = u.replaceFirst("file:", "");
0992: if (u.endsWith("!/"))
0993: u = u.substring(0, u.length() - 2);
0994:
0995: u = u.replaceAll("%20", " ");
0996: File f = new File(u);
0997: files.add(f);
0998: }
0999:
1000: AdaptiveClassLoader classLoader = new AdaptiveClassLoader(
1001: files, getClass().getClassLoader(), false);
1002: Class clazz = classLoader.loadClass(mainClass
1003: .trim());
1004: Class[] argTypes = new Class[1];
1005: argTypes[0] = String[].class;
1006: Method method = clazz.getDeclaredMethod("loadUI",
1007: argTypes);
1008: method.setAccessible(true);
1009:
1010: Object[] args = new Object[1];
1011: String actualArgs[] = new String[1];
1012: actualArgs[0] = arguments;
1013: args[0] = actualArgs;
1014: method.invoke(null, args);
1015:
1016: new TranslationPane(editorProject);
1017: } catch (Exception ex) {
1018: if (BuildProperties.DEBUG)
1019: ex.printStackTrace();
1020: }
1021: }
1022: });
1023: }
1024:
1025: void stripSymbols() {
1026: try {
1027: int numItems = targetLang.getSize();
1028: for (int iItem = 0; iItem < numItems; iItem++) {
1029: int targetId = sourceLang.getStringId(iItem);
1030: String str = targetLang.getStringAt(iItem);
1031: String newStr;
1032: int idx = str.indexOf(delimiterStartChar);
1033: boolean modified = false;
1034: while (idx > -1) {
1035: newStr = str.substring(0, idx)
1036: + str.substring(idx + 1);
1037: str = newStr;
1038: idx = str.indexOf(delimiterStartChar);
1039: modified = true;
1040: }
1041: idx = str.indexOf(delimiterEndChar);
1042: while (idx > -1) {
1043: newStr = str.substring(0, idx)
1044: + str.substring(idx + 1);
1045: str = newStr;
1046: idx = str.indexOf(delimiterEndChar);
1047: modified = true;
1048: }
1049: if (modified)
1050: targetLang.setString(targetId, sourceLang
1051: .getString(targetId), str);
1052: }
1053: targetLangModel = new LangListModel(targetLang, false,
1054: false);
1055: targetList.setModel(targetLangModel);
1056:
1057: sourceList.setSelectedIndex(0);
1058: } catch (Exception ex) {
1059: }
1060: if (currentProject != null)
1061: currentProject.setModified(true);
1062: }
1063:
1064: public void setDelimiters(boolean isStart) {
1065: Object[] possibleValues = { "@", "�", "~", "#", ":", "*",
1066: "/", "\\" };
1067: Object selectedValue = JOptionPane.showInputDialog(null,
1068: "Choose one", "Input", JOptionPane.INFORMATION_MESSAGE,
1069: null, possibleValues, possibleValues[0]);
1070:
1071: if (isStart) {
1072: delimiterStartChar = ((String) selectedValue).charAt(0);
1073: prefs.put("delimiterStartChar", "" + delimiterStartChar);
1074: } else {
1075: delimiterEndChar = ((String) selectedValue).charAt(0);
1076: prefs.put("delimiterEndChar", "" + delimiterEndChar);
1077: }
1078: }
1079:
1080: public void setDelimiterChar(char c, boolean isStart) {
1081: if (isStart)
1082: delimiterStartChar = c;
1083: else
1084: delimiterEndChar = c;
1085: }
1086:
1087: void addLanguage(String code, String name, String encoding) {
1088: if (langMgr.isLoadedFromExportedFiles())
1089: return;
1090:
1091: langMgr.addLang(code, name, encoding, usesDatabaseSource);
1092: sourceLang = langMgr.getLang(0);
1093: targetLang = sourceLang;
1094:
1095: if (sourceLang.getNumStrings() == 0)
1096: newString();
1097:
1098: setupSourceLangList();
1099: setupTargetLangList();
1100: setupLangMenu();
1101: if (currentProject != null)
1102: currentProject.setModified(true);
1103: }
1104:
1105: public void dispose() {
1106: hideMenuAndTools();
1107: }
1108:
1109: /**
1110: * Setup the context menu and the toolbar.
1111: */
1112: public void showMenuAndTools() {
1113: setupSourceLangList();
1114: setupTargetLangList();
1115: setupLangMenu();
1116: }
1117:
1118: /**
1119: * Clear the context menu and the toolbar.
1120: */
1121: public void hideMenuAndTools() {
1122: // if ( langMenu != null ) {
1123: // if ( mainMenu != null ) {
1124: // mainMenu.remove( helpMenu );
1125: // mainMenu.remove( sourceMenu );
1126: // mainMenu.remove( targetMenu );
1127: // mainMenu.remove( langMenu );
1128: // mainMenu.add( helpMenu );
1129: // mainMenu.getParent().doLayout();
1130: // mainMenu.doLayout();
1131: // }
1132: // else {
1133: // mainMenuBar.remove( helpMenu );
1134: // mainMenuBar.remove( sourceMenu );
1135: // mainMenuBar.remove( targetMenu );
1136: // mainMenuBar.remove( langMenu );
1137: // mainMenuBar.add( helpMenu );
1138: // mainMenuBar.getParent().doLayout();
1139: // mainMenuBar.doLayout();
1140: // }
1141: // }
1142: }
1143:
1144: /**
1145: * Creates the JSplitPane.
1146: */
1147: protected void createSplitPane() {
1148: sourceLang = langMgr.getCurrentLang();
1149: sourceLangModel = new LangListModel(sourceLang, true,
1150: sourceLang == refLang);
1151: targetLangModel = new LangListModel(sourceLang, false, false);
1152:
1153: sourceList = new JList(sourceLangModel);
1154: targetList = new JList(targetLangModel);
1155: sourceList.setFont(defaultFont);
1156: targetList.setFont(defaultFont);
1157: sourceList.setPrototypeCellValue("hello world");
1158: targetList.setPrototypeCellValue("hello world");
1159:
1160: IdCellRenderer myCellRenderer = new IdCellRenderer();
1161: sourceList.setCellRenderer(myCellRenderer);
1162: myCellRenderer.setFont(defaultFont);
1163:
1164: targetEdit = new JTextArea();
1165: targetEdit.setWrapStyleWord(true);
1166: targetEdit.setFont(defaultFont);
1167: targetEdit.setLineWrap(true);
1168: targetEdit.setMinimumSize(new Dimension(100, 100));
1169: targetEdit.setBorder(new EmptyBorder(0, 0, 0, 0));
1170: targetEdit.addFocusListener(new FocusListener() {
1171: public void focusGained(FocusEvent e) {
1172: }
1173:
1174: public void focusLost(FocusEvent e) {
1175: saveTargetEdit();
1176: }
1177: });
1178: targetEdit.addKeyListener(new KeyListener() {
1179: public void keyPressed(KeyEvent e) {
1180: if (e.getKeyCode() == KeyEvent.VK_F7) {
1181: previousComment();
1182: e.consume();
1183: } else if (e.getKeyCode() == KeyEvent.VK_F8) {
1184: nextComment();
1185: e.consume();
1186: } else if ((e.getKeyCode() == KeyEvent.VK_L)
1187: && e.isControlDown()) {
1188: checkSpelling();
1189: e.consume();
1190: }
1191: }
1192:
1193: public void keyReleased(KeyEvent e) {
1194: }
1195:
1196: public void keyTyped(KeyEvent e) {
1197: }
1198: });
1199:
1200: JPanel targetPanel = new JPanel();
1201: targetPanel.setLayout(new BorderLayout());
1202: ImageIcon icon = new ImageIcon(
1203: LanguageEditorApplication.class
1204: .getResource("/com/xoetrope/carousel/langed/editor.gif"));
1205: JLabel targetTitle = new JLabel("Editor", icon,
1206: SwingConstants.LEFT);
1207: targetTitle.setBackground(new Color(82, 69, 147));
1208: targetTitle.setForeground(Color.white);
1209: targetTitle.setOpaque(true);
1210: targetPanel.add(targetTitle, BorderLayout.NORTH);
1211: targetPanel.add(targetEdit, BorderLayout.CENTER);
1212:
1213: JPanel helpPanel = new JPanel();
1214: JPanel previewPanel = new JPanel();
1215: JPanel hintPanel = new JPanel();
1216: helpPanel.setLayout(new BoxLayout(helpPanel, BoxLayout.Y_AXIS));
1217: previewPanel.setLayout(new BorderLayout());
1218: hintPanel.setLayout(new BorderLayout());
1219:
1220: icon = new ImageIcon(
1221: LanguageEditorApplication.class
1222: .getResource("/com/xoetrope/carousel/langed/preview.gif"));
1223: previewTitle = new JLabel("Preview ("
1224: + (previewUsingSource ? "reference)" : "target)"),
1225: icon, SwingConstants.LEFT);
1226: previewTitle.setBackground(new Color(82, 69, 147));
1227: previewTitle.setForeground(Color.white);
1228: previewTitle.setOpaque(true);
1229:
1230: previewArea = new JTextPane();//JTextArea();
1231: //previewArea.setWrapStyleWord( true );
1232: previewArea.setFont(defaultFont);
1233: previewArea.setEditable(false);
1234: //previewArea.setLineWrap( true );
1235: previewArea.setMinimumSize(new Dimension(100, 40));
1236: previewArea.setPreferredSize(new Dimension(100, 100));
1237:
1238: icon = new ImageIcon(LanguageEditorApplication.class
1239: .getResource("/com/xoetrope/carousel/langed/hint.gif"));
1240: JLabel hintTitle = new JLabel("Translator's hints", icon,
1241: SwingConstants.LEFT);
1242: hintTitle.setBackground(new Color(82, 69, 147));
1243: hintTitle.setForeground(Color.white);
1244: hintTitle.setOpaque(true);
1245:
1246: hintArea = new JTextArea("This is where the hints go");
1247: hintArea.setFont(defaultFont);
1248: hintArea.setEditable(true);
1249: hintArea.setLineWrap(true);
1250: hintArea.setMinimumSize(new Dimension(100, 20));
1251: hintArea.setPreferredSize(new Dimension(100, 60));
1252:
1253: previewPanel.add(previewTitle, BorderLayout.NORTH);
1254: previewPanel.add(previewArea, BorderLayout.CENTER);
1255:
1256: hintPanel.add(hintTitle, BorderLayout.NORTH);
1257: hintPanel.add(hintArea, BorderLayout.CENTER);
1258:
1259: helpPanel.add(previewPanel, BorderLayout.CENTER);
1260: helpPanel.add(hintPanel, BorderLayout.SOUTH);
1261:
1262: sourceList
1263: .addListSelectionListener(new ListSelectionListener() {
1264: public void valueChanged(ListSelectionEvent evt) {
1265: sourceListChanging = true;
1266: int srcIdx, srcId, targetIdx;
1267: try {
1268: saveTargetEdit();
1269:
1270: srcIdx = sourceList.getSelectedIndex();
1271: srcId = sourceLang.getStringId(srcIdx);
1272: if (targetLang == null)
1273: targetLang = sourceLang;
1274: targetIdx = targetLang
1275: .getStringIndex(srcId);
1276: if (targetIdx >= 0) {
1277: targetString = targetLang
1278: .getString(srcId);
1279: targetList.setSelectedIndex(targetIdx);
1280: } else {
1281: // Add a new string to the target language.
1282: String str = sourceLang
1283: .getString(srcId);
1284: targetIdx = targetLang.addString(srcId,
1285: str, str);
1286: targetLangModel = new LangListModel(
1287: targetLang, false, false);
1288: targetList.setModel(targetLangModel);
1289: targetList.setSelectedIndex(targetIdx);
1290: }
1291: targetList.ensureIndexIsVisible(targetIdx);
1292: } catch (Exception e) {
1293: } finally {
1294: sourceListChanging = false;
1295: }
1296: }
1297: });
1298:
1299: targetList
1300: .addListSelectionListener(new ListSelectionListener() {
1301: public void valueChanged(ListSelectionEvent evt) {
1302: int srcIdx, srcId, targetIdx;
1303: try {
1304: if (!sourceListChanging)
1305: saveTargetEdit();
1306:
1307: srcIdx = targetList.getSelectedIndex();
1308: if (targetLang == null) {
1309: targetLang = sourceLang;
1310: if (targetLang == null)
1311: return;
1312: }
1313: if (srcIdx >= 0) {
1314: srcId = targetLang.getStringId(srcIdx);
1315: targetIdx = sourceLang
1316: .getStringIndex(srcId);
1317:
1318: if (targetIdx >= 0) {
1319: sourceList
1320: .setSelectedIndex(targetIdx);
1321: targetString = targetList
1322: .getSelectedValue()
1323: .toString();
1324: setPreviewText(replaceCRLFPairs(previewUsingSource ? sourceLang
1325: .getString(srcId)
1326: : targetString));
1327: if (hintsLang != null)
1328: hintArea
1329: .setText(hintString = hintsLang
1330: .getString(srcId));
1331: targetEdit.setText(targetString);
1332: targetEdit.validate();
1333: targetEdit.repaint();
1334: targetEdit.requestFocus();
1335: } else {
1336: // Add a new string to the source language.
1337: System.out
1338: .println("WARNING: Missing string in the source language");
1339: targetIdx = sourceLang
1340: .addString(
1341: srcId,
1342: refLang
1343: .getString(srcId),
1344: targetLang
1345: .getString(srcId));
1346: sourceLangModel = new LangListModel(
1347: sourceLang, true,
1348: sourceLang == refLang);
1349: sourceList
1350: .setModel(sourceLangModel);
1351: sourceList
1352: .setSelectedIndex(targetIdx);
1353: }
1354: sourceList
1355: .ensureIndexIsVisible(targetIdx);
1356: }
1357: } catch (Exception e) {
1358: e.printStackTrace();
1359: }
1360: }
1361: });
1362:
1363: leftScroller = new JScrollPane(sourceList);
1364: leftScroller.setAlignmentX(LEFT_ALIGNMENT);
1365: leftScroller.setAlignmentY(TOP_ALIGNMENT);
1366: leftScroller.setMinimumSize(new Dimension(100, 100));
1367: leftScroller.setPreferredSize(new Dimension(287, 300));
1368: icon = new ImageIcon(LanguageEditorApplication.class
1369: .getResource("/com/xoetrope/carousel/langed/ref.gif"));
1370: sourceTranslationLabel = new JLabel("Reference", icon,
1371: SwingConstants.LEFT);
1372: sourceTranslationLabel.setBackground(new Color(82, 69, 147));
1373: sourceTranslationLabel.setForeground(Color.white);
1374: sourceTranslationLabel.setOpaque(true);
1375: leftScroller.setColumnHeaderView(sourceTranslationLabel);
1376:
1377: rightScroller = new JScrollPane(targetList);
1378: rightScroller.setAlignmentX(LEFT_ALIGNMENT);
1379: rightScroller.setAlignmentY(TOP_ALIGNMENT);
1380: rightScroller.setMinimumSize(new Dimension(100, 400));
1381: rightScroller.setPreferredSize(new Dimension(287, 300));
1382: icon = new ImageIcon(LanguageEditorApplication.class
1383: .getResource("/com/xoetrope/carousel/langed/dest.gif"));
1384: targetTranslationCaption = new JLabel("Translation", icon,
1385: SwingConstants.LEFT);
1386: targetTranslationCaption.setBackground(new Color(82, 69, 147));
1387: targetTranslationCaption.setForeground(Color.white);
1388: targetTranslationCaption.setOpaque(true);
1389: rightScroller.setColumnHeaderView(targetTranslationCaption);
1390:
1391: leftSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
1392: leftScroller, helpPanel);
1393: leftSplitPane.setContinuousLayout(true);
1394: leftSplitPane.setDividerSize(8);
1395: leftSplitPane.setMinimumSize(new Dimension(100, 200));
1396: leftSplitPane.setPreferredSize(new Dimension(287, 400));
1397: leftSplitPane.setBorder(new EmptyBorder(0, 0, 0, 0));
1398: leftScroller.setBorder(new EmptyBorder(0, 0, 0, 0));
1399:
1400: rightSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
1401: rightScroller, targetPanel);
1402: rightSplitPane.setContinuousLayout(true);
1403: rightSplitPane.setDividerSize(8);
1404: rightSplitPane.setMinimumSize(new Dimension(100, 200));
1405: rightSplitPane.setPreferredSize(new Dimension(287, 480));
1406: rightSplitPane.setBorder(new EmptyBorder(0, 0, 0, 0));
1407: rightScroller.setBorder(new EmptyBorder(0, 0, 0, 0));
1408:
1409: leftSplitPane
1410: .addPropertyChangeListener(new PropertyChangeListener() {
1411: public void propertyChange(PropertyChangeEvent evt) {
1412: if ((evt.getPropertyName() == "lastDividerLocation")
1413: && (leftSplitPane.getDividerLocation() != rightSplitPane
1414: .getDividerLocation())) {
1415: rightSplitPane
1416: .setDividerLocation(leftSplitPane
1417: .getDividerLocation());
1418: }
1419: }
1420: });
1421:
1422: rightSplitPane
1423: .addPropertyChangeListener(new PropertyChangeListener() {
1424: public void propertyChange(PropertyChangeEvent evt) {
1425: if ((evt.getPropertyName() == "lastDividerLocation")
1426: && (leftSplitPane.getDividerLocation() != rightSplitPane
1427: .getDividerLocation())) {
1428: leftSplitPane
1429: .setDividerLocation(rightSplitPane
1430: .getDividerLocation());
1431: leftSplitPane.validate();
1432: leftSplitPane.repaint();
1433: }
1434: }
1435: });
1436:
1437: splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
1438: leftSplitPane, rightSplitPane);
1439: splitPane.setContinuousLayout(true);
1440: splitPane.setOneTouchExpandable(true);
1441: splitPane.setDividerSize(6);
1442: splitPane.setPreferredSize(new Dimension(600, 480));
1443: splitPane.setBorder(new EmptyBorder(0, 0, 0, 0));
1444:
1445: add(splitPane, BorderLayout.CENTER);
1446:
1447: setupSourceLangList();
1448: setupTargetLangList();
1449: }
1450:
1451: public void isStandalone(boolean isS) {
1452: bIsStandalone = isS;
1453: }
1454:
1455: /**
1456: * Move to the previous comment.
1457: */
1458: public void previousComment() {
1459: int srcIdx = sourceList.getSelectedIndex();
1460: saveTargetEdit();
1461: int newIdx = srcIdx > 0 ? srcIdx - 1 : 0;
1462: sourceList.setSelectedIndex(newIdx);
1463: sourceList.ensureIndexIsVisible(newIdx);
1464: targetList.ensureIndexIsVisible(newIdx);
1465: }
1466:
1467: /**
1468: * Move to the next comment.
1469: */
1470: public void nextComment() {
1471: saveTargetEdit();
1472: int srcIdx = sourceList.getSelectedIndex();
1473: int numItems = sourceLang.getSize();
1474: int newIdx = srcIdx < (numItems - 1) ? srcIdx + 1
1475: : numItems - 1;
1476: sourceList.setSelectedIndex(newIdx);
1477: sourceList.ensureIndexIsVisible(newIdx);
1478: targetList.ensureIndexIsVisible(newIdx);
1479: }
1480:
1481: /**
1482: * Saves the value of a modified edit field.
1483: */
1484: private void saveTargetEdit() {
1485: if (targetString != null) {
1486: String updateString = targetEdit.getText();
1487: if (targetString.compareTo(updateString) != 0) {
1488: int id = sourceLang.getStringId(sourceList
1489: .getSelectedIndex());
1490: targetLang.setString(id, refLang.getString(id),
1491: updateString);
1492: targetList.repaint();
1493: targetString = updateString;
1494: }
1495:
1496: if (targetLang != hintsLang) {
1497: updateString = hintArea.getText();
1498: if (hintString == null) {
1499: int srcIdx = targetList.getSelectedIndex();
1500: if (srcIdx >= 0) {
1501: int srcId = targetLang.getStringId(srcIdx);
1502: if (hintsLang != null) {
1503: hintString = hintsLang.getString(srcId);
1504: if (currentProject != null)
1505: currentProject.setModified(true);
1506: }
1507: }
1508: }
1509: if ((hintString != null)
1510: && (hintString.compareTo(updateString) != 0)) {
1511: if (hintsLang != null) {
1512: int id = sourceLang.getStringId(sourceList
1513: .getSelectedIndex());
1514: hintsLang.setString(id, refLang.getString(id),
1515: updateString);
1516: if (currentProject != null)
1517: currentProject.setModified(true);
1518: }
1519: hintString = updateString;
1520: }
1521: }
1522: }
1523: }
1524:
1525: /**
1526: * Replace the '${CRLF} strings with '\r\n' strings.
1527: */
1528: private String replaceCRLFPairs(String srcStr) {
1529: return srcStr.replace(XTextDefaults.CRLF_PAIR_ENCODING
1530: .subSequence(0, XTextDefaults.CRLF_PAIR_ENCODING
1531: .length()), XTextDefaults.CRLF_PAIR
1532: .subSequence(0, XTextDefaults.CRLF_PAIR.length()));
1533: }
1534:
1535: public void sortA2Z() {
1536: sort(new LangComparator(LangComparator.ALPHA_ASCENDING));
1537: }
1538:
1539: public void sortZ2A() {
1540: sort(new LangComparator(LangComparator.ALPHA_DESCENDING));
1541: }
1542:
1543: public void sort0to9() {
1544: sort(new LangComparator(LangComparator.NUM_ASCENDING));
1545: }
1546:
1547: public void sort9to0() {
1548: sort(new LangComparator(LangComparator.NUM_DESCENDING));
1549: }
1550:
1551: private void sort(Comparator c) {
1552: if (sourceLang != null) {
1553: sourceLang.sort(c);
1554: sourceLangModel = new LangListModel(sourceLang, true,
1555: sourceLang == refLang);
1556: sourceList.setModel(sourceLangModel);
1557:
1558: targetLang.sort(c);
1559: targetLangModel = new LangListModel(targetLang, false,
1560: false);
1561: targetList.setModel(targetLangModel);
1562: }
1563: }
1564:
1565: public void cut() {
1566: copy();
1567: targetEdit.replaceSelection("");
1568: }
1569:
1570: public boolean hasSelection() {
1571: String s = targetEdit.getSelectedText();
1572: if ((s != null) && (s.length() > 0))
1573: return true;
1574: return false;
1575: }
1576:
1577: public void copy() {
1578: Clipboard clipboard = Toolkit.getDefaultToolkit()
1579: .getSystemClipboard();
1580: String selection = targetEdit.getSelectedText();
1581: StringSelection data = new StringSelection(selection);
1582: clipboard.setContents(data, data);
1583: }
1584:
1585: public void paste() {
1586: Clipboard clipboard = Toolkit.getDefaultToolkit()
1587: .getSystemClipboard();
1588: Transferable clipData = clipboard.getContents(clipboard);
1589: if (clipData != null) {
1590: try {
1591: String s = (String) (clipData
1592: .getTransferData(DataFlavor.stringFlavor));
1593: targetEdit.replaceSelection(s);
1594: } catch (UnsupportedFlavorException ee) {
1595: System.err.println("Unsupported flavor: " + ee);
1596: } catch (IOException ee) {
1597: System.err.println("Unable to get data: " + ee);
1598: }
1599: }
1600: }
1601:
1602: public void checkSpelling() {
1603: try {
1604: spellChecker.spellCheck(targetEdit);
1605: } catch (Exception ex) {
1606: ex.printStackTrace();
1607: }
1608: }
1609:
1610: public void setupSpelling(boolean pickLang) {
1611: try {
1612: URL resource = null;
1613: ZipInputStream zip = null;
1614: try {
1615: if (pickLang) {
1616: JFileChooser fileDialog = new JFileChooser();
1617: LanguageEditorApplication
1618: .setDefaultFont(fileDialog);
1619:
1620: AFileFilter langFileFilter = new AFileFilter("zip",
1621: "Zipped Dictionary Files");
1622: fileDialog.addChoosableFileFilter(langFileFilter);
1623: fileDialog.setFileHidingEnabled(false);
1624: fileDialog
1625: .setFileSelectionMode(JFileChooser.FILES_ONLY);
1626: fileDialog.setCurrentDirectory(new File(
1627: dictionaryFile));
1628:
1629: int retval = fileDialog.showOpenDialog(this );
1630: if (retval == JFileChooser.APPROVE_OPTION) {
1631: File theFile = fileDialog.getSelectedFile();
1632:
1633: if ((theFile != null) && theFile.exists()) {
1634: dictionaryFile = theFile.getAbsolutePath();
1635: prefs.put("dictionaryFile", dictionaryFile);
1636: } else {
1637: // should put in status panel
1638: System.err.println("No such file: "
1639: + theFile);
1640: }
1641: }
1642: }
1643:
1644: String localStr = dictionaryFile;
1645: resource = LanguageEditorApplication.class
1646: .getResource(dictionaryFile);
1647: if (resource != null)
1648: zip = new ZipInputStream(resource.openStream());
1649: else
1650: zip = new ZipInputStream(new FileInputStream(
1651: localStr));
1652: } catch (NullPointerException e) {
1653: FileInputStream fin = new FileInputStream(
1654: dictionaryFile);
1655: zip = new ZipInputStream(fin);
1656: DebugLogger
1657: .logWarning("Unabled to open the dictionary file: "
1658: + dictionaryFile);
1659: }
1660: zip.getNextEntry();
1661: dictionary = new SpellDictionary(new BufferedReader(
1662: new InputStreamReader(zip)));
1663:
1664: spellChecker = new JTextComponentSpellChecker(dictionary,
1665: "Spell checker");
1666: } catch (Exception e) {
1667: DebugLogger
1668: .logWarning("Unabled to open the dictionary file");
1669: }
1670: }
1671:
1672: /**
1673: * Toggles preview with the source or the target language
1674: * @param text
1675: */
1676: public void swapPreviewLanguage() {
1677: int srcIdx = sourceList.getSelectedIndex();
1678: if (srcIdx < 0) {
1679: srcIdx = targetList.getSelectedIndex();
1680: if (srcIdx < 0)
1681: return;
1682: else {
1683: int srcId = targetLang.getStringId(srcIdx);
1684: int targetIdx = sourceLang.getStringIndex(srcId);
1685:
1686: if (targetIdx >= 0)
1687: sourceList.setSelectedIndex(targetIdx);
1688: }
1689: }
1690: int srcId = sourceLang.getStringId(srcIdx);
1691:
1692: previewUsingSource = !previewUsingSource;
1693: prefs.put("previewUsingSource",
1694: (previewUsingSource ? "1" : "0"));
1695: previewTitle
1696: .setText("Preview ("
1697: + (previewUsingSource ? sourceTranslationLabel
1698: .getText() : targetTranslationCaption
1699: .getText()) + ")");
1700: setPreviewText(replaceCRLFPairs(previewUsingSource ? sourceLang
1701: .getString(srcId) : targetLang.getString(srcId)));
1702: }
1703:
1704: private void setPreviewText(String text) {
1705: DefaultStyledDocument document = new DefaultStyledDocument();
1706: previewArea.setDocument(document);
1707: try {
1708: String srcString = sourceList.getSelectedValue().toString();
1709: int startPos = 0;
1710: int pos = srcString.indexOf('|');
1711: startPos = (pos > 0 ? pos + 1 : 0);
1712:
1713: FontMetrics fm = previewArea.getFontMetrics(previewArea
1714: .getFont());
1715: int srcWidth = fm
1716: .stringWidth(srcString.substring(startPos));
1717: byte[] bytes = text.getBytes();
1718: int aveCharWidth = 0;
1719: int srcLen = 0;
1720: int targetTextLen = text.length();
1721: int targetWidth = 0;
1722:
1723: // Calculate the number of characters from the source string that could fit
1724: // in the space using the average width of the output characters. This
1725: // brings both strings onto the same basis and therefore we may see if the
1726: // number of characters from the output string will fit in the length
1727: // provided for the source string.
1728: if (targetTextLen > 0) {
1729: targetWidth = fm.bytesWidth(bytes, 0, bytes.length);
1730: aveCharWidth = targetWidth / targetTextLen;
1731: srcLen = srcWidth / aveCharWidth;
1732: // srcLen = targetWidth / ( srcString.length() * srcWidth );
1733: }
1734:
1735: if (previewStringLength && (targetWidth > srcWidth)
1736: && (srcLen < targetTextLen)) {
1737: String s1 = text.substring(0, srcLen);
1738: String s2 = text.substring(srcLen);
1739: document.insertString(document.getLength(), s1, bold);
1740: document.insertString(document.getLength(), s2, normal);
1741: } else
1742: document.insertString(document.getLength(), text, null);
1743: } catch (BadLocationException e) {
1744: e.printStackTrace();
1745: }
1746: }
1747:
1748: public void swapPreviewLength() {
1749: previewStringLength = !previewStringLength;
1750: prefs.put("previewStringLength", (previewStringLength ? "1"
1751: : "0"));
1752:
1753: int srcIdx = sourceList.getSelectedIndex();
1754: int srcId;
1755: if (srcIdx < 0) {
1756: srcIdx = targetList.getSelectedIndex();
1757: srcId = targetLang.getStringId(srcIdx);
1758: }
1759: srcId = sourceLang.getStringId(srcIdx);
1760: setPreviewText(replaceCRLFPairs(previewUsingSource ? sourceLang
1761: .getString(srcId) : targetLang.getString(srcId)));
1762: }
1763:
1764: int getNumStrings() {
1765: int numLangs = langMgr.getNumLangs();
1766: int maxStrings = 0;
1767: for (int i = 0; i < numLangs; i++) {
1768: EdLanguage el = langMgr.getLang(i);
1769: maxStrings = Math.max(maxStrings, el.getNumStrings());
1770: }
1771: return maxStrings;
1772: }
1773:
1774: public EdLangMgr getLangMgr() {
1775: return langMgr;
1776: }
1777:
1778: /**
1779: * Invoked when an item has been selected or deselected by the user.
1780: * The code written for this method performs the operations
1781: * that need to occur when an item is selected (or deselected).
1782: */
1783: public void itemStateChanged(ItemEvent e) {
1784: if (e.getSource() == sourceLangList)
1785: setSourceLang((String) e.getItem());
1786: else
1787: setTargetLang((String) e.getItem());
1788: }
1789: }
|