Example #1
0
        private void init()   // Get settings and current locale data
        {
            settings = settings == null?Resources.Load <TranslationSettings>(Translation.Strings.SettingsPath) : settings;

            LocaleData[] locales = Resources.LoadAll <LocaleData>(settings.LocalesResourcePath);
            serializedLocales = locales != null && locales.Length > 0 ? new SerializedObject(locales) : null;
        }
        public TypeNameTranslation(Type type, ITranslationContext context)
        {
            Type = type;
            _translationSettings = context.Settings;
            _isObject            = type == typeof(object);

            if (_isObject)
            {
                EstimatedSize = _object.Length;
                return;
            }

            if (type.FullName == null)
            {
                return;
            }

            if (_translationSettings.FullyQualifyTypeNames && (type.Namespace != null))
            {
                EstimatedSize = type.Namespace.Length;
            }

            EstimatedSize += type.GetSubstitutionOrNull()?.Length ?? type.Name.Length;

            while (type.IsNested)
            {
                type           = type.DeclaringType;
                EstimatedSize += type.Name.Length;
            }
        }
Example #3
0
        public static void CreateLocalisationSettings()
        {
            string soundName = "Assets/" + Constants.GameName.NameOfGame + "/Settings/Localisations/SoundSettings.asset";

            AssertExistingAsset(soundName);
            string textName = "Assets/" + Constants.GameName.NameOfGame + "/Settings/Localisations/TranslationSettings.asset";

            AssertExistingAsset(textName);
            string localisationName = "Assets/" + Constants.GameName.NameOfGame + "/Settings/Localisations/LocalisationSettings.asset";

            AssertExistingAsset(localisationName);

            SoundSettings soundAsset = ScriptableObject.CreateInstance <SoundSettings>();

            AssetDatabase.CreateAsset(soundAsset, soundName);

            TranslationSettings translationAsset = ScriptableObject.CreateInstance <TranslationSettings>();

            AssetDatabase.CreateAsset(translationAsset, textName);

            LocalisationSettings localisationAsset = ScriptableObject.CreateInstance <LocalisationSettings>();

            localisationAsset.Sound = new[] { soundAsset };
            localisationAsset.Text  = new[] { translationAsset };
            AssetDatabase.CreateAsset(localisationAsset, localisationName);

            Selection.activeObject = localisationAsset;
            EditorGUIUtility.PingObject(localisationAsset);
        }
        protected InitializerSetTranslationBase(IList <TInitializer> initializers, ITranslationContext context)
        {
            _settings = context.Settings;

            var initializersCount = initializers.Count;

            Count = initializersCount;
            _initializerTranslations = new ITranslatable[initializersCount];

            var translationSize = 4;
            var formattingSize  = 0;

            for (var i = 0; ;)
            {
                // ReSharper disable once VirtualMemberCallInConstructor
                var initializerTranslation = GetTranslation(initializers[i], context);
                _initializerTranslations[i] = initializerTranslation;
                translationSize            += initializerTranslation.TranslationSize;
                formattingSize += initializerTranslation.FormattingSize;

                ++i;

                if (i == initializersCount)
                {
                    break;
                }

                translationSize += 2; // For ', '
            }

            TranslationSize = translationSize;
            FormattingSize  = formattingSize;
        }
        public TranslationExpression <T> AddTranslation <T>(string profileName, TranslationSettings translationSettings) where T : new()
        {
            var translation = new Translation(typeof(T), GetProfile(profileName), translationSettings);

            this._translations.Add(translation.TranslationUniqueIdentifier, translation);
            return(new TranslationExpression <T>(translation));
        }
Example #6
0
    /// <summary>
    /// Submits the node for translation. Does not check the permissions, you need to chek it before calling this method.
    /// </summary>
    public string SubmitToTranslation()
    {
        string err = ValidateData();

        if (!string.IsNullOrEmpty(err))
        {
            return(err);
        }

        TranslationSettings settings = TranslationSettings ?? new TranslationSettings();

        if (string.IsNullOrEmpty(settings.TargetLanguage))
        {
            settings.TargetLanguage = LocalizationContext.PreferredCultureCode;
        }
        settings.TranslateWebpartProperties = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSTranslateWebpartProperties");
        settings.SourceLanguage             = FromLanguage;
        settings.Instructions           = Instructions;
        settings.Priority               = Priority;
        settings.ProcessBinary          = ProcessBinary;
        settings.TranslateAttachments   = ProcessBinary;
        settings.TranslationDeadline    = Deadline;
        settings.TranslationServiceName = hdnSelectedName.Value;

        TreeProvider tree = TreeProvider ?? new TreeProvider();
        TreeNode     node = DocumentHelper.GetDocument(NodeID, settings.SourceLanguage, true, tree);

        TranslationSubmissionInfo submissionInfo;

        return(TranslationServiceHelper.SubmitToTranslation(settings, node, out submissionInfo));
    }
Example #7
0
        private void RegenerateSchema(IFilePresenterTab filePresenterTab)
        {
            XDocument document;
            ILog      log;

            TagClass            tag      = (TagClass)filePresenterTab.Tag;
            TranslationSettings settings = tag.settings;

            foreach (FilePresenterButtonInfo buttonInfo in filePresenterTab.FilePresenterButtons)
            {
                if (buttonInfo.ButtonName == "SA")
                {
                    settings.SchemaAware = buttonInfo.IsToggled;
                }
                if (buttonInfo.ButtonName == "F")
                {
                    settings.Functional = buttonInfo.IsToggled;
                }
            }
            settings.SubexpressionTranslations.Clear();
            settings.Retranslation = false;
            GenerateSchema(filePresenterTab.SourcePSMSchema, settings, out document, out log);
            tag.tweakingPanel.Bind(settings.SubexpressionTranslations);
            filePresenterTab.ReDisplayFile(document, EDisplayedFileType.SCH, filePresenterTab.SourcePSMSchema.Caption, log, filePresenterTab.ValidationSchema, filePresenterTab.SourcePSMSchema);
        }
Example #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <TranslationSettings> translationOptions)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            TranslationSettings = translationOptions.Value;
            SetupTranslationManager();
        }
Example #9
0
        private static string GetVariableName(Type type, TranslationSettings settings)
        {
            if (type.IsArray)
            {
                return(GetVariableName(type.GetElementType(), settings) + "Array");
            }

            var typeIsEnumerable = type.IsEnumerable();
            var typeIsDictionary = typeIsEnumerable && type.IsDictionary();
            var namingType       = (typeIsEnumerable && !typeIsDictionary) ? type.GetEnumerableElementType() : type;
            var variableName     = GetBaseVariableName(namingType, settings);

            if (namingType.IsInterface())
            {
                variableName = variableName.Substring(1);
            }

            if (namingType.IsGenericType())
            {
                variableName = GetGenericTypeVariableName(variableName, namingType, settings);
            }

            variableName = RemoveLeadingNonAlphaNumerics(variableName);

            return((typeIsDictionary || !typeIsEnumerable) ? variableName : variableName.Pluralise());
        }
        internal static string GetFriendlyName(this Type type, TranslationSettings translationSettings)
        {
            var buffer = new TranslationBuffer((type.FullName ?? type.ToString()).Length);

            buffer.WriteFriendlyName(type, translationSettings);

            return(buffer.GetContent());
        }
Example #11
0
 public ParameterSetTranslation(ITranslation parameter, ITranslationContext context)
 {
     _settings = context.Settings;
     _parameterTranslations = new[] { new CodeBlockTranslation(parameter, context) };
     TranslationSize        = parameter.TranslationSize + _openAndCloseParentheses.Length;
     FormattingSize         = parameter.FormattingSize;
     Count = 1;
 }
Example #12
0
        /// <summary>
        /// Creates a new instance of ManipulatorSettings with default setting values
        /// </summary>
        internal ManipulatorSettings()
        {
            mTranslationSettings = new TranslationSettings();
            mRotationSettings    = new RotationSettings();
            mScaleSettings       = new ScaleSettings();

            mTranslationSettings.RestoreDefaults();
            mRotationSettings.RestoreDefaults();
            mScaleSettings.RestoreDefaults();
        }
Example #13
0
        internal static void WriteFriendlyName(
            this TranslationBuffer buffer,
            Type type,
            TranslationSettings settings)
        {
            if (type.FullName == null)
            {
                // An open generic parameter Type:
                return;
            }

            if (type.IsArray)
            {
                buffer.WriteFriendlyName(type.GetElementType(), settings);
                buffer.WriteToTranslation("[]");
                return;
            }

            if (!type.IsGenericType())
            {
                var substitutedTypeName = type.GetSubstitutionOrNull();

                if (type.IsNested)
                {
                    buffer.WriteFriendlyName(type.DeclaringType, settings);
                    buffer.WriteToTranslation('.');
                    buffer.WriteToTranslation(substitutedTypeName ?? type.Name);
                    return;
                }

                if (substitutedTypeName != null)
                {
                    buffer.WriteToTranslation(substitutedTypeName);
                    return;
                }

                buffer.WriteTypeNamespaceIfRequired(type, settings);
                buffer.WriteToTranslation(type.Name);
                return;
            }

            Type underlyingNullableType;

            if ((underlyingNullableType = Nullable.GetUnderlyingType(type)) == null)
            {
                buffer.WriteGenericTypeName(type, settings);
                return;
            }

            buffer.WriteFriendlyName(underlyingNullableType, settings);
            buffer.WriteToTranslation('?');
        }
Example #14
0
        void tweakingPanel_TranslationTweaked(object sender, ExpressionTweakingPanel.TranslationTweakedEventArgs translationTweakedEventArgs)
        {
            ExpressionTweakingPanel p = (ExpressionTweakingPanel)sender;
            XDocument           document;
            ILog                log;
            TagClass            tag      = (TagClass)p.FilePresenterTab.Tag;
            TranslationSettings settings = tag.settings;

            settings.Retranslation = true;
            GenerateSchema(p.FilePresenterTab.SourcePSMSchema, settings, out document, out log);
            p.FilePresenterTab.ReDisplayFile(document, EDisplayedFileType.SCH,
                                             p.FilePresenterTab.SourcePSMSchema.Caption, log, p.FilePresenterTab.ValidationSchema, p.FilePresenterTab.SourcePSMSchema);
        }
Example #15
0
        private static void WriteTypeNamespaceIfRequired(
            this TranslationBuffer buffer,
            Type type,
            TranslationSettings settings)
        {
            if (!settings.FullyQualifyTypeNames || (type.Namespace == null))
            {
                return;
            }

            buffer.WriteToTranslation(type.Namespace);
            buffer.WriteToTranslation('.');
        }
Example #16
0
        public static void TestTranslation(PIMSchema schema, string expected, TranslationSettings settings = null)
        {
            if (settings == null)
            {
                settings = new TranslationSettings();
            }
            Exolutio.SupportingClasses.ILog log;
            SourceFile[] files  = Translations.TranslatePIMToCSharp(schema, settings, out log);
            string       s      = files[0].Code;
            string       prolog = "using Exolutio.CodeContracts.Support; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; ";

            TestUtils.AssertEqualIgnoreSpace(prolog + expected, s);
        }
        protected internal TranslationBase(Type type, TranslationProfile translationProfile, TranslationSettings translationSettings)
        {
            if (string.IsNullOrEmpty(translationSettings.TranslationName))
            {
                translationSettings.TranslationName = type.BuildFormattedName();
            }

            this.TranslationProfile = translationProfile;
            this.TranslationSettings = translationSettings;
            this.TraversedGenericArguments = type.GetTraversedGenericTypes().ToList();
            this.ColumnConfigurations = new List<NonIdentityColumnConfiguration>();
            this.TypeInfo = type.GetTypeInfo();
            this.TranslationUniqueIdentifier = TranslationUniqueIdentifier.GetInstance(this);
        }
        internal static string GetFriendlyName(
            this Type type,
            TranslationSettings translationSettings,
            ITranslationFormatter formatter)
        {
            var writer = new TranslationWriter(
                formatter,
                translationSettings.Indent,
                (type.FullName ?? type.ToString()).Length);

            writer.WriteFriendlyName(type, translationSettings);

            return(writer.GetContent());
        }
Example #19
0
        protected internal TranslationBase(Type type, TranslationProfile translationProfile, TranslationSettings translationSettings)
        {
            if (string.IsNullOrEmpty(translationSettings.TranslationName))
            {
                translationSettings.TranslationName = type.BuildFormattedName();
            }

            this.TranslationProfile        = translationProfile;
            this.TranslationSettings       = translationSettings;
            this.TraversedGenericArguments = type.GetTraversedGenericTypes().ToList();
            this.ColumnConfigurations      = new List <NonIdentityColumnConfiguration>();
            this.TypeInfo = type.GetTypeInfo();
            this.TranslationUniqueIdentifier = TranslationUniqueIdentifier.GetInstance(this);
        }
Example #20
0
        internal static string GetFriendlyName(this Type type, TranslationSettings translationSettings)
        {
            if (type.FullName == null)
            {
                // An open generic parameter Type:
                return(null);
            }

            var buffer = new TranslationBuffer(type.FullName.Length);

            buffer.WriteFriendlyName(type, translationSettings);

            return(buffer.GetContent());
        }
Example #21
0
 public override void OnInspectorGUI()
 {
     settings = settings ?? Resources.Load <TranslationSettings>(Translation.Strings.SettingsPath);
     serializedObject.Update();
     if (useFancyEdit)
     {
         fancyEdit();
     }
     else
     {
         EditorGUILayout.PropertyField(localizedKeyProp);
     }
     serializedObject.ApplyModifiedProperties();
     base.OnInspectorGUI();
 }
 public AssignmentTranslation(
     ExpressionType nodeType,
     ITranslation targetTranslation,
     Expression value,
     ITranslationContext context)
     : base(IsCheckedAssignment(nodeType), " { ", " }")
 {
     NodeType           = nodeType;
     _targetTranslation = targetTranslation;
     _settings          = context.Settings;
     _operator          = GetOperatorOrNull(nodeType);
     _valueTranslation  = GetValueTranslation(value, context);
     TranslationSize    = GetTranslationSize();
     FormattingSize     = _targetTranslation.FormattingSize + _valueTranslation.FormattingSize;
 }
Example #23
0
        //private void GenerateSchemaAware(IFilePresenterTab filePresenterTab)
        //{
        //    XDocument document;
        //    ILog log;
        //    SchematronSchemaGenerator.TranslationSettings settings = (SchematronSchemaGenerator.TranslationSettings)filePresenterTab.Tag;
        //    GenerateSchema(filePresenterTab.SourcePSMSchema, settings, out document, out log);
        //    filePresenterTab.ReDisplayFile(document, EDisplayedFileType.SCH, filePresenterTab.SourcePSMSchema.Caption, log, filePresenterTab.ValidationSchema, filePresenterTab.SourcePSMSchema);
        //}

        private static void GenerateSchema(PSMSchema psmSchema, TranslationSettings settings, out XDocument schematronSchemaDocument, out ILog log)
        {
            SchematronSchemaGenerator schemaGenerator = new SchematronSchemaGenerator();

            schemaGenerator.Initialize(psmSchema);
            settings.SubexpressionTranslations.Log = schemaGenerator.Log;
            schematronSchemaDocument = schemaGenerator.GetSchematronSchema(settings);

            if (Environment.MachineName.Contains("TRUPIK"))
            {
                schematronSchemaDocument.Save(@"d:\Development\Exolutio\SchematronTest\LastSchSchema.sch");
            }

            log = schemaGenerator.Log;
        }
Example #24
0
        private static void WriteGenericTypeName(
            this TranslationBuffer buffer,
            Type type,
            int numberOfParameters,
            IList <Type> typeArguments,
            TranslationSettings settings)
        {
            var isAnonType =
                type.Name.StartsWith('<') &&
                (type.Name.IndexOf("AnonymousType", StringComparison.Ordinal)) != -1;

            if (isAnonType && (settings.AnonymousTypeNameFactory != null))
            {
                buffer.WriteToTranslation(settings.AnonymousTypeNameFactory.Invoke(type));
                return;
            }

            string typeName;

            if (isAnonType)
            {
                typeName = "AnonymousType";
            }
            else
            {
                var parameterCountIndex = type.Name.IndexOf("`" + numberOfParameters, StringComparison.Ordinal);
                typeName = type.Name.Substring(0, parameterCountIndex);
            }

            buffer.WriteToTranslation(typeName);
            buffer.WriteToTranslation('<');

            for (var i = 0; ;)
            {
                var typeArgument = typeArguments[i++];

                buffer.WriteFriendlyName(typeArgument, settings);

                if (i == typeArguments.Count)
                {
                    break;
                }

                buffer.WriteToTranslation(", ");
            }

            buffer.WriteToTranslation('>');
        }
    /// <summary>
    /// Reads the settings from the configuration file in the mod settings folder
    /// </summary>
    /// <returns></returns>
    TranslationSettings ReadConfig()
    {
        Configuration <TranslationSettings> config = new Configuration <TranslationSettings>(_settingsFileName);
        TranslationSettings settings = config.Settings;

        config.Settings = settings;

        if (settings.UseGlobalSettings)
        {
            Configuration <TranslationSettings> configG = new Configuration <TranslationSettings>("TranslatedModules-Settings");
            if (configG.Settings != null)
            {
                configG.Settings.UseGlobalSettings = true;
                Log("Config file dictates using the global translated modules settings.");
                return(configG.Settings);
            }
            else
            {
                // could not find global config file. See if the service is installed, and whether there perhaps was an update that renamed the settings file.
                GameObject ts = GameObject.Find("TranslatedModulesService(Clone)");
                if (ts == null)
                {
                    // translated modules service not installed.
                    Log("Config file dictates using the global translated modules settings, but the translated modules service does not appear to be installed.");
                    return(null);
                }
                try {
                    Component service          = ts.GetComponent("TranslatedModulesService");
                    Type      type             = service.GetType();
                    FieldInfo fieldSettings    = type.GetField("SettingsFileName");
                    string    settingsFileName = (string)fieldSettings.GetValue(service);
                    Configuration <TranslationSettings> configG2 = new Configuration <TranslationSettings>("TranslatedModules-Settings");
                    if (configG2.Settings != null)
                    {
                        configG2.Settings.UseGlobalSettings = true;
                        Log("Config file dictates using the global translated modules settings. These settings were found, but under a different filename than expected.");
                        return(configG2.Settings);
                    }
                }
                catch (Exception e) {
                    Debug.Log(e.Message);
                    Log("Config file dictates using the global translated modules settings, but an error occured trying to acquire them.");
                    return(null);
                }
            }
        }
        return(config.Settings);
    }
Example #26
0
    /// <summary>
    /// Prepares translation settings.
    /// </summary>
    private TranslationSettings PrepareTranslationSettings()
    {
        var settings = new TranslationSettings
        {
            SourceLanguage         = translationElem.FromLanguage,
            Instructions           = translationElem.Instructions,
            Priority               = translationElem.Priority,
            TranslateAttachments   = translationElem.ProcessBinary,
            TranslationDeadline    = translationElem.Deadline,
            TranslationServiceName = translationElem.SelectedService
        };

        settings.TargetLanguages.AddRangeToSet(targetCultures);

        return(settings);
    }
        private static string GetGenericTypeVariableName(Type namingType, TranslationSettings settings)
        {
            var nonNullableType      = namingType.GetNonNullableType();
            var genericTypeArguments = namingType.GetGenericTypeArguments();

            if (nonNullableType != namingType)
            {
                return("nullable" + genericTypeArguments[0].GetVariableNameInPascalCase(settings));
            }

            var writer = new GenericVariableNameWriter(settings);

            writer.WriteGenericTypeName(namingType, genericTypeArguments);

            return(writer.TypeName);
        }
    /// <summary>
    /// Prepares translation settings.
    /// </summary>
    private TranslationSettings PrepareTranslationSettings()
    {
        var settings = new TranslationSettings
        {
            TranslateWebpartProperties = SettingsKeyInfoProvider.GetBoolValue(CurrentSiteName + ".CMSTranslateWebpartProperties"),
            SourceLanguage             = translationElem.FromLanguage,
            Instructions           = translationElem.Instructions,
            Priority               = translationElem.Priority,
            TranslateAttachments   = translationElem.ProcessBinary,
            TranslationDeadline    = translationElem.Deadline,
            TranslationServiceName = translationElem.SelectedService
        };

        settings.TargetLanguages.AddRange(targetCultures);

        return(settings);
    }
        public static TranslationSettings Update(
            this VisualizerDialogSettings dialogSettings,
            TranslationSettings settings)
        {
            if (dialogSettings.UseFullyQualifiedTypeNames)
            {
                settings = settings.UseFullyQualifiedTypeNames;
            }

            if (dialogSettings.UseExplicitTypeNames)
            {
                settings = settings.UseExplicitTypeNames;
            }

            if (dialogSettings.UseExplicitGenericParameters)
            {
                settings = settings.UseExplicitGenericParameters;
            }

            if (dialogSettings.DeclareOutputParametersInline)
            {
                settings = settings.DeclareOutputParametersInline;
            }

            if (dialogSettings.ShowImplicitArrayTypes)
            {
                settings = settings.ShowImplicitArrayTypes;
            }

            if (dialogSettings.ShowLambdaParameterTypeNames)
            {
                settings = settings.ShowLambdaParameterTypes;
            }

            if (dialogSettings.ShowQuotedLambdaComments)
            {
                settings = settings.ShowQuotedLambdaComments;
            }

            settings.IndentUsing(dialogSettings.Indent);

            return(settings);
        }
Example #30
0
        public override void Execute(object parameter = null)
        {
            if (Current.ActiveDiagram != null && Current.ActiveDiagram is PSMDiagram)
            {
                XDocument schematronSchemaDocument;
                ILog      log;

                TranslationSettings settings = new TranslationSettings();
                settings.Functional  = true;
                settings.SchemaAware = true;

                GenerateSchema((PSMSchema)Current.ActiveDiagram.Schema, settings, out schematronSchemaDocument, out log);

                FilePresenterButtonInfo[] additionalButtonsInfo = new[] {
                    new FilePresenterButtonInfo()
                    {
                        ButtonName = "SA", Text = "Schema aware", Icon = ExolutioResourceNames.GetResourceImageSource(ExolutioResourceNames.refresh), UpdateFileContentAction = RegenerateSchema, ToggleButton = true, IsToggled = true
                    },
                    new FilePresenterButtonInfo()
                    {
                        ButtonName = "F", Text = "Functional", Icon = ExolutioResourceNames.GetResourceImageSource(ExolutioResourceNames.refresh), UpdateFileContentAction = RegenerateSchema, ToggleButton = true, IsToggled = true
                    },
                };

                ExpressionTweakingPanel tweakingPanel = new ExpressionTweakingPanel();

                TagClass tag = new TagClass();
                tag.settings      = settings;
                tag.tweakingPanel = tweakingPanel;

                IFilePresenterTab filePresenterTab
                    = Current.MainWindow.FilePresenter.DisplayFile(schematronSchemaDocument, EDisplayedFileType.SCH, Current.ActiveDiagram.Caption + ".sch", log, sourcePSMSchema: (PSMSchema)Current.ActiveDiagram.Schema,
                                                                   additionalActions: additionalButtonsInfo, tag: tag);
                filePresenterTab.RefreshCallback += RegenerateSchema;
                if (settings.SubexpressionTranslations.TranslationOptionsWithMorePossibilities.Any())
                {
                    tweakingPanel.Bind(settings.SubexpressionTranslations);
                    tweakingPanel.FilePresenterTab = filePresenterTab;
                    filePresenterTab.DisplayAdditionalControl(tweakingPanel, "Expression Tweaking");
                    tweakingPanel.TranslationTweaked += tweakingPanel_TranslationTweaked;
                }
            }
        }
    private bool CheckLanguageSupport(AbstractHumanTranslationService humanService, TranslationSettings settings)
    {
        var sourceLanguage = settings.SourceLanguage;

        if (!humanService.CheckSourceLanguageAvailability(sourceLanguage))
        {
            AddError(String.Format(ResHelper.GetString("translationservice.sourcelanguagenotsupported"), sourceLanguage));
            return(false);
        }

        var unavailableLanguages = humanService.CheckTargetLanguagesAvailability(settings.TargetLanguages);

        if (unavailableLanguages.Count > 0)
        {
            AddError(String.Format(ResHelper.GetString("translationservice.targetlanguagenotsupported"), String.Join(", ", unavailableLanguages)));
            return(false);
        }

        return(true);
    }
    /// <summary>
    /// Prepares translation settings.
    /// </summary>
    private TranslationSettings PrepareTranslationSettings()
    {
        var settings = new TranslationSettings
        {
            TranslateWebpartProperties = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSTranslateWebpartProperties"),
            SourceLanguage = translationElem.FromLanguage,
            Instructions = translationElem.Instructions,
            Priority = translationElem.Priority,
            TranslateAttachments = translationElem.ProcessBinary,
            ProcessBinary = translationElem.ProcessBinary,
            TranslationDeadline = translationElem.Deadline,
            TranslationServiceName = translationElem.SelectedService
        };
        settings.TargetLanguages.AddRange(targetCultures);

        return settings;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script files
        ScriptHelper.RegisterCMS(this);
        ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js");

        if (!QueryHelper.ValidateHash("hash"))
        {
            pnlContent.Visible = false;
            ShowError(GetString("dialogs.badhashtext"));
            return;
        }

        // Setup page title text and image
        PageTitle.TitleText = GetString("Content.TranslateTitle");
        EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText);

        if (IsDialog)
        {
            RegisterModalPageScripts();
            RegisterEscScript();

            plcInfo.Visible = false;

            pnlButtons.Visible = false;
        }

        if (!TranslationServiceHelper.IsTranslationAllowed(CurrentSiteName))
        {
            pnlContent.Visible = false;
            ShowError(GetString("translations.translationnotallowed"));
            return;
        }

        // Initialize current user
        currentUser = MembershipContext.AuthenticatedUser;
        // Initialize current site
        currentSite = SiteContext.CurrentSite;

        // Initialize events
        ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished;
        ctlAsyncLog.OnError += ctlAsyncLog_OnError;
        ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel;

        isSelect = QueryHelper.GetBoolean("select", false);
        if (isSelect)
        {
            pnlDocList.Visible = false;
            pnlDocSelector.Visible = true;
            translationElem.DisplayMachineServices = false;
        }

        var displayTargetLanguage = !IsDialog || isSelect;
        translationElem.DisplayTargetlanguage = displayTargetLanguage;

        // Get target culture(s)
        targetCultures = displayTargetLanguage ? translationElem.TargetLanguages : new HashSet<string>(new[] { QueryHelper.GetString("targetculture", currentCulture) });

        // Set the target settings
        var settings = new TranslationSettings();
        settings.TargetLanguages.AddRange(targetCultures);

        var useCurrentAsDefault = QueryHelper.GetBoolean("currentastargetdefault", false);
        if (!currentUser.IsGlobalAdministrator && currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(currentCulture, SiteContext.CurrentSiteName))
        {
            // Do not use current culture as default if user has no permissions to edit it
            useCurrentAsDefault = false;
        }

        translationElem.UseCurrentCultureAsDefaultTarget = useCurrentAsDefault;

        // Do not include default culture if it is current one
        if (useCurrentAsDefault && !currentCulture.EqualsCSafe(defaultCulture, true) && !RequestHelper.IsPostBack())
        {
            settings.TargetLanguages.Add(currentCulture);
        }

        translationElem.TranslationSettings = settings;
        allowTranslate = true;

        if (RequestHelper.IsCallback())
        {
            return;
        }

        // If not in select mode, load all the document IDs and check permissions
        // In select mode, documents are checked when the button is clicked
        if (!isSelect)
        {
            DataSet allDocs = null;
            TreeProvider tree = new TreeProvider();

            // Current Node ID to translate
            string parentAliasPath = string.Empty;
            if (Parameters != null)
            {
                parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty);
                nodeIdsArr = ValidationHelper.GetString(Parameters["nodeids"], string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            }

            if (string.IsNullOrEmpty(parentAliasPath))
            {
                if (nodeIdsArr == null)
                {
                    // One document translation is requested
                    string nodeIdQuery = QueryHelper.GetString("nodeid", "");
                    if (nodeIdQuery != "")
                    {
                        // Mode of single node translation
                        pnlList.Visible = false;
                        chkSkipTranslated.Checked = false;

                        translationElem.NodeID = ValidationHelper.GetInteger(nodeIdQuery, 0);

                        nodeIdsArr = new[] { nodeIdQuery };
                    }
                    else
                    {
                        nodeIdsArr = new string[] { };
                    }
                }

                foreach (string nodeId in nodeIdsArr)
                {
                    int id = ValidationHelper.GetInteger(nodeId, 0);
                    if (id != 0)
                    {
                        nodeIds.Add(id);
                    }
                }
            }
            else
            {
                // Exclude root of the website from multiple translation requested by document listing bulk action
                var where = new WhereCondition(WhereCondition)
                    .WhereNotEquals("ClassName", SystemDocumentTypes.Root);

                allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%",
                    TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where.ToString(true),
                    "DocumentName", AllLevels ? TreeProvider.ALL_LEVELS : 1, false, 0,
                    DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath");

                if (!DataHelper.DataSourceIsEmpty(allDocs))
                {
                    foreach (DataTable table in allDocs.Tables)
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0));
                        }
                    }
                }
            }

            if (nodeIds.Count > 0)
            {
                var where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true);
                DataSet ds = allDocs ?? tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", TreeProvider.ALL_LEVELS, false);

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    string docList = null;

                    cancelNodeId = string.IsNullOrEmpty(parentAliasPath)
                        ? DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID")
                        : TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath);

                    foreach (DataTable table in ds.Tables)
                    {
                        foreach (DataRow dr in table.Rows)
                        {
                            bool isLink = (dr["NodeLinkedNodeID"] != DBNull.Value);
                            string name = (string)dr["DocumentName"];
                            docList += HTMLHelper.HTMLEncode(name);
                            if (isLink)
                            {
                                docList += DocumentUIHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link);
                            }
                            docList += "<br />";
                            lblDocuments.Text = docList;

                            // Set visibility of checkboxes
                            TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr);

                            if (!TranslationServiceHelper.IsAuthorizedToTranslateDocument(node, currentUser, targetCultures))
                            {
                                allowTranslate = false;

                                plcMessages.AddError(String.Format(GetString("cmsdesk.notauthorizedtotranslatedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)));
                            }
                        }
                    }

                    if (!allowTranslate && !RequestHelper.IsPostBack())
                    {
                        // Hide UI only when security check is performed within first load, if postback used user may loose some setting
                        HideUI();
                    }
                }

                // Display check box for separate submissions for each document if there is more than one document
                translationElem.DisplaySeparateSubmissionOption = (nodeIds.Count > 1);
            }
            else
            {
                // Hide everything
                pnlContent.Visible = false;
            }
        }

        // Register the dialog script
        ScriptHelper.RegisterDialogScript(this);

        ctlAsyncLog.TitleText = GetString("contentrequest.starttranslate");
        // Set visibility of panels
        pnlContent.Visible = true;
        pnlLog.Visible = false;
    }
    /// <summary>
    /// Translates document(s).
    /// </summary>
    private void Translate(object parameter)
    {
        if (parameter == null || nodeIds.Count < 1)
        {
            return;
        }

        int refreshId = 0;

        TreeProvider tree = new TreeProvider(currentUser);
        tree.AllowAsyncActions = false;

        try
        {
            // Begin log
            AddLog(ResHelper.GetString("contentrequest.starttranslate", currentCulture));

            bool oneSubmission = chkSeparateSubmissions.Checked;

            // Prepare translation settings
            TranslationSettings settings = new TranslationSettings();
            settings.TargetLanguage = targetCulture;
            settings.TranslateWebpartProperties = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSTranslateWebpartProperties");
            settings.SourceLanguage = translationElem.FromLanguage;
            settings.Instructions = translationElem.Instructions;
            settings.Priority = translationElem.Priority;
            settings.TranslateAttachments = translationElem.ProcessBinary;
            settings.ProcessBinary = translationElem.ProcessBinary;
            settings.TranslationDeadline = translationElem.Deadline;
            settings.TranslationServiceName = translationElem.SelectedService;

            using (CMSTransactionScope tr = new CMSTransactionScope())
            {
                // Get the translation provider
                AbstractMachineTranslationService machineService = null;
                AbstractHumanTranslationService humanService = null;
                TranslationSubmissionInfo submission = null;
                TranslationServiceInfo ti = TranslationServiceInfoProvider.GetTranslationServiceInfo(translationElem.SelectedService);
                if (ti != null)
                {
                    if (oneSubmission)
                    {
                        if (ti.TranslationServiceIsMachine)
                        {
                            machineService = AbstractMachineTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                        else
                        {
                            humanService = AbstractHumanTranslationService.GetTranslationService(ti, CurrentSiteName);

                            if (oneSubmission)
                            {
                                submission = TranslationServiceHelper.CreateSubmissionInfo(settings, ti, CMSContext.CurrentUser.UserID, CMSContext.CurrentSiteID, "Document submission " + DateTime.Now);
                            }
                        }
                    }

                    bool langSupported = true;
                    if (humanService != null)
                    {
                        if (!humanService.IsLanguageSupported(settings.TargetLanguage))
                        {
                            AddError(ResHelper.GetString("translationservice.targetlanguagenotsupported"));
                            langSupported = false;
                        }
                    }

                    if (langSupported)
                    {
                        if (!oneSubmission || (machineService != null) || (humanService != null))
                        {
                            // Prepare the where condition
                            string where = SqlHelperClass.GetWhereCondition("NodeID", (int[])nodeIds.ToArray(typeof(int)));
                            string columns = "NodeID, NodeAliasPath, DocumentCulture, NodeParentID";

                            string submissionFileName = "";
                            string submissionName = "";
                            int charCount = 0;
                            int wordCount = 0;

                            int docCount = 0;

                            // Get the documents in target culture to be able to check if "Skip already translated" option is on
                            // Combine both, source and target culture (at least one hit has to be found - to find the source of translation)
                            where = SqlHelperClass.AddWhereCondition(where, "DocumentCulture = N'" + settings.SourceLanguage + "' OR DocumentCulture = N'" + settings.TargetLanguage + "'");

                            DataSet ds = tree.SelectNodes(CMSContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns);
                            if (!DataHelper.DataSourceIsEmpty(ds))
                            {
                                List<int> processedNodes = new List<int>();

                                // Translate the documents
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    refreshId = ValidationHelper.GetInteger(dr["NodeParentID"], 0);
                                    int nodeId = ValidationHelper.GetInteger(dr["NodeID"], 0);

                                    if (!processedNodes.Contains(nodeId))
                                    {
                                        processedNodes.Add(nodeId);

                                        string aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], "");
                                        string culture = ValidationHelper.GetString(dr["DocumentCulture"], "");

                                        if (chkSkipTranslated.Checked)
                                        {
                                            if (culture == settings.TargetLanguage)
                                            {
                                                // Document already exists in requested culture, skip it
                                                AddLog(string.Format(ResHelper.GetString("content.translatedalready"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));
                                                continue;
                                            }
                                        }

                                        AddLog(string.Format(ResHelper.GetString("content.translating"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));

                                        TreeNode node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, true, null);

                                        // Save the first document as a base for submission name
                                        if (string.IsNullOrEmpty(submissionName))
                                        {
                                            submissionName = node.GetDocumentName();
                                        }
                                        if (string.IsNullOrEmpty(submissionFileName))
                                        {
                                            submissionFileName = node.NodeAlias;
                                        }

                                        docCount++;

                                        // Submit the document
                                        if (machineService != null)
                                        {
                                            TranslationServiceHelper.Translate(machineService, settings, node);
                                        }
                                        else
                                        {
                                            if (oneSubmission && (humanService != null))
                                            {
                                                TreeNode targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, settings.TargetLanguage, true, false);
                                                TranslationSubmissionItemInfo submissionItem = TranslationServiceHelper.CreateSubmissionItemInfo(settings, submission, node, targetNode.DocumentID);

                                                charCount += submissionItem.SubmissionItemCharCount;
                                                wordCount += submissionItem.SubmissionItemWordCount;
                                            }
                                            else
                                            {
                                                TranslationServiceHelper.SubmitToTranslation(settings, node, out submission);
                                            }
                                        }
                                    }
                                }

                                if (docCount > 0)
                                {
                                    if (oneSubmission && (humanService != null))
                                    {
                                        AddLog(ResHelper.GetString("content.submitingtranslation"));

                                        // Set submission name
                                        int itemCount = processedNodes.Count;
                                        if (itemCount > 1)
                                        {
                                            submissionName += " " + string.Format(GetString("translationservices.submissionnamesuffix"), itemCount - 1);
                                        }
                                        submission.SubmissionName = submissionName;
                                        submission.SubmissionCharCount = charCount;
                                        submission.SubmissionWordCount = wordCount;
                                        submission.SubmissionItemCount = itemCount;
                                        submission.SubmissionParameter = submissionFileName;

                                        string err = humanService.CreateSubmission(submission);
                                        if (!string.IsNullOrEmpty(err))
                                        {
                                            AddError(err);
                                        }

                                        // Save submission with ticket
                                        TranslationSubmissionInfoProvider.SetTranslationSubmissionInfo(submission);
                                    }
                                }
                                else
                                {
                                    TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                    AddError(ResHelper.GetString("TranslateDocument.DocumentsAlreadyTranslated", currentCulture));
                                }
                            }
                        }
                        else
                        {
                            AddError(ResHelper.GetString("TranslateDocument.TranslationServiceNotFound", currentCulture));
                        }
                    }
                }

                tr.Commit();
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                AddError(ResHelper.GetString("TranslateDocument.TranslationCanceled", currentCulture));
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
        finally
        {
            if (isModal)
            {
                ctlAsync.Parameter = "wopener.location.replace(wopener.location); CloseDialog();";
            }
            else
            {
                if (string.IsNullOrEmpty(CurrentError))
                {
                    // Refresh tree
                    ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    ctlAsync.Parameter = "RefreshTree(null, null);";
                }
            }
        }
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        EnsureScripts();

        radCopy.Text = GetString("ContentNewCultureVersion.Copy");
        radEmpty.Text = GetString("ContentNewCultureVersion.Empty");
        radTranslate.Text = GetString("ContentNewCultureVersion.Translate");

        radCopy.Attributes.Add("onclick", "ShowSelection();");
        radEmpty.Attributes.Add("onclick", "ShowSelection()");
        radTranslate.Attributes.Add("onclick", "ShowSelection()");

        btnCreateDocument.Text = GetString("ContentNewCultureVersion.Create");
        btnTranslate.Text = GetString("ContentNewCultureVersion.TranslateButton");
        btnTranslate.Click += btnTranslate_Click;
        btnCreateDocument.Click += btnCreateDocument_Click;

        if ((NodeID <= 0) || (Node == null))
        {
            return;
        }

        // Fill in the existing culture versions
        bool translationAllowed = SettingsKeyInfoProvider.GetBoolValue(Node.NodeSiteName + ".CMSEnableTranslations") && LicenseHelper.IsFeatureAvailableInUI(FeatureEnum.TranslationServices, ModuleName.TRANSLATIONSERVICES);
        if (translationAllowed)
        {
            var settings = new TranslationSettings();
            settings.TargetLanguages.Add(RequiredCulture);
            translationElem.TranslationSettings = settings;

            translationElem.NodeID = Node.NodeID;
        }
        else
        {
            translationElem.StopProcessing = true;
            plcTranslationServices.Visible = false;
        }

        if (!MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(Node.NodeParentID, Node.NodeClassName))
        {
            pnlNewVersion.Visible = false;
            headNewCultureVersion.Visible = false;
            ShowError(GetString("accessdenied.notallowedtocreatenewcultureversion"));
        }
        else
        {
            SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID);
            if (si == null)
            {
                return;
            }

            TreeNode originalNode = Tree.GetOriginalNode(Node);
            copyCulturesElem.UniSelector.DisplayNameFormat = "{% CultureName %}{% if (CultureCode == \"" + CultureHelper.GetDefaultCultureCode(si.SiteName) + "\") { \" \" +\"" + GetString("general.defaultchoice") + "\" } %}";
            copyCulturesElem.AdditionalWhereCondition = "CultureCode IN (SELECT DocumentCulture FROM CMS_Document WHERE DocumentNodeID = " + originalNode.NodeID + ")";

            if (!MembershipContext.AuthenticatedUser.IsCultureAllowed(RequiredCulture, si.SiteName))
            {
                pnlNewVersion.Visible = false;
                headNewCultureVersion.Visible = false;
                ShowError(GetString("transman.notallowedcreate"));
            }
        }
    }