def __init__(self, color_palette=None):
		"""
		@param widgets: WidgetsDict
		"""
		self.gui = load_uh_widget('playerdataselection.xml')

		self.colors = self.gui.findChild(name='playercolor')
		self.selected_color = horizons.globals.fife.get_uh_setting("ColorID") # starts at 1!
		self.set_color(self.selected_color)

		colorlabels = []
		events = {}

		# need the id to save it as int in settings file.
		for color in (Color if color_palette is None else color_palette):
			label = Label(name = u'{color}'.format(color=color.name),
			              text = u"    ",
			              max_size = (20,20),
			              min_size = (20,20),
			              background_color = color)
			events['{label}/mouseClicked'.format(label=color.name)] = \
			                             Callback(self.set_color, color.id)
			colorlabels.append(label)

		# split into three rows with at max 5 entries in each row
		# right now there are 14 different colors to choose from.
		for i in xrange(0, len(colorlabels), 5):
			hbox = HBox(name='line_{index}'.format(index=i))
			hbox.addChildren(colorlabels[i:i+5])
			self.colors.addChild(hbox)

		self.gui.distributeData({
			'playername': unicode(horizons.globals.fife.get_uh_setting("Nickname")),
		})
		self.gui.mapEvents(events)
Esempio n. 2
0
	def show_tooltip(self):
		if not self.helptext:
			return
		if self.gui is None:
			self.__init_gui()

		#HACK: support icons in build menu
		# Code below exists for the sole purpose of build menu tooltips showing
		# resource icons. Even supporting that is a pain (as you will see),
		# so if you think you need icons in other tooltips, maybe reconsider.
		# [These unicode() calls brought to you by status icon tooltip code.]
		buildmenu_icons = self.icon_regexp.findall(unicode(self.helptext))
		# Remove the weird stuff before displaying text.
		replaced = self.icon_regexp.sub('', unicode(self.helptext))
		# Specification looks like [[Buildmenu 1:250 4:2 6:2]]
		if buildmenu_icons:
			hbox = HBox(position=(7, 5), padding=0)
			for spec in buildmenu_icons[0].split():
				(res_id, amount) = spec.split(':')
				label = Label(text=amount+'  ')
				icon = Icon(image=get_res_icon_path(int(res_id)), size=(16, 16),
				            scale=True)
				# For compatibility with FIFE 0.3.5 and older, also set min/max.
				icon.max_size = icon.min_size = (16, 16)
				hbox.addChildren(icon, label)
			hbox.adaptLayout()
			# Now display the 16x16px "required resources" icons in the last line.
			self.gui.addChild(hbox)

		#HACK: wrap tooltip text
		# This looks better than splitting into several lines and joining them.
		# It works because replace_whitespace in `fill` defaults to True.
		replaced = replaced.replace(r'\n', self.CHARS_PER_LINE * ' ')
		replaced = replaced.replace('[br]', self.CHARS_PER_LINE * ' ')
		tooltip = textwrap.fill(replaced, self.CHARS_PER_LINE)

		# Finish up the actual tooltip (text, background panel amount, layout).
		# To display build menu icons, we need another empty (first) line.
		self.bg.amount = len(tooltip.splitlines()) - 1 + bool(buildmenu_icons)
		self.label.text = bool(buildmenu_icons) * '\n' + tooltip
		self.gui.adaptLayout()
		self.gui.show()

		# NOTE: the below code in this method is a hack to resolve #2227
		# cannot find a better way to fix it, cause in fife.pychan, it seems
		# if a widget gets hidden or removed, the children of that widget are not
		# hidden or removed properly (at least in Python code)

		# update topmost_widget every time the tooltip is shown
		# this is to dismiss the tooltip later, see _check_hover_alive
		target_widget = self
		while target_widget:
			self.topmost_widget = target_widget
			target_widget = target_widget.parent

		# add an event to constantly check whether the hovered widget is still there
		# if this is no longer there, dismiss the tooltip widget
		ExtScheduler().add_new_object(self._check_hover_alive, self, run_in=0.5, loops=-1)
Esempio n. 3
0
 def createStatisticList(self, statistics):
     statistics_list = self.gui.findChild(name='statisticsList')
     # Start with an empty list.
     statistics_list.removeAllChildren()
     for statistic in statistics:
         name = statistic.long_name
         hbox = HBox()
         hbox.opaque = 0
         label = Label(text=name)
         spinner = IntSpinner(lower_limit=0, upper_limit=100)
         hbox.addChildren(label, spinner)
         statistics_list.addChildren(hbox)
 def update_needed_resources(self, needed_res_container):
     """ Update needed resources """
     production = self.producer.get_productions()[0]
     needed_res = production.get_consumed_resources()
     # Now sort! -amount is the positive value, drop unnecessary res (amount 0)
     needed_res = dict((res, -amount) for res, amount in needed_res.iteritems() if amount < 0)
     needed_res = sorted(needed_res.iteritems(), key=itemgetter(1), reverse=True)
     needed_res_container.removeAllChildren()
     for i, (res, amount) in enumerate(needed_res):
         icon = create_resource_icon(res, self.instance.session.db)
         icon.max_size = icon.min_size = icon.size = (16, 16)
         label = Label(name="needed_res_lbl_%s" % i)
         label.text = u"{amount}t".format(amount=amount)
         new_hbox = HBox(name="needed_res_box_%s" % i)
         new_hbox.addChildren(icon, label)
         needed_res_container.addChild(new_hbox)
Esempio n. 5
0
	def update_needed_resources(self, needed_res_container):
		""" Update needed resources """
		production = self.producer.get_productions()[0]
		needed_res = production.get_consumed_resources()
		# Now sort! -amount is the positive value, drop unnecessary res (amount 0)
		needed_res = dict((res, -amount) for res, amount in needed_res.items() if amount < 0)
		needed_res = sorted(needed_res.items(), key=itemgetter(1), reverse=True)
		needed_res_container.removeAllChildren()
		for i, (res, amount) in enumerate(needed_res):
			icon = create_resource_icon(res, self.instance.session.db)
			icon.max_size = icon.min_size = icon.size = (16, 16)
			label = Label(name="needed_res_lbl_%s" % i)
			label.text = '{amount}t'.format(amount=amount)
			new_hbox = HBox(name="needed_res_box_%s" % i)
			new_hbox.addChildren(icon, label)
			needed_res_container.addChild(new_hbox)
Esempio n. 6
0
	def show_tooltip(self):
		if self.shown is True:
			return
		self.shown = True

		if not self.helptext:
			return
		if self.gui is None:
			self.__init_gui()

		#HACK: support icons in build menu
		# Code below exists for the sole purpose of build menu tooltips showing
		# resource icons. Even supporting that is a pain (as you will see),
		# so if you think you need icons in other tooltips, maybe reconsider.
		# [These unicode() calls brought to you by status icon tooltip code.]
		buildmenu_icons = self.icon_regexp.findall(unicode(self.helptext))
		# Remove the weird stuff before displaying text.
		replaced = self.icon_regexp.sub('', unicode(self.helptext))
		# Specification looks like [[Buildmenu 1:250 4:2 6:2]]
		if buildmenu_icons:
			hbox = HBox(position=(7, 5), padding=0)
			for spec in buildmenu_icons[0].split():
				(res_id, amount) = spec.split(':')
				label = Label(text=amount+'  ')
				icon = Icon(image=get_res_icon_path(int(res_id)), size=(16, 16))
				# For compatibility with FIFE 0.3.5 and older, also set min/max.
				icon.max_size = icon.min_size = (16, 16)
				hbox.addChildren(icon, label)
			hbox.adaptLayout()
			# Now display the 16x16px "required resources" icons in the last line.
			self.gui.addChild(hbox)

		#HACK: wrap tooltip text
		# This looks better than splitting into several lines and joining them.
		# It works because replace_whitespace in `fill` defaults to True.
		replaced = replaced.replace(r'\n', self.CHARS_PER_LINE * ' ')
		replaced = replaced.replace('[br]', self.CHARS_PER_LINE * ' ')
		tooltip = textwrap.fill(replaced, self.CHARS_PER_LINE)

		# Finish up the actual tooltip (text, background panel amount, layout).
		# To display build menu icons, we need another empty (first) line.
		self.bg.amount = len(tooltip.splitlines()) - 1 + bool(buildmenu_icons)
		self.label.text = bool(buildmenu_icons) * '\n' + tooltip
		self.gui.adaptLayout()
		self.gui.show()
    def __init__(self, color_palette=None):
        """
		@param widgets: WidgetsDict
		"""
        self.gui = load_uh_widget("playerdataselection.xml")

        self.colors = self.gui.findChild(name="playercolor")
        self.selected_color = horizons.globals.fife.get_uh_setting("ColorID")  # starts at 1!
        self.set_color(self.selected_color)

        colorlabels = []
        events = {}

        # need the id to save it as int in settings file.
        for color in Color if color_palette is None else color_palette:
            label = Label(
                name=u"{color}".format(color=color.name),
                text=u"    ",
                max_size=(20, 20),
                min_size=(20, 20),
                background_color=color,
            )
            events["{label}/mouseClicked".format(label=color.name)] = Callback(self.set_color, color.id)
            colorlabels.append(label)

            # split into three rows with at max 5 entries in each row
            # right now there are 14 different colors to choose from.
        for i in xrange(0, len(colorlabels), 5):
            hbox = HBox(name="line_{index}".format(index=i))
            hbox.addChildren(colorlabels[i : i + 5])
            self.colors.addChild(hbox)

        playertextfield = self.gui.findChild(name="playername")

        def playertextfield_clicked():
            if playertextfield.text == "Unnamed Traveler":
                playertextfield.text = ""

        playertextfield.capture(playertextfield_clicked, event_name="mouseClicked")

        self.gui.distributeData({"playername": unicode(horizons.globals.fife.get_uh_setting("Nickname"))})
        self.gui.mapEvents(events)
Esempio n. 8
0
	def show_tooltip(self):
		if not self.helptext:
			return
		if self.gui is None:
			self.__init_gui()

		#HACK: support icons in build menu
		# Code below exists for the sole purpose of build menu tooltips showing
		# resource icons. Even supporting that is a pain (as you will see),
		# so if you think you need icons in other tooltips, maybe reconsider.
		# [These unicode() calls brought to you by status icon tooltip code.]
		buildmenu_icons = self.icon_regexp.findall(unicode(self.helptext))
		# Remove the weird stuff before displaying text.
		replaced = self.icon_regexp.sub('', unicode(self.helptext))
		# Specification looks like [[Buildmenu 1:250 4:2 6:2]]
		if buildmenu_icons:
			hbox = HBox(position=(7, 5), padding=0)
			for spec in buildmenu_icons[0].split():
				(res_id, amount) = spec.split(':')
				label = Label(text=amount+'  ')
				icon = Icon(image=get_res_icon_path(int(res_id)), size=(16, 16))
				# For compatibility with FIFE 0.3.5 and older, also set min/max.
				icon.max_size = icon.min_size = (16, 16)
				hbox.addChildren(icon, label)
			hbox.adaptLayout()
			# Now display the 16x16px "required resources" icons in the last line.
			self.gui.addChild(hbox)

		#HACK: wrap tooltip text
		# This looks better than splitting into several lines and joining them.
		# It works because replace_whitespace in `fill` defaults to True.
		replaced = replaced.replace(r'\n', self.CHARS_PER_LINE * ' ')
		replaced = replaced.replace('[br]', self.CHARS_PER_LINE * ' ')
		tooltip = textwrap.fill(replaced, self.CHARS_PER_LINE)

		# Finish up the actual tooltip (text, background panel amount, layout).
		# To display build menu icons, we need another empty (first) line.
		self.bg.amount = len(tooltip.splitlines()) - 1 + bool(buildmenu_icons)
		self.label.text = bool(buildmenu_icons) * '\n' + tooltip
		self.gui.adaptLayout()
		self.gui.show()
    def __init__(self, color_palette=None):
        """
		@param widgets: WidgetsDict
		"""
        self.gui = load_uh_widget('playerdataselection.xml')

        self.colors = self.gui.findChild(name='playercolor')

        colorlabels = []
        events = {}

        # need the id to save it as int in settings file.
        for color in (Color.get_defaults()
                      if color_palette is None else color_palette):
            label = Label(name='{color}'.format(color=color.name),
                          text="    ",
                          max_size=(20, 20),
                          min_size=(20, 20),
                          background_color=color)
            events['{label}/mouseClicked'.format(label=color.name)] = \
                                         Callback(self.set_color, color.id)
            colorlabels.append(label)

        # split into three rows with at max 5 entries in each row
        # right now there are 14 different colors to choose from.
        for i in range(0, len(colorlabels), 5):
            hbox = HBox(name='line_{index}'.format(index=i))
            hbox.addChildren(colorlabels[i:i + 5])
            self.colors.addChild(hbox)

        playertextfield = self.gui.findChild(name='playername')

        def playertextfield_clicked():
            if playertextfield.text == 'Unnamed Traveler':
                playertextfield.text = ""

        playertextfield.capture(playertextfield_clicked,
                                event_name='mouseClicked')

        self.gui.mapEvents(events)
        self.update_data()
        def _add_player_line(player):
            name = player['name']
            pname = Label(name="pname_%s" % name)
            pname.helptext = _("Click here to change your name and/or color")
            pname.text = name
            pname.min_size = pname.max_size = (130, 15)

            if name == NetworkInterface().get_client_name():
                pname.capture(
                    Callback(self._show_change_player_details_popup, game))

            pcolor = Label(name="pcolor_%s" % name, text=u"   ")
            pcolor.helptext = _("Click here to change your name and/or color")
            pcolor.background_color = player['color']
            pcolor.min_size = pcolor.max_size = (15, 15)

            if name == NetworkInterface().get_client_name():
                pcolor.capture(
                    Callback(self._show_change_player_details_popup, game))

            pstatus = Label(name="pstatus_%s" % name)
            pstatus.text = "\t\t\t" + player['status']
            pstatus.min_size = pstatus.max_size = (120, 15)

            picon = HRule(name="picon_%s" % name)

            hbox = HBox()
            hbox.addChildren(pname, pcolor, pstatus)

            if NetworkInterface().get_client_name(
            ) == game.creator and name != game.creator:
                pkick = CancelButton(name="pkick_%s" % name)
                pkick.helptext = _("Kick {player}").format(player=name)
                pkick.capture(Callback(NetworkInterface().kick, player['sid']))
                pkick.path = "images/buttons/delete_small"
                pkick.min_size = pkick.max_size = (20, 15)
                hbox.addChild(pkick)

            players_vbox.addChildren(hbox, picon)
Esempio n. 11
0
	def __init__(self, parent_gui, widgets, color_palette=None):
		"""
		Adds the playerdataselection container to a parent gui
		@param parent_gui: a pychan gui object containing a container named "playerdataselectioncontainer"
		@param widgets: WidgetsDict
		"""
		widgets.reload( 'playerdataselection' )
		self.gui = widgets[ 'playerdataselection' ]

		self.colors = self.gui.findChild(name='playercolor')
		self.selected_color = horizons.globals.fife.get_uh_setting("ColorID") # starts at 1!
		self.set_color(self.selected_color)

		colorlabels = []
		events = {}

		# need the id to save it as int in settings file.
		for color in (Color if color_palette is None else color_palette):
			label = Label(name = u'{color}'.format(color=color.name),
			              text = u"    ",
			              max_size = (20,20),
			              min_size = (20,20),
			              background_color = color)
			events['{label}/mouseClicked'.format(label=color.name)] = \
			                             Callback(self.set_color, color.id)
			colorlabels.append(label)

		# split into three rows with at max 5 entries in each row
		# right now there are 14 different colors to choose from.
		for i in xrange(0, len(colorlabels), 5):
			hbox = HBox(name='line_{index}'.format(index=i))
			hbox.addChildren(colorlabels[i:i+5])
			self.colors.addChild(hbox)

		self.gui.distributeData({
			'playername': unicode(horizons.globals.fife.get_uh_setting("Nickname")),
		})
		parent_gui.findChild(name="playerdataselectioncontainer").addChild( self.gui )
		parent_gui.mapEvents(events)
	def __init__(self, parent_gui, widgets):
		"""
		Adds the playerdataselection container to a parent gui
		@param parent_gui: a pychan gui object containing a container named "playerdataselectioncontainer"
		@param widgets: WidgetsDict
		"""
		widgets.reload( 'playerdataselection' )
		self.gui = widgets[ 'playerdataselection' ]

		self.colors = self.gui.findChild(name = 'playercolor')
		self.selected_color = horizons.main.fife.get_uh_setting("ColorID") # starts at 1!
		self._set_color(self.selected_color)

		colorlabels = []
		events = {}

		# need the id to save it as int in settings file.
		for color_id, color in enumerate(Color):
			label = Label(name = u'{color}'.format(color=color.name),
			              text = u"    ",
			              max_size = (20,20),
			              min_size = (20,20),
			              background_color = color)
			events['{label}/mouseClicked'.format(label=color.name)] = \
			                             Callback(self._set_color, color_id+1)
			colorlabels.append(label)

		# split into three rows with at max 5 entries in each row
		# right now there are 14 different colors to choose from.
		for i in xrange(0, len(colorlabels), 5):
			hbox = HBox(name='line_{index}'.format(index=i))
			hbox.addChildren(colorlabels[i:i+5])
			self.colors.addChild(hbox)

		self.gui.distributeData({
			'playername': unicode(horizons.main.fife.get_uh_setting("Nickname")),
		})
		parent_gui.findChild(name="playerdataselectioncontainer").addChild( self.gui )
		parent_gui.mapEvents(events)
	def __init__(self, color_palette=None):
		"""
		@param widgets: WidgetsDict
		"""
		self.gui = load_uh_widget('playerdataselection.xml')

		self.colors = self.gui.findChild(name='playercolor')

		colorlabels = []
		events = {}

		# need the id to save it as int in settings file.
		for color in (Color if color_palette is None else color_palette):
			label = Label(name = u'{color}'.format(color=color.name),
			              text = u"    ",
			              max_size = (20, 20),
			              min_size = (20, 20),
			              background_color = color)
			events['{label}/mouseClicked'.format(label=color.name)] = \
			                             Callback(self.set_color, color.id)
			colorlabels.append(label)

		# split into three rows with at max 5 entries in each row
		# right now there are 14 different colors to choose from.
		for i in xrange(0, len(colorlabels), 5):
			hbox = HBox(name='line_{index}'.format(index=i))
			hbox.addChildren(colorlabels[i:i+5])
			self.colors.addChild(hbox)
		
		playertextfield = self.gui.findChild(name='playername')
		def playertextfield_clicked():
			if playertextfield.text == 'Unnamed Traveler':
				playertextfield.text = "";
		playertextfield.capture(playertextfield_clicked, event_name='mouseClicked')
		
		self.gui.mapEvents(events)
		self.update_data()
Esempio n. 14
0
		def _add_player_line(player):
			name = player['name']
			pname = Label(name="pname_%s" % name)
			pname.helptext = _("Click here to change your name and/or color")
			pname.text = name
			pname.min_size = pname.max_size = (130, 15)

			if name == NetworkInterface().get_client_name():
				pname.capture(Callback(self._show_change_player_details_popup, game))

			pcolor = Label(name="pcolor_%s" % name, text=u"   ")
			pcolor.helptext = _("Click here to change your name and/or color")
			pcolor.background_color = player['color']
			pcolor.min_size = pcolor.max_size = (15, 15)

			if name == NetworkInterface().get_client_name():
				pcolor.capture(Callback(self._show_change_player_details_popup, game))

			pstatus = Label(name="pstatus_%s" % name)
			pstatus.text = "\t\t\t" + player['status']
			pstatus.min_size = pstatus.max_size = (120, 15)

			picon = HRule(name="picon_%s" % name)

			hbox = HBox()
			hbox.addChildren(pname, pcolor, pstatus)

			if NetworkInterface().get_client_name() == game.creator and name != game.creator:
				pkick = CancelButton(name="pkick_%s" % name)
				#xgettext:python-format
				pkick.helptext = _("Kick {player}").format(player=name)
				pkick.capture(Callback(NetworkInterface().kick, player['sid']))
				pkick.path = "images/buttons/delete_small"
				pkick.min_size = pkick.max_size = (20, 15)
				hbox.addChild(pkick)

			players_vbox.addChildren(hbox, picon)
    def refresh(self):
        """This function is called by the TabWidget to redraw the widget."""
        super(BoatbuilderTab, self).refresh()

        main_container = self.widget.findChild(name="BB_main_tab")
        container_active = main_container.findChild(name="container_active")
        container_inactive = main_container.findChild(
            name="container_inactive")
        progress_container = main_container.findChild(
            name="BB_progress_container")
        cancel_container = main_container.findChild(name="BB_cancel_container")
        needed_res_container = self.widget.findChild(
            name="BB_needed_resources_container")

        # a boatbuilder is considered active here if it builds sth, no matter if it's paused
        production_lines = self.producer.get_production_lines()

        if production_lines:
            cancel_container.parent.showChild(cancel_container)

            # Set progress
            progress_container.parent.showChild(progress_container)
            progress = math.floor(self.producer.get_production_progress() *
                                  100)
            self.widget.findChild(name='progress').progress = progress
            progress_perc = self.widget.findChild(name='BB_progress_perc')
            progress_perc.text = u'{progress}%'.format(progress=progress)

            container_active.parent.showChild(container_active)
            if (Fife.getVersion() >= (0, 4, 0)):
                container_inactive.parent.hideChild(container_inactive)
            else:
                if not container_inactive in container_inactive.parent.hidden_children:
                    container_inactive.parent.hideChild(container_inactive)

            # Update boatbuilder queue
            queue = self.producer.get_unit_production_queue()
            queue_container = container_active.findChild(
                name="queue_container")
            queue_container.removeAllChildren()
            for place_in_queue, unit_type in enumerate(queue):
                image = self.__class__.SHIP_THUMBNAIL.format(type_id=unit_type)
                helptext = _("{ship} (place in queue: {place})").format(
                    ship=self.instance.session.db.get_unit_type_name(
                        unit_type),
                    place=place_in_queue + 1)
                # people don't count properly, always starting at 1..
                icon_name = "queue_elem_" + str(place_in_queue)
                icon = Icon(name=icon_name, image=image, helptext=helptext)
                rm_from_queue_cb = Callback(
                    RemoveFromQueue(self.producer, place_in_queue).execute,
                    self.instance.session)
                icon.capture(rm_from_queue_cb, event_name="mouseClicked")
                queue_container.addChild(icon)

            # Set built ship info
            production_line = self.producer._get_production(
                production_lines[0])
            produced_unit_id = production_line.get_produced_units().keys()[0]

            name = self.instance.session.db.get_unit_type_name(
                produced_unit_id)

            container_active.findChild(
                name="headline_BB_builtship_label").text = _(name)
            ship_icon = container_active.findChild(name="BB_cur_ship_icon")
            ship_icon.helptext = self.instance.session.db.get_ship_tooltip(
                produced_unit_id)
            ship_icon.image = self.__class__.SHIP_PREVIEW_IMG.format(
                type_id=produced_unit_id)

            button_active = container_active.findChild(
                name="toggle_active_active")
            button_inactive = container_active.findChild(
                name="toggle_active_inactive")
            to_active = not self.producer.is_active()

            if not to_active:  # swap what we want to show and hide
                button_active, button_inactive = button_inactive, button_active
            if (Fife.getVersion() >= (0, 4, 0)):
                button_active.parent.hideChild(button_active)
            else:
                if not button_active in button_active.parent.hidden_children:
                    button_active.parent.hideChild(button_active)
            button_inactive.parent.showChild(button_inactive)

            set_active_cb = Callback(self.producer.set_active,
                                     active=to_active)
            button_inactive.capture(set_active_cb, event_name="mouseClicked")

            upgrades_box = container_active.findChild(name="BB_upgrades_box")
            upgrades_box.removeAllChildren()

            # Update needed resources
            production = self.producer.get_productions()[0]
            needed_res = production.get_consumed_resources()
            # Now sort! -amount is the positive value, drop unnecessary res (amount 0)
            needed_res = dict((res, -amount)
                              for res, amount in needed_res.iteritems()
                              if amount < 0)
            needed_res = sorted(needed_res.iteritems(),
                                key=itemgetter(1),
                                reverse=True)
            needed_res_container.removeAllChildren()
            for i, (res, amount) in enumerate(needed_res):
                icon = create_resource_icon(res, self.instance.session.db)
                icon.max_size = icon.min_size = icon.size = (16, 16)
                label = Label(name="needed_res_lbl_%s" % i)
                label.text = u'{amount}t'.format(amount=amount)
                new_hbox = HBox(name="needed_res_box_%s" % i)
                new_hbox.addChildren(icon, label)
                needed_res_container.addChild(new_hbox)

            cancel_button = self.widget.findChild(name="BB_cancel_button")
            cancel_cb = Callback(
                CancelCurrentProduction(self.producer).execute,
                self.instance.session)
            cancel_button.capture(cancel_cb, event_name="mouseClicked")

        else:  # display sth when nothing is produced
            container_inactive.parent.showChild(container_inactive)
            for w in (container_active, progress_container, cancel_container):
                if (Fife.getVersion() >= (0, 4, 0)):
                    w.parent.hideChild(w)
                else:
                    if not w in w.parent.hidden_children:
                        w.parent.hideChild(w)

        self.widget.adaptLayout()
Esempio n. 16
0
    def show_tooltip(self):
        if not self.helptext:
            return
        if self.gui is None:
            self.__init_gui()

        # Compare and reset timer value if difference from current time shorter than X sec.
        if (time.time() - self.cooldown) < 1:
            return
        else:
            self.cooldown = time.time()

        #HACK: support icons in build menu
        # Code below exists for the sole purpose of build menu tooltips showing
        # resource icons. Even supporting that is a pain (as you will see),
        # so if you think you need icons in other tooltips, maybe reconsider.
        # [These unicode() calls brought to you by status icon tooltip code.]
        buildmenu_icons = self.icon_regexp.findall(str(self.helptext))
        # Remove the weird stuff before displaying text.
        replaced = self.icon_regexp.sub('', str(self.helptext))
        # Specification looks like [[Buildmenu 1:250 4:2 6:2]]
        if buildmenu_icons:
            hbox = HBox(position=(7, 5))
            for spec in buildmenu_icons[0].split():
                (res_id, amount) = spec.split(':')
                label = Label(text=amount + '  ')
                icon = Icon(image=get_res_icon_path(int(res_id)),
                            size=(16, 16),
                            scale=True)
                hbox.addChildren(icon, label)
            hbox.adaptLayout()
            # Now display the 16x16px "required resources" icons in the last line.
            self.gui.addChild(hbox)

        #HACK: wrap tooltip text
        # This looks better than splitting into several lines and joining them.
        # It works because replace_whitespace in `fill` defaults to True.
        replaced = replaced.replace(r'\n', self.CHARS_PER_LINE * ' ')
        replaced = replaced.replace('[br]', self.CHARS_PER_LINE * ' ')
        tooltip = textwrap.fill(replaced, self.CHARS_PER_LINE)

        # Finish up the actual tooltip (text, background panel amount, layout).
        # To display build menu icons, we need another empty (first) line.
        self.bg.amount = len(tooltip.splitlines()) - 1 + bool(buildmenu_icons)
        self.label.text = bool(buildmenu_icons) * '\n' + tooltip
        self.gui.adaptLayout()
        self.gui.show()

        # NOTE: the below code in this method is a hack to resolve #2227
        # cannot find a better way to fix it, cause in fife.pychan, it seems
        # if a widget gets hidden or removed, the children of that widget are not
        # hidden or removed properly (at least in Python code)

        # update topmost_widget every time the tooltip is shown
        # this is to dismiss the tooltip later, see _check_hover_alive
        target_widget = self
        while target_widget:
            self.topmost_widget = target_widget
            target_widget = target_widget.parent

        # add an event to constantly check whether the hovered widget is still there
        # if this is no longer there, dismiss the tooltip widget
        ExtScheduler().add_new_object(self._check_hover_alive,
                                      self,
                                      run_in=0.5,
                                      loops=-1)
Esempio n. 17
0
	def refresh(self):
		"""This function is called by the TabWidget to redraw the widget."""
		super(BoatbuilderTab, self).refresh()

		main_container = self.widget.findChild(name="BB_main_tab")
		container_active = main_container.findChild(name="container_active")
		container_inactive = main_container.findChild(name="container_inactive")
		progress_container = main_container.findChild(name="BB_progress_container")
		cancel_container = main_container.findChild(name="BB_cancel_container")
		needed_res_container = self.widget.findChild(name="BB_needed_resources_container")

		# a boatbuilder is considered active here if it build sth, no matter if it's paused
		production_lines = self.producer.get_production_lines()

		if production_lines:
			cancel_container.parent.showChild(cancel_container)

			# Set progress
			progress_container.parent.showChild(progress_container)
			progress = math.floor(self.producer.get_production_progress() * 100)
			self.widget.findChild(name='progress').progress = progress
			progress_perc = self.widget.findChild(name='BB_progress_perc')
			progress_perc.text = u'{progress}%'.format(progress=progress)

			container_active.parent.showChild(container_active)
			if not container_inactive in container_inactive.parent.hidden_children:
				container_inactive.parent.hideChild(container_inactive)

			# Update boatbuilder queue
			queue = self.producer.get_unit_production_queue()
			queue_container = container_active.findChild(name="queue_container")
			queue_container.removeAllChildren()
			for place_in_queue, unit_type in enumerate(queue):
				image = self.__class__.SHIP_THUMBNAIL.format(type_id=unit_type)
				helptext = _(u"{ship} (place in queue: {place})") #xgettext:python-format
				helptext.format(ship=self.instance.session.db.get_unit_type_name(unit_type),
				                place=place_in_queue+1)
				# people don't count properly, always starting at 1..
				icon_name = "queue_elem_"+str(place_in_queue)
				icon = Icon(name=icon_name, image=image, helptext=helptext)
				rm_from_queue_cb = Callback(RemoveFromQueue(self.producer, place_in_queue).execute,
				                            self.instance.session)
				icon.capture(rm_from_queue_cb, event_name="mouseClicked")
				queue_container.addChild( icon )

			# Set built ship info
			production_line = self.producer._get_production(production_lines[0])
			produced_unit_id = production_line.get_produced_units().keys()[0]

			name = self.instance.session.db.get_unit_type_name(produced_unit_id)

			container_active.findChild(name="headline_BB_builtship_label").text = _(name)
			ship_icon = container_active.findChild(name="BB_cur_ship_icon")
			ship_icon.helptext = self.instance.session.db.get_ship_tooltip(produced_unit_id)
			ship_icon.image = self.__class__.SHIP_PREVIEW_IMG.format(type_id=produced_unit_id)

			button_active = container_active.findChild(name="toggle_active_active")
			button_inactive = container_active.findChild(name="toggle_active_inactive")
			to_active = not self.producer.is_active()

			if not to_active: # swap what we want to show and hide
				button_active, button_inactive = button_inactive, button_active
			if not button_active in button_active.parent.hidden_children:
				button_active.parent.hideChild(button_active)
			button_inactive.parent.showChild(button_inactive)

			set_active_cb = Callback(self.producer.set_active, active=to_active)
			button_inactive.capture(set_active_cb, event_name="mouseClicked")

			upgrades_box = container_active.findChild(name="BB_upgrades_box")
			upgrades_box.removeAllChildren()
#			upgrades_box.addChild(Label(text=u"+ love"))
#			upgrades_box.addChild(Label(text=u"+ affection"))
# no upgrades in 2010.1 release ---^
			upgrades_box.stylize('menu_black')

			# Update needed resources
			production = self.producer.get_productions()[0]
			needed_res = production.get_consumed_resources()
			# Now sort! -amount is the positive value, drop unnecessary res (amount 0)
			needed_res = dict((res, -amount) for res, amount in needed_res.iteritems() if amount < 0)
			needed_res = sorted(needed_res.iteritems(), key=itemgetter(1), reverse=True)
			needed_res_container.removeAllChildren()
			for i, (res, amount) in enumerate(needed_res):
				icon = create_resource_icon(res, self.instance.session.db)
				icon.max_size = icon.min_size = icon.size = (16, 16)
				label = Label(name="needed_res_lbl_%s" % i)
				label.text = u'{amount}t'.format(amount=amount)
				new_hbox = HBox(name="needed_res_box_%s" % i)
				new_hbox.addChildren(icon, label)
				needed_res_container.addChild(new_hbox)

			cancel_button = self.widget.findChild(name="BB_cancel_button")
			cancel_cb = Callback(CancelCurrentProduction(self.producer).execute, self.instance.session)
			cancel_button.capture(cancel_cb, event_name="mouseClicked")

		else: # display sth when nothing is produced
			container_inactive.parent.showChild(container_inactive)
			for w in (container_active, progress_container, cancel_container):
				if not w in w.parent.hidden_children:
					w.parent.hideChild(w)

		self.widget.adaptLayout()
	def refresh(self):
		"""This function is called by the TabWidget to redraw the widget."""
		super(BoatbuilderTab, self).refresh()

		THUMB_PATH = "content/gui/images/objects/ships/116/%s.png"

		main_container = self.widget.findChild(name="BB_main_tab")
		container_active = main_container.findChild(name="container_active")
		container_inactive = main_container.findChild(name="container_inactive")
		progress_container = main_container.findChild(name="BB_progress_container")
		cancel_container = main_container.findChild(name="BB_cancel_container")
		needed_res_container = self.widget.findChild(name="BB_needed_resources_container")

		# a boatbuilder is considered active here if it build sth, no matter if it's paused
		production_lines = self.producer.get_production_lines()

		if production_lines:

			if cancel_container is None:
				main_container.addChild(main_container.cancel_container)
				cancel_container = main_container.cancel_container

			if needed_res_container is None:
				main_container.insertChildBefore(main_container.needed_res_container, cancel_container)
				needed_res_container = main_container.needed_res_container

			# Set progress
			if progress_container is None:
				main_container.insertChildBefore( main_container.progress_container, self.widget.findChild(name="BB_needed_resources_container"))
				progress_container = main_container.progress_container

			progress = math.floor(self.producer.get_production_progress() * 100)
			self.widget.findChild(name='progress').progress = progress
			self.widget.findChild(name='BB_progress_perc').text = u'{progress}%'.format(progress=progress)

			# remove other container, but save it
			if container_inactive is not None:
				main_container.container_inactive = container_inactive
				main_container.removeChild( container_inactive )
			if container_active is None:
				main_container.insertChildBefore( main_container.container_active, progress_container)
				container_active = main_container.container_active

			# Update boatbuilder queue
			queue = self.producer.get_unit_production_queue()
			queue_container = container_active.findChild(name="queue_container")
			queue_container.removeAllChildren()
			for place_in_queue, unit_type in enumerate(queue):
				image = self.__class__.SHIP_THUMBNAIL.format(type_id=unit_type)
				#xgettext:python-format
				helptext = _(u"{ship} (place in queue: {place})").format(
				               ship=self.instance.session.db.get_unit_type_name(unit_type),
				               place=place_in_queue+1 )
				# people don't count properly, always starting at 1..
				icon_name = "queue_elem_"+str(place_in_queue)
				icon = Icon(name=icon_name, image=image, helptext=helptext)
				icon.capture(
				  Callback(RemoveFromQueue(self.producer, place_in_queue).execute, self.instance.session),
				  event_name="mouseClicked"
				)
				queue_container.addChild( icon )

			# Set built ship info
			produced_unit_id = self.producer._get_production(production_lines[0]).get_produced_units().keys()[0]
			name = self.instance.session.db.get_unit_type_name(produced_unit_id)
			container_active.findChild(name="headline_BB_builtship_label").text = _(name)
			container_active.findChild(name="BB_cur_ship_icon").helptext = "Storage: 4 slots, 120t \nHealth: 100"
			container_active.findChild(name="BB_cur_ship_icon").image = THUMB_PATH % produced_unit_id

			button_active = container_active.findChild(name="toggle_active_active")
			button_inactive = container_active.findChild(name="toggle_active_inactive")

			if not self.producer.is_active(): # if production is paused
				# remove active button, if it's there, and save a reference to it
				if button_active is not None:
					container_active.button_active = button_active
					container_active.removeChild( button_active )
				# restore inactive button, if it isn't in the gui
				if button_inactive is None:
					# insert at the end
					container_active.insertChild(container_active.button_inactive,
					                             len(container_active.children))
				container_active.mapEvents({
				  'toggle_active_inactive' : Callback(self.producer.set_active, active=True)
				})
				# TODO: make this button do sth
			else:
				# remove inactive button, if it's there, and save a reference to it
				if button_inactive is not None:
					container_active.button_inactive = button_inactive
					container_active.removeChild( button_inactive )
				# restore active button, if it isn't in the gui
				if button_active is None:
					# insert at the end
					container_active.insertChild(container_active.button_active,
					                             len(container_active.children))

				container_active.mapEvents({
				  'toggle_active_active' : Callback(self.producer.set_active, active=False)
				})
			upgrades_box = container_active.findChild(name="BB_upgrades_box")
			for child in upgrades_box.children[:]:
				upgrades_box.removeChild(child)
#			upgrades_box.addChild( pychan.widgets.Label(text=u"+ love") )
#			upgrades_box.addChild( pychan.widgets.Label(text=u"+ affection") )
# no upgrades in 2010.1 release ---^
			upgrades_box.stylize('menu_black')

			# Update needed resources
			production = self.producer.get_productions()[0]
			needed_res = production.get_consumed_resources()
			# Now sort! -amount is the positive value, drop unnecessary res (amount 0)
			needed_res = dict((res, -amount) for res, amount in needed_res.iteritems() if amount < 0)
			needed_res = sorted(needed_res.iteritems(), key=itemgetter(1), reverse=True)
			needed_res_container.removeAllChildren()
			for i, (res, amount) in enumerate(needed_res):
				icon = create_resource_icon(res, self.instance.session.db)
				icon.max_size = icon.min_size = icon.size = (16, 16)
				label = Label(name="needed_res_lbl_%s" % i)
				label.text = u'{amount}t'.format(amount=amount)
				new_hbox = HBox(name="needed_res_box_%s" % i)
				new_hbox.addChildren(icon, label)
				needed_res_container.addChild(new_hbox)

			cancel_button = self.widget.findChild(name="BB_cancel_button")
			cancel_cb = Callback(CancelCurrentProduction(self.producer).execute, self.instance.session)
			cancel_button.capture(cancel_cb, event_name="mouseClicked")

		else: # display sth when nothing is produced
			# remove other container, but save it
			if container_active is not None:
				main_container.container_active = container_active
				main_container.removeChild( container_active )
			if container_inactive is None:
				main_container.insertChildBefore( main_container.container_inactive, progress_container)
				container_inactive = main_container.container_inactive

			if progress_container is not None:
				main_container.progress_container = progress_container
				main_container.removeChild(progress_container)

			if needed_res_container is not None:
				main_container.needed_res_container = needed_res_container
				main_container.removeChild(needed_res_container)

			if cancel_container is not None:
				main_container.cancel_container = cancel_container
				main_container.removeChild(cancel_container)


		self.widget.adaptLayout()