Example #1
0
    def __init__(self, mainmenu):
        self.mainmenu = mainmenu
        self.widgets = mainmenu.widgets

        self.keyconf = KeyConfig()  # before _build_strings
        self.HELPSTRING_LAYOUT = None
        self._build_strings()
        self._is_displayed = False

        LanguageChanged.subscribe(lambda msg: self._build_strings())
Example #2
0
def change_language(language=None):
    """Load/change the language of Unknown Horizons.

	Called on startup and when changing the language in the settings menu.
	"""

    if language:  # non-default
        try:
            # NOTE about gettext fallback mechanism:
            # English is not shipped as .mo file, thus if English is
            # selected we use NullTranslations to get English output.
            fallback = (language == 'en')
            trans = gettext.translation('unknown-horizons',
                                        find_available_languages()[language],
                                        languages=[language],
                                        fallback=fallback)
            trans.install(unicode=True, names=[
                'ngettext',
            ])
        except (IOError, KeyError, ValueError) as err:
            # KeyError can happen with a settings file written to by more than one UH
            # installation (one that has compiled language files and one that hasn't)
            # ValueError can be raised by gettext if for instance the plural forms are
            # corrupted.
            log.warning("Configured language %s could not be loaded.",
                        language)
            log.warning("Error: %s", err)
            log.warning("Continuing with English as fallback.")
            horizons.globals.fife.set_uh_setting('Language', LANGUAGENAMES[''])
            return change_language()  # recurse
    else:
        # default locale
        if platform.system(
        ) == "Windows":  # win doesn't set the language variable by default
            os.environ['LANGUAGE'] = locale.getdefaultlocale()[0]
        gettext.install('unknown-horizons',
                        'content/lang',
                        unicode=True,
                        names=[
                            'ngettext',
                        ])

    # expose the plural-aware translate function as builtin N_ (gettext does the same to _)
    import __builtin__
    __builtin__.__dict__['N_'] = __builtin__.__dict__['ngettext']

    # update fonts
    new_locale = language or horizons.globals.fife.get_locale()
    fontdef = get_fontdef_for_locale(new_locale)
    horizons.globals.fife.pychan.loadFonts(fontdef)

    # dynamically reset all translations of active widgets
    update_all_translations()
    LanguageChanged.broadcast(None)
Example #3
0
    def __init__(self, mainmenu):
        self.mainmenu = mainmenu
        self.widgets = mainmenu.widgets

        #i18n this defines how each line in our help looks like. Default: '[C] = Chat'
        self.HELPSTRING_LAYOUT = _('[{key}] = {text}')  #xgettext:python-format

        self.keyconf = KeyConfig()  # before _build_strings
        self._build_strings()
        self._is_displayed = False

        LanguageChanged.subscribe(lambda msg: self._build_strings())
Example #4
0
	def __init__(self, mainmenu):
		self.mainmenu = mainmenu
		self.widgets = mainmenu.widgets

		#i18n this defines how each line in our help looks like. Default: '[C] = Chat'
		self.HELPSTRING_LAYOUT = _('[{key}] = {text}') #xgettext:python-format

		self.keyconf = KeyConfig() # before _build_strings
		self._build_strings()
		self._is_displayed = False

		LanguageChanged.subscribe(lambda msg: self._build_strings())
Example #5
0
	def __init__(self, windows, session=None):
		super(HelpDialog, self).__init__(windows)

		self._session = session
		self.widget = load_uh_widget('help.xml')

		self.keyconf = KeyConfig() # before _build_strings
		self.HELPSTRING_LAYOUT = None
		self._build_strings()
		self._is_displayed = False

		self.widget.findChild(name=OkButton.DEFAULT_NAME).capture(self._windows.close)

		LanguageChanged.subscribe(lambda msg: self._build_strings())
Example #6
0
	def __init__(self, windows, session=None):
		super(HelpDialog, self).__init__(windows)

		self._session = session
		self.widget = load_uh_widget('help.xml')

		self.keyconf = KeyConfig() # before _build_strings
		self.HELPSTRING_LAYOUT = None
		self._build_strings()
		self._is_displayed = False

		self.widget.findChild(name=OkButton.DEFAULT_NAME).capture(self._windows.close)

		LanguageChanged.subscribe(lambda msg: self._build_strings())
Example #7
0
def change_language(language=None):
	"""Load/change the language of Unknown Horizons.

	Called on startup and when changing the language in the settings menu.
	"""

	if language: # non-default
		try:
			# NOTE about gettext fallback mechanism:
			# English is not shipped as .mo file, thus if English is
			# selected we use NullTranslations to get English output.
			fallback = (language == 'en')
			trans = gettext.translation('unknown-horizons', find_available_languages()[language],
			                            languages=[language], fallback=fallback)
			trans.install(unicode=True, names=['ngettext',])
		except (IOError, KeyError, ValueError) as err:
			# KeyError can happen with a settings file written to by more than one UH
			# installation (one that has compiled language files and one that hasn't)
			# ValueError can be raised by gettext if for instance the plural forms are
			# corrupted.
			log.warning("Configured language %s could not be loaded.", language)
			log.warning("Error: %s", err)
			log.warning("Continuing with English as fallback.")
			horizons.globals.fife.set_uh_setting('Language', LANGUAGENAMES[''])
			return change_language() # recurse
	else:
		# default locale
		if platform.system() == "Windows": # win doesn't set the language variable by default
			os.environ['LANGUAGE'] = locale.getdefaultlocale()[0]
		gettext.install('unknown-horizons', 'content/lang', unicode=True, names=['ngettext',])

	# expose the plural-aware translate function as builtin N_ (gettext does the same to _)
	import __builtin__
	__builtin__.__dict__['N_'] = __builtin__.__dict__['ngettext']

	# update fonts
	new_locale = language or horizons.globals.fife.get_locale()
	fontdef = get_fontdef_for_locale(new_locale)
	horizons.globals.fife.pychan.loadFonts(fontdef)

	# dynamically reset all translations of active widgets
	update_all_translations()
	LanguageChanged.broadcast(None)
Example #8
0
        setattr(widget, attribute, text)
    else:
        log.warning("Could not replace attribute %s in widget %s", attribute,
                    widget)


def update_translations(message):
    global translated_widgets
    translations.set_translations()

    for (filename, widget) in translated_widgets.iteritems():
        widget = widget()  # resolve weakref
        if not widget:
            continue
        all_widgets = translations.text_translations.get(filename, {})
        for (element_name, attribute), translation in all_widgets.iteritems():
            element = widget.findChild(name=element_name)
            if element is None:
                # something hidden by pychan currently, we cannot find it
                log.debug(
                    'Could not find element `%s` in widget `%s` - '
                    'assuming it is hidden', element_name, widget)
                continue
            replace_attribute(element, attribute, translation)
            #NOTE pychan + reloading font = ???
            element.font = element.font
        widget.adaptLayout()


LanguageChanged.subscribe(update_translations)
Example #9
0
    def __init__(self, session):
        super().__init__()
        self.session = session
        assert isinstance(self.session, horizons.session.Session)
        self.settlement = None
        self._old_menu = None

        self.cursor = None
        self.coordinates_tooltip = None

        self.keylistener = IngameKeyListener(self.session)

        self.cityinfo = CityInfo(self)
        LastActivePlayerSettlementManager.create_instance(self.session)

        self.message_widget = MessageWidget(self.session)

        # Windows
        self.windows = WindowManager()
        self.open_popup = self.windows.open_popup
        self.open_error_popup = self.windows.open_error_popup

        self.logbook = LogBook(self.session, self.windows)
        self.players_overview = PlayersOverview(self.session)
        self.players_settlements = PlayersSettlements(self.session)
        self.players_ships = PlayersShips(self.session)

        self.chat_dialog = ChatDialog(self.windows, self.session)
        self.change_name_dialog = ChangeNameDialog(self.windows, self.session)
        self.pausemenu = PauseMenu(self.session,
                                   self,
                                   self.windows,
                                   in_editor_mode=False)
        self.help_dialog = HelpDialog(self.windows)

        # Icon manager
        self.status_icon_manager = StatusIconManager(
            renderer=self.session.view.renderer['GenericRenderer'],
            layer=self.session.view.layers[LAYERS.OBJECTS])
        self.production_finished_icon_manager = ProductionFinishedIconManager(
            renderer=self.session.view.renderer['GenericRenderer'],
            layer=self.session.view.layers[LAYERS.OBJECTS])

        # 'minimap' is the guichan gui around the actual minimap, which is saved
        # in self.minimap
        self.mainhud = load_uh_widget('minimap.xml')
        self.mainhud.position_technique = "right:top"

        icon = self.mainhud.findChild(name="minimap")
        self.minimap = Minimap(
            icon,
            targetrenderer=horizons.globals.fife.targetrenderer,
            imagemanager=horizons.globals.fife.imagemanager,
            session=self.session,
            view=self.session.view)

        def speed_up():
            SpeedUpCommand().execute(self.session)

        def speed_down():
            SpeedDownCommand().execute(self.session)

        self.mainhud.mapEvents({
            'zoomIn':
            self.session.view.zoom_in,
            'zoomOut':
            self.session.view.zoom_out,
            'rotateRight':
            Callback.ChainedCallbacks(self.session.view.rotate_right,
                                      self.minimap.update_rotation),
            'rotateLeft':
            Callback.ChainedCallbacks(self.session.view.rotate_left,
                                      self.minimap.update_rotation),
            'speedUp':
            speed_up,
            'speedDown':
            speed_down,
            'destroy_tool':
            self.toggle_destroy_tool,
            'build':
            self.show_build_menu,
            'diplomacyButton':
            self.show_diplomacy_menu,
            'gameMenuButton':
            self.toggle_pause,
            'logbook':
            lambda: self.windows.toggle(self.logbook)
        })
        self.mainhud.show()

        self._replace_hotkeys_in_widgets()

        self.resource_overview = ResourceOverviewBar(self.session)

        # Register for messages
        SpeedChanged.subscribe(self._on_speed_changed)
        NewDisaster.subscribe(self._on_new_disaster)
        NewSettlement.subscribe(self._on_new_settlement)
        PlayerLevelUpgrade.subscribe(self._on_player_level_upgrade)
        MineEmpty.subscribe(self._on_mine_empty)
        ZoomChanged.subscribe(self._update_zoom)
        GuiAction.subscribe(self._on_gui_click_action)
        GuiHover.subscribe(self._on_gui_hover_action)
        GuiCancelAction.subscribe(self._on_gui_cancel_action)
        # NOTE: This has to be called after the text is replaced!
        LanguageChanged.subscribe(self._on_language_changed)

        self._display_speed(self.session.timer.ticks_per_second)
def replace_attribute(widget, attribute, text):
	if hasattr(widget, attribute):
		setattr(widget, attribute, text)
	else:
		log.warning("Could not replace attribute %s in widget %s", attribute, widget)


def update_translations(message):
	global translated_widgets
	translations.set_translations()

	for (filename, widget) in translated_widgets.items():
		widget = widget() # resolve weakref
		if not widget:
			continue
		all_widgets = translations.text_translations.get(filename, {})
		for (element_name, attribute), translation in all_widgets.items():
			element = widget.findChild(name=element_name)
			if element is None:
				# something hidden by pychan currently, we cannot find it
				log.debug('Could not find element `%s` in widget `%s` - '
				          'assuming it is hidden', element_name, widget)
				continue
			replace_attribute(element, attribute, translation)
			#NOTE pychan + reloading font = ???
			element.font = element.font
		widget.adaptLayout()


LanguageChanged.subscribe(update_translations)
Example #11
0
	def __init__(self, session):
		super(IngameGui, self).__init__()
		self.session = session
		assert isinstance(self.session, horizons.session.Session)
		self.settlement = None
		self._old_menu = None

		self.cursor = None
		self.coordinates_tooltip = None

		self.keylistener = IngameKeyListener(self.session)

		self.cityinfo = CityInfo(self)
		LastActivePlayerSettlementManager.create_instance(self.session)

		self.message_widget = MessageWidget(self.session)

		# Windows
		self.windows = WindowManager()
		self.open_popup = self.windows.open_popup
		self.open_error_popup = self.windows.open_error_popup

		self.logbook = LogBook(self.session, self.windows)
		self.players_overview = PlayersOverview(self.session)
		self.players_settlements = PlayersSettlements(self.session)
		self.players_ships = PlayersShips(self.session)

		self.chat_dialog = ChatDialog(self.windows, self.session)
		self.change_name_dialog = ChangeNameDialog(self.windows, self.session)
		self.pausemenu = PauseMenu(self.session, self, self.windows, in_editor_mode=False)
		self.help_dialog = HelpDialog(self.windows)

		# Icon manager
		self.status_icon_manager = StatusIconManager(
			renderer=self.session.view.renderer['GenericRenderer'],
			layer=self.session.view.layers[LAYERS.OBJECTS]
		)
		self.production_finished_icon_manager = ProductionFinishedIconManager(
			renderer=self.session.view.renderer['GenericRenderer'],
			layer=self.session.view.layers[LAYERS.OBJECTS]
		)

		# 'minimap' is the guichan gui around the actual minimap, which is saved
		# in self.minimap
		self.mainhud = load_uh_widget('minimap.xml')
		self.mainhud.position_technique = "right:top"

		icon = self.mainhud.findChild(name="minimap")
		self.minimap = Minimap(icon,
		                       targetrenderer=horizons.globals.fife.targetrenderer,
		                       imagemanager=horizons.globals.fife.imagemanager,
		                       session=self.session,
		                       view=self.session.view)

		def speed_up():
			SpeedUpCommand().execute(self.session)

		def speed_down():
			SpeedDownCommand().execute(self.session)

		self.mainhud.mapEvents({
			'zoomIn' : self.session.view.zoom_in,
			'zoomOut' : self.session.view.zoom_out,
			'rotateRight' : Callback.ChainedCallbacks(self.session.view.rotate_right, self.minimap.rotate_right),
			'rotateLeft' : Callback.ChainedCallbacks(self.session.view.rotate_left, self.minimap.rotate_left),
			'speedUp' : speed_up,
			'speedDown' : speed_down,
			'destroy_tool' : self.toggle_destroy_tool,
			'build' : self.show_build_menu,
			'diplomacyButton' : self.show_diplomacy_menu,
			'gameMenuButton' : self.toggle_pause,
			'logbook' : lambda: self.windows.toggle(self.logbook)
		})
		self.mainhud.show()

		self._replace_hotkeys_in_widgets()

		self.resource_overview = ResourceOverviewBar(self.session)

		# Register for messages
		SpeedChanged.subscribe(self._on_speed_changed)
		NewDisaster.subscribe(self._on_new_disaster)
		NewSettlement.subscribe(self._on_new_settlement)
		PlayerLevelUpgrade.subscribe(self._on_player_level_upgrade)
		MineEmpty.subscribe(self._on_mine_empty)
		ZoomChanged.subscribe(self._update_zoom)
		GuiAction.subscribe(self._on_gui_click_action)
		GuiHover.subscribe(self._on_gui_hover_action)
		GuiCancelAction.subscribe(self._on_gui_cancel_action)
		# NOTE: This has to be called after the text is replaced!
		LanguageChanged.subscribe(self._on_language_changed)

		self._display_speed(self.session.timer.ticks_per_second)