view Translatable/ControlTranslator.cs @ 23:ae37467335ae

Re #47: Add translatable GTK# widgets * Handle tool buttons, assuming that they're shown as icons and need a tooltip for text * Translate actions before contained widgets (where they exist) on the assumption that some widgets (e.g. menus and buttons) may want to use the action text
author IBBoard <dev@ibboard.co.uk>
date Tue, 28 Dec 2010 20:18:46 +0000
parents edae1d817962
children 63919afde887
line wrap: on
line source

//  This file (ControlTranslator.cs) is a part of the IBBoard.GtkSharp project and is copyright 2010 IBBoard
// 
// // The file and the library/program it is in are licensed and distributed, without warranty, under the GNU LGPL license, either version 3 of the License or (at your option) any later version. Please see COPYING for more information and the full license.

using System;
using Gtk;
using IBBoard.Lang;

namespace IBBoard.GtkSharp.Translatable
{
	/// <summary>
	/// A custom cascading translator. It takes any widget type and translates them if they implement <see>ITranslatable</see>
	/// and optionally cascades the process to translate all children.
	/// </summary>
	public class ControlTranslator
	{
		public static void TranslateWidget(Widget toTranslate)
		{
			TranslateWidget(toTranslate, true);
		}

		public static void TranslateWidget(Widget toTranslate, bool cascade)
		{
			if (toTranslate is ITranslatable)
			{
				Translation.Translate((ITranslatable)toTranslate);
			}
			else if (toTranslate is MenuItem)
			{
				TranslateAction(((MenuItem)toTranslate).Action);
			}
			else if (toTranslate is ToolButton)
			{
				ToolButton toolButton = ((ToolButton)toTranslate);
				TranslateToolButton(toolButton);
			}

			if (cascade && toTranslate is Container)
			{
				CascadeTranslations((Container)toTranslate, cascade);
			}
		}

		private static void TranslateToolButton(ToolButton toolButton)
		{
			Action action = toolButton.Action;
			string translation = Translation.GetTranslation(toolButton.Name, "");

			if (translation == "")
			{
				toolButton.TooltipText = action.Label;
			}
			else
			{
				toolButton.TooltipText = translation;
			}
		}

		private static void CascadeTranslations(Container container, bool cascade)
		{
			if (container is ITranslatableWithActions)
			{
				TranslateActions((ITranslatableWithActions)container);
			}

			foreach (Widget childWidget in container.AllChildren)
			{
				TranslateWidget(childWidget, cascade);
			}
		}

		private static void TranslateActions(ITranslatableWithActions actionContainer)
		{
			foreach (Action action in actionContainer.Actions)
			{
				TranslateAction(action);
			}
		}

		private static void TranslateAction(Action action)
		{
			action.Label = Translation.GetTranslation(action.Name, action.Label);
		}
	}
}