Search in sources :

Example 21 with Language

use of net.heartsome.cat.common.locale.Language in project translationstudio8 by heartsome.

the class ConverterViewModel method convert.

/**
	 * 正向转换
	 * @param sourceItem
	 * @param monitor
	 * @return ;
	 */
private Map<String, String> convert(final IConversionItem sourceItem, IProgressMonitor monitor) throws ConverterException {
    Map<String, String> result = null;
    boolean convertFlg = false;
    String xliffDir = ConverterUtil.toLocalPath(configBean.getXliffDir());
    String targetFile = ConverterUtil.toLocalPath(configBean.getTarget());
    String skeletonFile = ConverterUtil.toLocalPath(configBean.getSkeleton());
    // 转换前的准备
    ConverterContext converterContext = new ConverterContext(configBean);
    final Map<String, String> configuration = converterContext.getConvertConfiguration();
    // 转换前,生成临时的XLIFF文件,用此文件生成指定目标语言的XLIFF文件
    File targetTempFile = null;
    try {
        targetTempFile = File.createTempFile("tempxlf", "xlf");
    } catch (IOException e) {
        LOGGER.error(Messages.getString("model.ConverterViewModel.msg10"), e);
    }
    configuration.put(Converter.ATTR_XLIFF_FILE, targetTempFile.getAbsolutePath());
    if (configBean.getFileType().equals(FileFormatUtils.MS)) {
        IPreferenceStore ps = net.heartsome.cat.ts.ui.Activator.getDefault().getPreferenceStore();
        String path = ps.getString(ITranslationPreferenceConstants.PATH_OF_OPENOFFICE);
        String port = ps.getString(ITranslationPreferenceConstants.PORT_OF_OPENOFFICE);
        configuration.put("ooPath", path);
        configuration.put("ooPort", port);
    }
    // 创建skeleton文件
    File skeleton = new File(skeletonFile);
    if (!skeleton.exists()) {
        try {
            File parent = skeleton.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            skeleton.createNewFile();
        } catch (IOException e) {
            String message = MessageFormat.format(Messages.getString("model.ConverterViewModel.msg11"), skeletonFile);
            LOGGER.error(message, e);
            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message + "\n" + e.getMessage());
            throw new ConverterException(status);
        }
    }
    try {
        // 执行转换
        Converter converter = getConverter();
        if (converter == null) {
            // Build a message
            String message = Messages.getString("model.ConverterViewModel.msg2") + configBean.getFileType();
            // Build a new IStatus
            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message);
            throw new ConverterException(status);
        }
        result = converter.convert(configuration, monitor);
        final String alert = result.get("ttx2xlfAlert39238409230481092830");
        if (result.containsKey("ttx2xlfAlert39238409230481092830")) {
            //ttx 转 xlf 时,提示含有未预翻译,不推荐,但没办法。
            Display.getDefault().syncExec(new Runnable() {

                public void run() {
                    MessageDialog.openWarning(Display.getCurrent().getActiveShell(), Messages.getString("handler.PreviewTranslationHandler.msgTitle"), alert);
                }
            });
        }
        // 处理骨架文件,将骨架文件路径修改为项目相对路径,此路径写入external-file节点的href属性
        String projectPath = sourceItem.getProject().getLocation().toOSString();
        String sklPath = skeletonFile.replace(projectPath, "");
        // 处理目标语言, 创建多个目标语言的文件
        List<Language> tgtLang = configBean.getHasSelTgtLangList();
        if (tgtLang != null && tgtLang.size() > 0) {
            // 解析XLIFF文件
            File f = new File(targetTempFile.getAbsolutePath());
            FileInputStream is = null;
            byte[] b = new byte[(int) f.length()];
            try {
                is = new FileInputStream(f);
                is.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            VTDGen vg = new VTDGen();
            vg.setDoc(b);
            try {
                vg.parse(true);
            } catch (VTDException e) {
                String message = Messages.getString("model.ConverterViewModel.msg12");
                LOGGER.error(message, e);
                IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message + "\n" + e.getMessage());
                throw new ConverterException(status);
            }
            VTDNav vn = vg.getNav();
            VTDUtils vu = new VTDUtils();
            // 生成多个XLIFF文件,只是修改目标语言和骨架文件路径
            for (Language lang : tgtLang) {
                // 修复 bug 2949 ,当文件名中出现 XLIFF 时,文件名获取失败,下面注释代码为之前的代码。	--robert	2013-04-01
                //					String[] pathArray = targetFile.split(Constant.FOLDER_XLIFF);
                //					StringBuffer xlffPath = new StringBuffer(pathArray[0]);
                //					xlffPath.append(Constant.FOLDER_XLIFF).append(File.separator).append(lang.getCode())
                //							.append(pathArray[1]);
                String fileName = targetFile.substring(xliffDir.length());
                StringBuffer xlfPahtSB = new StringBuffer();
                xlfPahtSB.append(xliffDir);
                xlfPahtSB.append(File.separator);
                xlfPahtSB.append(lang.getCode());
                xlfPahtSB.append(fileName);
                File tmpFile = new File(xlfPahtSB.toString());
                generateTgtFileList.add(tmpFile);
                if (!tmpFile.exists()) {
                    File parent = tmpFile.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    try {
                        tmpFile.createNewFile();
                    } catch (IOException e) {
                        String message = Messages.getString("model.ConverterViewModel.msg13");
                        LOGGER.error(message, e);
                        IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message + "\n" + e.getMessage());
                        throw new ConverterException(status);
                    }
                }
                try {
                    vu.bind(vn.duplicateNav());
                } catch (NavException e) {
                    LOGGER.error("", e);
                }
                XMLModifier xm = vu.update("/xliff/file/@target-language", lang.getCode(), VTDUtils.CREATE_IF_NOT_EXIST);
                xm = vu.update(null, xm, "/xliff/file/header/skl/external-file/@href", TextUtil.cleanString(sklPath));
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(tmpFile);
                    // 写入文件
                    xm.output(fos);
                } catch (Exception e) {
                    String message = Messages.getString("model.ConverterViewModel.msg13");
                    LOGGER.error(message, e);
                    IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message + "\n" + e.getMessage());
                    throw new ConverterNotFoundException(status);
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            LOGGER.error("", e);
                        }
                    }
                }
            }
            vg.clear();
        }
        convertFlg = true;
    } catch (OperationCanceledException e) {
        LOGGER.info("ConverterViewerModel: 取消转换");
    } finally {
        if (!convertFlg) {
            for (File f : generateTgtFileList) {
                if (f != null && f.exists()) {
                    f.delete();
                }
            }
            if (skeleton != null && skeleton.exists()) {
                skeleton.delete();
            }
        }
        targetTempFile.delete();
        sourceItem.refresh();
    }
    return result;
}
Also used : ConverterException(net.heartsome.cat.converter.ConverterException) XMLModifier(com.ximpleware.XMLModifier) IStatus(org.eclipse.core.runtime.IStatus) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) Language(net.heartsome.cat.common.locale.Language) VTDException(com.ximpleware.VTDException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) Converter(net.heartsome.cat.converter.Converter) ValidationStatus(org.eclipse.core.databinding.validation.ValidationStatus) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) NavException(com.ximpleware.NavException) VTDGen(com.ximpleware.VTDGen) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) NavException(com.ximpleware.NavException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ConverterException(net.heartsome.cat.converter.ConverterException) IOException(java.io.IOException) VTDException(com.ximpleware.VTDException) JobRunnable(net.heartsome.cat.convert.ui.job.JobRunnable) FileOutputStream(java.io.FileOutputStream) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) File(java.io.File) VTDNav(com.ximpleware.VTDNav)

Example 22 with Language

use of net.heartsome.cat.common.locale.Language in project translationstudio8 by heartsome.

the class XLIFFEditorImplWithNatTable method changeLayout.

public void changeLayout(boolean isHorizontalLayout) {
    // 同步布局状态
    this.isHorizontalLayout = isHorizontalLayout;
    // 如果当前的 table 已经存在,销毁后再重新创建。
    if (table != null && !table.isDisposed()) {
        table.dispose();
        for (Control control : parent.getChildren()) {
            control.dispose();
        }
    }
    // 构建 NatTable 的数据提供者
    bodyDataProvider = setupBodyDataProvider(isHorizontalLayout);
    // 构建 NatTable 列头的数据提供者
    DefaultColumnHeaderDataProvider colHeaderDataProvider = new DefaultColumnHeaderDataProvider(propertyNames, propertyToLabels);
    // 构建 NatTable 的 body layer stack
    bodyLayer = new BodyLayerStack(bodyDataProvider, isHorizontalLayout);
    // 构建 NatTable 的 column header layout stack
    ColumnHeaderLayerStack columnHeaderLayer = new ColumnHeaderLayerStack(colHeaderDataProvider);
    // 构建 NatTable 之下的 composite layer,不使用默认的 configuration(默认的 configuration 是在点击可编辑单元格时,直接进入编辑状态)。
    CompositeLayer compositeLayer = new CompositeLayer(1, 2);
    compositeLayer.setChildLayer(GridRegion.COLUMN_HEADER, columnHeaderLayer, 0, 0);
    compositeLayer.setChildLayer(GridRegion.BODY, bodyLayer, 0, 1);
    // 标识 BodyLayer 在 CompositeLayer 上的位置
    LayerUtil.setBodyLayerPosition(0, 1);
    /* 给 composite layer 添加编辑相关的命令和 handler */
    // 添加行背景色(奇数行和偶数行不同)
    addRowBackgroundColor(compositeLayer);
    // 构建 NatTable
    table = new NatTable(parent, compositeLayer, false);
    Language srcLang = LocaleService.getLanguageConfiger().getLanguageByCode(srcColumnName);
    Language tgtLang = LocaleService.getLanguageConfiger().getLanguageByCode(tgtColumnName);
    if (srcLang.isBidi() || tgtLang.isBidi()) {
        table.setOrientation(SWT.RIGHT_TO_LEFT);
    }
    // 去除默认绘画器
    table.removePaintListener(table);
    // 使用自定义绘画器,此绘画器,具有自动计算行高功能。
    table.addPaintListener(paintListenerWithAutoRowSize);
    Listener[] ls = table.getListeners(SWT.Resize);
    for (Listener l : ls) {
        table.removeListener(SWT.Resize, l);
    }
    table.addListener(SWT.Resize, resizeListenerWithColumnResize);
    table.addDisposeListener(new DisposeListener() {

        public void widgetDisposed(DisposeEvent e) {
            // ActiveCellEditor.commit(); // 关闭编辑时,先提交未提交的单元格,避免造成内容丢失。Bug #2685
            HsMultiActiveCellEditor.commit(true);
            table.removeListener(SWT.Resize, resizeListenerWithColumnResize);
            table.removePaintListener(paintListenerWithAutoRowSize);
        }
    });
    table.setLayoutData(new GridData(GridData.FILL_BOTH));
    // 给 NatTable 添加相应的配置
    DefaultNatTableStyleConfiguration configuration = new DefaultNatTableStyleConfiguration();
    configuration.hAlign = HorizontalAlignmentEnum.LEFT;
    table.addConfiguration(configuration);
    // To be changed 给NatTable添加选择列的功能 Add By Leakey
    /*
		 * ColumnGroupModel columnGroupModel = new ColumnGroupModel(); DisplayColumnChooserCommandHandler
		 * columnChooserCommandHandler = new DisplayColumnChooserCommandHandler( bodyLayer.getSelectionLayer(),
		 * bodyLayer.getColumnHideShowLayer(), columnHeaderLayer.getColumnHeaderLayer(),
		 * columnHeaderLayer.getColumnHeaderDataLayer(), columnHeaderLayer.getColumnGroupHeaderLayer(), columnGroupModel
		 * ); bodyLayer.registerCommandHandler(columnChooserCommandHandler);
		 */
    /*
		 * 不使用默认的表头菜单,使用自定义的菜单,因此自定义菜单在 corner 中添加了相应的菜单项,所以需要指定这些添加的 command 在哪一层进一处理
		 */
    // 表头中添加自定义菜单会引发一些不可预料的问题,故先去掉
    // table.addConfiguration(new HeaderMenuConfiguration(table));
    /*
		 * 增加表格的自定义右键菜单
		 */
    table.addConfiguration(new BodyMenuConfiguration(this));
    // 注册列头点击监听(处理排序)
    table.addConfiguration(new SingleClickSortConfiguration());
    /*
		 * 初始化“撤销/重做”历史
		 */
    initializeOperationHistory();
    table.setData(IUndoContext.class.getName(), undoContext);
    /* Weachy - 注册修改后保存内容并自适应大小的处理 handler(覆盖默认的handler:UpdateDataCommandHandler) */
    bodyLayer.getBodyDataLayer().registerCommandHandler(new UpdateDataAndAutoResizeCommandHandler(table, bodyLayer.getBodyDataLayer()));
    /* Weachy - 注册当前显示行的行高自适应处理 handler */
    compositeLayer.registerCommandHandler(new AutoResizeCurrentRowsCommandHandler(compositeLayer));
    /* Weachy - 移除系统默认的查找 handler,添加自定义的查找替换 handler */
    bodyLayer.getSelectionLayer().unregisterCommandHandler(SearchCommand.class);
    bodyLayer.getSelectionLayer().registerCommandHandler(new FindReplaceCommandHandler(bodyLayer.getSelectionLayer()));
    /*
		 * 下面给 NatTable 添加可编辑单元格的配置
		 */
    table.addConfiguration(editableGridConfiguration());
    // 添加标记的自定义显示样式
    IConfigRegistry configRegistry = new ConfigRegistry();
    /*
		 * 如果是水平布局,则使用 ColumnOverrideLabelAccumulator 实现指定列都使用相同的显示样式;否则使用 CellOverrideLabelAccumulator 实现根据显示的内容来显示样式。
		 */
    if (isHorizontalLayout) {
        // 第一步:创建一个标签累加器,给需要绘制会不同效果的 cells 添加自定义的标签。在这里是第三列的标签列。
        ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(bodyLayer);
        columnLabelAccumulator.registerColumnOverrides(0, "LINENUMBER_CELL_LABEL");
        columnLabelAccumulator.registerColumnOverrides(1, SOURCE_EDIT_CELL_LABEL);
        columnLabelAccumulator.registerColumnOverrides(2, FLAG_CELL_LABEL);
        columnLabelAccumulator.registerColumnOverrides(3, TARGET_EDIT_CELL_LABEL);
        // 第二步:注册这个标签累加器。
        bodyLayer.setConfigLabelAccumulator(columnLabelAccumulator);
        // 第三步:把自定义的 cell painter,cell style 与自定义的标签进行关联。
        addFlagLableToColumn(configRegistry);
        addLineNumberToColumn(configRegistry);
    } else {
        ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(bodyLayer);
        columnLabelAccumulator.registerColumnOverrides(0, "LINENUMBER_CELL_LABEL");
        columnLabelAccumulator.registerColumnOverrides(1, FLAG_CELL_LABEL);
        columnLabelAccumulator.registerColumnOverrides(VerticalNatTableConfig.TARGET_COL_INDEX, SOURCE_EDIT_CELL_LABEL);
        columnLabelAccumulator.registerColumnOverrides(VerticalNatTableConfig.TARGET_COL_INDEX, TARGET_EDIT_CELL_LABEL);
        bodyLayer.setConfigLabelAccumulator(columnLabelAccumulator);
        // CellOverrideLabelAccumulator<TransUnitDummy> cellLabelAccumulator = new
        // CellOverrideLabelAccumulator<TransUnitDummy>(
        // (IRowDataProvider) bodyDataProvider);
        // CellOverrideLabelAccumulator<TransUnitBean> cellLabelAccumulator = new
        // CellOverrideLabelAccumulator<TransUnitBean>(
        // (IRowDataProvider) bodyDataProvider);
        // cellLabelAccumulator.registerOverride("flag", VerticalNatTableConfig.SOURCE_COL_INDEX,
        // FOCUS_CELL_LABEL);
        //
        // bodyLayer.getBodyDataLayer().setConfigLabelAccumulator(cellLabelAccumulator);
        addFlagLableToColumn(configRegistry);
        addLineNumberToColumn(configRegistry);
    }
    table.setConfigRegistry(configRegistry);
    // configure manually
    table.configure();
    /* Weachy - 垂直布局下,注册使键盘方向键以 2 行为一个单位移动选中行的处理 handler(覆盖默认的handler:MoveRowSelectionCommandHandler) */
    if (!isHorizontalLayout) {
    // SelectionLayer selectionLayer = bodyLayer.getSelectionLayer();
    // selectionLayer.registerCommandHandler(new VerticalMoveRowSelectionCommandHandler(selectionLayer));
    }
    if (bodyLayer.selectionLayer.getRowCount() > 0) {
        // 默认选中第一行
        HsMultiActiveCellEditor.commit(true);
        bodyLayer.selectionLayer.doCommand(new SelectCellCommand(bodyLayer.getSelectionLayer(), getTgtColumnIndex(), isHorizontalLayout ? 0 : 1, false, false));
        HsMultiCellEditorControl.activeSourceAndTargetCell(this);
    }
    IWorkbenchPage page = getSite().getPage();
    IViewReference[] viewReferences = page.getViewReferences();
    IViewPart view;
    for (int i = 0; i < viewReferences.length; i++) {
        view = viewReferences[i].getView(false);
        if (view == null) {
            continue;
        }
        // 切换到其他视图,再切换回来,解决NatTable改变布局后其他视图无法监听到的问题。
        view.setFocus();
    // break;
    }
    // 改变布局方式后,把焦点给 NatTable
    table.setFocus();
    RowHeightCalculator rowHeightCalculator = new RowHeightCalculator(bodyLayer, table, 32);
    ILayer lay = bodyLayer.getViewportLayer();
    if (lay instanceof HorizontalViewportLayer) {
        ((HorizontalViewportLayer) bodyLayer.getViewportLayer()).setRowHeightCalculator(rowHeightCalculator);
    } else if (lay instanceof VerticalViewportLayer) {
        ((VerticalViewportLayer) bodyLayer.getViewportLayer()).setRowHeightCalculator(rowHeightCalculator);
    }
    parent.layout();
    NoteToolTip toolTip = new NoteToolTip(table);
    toolTip.setPopupDelay(10);
    toolTip.activate();
    toolTip.setShift(new Point(10, 10));
    StateToolTip stateTip = new StateToolTip(table);
    stateTip.setPopupDelay(10);
    stateTip.activate();
    stateTip.setShift(new Point(10, 10));
    NotSendToTmToolTip notSendToTMToolTip = new NotSendToTmToolTip(table);
    notSendToTMToolTip.setPopupDelay(10);
    notSendToTMToolTip.activate();
    notSendToTMToolTip.setShift(new Point(10, 10));
    HasQustionToolTip hasqustionTooltip = new HasQustionToolTip(table);
    hasqustionTooltip.setPopupDelay(10);
    hasqustionTooltip.activate();
    hasqustionTooltip.setShift(new Point(10, 10));
    // 在状态栏上显示当前文本段的信息。
    updateStatusLine();
}
Also used : DisposeListener(org.eclipse.swt.events.DisposeListener) IViewPart(org.eclipse.ui.IViewPart) PaintListener(org.eclipse.swt.events.PaintListener) IPropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener) DisposeListener(org.eclipse.swt.events.DisposeListener) Listener(org.eclipse.swt.widgets.Listener) IPropertyListener(org.eclipse.ui.IPropertyListener) VerifyListener(org.eclipse.swt.events.VerifyListener) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) FindReplaceCommandHandler(net.heartsome.cat.ts.ui.xliffeditor.nattable.search.command.FindReplaceCommandHandler) DisposeEvent(org.eclipse.swt.events.DisposeEvent) BodyMenuConfiguration(net.heartsome.cat.ts.ui.xliffeditor.nattable.menu.BodyMenuConfiguration) IUndoContext(org.eclipse.core.commands.operations.IUndoContext) IConfigRegistry(net.sourceforge.nattable.config.IConfigRegistry) ConfigRegistry(net.sourceforge.nattable.config.ConfigRegistry) Control(org.eclipse.swt.widgets.Control) Language(net.heartsome.cat.common.locale.Language) DefaultNatTableStyleConfiguration(net.sourceforge.nattable.config.DefaultNatTableStyleConfiguration) IViewReference(org.eclipse.ui.IViewReference) NatTable(net.sourceforge.nattable.NatTable) ColumnOverrideLabelAccumulator(net.sourceforge.nattable.layer.cell.ColumnOverrideLabelAccumulator) UpdateDataAndAutoResizeCommandHandler(net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.UpdateDataAndAutoResizeCommandHandler) SelectCellCommand(net.sourceforge.nattable.selection.command.SelectCellCommand) ILayer(net.sourceforge.nattable.layer.ILayer) Point(org.eclipse.swt.graphics.Point) CompositeLayer(net.sourceforge.nattable.layer.CompositeLayer) Point(org.eclipse.swt.graphics.Point) RowHeightCalculator(net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.RowHeightCalculator) VerticalViewportLayer(net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.VerticalViewportLayer) HorizontalViewportLayer(net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.HorizontalViewportLayer) SingleClickSortConfiguration(net.sourceforge.nattable.sort.config.SingleClickSortConfiguration) IConfigRegistry(net.sourceforge.nattable.config.IConfigRegistry) GridData(org.eclipse.swt.layout.GridData) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) DefaultColumnHeaderDataProvider(net.sourceforge.nattable.grid.data.DefaultColumnHeaderDataProvider) AutoResizeCurrentRowsCommandHandler(net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.AutoResizeCurrentRowsCommandHandler)

Example 23 with Language

use of net.heartsome.cat.common.locale.Language in project translationstudio8 by heartsome.

the class AddTermToTBDialog method okPressed.

@Override
protected void okPressed() {
    String srcTerm = cleanString(txtSrc.getText());
    String tgtTerm = cleanString(txtTgt.getText());
    if (srcTerm == null || srcTerm.equals("")) {
        MessageDialog.openInformation(getShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.msg1"));
        return;
    }
    if (tgtTerm == null || tgtTerm.equals("")) {
        MessageDialog.openInformation(getShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.msg2"));
        return;
    }
    // 添加空格不可入库的判断,--robert 2012-11-19
    if (srcTerm.length() > 0 && srcTerm.trim().equals("")) {
        MessageDialog.openInformation(getShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.addTip1"));
        return;
    }
    if (tgtTerm.length() > 0 && tgtTerm.trim().equals("")) {
        MessageDialog.openInformation(getShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.addTip2"));
        return;
    }
    srcTerm = srcTerm.trim();
    tgtTerm = tgtTerm.trim();
    XLFHandler handler = new XLFHandler();
    IStructuredSelection srcSelected = (IStructuredSelection) cmbSrcLang.getSelection();
    Language srcSelectedLang = (Language) srcSelected.getFirstElement();
    String srcLang = srcSelectedLang.getCode();
    IStructuredSelection tgtSelection = (IStructuredSelection) cmbTgtLang.getSelection();
    Language tgtSelectedLang = (Language) tgtSelection.getFirstElement();
    String tgtLang = tgtSelectedLang.getCode();
    String strTBX = handler.generateTBXWithString(srcLang, tgtLang, srcTerm, tgtTerm, txtProperty.getText());
    TbImporter importer = TbImporter.getInstance();
    importer.setProject(project);
    int state = -1;
    try {
        if (TYPE == EDIT_TYPE) {
            if (null != this.dbOperator) {
                state = DatabaseService.importTbxWithString(strTBX, null, this.dbOperator, Constants.IMPORT_MODEL_ALWAYSADD, srcLang);
                if (state != 1) {
                    return;
                }
            }
        } else if (TYPE == ADD_TYPE) {
            state = importer.executeImport(strTBX, srcLang, null);
            if (state == ITbImporter.IMPORT_STATE_FAILED) {
                MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.msg3"));
                importer.clearResources();
                return;
            }
        }
    } catch (ImportException e) {
        final String msg = e.getMessage();
        Display.getDefault().syncExec(new Runnable() {

            public void run() {
                MessageDialog.openInformation(Display.getDefault().getActiveShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), msg);
            }
        });
        return;
    }
    importer.clearResources();
    TerminologyViewPart view = (TerminologyViewPart) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(TerminologyViewPart.ID);
    if (view != null) {
        view.refresh();
    }
    setReturnCode(OK);
    if (TYPE == ADD_TYPE) {
        try {
            project.refreshLocal(IResource.DEPTH_INFINITE, null);
        } catch (CoreException e) {
            LOGGER.error("", e);
        }
    }
    close();
}
Also used : ImportException(net.heartsome.cat.common.core.exception.ImportException) Language(net.heartsome.cat.common.locale.Language) CoreException(org.eclipse.core.runtime.CoreException) TbImporter(net.heartsome.cat.ts.tb.importer.TbImporter) ITbImporter(net.heartsome.cat.ts.tb.importer.extension.ITbImporter) TerminologyViewPart(net.heartsome.cat.ts.ui.term.view.TerminologyViewPart) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) XLFHandler(net.heartsome.cat.ts.core.file.XLFHandler)

Example 24 with Language

use of net.heartsome.cat.common.locale.Language in project translationstudio8 by heartsome.

the class XLFValidator method validateXliffFile.

/**
	 * 验证 XLIFF 文件的语言对是否与项目的语言对一致。
	 * @param iFile
	 *            ;
	 * @throws XPathEvalException
	 * @throws XPathParseException
	 * @throws NavException
	 */
public static boolean validateXliffFile(IFile iFile) {
    shell = Display.getDefault().getActiveShell();
    try {
        Object[] arrObj = getProjectLang(iFile);
        if (arrObj == null) {
            return false;
        }
        String xlfFolderPath = iFile.getProject().getFullPath().append(Constant.FOLDER_XLIFF).toOSString();
        String xlfFullPath = iFile.getFullPath().toOSString();
        if (!xlfFullPath.startsWith(xlfFolderPath) || iFile.getParent().getFullPath().toOSString().equals(xlfFolderPath)) {
            // 该 XLIFF 文件是 XLIFF 目录的直接子文件或者不在 XLIFF 的目录下
            if (!blnMsg1) {
                MessageDialogWithToggle dialog = MessageDialogWithToggle.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"), MessageFormat.format(Messages.getString("file.XLFValidator.msg1"), xlfFullPath), Messages.getString("file.XLFValidator.toggleStateMsg"), false, null, null);
                blnMsg1 = dialog.getToggleState();
            }
            return false;
        }
        Language projectSrcLang = (Language) arrObj[0];
        @SuppressWarnings("unchecked") List<Language> lstProjectTgtLang = (List<Language>) arrObj[1];
        // /test/XLIFF/zh-CN/split/test.xlf (zh-CN 在第三级目录下)
        String parentName = xlfFullPath.split(System.getProperty("file.separator").replaceAll("\\\\", "\\\\\\\\"))[3];
        Vector<String> languageVector = new Vector<String>();
        languageVector.add(parentName);
        if (LocaleService.verifyLanguages(languageVector)) {
            boolean flag = false;
            for (Language lang : lstProjectTgtLang) {
                if (lang.getCode().equalsIgnoreCase(parentName)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                if (!blnMsg1) {
                    MessageDialogWithToggle dialog = MessageDialogWithToggle.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"), MessageFormat.format(Messages.getString("file.XLFValidator.msg2"), xlfFullPath), Messages.getString("file.XLFValidator.toggleStateMsg"), false, null, null);
                    blnMsg1 = dialog.getToggleState();
                }
                return false;
            }
        } else {
            if (!blnMsg1) {
                MessageDialogWithToggle dialog = MessageDialogWithToggle.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"), MessageFormat.format(Messages.getString("file.XLFValidator.msg3"), xlfFullPath), Messages.getString("file.XLFValidator.toggleStateMsg"), false, null, null);
                blnMsg1 = dialog.getToggleState();
            }
            return false;
        }
        String xlfSrcLang = null;
        String xlfTgtLang = null;
        VTDGen vg = new VTDGen();
        XMLModifier xm = null;
        boolean isConfirmSrc = false;
        boolean isConfirmTgt = false;
        String fileOsPath = ResourceUtils.iFileToOSPath(iFile);
        boolean result = false;
        try {
            result = vg.parseFile(fileOsPath, true);
        } catch (Exception e) {
        }
        if (!result) {
            MessageDialog.openError(shell, Messages.getString("file.XLFValidator.errorTitle"), MessageFormat.format(Messages.getString("file.XLFValidator.parseError"), fileOsPath));
            return false;
        }
        VTDNav vn = vg.getNav();
        VTDUtils vu = new VTDUtils(vn);
        AutoPilot ap = new AutoPilot(vn);
        ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
        ap.selectXPath("/xliff/file");
        String original = null;
        int tempi = ap.evalXPath();
        if (tempi == -1) {
            MessageDialog.openError(shell, Messages.getString("file.XLFValidator.errorTitle"), MessageFormat.format(Messages.getString("file.XLFValidator.parseError"), fileOsPath));
            return false;
        }
        do {
            xlfSrcLang = vu.getCurrentElementAttribut("source-language", null);
            xlfTgtLang = vu.getCurrentElementAttribut("target-language", null);
            original = vu.getCurrentElementAttribut("original", null);
            if (original == null || original.trim().isEmpty()) {
                MessageDialog.openWarning(shell, Messages.getString("file.XLFValidator.warningTitle"), MessageFormat.format(Messages.getString("file.XLFValidator.msg10"), xlfFullPath));
                return false;
            }
            String msg = null;
            // XLIFF 源语言为空或与项目源语言不一致;
            if (xlfSrcLang == null || !xlfSrcLang.equalsIgnoreCase(projectSrcLang.getCode())) {
                if (!blnIsOpenConfirmSrc && !isConfirmSrc) {
                    if (xlfSrcLang == null) {
                        msg = MessageFormat.format(Messages.getString("file.XLFValidator.msg4"), xlfFullPath, projectSrcLang.getCode());
                    } else {
                        msg = MessageFormat.format(Messages.getString("file.XLFValidator.msg5"), xlfFullPath, xlfSrcLang.toLowerCase(), projectSrcLang.getCode());
                    }
                    MessageDialogWithToggle dialog = new MessageDialogWithToggle(shell, Messages.getString("file.XLFValidator.msgTitle2"), null, msg, MessageDialog.CONFIRM, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0, Messages.getString("file.XLFValidator.toggleStateMsg"), false);
                    int returnCode = dialog.open();
                    if (returnCode == IDialogConstants.YES_ID) {
                        isConfirmSrc = true;
                        blnIsOpenConfirmSrcY = true;
                    } else if (returnCode == IDialogConstants.NO_ID) {
                        isConfirmSrc = false;
                        blnIsOpenConfirmSrcY = false;
                    }
                    blnIsOpenConfirmSrc = dialog.getToggleState();
                }
                if ((isConfirmSrc || (blnIsOpenConfirmSrc && blnIsOpenConfirmSrcY)) && xlfSrcLang != null) {
                    xm = vu.update(null, xm, "/xliff/file[@original=\"" + original + "\"]/@source-language", projectSrcLang.getCode(), VTDUtils.CREATE_IF_NOT_EXIST);
                } else if (!isConfirmSrc && !(blnIsOpenConfirmSrc && blnIsOpenConfirmSrcY)) {
                    return false;
                }
            }
            // XLIFF 目标语言为空,(且其所在的 XLIFF 一级子目录名称是项目的目标语言代码之一,已在上面验证)直接设置
            if (xlfTgtLang == null || xlfSrcLang == null) {
                // XLIFF 文件中源与目标都为空时,由于 VTD 要求不能在一个位置修改两次,因此使用下面的方式插入源与目标到 file 节点中
                if (xlfTgtLang == null && xlfSrcLang == null) {
                    String attrFragment = new StringBuffer(" source-language=\"").append(projectSrcLang.getCode()).append("\" target-language=\"").append(parentName).append("\"").toString();
                    // attrName="attrValue"
                    // ”
                    // 得到开始标记的结束位置
                    long i = vn.getOffsetAfterHead();
                    if (xm == null) {
                        xm = new XMLModifier(vn);
                    }
                    if (vn.getEncoding() < VTDNav.FORMAT_UTF_16BE) {
                        xm.insertBytesAt((int) i - 1, attrFragment.getBytes());
                    } else {
                        xm.insertBytesAt(((int) i - 1) << 1, attrFragment.getBytes());
                    }
                } else if (xlfTgtLang == null) {
                    xm = vu.update(null, xm, "/xliff/file[@original=\"" + original + "\"]/@target-language", parentName, VTDUtils.CREATE_IF_NOT_EXIST);
                } else if (xlfSrcLang == null) {
                    xm = vu.update(null, xm, "/xliff/file[@original=\"" + original + "\"]/@source-language", projectSrcLang.getCode(), VTDUtils.CREATE_IF_NOT_EXIST);
                }
            }
            if (xlfTgtLang != null) {
                // XLIFF 目标语言非空,但未放在对应的目录下。
                boolean flag = false;
                for (Language lang : lstProjectTgtLang) {
                    if (lang.getCode().equalsIgnoreCase(xlfTgtLang)) {
                        flag = true;
                        break;
                    }
                }
                String message = null;
                if (!flag) {
                    message = MessageFormat.format(Messages.getString("file.XLFValidator.msg6"), xlfFullPath, xlfTgtLang, parentName);
                } else if (!xlfTgtLang.equalsIgnoreCase(parentName)) {
                    message = MessageFormat.format(Messages.getString("file.XLFValidator.msg7"), xlfFullPath, xlfTgtLang, parentName);
                }
                if (!blnIsOpenConfirmTgt && !isConfirmTgt && message != null) {
                    MessageDialogWithToggle dialog = new MessageDialogWithToggle(shell, Messages.getString("file.XLFValidator.msgTitle2"), null, message, MessageDialog.CONFIRM, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0, Messages.getString("file.XLFValidator.toggleStateMsg"), false);
                    int returnCode = dialog.open();
                    if (returnCode == IDialogConstants.YES_ID) {
                        isConfirmTgt = true;
                        blnIsOpenConfirmTgtY = true;
                    } else if (returnCode == IDialogConstants.NO_ID) {
                        isConfirmTgt = false;
                        blnIsOpenConfirmTgtY = false;
                    }
                    blnIsOpenConfirmTgt = dialog.getToggleState();
                }
                if ((blnIsOpenConfirmTgt && blnIsOpenConfirmTgtY) || isConfirmTgt) {
                    xm = vu.update(null, xm, "/xliff/file[@original=\"" + original + "\"]/@target-language", parentName, VTDUtils.CREATE_IF_NOT_EXIST | VTDUtils.PILOT_TO_END);
                // vu.bind(xm.outputAndReparse());
                } else if (message != null) {
                    return false;
                }
            }
            // Bug #2329:文件语言更改成项目语言时应同时更改 source 节点的 xml:lang 属性值,如果 target 节点有 xml:lang 属性,也要修改成项目语言
            AutoPilot tempAp = new AutoPilot(vn);
            tempAp.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
            xm = vu.update(tempAp, xm, "/xliff/file[@original=\"" + original + "\"]/body//trans-unit/source/@xml:lang", projectSrcLang.getCode(), VTDUtils.CREATE_IF_NOT_EXIST | VTDUtils.PILOT_TO_END);
            xm = vu.update(tempAp, xm, "/xliff/file[@original=\"" + original + "\"]/body//trans-unit/target/@xml:lang", parentName, VTDUtils.PILOT_TO_END);
        } while (ap.evalXPath() != -1);
        if (xm != null) {
            // vu.bind(xm.outputAndReparse());
            vu.bind(vu.updateVTDNav(xm, ResourceUtils.iFileToOSPath(iFile)));
        }
        vg.clear();
        iFile.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (XPathParseException e) {
        e.printStackTrace();
        logger.error(Messages.getString("file.XLFValidator.logger1"), e);
        MessageDialog.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"), Messages.getString("file.XLFValidator.msg8"));
        return false;
    } catch (XPathEvalException e) {
        e.printStackTrace();
        logger.error(Messages.getString("file.XLFValidator.logger1"), e);
        MessageDialog.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"), Messages.getString("file.XLFValidator.msg8"));
        return false;
    } catch (NavException e) {
        e.printStackTrace();
        logger.error(Messages.getString("file.XLFValidator.logger1"), e);
        MessageDialog.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"), Messages.getString("file.XLFValidator.msg8"));
        return false;
    } catch (CoreException e) {
        logger.error("", e);
    } catch (ModifyException e) {
        logger.error("", e);
    }
    return true;
}
Also used : XMLModifier(com.ximpleware.XMLModifier) XPathParseException(com.ximpleware.XPathParseException) Language(net.heartsome.cat.common.locale.Language) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) MessageDialogWithToggle(org.eclipse.jface.dialogs.MessageDialogWithToggle) ModifyException(com.ximpleware.ModifyException) ArrayList(java.util.ArrayList) List(java.util.List) Vector(java.util.Vector) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) VTDGen(com.ximpleware.VTDGen) NavException(com.ximpleware.NavException) CoreException(org.eclipse.core.runtime.CoreException) XPathEvalException(com.ximpleware.XPathEvalException) XPathParseException(com.ximpleware.XPathParseException) ModifyException(com.ximpleware.ModifyException) CoreException(org.eclipse.core.runtime.CoreException) AutoPilot(com.ximpleware.AutoPilot) VTDNav(com.ximpleware.VTDNav)

Example 25 with Language

use of net.heartsome.cat.common.locale.Language in project translationstudio8 by heartsome.

the class LanguageConfiger method getLanuagesByCodes.

/**
	 * 返回一组语言Code对应的<code>Language</code>对象,如果此Code在语言配置中未找到,此Language对象只保存Code
	 * @param codeList
	 * @return ;
	 */
public List<Language> getLanuagesByCodes(List<String> codeList) {
    List<Language> result = new ArrayList<Language>();
    for (String code : codeList) {
        Language lang = getLanguageByCode(code);
        if (lang == null) {
            lang = new Language(code, "", "", false);
        }
        result.add(lang);
    }
    return result;
}
Also used : Language(net.heartsome.cat.common.locale.Language) ArrayList(java.util.ArrayList)

Aggregations

Language (net.heartsome.cat.common.locale.Language)31 ArrayList (java.util.ArrayList)10 AutoPilot (com.ximpleware.AutoPilot)6 NavException (com.ximpleware.NavException)5 IStructuredSelection (org.eclipse.jface.viewers.IStructuredSelection)5 XPathEvalException (com.ximpleware.XPathEvalException)4 XPathParseException (com.ximpleware.XPathParseException)4 File (java.io.File)4 IOException (java.io.IOException)4 ProjectConfiger (net.heartsome.cat.ts.core.file.ProjectConfiger)4 CoreException (org.eclipse.core.runtime.CoreException)4 GridData (org.eclipse.swt.layout.GridData)4 VTDGen (com.ximpleware.VTDGen)3 VTDNav (com.ximpleware.VTDNav)3 List (java.util.List)3 LanguageLabelProvider (net.heartsome.cat.ts.ui.composite.LanguageLabelProvider)3 IXliffEditor (net.heartsome.cat.ts.ui.editors.IXliffEditor)3 VTDUtils (net.heartsome.xml.vtdimpl.VTDUtils)3 XMLModifier (com.ximpleware.XMLModifier)2 FileOutputStream (java.io.FileOutputStream)2