use of org.spongepowered.api.text.format.TextColor in project SpongeAPI by SpongePowered.
the class Text method of.
/**
* Builds a {@link Text} from a given array of objects.
*
* <p>For instance, you can use this like
* <code>Text.of(TextColors.DARK_AQUA, "Hi", TextColors.AQUA, "Bye")</code>
* </p>
*
* <p>This will create the correct {@link Text} instance if the input object
* is the input for one of the {@link Text} types or convert the object to a
* string otherwise.</p>
*
* <p>For instances of type {@link TextRepresentable} (e.g. {@link Text},
* {@link Builder}, ...) the formatting of appended text has priority over
* the current formatting in the method, e.g. the following results in a
* green, then yellow and at the end green again {@link Text}:</p>
*
* <code>Text.of(TextColors.GREEN, "Hello ", Text.of(TextColors.YELLOW,
* "Spongie"), '!');</code>
*
* @param objects The object array
* @return The built text object
*/
public static Text of(Object... objects) {
// Shortcut for lonely TextRepresentables
if (objects.length == 1 && objects[0] instanceof TextRepresentable) {
return ((TextRepresentable) objects[0]).toText();
}
final Text.Builder builder = builder();
TextFormat format = TextFormat.NONE;
HoverAction<?> hoverAction = null;
ClickAction<?> clickAction = null;
ShiftClickAction<?> shiftClickAction = null;
boolean changedFormat = false;
for (Object obj : objects) {
// Text formatting + actions
if (obj instanceof TextFormat) {
changedFormat = true;
format = (TextFormat) obj;
} else if (obj instanceof TextColor) {
changedFormat = true;
format = format.color((TextColor) obj);
} else if (obj instanceof TextStyle) {
changedFormat = true;
format = format.style(obj.equals(TextStyles.RESET) ? TextStyles.NONE : format.getStyle().and((TextStyle) obj));
} else if (obj instanceof TextAction) {
changedFormat = true;
if (obj instanceof HoverAction) {
hoverAction = (HoverAction<?>) obj;
} else if (obj instanceof ClickAction) {
clickAction = (ClickAction<?>) obj;
} else if (obj instanceof ShiftClickAction) {
shiftClickAction = (ShiftClickAction<?>) obj;
} else {
// Unsupported TextAction
}
} else if (obj instanceof TextRepresentable) {
// Special content
changedFormat = false;
Text.Builder childBuilder = ((TextRepresentable) obj).toText().toBuilder();
// Merge format (existing format has priority)
childBuilder.format(format.merge(childBuilder.format));
// Overwrite text actions if *NOT* present
if (childBuilder.clickAction == null) {
childBuilder.clickAction = clickAction;
}
if (childBuilder.hoverAction == null) {
childBuilder.hoverAction = hoverAction;
}
if (childBuilder.shiftClickAction == null) {
childBuilder.shiftClickAction = shiftClickAction;
}
builder.append(childBuilder.build());
} else {
// Simple content
changedFormat = false;
Text.Builder childBuilder;
if (obj instanceof String) {
childBuilder = builder((String) obj);
} else if (obj instanceof Translation) {
childBuilder = builder((Translation) obj);
} else if (obj instanceof Translatable) {
childBuilder = builder(((Translatable) obj).getTranslation());
} else if (obj instanceof Selector) {
childBuilder = builder((Selector) obj);
} else if (obj instanceof Score) {
childBuilder = builder((Score) obj);
} else {
childBuilder = builder(String.valueOf(obj));
}
if (hoverAction != null) {
childBuilder.onHover(hoverAction);
}
if (clickAction != null) {
childBuilder.onClick(clickAction);
}
if (shiftClickAction != null) {
childBuilder.onShiftClick(shiftClickAction);
}
builder.append(childBuilder.format(format).build());
}
}
if (changedFormat) {
// Did the formatting change without being applied to something?
// Then just append an empty text with that formatting
final Text.Builder childBuilder = builder();
if (hoverAction != null) {
childBuilder.onHover(hoverAction);
}
if (clickAction != null) {
childBuilder.onClick(clickAction);
}
if (shiftClickAction != null) {
childBuilder.onShiftClick(shiftClickAction);
}
builder.append(childBuilder.format(format).build());
}
if (builder.children.size() == 1) {
// Single content, reduce Text depth
return builder.children.get(0);
}
return builder.build();
}
use of org.spongepowered.api.text.format.TextColor in project Almura by AlmuraDev.
the class IngameFarmersAlmanac method loadProperties.
@SuppressWarnings("unchecked")
private void loadProperties(World world, IBlockState blockState, BlockPos targetBlockPos) {
final Hydration hydration = getHydrationDefinition(blockState).orElse(null);
if (hydration != null) {
this.addLineLabel(Text.of(TextColors.WHITE, "Hydrated by:"));
hydration.blockStates().forEach(bs -> {
this.addLineLabel(Text.of(TextColors.WHITE, "- ", TextColors.YELLOW, bs.block().getLocalizedName()), 2);
bs.properties().forEach(property -> bs.value(property).ifPresent(stateValue -> {
final String formattedValue;
if (stateValue instanceof RangeStateValue) {
final RangeStateValue rangeStateValue = (RangeStateValue) stateValue;
formattedValue = numberFormat.format(rangeStateValue.min()) + "-" + numberFormat.format(rangeStateValue.max());
} else {
final Comparable rawValue = stateValue.get((IProperty) property);
formattedValue = rawValue == null ? "" : rawValue.toString();
}
this.addLineLabel(this.getGenericPropertyText("- " + property.getName(), formattedValue), 6);
}));
// Todo: this MAX radius check, is it intended to be per block or per hydration or per crop?
if (hydration.getMaxRadius() > 0) {
// Range > 0 for only things such as water, never farmland.
this.addLineLabel(this.getGenericPropertyText("- radius", String.valueOf(hydration.getMaxRadius())), 6);
boolean found = false;
for (final BlockPos.MutableBlockPos inRange : BlockPos.getAllInBoxMutable(targetBlockPos.add(-hydration.getMaxRadius(), -1, -hydration.getMaxRadius()), targetBlockPos.add(hydration.getMaxRadius(), -1, hydration.getMaxRadius()))) {
IBlockState inRangeState = null;
if (inRange.equals(targetBlockPos)) {
inRangeState = null;
} else {
inRangeState = world.getBlockState(inRange);
}
if (inRangeState != null && hydration.doesStateMatch(inRangeState)) {
found = true;
}
}
if (found) {
this.addLineLabel(Text.of(TextColors.WHITE, "- found: ", TextColors.DARK_GREEN, "Yes"), 6);
} else {
this.addLineLabel(Text.of(TextColors.WHITE, "- found: ", TextColors.RED, "No"), 6);
this.growing = false;
// ToDo: this design only allows for ONE hydration block to be used before this breaks.
}
}
});
}
if (!message.irrigationPipe) {
// Growth stage
getGrowthStage(blockState).ifPresent(growthStage -> this.addLineLabel(this.getGenericPropertyText("Growth Stage", String.format("%d of %d", growthStage.getFirst() + 1, growthStage.getSecond() + 1))));
getGrowthStage(blockState).ifPresent(growthStage -> readyForHarvest = growthStage.getFirst() == growthStage.getSecond());
// Ground moisture
final IBlockState moistureBlockStateTarget = blockState.getBlock() instanceof BlockCrops ? world.getBlockState(targetBlockPos.down()) : blockState;
final int moistureLevel = getMoistureLevel(moistureBlockStateTarget);
// Todo: theoretically this should work.
final boolean isFertile = (moistureLevel > 0) || (hydration != null && growing);
final TextColor fertileColor = isFertile ? TextColors.DARK_GREEN : TextColors.RED;
this.addLineLabel(Text.of(TextColors.WHITE, "Soil Quality: ", fertileColor, isFertile ? "Fertile" : "Too dry"));
if (isFertile) {
final TextColor moistureColor = moistureLevel > 3 ? TextColors.DARK_GREEN : TextColors.YELLOW;
this.addLineLabel(Text.of(TextColors.WHITE, "Moisture Level: ", moistureColor, moistureLevel), 2);
} else {
this.growing = false;
}
// Biome rain
this.addLineLabel(Text.of(TextColors.WHITE, "Rain: ", message.biomeRainfall > 0.5 ? TextColors.DARK_GREEN : TextColors.GOLD, numberFormat.format(message.biomeRainfall)), 2);
}
// Ground temperature
final DoubleRange temperatureRange = getTemperatureRange(world, blockState, targetBlockPos).orElse(null);
if (temperatureRange != null) {
TextColor temperatureColor = TextColors.DARK_GREEN;
if (!MathUtil.withinRange(round(message.biomeTemperature, 2), temperatureRange.min(), temperatureRange.max())) {
if (!message.hasAdditionalLightHeatSource) {
this.growing = false;
temperatureColor = TextColors.RED;
} else {
temperatureColor = TextColors.YELLOW;
}
}
this.addLineLabel(Text.of(TextColors.WHITE, "Ground Temperature: ", temperatureColor, numberFormat.format(message.biomeTemperature)));
this.addLineLabel(this.getGenericPropertyText("Required", String.format("%s-%s", numberFormat.format(temperatureRange.min()), numberFormat.format(temperatureRange.max()))), 2);
} else {
// Is a farmland block or an irrigation pipe
this.addLineLabel(Text.of(TextColors.WHITE, "Ground Temperature: ", TextColors.DARK_GREEN, numberFormat.format(message.biomeTemperature)));
}
// Server light values, can't trust client world. lookups.
final int sunlight = message.skyLight;
final int areaLight = message.blockLight;
final int combinedLightValue = message.combinedLight;
final boolean isDaytime = message.isDaytime;
final boolean canSeeSky = message.canSeeSky;
// Area light value
final DoubleRange lightRange = getLightRange(world, blockState, targetBlockPos).orElse(null);
if (lightRange != null) {
if (!MathUtil.withinRange(combinedLightValue, lightRange.min(), lightRange.max())) {
if (// Its night time and the crop is NOT exposed to direct sunlight
!isDaytime && !canSeeSky)
this.growing = false;
}
TextColor combinedlightColor = MathUtil.withinRange(combinedLightValue, lightRange.min(), lightRange.max()) ? TextColors.DARK_GREEN : TextColors.RED;
if (!isDaytime && canSeeSky) {
// Night time and the crop IS exposed to direct sunlight.
combinedlightColor = TextColors.YELLOW;
}
this.addLineLabel(Text.of(TextColors.WHITE, "Combined Light: ", combinedlightColor, String.valueOf(combinedLightValue)));
if (!isDaytime && canSeeSky && !readyForHarvest) {
this.addLineLabel(Text.of(TextColors.GRAY, "[Night Time Growth]"), 3);
}
this.addLineLabel(this.getGenericPropertyText("Required", String.format("%s-%s", numberFormat.format(lightRange.min()), numberFormat.format(lightRange.max()))), 2);
this.addLineLabel(Text.of(TextColors.WHITE, "Sunlight: ", TextColors.YELLOW, String.valueOf(sunlight)), 4);
this.addLineLabel(Text.of(TextColors.WHITE, "Area light: ", TextColors.YELLOW, String.valueOf(areaLight)), 4);
} else {
// is farmland
this.addLineLabel(Text.of(TextColors.WHITE, "Combined Light: ", TextColors.DARK_GREEN, String.valueOf(combinedLightValue)));
}
if (!message.irrigationPipe) {
// Can Die
if (!(blockState.getBlock() instanceof BlockFarmland)) {
if (!this.readyForHarvest) {
if (String.valueOf(canRollback(blockState)).equalsIgnoreCase("true")) {
this.addLineLabel((Text.of(TextColors.WHITE, "Can Die: ", TextColors.RED, "Yes")));
canDie = true;
} else {
this.addLineLabel((Text.of(TextColors.WHITE, "Can Die: ", TextColors.DARK_GREEN, "No")));
canDie = false;
}
}
} else {
this.cropStatusLabel.setVisible(false);
}
// Harvest Tool
final String harvestTool = blockState.getBlock().getHarvestTool(blockState);
if (harvestTool != null && !harvestTool.isEmpty()) {
this.addLineLabel(this.getGenericPropertyText("Harvested by", harvestTool));
}
}
if (message.hasAdditionalLightHeatSource) {
this.addLineLabel(Text.of(TextColors.WHITE, "Special: "));
this.addLineLabel(Text.of(TextColors.YELLOW, "Heat Lamp Found!"), 4);
}
if (message.irrigationPipe) {
this.addLineLabel((Text.of(TextColors.WHITE, "Irrigation Water Range: ", TextColors.DARK_GREEN, "6")));
this.cropStatusLabel.setVisible(false);
} else {
if (message.irrigationPipeNear) {
this.addLineLabel((Text.of(TextColors.WHITE, "In-Range of Irrigation: ", TextColors.DARK_GREEN, "Yes")));
} else {
this.addLineLabel(Text.of(TextColors.WHITE, "In-Range of Irrigation: ", message.biomeRainfall > 0.5 ? TextColors.DARK_GREEN : TextColors.GOLD, "No"));
}
}
}
use of org.spongepowered.api.text.format.TextColor in project modules-extra by CubeEngine.
the class MarketSignManager method getItemText.
private Text getItemText(MarketSignData data, boolean inEditMode) {
TextColor color;
String raw;
ItemStack item = data.getItem();
color = TextColors.DARK_RED;
raw = "No Item";
if (item != null) {
color = TextColors.BLACK;
raw = item.getTranslation().get();
if (item.get(Keys.DISPLAY_NAME).isPresent()) {
color = TextColors.DARK_AQUA;
raw = item.get(Keys.DISPLAY_NAME).get().toPlain();
}
if (item.get(Keys.ITEM_LORE).isPresent() || (item.get(Keys.ITEM_ENCHANTMENTS).isPresent() && item.get(Keys.ITEM_ENCHANTMENTS).get().size() > 0)) {
color = TextColors.DARK_AQUA;
}
}
return Text.of(inEditMode ? DARK_PURPLE : color, raw);
}
use of org.spongepowered.api.text.format.TextColor in project LanternServer by LanternPowered.
the class ScoreboardIO method read.
public static Scoreboard read(Path worldFolder) throws IOException {
DataView dataView = IOHelper.<DataView>read(worldFolder.resolve(SCOREBOARD_DATA), file -> {
try {
return NbtStreamUtils.read(Files.newInputStream(file), true);
} catch (IOException e) {
throw new IOException("Unable to access " + file.getFileName() + "!", e);
}
}).orElse(null);
final Scoreboard.Builder scoreboardBuilder = Scoreboard.builder();
if (dataView == null) {
return scoreboardBuilder.build();
}
final Map<String, Objective> objectives = new HashMap<>();
dataView = dataView.getView(DATA).orElseThrow(() -> new IllegalStateException("Unable to find the data compound."));
dataView.getViewList(OBJECTIVES).ifPresent(list -> list.forEach(entry -> {
final String name = entry.getString(NAME).get();
final Text displayName = LanternTexts.fromLegacy(entry.getString(DISPLAY_NAME).get());
final Criterion criterion = Sponge.getRegistry().getType(Criterion.class, entry.getString(CRITERION_NAME).get()).orElseGet(() -> {
Lantern.getLogger().warn("Unable to find a criterion with id: {}, default to dummy.", entry.getString(CRITERION_NAME).get());
return Criteria.DUMMY;
});
final ObjectiveDisplayMode objectiveDisplayMode = Sponge.getRegistry().getType(ObjectiveDisplayMode.class, entry.getString(DISPLAY_MODE).get()).orElseGet(() -> {
Lantern.getLogger().warn("Unable to find a display mode with id: {}, default to integer.", entry.getString(CRITERION_NAME).get());
return ObjectiveDisplayModes.INTEGER;
});
objectives.put(name, Objective.builder().name(name).displayName(displayName).criterion(criterion).objectiveDisplayMode(objectiveDisplayMode).build());
}));
dataView.getViewList(SCORES).ifPresent(list -> list.forEach(entry -> {
// We have to keep all the entries to remain compatible with vanilla mc.
if (entry.getInt(INVALID).orElse(0) > 0) {
return;
}
final Text name = LanternTexts.fromLegacy(entry.getString(NAME).get());
final int value = entry.getInt(SCORE).get();
// TODO
final boolean locked = entry.getInt(LOCKED).orElse(0) > 0;
final String objectiveName = entry.getString(OBJECTIVE).get();
Score score = null;
Objective objective = objectives.get(objectiveName);
if (objective != null) {
score = addToObjective(objective, null, name, value);
}
final List<String> extraObjectives = entry.getStringList(EXTRA_OBJECTIVES).orElse(null);
if (extraObjectives != null) {
for (String extraObjective : extraObjectives) {
objective = objectives.get(extraObjective);
if (objective != null) {
score = addToObjective(objective, score, name, value);
}
}
}
}));
final List<Team> teams = new ArrayList<>();
dataView.getViewList(TEAMS).ifPresent(list -> list.forEach(entry -> {
final Team.Builder builder = Team.builder().allowFriendlyFire(entry.getInt(ALLOW_FRIENDLY_FIRE).orElse(0) > 0).canSeeFriendlyInvisibles(entry.getInt(CAN_SEE_FRIENDLY_INVISIBLES).orElse(0) > 0).name(entry.getString(NAME).get()).displayName(LanternTexts.fromLegacy(entry.getString(DISPLAY_NAME).get())).prefix(LanternTexts.fromLegacy(entry.getString(PREFIX).get())).suffix(LanternTexts.fromLegacy(entry.getString(SUFFIX).get())).members(entry.getStringList(MEMBERS).get().stream().map(LanternTexts::fromLegacy).collect(Collectors.toSet()));
entry.getString(NAME_TAG_VISIBILITY).ifPresent(value -> builder.nameTagVisibility(Sponge.getRegistry().getAllOf(Visibility.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
Lantern.getLogger().warn("Unable to find a name tag visibility with id: {}, default to always.", value);
return Visibilities.ALWAYS;
})));
entry.getString(DEATH_MESSAGE_VISIBILITY).ifPresent(value -> builder.deathTextVisibility(Sponge.getRegistry().getAllOf(Visibility.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
Lantern.getLogger().warn("Unable to find a death message visibility with id: {}, default to always.", value);
return Visibilities.ALWAYS;
})));
entry.getString(COLLISION_RULE).ifPresent(value -> builder.collisionRule(Sponge.getRegistry().getAllOf(CollisionRule.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
Lantern.getLogger().warn("Unable to find a collision rule with id: {}, default to never.", value);
return CollisionRules.NEVER;
})));
entry.getString(TEAM_COLOR).ifPresent(color -> {
TextColor textColor = Sponge.getRegistry().getType(TextColor.class, color).orElseGet(() -> {
Lantern.getLogger().warn("Unable to find a team color with id: {}, default to none.", color);
return TextColors.NONE;
});
if (textColor != TextColors.NONE && textColor != TextColors.RESET) {
builder.color(textColor);
}
});
teams.add(builder.build());
}));
final Scoreboard scoreboard = scoreboardBuilder.objectives(new ArrayList<>(objectives.values())).teams(teams).build();
dataView.getView(DISPLAY_SLOTS).ifPresent(displaySlots -> {
for (DataQuery key : displaySlots.getKeys(false)) {
final Matcher matcher = DISPLAY_SLOT_PATTERN.matcher(key.getParts().get(0));
if (matcher.matches()) {
final int internalId = Integer.parseInt(matcher.group(1));
Lantern.getRegistry().getRegistryModule(DisplaySlotRegistryModule.class).get().getByInternalId(internalId).ifPresent(slot -> {
final Objective objective = objectives.get(displaySlots.getString(key).get());
if (objective != null) {
scoreboard.updateDisplaySlot(objective, slot);
}
});
}
}
});
return scoreboard;
}
use of org.spongepowered.api.text.format.TextColor in project LanternServer by LanternPowered.
the class ScoreboardIO method write.
public static void write(Path folder, Scoreboard scoreboard) throws IOException {
final List<DataView> objectives = scoreboard.getObjectives().stream().map(objective -> DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(NAME, objective.getName()).set(DISPLAY_NAME, ((LanternObjective) objective).getLegacyDisplayName()).set(CRITERION_NAME, objective.getCriterion().getId()).set(DISPLAY_MODE, objective.getDisplayMode().getId())).collect(Collectors.toList());
final List<DataView> scores = new ArrayList<>();
for (Score score : scoreboard.getScores()) {
final Iterator<Objective> it = score.getObjectives().iterator();
final DataView baseView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(NAME, ((LanternScore) score).getLegacyName()).set(SCORE, score.getScore());
// TODO: Locked state
final DataView mainView = baseView.copy().set(OBJECTIVE, it.next().getName());
final List<String> extraObjectives = new ArrayList<>();
while (it.hasNext()) {
final String extraObjectiveName = it.next().getName();
scores.add(baseView.copy().set(OBJECTIVE, extraObjectiveName).set(INVALID, (byte) 1));
extraObjectives.add(extraObjectiveName);
}
if (!extraObjectives.isEmpty()) {
mainView.set(EXTRA_OBJECTIVES, extraObjectives);
}
}
final List<DataView> teams = new ArrayList<>();
for (Team team : scoreboard.getTeams()) {
final DataView container = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(ALLOW_FRIENDLY_FIRE, (byte) (team.allowFriendlyFire() ? 1 : 0)).set(CAN_SEE_FRIENDLY_INVISIBLES, (byte) (team.canSeeFriendlyInvisibles() ? 1 : 0)).set(NAME_TAG_VISIBILITY, team.getNameTagVisibility().getName()).set(NAME, team.getName()).set(DISPLAY_NAME, ((LanternTeam) team).getLegacyDisplayName()).set(DEATH_MESSAGE_VISIBILITY, team.getDeathMessageVisibility().getName()).set(COLLISION_RULE, team.getCollisionRule().getName()).set(PREFIX, ((LanternTeam) team).getLegacyPrefix()).set(SUFFIX, ((LanternTeam) team).getLegacySuffix());
final TextColor teamColor = team.getColor();
if (teamColor != TextColors.NONE) {
container.set(TEAM_COLOR, teamColor.getId());
}
final Set<Text> members = team.getMembers();
container.set(MEMBERS, members.stream().map(LanternTexts::toLegacy).collect(Collectors.toList()));
teams.add(container);
}
final DataContainer rootDataContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
final DataView dataView = rootDataContainer.createView(DATA).set(OBJECTIVES, objectives).set(SCORES, scores).set(TEAMS, teams);
final DataView displaySlots = dataView.createView(DISPLAY_SLOTS);
((LanternScoreboard) scoreboard).getObjectivesInSlot().entrySet().forEach(entry -> displaySlots.set(DataQuery.of("slot_" + ((LanternDisplaySlot) entry.getKey()).getInternalId()), entry.getValue().getName()));
IOHelper.write(folder.resolve(SCOREBOARD_DATA), file -> {
NbtStreamUtils.write(rootDataContainer, Files.newOutputStream(file), true);
return true;
});
}
Aggregations