use of org.omegat.util.Language in project omegat by omegat-org.
the class AlignFilePickerController method show.
/**
* Display the align tool file picker. The picker is not modal, so this call will return immediately.
*
* @param parent
* Parent window of file picker and align window
*/
@SuppressWarnings("serial")
public void show(final Component parent) {
final JFrame frame = new JFrame(OStrings.getString("ALIGNER_FILEPICKER"));
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
StaticUIUtils.setEscapeClosable(frame);
final AlignFilePicker picker = new AlignFilePicker();
picker.sourceLanguagePicker.setModel(new DefaultComboBoxModel<>(new Vector<>(Language.getLanguages())));
picker.sourceLanguagePicker.setRenderer(new LanguageComboBoxRenderer());
picker.sourceLanguagePicker.setSelectedItem(sourceLanguage);
picker.sourceLanguagePicker.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() != ItemEvent.SELECTED) {
return;
}
if (e.getItem() instanceof String) {
String newVal = (String) e.getItem();
if (Language.verifySingleLangCode(newVal)) {
sourceLanguage = new Language(newVal);
} else {
sourceLanguage = null;
JOptionPane.showMessageDialog(frame, OStrings.getString("NP_INVALID_SOURCE_LOCALE") + OStrings.getString("NP_LOCALE_SUGGESTION"), OStrings.getString("TF_ERROR"), JOptionPane.ERROR_MESSAGE);
picker.sourceLanguagePicker.requestFocusInWindow();
}
} else if (e.getItem() instanceof Language) {
sourceLanguage = (Language) e.getItem();
} else {
throw new IllegalArgumentException();
}
updatePicker(picker);
}
});
picker.targetLanguagePicker.setModel(new DefaultComboBoxModel<>(new Vector<>(Language.getLanguages())));
picker.targetLanguagePicker.setRenderer(new LanguageComboBoxRenderer());
picker.targetLanguagePicker.setSelectedItem(targetLanguage);
picker.targetLanguagePicker.addItemListener(e -> {
if (e.getStateChange() != ItemEvent.SELECTED) {
return;
}
if (e.getItem() instanceof String) {
String newVal = (String) e.getItem();
if (Language.verifySingleLangCode(newVal)) {
targetLanguage = new Language(newVal);
} else {
targetLanguage = null;
JOptionPane.showMessageDialog(frame, OStrings.getString("NP_INVALID_TARGET_LOCALE") + OStrings.getString("NP_LOCALE_SUGGESTION"), OStrings.getString("TF_ERROR"), JOptionPane.ERROR_MESSAGE);
picker.targetLanguagePicker.requestFocusInWindow();
}
} else if (e.getItem() instanceof Language) {
targetLanguage = (Language) e.getItem();
} else {
throw new IllegalArgumentException();
}
updatePicker(picker);
});
picker.sourceChooseFileButton.addActionListener(e -> {
File file = chooseFile(frame, OStrings.getString("ALIGNER_FILEPICKER_CHOOSE_SOURCE"), StringUtil.isEmpty(sourceFile) ? sourceDefaultDir : sourceFile);
if (file != null) {
sourceDefaultDir = file.getParent();
targetDefaultDir = targetDefaultDir == null ? sourceDefaultDir : targetDefaultDir;
defaultSaveDir = defaultSaveDir == null ? sourceDefaultDir : defaultSaveDir;
picker.sourceLanguageFileField.setText(file.getAbsolutePath());
}
});
picker.targetChooseFileButton.addActionListener(e -> {
File file = chooseFile(frame, OStrings.getString("ALIGNER_FILEPICKER_CHOOSE_TARGET"), StringUtil.isEmpty(targetFile) ? targetDefaultDir : targetFile);
if (file != null) {
targetDefaultDir = file.getParent();
sourceDefaultDir = sourceDefaultDir == null ? targetDefaultDir : sourceDefaultDir;
defaultSaveDir = defaultSaveDir == null ? targetDefaultDir : defaultSaveDir;
picker.targetLanguageFileField.setText(file.getAbsolutePath());
}
});
picker.sourceLanguageFileField.setText(sourceFile);
picker.sourceLanguageFileField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
update();
}
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void changedUpdate(DocumentEvent e) {
update();
}
private void update() {
sourceFile = picker.sourceLanguageFileField.getText();
updatePicker(picker);
}
});
picker.targetLanguageFileField.setText(targetFile);
picker.targetLanguageFileField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
update();
}
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void changedUpdate(DocumentEvent e) {
update();
}
private void update() {
targetFile = picker.targetLanguageFileField.getText();
updatePicker(picker);
}
});
TransferHandler transferHandler = new TransferHandler() {
@Override
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
@Override
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
try {
List<?> list = (List<?>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
List<File> files = getSupportedFiles(list);
if (files.isEmpty()) {
return false;
}
JTextComponent field = (JTextComponent) support.getComponent();
field.setText(files.get(0).getAbsolutePath());
return true;
} catch (Exception e) {
Log.log(e);
return false;
}
}
};
picker.sourceLanguageFileField.setTransferHandler(transferHandler);
picker.targetLanguageFileField.setTransferHandler(transferHandler);
picker.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
@Override
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
try {
List<?> list = (List<?>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
List<File> files = getSupportedFiles(list);
if (files.isEmpty()) {
return false;
} else if (files.size() == 1) {
JTextComponent insertTarget = picker.sourceLanguageFileField;
if (picker.sourceLanguageFileField.getDocument().getLength() != 0 && picker.targetLanguageFileField.getDocument().getLength() == 0) {
insertTarget = picker.targetLanguageFileField;
}
insertTarget.setText(files.get(0).getAbsolutePath());
} else {
picker.sourceLanguageFileField.setText(files.get(0).getAbsolutePath());
picker.targetLanguageFileField.setText(files.get(1).getAbsolutePath());
}
return true;
} catch (Exception e) {
Log.log(e);
return false;
}
}
});
picker.okButton.addActionListener(e -> {
picker.bottomPanel.remove(picker.messageTextArea);
picker.bottomPanel.add(picker.progressBar, BorderLayout.CENTER);
picker.bottomPanel.revalidate();
new SwingWorker<Aligner, Void>() {
@Override
protected Aligner doInBackground() throws Exception {
Aligner aligner = new Aligner(sourceFile, sourceLanguage, targetFile, targetLanguage);
aligner.loadFiles();
return aligner;
}
@Override
protected void done() {
try {
Aligner aligner = get();
new AlignPanelController(aligner, defaultSaveDir).show(parent);
} catch (CancellationException e) {
// Ignore
} catch (Exception e) {
Log.log(e);
JOptionPane.showMessageDialog(frame, OStrings.getString("ALIGNER_ERROR_LOADING"), OStrings.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
}
frame.dispose();
}
}.execute();
});
picker.cancelButton.addActionListener(e -> frame.dispose());
frame.getRootPane().setDefaultButton(picker.okButton);
updatePicker(picker);
frame.add(picker);
frame.pack();
frame.setLocationRelativeTo(parent);
frame.setVisible(true);
}
use of org.omegat.util.Language in project omegat by omegat-org.
the class RealProject method loadTM.
/**
* Locates and loads external TMX files with legacy translations. Uses directory monitor for check file
* updates.
*/
private void loadTM() throws IOException {
File tmRoot = new File(config.getTMRoot());
tmMonitor = new DirectoryMonitor(tmRoot, file -> {
if (!ExternalTMFactory.isSupported(file)) {
// not a TMX file
return;
}
if (file.getPath().replace('\\', '/').startsWith(config.getTMOtherLangRoot())) {
// tmx in other language, which is already shown in editor. Skip it.
return;
}
// create new translation memories map
Map<String, ExternalTMX> newTransMemories = new TreeMap<>(transMemories);
if (file.exists()) {
try {
ExternalTMX newTMX = ExternalTMFactory.load(file);
newTransMemories.put(file.getPath(), newTMX);
// directory separators into "/".
if (FileUtil.computeRelativePath(tmRoot, file).startsWith(OConsts.AUTO_TM + "/")) {
appendFromAutoTMX(newTMX, false);
} else if (FileUtil.computeRelativePath(tmRoot, file).startsWith(OConsts.AUTO_ENFORCE_TM + '/')) {
appendFromAutoTMX(newTMX, true);
}
} catch (Exception e) {
String filename = file.getPath();
Log.logErrorRB(e, "TF_TM_LOAD_ERROR", filename);
Core.getMainWindow().displayErrorRB(e, "TF_TM_LOAD_ERROR", filename);
}
} else {
newTransMemories.remove(file.getPath());
}
transMemories = newTransMemories;
});
tmMonitor.checkChanges();
tmMonitor.start();
}
use of org.omegat.util.Language in project omegat by omegat-org.
the class Searcher method searchProject.
private void searchProject() {
// reset the number of search hits
m_numFinds = 0;
// search the Memory, if requested
if (m_searchExpression.memory) {
// search through all project entries
IProject dataEngine = m_project;
for (int i = 0; i < m_project.getAllEntries().size(); i++) {
// stop searching if the max. nr of hits has been reached
if (m_numFinds >= expression.numberOfResults) {
return;
}
// get the source and translation of the next entry
SourceTextEntry ste = dataEngine.getAllEntries().get(i);
TMXEntry te = m_project.getTranslationInfo(ste);
checkEntry(ste.getSrcText(), te.translation, te.note, ste.getComment(), te, i, null);
checkStop.checkInterrupted();
}
// search in orphaned
if (!m_searchExpression.excludeOrphans) {
m_project.iterateByDefaultTranslations(new IProject.DefaultTranslationsIterator() {
final String file = OStrings.getString("CT_ORPHAN_STRINGS");
public void iterate(String source, TMXEntry en) {
// stop searching if the max. nr of hits has been reached
if (m_numFinds >= expression.numberOfResults) {
return;
}
checkStop.checkInterrupted();
if (m_project.isOrphaned(source)) {
checkEntry(en.source, en.translation, en.note, null, en, ENTRY_ORIGIN_ORPHAN, file);
}
}
});
m_project.iterateByMultipleTranslations(new IProject.MultipleTranslationsIterator() {
final String file = OStrings.getString("CT_ORPHAN_STRINGS");
public void iterate(EntryKey source, TMXEntry en) {
// reached
if (m_numFinds >= expression.numberOfResults) {
return;
}
checkStop.checkInterrupted();
if (m_project.isOrphaned(source)) {
checkEntry(en.source, en.translation, en.note, null, en, ENTRY_ORIGIN_ORPHAN, file);
}
}
});
}
}
// search the TM, if requested
if (m_searchExpression.tm) {
// that case.
if (!expression.searchAuthor && !expression.searchDateAfter && !expression.searchDateBefore) {
for (Map.Entry<String, ExternalTMX> tmEn : m_project.getTransMemories().entrySet()) {
final String fileTM = tmEn.getKey();
if (!searchEntries(tmEn.getValue().getEntries(), fileTM)) {
return;
}
checkStop.checkInterrupted();
}
for (Map.Entry<Language, ProjectTMX> tmEn : m_project.getOtherTargetLanguageTMs().entrySet()) {
final Language langTM = tmEn.getKey();
if (!searchEntriesAlternative(tmEn.getValue().getDefaults(), langTM.getLanguage())) {
return;
}
if (!searchEntriesAlternative(tmEn.getValue().getAlternatives(), langTM.getLanguage())) {
return;
}
checkStop.checkInterrupted();
}
}
}
// search the glossary, if requested
if (m_searchExpression.glossary) {
String intro = OStrings.getString("SW_GLOSSARY_RESULT");
List<GlossaryEntry> entries = Core.getGlossaryManager().getLocalEntries();
for (GlossaryEntry en : entries) {
checkEntry(en.getSrcText(), en.getLocText(), null, null, null, ENTRY_ORIGIN_GLOSSARY, intro);
// stop searching if the max. nr of hits has been reached
if (m_numFinds >= expression.numberOfResults) {
return;
}
checkStop.checkInterrupted();
}
}
}
use of org.omegat.util.Language in project omegat by omegat-org.
the class EditorController method loadDocument.
/**
* Displays the {@link Preferences#EDITOR_INITIAL_SEGMENT_LOAD_COUNT}
* segments surrounding the entry with index {@link #displayedEntryIndex}.
*/
protected void loadDocument() {
UIThreadsUtil.mustBeSwingThread();
// Currently displayed file
IProject.FileInfo file;
try {
file = Core.getProject().getProjectFiles().get(displayedFileIndex);
} catch (IndexOutOfBoundsException ex) {
// there is no displayedFileIndex file in project - load first file
file = Core.getProject().getProjectFiles().get(0);
}
// remove old segments
if (m_docSegList != null) {
markerController.removeAll();
}
// check if RTL support required for document
boolean hasRTL = sourceLangIsRTL || targetLangIsRTL || EditorUtils.localeIsRTL() || currentOrientation != Document3.ORIENTATION.ALL_LTR;
Map<Language, ProjectTMX> otherLanguageTMs = Core.getProject().getOtherTargetLanguageTMs();
for (Map.Entry<Language, ProjectTMX> entry : otherLanguageTMs.entrySet()) {
hasRTL = hasRTL || EditorUtils.isRTL(entry.getKey().getLanguageCode().toLowerCase(Locale.ENGLISH));
}
Document3 doc = new Document3(this);
// Create all SegmentBuilders now...
ArrayList<SegmentBuilder> tmpSegList = new ArrayList<SegmentBuilder>(file.entries.size());
for (SourceTextEntry ste : file.entries) {
if (entriesFilter == null || entriesFilter.allowed(ste)) {
SegmentBuilder sb = new SegmentBuilder(this, doc, settings, ste, ste.entryNum(), hasRTL);
tmpSegList.add(sb);
}
}
m_docSegList = tmpSegList.toArray(new SegmentBuilder[tmpSegList.size()]);
// Clamp displayedSegment to actually available entries.
displayedEntryIndex = Math.max(0, Math.min(m_docSegList.length - 1, displayedEntryIndex));
// Calculate start, end indices of a span of initialSegCount segments
// centered around displayedEntryIndex and clamped to [0, m_docSegList.length).
final int initialSegCount = Preferences.getPreferenceDefault(Preferences.EDITOR_INITIAL_SEGMENT_LOAD_COUNT, Preferences.EDITOR_INITIAL_SEGMENT_LOAD_COUNT_DEFAULT);
firstLoaded = Math.max(0, displayedEntryIndex - initialSegCount / 2);
lastLoaded = Math.min(file.entries.size() - 1, firstLoaded + initialSegCount - 1);
// ...but only display the ones in [firstLoaded, lastLoaded]
for (int i = 0; i < m_docSegList.length; i++) {
if (i >= firstLoaded && i <= lastLoaded) {
SegmentBuilder sb = m_docSegList[i];
sb.createSegmentElement(false, Core.getProject().getTranslationInfo(sb.ste));
sb.addSegmentSeparator();
}
}
doc.setDocumentFilter(new DocumentFilter3());
// add locate for target language to editor
Locale targetLocale = Core.getProject().getProjectProperties().getTargetLanguage().getLocale();
editor.setLocale(targetLocale);
editor.setDocument(doc);
doc.addUndoableEditListener(editor.undoManager);
editor.undoManager.reset();
doc.addDocumentListener(new DocumentListener() {
// we cannot edit the document here, only other stuff.
public void changedUpdate(DocumentEvent e) {
showLengthMessage();
onTextChanged();
}
public void insertUpdate(DocumentEvent e) {
showLengthMessage();
onTextChanged();
}
public void removeUpdate(DocumentEvent e) {
showLengthMessage();
onTextChanged();
}
});
markerController.process(m_docSegList);
editor.repaint();
}
use of org.omegat.util.Language in project omegat by omegat-org.
the class GlossaryManager method addExternalGlossaryEntries.
private void addExternalGlossaryEntries(List<GlossaryEntry> result, String src) {
Language source = Core.getProject().getProjectProperties().getSourceLanguage();
Language target = Core.getProject().getProjectProperties().getTargetLanguage();
for (IGlossary gl : externalGlossaries) {
try {
result.addAll(gl.search(source, target, src));
} catch (Exception ex) {
Log.log(ex);
}
}
}
Aggregations