예제 #1
0
 def _set_tile_amount(self, amount):
     self.__tile_amount = amount
     for i in xrange(self.amount):
         mid = Icon(image=self.tiles_img, name=self.name + str(i + 1))
         self.addChild(mid)
     self.addChild(
         Icon(image=self.final_img, name=self.name + str(self.amount + 1)))
예제 #2
0
    def update_queue(self, container_active):
        """ Update the queue display"""
        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__.UNIT_THUMBNAIL.format(type_id=unit_type)
            helptext = T("{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)

            try:
                icon = Icon(name=icon_name, image=image, helptext=helptext)
            except fife.NotFound as e:
                # It's possible that this error was raised from a missing thumbnail asset,
                # so we check against that now and use a fallback thumbnail instead
                if 'content/gui/icons/thumbnails/' in e.what():
                    # actually load the fallback unit image
                    image = self.__class__.UNIT_THUMBNAIL.format(
                        type_id="unknown_unit")
                    icon = Icon(name=icon_name, image=image, helptext=helptext)
                else:
                    raise

            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)
	def _draw(self):
		"""Draws the icon + bar."""
		# hash buttons by creation function call
		# NOTE: there may be problems with multiple buttons with the same
		# images and helptext at the same time
		create_btn = Callback(ImageButton, path=self.path, helptext=self.helptext)
		self.button = None
		if self.uncached:
			self.button = create_btn()
		else:
			self.button = self.__widget_cache.get(create_btn, None)
			if self.button is None: # create button
				self.__widget_cache[create_btn] = self.button = create_btn()
			else: # disconnect button from earlier layout
				if self.button.parent:
					self.button.parent.removeChild(self.button)

		# can't cache the other instances, because we need multiple instances
		# with the same data active at the same time
		self.label = Label(text=self.text)
		self.label.position = self.text_position
		self.fill_bar = Icon(image="content/gui/images/tabwidget/green_line.png")
		fill_level = (self.button.height * self.filled) // 100
		self.fill_bar.size = ((2 * self.fill_bar.size[0]) // 3, fill_level)
		# move fillbar down after resizing, since its origin is top aligned
		self.fill_bar.position = (self.button.width, self.button.height - fill_level)
		self.addChildren(self.button, self.fill_bar, self.label)
		if self.marker > 0:
			marker_icon = Icon(image="content/gui/icons/templates/production/marker.png")
			marker_level = (self.button.height * self.marker) // 100
			marker_icon.position = (self.button.width - 1, self.button.height - marker_level)
			marker_icon.max_size = (5, 1)
			self.addChild(marker_icon)
예제 #4
0
	def show_tooltip(self):
		if not self.helptext:
			return
		# recreate full tooltip since new text needs to be relayouted
		if self.gui is None:
			self.gui = load_uh_widget('tooltip.xml')
		else:
			self.gui.removeAllChildren()
		translated_tooltip = _(self.helptext)
		#HACK this looks better than splitting into several lines & joining
		# them. works because replace_whitespace in fill defaults to True:
		replaced = translated_tooltip.replace(r'\n', self.CHARS_PER_LINE*' ')
		replaced = replaced.replace(r'[br]', self.CHARS_PER_LINE*' ')
		tooltip = textwrap.fill(replaced, self.CHARS_PER_LINE)

		line_count = len(tooltip.splitlines()) - 1
		top_image = Icon(image=self.TOP_IMAGE, position=(0, 0))
		self.gui.addChild(top_image)
		top_x, top_y = top_image.position
		top_y += self.SIZE_BG_TOP
		for i in xrange(0, line_count):
			middle_image = Icon(image=self.MIDDLE_IMAGE)
			middle_image.position = (top_x, top_y + self.LINE_HEIGHT * i)
			self.gui.addChild(middle_image)
		bottom_image = Icon(image=self.BOTTOM_IMAGE)
		bottom_image.position = (top_x, top_y + self.LINE_HEIGHT * line_count)
		self.gui.addChild(bottom_image)

		label = Label(text=tooltip, position=(10, 5))
		self.gui.addChild(label)
		self.gui.stylize('tooltip')
		size_y = self.SIZE_BG_TOP + self.LINE_HEIGHT * line_count + self.SIZE_BG_BOTTOM
		self.gui.size = (145, size_y)
		self.gui.show()
예제 #5
0
	def set_construction_mode(self, resource_source_instance, build_costs):
		"""Show resources relevant to construction and build costs
		@param resource_source_instance: object with StorageComponent
		@param build_costs: dict, { res : amount }
		"""
		if resource_source_instance is None:
			# Build moved out of settlement. This is usually not sane and an interaction error.
			# Use this heuristically computed settlement to fix preconditions.
			resource_source_instance = LastActivePlayerSettlementManager().get()
		if self.construction_mode and \
		   resource_source_instance == self.current_instance() and \
		   build_costs == self._last_build_costs:
			return # now that's not an update

		self._last_build_costs = build_costs

		self.construction_mode = True
		self.set_inventory_instance(resource_source_instance, keep_construction_mode=True)

		# label background icons
		cost_icon_gold = "content/gui/images/background/widgets/resbar_stats_bottom.png"
		cost_icon_res = "content/gui/images/background/widgets/res_extra_bg.png"

		res_list = self._get_current_resources()

		# remove old one before, avoids duplicates
		self._drop_cost_labels()

		for res, amount in build_costs.iteritems():
			assert res in res_list or res == RES.GOLD

			cost_label = Label(text=u"-"+unicode(amount))
			cost_label.stylize( self.__class__.STYLE )
			# add icon below end of background icon
			if res in res_list:
				entry = res_list.index(res)
				cur_gui = self.gui[ entry ]
				reference_icon = cur_gui.findChild(name="background_icon")
				below = reference_icon.size[1]
				cost_icon = Icon(image=cost_icon_res, position=(0, below))
				cost_label.position = (15, below) # TODO: centering

				cur_gui.addChild(cost_icon)
				cur_gui.addChild(cost_label)
				cur_gui.cost_gui = [cost_label, cost_icon]

				cur_gui.resizeToContent() # container needs to be bigger now
			else: # must be gold
				# there is an icon with scales there, use its positioning
				reference_icon = self.gold_gui.child_finder("balance_background")
				cost_icon = Icon(image=cost_icon_gold, position=(reference_icon.x, reference_icon.y))
				cost_label.position = (23, 74) # TODO: centering

				self.gold_gui.addChild(cost_icon)
				self.gold_gui.addChild(cost_label)
				self.gold_gui.cost_gui = [cost_label, cost_icon]

				self.gold_gui.resizeToContent()
예제 #6
0
    def build_ship_info(self, index, ship, prodline):
        size = (260, 90)
        widget = Container(name='showcase_%s' % index,
                           position=(0, 20 + index * 90),
                           min_size=size,
                           max_size=size,
                           size=size)
        bg_icon = Icon(image='content/gui/images/background/square_80.png',
                       name='bg_%s' % index)
        widget.addChild(bg_icon)

        image = 'content/gui/images/objects/ships/76/{unit_id}.png'.format(
            unit_id=ship)
        helptext = self.instance.session.db.get_ship_tooltip(ship)
        unit_icon = Icon(image=image,
                         name='icon_%s' % index,
                         position=(2, 2),
                         helptext=helptext)
        widget.addChild(unit_icon)

        # if not buildable, this returns string with reason why to be displayed as helptext
        #ship_unbuildable = self.is_ship_unbuildable(ship)
        ship_unbuildable = False
        if not ship_unbuildable:
            button = OkButton(position=(60, 50),
                              name='ok_%s' % index,
                              helptext=_('Build this ship!'))
            button.capture(Callback(self.start_production, prodline))
        else:
            button = CancelButton(position=(60, 50),
                                  name='ok_%s' % index,
                                  helptext=ship_unbuildable)

        widget.addChild(button)

        # Get production line info
        production = self.producer.create_production_line(prodline)
        # consumed == negative, reverse to sort in *ascending* order:
        costs = sorted(production.consumed_res.iteritems(), key=itemgetter(1))
        for i, (res, amount) in enumerate(costs):
            xoffset = 103 + (i % 2) * 55
            yoffset = 20 + (i // 2) * 20
            icon = create_resource_icon(res, self.instance.session.db)
            icon.max_size = icon.min_size = icon.size = (16, 16)
            icon.position = (xoffset, yoffset)
            label = Label(name='cost_%s_%s' % (index, i))
            if res == RES.GOLD:
                label.text = unicode(-amount)
            else:
                label.text = u'{amount:02}t'.format(amount=-amount)
            label.position = (22 + xoffset, yoffset)
            widget.addChild(icon)
            widget.addChild(label)
        return widget
예제 #7
0
	def _set_tile_amount(self, amount):
		if amount == self.__tile_amount and amount > 0:
			# Default amount of 0 should still add top/bottom graphics once
			return
		self.__tile_amount = amount
		self.removeAllChildren()
		start_img = Icon(image=self.start_img, name=self.name + '0')
		self.addChild(start_img)
		for i in xrange(self.amount):
			mid = Icon(image=self.tiles_img, name=self.name + str(i+1))
			self.addChild(mid)
		self.addChild(Icon(image=self.final_img, name=self.name + str(self.amount+1)))
예제 #8
0
	def _draw_pretty_arrows(self, parent_container, amount, x=0, y=0, out=False):
		"""Draws incoming or outgoing arrows for production line container."""
		if amount % 2:
			# Add center arrow for 1, 3, 5, ... but not 2, 4, ...
			if out:
				mid_arrow = Icon(image=self.__class__.ARROWHEAD_MID)
			else:
				mid_arrow = Icon(image=self.__class__.ARROW_MID)
			mid_arrow.position = (x, 17 + y)
			parent_container.insertChild(mid_arrow, 0)

		for res in xrange(amount // 2):
			# --\                      <= placed for res = 1
			# --\| <= place connector  <= placed for res = 0
			# ---O-->                  <= placed above (mid_arrow)
			# --/| <= place connector  <= placed for res = 0
			# --/                      <= placed for res = 1
			offset = -17 + (self.ICON_HEIGHT // 2) * (2 * res + (amount % 2) + 1)

			if out:
				top_arrow = Icon(image=self.__class__.ARROWHEAD_TOP)
			else:
				top_arrow = Icon(image=self.__class__.ARROW_TOP)
			top_arrow.position = (x, y - offset)
			parent_container.insertChild(top_arrow, 0)

			if out:
				bottom_arrow = Icon(image=self.__class__.ARROWHEAD_BOTTOM)
			else:
				bottom_arrow = Icon(image=self.__class__.ARROW_BOTTOM)
			bottom_arrow.position = (x, y + offset)
			parent_container.insertChild(bottom_arrow, 0)

			# Place a connector image (the | in above sketch) that vertically connects
			# the input resource arrows. We need those if the production line has more
			# than three input resources. Connectors are placed in the inner loop parts.
			place_connectors = amount > (3 + 2 * res)
			if place_connectors:
				# the connector downwards connects top_arrows
				if out:
					down_connector = Icon(image=self.__class__.ARROWHEAD_CONNECT_DOWN)
				else:
					down_connector = Icon(image=self.__class__.ARROW_CONNECT_DOWN)
				down_connector.position = (98, y - offset)
				parent_container.insertChild(down_connector, 0)
				# the connector upwards connects up_arrows
				if out:
					up_connector = Icon(image=self.__class__.ARROWHEAD_CONNECT_UP)
				else:
					up_connector = Icon(image=self.__class__.ARROW_CONNECT_UP)
				up_connector.position = (98, y + offset)
				parent_container.insertChild(up_connector, 0)
예제 #9
0
    def _connect_multiple_input_res_for_production(self, centered_container,
                                                   container, production):
        """Draws incoming arrows for production line container."""
        input_amount = len(production.get_consumed_resources())
        if input_amount == 0:
            # Do not draw input arrows if there is no input
            return

        # center the production line
        icon_height = ImageFillStatusButton.CELL_SIZE[
            1] + ImageFillStatusButton.PADDING
        center_y = (icon_height // 2) * (input_amount - 1)
        centered_container.position = (0, center_y)

        if input_amount % 2:
            # Add center arrow for 1, 3, 5, ... but not 2, 4, ...
            mid_arrow = Icon(image=self.__class__.ARROW_MID)
            mid_arrow.position = (58, 17 + center_y)
            container.insertChild(mid_arrow, 0)

        for res in xrange(input_amount // 2):
            # --\                      <= placed for res = 1
            # --\| <= place connector  <= placed for res = 0
            # ---O-->                  <= placed above
            # --/| <= place connector  <= placed for res = 0
            # --/                      <= placed for res = 1
            offset = -17 + (icon_height // 2) * (2 * res +
                                                 (input_amount % 2) + 1)

            top_arrow = Icon(image=self.__class__.ARROW_TOP)
            top_arrow.position = (58, center_y - offset)
            container.insertChild(top_arrow, 0)

            bottom_arrow = Icon(image=self.__class__.ARROW_BOTTOM)
            bottom_arrow.position = (58, center_y + offset)
            container.insertChild(bottom_arrow, 0)

            # Place a connector image (the | in above sketch) that vertically connects
            # the input resource arrows. We need those if the production line has more
            # than three input resources. Connectors are placed in the inner loop parts.
            place_connectors = (1 + 2 * res) < (input_amount // 2)
            if place_connectors:
                # the connector downwards connects top_arrows
                down_connector = Icon(image=self.__class__.ARROW_CONNECT_DOWN)
                down_connector.position = (98, center_y - offset)
                container.insertChild(down_connector, 0)
                # the connector upwards connects up_arrows
                up_connector = Icon(image=self.__class__.ARROW_CONNECT_UP)
                up_connector.position = (98, center_y + offset)
                container.insertChild(up_connector, 0)
예제 #10
0
    def parse_logbook_item(self, parameter):
        # json.loads() returns unicode, thus convert strings and compare to unicode
        # Image works with str() since pychan can only use str objects as file path
        if parameter and parameter[0]:  # allow empty Labels
            parameter_type = parameter[0]
        if isinstance(parameter, basestring):
            add = Label(text=unicode(parameter),
                        wrap_text=True,
                        min_size=(335, 0),
                        max_size=(335, 508))
        elif parameter_type == u'Label':
            add = Label(text=unicode(parameter[1]),
                        wrap_text=True,
                        min_size=(335, 0),
                        max_size=(335, 508))
        elif parameter_type == u'Image':
            add = Icon(image=str(parameter[1]))
        elif parameter_type == u'Gallery':
            add = HBox()
            for image in parameter[1]:
                add.addChild(Icon(image=str(image)))
        elif parameter_type == u'Headline':
            add = Label(text=unicode(parameter[1]),
                        wrap_text=True,
                        min_size=(335, 0),
                        max_size=(335, 508),
                        font='headline')
        elif parameter_type == u'BoldLabel':
            add = Label(text=unicode(parameter[1]),
                        wrap_text=True,
                        min_size=(335, 0),
                        max_size=(335, 508),
                        font='14_bold')
        elif parameter_type == u'Message':
            add = None
            # parameters are re-read on page reload.
            # duplicate_message stops messages from
            # being duplicated on page reload.
            message = parameter[1]
            duplicate_message = message in self._messages_to_display  # message is already going to be displayed

            if not duplicate_message:
                self._messages_to_display.append(
                    message)  # the new message has not been displayed
        else:
            print '[WW] Warning: Unknown parameter type {typ} in parameter {prm}'.format(
                typ=parameter[0], prm=parameter)
            add = None
        return add
예제 #11
0
    def _init_tab_buttons(self):
        """Add enough tabbuttons for all widgets."""
        def on_tab_removal(tabwidget):
            # called when a tab is being removed (via weakref since tabs shouldn't have references to the parent tabwidget)
            # If one tab is removed, the whole tabwidget will die..
            # This is easy usually the desired behavior.
            if tabwidget():
                tabwidget().on_remove()

        # Load buttons
        for index, tab in enumerate(self._tabs):
            # don't add a reference to the
            tab.add_remove_listener(Callback(on_tab_removal,
                                             weakref.ref(self)))
            container = Container(name="container_{}".format(index))
            background = Icon(name="bg_{}".format(index))
            button = ImageButton(name=str(index), size=(50, 50))
            if self.current_tab is tab:
                background.image = tab.button_background_image_active
                button.path = tab.path_active
            else:
                background.image = tab.button_background_image
                button.path = tab.path
            button.capture(Callback(self.show_tab, index))
            if hasattr(tab, 'helptext') and tab.helptext:
                button.helptext = tab.helptext
            container.size = (50, 52)
            container.addChild(background)
            container.addChild(button)
            self.content.addChild(container)
        self.widget.size = (54, 55 * len(self._tabs))
        self.widget.adaptLayout()

        self._apply_layout_hack()
예제 #12
0
    def show_text(self, index):
        """Shows the text for a button.
		@param index: index of button"""
        assert isinstance(index, int)
        ExtScheduler().rem_call(
            self, self.hide_text)  # stop hiding if a new text has been shown
        label = self.text_widget.findChild(name='text')
        text = self.active_messages[self.item + index].message
        text = text.replace(r'\n', self.CHARS_PER_LINE * ' ')
        text = text.replace(r'[br]', self.CHARS_PER_LINE * ' ')
        text = textwrap.fill(text, self.CHARS_PER_LINE)

        self.bg_middle = self.text_widget.findChild(name='msg_bg_middle')
        self.bg_middle.removeAllChildren()

        line_count = len(text.splitlines()) - 1
        for i in xrange(line_count * self.LINE_HEIGHT // self.IMG_HEIGHT):
            middle_icon = Icon(image=self.BG_IMAGE_MIDDLE)
            self.bg_middle.addChild(middle_icon)

        message_container = self.text_widget.findChild(name='message')
        message_container.size = (300, 21 + self.IMG_HEIGHT * line_count + 21)

        self.bg_middle.adaptLayout()
        label.text = text
        label.adaptLayout()
        self.text_widget.show()
예제 #13
0
def create_resource_icon(res_id, db):
	"""Creates a pychan Icon for a resource. Helptext is set to name of *res_id*.
	@param res_id: resource id
	@param db: dbreader for main db"""
	widget = Icon(image=get_res_icon_path(res_id))
	widget.helptext = db.get_res_name(res_id)
	return widget
예제 #14
0
	def init(self, db, inventory, ordinal=None):
		"""
		@param ordinal: {res: (min, max)} Display ordinal scale with these boundaries instead of numbers for a particular resource. Currently implemented via ImageFillStatusButton.
		"""
		# check if we must init everything anew
		if self.init_needed(inventory):
			# this inits the logic of the inventory. @see __init__().
			self._inited = True
			self.db = db
			self._inventory = inventory

			# specific to Inventory
			self.ordinal = ordinal
			self._res_order = sorted(self._inventory.iterslots())
			self.legend = Label(name="legend")
			self.__icon = Icon(name="legend_icon")
			self.__icon.image = "content/gui/icons/ship/civil_16.png"
			if isinstance(self._inventory, TotalStorage):
				self.__icon.position = (130, 53)
				self.legend.position = (150, 53)
			elif isinstance(self._inventory, PositiveSizedSlotStorage):
				self.__icon.position = ( 0, 248)
				self.legend.position = (20, 248)

		self.update()
예제 #15
0
 def update(self):
     self.removeAllChildren()
     weapons_added = False
     if hasattr(self.instance, 'get_weapon_storage'):
         storage = self.instance.get_weapon_storage()
         for weapon, amount in storage:
             weapons_added = True
             icon_image = get_res_icon_path(weapon, 24)
             icon_tooltip = self.instance.session.db.get_res_name(
                 weapon) + ': ' + str(amount)
             icon = Icon(image=icon_image, helptext=icon_tooltip)
             self.addChild(icon)
     if not weapons_added:
         icon_image = "content/gui/icons/resources/none.png"
         icon = Icon(image=icon_image, helptext=_("none"))
         self.addChild(icon)
예제 #16
0
			def __init__(self, cursor_tool, **kwargs):
				super(CoordsTooltip, self).__init__(**kwargs)
				cursor_tool.session.ingame_gui.coordinates_tooltip = self
				self.cursor_tool = cursor_tool
				self.enabled = False

				self.icon = Icon(position=(1, 1)) # 0, 0 is currently not supported by tooltips
예제 #17
0
def get_res_icon_path(res, size=32, greyscale=False, full_path=True):
	"""Returns path of a resource icon or placeholder path, if icon does not exist.
	@param res: resource id. Pass 'placeholder' to get placeholder path.
	@param full_path: whether to return full icon path or a stub path suitable for ImageButton path=
	"""
	icon_path = 'content/gui/icons/resources/{size}/'.format(size=size)
	if greyscale:
		icon_path = icon_path + 'greyscale/'
	if res == 'placeholder':
		icon_path = icon_path + 'placeholder.png'
	else:
		icon_path = icon_path + '{res:03d}.png'.format(res=res)

	try:
		Icon(image=icon_path).hide()
	except fife.NotFound: # ImageManager: image not found, use placeholder or die
		if res == 'placeholder':
			raise Exception('Image not found: {icon_path}'.format(icon_path=icon_path))
		else:
			log = logging.getLogger('gui')
			log.warning('Image not found: %s', icon_path)
			icon_path = get_res_icon_path('placeholder', size)

	if full_path:
		return icon_path
	else:
		# remove 'content/gui/' and '.png'
		return icon_path[12:][:-4]
예제 #18
0
 def _icon(image):
     try:
         # Pychan can only use str objects as file path.
         # json.loads() however returns unicode.
         return Icon(image=str(image))
     except RuntimeError:
         return None
예제 #19
0
    def show_text(self, index):
        """Shows the text for a button.
		@param index: index of button"""
        assert isinstance(index, int)
        # stop hiding if a new text has been shown
        ExtScheduler().rem_call(self, self.hide_text)

        text = self.active_messages[index].message
        text = text.replace(r'\n', self.CHARS_PER_LINE * ' ')
        text = text.replace('[br]', self.CHARS_PER_LINE * ' ')
        text = textwrap.fill(text, self.CHARS_PER_LINE)

        self.bg_middle = self.text_widget.findChild(name='msg_bg_middle')
        self.bg_middle.removeAllChildren()

        line_count = len(text.splitlines()) - 1
        for i in range(line_count * self.LINE_HEIGHT // self.IMG_HEIGHT):
            middle_icon = Icon(image=self.BG_IMAGE_MIDDLE)
            self.bg_middle.addChild(middle_icon)

        button = self.widget.findChild(name=str(index))
        # y position relative to parent
        button_y = button.position[1]
        # Show text next to corresponding icon
        x, y = self.reference_text_widget_position
        self.text_widget.position = (x, y + button_y)

        message_container = self.text_widget.findChild(name='message')
        message_container.size = (300, 21 + self.IMG_HEIGHT * line_count + 21)

        self.bg_middle.adaptLayout()
        label = self.text_widget.findChild(name='text')
        label.text = text
        label.adaptLayout()
        self.text_widget.show()
예제 #20
0
    def refresh(self):
        """
		This function is called by the TabWidget to redraw the widget.
		"""
        # remove old data
        parent_container = self.widget.child_finder('related_buildings')
        while parent_container.children:
            parent_container.removeChild(parent_container.children[0])

        # load all related buildings from DB
        building_ids = self.instance.session.db.get_related_building_ids_for_menu(
            self.instance.id)
        sorted_ids = sorted([(b, Entities.buildings[b].settler_level)
                             for b in building_ids],
                            key=lambda x: x[1])
        container = self.__get_new_container()
        for i, (building_id, level) in enumerate(sorted_ids):
            if level > self.instance.owner.settler_level:
                break

            button = self._create_build_buttons(building_id, container)
            # check whether to start new line (currently only 4 fit per line)
            if i and i % 4 == 0:
                parent_container.addChild(container)
                container = self.__get_new_container()
            container.findChild(name="build_button_container").addChild(button)
            button_bg = Icon(
                image="content/gui/images/buttons/buildmenu_button_bg.png")
            container.findChild(
                name="build_button_bg_container").addChild(button_bg)
        # Still need to add last container
        parent_container.addChild(container)
        super(BuildRelatedTab, self).refresh()
예제 #21
0
		def _icon(image):
			try:
				# Pychan can only use str objects as file path.
				# json.loads() however returns unicode.
				return Icon(image=str(image))
			except fife.NotFound:
				return None
예제 #22
0
	def __init__(self):
		self.mainlistener = MainListener(self)

		self.windows = WindowManager()
		# temporary aliases for compatibility with rest of the code
		self.open_popup = self.windows.open_popup
		self.open_error_popup = self.windows.open_error_popup

		# Main menu background image setup.
		available_images = glob.glob('content/gui/images/background/mainmenu/bg_*.png')
		self.bg_images = deque(available_images)

		latest_bg = horizons.globals.fife.get_uh_setting("LatestBackground")
		try:
			# If we know the current background from an earlier session,
			# show all other available ones before picking that one again.
			self.bg_images.remove(latest_bg)
			self.bg_images.append(latest_bg)
		except ValueError:
			pass
		self._background = Icon(position_technique='center:center')
		self.rotate_background()
		self._background.show()

		# Initialize menu dialogs and widgets that are accessed from `gui`.
		self.singleplayermenu = SingleplayerMenu(self.windows)
		self.multiplayermenu = MultiplayerMenu(self, self.windows)
		self.help_dialog = HelpDialog(self.windows)
		self.loadingscreen = LoadingScreen()
		self.settings_dialog = SettingsDialog(self.windows)
		self.mainmenu = MainMenu(self, self.windows)
		self.fps_display = FPSDisplay()
예제 #23
0
	def update(self):
		self.removeAllChildren()
		weapons_added = False
		if hasattr(self.instance, 'get_weapon_storage'):
			storage = self.instance.get_weapon_storage()
			for weapon, amount in storage:
				weapons_added = True
				icon_image = get_res_icon_path(weapon, 24)
				weapon_name = self.instance.session.db.get_res_name(weapon)
				# You usually do not need to change anything here when translating
				helptext = T('{weapon}: {amount}').format(weapon=weapon_name, amount=amount)
				icon = Icon(image=icon_image, helptext=helptext)
				self.addChild(icon)
		if not weapons_added:
			icon_image = "content/gui/icons/resources/none.png"
			icon = Icon(image=icon_image, helptext=T("none"))
			self.addChild(icon)
예제 #24
0
 def init_widget(self):
     super().init_widget()
     container = ABox(position=(20, 210))
     icon = Icon(name='build_all_bg')
     button = ImageButton(name='build_all_button')
     container.addChild(icon)
     container.addChild(button)
     self.widget.addChild(container)
     self.update_data()
예제 #25
0
	def init_widget(self):
		super(LumberjackOverviewTab, self).init_widget()
		container = AutoResizeContainer(position=(20, 210))
		icon = Icon(name='build_all_bg')
		button = ImageButton(name='build_all_button')
		container.addChild(icon)
		container.addChild(button)
		self.widget.addChild(container)
		self.update_data()
예제 #26
0
 def get_unit_thumbnail(self, unit_id):
     """Returns path of the thumbnail icon for unit with id *unit_id*."""
     template = "content/gui/icons/thumbnails/{unit_id}.png"
     path = template.format(unit_id=unit_id)
     try:
         Icon(image=path)
     except RuntimeError:
         self.log.warning('Missing unit thumbnail {0}'.format(path))
         path = template.format(unit_id='unknown_unit')
     return path
예제 #27
0
    def _set_path(self, path):
        self.__path = path
        image_path = self.IMAGE.format(path=path)
        try:
            self.up_image = image_path.format(mode='')
        except RuntimeError:
            # RuntimeError: _[NotFound]_ , Something was searched, but not found
            #TODO Temporarily try to find _u for the tabwidget
            self.up_image = image_path.format(mode='_u')
        try:
            self.hover_image = image_path.format(mode='_h')
        except RuntimeError:
            # By default, guichan/pychan will set hover_image to be the same as
            # up_image even if it is not explicitly set here (the following line
            # just reading `pass` instead of setting hover_image to up_image).
            # This however is stored internally in a way that would segfault FIFE
            # when trying to restore images from self.old_images that were set
            # like that implicitly (see #2000).
            self.hover_image = self.up_image
        try:
            self.down_image = image_path.format(mode='_d')
        except RuntimeError:
            self.down_image = self.up_image

        # Since inactive_image is no image attribute in pychan, it would
        # not be validated upon setting self.inactive_image (which works
        # for ImageButton.{up,down,hover}_image and Icon.image).
        # Instead, we try to load an Icon with that image and manually
        # set inactive_image to the path that worked, if there is any.
        try:
            image = image_path.format(mode='_bw')
            Icon(image=image).hide(
            )  # hide will remove Icon from widgets of pychan.internals.manager
            self.inactive_image = image
        except RuntimeError:
            try:
                image = image_path.format(mode='_gr')
                Icon(image=image).hide(
                )  # hide will remove Icon from widgets of pychan.internals.manager
                self.inactive_image = image
            except RuntimeError:
                self.inactive_image = self.up_image
예제 #28
0
    def _show_modal_background(self):
        """
		Loads transparent background that de facto prohibits access to other
		gui elements by eating all input events.
		"""
        height = horizons.globals.fife.engine_settings.getScreenHeight()
        width = horizons.globals.fife.engine_settings.getScreenWidth()
        image = horizons.globals.fife.imagemanager.loadBlank(width, height)
        image = fife.GuiImage(image)
        self._modal_background = Icon(image=image)
        self._modal_background.position = (0, 0)
        self._modal_background.show()
예제 #29
0
 def __init__(self, amount, name, base_path, start_img, tiles_img,
              final_img, **kwargs):
     super(TilingBackground, self).__init__(name=name,
                                            padding=0,
                                            border_size=0,
                                            **kwargs)
     # Note: Don't set the tile amount in the constructor,
     # as it will not layout correctly, blame pychan for it :-)
     self.__tile_amount = amount
     self.start_img = base_path + start_img
     self.tiles_img = base_path + tiles_img
     self.final_img = base_path + final_img
     start_img = Icon(image=self.start_img, name=self.name + '0')
     self.addChild(start_img)
예제 #30
0
    def update_queue(self, container_active):
        """ Update the queue display"""
        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__.UNIT_THUMBNAIL.format(type_id=unit_type)
            helptext = T("{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)

            try:
                icon = Icon(name=icon_name, image=image, helptext=helptext)
            except RuntimeError, e:
                # It's possible that this error was raised from a missing thumbnail asset,
                # so we check against that now and use a fallback thumbnail instead

                # TODO string matching for runtime errors is nightmare fuel
                # Better: Replace RuntimeError in fife with a more precise error class if possible
                # and only catch that class here
                if e.message.startswith(
                        '_[NotFound]_ , Something was searched, but not found :: content/gui/icons/thumbnails/'
                ):
                    # actually load the fallback unit image
                    image = self.__class__.UNIT_THUMBNAIL.format(
                        type_id="unknown_unit")
                    icon = Icon(name=icon_name, image=image, helptext=helptext)
                else:
                    raise

            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)