Completely refactor the GUI code.

All direct references to a gui have been replaced by a field, allowing dynamic GUI assignment throughout the code (necessary for eg. network play). Fixes almost all errors. Untested.
This commit is contained in:
elcnesh
2014-09-04 09:44:31 +00:00
parent 1a9b54cdd4
commit 89b3395cec
128 changed files with 3332 additions and 2899 deletions

5
.gitattributes vendored
View File

@@ -716,6 +716,7 @@ forge-gui-desktop/src/main/html/js/jquery/jquery-1.9.1.js -text
forge-gui-desktop/src/main/html/js/jquery/jquery-1.9.1.min.js -text forge-gui-desktop/src/main/html/js/jquery/jquery-1.9.1.min.js -text
forge-gui-desktop/src/main/html/js/observable.js -text forge-gui-desktop/src/main/html/js/observable.js -text
forge-gui-desktop/src/main/html/js/socket.js -text forge-gui-desktop/src/main/html/js/socket.js -text
forge-gui-desktop/src/main/java/forge/GuiBase.java -text
forge-gui-desktop/src/main/java/forge/GuiDesktop.java -text forge-gui-desktop/src/main/java/forge/GuiDesktop.java -text
forge-gui-desktop/src/main/java/forge/ImageCache.java -text forge-gui-desktop/src/main/java/forge/ImageCache.java -text
forge-gui-desktop/src/main/java/forge/ImageLoader.java -text forge-gui-desktop/src/main/java/forge/ImageLoader.java -text
@@ -16643,7 +16644,6 @@ forge-gui/src/main/html/js/jquery/jquery-1.9.1.min.js -text
forge-gui/src/main/html/js/observable.js -text forge-gui/src/main/html/js/observable.js -text
forge-gui/src/main/html/js/socket.js -text forge-gui/src/main/html/js/socket.js -text
forge-gui/src/main/java/forge/FThreads.java -text forge-gui/src/main/java/forge/FThreads.java -text
forge-gui/src/main/java/forge/GuiBase.java -text
forge-gui/src/main/java/forge/UiCommand.java svneol=native#text/plain forge-gui/src/main/java/forge/UiCommand.java svneol=native#text/plain
forge-gui/src/main/java/forge/assets/FSkinProp.java -text forge-gui/src/main/java/forge/assets/FSkinProp.java -text
forge-gui/src/main/java/forge/assets/ISkinImage.java -text forge-gui/src/main/java/forge/assets/ISkinImage.java -text
@@ -16719,7 +16719,6 @@ forge-gui/src/main/java/forge/limited/WinstonDraft.java -text
forge-gui/src/main/java/forge/limited/WinstonDraftAI.java -text forge-gui/src/main/java/forge/limited/WinstonDraftAI.java -text
forge-gui/src/main/java/forge/limited/package-info.java svneol=native#text/plain forge-gui/src/main/java/forge/limited/package-info.java svneol=native#text/plain
forge-gui/src/main/java/forge/match/MatchConstants.java -text forge-gui/src/main/java/forge/match/MatchConstants.java -text
forge-gui/src/main/java/forge/match/MatchUtil.java -text
forge-gui/src/main/java/forge/match/input/ButtonUtil.java -text forge-gui/src/main/java/forge/match/input/ButtonUtil.java -text
forge-gui/src/main/java/forge/match/input/Input.java -text forge-gui/src/main/java/forge/match/input/Input.java -text
forge-gui/src/main/java/forge/match/input/InputAttack.java -text forge-gui/src/main/java/forge/match/input/InputAttack.java -text
@@ -16758,6 +16757,7 @@ forge-gui/src/main/java/forge/player/HumanPlay.java -text
forge-gui/src/main/java/forge/player/HumanPlaySpellAbility.java -text forge-gui/src/main/java/forge/player/HumanPlaySpellAbility.java -text
forge-gui/src/main/java/forge/player/LobbyPlayerHuman.java -text forge-gui/src/main/java/forge/player/LobbyPlayerHuman.java -text
forge-gui/src/main/java/forge/player/PlayerControllerHuman.java -text forge-gui/src/main/java/forge/player/PlayerControllerHuman.java -text
forge-gui/src/main/java/forge/player/PlayerControllerLocal.java -text
forge-gui/src/main/java/forge/player/TargetSelection.java -text forge-gui/src/main/java/forge/player/TargetSelection.java -text
forge-gui/src/main/java/forge/player/package-info.java -text forge-gui/src/main/java/forge/player/package-info.java -text
forge-gui/src/main/java/forge/properties/ForgeConstants.java -text forge-gui/src/main/java/forge/properties/ForgeConstants.java -text
@@ -16837,7 +16837,6 @@ forge-gui/src/main/java/forge/util/IgnoringXStream.java -text
forge-gui/src/main/java/forge/util/LineReader.java -text forge-gui/src/main/java/forge/util/LineReader.java -text
forge-gui/src/main/java/forge/util/MultiplexOutputStream.java svneol=native#text/plain forge-gui/src/main/java/forge/util/MultiplexOutputStream.java svneol=native#text/plain
forge-gui/src/main/java/forge/util/OperatingSystem.java -text forge-gui/src/main/java/forge/util/OperatingSystem.java -text
forge-gui/src/main/java/forge/util/WaitCallback.java -text
forge-gui/src/main/java/forge/util/XmlUtil.java -text forge-gui/src/main/java/forge/util/XmlUtil.java -text
forge-gui/src/main/java/forge/util/gui/SGuiChoose.java -text forge-gui/src/main/java/forge/util/gui/SGuiChoose.java -text
forge-gui/src/main/java/forge/util/gui/SGuiDialog.java -text forge-gui/src/main/java/forge/util/gui/SGuiDialog.java -text

View File

@@ -21,6 +21,7 @@ import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import forge.StaticData; import forge.StaticData;
import forge.card.CardDb.SetPreference; import forge.card.CardDb.SetPreference;
import forge.deck.CardPool; import forge.deck.CardPool;
@@ -30,9 +31,11 @@ import forge.util.Aggregates;
import forge.util.FileSection; import forge.util.FileSection;
import forge.util.FileUtil; import forge.util.FileUtil;
import forge.util.IItemReader; import forge.util.IItemReader;
import forge.util.MyRandom;
import forge.util.storage.StorageBase; import forge.util.storage.StorageBase;
import forge.util.storage.StorageReaderBase; import forge.util.storage.StorageReaderBase;
import forge.util.storage.StorageReaderFolder; import forge.util.storage.StorageReaderFolder;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.io.File; import java.io.File;
@@ -484,4 +487,19 @@ public final class CardEdition implements Comparable<CardEdition> { // immutable
}; };
}; };
} }
public static int getRandomFoil(final String setCode) {
FoilType foilType = FoilType.NOT_SUPPORTED;
if (setCode != null
&& StaticData.instance().getEditions().get(setCode) != null) {
foilType = StaticData.instance().getEditions().get(setCode)
.getFoilType();
}
if (foilType != FoilType.NOT_SUPPORTED) {
return foilType == FoilType.MODERN
? MyRandom.getRandom().nextInt(9) + 1
: MyRandom.getRandom().nextInt(9) + 11;
}
return 0;
}
} }

View File

@@ -23,13 +23,10 @@ import forge.game.io.GameStateDeserializer;
import forge.game.io.GameStateSerializer; import forge.game.io.GameStateSerializer;
import forge.game.io.IGameStateObject; import forge.game.io.IGameStateObject;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Observable; import java.util.Observable;
/** /**
* <p> * <p>
* GameLog class. * GameLog class.
@@ -64,7 +61,6 @@ public class GameLog extends Observable implements IGameStateObject {
* Instantiates a new game log. * Instantiates a new game log.
*/ */
public GameLog() { public GameLog() {
} }
/** /**
@@ -84,11 +80,6 @@ public class GameLog extends Observable implements IGameStateObject {
this.notifyObservers(); this.notifyObservers();
} }
public String getLogText(final GameLogEntryType logLevel) {
List<GameLogEntry> filteredAndReversed = getLogEntries(logLevel);
return StringUtils.join(filteredAndReversed, "\r\n");
}
/** /**
* Gets the log entries below a certain level as a list. * Gets the log entries below a certain level as a list.
* *

View File

@@ -1,6 +1,8 @@
package forge.game.ability.effects; package forge.game.ability.effects;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import forge.game.GameEntity;
import forge.game.GameObject; import forge.game.GameObject;
import forge.game.ability.SpellAbilityEffect; import forge.game.ability.SpellAbilityEffect;
import forge.game.player.Player; import forge.game.player.Player;
@@ -9,6 +11,7 @@ import forge.game.spellability.SpellAbilityStackInstance;
import forge.game.spellability.TargetChoices; import forge.game.spellability.TargetChoices;
import forge.game.zone.MagicStack; import forge.game.zone.MagicStack;
import forge.util.Aggregates; import forge.util.Aggregates;
import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
@@ -87,8 +90,8 @@ public class ChangeTargetsEffect extends SpellAbilityEffect {
SpellAbility changingTgtSA = changingTgtSI.getSpellAbility(); SpellAbility changingTgtSA = changingTgtSI.getSpellAbility();
if (sa.hasParam("RandomTarget")){ if (sa.hasParam("RandomTarget")){
changingTgtSA.resetTargets(); changingTgtSA.resetTargets();
List<GameObject> candidates = changingTgtSA.getTargetRestrictions().getAllCandidates(changingTgtSA, true); List<GameEntity> candidates = changingTgtSA.getTargetRestrictions().getAllCandidates(changingTgtSA, true);
GameObject choice = Aggregates.random(candidates); GameEntity choice = Aggregates.random(candidates);
changingTgtSA.getTargets().add(choice); changingTgtSA.getTargets().add(choice);
changingTgtSI.updateTarget(changingTgtSA.getTargets()); changingTgtSI.updateTarget(changingTgtSA.getTargets());
} else if (sa.hasParam("DefinedMagnet")){ } else if (sa.hasParam("DefinedMagnet")){

View File

@@ -1,7 +1,8 @@
package forge.game.ability.effects; package forge.game.ability.effects;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import forge.game.GameObject;
import forge.game.GameEntity;
import forge.game.ability.AbilityUtils; import forge.game.ability.AbilityUtils;
import forge.game.ability.SpellAbilityEffect; import forge.game.ability.SpellAbilityEffect;
import forge.game.card.Card; import forge.game.card.Card;
@@ -94,7 +95,7 @@ public class CopySpellAbilityEffect extends SpellAbilityEffect {
if (targetedSA == null) { if (targetedSA == null) {
return; return;
} }
List<GameObject> candidates = targetedSA.getTargetRestrictions().getAllCandidates(targetedSA, true); final List<GameEntity> candidates = targetedSA.getTargetRestrictions().getAllCandidates(targetedSA, true);
if (sa.hasParam("CanTargetPlayer")) { if (sa.hasParam("CanTargetPlayer")) {
// Radiate // Radiate
// Remove targeted players because getAllCandidates include all the valid players // Remove targeted players because getAllCandidates include all the valid players
@@ -102,7 +103,7 @@ public class CopySpellAbilityEffect extends SpellAbilityEffect {
candidates.remove(p); candidates.remove(p);
mayChoseNewTargets = false; mayChoseNewTargets = false;
for (GameObject o : candidates) { for (GameEntity o : candidates) {
SpellAbility copy = CardFactory.copySpellAbilityAndSrcCard(card, chosenSA.getHostCard(), chosenSA, true); SpellAbility copy = CardFactory.copySpellAbilityAndSrcCard(card, chosenSA.getHostCard(), chosenSA, true);
copy.resetFirstTarget(o, targetedSA); copy.resetFirstTarget(o, targetedSA);
copies.add(copy); copies.add(copy);
@@ -110,7 +111,7 @@ public class CopySpellAbilityEffect extends SpellAbilityEffect {
} else {// Precursor Golem, Ink-Treader Nephilim } else {// Precursor Golem, Ink-Treader Nephilim
final String type = sa.getParam("CopyForEachCanTarget"); final String type = sa.getParam("CopyForEachCanTarget");
List<Card> valid = new ArrayList<Card>(); List<Card> valid = new ArrayList<Card>();
for (final Object o : candidates) { for (final GameEntity o : candidates) {
if (o instanceof Card) { if (o instanceof Card) {
valid.add((Card) o); valid.add((Card) o);
} }

View File

@@ -58,7 +58,6 @@ import forge.item.PaperCard;
import forge.util.CollectionSuppliers; import forge.util.CollectionSuppliers;
import forge.util.Expressions; import forge.util.Expressions;
import forge.util.Lang; import forge.util.Lang;
import forge.util.MyRandom;
import forge.util.TextUtil; import forge.util.TextUtil;
import forge.util.maps.HashMapOfLists; import forge.util.maps.HashMapOfLists;
import forge.util.maps.MapOfLists; import forge.util.maps.MapOfLists;
@@ -1632,29 +1631,15 @@ public class Card extends GameEntity implements Comparable<Card> {
} }
/** /**
* * @return a {@link ColorSet}.
* TODO Write javadoc for this method. * @see CardCharacteristics#determineColor()
*
* @param globalChanges
* an ArrayList<CardColor>
* @return a CardColor
*/ */
public final ColorSet determineColor() { public final ColorSet determineColor() {
if (this.isImmutable()) { if (this.isImmutable()) {
return ColorSet.getNullColor(); return ColorSet.getNullColor();
} }
List<CardColor> colorList = this.getCharacteristics().getCardColor(); return this.getCharacteristics().determineColor();
byte colors = 0;
for (int i = colorList.size() - 1;i >= 0;i--) {
final CardColor cc = colorList.get(i);
colors |= cc.getColorMask();
if (!cc.isAdditional()) {
return ColorSet.fromMask(colors);
}
}
return ColorSet.fromMask(colors);
} }
/** /**
@@ -8244,13 +8229,7 @@ public class Card extends GameEntity implements Comparable<Card> {
* removed. * removed.
*/ */
public final void setRandomFoil() { public final void setRandomFoil() {
CardEdition.FoilType foilType = CardEdition.FoilType.NOT_SUPPORTED; this.setFoil(CardEdition.getRandomFoil(this.getCurSetCode()));
if (this.getCurSetCode() != null && StaticData.instance().getEditions().get(this.getCurSetCode()) != null) {
foilType = StaticData.instance().getEditions().get(this.getCurSetCode()).getFoilType();
}
if (foilType != CardEdition.FoilType.NOT_SUPPORTED) {
this.setFoil(foilType == CardEdition.FoilType.MODERN ? MyRandom.getRandom().nextInt(9) + 1 : MyRandom.getRandom().nextInt(9) + 11);
}
} }
/** /**

View File

@@ -18,8 +18,10 @@
package forge.game.card; package forge.game.card;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import forge.card.CardEdition; import forge.card.CardEdition;
import forge.card.CardRarity; import forge.card.CardRarity;
import forge.card.ColorSet;
import forge.card.mana.ManaCost; import forge.card.mana.ManaCost;
import forge.game.replacement.ReplacementEffect; import forge.game.replacement.ReplacementEffect;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
@@ -432,7 +434,6 @@ public class CardCharacteristics {
} }
} }
public CardRarity getRarity() { public CardRarity getRarity() {
return rarity; return rarity;
} }
@@ -452,4 +453,22 @@ public class CardCharacteristics {
this.curSetCode = curSetCode; this.curSetCode = curSetCode;
} }
/**
* Determine the colors.
*
* @return a {@link ColorSet}.
*/
public final ColorSet determineColor() {
final List<CardColor> colorList = this.getCardColor();
byte colors = 0;
for (int i = colorList.size() - 1;i >= 0;i--) {
final CardColor cc = colorList.get(i);
colors |= cc.getColorMask();
if (!cc.isAdditional()) {
return ColorSet.fromMask(colors);
}
}
return ColorSet.fromMask(colors);
}
} }

View File

@@ -3,6 +3,7 @@ package forge.game.player;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import forge.LobbyPlayer; import forge.LobbyPlayer;
import forge.card.ColorSet; import forge.card.ColorSet;
@@ -38,12 +39,10 @@ import org.apache.commons.lang3.tuple.Pair;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
* A prototype for player controller class * A prototype for player controller class
* *
@@ -83,11 +82,11 @@ public abstract class PlayerController {
} }
/** /**
* Automatically pass priority until reaching the given phase of the current turn * Automatically pass priority until reaching the Cleanup phase of the
* @param phase * current turn.
*/ */
public void autoPassUntil(PhaseType phase) { public void autoPassUntilEndOfTurn() {
autoPassUntilPhase = phase; autoPassUntilPhase = PhaseType.CLEANUP;
} }
protected PhaseType getAutoPassUntilPhase() { protected PhaseType getAutoPassUntilPhase() {
@@ -118,14 +117,14 @@ public abstract class PlayerController {
} }
// Abilities to auto-yield to // Abilities to auto-yield to
private Set<String> autoYields = new HashSet<String>(); private final Set<String> autoYields = Sets.newHashSet();
public Iterable<String> getAutoYields() { public Iterable<String> getAutoYields() {
return autoYields; return autoYields;
} }
public boolean shouldAutoYield(String key) { public boolean shouldAutoYield(final String key) {
return autoYields.contains(key); return autoYields.contains(key);
} }
public void setShouldAutoYield(String key, boolean autoYield) { public void setShouldAutoYield(final String key, final boolean autoYield) {
if (autoYield) { if (autoYield) {
autoYields.add(key); autoYields.add(key);
} }

View File

@@ -17,21 +17,22 @@
*/ */
package forge.game.spellability; package forge.game.spellability;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Lists;
import forge.card.CardType; import forge.card.CardType;
import forge.game.Game; import forge.game.Game;
import forge.game.GameObject; import forge.game.GameEntity;
import forge.game.ability.AbilityUtils; import forge.game.ability.AbilityUtils;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/** /**
* <p> * <p>
* Target class. * Target class.
@@ -473,9 +474,9 @@ public class TargetRestrictions {
* Check Valid Candidates and Targeting * Check Valid Candidates and Targeting
* @return a List<Object>. * @return a List<Object>.
*/ */
public final List<GameObject> getAllCandidates(final SpellAbility sa, final boolean isTargeted) { public final List<GameEntity> getAllCandidates(final SpellAbility sa, final boolean isTargeted) {
final Game game = sa.getActivatingPlayer().getGame(); final Game game = sa.getActivatingPlayer().getGame();
List<GameObject> candidates = new ArrayList<GameObject>(); final List<GameEntity> candidates = Lists.newArrayList();
for (Player player : game.getPlayers()) { for (Player player : game.getPlayers()) {
if (sa.canTarget(player)) { if (sa.canTarget(player)) {
candidates.add(player); candidates.add(player);

View File

@@ -36,7 +36,7 @@ import forge.game.Match;
import forge.game.phase.PhaseType; import forge.game.phase.PhaseType;
import forge.game.player.IHasIcon; import forge.game.player.IHasIcon;
import forge.game.player.RegisteredPlayer; import forge.game.player.RegisteredPlayer;
import forge.game.spellability.SpellAbility; //import forge.game.spellability.SpellAbility;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import forge.gui.BoxedProductCardListViewer; import forge.gui.BoxedProductCardListViewer;
import forge.gui.CardListViewer; import forge.gui.CardListViewer;
@@ -79,6 +79,7 @@ import forge.view.CombatView;
import forge.view.GameEntityView; import forge.view.GameEntityView;
import forge.view.IGameView; import forge.view.IGameView;
import forge.view.PlayerView; import forge.view.PlayerView;
import forge.view.SpellAbilityView;
public class GuiDesktop implements IGuiBase { public class GuiDesktop implements IGuiBase {
@@ -153,7 +154,7 @@ public class GuiDesktop implements IGuiBase {
@Override @Override
public int showCardOptionDialog(final CardView card, String message, String title, FSkinProp skinIcon, String[] options, int defaultOption) { public int showCardOptionDialog(final CardView card, String message, String title, FSkinProp skinIcon, String[] options, int defaultOption) {
if (card != null) { if (card != null) {
FThreads.invokeInEdtAndWait(new Runnable() { FThreads.invokeInEdtAndWait(GuiBase.getInterface(), new Runnable() {
@Override @Override
public void run() { public void run() {
GuiBase.getInterface().setCard(card); GuiBase.getInterface().setCard(card);
@@ -213,7 +214,7 @@ public class GuiDesktop implements IGuiBase {
public void focusButton(final IButton button) { public void focusButton(final IButton button) {
// ensure we don't steal focus from an overlay // ensure we don't steal focus from an overlay
if (!SOverlayUtils.overlayHasFocus()) { if (!SOverlayUtils.overlayHasFocus()) {
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(GuiBase.getInterface(), new Runnable() {
@Override @Override
public void run() { public void run() {
((FButton)button).requestFocusInWindow(); ((FButton)button).requestFocusInWindow();
@@ -294,7 +295,7 @@ public class GuiDesktop implements IGuiBase {
} }
@Override @Override
public SpellAbility getAbilityToPlay(List<SpellAbility> abilities, ITriggerEvent triggerEvent) { public SpellAbilityView getAbilityToPlay(List<SpellAbilityView> abilities, ITriggerEvent triggerEvent) {
if (triggerEvent == null) { if (triggerEvent == null) {
if (abilities.isEmpty()) { if (abilities.isEmpty()) {
return null; return null;
@@ -308,7 +309,7 @@ public class GuiDesktop implements IGuiBase {
if (abilities.isEmpty()) { if (abilities.isEmpty()) {
return null; return null;
} }
if (abilities.size() == 1 && !abilities.get(0).promptIfOnlyPossibleAbility()) { if (abilities.size() == 1 && !abilities.get(0).isPromptIfOnlyPossibleAbility()) {
if (abilities.get(0).canPlay()) { if (abilities.get(0).canPlay()) {
return abilities.get(0); //only return ability if it's playable, otherwise return null return abilities.get(0); //only return ability if it's playable, otherwise return null
} }
@@ -321,7 +322,7 @@ public class GuiDesktop implements IGuiBase {
boolean enabled; boolean enabled;
boolean hasEnabled = false; boolean hasEnabled = false;
int shortcut = KeyEvent.VK_1; //use number keys as shortcuts for abilities 1-9 int shortcut = KeyEvent.VK_1; //use number keys as shortcuts for abilities 1-9
for (final SpellAbility ab : abilities) { for (final SpellAbilityView ab : abilities) {
enabled = ab.canPlay(); enabled = ab.canPlay();
if (enabled) { if (enabled) {
hasEnabled = true; hasEnabled = true;
@@ -451,7 +452,7 @@ public class GuiDesktop implements IGuiBase {
} }
@Override @Override
public void refreshCardDetails(final Collection<CardView> cards) { public void refreshCardDetails(final Iterable<CardView> cards) {
CMatchUI.SINGLETON_INSTANCE.refreshCardDetails(cards); CMatchUI.SINGLETON_INSTANCE.refreshCardDetails(cards);
} }

View File

@@ -199,7 +199,7 @@ public class ImageCache {
* Returns the Image corresponding to the key. * Returns the Image corresponding to the key.
*/ */
private static BufferedImage getImage(final String key) { private static BufferedImage getImage(final String key) {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
try { try {
return ImageCache._CACHE.get(key); return ImageCache._CACHE.get(key);
} catch (final ExecutionException ex) { } catch (final ExecutionException ex) {

View File

@@ -19,6 +19,8 @@ package forge;
import forge.control.FControl; import forge.control.FControl;
import forge.model.FModel; import forge.model.FModel;
import forge.properties.ForgeConstants;
import forge.properties.ForgeProfileProperties;
import forge.view.FView; import forge.view.FView;
/** /**
@@ -37,7 +39,7 @@ public final class Singletons {
public static FControl getControl() { return control; } public static FControl getControl() { return control; }
public static void initializeOnce(boolean withUi) { public static void initializeOnce(boolean withUi) {
FThreads.assertExecutedByEdt(false); FThreads.assertExecutedByEdt(GuiBase.getInterface(), false);
synchronized (Singletons.class) { synchronized (Singletons.class) {
if (initialized) { if (initialized) {
@@ -46,11 +48,14 @@ public final class Singletons {
initialized = true; initialized = true;
} }
ForgeConstants.init(GuiBase.getInterface());
ForgeProfileProperties.init(GuiBase.getInterface());
if (withUi) { if (withUi) {
view = FView.SINGLETON_INSTANCE; view = FView.SINGLETON_INSTANCE;
} }
FModel.initialize(view == null ? null : view.getSplash().getProgressBar()); FModel.initialize(GuiBase.getInterface(), view == null ? null : view.getSplash().getProgressBar());
if (withUi) { if (withUi) {
control = FControl.instance; control = FControl.instance;

View File

@@ -51,6 +51,7 @@ import forge.game.GameRules;
import forge.game.GameType; import forge.game.GameType;
import forge.game.Match; import forge.game.Match;
import forge.game.player.Player; import forge.game.player.Player;
//import forge.game.player.Player;
import forge.game.player.RegisteredPlayer; import forge.game.player.RegisteredPlayer;
import forge.gui.GuiDialog; import forge.gui.GuiDialog;
import forge.gui.SOverlayUtils; import forge.gui.SOverlayUtils;
@@ -66,6 +67,8 @@ import forge.menus.ForgeMenu;
import forge.model.FModel; import forge.model.FModel;
import forge.player.GamePlayerUtil; import forge.player.GamePlayerUtil;
import forge.player.LobbyPlayerHuman; import forge.player.LobbyPlayerHuman;
import forge.player.PlayerControllerHuman;
import forge.player.PlayerControllerLocal;
import forge.properties.ForgeConstants; import forge.properties.ForgeConstants;
import forge.properties.ForgePreferences; import forge.properties.ForgePreferences;
import forge.properties.ForgePreferences.FPref; import forge.properties.ForgePreferences.FPref;
@@ -122,7 +125,7 @@ public enum FControl implements KeyEventDispatcher {
EXIT_FORGE EXIT_FORGE
} }
private final SoundSystem soundSystem = new SoundSystem(); private final SoundSystem soundSystem = new SoundSystem(GuiBase.getInterface());
/** /**
* <p> * <p>
@@ -190,10 +193,10 @@ public enum FControl implements KeyEventDispatcher {
public boolean canExitForge(boolean forRestart) { public boolean canExitForge(boolean forRestart) {
String action = (forRestart ? "Restart" : "Exit"); String action = (forRestart ? "Restart" : "Exit");
String userPrompt = "Are you sure you wish to " + (forRestart ? "restart" : "exit") + " Forge?"; String userPrompt = "Are you sure you wish to " + (forRestart ? "restart" : "exit") + " Forge?";
if (this.game != null) { if (this.gameView != null) {
userPrompt = "A game is currently active. " + userPrompt; userPrompt = "A game is currently active. " + userPrompt;
} }
if (!FOptionPane.showConfirmDialog(userPrompt, action + " Forge", action, "Cancel", this.game == null)) { //default Yes if no game active if (!FOptionPane.showConfirmDialog(userPrompt, action + " Forge", action, "Cancel", this.gameView == null)) { //default Yes if no game active
return false; return false;
} }
if (!CDeckEditorUI.SINGLETON_INSTANCE.canSwitchAway(true)) { if (!CDeckEditorUI.SINGLETON_INSTANCE.canSwitchAway(true)) {
@@ -385,11 +388,6 @@ public enum FControl implements KeyEventDispatcher {
private IGameView gameView; private IGameView gameView;
private boolean gameHasHumanPlayer; private boolean gameHasHumanPlayer;
@Deprecated
public Game getObservedGame() {
return game;
}
public IGameView getGameView() { public IGameView getGameView() {
return this.gameView; return this.gameView;
} }
@@ -443,22 +441,24 @@ public enum FControl implements KeyEventDispatcher {
} }
public final void startGameWithUi(final Match match) { public final void startGameWithUi(final Match match) {
if (this.game != null) { if (this.gameView != null) {
this.setCurrentScreen(FScreen.MATCH_SCREEN); this.setCurrentScreen(FScreen.MATCH_SCREEN);
SOverlayUtils.hideOverlay(); SOverlayUtils.hideOverlay();
FOptionPane.showMessageDialog("Cannot start a new game while another game is already in progress."); FOptionPane.showMessageDialog("Cannot start a new game while another game is already in progress.");
return; //TODO: See if it's possible to run multiple games at once without crashing return; //TODO: See if it's possible to run multiple games at once without crashing
} }
setPlayerName(match.getPlayers()); setPlayerName(match.getPlayers());
this.game = match.createGame(); final Game game = match.createGame();
final LobbyPlayer me = getGuiPlayer(); final LobbyPlayer me = getGuiPlayer();
for (final Player p : this.game.getPlayers()) { for (final Player p : game.getPlayers()) {
if (p.getLobbyPlayer().equals(me)) { if (p.getLobbyPlayer().equals(me)) {
this.gameView = (IGameView) p.getController(); this.gameView = (IGameView) p.getController();
fcVisitor = new FControlGameEventHandler((PlayerControllerHuman) p.getController());
break; break;
} }
} }
inputQueue = new InputQueue(GuiBase.getInterface(), game);
attachToGame(this.gameView); attachToGame(this.gameView);
// It's important to run match in a different thread to allow GUI inputs to be invoked from inside game. // It's important to run match in a different thread to allow GUI inputs to be invoked from inside game.
@@ -473,14 +473,15 @@ public enum FControl implements KeyEventDispatcher {
} }
public final void endCurrentGame() { public final void endCurrentGame() {
if (this.game == null) { return; } if (this.gameView == null) { return; }
Singletons.getView().getNavigationBar().closeTab(FScreen.MATCH_SCREEN); Singletons.getView().getNavigationBar().closeTab(FScreen.MATCH_SCREEN);
this.game = null; this.game = null;
this.gameView = null;
} }
private final FControlGameEventHandler fcVisitor = new FControlGameEventHandler(); private FControlGameEventHandler fcVisitor;
private final FControlGamePlayback playbackControl = new FControlGamePlayback(); private FControlGamePlayback playbackControl;// = new FControlGamePlayback();
private void attachToGame(final IGameView game0) { private void attachToGame(final IGameView game0) {
if (game0.getGameType().equals(GameType.Quest)) { if (game0.getGameType().equals(GameType.Quest)) {
QuestController qc = FModel.getQuest(); QuestController qc = FModel.getQuest();
@@ -491,8 +492,6 @@ public enum FControl implements KeyEventDispatcher {
game0.subscribeToEvents(qc); // this one listens to player's mulligans ATM game0.subscribeToEvents(qc); // this one listens to player's mulligans ATM
} }
inputQueue = new InputQueue();
game0.subscribeToEvents(Singletons.getControl().getSoundSystem()); game0.subscribeToEvents(Singletons.getControl().getSoundSystem());
//switch back to match screen music //switch back to match screen music
@@ -531,6 +530,11 @@ public enum FControl implements KeyEventDispatcher {
// Add playback controls to match if needed // Add playback controls to match if needed
if (localPlayer != null) { if (localPlayer != null) {
// Create dummy controller
final PlayerControllerHuman controller =
new PlayerControllerLocal(game, null, humanLobbyPlayer, GuiBase.getInterface());
playbackControl = new FControlGamePlayback(controller);
playbackControl.setGame(game);
game0.subscribeToEvents(playbackControl); game0.subscribeToEvents(playbackControl);
} }
@@ -590,7 +594,7 @@ public enum FControl implements KeyEventDispatcher {
boolean isPlayerOneHuman = players.get(0).getPlayer() instanceof LobbyPlayerHuman; boolean isPlayerOneHuman = players.get(0).getPlayer() instanceof LobbyPlayerHuman;
boolean isPlayerTwoComputer = players.get(1).getPlayer() instanceof LobbyPlayerAi; boolean isPlayerTwoComputer = players.get(1).getPlayer() instanceof LobbyPlayerAi;
if (isPlayerOneHuman && isPlayerTwoComputer) { if (isPlayerOneHuman && isPlayerTwoComputer) {
GamePlayerUtil.setPlayerName(); GamePlayerUtil.setPlayerName(GuiBase.getInterface());
} }
} }
} }
@@ -616,7 +620,7 @@ public enum FControl implements KeyEventDispatcher {
final Match mc = new Match(rules, players); final Match mc = new Match(rules, players);
SOverlayUtils.startGameOverlay(); SOverlayUtils.startGameOverlay();
SOverlayUtils.showOverlay(); SOverlayUtils.showOverlay();
FThreads.invokeInEdtLater(new Runnable(){ FThreads.invokeInEdtLater(GuiBase.getInterface(), new Runnable(){
@Override @Override
public void run() { public void run() {
startGameWithUi(mc); startGameWithUi(mc);
@@ -740,7 +744,7 @@ public enum FControl implements KeyEventDispatcher {
return player; return player;
} }
private final LobbyPlayer guiPlayer = new LobbyPlayerHuman("Human"); private final LobbyPlayer guiPlayer = new LobbyPlayerHuman("Human", GuiBase.getInterface());
public final LobbyPlayer getGuiPlayer() { public final LobbyPlayer getGuiPlayer() {
return guiPlayer; return guiPlayer;
} }

View File

@@ -1,6 +1,7 @@
package forge.deckchooser; package forge.deckchooser;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.deck.ColorDeckGenerator; import forge.deck.ColorDeckGenerator;
import forge.deck.Deck; import forge.deck.Deck;
@@ -50,7 +51,7 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
//Show dialog to select a deck //Show dialog to select a deck
public static Deck promptForDeck(String title, DeckType defaultDeckType, boolean forAi) { public static Deck promptForDeck(String title, DeckType defaultDeckType, boolean forAi) {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
final FDeckChooser chooser = new FDeckChooser(forAi); final FDeckChooser chooser = new FDeckChooser(forAi);
chooser.initialize(defaultDeckType); chooser.initialize(defaultDeckType);
chooser.populate(); chooser.populate();
@@ -130,7 +131,7 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
"White", "Blue", "Black", "Red", "Green" }; "White", "Blue", "Black", "Red", "Green" };
ArrayList<DeckProxy> decks = new ArrayList<DeckProxy>(); ArrayList<DeckProxy> decks = new ArrayList<DeckProxy>();
for (int i = 0; i < colors.length; i++) { for (int i = 0; i < colors.length; i++) {
decks.add(new ColorDeckGenerator(colors[i], i, lstDecks, isAi)); decks.add(new ColorDeckGenerator(GuiBase.getInterface(), colors[i], i, lstDecks, isAi));
} }
lstDecks.setPool(decks); lstDecks.setPool(decks);

View File

@@ -19,6 +19,7 @@ package forge.download;
import java.net.Proxy; import java.net.Proxy;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.gui.SOverlayUtils; import forge.gui.SOverlayUtils;
@@ -95,7 +96,7 @@ public class GuiDownloader extends DefaultBoundedRangeModel {
pnl.add(pnlDialog, "w 400px!, h 350px!, ax center, ay center"); pnl.add(pnlDialog, "w 400px!, h 350px!, ax center, ay center");
SOverlayUtils.showOverlay(); SOverlayUtils.showOverlay();
service.initialize(txtAddress, txtPort, progressBar, btnStart, cmdClose, null, new Runnable() { service.initialize(GuiBase.getInterface(), txtAddress, txtPort, progressBar, btnStart, cmdClose, null, new Runnable() {
@Override @Override
public void run() { public void run() {
fireStateChanged(); fireStateChanged();

View File

@@ -17,6 +17,7 @@
*/ */
package forge.error; package forge.error;
import forge.GuiBase;
import forge.gui.WrapLayout; import forge.gui.WrapLayout;
import forge.toolbox.FHyperlink; import forge.toolbox.FHyperlink;
import forge.toolbox.FLabel; import forge.toolbox.FLabel;
@@ -92,7 +93,7 @@ public class BugReportDialog {
@Override @Override
public void actionPerformed(final ActionEvent e) { public void actionPerformed(final ActionEvent e) {
BugReporter.copyAndGoToForums(text.getText()); BugReporter.copyAndGoToForums(GuiBase.getInterface(), text.getText());
} }
} }
@@ -108,7 +109,7 @@ public class BugReportDialog {
@Override @Override
public void actionPerformed(final ActionEvent e) { public void actionPerformed(final ActionEvent e) {
BugReporter.saveToFile(area.getText()); BugReporter.saveToFile(GuiBase.getInterface(), area.getText());
} }
} }

View File

@@ -20,6 +20,7 @@ import com.google.common.base.Function;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.Singletons; import forge.Singletons;
import forge.item.InventoryItem; import forge.item.InventoryItem;
import forge.screens.match.CMatchUI; import forge.screens.match.CMatchUI;
@@ -237,7 +238,7 @@ public class GuiChoose {
}; };
FutureTask<List<T>> future = new FutureTask<List<T>>(showChoice); FutureTask<List<T>> future = new FutureTask<List<T>>(showChoice);
FThreads.invokeInEdtAndWait(future); FThreads.invokeInEdtAndWait(GuiBase.getInterface(), future);
try { try {
return future.get(); return future.get();
} catch (Exception e) { // should be no exception here } catch (Exception e) { // should be no exception here
@@ -296,7 +297,7 @@ public class GuiChoose {
}; };
FutureTask<List<T>> ft = new FutureTask<List<T>>(callable); FutureTask<List<T>> ft = new FutureTask<List<T>>(callable);
FThreads.invokeInEdtAndWait(ft); FThreads.invokeInEdtAndWait(GuiBase.getInterface(), ft);
try { try {
return ft.get(); return ft.get();
} catch (Exception e) { // we have waited enough } catch (Exception e) { // we have waited enough

View File

@@ -8,6 +8,7 @@ import javax.swing.UIManager;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.screens.match.CMatchUI; import forge.screens.match.CMatchUI;
import forge.toolbox.FOptionPane; import forge.toolbox.FOptionPane;
import forge.view.CardView; import forge.view.CardView;
@@ -45,7 +46,7 @@ public class GuiDialog {
}}; }};
FutureTask<Boolean> future = new FutureTask<Boolean>(confirmTask); FutureTask<Boolean> future = new FutureTask<Boolean>(confirmTask);
FThreads.invokeInEdtAndWait(future); FThreads.invokeInEdtAndWait(GuiBase.getInterface(), future);
try { try {
return future.get().booleanValue(); return future.get().booleanValue();
} }
@@ -68,7 +69,7 @@ public class GuiDialog {
} }
public static void message(final String message, final String title) { public static void message(final String message, final String title) {
FThreads.invokeInEdtAndWait(new Runnable() { FThreads.invokeInEdtAndWait(GuiBase.getInterface(), new Runnable() {
@Override @Override
public void run() { public void run() {
FOptionPane.showMessageDialog(message, title, null); FOptionPane.showMessageDialog(message, title, null);

View File

@@ -22,6 +22,7 @@ import com.google.common.base.Function;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.toolbox.FList; import forge.toolbox.FList;
import forge.toolbox.FMouseAdapter; import forge.toolbox.FMouseAdapter;
import forge.toolbox.FOptionPane; import forge.toolbox.FOptionPane;
@@ -75,7 +76,7 @@ public class ListChooser<T> {
private FOptionPane optionPane; private FOptionPane optionPane;
public ListChooser(final String title, final int minChoices, final int maxChoices, final Collection<T> list, final Function<T, String> display) { public ListChooser(final String title, final int minChoices, final int maxChoices, final Collection<T> list, final Function<T, String> display) {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
this.minChoices = minChoices; this.minChoices = minChoices;
this.maxChoices = maxChoices; this.maxChoices = maxChoices;
this.list = list.getClass().isInstance(List.class) ? (List<T>)list : Lists.newArrayList(list); this.list = list.getClass().isInstance(List.class) ? (List<T>)list : Lists.newArrayList(list);

View File

@@ -1,9 +1,11 @@
package forge.gui.framework; package forge.gui.framework;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.view.FFrame; import forge.view.FFrame;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@@ -100,7 +102,7 @@ public class SDisplayUtil {
} }
} }
}; };
FThreads.invokeInEdtLater(showTabRoutine); FThreads.invokeInEdtLater(GuiBase.getInterface(), showTabRoutine);
} }
public static GraphicsDevice getGraphicsDevice(Point point) { public static GraphicsDevice getGraphicsDevice(Point point) {

View File

@@ -1,5 +1,6 @@
package forge.screens.bazaar; package forge.screens.bazaar;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.gui.framework.FScreen; import forge.gui.framework.FScreen;
@@ -42,7 +43,7 @@ public enum VBazaarUI implements IVTopLevelUI {
final FLabel lbl = new FLabel.ButtonBuilder().text(s + " ") final FLabel lbl = new FLabel.ButtonBuilder().text(s + " ")
.fontAlign(SwingConstants.RIGHT).iconInBackground(true).selectable() .fontAlign(SwingConstants.RIGHT).iconInBackground(true).selectable()
.fontSize(16).icon((SkinImage)bazaar.getStall(s).getIcon()).build(); .fontSize(16).icon((SkinImage)GuiBase.getInterface().getSkinIcon(bazaar.getStall(s).getIcon())).build();
pnlAllStalls.add(lbl, "h 80px!, w 90%!, gap 0 0 10px 10px"); pnlAllStalls.add(lbl, "h 80px!, w 90%!, gap 0 0 10px 10px");

View File

@@ -17,6 +17,7 @@
*/ */
package forge.screens.deckeditor.controllers; package forge.screens.deckeditor.controllers;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.deck.DeckBase; import forge.deck.DeckBase;
@@ -148,7 +149,7 @@ public final class CEditorQuestCardShop extends ACEditorBase<InventoryItem, Deck
return; return;
} }
QuestSpellShop.buy(items, this.getCatalogManager(), this.getDeckManager(), true); QuestSpellShop.buy(GuiBase.getInterface(), items, this.getCatalogManager(), this.getDeckManager(), true);
updateCreditsLabel(); updateCreditsLabel();
} }
@@ -159,7 +160,7 @@ public final class CEditorQuestCardShop extends ACEditorBase<InventoryItem, Deck
protected void onRemoveItems(Iterable<Entry<InventoryItem, Integer>> items, boolean toAlternate) { protected void onRemoveItems(Iterable<Entry<InventoryItem, Integer>> items, boolean toAlternate) {
if (showingFullCatalog || toAlternate) { return; } if (showingFullCatalog || toAlternate) { return; }
QuestSpellShop.sell(items, this.getCatalogManager(), this.getDeckManager(), true); QuestSpellShop.sell(GuiBase.getInterface(), items, this.getCatalogManager(), this.getDeckManager(), true);
updateCreditsLabel(); updateCreditsLabel();
} }

View File

@@ -1,5 +1,6 @@
package forge.screens.home.quest; package forge.screens.home.quest;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.Singletons; import forge.Singletons;
import forge.gui.framework.EDocID; import forge.gui.framework.EDocID;
@@ -42,29 +43,29 @@ public enum CSubmenuChallenges implements ICDoc {
view.getBtnSpellShop().setCommand( view.getBtnSpellShop().setCommand(
new UiCommand() { @Override new UiCommand() { @Override
public void run() { QuestUtil.showSpellShop(); } }); public void run() { QuestUtil.showSpellShop(GuiBase.getInterface()); } });
view.getBtnBazaar().setCommand( view.getBtnBazaar().setCommand(
new UiCommand() { @Override new UiCommand() { @Override
public void run() { QuestUtil.showBazaar(); } }); public void run() { QuestUtil.showBazaar(GuiBase.getInterface()); } });
view.getBtnUnlock().setCommand( view.getBtnUnlock().setCommand(
new UiCommand() { @Override new UiCommand() { @Override
public void run() { QuestUtil.chooseAndUnlockEdition(); CSubmenuChallenges.this.update(); } }); public void run() { QuestUtil.chooseAndUnlockEdition(GuiBase.getInterface()); CSubmenuChallenges.this.update(); } });
view.getBtnTravel().setCommand( view.getBtnTravel().setCommand(
new UiCommand() { @Override new UiCommand() { @Override
public void run() { QuestUtil.travelWorld(); CSubmenuChallenges.this.update(); } }); public void run() { QuestUtil.travelWorld(GuiBase.getInterface()); CSubmenuChallenges.this.update(); } });
view.getBtnStart().addActionListener( view.getBtnStart().addActionListener(
new ActionListener() { @Override new ActionListener() { @Override
public void actionPerformed(final ActionEvent e) { QuestUtil.startGame(); } }); public void actionPerformed(final ActionEvent e) { QuestUtil.startGame(GuiBase.getInterface()); } });
((FLabel) view.getLblZep()).setCommand( ((FLabel) view.getLblZep()).setCommand(
new UiCommand() { new UiCommand() {
@Override @Override
public void run() { public void run() {
if (!QuestUtil.checkActiveQuest("Launch a Zeppelin.")) { if (!QuestUtil.checkActiveQuest(GuiBase.getInterface(), "Launch a Zeppelin.")) {
return; return;
} }
FModel.getQuest().getAchievements().setCurrentChallenges(null); FModel.getQuest().getAchievements().setCurrentChallenges(null);

View File

@@ -1,5 +1,6 @@
package forge.screens.home.quest; package forge.screens.home.quest;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.gui.framework.EDocID; import forge.gui.framework.EDocID;
import forge.gui.framework.ICDoc; import forge.gui.framework.ICDoc;
@@ -36,23 +37,23 @@ public enum CSubmenuDuels implements ICDoc {
view.getBtnSpellShop().setCommand( view.getBtnSpellShop().setCommand(
new UiCommand() { @Override new UiCommand() { @Override
public void run() { QuestUtil.showSpellShop(); } }); public void run() { QuestUtil.showSpellShop(GuiBase.getInterface()); } });
view.getBtnBazaar().setCommand( view.getBtnBazaar().setCommand(
new UiCommand() { @Override new UiCommand() { @Override
public void run() { QuestUtil.showBazaar(); } }); public void run() { QuestUtil.showBazaar(GuiBase.getInterface()); } });
view.getBtnTravel().setCommand( view.getBtnTravel().setCommand(
new UiCommand() { @Override new UiCommand() { @Override
public void run() { QuestUtil.travelWorld(); CSubmenuDuels.this.update(); } }); public void run() { QuestUtil.travelWorld(GuiBase.getInterface()); CSubmenuDuels.this.update(); } });
view.getBtnUnlock().setCommand( view.getBtnUnlock().setCommand(
new UiCommand() { @Override new UiCommand() { @Override
public void run() { QuestUtil.chooseAndUnlockEdition(); CSubmenuDuels.this.update(); } }); public void run() { QuestUtil.chooseAndUnlockEdition(GuiBase.getInterface()); CSubmenuDuels.this.update(); } });
view.getBtnStart().addActionListener( view.getBtnStart().addActionListener(
new ActionListener() { @Override new ActionListener() { @Override
public void actionPerformed(final ActionEvent e) { QuestUtil.startGame(); } }); public void actionPerformed(final ActionEvent e) { QuestUtil.startGame(GuiBase.getInterface()); } });
final QuestController quest = FModel.getQuest(); final QuestController quest = FModel.getQuest();
view.getCbPlant().addActionListener(new ActionListener() { view.getCbPlant().addActionListener(new ActionListener() {
@@ -86,11 +87,11 @@ public enum CSubmenuDuels implements ICDoc {
view.getBtnRandomOpponent().setCommand(new UiCommand() { view.getBtnRandomOpponent().setCommand(new UiCommand() {
@Override @Override
public void run() { public void run() {
if (QuestUtil.canStartGame()) { if (QuestUtil.canStartGame(GuiBase.getInterface())) {
FModel.getQuest().getDuelsManager().randomizeOpponents(); FModel.getQuest().getDuelsManager().randomizeOpponents();
final List<QuestEventDuel> duels = FModel.getQuest().getDuelsManager().generateDuels(); final List<QuestEventDuel> duels = FModel.getQuest().getDuelsManager().generateDuels();
QuestUtil.setEvent(duels.get((int) (Math.random() * duels.size()))); QuestUtil.setEvent(duels.get((int) (Math.random() * duels.size())));
QuestUtil.startGame(); QuestUtil.startGame(GuiBase.getInterface());
} }
} }
}); });

View File

@@ -1,5 +1,6 @@
package forge.screens.home.quest; package forge.screens.home.quest;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.Singletons; import forge.Singletons;
import forge.deck.DeckProxy; import forge.deck.DeckProxy;
@@ -56,7 +57,7 @@ public enum CSubmenuQuestDecks implements ICDoc {
VSubmenuQuestDecks.SINGLETON_INSTANCE.getBtnNewDeck().setCommand(new UiCommand() { VSubmenuQuestDecks.SINGLETON_INSTANCE.getBtnNewDeck().setCommand(new UiCommand() {
@Override @Override
public void run() { public void run() {
if (!QuestUtil.checkActiveQuest("Create a Deck.")) { if (!QuestUtil.checkActiveQuest(GuiBase.getInterface(), "Create a Deck.")) {
return; return;
} }
Singletons.getControl().setCurrentScreen(FScreen.DECK_EDITOR_QUEST); Singletons.getControl().setCurrentScreen(FScreen.DECK_EDITOR_QUEST);

View File

@@ -297,7 +297,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
view.setMode(Mode.TOURNAMENT_ACTIVE); view.setMode(Mode.TOURNAMENT_ACTIVE);
} }
QuestDraftUtils.update(); QuestDraftUtils.update(GuiBase.getInterface());
switch (view.getMode()) { switch (view.getMode()) {
@@ -477,7 +477,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
drafting = true; drafting = true;
BoosterDraft draft = draftEvent.enter(); BoosterDraft draft = draftEvent.enter(GuiBase.getInterface());
final CEditorQuestDraftingProcess draftController = new CEditorQuestDraftingProcess(); final CEditorQuestDraftingProcess draftController = new CEditorQuestDraftingProcess();
draftController.showGui(draft); draftController.showGui(draft);
@@ -517,7 +517,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
return; return;
} }
QuestDraftUtils.startNextMatch(); QuestDraftUtils.startNextMatch(GuiBase.getInterface());
} }

View File

@@ -1,6 +1,8 @@
package forge.screens.home.quest; package forge.screens.home.quest;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.model.FModel; import forge.model.FModel;
import forge.quest.QuestUtil; import forge.quest.QuestUtil;
import forge.quest.bazaar.IQuestBazaarItem; import forge.quest.bazaar.IQuestBazaarItem;
@@ -75,7 +77,23 @@ public class ViewItem extends FPanel {
final QuestAssets qA = FModel.getQuest().getAssets(); final QuestAssets qA = FModel.getQuest().getAssets();
IQuestBazaarItem bazaarItem = ViewItem.this.getItem(); IQuestBazaarItem bazaarItem = ViewItem.this.getItem();
ViewItem.this.lblIcon.setIcon((SkinImage)bazaarItem.getIcon(qA)); SkinImage i;
try {
final FSkinProp f = FSkinProp.valueOf(FSkinProp.class, bazaarItem.getIcon(qA));
i = (SkinImage) GuiBase.getInterface().getSkinIcon(f);
} catch (final IllegalArgumentException e) {
// Failed to parse FSkinProp
try {
i = (SkinImage) GuiBase.getInterface().getUnskinnedIcon(bazaarItem.getIcon(qA));
} catch (final Exception e1) {
// give up, icon unknown
e1.printStackTrace();
i = (SkinImage) GuiBase.getInterface().getSkinIcon(FSkinProp.ICO_UNKNOWN);
}
}
ViewItem.this.lblIcon.setIcon(i);
ViewItem.this.lblName.setText(bazaarItem.getPurchaseName()); ViewItem.this.lblName.setText(bazaarItem.getPurchaseName());
ViewItem.this.lblPrice.setText("Cost: " + String.valueOf(bazaarItem.getBuyingPrice(qA)) + " credits"); ViewItem.this.lblPrice.setText("Cost: " + String.valueOf(bazaarItem.getBuyingPrice(qA)) + " credits");
String desc = bazaarItem.getPurchaseDescription(qA); String desc = bazaarItem.getPurchaseDescription(qA);

View File

@@ -114,11 +114,11 @@ public enum CSubmenuDraft implements ICDoc {
} }
} }
FModel.getGauntletMini().resetGauntletDraft(); FModel.getGauntletMini(GuiBase.getInterface()).resetGauntletDraft();
if (gauntlet) { if (gauntlet) {
int rounds = FModel.getDecks().getDraft().get(humanDeck.getName()).getAiDecks().size(); int rounds = FModel.getDecks().getDraft().get(humanDeck.getName()).getAiDecks().size();
FModel.getGauntletMini().launch(rounds, humanDeck.getDeck(), gameType); FModel.getGauntletMini(GuiBase.getInterface()).launch(rounds, humanDeck.getDeck(), gameType);
return; return;
} }
@@ -152,7 +152,7 @@ public enum CSubmenuDraft implements ICDoc {
final LimitedPoolType poolType = GuiChoose.oneOrNone("Choose Draft Format", LimitedPoolType.values()); final LimitedPoolType poolType = GuiChoose.oneOrNone("Choose Draft Format", LimitedPoolType.values());
if (poolType == null) { return; } if (poolType == null) { return; }
BoosterDraft draft = BoosterDraft.createDraft(poolType); BoosterDraft draft = BoosterDraft.createDraft(GuiBase.getInterface(), poolType);
if (draft == null) { return; } if (draft == null) { return; }
final CEditorDraftingProcess draftController = new CEditorDraftingProcess(); final CEditorDraftingProcess draftController = new CEditorDraftingProcess();

View File

@@ -1,5 +1,6 @@
package forge.screens.home.sanctioned; package forge.screens.home.sanctioned;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.Singletons; import forge.Singletons;
import forge.deck.*; import forge.deck.*;
@@ -16,6 +17,7 @@ import forge.screens.deckeditor.CDeckEditorUI;
import forge.screens.deckeditor.controllers.ACEditorBase; import forge.screens.deckeditor.controllers.ACEditorBase;
import forge.screens.deckeditor.controllers.CEditorLimited; import forge.screens.deckeditor.controllers.CEditorLimited;
import forge.toolbox.FOptionPane; import forge.toolbox.FOptionPane;
import javax.swing.*; import javax.swing.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
@@ -108,12 +110,12 @@ public enum CSubmenuSealed implements ICDoc {
} }
int matches = FModel.getDecks().getSealed().get(human.getName()).getAiDecks().size(); int matches = FModel.getDecks().getSealed().get(human.getName()).getAiDecks().size();
FModel.getGauntletMini().launch(matches, human.getDeck(), gameType); FModel.getGauntletMini(GuiBase.getInterface()).launch(matches, human.getDeck(), gameType);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T extends DeckBase> void setupSealed() { private <T extends DeckBase> void setupSealed() {
final DeckGroup sealed = SealedCardPoolGenerator.generateSealedDeck(true); final DeckGroup sealed = SealedCardPoolGenerator.generateSealedDeck(GuiBase.getInterface(), true);
if (sealed == null) { return; } if (sealed == null) { return; }
final ACEditorBase<? extends InventoryItem, T> editor = (ACEditorBase<? extends InventoryItem, T>) new CEditorLimited( final ACEditorBase<? extends InventoryItem, T> editor = (ACEditorBase<? extends InventoryItem, T>) new CEditorLimited(

View File

@@ -142,7 +142,7 @@ public enum CSubmenuWinston implements ICDoc {
final LimitedPoolType poolType = GuiChoose.oneOrNone("Choose Draft Format", LimitedPoolType.values()); final LimitedPoolType poolType = GuiChoose.oneOrNone("Choose Draft Format", LimitedPoolType.values());
if (poolType == null) { return; } if (poolType == null) { return; }
WinstonDraft draft = WinstonDraft.createDraft(poolType); WinstonDraft draft = WinstonDraft.createDraft(GuiBase.getInterface(), poolType);
if (draft == null) { return; } if (draft == null) { return; }
final CEditorWinstonProcess draftController = new CEditorWinstonProcess(); final CEditorWinstonProcess draftController = new CEditorWinstonProcess();

View File

@@ -1,5 +1,6 @@
package forge.screens.home.settings; package forge.screens.home.settings;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.download.GuiDownloadPicturesLQ; import forge.download.GuiDownloadPicturesLQ;
import forge.download.GuiDownloadPrices; import forge.download.GuiDownloadPrices;
@@ -37,7 +38,7 @@ public enum CSubmenuDownloaders implements ICDoc {
private final UiCommand cmdImportPictures = new UiCommand() { @Override private final UiCommand cmdImportPictures = new UiCommand() { @Override
public void run() { new ImportDialog(null, null); } }; public void run() { new ImportDialog(null, null); } };
private final UiCommand cmdReportBug = new UiCommand() { @Override private final UiCommand cmdReportBug = new UiCommand() { @Override
public void run() { BugReporter.reportBug(null); } public void run() { BugReporter.reportBug(GuiBase.getInterface(), null); }
}; };
/* (non-Javadoc) /* (non-Javadoc)

View File

@@ -1,5 +1,6 @@
package forge.screens.home.settings; package forge.screens.home.settings;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.Singletons; import forge.Singletons;
import forge.ai.AiProfileUtil; import forge.ai.AiProfileUtil;
@@ -339,7 +340,7 @@ public enum CSubmenuPreferences implements ICDoc {
return new UiCommand() { return new UiCommand() {
@Override @Override
public void run() { public void run() {
GamePlayerUtil.setPlayerName(); GamePlayerUtil.setPlayerName(GuiBase.getInterface());
setPlayerNameButtonText(); setPlayerNameButtonText();
} }
}; };

View File

@@ -34,6 +34,7 @@ import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe; import com.google.common.eventbus.Subscribe;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.ImageCache; import forge.ImageCache;
import forge.LobbyPlayer; import forge.LobbyPlayer;
import forge.Singletons; import forge.Singletons;
@@ -257,7 +258,7 @@ public enum CMatchUI implements ICDoc, IMenuProvider {
} }
final Object[] result = { null }; // how else can I extract a value from EDT thread? final Object[] result = { null }; // how else can I extract a value from EDT thread?
FThreads.invokeInEdtAndWait(new Runnable() { FThreads.invokeInEdtAndWait(GuiBase.getInterface(), new Runnable() {
@Override @Override
public void run() { public void run() {
VAssignDamage v = new VAssignDamage(attacker, blockers, damage, defender, overrideOrder); VAssignDamage v = new VAssignDamage(attacker, blockers, damage, defender, overrideOrder);
@@ -285,7 +286,7 @@ public enum CMatchUI implements ICDoc, IMenuProvider {
} }
public void setCard(final CardView c, final boolean isInAltState) { public void setCard(final CardView c, final boolean isInAltState) {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
CDetail.SINGLETON_INSTANCE.showCard(c, isInAltState); CDetail.SINGLETON_INSTANCE.showCard(c, isInAltState);
CPicture.SINGLETON_INSTANCE.showCard(c, isInAltState); CPicture.SINGLETON_INSTANCE.showCard(c, isInAltState);
} }
@@ -335,7 +336,7 @@ public enum CMatchUI implements ICDoc, IMenuProvider {
Set<CardView> highlightedCards = Sets.newHashSet(); Set<CardView> highlightedCards = Sets.newHashSet();
// used to highlight cards in UI // used to highlight cards in UI
public void setUsedToPay(CardView card, boolean value) { public void setUsedToPay(CardView card, boolean value) {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
boolean hasChanged = value ? highlightedCards.add(card) : highlightedCards.remove(card); boolean hasChanged = value ? highlightedCards.add(card) : highlightedCards.remove(card);
if (hasChanged) { // since we are in UI thread, may redraw the card right now if (hasChanged) { // since we are in UI thread, may redraw the card right now
@@ -417,7 +418,7 @@ public enum CMatchUI implements ICDoc, IMenuProvider {
// UI-related events should arrive here // UI-related events should arrive here
public void fireEvent(UiEvent uiEvent) { public void fireEvent(UiEvent uiEvent) {
if (LOG_UIEVENTS) { if (LOG_UIEVENTS) {
System.out.println("UI: " + uiEvent.toString() + " \t\t " + FThreads.debugGetStackTraceItem(4, true)); System.out.println("UI: " + uiEvent.toString() + " \t\t " + FThreads.debugGetStackTraceItem(GuiBase.getInterface(), 4, true));
} }
uiEvents.post(uiEvent); uiEvents.post(uiEvent);
} }

View File

@@ -27,6 +27,7 @@ import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout; import net.miginfocom.swing.MigLayout;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.gauntlet.GauntletWinLoseController; import forge.gauntlet.GauntletWinLoseController;
import forge.interfaces.IGuiBase;
import forge.toolbox.FLabel; import forge.toolbox.FLabel;
import forge.toolbox.FSkin; import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinnedPanel; import forge.toolbox.FSkin.SkinnedPanel;
@@ -45,9 +46,9 @@ public class GauntletWinLose extends ControlWinLose {
* @param view0 ViewWinLose object * @param view0 ViewWinLose object
* @param match * @param match
*/ */
public GauntletWinLose(final ViewWinLose view0, final IGameView game0) { public GauntletWinLose(final ViewWinLose view0, final IGameView game0, final IGuiBase gui) {
super(view0, game0); super(view0, game0);
controller = new GauntletWinLoseController(view0, game0) { controller = new GauntletWinLoseController(view0, game0, gui) {
@Override @Override
protected void showOutcome(String message1, String message2, FSkinProp icon, List<String> lstEventNames, List<String> lstEventRecords, int len, int num) { protected void showOutcome(String message1, String message2, FSkinProp icon, List<String> lstEventNames, List<String> lstEventRecords, int len, int num) {
final JLabel lblTitle = new FLabel.Builder().text("Gauntlet Progress") final JLabel lblTitle = new FLabel.Builder().text("Gauntlet Progress")

View File

@@ -21,6 +21,7 @@ import java.awt.Dimension;
import javax.swing.SwingConstants; import javax.swing.SwingConstants;
import forge.GuiBase;
import forge.limited.LimitedWinLoseController; import forge.limited.LimitedWinLoseController;
import forge.toolbox.FSkin; import forge.toolbox.FSkin;
import forge.toolbox.FSkin.Colors; import forge.toolbox.FSkin.Colors;
@@ -48,7 +49,7 @@ public class LimitedWinLose extends ControlWinLose {
*/ */
public LimitedWinLose(final ViewWinLose view0, final IGameView game0) { public LimitedWinLose(final ViewWinLose view0, final IGameView game0) {
super(view0, game0); super(view0, game0);
controller = new LimitedWinLoseController(view0, game0) { controller = new LimitedWinLoseController(view0, game0, GuiBase.getInterface()) {
@Override @Override
protected void showOutcome(Runnable runnable) { protected void showOutcome(Runnable runnable) {
runnable.run(); //just run on GUI thread runnable.run(); //just run on GUI thread

View File

@@ -102,10 +102,10 @@ public class QuestDraftWinLose extends ControlWinLose {
if (lastGame.isMatchOver()) { if (lastGame.isMatchOver()) {
this.actionOnQuitMatch(); this.actionOnQuitMatch();
QuestDraftUtils.matchInProgress = false; QuestDraftUtils.matchInProgress = false;
QuestDraftUtils.update(); QuestDraftUtils.update(GuiBase.getInterface());
} else { } else {
this.actionOnContinue(); this.actionOnContinue();
QuestDraftUtils.update(); QuestDraftUtils.update(GuiBase.getInterface());
} }
return false; return false;
@@ -126,7 +126,7 @@ public class QuestDraftWinLose extends ControlWinLose {
public void actionPerformed(final ActionEvent e) { public void actionPerformed(final ActionEvent e) {
GuiBase.getInterface().endCurrentGame(); GuiBase.getInterface().endCurrentGame();
QuestDraftUtils.matchInProgress = false; QuestDraftUtils.matchInProgress = false;
QuestDraftUtils.continueMatches(); QuestDraftUtils.continueMatches(GuiBase.getInterface());
} }
}); });
} else { } else {
@@ -141,7 +141,7 @@ public class QuestDraftWinLose extends ControlWinLose {
if (FOptionPane.showOptionDialog("Quitting the match now will forfeit the tournament!\n\nReally quit?", "Really Quit Tournament?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2), new String[] { "Yes", "No" }, 1) == 0) { if (FOptionPane.showOptionDialog("Quitting the match now will forfeit the tournament!\n\nReally quit?", "Really Quit Tournament?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2), new String[] { "Yes", "No" }, 1) == 0) {
GuiBase.getInterface().endCurrentGame(); GuiBase.getInterface().endCurrentGame();
QuestDraftUtils.matchInProgress = false; QuestDraftUtils.matchInProgress = false;
QuestDraftUtils.continueMatches(); QuestDraftUtils.continueMatches(GuiBase.getInterface());
} }
} }
}); });

View File

@@ -21,6 +21,7 @@ import java.util.List;
import javax.swing.SwingConstants; import javax.swing.SwingConstants;
import forge.GuiBase;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.model.FModel; import forge.model.FModel;
@@ -64,7 +65,7 @@ public class QuestWinLose extends ControlWinLose {
public QuestWinLose(final ViewWinLose view0, final IGameView game0) { public QuestWinLose(final ViewWinLose view0, final IGameView game0) {
super(view0, game0); super(view0, game0);
view = view0; view = view0;
controller = new QuestWinLoseController(game0) { controller = new QuestWinLoseController(game0, GuiBase.getInterface()) {
@Override @Override
protected void showRewards(Runnable runnable) { protected void showRewards(Runnable runnable) {
runnable.run(); //just run on GUI thread runnable.run(); //just run on GUI thread

View File

@@ -14,6 +14,7 @@ import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import forge.GuiBase;
import forge.LobbyPlayer; import forge.LobbyPlayer;
import forge.UiCommand; import forge.UiCommand;
import forge.game.GameLogEntry; import forge.game.GameLogEntry;
@@ -68,14 +69,14 @@ public class ViewWinLose implements IWinLoseView<FButton> {
control = new QuestDraftWinLose(this, game0); control = new QuestDraftWinLose(this, game0);
break; break;
case Draft: case Draft:
if (!FModel.getGauntletMini().isGauntletDraft()) { if (!FModel.getGauntletMini(GuiBase.getInterface()).isGauntletDraft()) {
break; break;
} }
case Sealed: case Sealed:
control = new LimitedWinLose(this, game0); control = new LimitedWinLose(this, game0);
break; break;
case Gauntlet: case Gauntlet:
control = new GauntletWinLose(this, game0); control = new GauntletWinLose(this, game0, GuiBase.getInterface());
break; break;
default: // will catch it after switch default: // will catch it after switch
break; break;

View File

@@ -71,7 +71,7 @@ public enum CDock implements ICDoc {
SOverlayUtils.genericOverlay(); SOverlayUtils.genericOverlay();
FView.SINGLETON_INSTANCE.getPnlContent().removeAll(); FView.SINGLETON_INSTANCE.getPnlContent().removeAll();
FThreads.invokeInEdtLater(new Runnable(){ FThreads.invokeInEdtLater(GuiBase.getInterface(), new Runnable(){
@Override public void run() { @Override public void run() {
SLayoutIO.loadLayout(null); SLayoutIO.loadLayout(null);
SOverlayUtils.hideOverlay(); SOverlayUtils.hideOverlay();
@@ -101,7 +101,7 @@ public enum CDock implements ICDoc {
FView.SINGLETON_INSTANCE.getPnlContent().removeAll(); FView.SINGLETON_INSTANCE.getPnlContent().removeAll();
// let it redraw everything first // let it redraw everything first
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(GuiBase.getInterface(), new Runnable() {
@Override @Override
public void run() { public void run() {
if (loadFile != null) { if (loadFile != null) {

View File

@@ -28,6 +28,7 @@ import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.Singletons; import forge.Singletons;
import forge.UiCommand; import forge.UiCommand;
import forge.gui.framework.ICDoc; import forge.gui.framework.ICDoc;
@@ -79,7 +80,7 @@ public class CHand implements ICDoc {
} }
public void update(final Observable a, final Object b) { public void update(final Observable a, final Object b) {
FThreads.invokeInEdtNowOrLater(updateRoutine); FThreads.invokeInEdtNowOrLater(GuiBase.getInterface(), updateRoutine);
} }
private final Runnable updateRoutine = new Runnable() { private final Runnable updateRoutine = new Runnable() {
@@ -87,7 +88,7 @@ public class CHand implements ICDoc {
}; };
public void updateHand() { public void updateHand() {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
final HandArea p = view.getHandArea(); final HandArea p = view.getHandArea();

View File

@@ -1,5 +1,6 @@
package forge.screens.match.controllers; package forge.screens.match.controllers;
import forge.GuiBase;
import forge.UiCommand; import forge.UiCommand;
import forge.FThreads; import forge.FThreads;
import forge.gui.framework.ICDoc; import forge.gui.framework.ICDoc;
@@ -66,7 +67,7 @@ public enum CLog implements ICDoc, Observer {
*/ */
@Override @Override
public void update() { public void update() {
FThreads.invokeInEdtNowOrLater(r); FThreads.invokeInEdtNowOrLater(GuiBase.getInterface(), r);
} }
} }

View File

@@ -27,6 +27,7 @@ import java.awt.event.FocusListener;
import javax.swing.JButton; import javax.swing.JButton;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.Singletons; import forge.Singletons;
import forge.UiCommand; import forge.UiCommand;
import forge.gui.framework.ICDoc; import forge.gui.framework.ICDoc;
@@ -118,7 +119,7 @@ public enum CPrompt implements ICDoc {
*/ */
public void updateText() { public void updateText() {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
final IGameView game = Singletons.getControl().getGameView(); final IGameView game = Singletons.getControl().getGameView();
final String text = String.format("T:%d G:%d/%d [%s]", game.getTurnNumber(), game.getNumPlayedGamesInMatch() + 1, game.getNumGamesInMatch(), game.getGameType()); final String text = String.format("T:%d G:%d/%d [%s]", game.getTurnNumber(), game.getNumPlayedGamesInMatch() + 1, game.getNumGamesInMatch(), game.getGameType());
view.getLblGames().setText(text); view.getLblGames().setText(text);

View File

@@ -1,9 +1,16 @@
package forge.screens.match.menus; package forge.screens.match.menus;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import forge.Singletons; import forge.Singletons;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.control.FControl; import forge.control.FControl;
import forge.match.MatchUtil;
import forge.menus.MenuUtil; import forge.menus.MenuUtil;
import forge.model.FModel; import forge.model.FModel;
import forge.properties.ForgePreferences; import forge.properties.ForgePreferences;
@@ -11,13 +18,11 @@ import forge.properties.ForgePreferences.FPref;
import forge.screens.match.CMatchUI; import forge.screens.match.CMatchUI;
import forge.screens.match.VAutoYields; import forge.screens.match.VAutoYields;
import forge.screens.match.controllers.CDock; import forge.screens.match.controllers.CDock;
import forge.toolbox.FSkin.*; import forge.toolbox.FSkin.SkinIcon;
import forge.toolbox.FSkin.SkinnedCheckBoxMenuItem;
import javax.swing.*; import forge.toolbox.FSkin.SkinnedMenu;
import forge.toolbox.FSkin.SkinnedMenuItem;
import java.awt.event.ActionEvent; import forge.toolbox.FSkin.SkinnedRadioButtonMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/** /**
* Returns a JMenu containing options associated with current game. * Returns a JMenu containing options associated with current game.
@@ -80,7 +85,7 @@ public final class GameMenu {
return new ActionListener() { return new ActionListener() {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
MatchUtil.undoLastAction(); Singletons.getControl().getGameView().tryUndoLastAction();
} }
}; };
} }

View File

@@ -1,6 +1,7 @@
package forge.toolbox; package forge.toolbox;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.interfaces.IProgressBar; import forge.interfaces.IProgressBar;
import javax.swing.*; import javax.swing.*;
@@ -36,7 +37,7 @@ public class FProgressBar extends JProgressBar implements IProgressBar {
* @param s0 &emsp; A description to prepend before statistics. * @param s0 &emsp; A description to prepend before statistics.
*/ */
public void setDescription(final String s0) { public void setDescription(final String s0) {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
desc = s0; desc = s0;
setString(s0); setString(s0);
} }
@@ -81,7 +82,7 @@ public class FProgressBar extends JProgressBar implements IProgressBar {
/** Resets the various values required for this class. Must be called from EDT. */ /** Resets the various values required for this class. Must be called from EDT. */
public void reset() { public void reset() {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
setIndeterminate(true); setIndeterminate(true);
setValue(0); setValue(0);
tempVal = 0; tempVal = 0;

View File

@@ -18,6 +18,7 @@
package forge.toolbox; package forge.toolbox;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.Singletons; import forge.Singletons;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.assets.ISkinImage; import forge.assets.ISkinImage;
@@ -981,7 +982,7 @@ public class FSkin {
public static void loadLight(final String skinName, final boolean onInit) { public static void loadLight(final String skinName, final boolean onInit) {
if (onInit) { if (onInit) {
// No need for this method to be loaded while on the EDT. // No need for this method to be loaded while on the EDT.
FThreads.assertExecutedByEdt(false); FThreads.assertExecutedByEdt(GuiBase.getInterface(), false);
if (allSkins == null) { //initialize if (allSkins == null) { //initialize
allSkins = new ArrayList<String>(); allSkins = new ArrayList<String>();
@@ -1053,7 +1054,7 @@ public class FSkin {
public static void loadFull(final boolean onInit) { public static void loadFull(final boolean onInit) {
if (onInit) { if (onInit) {
// No need for this method to be loaded while on the EDT. // No need for this method to be loaded while on the EDT.
FThreads.assertExecutedByEdt(false); FThreads.assertExecutedByEdt(GuiBase.getInterface(), false);
// Preferred skin name must be called via loadLight() method, // Preferred skin name must be called via loadLight() method,
// which does some cleanup and init work. // which does some cleanup and init work.

View File

@@ -23,8 +23,6 @@ import java.awt.image.BufferedImage;
import java.awt.image.ColorModel; import java.awt.image.ColorModel;
import forge.ImageCache; import forge.ImageCache;
import forge.card.CardCharacteristicName;
import forge.game.card.Card;
import forge.model.FModel; import forge.model.FModel;
import forge.properties.ForgePreferences; import forge.properties.ForgePreferences;
import forge.toolbox.CardFaceSymbols; import forge.toolbox.CardFaceSymbols;
@@ -38,36 +36,9 @@ import forge.view.CardView.CardStateView;
* *
*/ */
public final class FImageUtil { public final class FImageUtil {
private FImageUtil() {} private FImageUtil() {}
@Deprecated
public static BufferedImage getImage(Card card, CardCharacteristicName state) {
BufferedImage image = ImageCache.getOriginalImage(card.getImageKey(state), true);
int foilIndex = card.getFoil();
if (image != null && foilIndex > 0) {
image = getImageWithFoilEffect(image, foilIndex);
}
return image;
}
/**
* Gets the image associated with a card.
* <p>
* Adds a random foil effect if enabled.
* <p>
* For double-sided cards, returns the front-side image.<br>
* For flip cards, returns the un-flipped image.
*/
@Deprecated
public static BufferedImage getImage(Card card) {
BufferedImage image = ImageCache.getOriginalImage(card.getImageKey(), true);
int foilIndex = card.getFoil();
if (image != null && foilIndex > 0) {
image = getImageWithFoilEffect(image, foilIndex);
}
return image;
}
/** /**
* Gets the image associated with a card. * Gets the image associated with a card.
* <p> * <p>

View File

@@ -18,6 +18,7 @@
package forge.view; package forge.view;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.gui.SOverlayUtils; import forge.gui.SOverlayUtils;
import forge.screens.match.VMatchUI; import forge.screens.match.VMatchUI;
@@ -68,7 +69,7 @@ public class ButtonUtil {
// ensure we don't steal focus from an overlay // ensure we don't steal focus from an overlay
if (!SOverlayUtils.overlayHasFocus()) { if (!SOverlayUtils.overlayHasFocus()) {
FThreads.invokeInEdtLater(new Runnable() { @Override public void run() { button.requestFocusInWindow(); } }); FThreads.invokeInEdtLater(GuiBase.getInterface(), new Runnable() { @Override public void run() { button.requestFocusInWindow(); } });
} }
} }

View File

@@ -21,7 +21,7 @@ import forge.util.Lang;
public class SimulateMatch { public class SimulateMatch {
public static void simulate(String[] args) { public static void simulate(String[] args) {
FModel.initialize(null); FModel.initialize(GuiBase.getInterface(), null);
System.out.println("Simulation mode"); System.out.println("Simulation mode");
if(args.length < 3 ) { if(args.length < 3 ) {

View File

@@ -30,6 +30,7 @@ import java.util.List;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.screens.match.CMatchUI; import forge.screens.match.CMatchUI;
import forge.toolbox.FScrollPane; import forge.toolbox.FScrollPane;
import forge.toolbox.FSkin.SkinnedPanel; import forge.toolbox.FSkin.SkinnedPanel;
@@ -332,7 +333,7 @@ public abstract class CardPanelContainer extends SkinnedPanel {
* a {@link forge.view.arcane.CardPanel} object. * a {@link forge.view.arcane.CardPanel} object.
*/ */
public final void removeCardPanel(final CardPanel fromPanel) { public final void removeCardPanel(final CardPanel fromPanel) {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
if (CardPanelContainer.this.getMouseDragPanel() != null) { if (CardPanelContainer.this.getMouseDragPanel() != null) {
CardPanel.getDragAnimationPanel().setVisible(false); CardPanel.getDragAnimationPanel().setVisible(false);
CardPanel.getDragAnimationPanel().repaint(); CardPanel.getDragAnimationPanel().repaint();
@@ -384,7 +385,7 @@ public abstract class CardPanelContainer extends SkinnedPanel {
* </p> * </p>
*/ */
public final void clear() { public final void clear() {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
for (CardPanel p : CardPanelContainer.this.getCardPanels()) { for (CardPanel p : CardPanelContainer.this.getCardPanels()) {
p.dispose(); p.dispose();
} }

View File

@@ -28,6 +28,7 @@ import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.screens.match.CMatchUI; import forge.screens.match.CMatchUI;
import forge.screens.match.controllers.CPrompt; import forge.screens.match.controllers.CPrompt;
import forge.toolbox.FScrollPane; import forge.toolbox.FScrollPane;
@@ -590,7 +591,7 @@ public class PlayArea extends CardPanelContainer implements CardPanelMouseListen
* </p> * </p>
*/ */
public void setupPlayZone() { public void setupPlayZone() {
FThreads.assertExecutedByEdt(true); FThreads.assertExecutedByEdt(GuiBase.getInterface(), true);
recalculateCardPanels(model); recalculateCardPanels(model);
} }

View File

@@ -3,6 +3,7 @@ package forge;
import forge.deck.CardPool; import forge.deck.CardPool;
import forge.limited.BoosterDraft; import forge.limited.BoosterDraft;
import forge.limited.LimitedPoolType; import forge.limited.LimitedPoolType;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
@@ -19,7 +20,7 @@ public class BoosterDraft1Test {
*/ */
@Test(groups = { "UnitTest", "fast" }, timeOut = 1000, enabled = false) @Test(groups = { "UnitTest", "fast" }, timeOut = 1000, enabled = false)
public void boosterDraft1Test1() throws Exception { public void boosterDraft1Test1() throws Exception {
final BoosterDraft draft = BoosterDraft.createDraft(LimitedPoolType.Full); final BoosterDraft draft = BoosterDraft.createDraft(GuiBase.getInterface(), LimitedPoolType.Full);
if (draft == null) { return; } if (draft == null) { return; }
while (draft.hasNextChoice()) { while (draft.hasNextChoice()) {

View File

@@ -97,7 +97,7 @@ public class PlayerControllerForTests extends PlayerController {
public void playSpellAbilityNoStack(SpellAbility effectSA, boolean mayChoseNewTargets) { public void playSpellAbilityNoStack(SpellAbility effectSA, boolean mayChoseNewTargets) {
//TODO: eventually (when the real code is refactored) this should be handled normally... //TODO: eventually (when the real code is refactored) this should be handled normally...
if (effectSA.getDescription().equals("At the beginning of your upkeep, if you have exactly 1 life, you win the game.")) {//test_104_2b_effect_may_state_that_player_wins_the_game if (effectSA.getDescription().equals("At the beginning of your upkeep, if you have exactly 1 life, you win the game.")) {//test_104_2b_effect_may_state_that_player_wins_the_game
HumanPlay.playSpellAbilityNoStack(player, effectSA, !mayChoseNewTargets); HumanPlay.playSpellAbilityNoStack(null, player, effectSA, !mayChoseNewTargets);
return; return;
} }
SpellAbilityAi sai = SpellApiToAi.Converter.get(effectSA.getApi()); SpellAbilityAi sai = SpellApiToAi.Converter.get(effectSA.getApi());
@@ -106,7 +106,7 @@ public class PlayerControllerForTests extends PlayerController {
(effectSA.getHostCard().getName().equals("Laboratory Maniac") && sai instanceof GameWinAi) || (effectSA.getHostCard().getName().equals("Laboratory Maniac") && sai instanceof GameWinAi) ||
(effectSA.getHostCard().getName().equals("Nefarious Lich") && sai instanceof ChangeZoneAi) (effectSA.getHostCard().getName().equals("Nefarious Lich") && sai instanceof ChangeZoneAi)
) {//test_104_3f_if_a_player_would_win_and_lose_simultaneously_he_loses ) {//test_104_3f_if_a_player_would_win_and_lose_simultaneously_he_loses
HumanPlay.playSpellAbilityNoStack(player, effectSA, !mayChoseNewTargets); HumanPlay.playSpellAbilityNoStack(null, player, effectSA, !mayChoseNewTargets);
return; return;
} }
throw new IllegalStateException("Callers of this method currently assume that it performs extra functionality!"); throw new IllegalStateException("Callers of this method currently assume that it performs extra functionality!");

View File

@@ -1,9 +1,9 @@
package forge; package forge;
import forge.util.ThreadUtil;
import java.io.PrintStream; import java.io.PrintStream;
import forge.interfaces.IGuiBase;
import forge.util.ThreadUtil;
public class FThreads { public class FThreads {
private FThreads() { } // no instances supposed private FThreads() { } // no instances supposed
@@ -15,8 +15,8 @@ public class FThreads {
* @param methodName &emsp; String, part of the custom exception message. * @param methodName &emsp; String, part of the custom exception message.
* @param mustBeEDT &emsp; boolean: true = exception if not EDT, false = exception if EDT * @param mustBeEDT &emsp; boolean: true = exception if not EDT, false = exception if EDT
*/ */
public static void assertExecutedByEdt(final boolean mustBeEDT) { public static void assertExecutedByEdt(final IGuiBase gui, final boolean mustBeEDT) {
if (isGuiThread() != mustBeEDT) { if (isGuiThread(gui) != mustBeEDT) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace(); StackTraceElement[] trace = Thread.currentThread().getStackTrace();
final String methodName = trace[2].getClassName() + "." + trace[2].getMethodName(); final String methodName = trace[2].getClassName() + "." + trace[2].getMethodName();
String modalOperator = mustBeEDT ? " must be" : " may not be"; String modalOperator = mustBeEDT ? " must be" : " may not be";
@@ -24,16 +24,16 @@ public class FThreads {
} }
} }
public static void invokeInEdtLater(Runnable runnable) { public static void invokeInEdtLater(final IGuiBase gui, final Runnable runnable) {
GuiBase.getInterface().invokeInEdtLater(runnable); gui.invokeInEdtLater(runnable);
} }
public static void invokeInEdtNowOrLater(Runnable proc) { public static void invokeInEdtNowOrLater(final IGuiBase gui, final Runnable proc) {
if (isGuiThread()) { if (isGuiThread(gui)) {
proc.run(); proc.run();
} }
else { else {
invokeInEdtLater(proc); invokeInEdtLater(gui, proc);
} }
} }
@@ -49,8 +49,8 @@ public class FThreads {
* the Runnable to run * the Runnable to run
* @see fgd.SwingUtilities#invokeLater(Runnable) * @see fgd.SwingUtilities#invokeLater(Runnable)
*/ */
public static void invokeInEdtAndWait(final Runnable proc) { public static void invokeInEdtAndWait(final IGuiBase gui, final Runnable proc) {
GuiBase.getInterface().invokeInEdtAndWait(proc); gui.invokeInEdtAndWait(proc);
} }
private static int backgroundThreadCount; private static int backgroundThreadCount;
@@ -60,31 +60,31 @@ public class FThreads {
backgroundThreadCount++; backgroundThreadCount++;
} }
public static boolean isGuiThread() { public static boolean isGuiThread(IGuiBase gui) {
return GuiBase.getInterface().isGuiThread(); return gui.isGuiThread();
} }
public static void delayInEDT(int milliseconds, final Runnable inputUpdater) { public static void delayInEDT(final IGuiBase gui, final int milliseconds, final Runnable inputUpdater) {
Runnable runInEdt = new Runnable() { Runnable runInEdt = new Runnable() {
@Override @Override
public void run() { public void run() {
FThreads.invokeInEdtNowOrLater(inputUpdater); FThreads.invokeInEdtNowOrLater(gui, inputUpdater);
} }
}; };
ThreadUtil.delay(milliseconds, runInEdt); ThreadUtil.delay(milliseconds, runInEdt);
} }
public static String debugGetCurrThreadId() { public static String debugGetCurrThreadId(final IGuiBase gui) {
return isGuiThread() ? "EDT" : Thread.currentThread().getName(); return isGuiThread(gui) ? "EDT" : Thread.currentThread().getName();
} }
public static String prependThreadId(String message) { public static String prependThreadId(final IGuiBase gui, String message) {
return debugGetCurrThreadId() + " > " + message; return debugGetCurrThreadId(gui) + " > " + message;
} }
public static void dumpStackTrace(PrintStream stream) { public static void dumpStackTrace(final IGuiBase gui, final PrintStream stream) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace(); StackTraceElement[] trace = Thread.currentThread().getStackTrace();
stream.printf("%s > %s called from %s%n", debugGetCurrThreadId(), stream.printf("%s > %s called from %s%n", debugGetCurrThreadId(gui),
trace[2].getClassName() + "." + trace[2].getMethodName(), trace[3].toString()); trace[2].getClassName() + "." + trace[2].getMethodName(), trace[3].toString());
int i = 0; int i = 0;
for (StackTraceElement se : trace) { for (StackTraceElement se : trace) {
@@ -93,7 +93,7 @@ public class FThreads {
} }
} }
public static String debugGetStackTraceItem(int depth, boolean shorter) { public static String debugGetStackTraceItem(final IGuiBase gui, final int depth, final boolean shorter) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace(); StackTraceElement[] trace = Thread.currentThread().getStackTrace();
String lastItem = trace[depth].toString(); String lastItem = trace[depth].toString();
if (shorter) { if (shorter) {
@@ -101,13 +101,13 @@ public class FThreads {
lastPeriod = lastItem.lastIndexOf('.', lastPeriod-1); lastPeriod = lastItem.lastIndexOf('.', lastPeriod-1);
lastPeriod = lastItem.lastIndexOf('.', lastPeriod-1); lastPeriod = lastItem.lastIndexOf('.', lastPeriod-1);
lastItem = lastItem.substring(lastPeriod+1); lastItem = lastItem.substring(lastPeriod+1);
return String.format("%s > from %s", debugGetCurrThreadId(), lastItem); return String.format("%s > from %s", debugGetCurrThreadId(gui), lastItem);
} }
return String.format("%s > %s called from %s", debugGetCurrThreadId(), return String.format("%s > %s called from %s", debugGetCurrThreadId(gui),
trace[2].getClassName() + "." + trace[2].getMethodName(), lastItem); trace[2].getClassName() + "." + trace[2].getMethodName(), lastItem);
} }
public static String debugGetStackTraceItem(int depth) { public static String debugGetStackTraceItem(final IGuiBase gui, final int depth) {
return debugGetStackTraceItem(depth, false); return debugGetStackTraceItem(gui, depth, false);
} }
} }

View File

@@ -17,20 +17,18 @@
*/ */
package forge.card; package forge.card;
import forge.CardStorageReader;
import forge.card.CardRules;
import forge.properties.ForgeConstants;
import forge.util.FileUtil;
import forge.util.gui.SOptionPane;
import org.apache.commons.lang3.StringUtils;
import java.io.File; import java.io.File;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import forge.CardStorageReader;
import forge.properties.ForgeConstants;
import forge.util.FileUtil;
public final class CardScriptInfo { public final class CardScriptInfo {
private String text; private String text;
private File file; private File file;
@@ -64,7 +62,8 @@ public final class CardScriptInfo {
return true; return true;
} }
catch (final Exception ex) { catch (final Exception ex) {
SOptionPane.showErrorDialog("Problem writing file - " + file + " : " + ex); System.err.println("Problem writing file - " + file);
ex.printStackTrace();
return false; return false;
} }
} }

View File

@@ -1,34 +1,69 @@
package forge.control; package forge.control;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.eventbus.Subscribe; import com.google.common.eventbus.Subscribe;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.game.Game; import forge.game.Game;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.event.*; import forge.game.event.GameEvent;
import forge.game.event.GameEventAnteCardsSelected;
import forge.game.event.GameEventAttackersDeclared;
import forge.game.event.GameEventBlockersDeclared;
import forge.game.event.GameEventCardAttachment;
import forge.game.event.GameEventCardCounters;
import forge.game.event.GameEventCardDamaged;
import forge.game.event.GameEventCardPhased;
import forge.game.event.GameEventCardStatsChanged;
import forge.game.event.GameEventCardTapped;
import forge.game.event.GameEventCombatEnded;
import forge.game.event.GameEventGameFinished;
import forge.game.event.GameEventGameOutcome;
import forge.game.event.GameEventManaPool;
import forge.game.event.GameEventPlayerControl;
import forge.game.event.GameEventPlayerLivesChanged;
import forge.game.event.GameEventPlayerPoisoned;
import forge.game.event.GameEventPlayerPriority;
import forge.game.event.GameEventSpellAbilityCast;
import forge.game.event.GameEventSpellRemovedFromStack;
import forge.game.event.GameEventSpellResolved;
import forge.game.event.GameEventTurnBegan;
import forge.game.event.GameEventTurnPhase;
import forge.game.event.GameEventZone;
import forge.game.event.IGameEventVisitor;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.zone.PlayerZone; import forge.game.zone.PlayerZone;
import forge.game.zone.Zone; import forge.game.zone.Zone;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import forge.interfaces.IGuiBase;
import forge.match.input.ButtonUtil; import forge.match.input.ButtonUtil;
import forge.match.input.InputBase; import forge.match.input.InputBase;
import forge.model.FModel; import forge.model.FModel;
import forge.player.PlayerControllerHuman;
import forge.properties.ForgePreferences.FPref; import forge.properties.ForgePreferences.FPref;
import forge.util.Lang; import forge.util.Lang;
import forge.util.gui.SGuiChoose; import forge.util.gui.SGuiChoose;
import forge.util.maps.MapOfLists; import forge.util.maps.MapOfLists;
import forge.view.CardView; import forge.view.CardView;
import forge.view.PlayerView;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> { public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
public FControlGameEventHandler() { private final PlayerControllerHuman controller;
private final IGuiBase gui;
public FControlGameEventHandler(final PlayerControllerHuman controller) {
this.controller = controller;
this.gui = controller.getGui();
} }
@Subscribe @Subscribe
@@ -41,11 +76,11 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
public Void visit(final GameEventTurnPhase ev) { public Void visit(final GameEventTurnPhase ev) {
if (phaseUpdPlanned.getAndSet(true)) return null; if (phaseUpdPlanned.getAndSet(true)) return null;
FThreads.invokeInEdtNowOrLater(new Runnable() { FThreads.invokeInEdtNowOrLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
phaseUpdPlanned.set(false); phaseUpdPlanned.set(false);
GuiBase.getInterface().updatePhase(); gui.updatePhase();
} }
}); });
return null; return null;
@@ -58,11 +93,11 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
@Override @Override
public Void visit(GameEventPlayerPriority event) { public Void visit(GameEventPlayerPriority event) {
if (combatUpdPlanned.getAndSet(true)) { return null; } if (combatUpdPlanned.getAndSet(true)) { return null; }
FThreads.invokeInEdtNowOrLater(new Runnable() { FThreads.invokeInEdtNowOrLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
combatUpdPlanned.set(false); combatUpdPlanned.set(false);
GuiBase.getInterface().showCombat(GuiBase.getInterface().getGame().getCombat()); gui.showCombat(controller.getCombat());
} }
}); });
return null; return null;
@@ -73,16 +108,16 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
public Void visit(final GameEventTurnBegan event) { public Void visit(final GameEventTurnBegan event) {
if (FModel.getPreferences().getPrefBoolean(FPref.UI_STACK_CREATURES) && event.turnOwner != null) { if (FModel.getPreferences().getPrefBoolean(FPref.UI_STACK_CREATURES) && event.turnOwner != null) {
// anything except stack will get here // anything except stack will get here
updateZone(Pair.of(event.turnOwner, ZoneType.Battlefield)); updateZone(Pair.of(controller.getPlayerView(event.turnOwner), ZoneType.Battlefield));
} }
if (turnUpdPlanned.getAndSet(true)) { return null; } if (turnUpdPlanned.getAndSet(true)) { return null; }
FThreads.invokeInEdtNowOrLater(new Runnable() { FThreads.invokeInEdtNowOrLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
turnUpdPlanned.set(false); turnUpdPlanned.set(false);
GuiBase.getInterface().updateTurn(event); gui.updateTurn(controller.getPlayerView(event.turnOwner));
} }
}); });
return null; return null;
@@ -97,20 +132,20 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
options.add(fakeCard); options.add(fakeCard);
options.add(kv.getValue()); options.add(kv.getValue());
} }
SGuiChoose.reveal("These cards were chosen to ante", options); SGuiChoose.reveal(gui, "These cards were chosen to ante", options);
return null; return null;
} }
@Override @Override
public Void visit(GameEventPlayerControl ev) { public Void visit(GameEventPlayerControl ev) {
if (GuiBase.getInterface().getGame().isGameOver()) { if (gui.getGame().isGameOver()) {
return null; return null;
} }
FThreads.invokeInEdtNowOrLater(new Runnable() { FThreads.invokeInEdtNowOrLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
GuiBase.getInterface().updatePlayerControl(); gui.updatePlayerControl();
} }
}); });
return null; return null;
@@ -119,25 +154,25 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
private final Runnable unlockGameThreadOnGameOver = new Runnable() { private final Runnable unlockGameThreadOnGameOver = new Runnable() {
@Override @Override
public void run() { public void run() {
GuiBase.getInterface().getInputQueue().onGameOver(true); // this will unlock any game threads waiting for inputs to complete gui.getInputQueue().onGameOver(true); // this will unlock any game threads waiting for inputs to complete
} }
}; };
@Override @Override
public Void visit(GameEventGameOutcome ev) { public Void visit(GameEventGameOutcome ev) {
FThreads.invokeInEdtNowOrLater(unlockGameThreadOnGameOver); FThreads.invokeInEdtNowOrLater(gui, unlockGameThreadOnGameOver);
return null; return null;
} }
@Override @Override
public Void visit(GameEventGameFinished ev) { public Void visit(GameEventGameFinished ev) {
FThreads.invokeInEdtNowOrLater(new Runnable() { FThreads.invokeInEdtNowOrLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
InputBase.cancelAwaitNextInput(); //ensure "Waiting for opponent..." doesn't appear behind WinLo InputBase.cancelAwaitNextInput(); //ensure "Waiting for opponent..." doesn't appear behind WinLo
GuiBase.getInterface().showPromptMessage(""); //clear prompt behind WinLose overlay gui.showPromptMessage(""); //clear prompt behind WinLose overlay
ButtonUtil.update("", "", false, false, false); ButtonUtil.update(gui, "", "", false, false, false);
GuiBase.getInterface().finishGame(); gui.finishGame();
} }
}); });
return null; return null;
@@ -148,38 +183,38 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
@Override @Override
public void run() { public void run() {
stackUpdPlanned.set(false); stackUpdPlanned.set(false);
GuiBase.getInterface().updateStack(); gui.updateStack();
} }
}; };
@Override @Override
public Void visit(GameEventSpellAbilityCast event) { public Void visit(GameEventSpellAbilityCast event) {
if (!stackUpdPlanned.getAndSet(true)) { if (!stackUpdPlanned.getAndSet(true)) {
FThreads.invokeInEdtNowOrLater(updStack); FThreads.invokeInEdtNowOrLater(gui, updStack);
} }
return null; return null;
} }
@Override @Override
public Void visit(GameEventSpellResolved event) { public Void visit(GameEventSpellResolved event) {
if (!stackUpdPlanned.getAndSet(true)) { if (!stackUpdPlanned.getAndSet(true)) {
FThreads.invokeInEdtNowOrLater(updStack); FThreads.invokeInEdtNowOrLater(gui, updStack);
} }
return null; return null;
} }
@Override @Override
public Void visit(GameEventSpellRemovedFromStack event) { public Void visit(GameEventSpellRemovedFromStack event) {
if (!stackUpdPlanned.getAndSet(true)) { if (!stackUpdPlanned.getAndSet(true)) {
FThreads.invokeInEdtNowOrLater(updStack); FThreads.invokeInEdtNowOrLater(gui, updStack);
} }
return null; return null;
} }
private final List<Pair<Player, ZoneType>> zonesToUpdate = new Vector<Pair<Player, ZoneType>>(); private final List<Pair<PlayerView, ZoneType>> zonesToUpdate = new Vector<Pair<PlayerView,ZoneType>>();
private final Runnable updZones = new Runnable() { private final Runnable updZones = new Runnable() {
@Override @Override
public void run() { public void run() {
synchronized (zonesToUpdate) { synchronized (zonesToUpdate) {
GuiBase.getInterface().updateZones(zonesToUpdate); gui.updateZones(zonesToUpdate);
zonesToUpdate.clear(); zonesToUpdate.clear();
} }
} }
@@ -189,7 +224,7 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
public Void visit(GameEventZone event) { public Void visit(GameEventZone event) {
if (event.player != null) { if (event.player != null) {
// anything except stack will get here // anything except stack will get here
updateZone(Pair.of(event.player, event.zoneType)); updateZone(Pair.of(controller.getPlayerView(event.player), event.zoneType));
} }
return null; return null;
} }
@@ -208,11 +243,11 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
return updateZone(zEq); return updateZone(zEq);
} }
private Void updateZone(Zone z) { private Void updateZone(final Zone z) {
return updateZone(Pair.of(z.getPlayer(), z.getZoneType())); return updateZone(Pair.of(controller.getPlayerView(z.getPlayer()), z.getZoneType()));
} }
private Void updateZone(Pair<Player, ZoneType> kv) { private Void updateZone(final Pair<PlayerView, ZoneType> kv) {
boolean needUpdate = false; boolean needUpdate = false;
synchronized (zonesToUpdate) { synchronized (zonesToUpdate) {
needUpdate = zonesToUpdate.isEmpty(); needUpdate = zonesToUpdate.isEmpty();
@@ -221,7 +256,7 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
} }
} }
if (needUpdate) { if (needUpdate) {
FThreads.invokeInEdtNowOrLater(updZones); FThreads.invokeInEdtNowOrLater(gui, updZones);
} }
return null; return null;
} }
@@ -231,37 +266,37 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
@Override @Override
public void run() { public void run() {
synchronized (cardsToUpdate) { synchronized (cardsToUpdate) {
GuiBase.getInterface().updateCards(cardsToUpdate); gui.updateCards(cardsToUpdate);
cardsToUpdate.clear(); cardsToUpdate.clear();
} }
} }
}; };
@Override @Override
public Void visit(GameEventCardTapped event) { public Void visit(final GameEventCardTapped event) {
return updateSingleCard(event.card); return updateSingleCard(controller.getCardView(event.card));
} }
@Override @Override
public Void visit(GameEventCardPhased event) { public Void visit(final GameEventCardPhased event) {
return updateSingleCard(event.card); return updateSingleCard(controller.getCardView(event.card));
} }
@Override @Override
public Void visit(GameEventCardDamaged event) { public Void visit(final GameEventCardDamaged event) {
return updateSingleCard(event.card); return updateSingleCard(controller.getCardView(event.card));
} }
@Override @Override
public Void visit(GameEventCardCounters event) { public Void visit(final GameEventCardCounters event) {
return updateSingleCard(event.card); return updateSingleCard(controller.getCardView(event.card));
} }
@Override @Override
public Void visit(GameEventBlockersDeclared event) { // This is to draw icons on blockers declared by AI public Void visit(final GameEventBlockersDeclared event) { // This is to draw icons on blockers declared by AI
for (MapOfLists<Card, Card> kv : event.blockers.values()) { for (MapOfLists<Card, Card> kv : event.blockers.values()) {
for (Collection<Card> blockers : kv.values()) { for (Collection<Card> blockers : kv.values()) {
updateManyCards(blockers); updateManyCards(controller.getCardViews(blockers));
} }
} }
return super.visit(event); return super.visit(event);
@@ -270,13 +305,13 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
@Override @Override
public Void visit(GameEventAttackersDeclared event) { public Void visit(GameEventAttackersDeclared event) {
// Skip redraw for GUI player? // Skip redraw for GUI player?
if (event.player.getLobbyPlayer() == GuiBase.getInterface().getGuiPlayer()) { if (event.player.getLobbyPlayer() == gui.getGuiPlayer()) {
return null; return null;
} }
// Update all attackers. // Update all attackers.
// Although they might have been updated when they were apped, there could be someone with vigilance, not redrawn yet. // Although they might have been updated when they were apped, there could be someone with vigilance, not redrawn yet.
updateManyCards(event.attackersMap.values()); updateManyCards(controller.getCardViews(event.attackersMap.values()));
return super.visit(event); return super.visit(event);
} }
@@ -284,8 +319,8 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
@Override @Override
public Void visit(GameEventCombatEnded event) { public Void visit(GameEventCombatEnded event) {
// This should remove sword/shield icons from combatants by the time game moves to M2 // This should remove sword/shield icons from combatants by the time game moves to M2
updateManyCards(event.attackers); updateManyCards(controller.getCardViews(event.attackers));
updateManyCards(event.blockers); updateManyCards(controller.getCardViews(event.blockers));
return null; return null;
} }
@@ -298,19 +333,19 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
} }
} }
if (needUpdate) { if (needUpdate) {
FThreads.invokeInEdtNowOrLater(updCards); FThreads.invokeInEdtNowOrLater(gui, updCards);
} }
return null; return null;
} }
private Void updateManyCards(Collection<Card> cc) { private Void updateManyCards(final Iterable<CardView> cc) {
boolean needUpdate = false; boolean needUpdate = false;
synchronized (cardsToUpdate) { synchronized (cardsToUpdate) {
needUpdate = cardsToUpdate.isEmpty(); needUpdate = cardsToUpdate.isEmpty();
cardsToUpdate.addAll(cc); Iterables.addAll(cardsToUpdate, cc);
} }
if (needUpdate) { if (needUpdate) {
FThreads.invokeInEdtNowOrLater(updCards); FThreads.invokeInEdtNowOrLater(gui, updCards);
} }
return null; return null;
} }
@@ -320,8 +355,9 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
*/ */
@Override @Override
public Void visit(GameEventCardStatsChanged event) { public Void visit(GameEventCardStatsChanged event) {
GuiBase.getInterface().refreshCardDetails(event.cards); final Iterable<CardView> cardViews = controller.getCardViews(event.cards);
return updateManyCards(event.cards); gui.refreshCardDetails(cardViews);
return updateManyCards(cardViews);
} }
// Update manapool // Update manapool
@@ -329,7 +365,7 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
private final Runnable updManaPool = new Runnable() { private final Runnable updManaPool = new Runnable() {
@Override public void run() { @Override public void run() {
synchronized (manaPoolUpdate) { synchronized (manaPoolUpdate) {
GuiBase.getInterface().updateManaPool(manaPoolUpdate); gui.updateManaPool(controller.getPlayerViews(manaPoolUpdate));
manaPoolUpdate.clear(); manaPoolUpdate.clear();
} }
} }
@@ -345,7 +381,7 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
} }
} }
if (invokeUpdate) { if (invokeUpdate) {
FThreads.invokeInEdtNowOrLater(updManaPool); FThreads.invokeInEdtNowOrLater(gui, updManaPool);
} }
return null; return null;
} }
@@ -355,7 +391,7 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
private final Runnable updLives = new Runnable() { private final Runnable updLives = new Runnable() {
@Override public void run() { @Override public void run() {
synchronized (livesUpdate) { synchronized (livesUpdate) {
GuiBase.getInterface().updateLives(livesUpdate); gui.updateLives(controller.getPlayerViews(livesUpdate));
livesUpdate.clear(); livesUpdate.clear();
} }
} }
@@ -370,7 +406,7 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
} }
} }
if (invokeUpdate) { if (invokeUpdate) {
FThreads.invokeInEdtNowOrLater(updLives); FThreads.invokeInEdtNowOrLater(gui, updLives);
} }
return null; return null;
} }
@@ -385,7 +421,7 @@ public class FControlGameEventHandler extends IGameEventVisitor.Base<Void> {
} }
} }
if (invokeUpdate) { if (invokeUpdate) {
FThreads.invokeInEdtNowOrLater(updLives); FThreads.invokeInEdtNowOrLater(gui, updLives);
} }
return null; return null;
} }

View File

@@ -1,23 +1,46 @@
package forge.control; package forge.control;
import com.google.common.eventbus.Subscribe;
import forge.FThreads;
import forge.GuiBase;
import forge.game.event.*;
import forge.match.input.InputPlaybackControl;
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier; import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import com.google.common.eventbus.Subscribe;
import forge.FThreads;
import forge.game.Game;
import forge.game.event.GameEvent;
import forge.game.event.GameEventBlockersDeclared;
import forge.game.event.GameEventGameFinished;
import forge.game.event.GameEventGameStarted;
import forge.game.event.GameEventLandPlayed;
import forge.game.event.GameEventPlayerPriority;
import forge.game.event.GameEventSpellAbilityCast;
import forge.game.event.GameEventSpellResolved;
import forge.game.event.GameEventTurnPhase;
import forge.game.event.IGameEventVisitor;
import forge.match.input.InputPlaybackControl;
import forge.player.PlayerControllerHuman;
public class FControlGamePlayback extends IGameEventVisitor.Base<Void> { public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
private final InputPlaybackControl inputPlayback = new InputPlaybackControl(this); private InputPlaybackControl inputPlayback;
private final AtomicBoolean paused = new AtomicBoolean(false); private final AtomicBoolean paused = new AtomicBoolean(false);
private final CyclicBarrier gameThreadPauser = new CyclicBarrier(2); private final CyclicBarrier gameThreadPauser = new CyclicBarrier(2);
public FControlGamePlayback() { private final PlayerControllerHuman controller;
public FControlGamePlayback(final PlayerControllerHuman controller) {
this.controller = controller;
}
private Game game;
public Game getGame() {
return game;
}
public void setGame(Game game) {
this.game = game;
this.inputPlayback = new InputPlaybackControl(controller.getGui(), game, this);
} }
@Subscribe @Subscribe
@@ -50,13 +73,14 @@ public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
*/ */
@Override @Override
public Void visit(GameEventTurnPhase ev) { public Void visit(GameEventTurnPhase ev) {
boolean isUiToStop = GuiBase.getInterface().stopAtPhase(ev.playerTurn, ev.phase); boolean isUiToStop = controller.getGui().stopAtPhase(
controller.getPlayerView(ev.playerTurn), ev.phase);
switch(ev.phase) { switch(ev.phase) {
case COMBAT_END: case COMBAT_END:
case COMBAT_DECLARE_ATTACKERS: case COMBAT_DECLARE_ATTACKERS:
case COMBAT_DECLARE_BLOCKERS: case COMBAT_DECLARE_BLOCKERS:
if (GuiBase.getInterface().getGame().getPhaseHandler().inCombat()) { if (getGame().getPhaseHandler().inCombat()) {
pauseForEvent(combatDelay); pauseForEvent(combatDelay);
} }
break; break;
@@ -75,13 +99,13 @@ public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
*/ */
@Override @Override
public Void visit(GameEventGameFinished event) { public Void visit(GameEventGameFinished event) {
GuiBase.getInterface().getInputQueue().removeInput(inputPlayback); controller.getGui().getInputQueue().removeInput(inputPlayback);
return null; return null;
} }
@Override @Override
public Void visit(GameEventGameStarted event) { public Void visit(GameEventGameStarted event) {
GuiBase.getInterface().getInputQueue().setInput(inputPlayback); controller.getGui().getInputQueue().setInput(inputPlayback);
return null; return null;
} }
@@ -93,7 +117,13 @@ public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
@Override @Override
public Void visit(final GameEventSpellResolved event) { public Void visit(final GameEventSpellResolved event) {
FThreads.invokeInEdtNowOrLater(new Runnable() { @Override public void run() { GuiBase.getInterface().setCard(event.spell.getHostCard()); } }); FThreads.invokeInEdtNowOrLater(controller.getGui(), new Runnable() {
@Override
public void run() {
controller.getGui().setCard(
controller.getCardView(event.spell.getHostCard()));
}
});
pauseForEvent(resolveDelay); pauseForEvent(resolveDelay);
return null; return null;
} }
@@ -103,7 +133,13 @@ public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
*/ */
@Override @Override
public Void visit(final GameEventSpellAbilityCast event) { public Void visit(final GameEventSpellAbilityCast event) {
FThreads.invokeInEdtNowOrLater(new Runnable() { @Override public void run() { GuiBase.getInterface().setCard(event.sa.getHostCard()); } }); FThreads.invokeInEdtNowOrLater(controller.getGui(), new Runnable() {
@Override
public void run() {
controller.getGui().setCard(
controller.getCardView(event.sa.getHostCard()));
}
});
pauseForEvent(castDelay); pauseForEvent(castDelay);
return null; return null;
} }
@@ -139,7 +175,7 @@ public class FControlGamePlayback extends IGameEventVisitor.Base<Void> {
private void releaseGameThread() { private void releaseGameThread() {
// just need to run another thread through the barrier... not edt preferrably :) // just need to run another thread through the barrier... not edt preferrably :)
GuiBase.getInterface().getGame().getAction().invoke(new Runnable() { getGame().getAction().invoke(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {

View File

@@ -3,17 +3,20 @@ package forge.deck;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import forge.interfaces.IGuiBase;
import forge.itemmanager.IItemManager; import forge.itemmanager.IItemManager;
public class ColorDeckGenerator extends DeckProxy implements Comparable<ColorDeckGenerator> { public class ColorDeckGenerator extends DeckProxy implements Comparable<ColorDeckGenerator> {
private final IGuiBase gui;
private String name; private String name;
private int index; private int index;
private final IItemManager<DeckProxy> lstDecks; private final IItemManager<DeckProxy> lstDecks;
private final boolean isAi; private final boolean isAi;
public ColorDeckGenerator(String name0, int index0, IItemManager<DeckProxy> lstDecks0, boolean isAi0) { public ColorDeckGenerator(final IGuiBase gui, String name0, int index0, IItemManager<DeckProxy> lstDecks0, boolean isAi0) {
super(); super();
this.gui = gui;
name = name0; name = name0;
index = index0; index = index0;
lstDecks = lstDecks0; lstDecks = lstDecks0;
@@ -42,7 +45,7 @@ public class ColorDeckGenerator extends DeckProxy implements Comparable<ColorDec
for (DeckProxy deck : lstDecks.getSelectedItems()) { for (DeckProxy deck : lstDecks.getSelectedItems()) {
selection.add(deck.getName()); selection.add(deck.getName());
} }
if (DeckgenUtil.colorCheck(selection)) { if (DeckgenUtil.colorCheck(gui, selection)) {
return DeckgenUtil.buildColorDeck(selection, isAi); return DeckgenUtil.buildColorDeck(selection, isAi);
} }
return null; return null;

View File

@@ -1,5 +1,11 @@
package forge.deck; package forge.deck;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@@ -9,11 +15,6 @@ import forge.card.CardEdition;
import forge.card.CardRarity; import forge.card.CardRarity;
import forge.card.ColorSet; import forge.card.ColorSet;
import forge.card.MagicColor; import forge.card.MagicColor;
import forge.deck.CardPool;
import forge.deck.Deck;
import forge.deck.DeckGroup;
import forge.deck.DeckSection;
import forge.error.BugReporter;
import forge.game.GameFormat; import forge.game.GameFormat;
import forge.game.GameType; import forge.game.GameType;
import forge.item.InventoryItem; import forge.item.InventoryItem;
@@ -28,12 +29,6 @@ import forge.util.IHasName;
import forge.util.storage.IStorage; import forge.util.storage.IStorage;
import forge.util.storage.StorageImmediatelySerialized; import forge.util.storage.StorageImmediatelySerialized;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
// Adding a generic to this class creates compile problems in ItemManager (that I can not fix) // Adding a generic to this class creates compile problems in ItemManager (that I can not fix)
public class DeckProxy implements InventoryItem { public class DeckProxy implements InventoryItem {
protected IHasName deck; protected IHasName deck;
@@ -361,7 +356,7 @@ public class DeckProxy implements InventoryItem {
StringBuilder errorBuilder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder();
deck.getMain().addAll(gen.getThemeDeck(this.getName(), 60, errorBuilder)); deck.getMain().addAll(gen.getThemeDeck(this.getName(), 60, errorBuilder));
if (errorBuilder.length() > 0) { if (errorBuilder.length() > 0) {
BugReporter.reportBug(errorBuilder.toString()); throw new RuntimeException(errorBuilder.toString());
} }
return deck; return deck;
} }

View File

@@ -12,6 +12,7 @@ import forge.deck.CardPool;
import forge.deck.Deck; import forge.deck.Deck;
import forge.deck.DeckSection; import forge.deck.DeckSection;
import forge.deck.generation.*; import forge.deck.generation.*;
import forge.interfaces.IGuiBase;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.itemmanager.IItemManager; import forge.itemmanager.IItemManager;
import forge.model.FModel; import forge.model.FModel;
@@ -186,18 +187,18 @@ public class DeckgenUtil {
* @param colors0 String[] * @param colors0 String[]
* @return boolean * @return boolean
*/ */
public static boolean colorCheck(final List<String> colors0) { public static boolean colorCheck(final IGuiBase gui, final List<String> colors0) {
boolean result = true; boolean result = true;
if (colors0.size() == 4) { if (colors0.size() == 4) {
SOptionPane.showMessageDialog( SOptionPane.showMessageDialog(gui,
"Sorry, four color generated decks aren't supported yet." "Sorry, four color generated decks aren't supported yet."
+ "\n\rPlease use 2, 3, or 5 colors for this deck.", + "\n\rPlease use 2, 3, or 5 colors for this deck.",
"Generate deck: 4 colors", SOptionPane.ERROR_ICON); "Generate deck: 4 colors", SOptionPane.ERROR_ICON);
result = false; result = false;
} }
else if (colors0.size() > 5) { else if (colors0.size() > 5) {
SOptionPane.showMessageDialog( SOptionPane.showMessageDialog(gui,
"Generate deck: maximum five colors!", "Generate deck: maximum five colors!",
"Generate deck: too many colors", SOptionPane.ERROR_ICON); "Generate deck: too many colors", SOptionPane.ERROR_ICON);
result = false; result = false;

View File

@@ -19,6 +19,7 @@ package forge.deck.io;
import forge.deck.Deck; import forge.deck.Deck;
import forge.deck.DeckGroup; import forge.deck.DeckGroup;
import forge.interfaces.IGuiBase;
import forge.properties.ForgeConstants; import forge.properties.ForgeConstants;
import forge.util.FileSection; import forge.util.FileSection;
import forge.util.FileUtil; import forge.util.FileUtil;
@@ -47,6 +48,8 @@ public class OldDeckParser {
} }
}; };
private final IGuiBase gui;
/** /**
* TODO: Write javadoc for Constructor. * TODO: Write javadoc for Constructor.
* *
@@ -56,8 +59,9 @@ public class OldDeckParser {
* @param sealed2 the sealed2 * @param sealed2 the sealed2
* @param cube2 the cube2 * @param cube2 the cube2
*/ */
public OldDeckParser(final IStorage<Deck> constructed2, final IStorage<DeckGroup> draft2, public OldDeckParser(final IGuiBase gui, final IStorage<Deck> constructed2, final IStorage<DeckGroup> draft2,
final IStorage<DeckGroup> sealed2, final IStorage<Deck> cube2) { final IStorage<DeckGroup> sealed2, final IStorage<Deck> cube2) {
this.gui = gui;
this.deckDir = new File(ForgeConstants.DECK_BASE_DIR); this.deckDir = new File(ForgeConstants.DECK_BASE_DIR);
this.sealed = sealed2; this.sealed = sealed2;
this.constructed = constructed2; this.constructed = constructed2;
@@ -145,7 +149,7 @@ public class OldDeckParser {
this.draft.add(d); this.draft.add(d);
} else { } else {
final String msg = String.format("Draft '%s' lacked some decks.%n%nShould it be deleted?"); final String msg = String.format("Draft '%s' lacked some decks.%n%nShould it be deleted?");
mayDelete = SOptionPane.showConfirmDialog(msg, "Draft loading error"); mayDelete = SOptionPane.showConfirmDialog(gui, msg, "Draft loading error");
} }
if (mayDelete) { if (mayDelete) {
@@ -181,7 +185,7 @@ public class OldDeckParser {
final String msg = String final String msg = String
.format("Can not convert deck '%s' for some unsupported cards it contains. %n%s%n%nMay Forge delete all such decks?", .format("Can not convert deck '%s' for some unsupported cards it contains. %n%s%n%nMay Forge delete all such decks?",
name, ex.getMessage()); name, ex.getMessage());
allowDeleteUnsupportedConstructed = SOptionPane.showConfirmDialog(msg, "Problem converting decks"); allowDeleteUnsupportedConstructed = SOptionPane.showConfirmDialog(gui, msg, "Problem converting decks");
} }
} }
if (importedOk || allowDeleteUnsupportedConstructed) { if (importedOk || allowDeleteUnsupportedConstructed) {
@@ -200,7 +204,7 @@ public class OldDeckParser {
final String msg = String final String msg = String
.format("Can not convert deck '%s' for some unsupported cards it contains. %n%s%n%nMay Forge delete all such decks?", .format("Can not convert deck '%s' for some unsupported cards it contains. %n%s%n%nMay Forge delete all such decks?",
name, ex.getMessage()); name, ex.getMessage());
allowDeleteUnsupportedConstructed = SOptionPane.showConfirmDialog(msg, "Problem converting decks"); allowDeleteUnsupportedConstructed = SOptionPane.showConfirmDialog(gui, msg, "Problem converting decks");
} }
} }
if (importedOk || allowDeleteUnsupportedConstructed) { if (importedOk || allowDeleteUnsupportedConstructed) {
@@ -252,7 +256,7 @@ public class OldDeckParser {
} }
sb.append(System.getProperty("line.separator")); sb.append(System.getProperty("line.separator"));
sb.append("May Forge delete these decks?"); sb.append("May Forge delete these decks?");
if (SOptionPane.showConfirmDialog(sb.toString(), "Some of your sealed decks are orphaned")) { if (SOptionPane.showConfirmDialog(gui, sb.toString(), "Some of your sealed decks are orphaned")) {
for (final Pair<DeckGroup, MutablePair<File, File>> s : sealedDecks.values()) { for (final Pair<DeckGroup, MutablePair<File, File>> s : sealedDecks.values()) {
if (s.getRight().getLeft() != null) { if (s.getRight().getLeft() != null) {
s.getRight().getLeft().delete(); s.getRight().getLeft().delete();

View File

@@ -17,31 +17,36 @@
*/ */
package forge.download; package forge.download;
import com.esotericsoftware.minlog.Log;
import forge.FThreads;
import forge.GuiBase;
import forge.UiCommand;
import forge.error.BugReporter;
import forge.interfaces.IButton;
import forge.interfaces.IProgressBar;
import forge.interfaces.ITextField;
import forge.util.FileUtil;
import forge.util.MyRandom;
import org.apache.commons.lang3.tuple.Pair;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.*; import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.nio.channels.Channels; import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Random; import java.util.Random;
import org.apache.commons.lang3.tuple.Pair;
import com.esotericsoftware.minlog.Log;
import forge.FThreads;
import forge.UiCommand;
import forge.error.BugReporter;
import forge.interfaces.IButton;
import forge.interfaces.IGuiBase;
import forge.interfaces.IProgressBar;
import forge.interfaces.ITextField;
import forge.util.FileUtil;
import forge.util.MyRandom;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public abstract class GuiDownloadService implements Runnable { public abstract class GuiDownloadService implements Runnable {
public static final Proxy.Type[] TYPES = Proxy.Type.values(); public static final Proxy.Type[] TYPES = Proxy.Type.values();
@@ -53,12 +58,13 @@ public abstract class GuiDownloadService implements Runnable {
private IButton btnStart; private IButton btnStart;
private UiCommand cmdClose; private UiCommand cmdClose;
private Runnable onUpdate; private Runnable onUpdate;
private IGuiBase gui;
private final UiCommand cmdStartDownload = new UiCommand() { private final UiCommand cmdStartDownload = new UiCommand() {
@Override @Override
public void run() { public void run() {
//invalidate image cache so newly downloaded images will be loaded //invalidate image cache so newly downloaded images will be loaded
GuiBase.getInterface().clearImageCache(); gui.clearImageCache();
FThreads.invokeInBackgroundThread(GuiDownloadService.this); FThreads.invokeInBackgroundThread(GuiDownloadService.this);
btnStart.setEnabled(false); btnStart.setEnabled(false);
} }
@@ -78,13 +84,14 @@ public abstract class GuiDownloadService implements Runnable {
protected GuiDownloadService() { protected GuiDownloadService() {
} }
public void initialize(ITextField txtAddress0, ITextField txtPort0, IProgressBar progressBar0, IButton btnStart0, UiCommand cmdClose0, final Runnable onReadyToStart, Runnable onUpdate0) { public void initialize(final IGuiBase gui, ITextField txtAddress0, ITextField txtPort0, IProgressBar progressBar0, IButton btnStart0, UiCommand cmdClose0, final Runnable onReadyToStart, Runnable onUpdate0) {
txtAddress = txtAddress0; txtAddress = txtAddress0;
txtPort = txtPort0; txtPort = txtPort0;
progressBar = progressBar0; progressBar = progressBar0;
btnStart = btnStart0; btnStart = btnStart0;
cmdClose = cmdClose0; cmdClose = cmdClose0;
onUpdate = onUpdate0; onUpdate = onUpdate0;
this.gui = gui;
// Free up the EDT by assembling card list on a background thread // Free up the EDT by assembling card list on a background thread
FThreads.invokeInBackgroundThread(new Runnable() { FThreads.invokeInBackgroundThread(new Runnable() {
@@ -96,7 +103,7 @@ public abstract class GuiDownloadService implements Runnable {
catch (Exception e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
if (onReadyToStart != null) { if (onReadyToStart != null) {
@@ -123,7 +130,7 @@ public abstract class GuiDownloadService implements Runnable {
} }
btnStart.setEnabled(true); btnStart.setEnabled(true);
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
btnStart.requestFocusInWindow(); btnStart.requestFocusInWindow();
@@ -162,7 +169,7 @@ public abstract class GuiDownloadService implements Runnable {
} }
private void update(final int count, final File dest) { private void update(final int count, final File dest) {
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
if (onUpdate != null) { if (onUpdate != null) {

View File

@@ -17,16 +17,21 @@
*/ */
package forge.error; package forge.error;
import forge.FThreads; import java.io.BufferedWriter;
import forge.GuiBase; import java.io.File;
import forge.util.BuildInfo; import java.io.FileWriter;
import forge.util.gui.SOptionPane; import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.io.*; import forge.FThreads;
import java.util.Map; import forge.interfaces.IGuiBase;
import java.util.Map.Entry; import forge.util.BuildInfo;
import forge.util.gui.SOptionPane;
/** /**
* The class ErrorViewer. Enables showing and saving error messages that * The class ErrorViewer. Enables showing and saving error messages that
@@ -68,22 +73,22 @@ public class BugReporter {
* Shows exception information in a format ready to post to the forum as a crash report. Uses the exception's message * Shows exception information in a format ready to post to the forum as a crash report. Uses the exception's message
* as the reason if message is null. * as the reason if message is null.
*/ */
public static void reportException(final Throwable ex, final String message) { public static void reportException(final Throwable ex, final IGuiBase gui, final String message) {
if (ex == null) { if (ex == null) {
return; return;
} }
if (message != null) { if (message != null) {
System.err.printf("%s > %s%n", FThreads.debugGetCurrThreadId(), message); System.err.printf("%s > %s%n", FThreads.debugGetCurrThreadId(gui), message);
} }
System.err.print(FThreads.debugGetCurrThreadId() + " > "); System.err.print(FThreads.debugGetCurrThreadId(gui) + " > ");
ex.printStackTrace(); ex.printStackTrace();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Description: [describe what you were doing when the crash occurred]\n\n"); sb.append("Description: [describe what you were doing when the crash occurred]\n\n");
buildSpoilerHeader(sb, ex.getClass().getSimpleName()); buildSpoilerHeader(gui, sb, ex.getClass().getSimpleName());
sb.append("\n\n"); sb.append("\n\n");
if (null != message && !message.isEmpty()) { if (null != message && !message.isEmpty()) {
sb.append(FThreads.debugGetCurrThreadId()).append(" > ").append(message).append("\n"); sb.append(FThreads.debugGetCurrThreadId(gui)).append(" > ").append(message).append("\n");
} }
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
@@ -103,7 +108,7 @@ public class BugReporter {
buildSpoilerFooter(sb); buildSpoilerFooter(sb);
GuiBase.getInterface().showBugReportDialog("Report a crash", sb.toString(), true); gui.showBugReportDialog("Report a crash", sb.toString(), true);
} }
/** /**
@@ -123,26 +128,26 @@ public class BugReporter {
/** /**
* Shows a forum post template for reporting a bug. * Shows a forum post template for reporting a bug.
*/ */
public static void reportBug(String details) { public static void reportBug(final IGuiBase gui, final String details) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Description: [describe the problem]\n\n"); sb.append("Description: [describe the problem]\n\n");
buildSpoilerHeader(sb, "General bug report"); buildSpoilerHeader(gui, sb, "General bug report");
if (null != details && !details.isEmpty()) { if (null != details && !details.isEmpty()) {
sb.append("\n\n"); sb.append("\n\n");
sb.append(details); sb.append(details);
} }
buildSpoilerFooter(sb); buildSpoilerFooter(sb);
GuiBase.getInterface().showBugReportDialog("Report a bug", sb.toString(), false); gui.showBugReportDialog("Report a bug", sb.toString(), false);
} }
/** /**
* Shows thread stack information in a format ready to post to the forum. * Shows thread stack information in a format ready to post to the forum.
*/ */
public static void reportThreadStacks(final String message) { public static void reportThreadStacks(final IGuiBase gui,final String message) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Description: [describe what you were doing at the time]\n\n"); sb.append("Description: [describe what you were doing at the time]\n\n");
buildSpoilerHeader(sb, "Thread stack dump"); buildSpoilerHeader(gui, sb, "Thread stack dump");
sb.append("\n\n"); sb.append("\n\n");
if (null != message && !message.isEmpty()) { if (null != message && !message.isEmpty()) {
sb.append(message); sb.append(message);
@@ -162,7 +167,7 @@ public class BugReporter {
sb.append(sw.toString()); sb.append(sw.toString());
buildSpoilerFooter(sb); buildSpoilerFooter(sb);
GuiBase.getInterface().showBugReportDialog("Thread stack dump", sb.toString(), false); gui.showBugReportDialog("Thread stack dump", sb.toString(), false);
} }
/** /**
@@ -172,9 +177,9 @@ public class BugReporter {
reportThreadStacks(String.format(format, args)); reportThreadStacks(String.format(format, args));
} }
private static StringBuilder buildSpoilerHeader(StringBuilder sb, String reportTitle) { private static StringBuilder buildSpoilerHeader(final IGuiBase gui, final StringBuilder sb, final String reportTitle) {
sb.append("[spoiler=").append(reportTitle).append("][code]"); sb.append("[spoiler=").append(reportTitle).append("][code]");
sb.append("\nForge Version: ").append(GuiBase.getInterface().getCurrentVersion()); sb.append("\nForge Version: ").append(gui.getCurrentVersion());
sb.append("\nOperating System: ").append(System.getProperty("os.name")) sb.append("\nOperating System: ").append(System.getProperty("os.name"))
.append(" ").append(System.getProperty("os.version")) .append(" ").append(System.getProperty("os.version"))
.append(" ").append(System.getProperty("os.arch")); .append(" ").append(System.getProperty("os.arch"));
@@ -188,19 +193,19 @@ public class BugReporter {
return sb; return sb;
} }
public static void copyAndGoToForums(String text) { public static void copyAndGoToForums(final IGuiBase gui, final String text) {
try { try {
// copy text to clipboard // copy text to clipboard
GuiBase.getInterface().copyToClipboard(text); gui.copyToClipboard(text);
GuiBase.getInterface().browseToUrl(FORUM_URL); gui.browseToUrl(FORUM_URL);
} }
catch (Exception ex) { catch (Exception ex) {
SOptionPane.showMessageDialog("Sorry, a problem occurred while opening the forum in your default browser.", SOptionPane.showMessageDialog(gui, "Sorry, a problem occurred while opening the forum in your default browser.",
"A problem occurred", SOptionPane.ERROR_ICON); "A problem occurred", SOptionPane.ERROR_ICON);
} }
} }
public static void saveToFile(String text) { public static void saveToFile(final IGuiBase gui, final String text) {
File f; File f;
long curTime = System.currentTimeMillis(); long curTime = System.currentTimeMillis();
for (int i = 0;; i++) { for (int i = 0;; i++) {
@@ -211,7 +216,7 @@ public class BugReporter {
} }
} }
f = GuiBase.getInterface().getSaveFile(f); f = gui.getSaveFile(f);
try { try {
final BufferedWriter bw = new BufferedWriter(new FileWriter(f)); final BufferedWriter bw = new BufferedWriter(new FileWriter(f));
@@ -219,7 +224,7 @@ public class BugReporter {
bw.close(); bw.close();
} }
catch (final IOException ex) { catch (final IOException ex) {
SOptionPane.showMessageDialog("There was an error during saving. Sorry!\n" + ex, SOptionPane.showMessageDialog(gui, "There was an error during saving. Sorry!\n" + ex,
"Error saving file", SOptionPane.ERROR_ICON); "Error saving file", SOptionPane.ERROR_ICON);
} }
} }

View File

@@ -4,7 +4,6 @@ import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import forge.GuiBase;
import forge.LobbyPlayer; import forge.LobbyPlayer;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.deck.Deck; import forge.deck.Deck;
@@ -19,10 +18,12 @@ import forge.view.IGameView;
public abstract class GauntletWinLoseController { public abstract class GauntletWinLoseController {
private final IGameView lastGame; private final IGameView lastGame;
private final IWinLoseView<? extends IButton> view; private final IWinLoseView<? extends IButton> view;
private final IGuiBase gui;
public GauntletWinLoseController(IWinLoseView<? extends IButton> view0, final IGameView game0) { public GauntletWinLoseController(IWinLoseView<? extends IButton> view0, final IGameView game0, final IGuiBase gui) {
view = view0; view = view0;
lastGame = game0; lastGame = game0;
this.gui = gui;
} }
public void showOutcome() { public void showOutcome() {
@@ -47,7 +48,7 @@ public abstract class GauntletWinLoseController {
// the player can restart Forge to replay a match. // the player can restart Forge to replay a match.
// Pretty sure this can't be fixed until in-game states can be // Pretty sure this can't be fixed until in-game states can be
// saved. Doublestrike 07-10-12 // saved. Doublestrike 07-10-12
LobbyPlayer questPlayer = GuiBase.getInterface().getQuestPlayer(); LobbyPlayer questPlayer = gui.getQuestPlayer();
// In all cases, update stats. // In all cases, update stats.
lstEventRecords.set(gd.getCompleted(), lastGame.getGamesWonBy(questPlayer) + " - " lstEventRecords.set(gd.getCompleted(), lastGame.getGamesWonBy(questPlayer) + " - "
@@ -114,15 +115,14 @@ public abstract class GauntletWinLoseController {
GauntletData gd = FModel.getGauntletData(); GauntletData gd = FModel.getGauntletData();
Deck aiDeck = gd.getDecks().get(gd.getCompleted()); Deck aiDeck = gd.getDecks().get(gd.getCompleted());
List<RegisteredPlayer> players = Lists.newArrayList(); List<RegisteredPlayer> players = Lists.newArrayList();
IGuiBase fc = GuiBase.getInterface(); players.add(new RegisteredPlayer(gd.getUserDeck()).setPlayer(gui.getGuiPlayer()));
players.add(new RegisteredPlayer(gd.getUserDeck()).setPlayer(fc.getGuiPlayer())); players.add(new RegisteredPlayer(aiDeck).setPlayer(gui.createAiPlayer()));
players.add(new RegisteredPlayer(aiDeck).setPlayer(fc.createAiPlayer()));
view.hide(); view.hide();
saveOptions(); saveOptions();
GuiBase.getInterface().endCurrentGame(); gui.endCurrentGame();
GuiBase.getInterface().startMatch(GameType.Gauntlet, players); gui.startMatch(GameType.Gauntlet, players);
return true; return true;
} }
return false; return false;

View File

@@ -20,7 +20,6 @@ import forge.game.Match;
import forge.game.phase.PhaseType; import forge.game.phase.PhaseType;
import forge.game.player.IHasIcon; import forge.game.player.IHasIcon;
import forge.game.player.RegisteredPlayer; import forge.game.player.RegisteredPlayer;
import forge.game.spellability.SpellAbility;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.match.input.InputQueue; import forge.match.input.InputQueue;
@@ -32,6 +31,7 @@ import forge.view.CombatView;
import forge.view.GameEntityView; import forge.view.GameEntityView;
import forge.view.IGameView; import forge.view.IGameView;
import forge.view.PlayerView; import forge.view.PlayerView;
import forge.view.SpellAbilityView;
public interface IGuiBase { public interface IGuiBase {
boolean isRunningOnDesktop(); boolean isRunningOnDesktop();
@@ -81,7 +81,7 @@ public interface IGuiBase {
void updateStack(); void updateStack();
void updateZones(List<Pair<PlayerView, ZoneType>> zonesToUpdate); void updateZones(List<Pair<PlayerView, ZoneType>> zonesToUpdate);
void updateCards(Set<CardView> cardsToUpdate); void updateCards(Set<CardView> cardsToUpdate);
void refreshCardDetails(Collection<CardView> cards); void refreshCardDetails(Iterable<CardView> cards);
void updateManaPool(List<PlayerView> manaPoolUpdate); void updateManaPool(List<PlayerView> manaPoolUpdate);
void updateLives(List<PlayerView> livesUpdate); void updateLives(List<PlayerView> livesUpdate);
void endCurrentGame(); void endCurrentGame();
@@ -89,7 +89,7 @@ public interface IGuiBase {
void setPanelSelection(CardView hostCard); void setPanelSelection(CardView hostCard);
Map<CardView, Integer> getDamageToAssign(CardView attacker, List<CardView> blockers, Map<CardView, Integer> getDamageToAssign(CardView attacker, List<CardView> blockers,
int damageDealt, GameEntityView defender, boolean overrideOrder); int damageDealt, GameEntityView defender, boolean overrideOrder);
SpellAbility getAbilityToPlay(List<SpellAbility> abilities, ITriggerEvent triggerEvent); SpellAbilityView getAbilityToPlay(List<SpellAbilityView> abilities, ITriggerEvent triggerEvent);
void hear(LobbyPlayer player, String message); void hear(LobbyPlayer player, String message);
int getAvatarCount(); int getAvatarCount();
void copyToClipboard(String text); void copyToClipboard(String text);

View File

@@ -25,6 +25,7 @@ import forge.card.UnOpenedProduct;
import forge.deck.CardPool; import forge.deck.CardPool;
import forge.deck.Deck; import forge.deck.Deck;
import forge.game.card.Card; import forge.game.card.Card;
import forge.interfaces.IGuiBase;
import forge.item.IPaperCard; import forge.item.IPaperCard;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.item.SealedProduct; import forge.item.SealedProduct;
@@ -66,13 +67,13 @@ public class BoosterDraft implements IBoosterDraft {
protected final List<Supplier<List<PaperCard>>> product = new ArrayList<Supplier<List<PaperCard>>>(); protected final List<Supplier<List<PaperCard>>> product = new ArrayList<Supplier<List<PaperCard>>>();
public static BoosterDraft createDraft(final LimitedPoolType draftType) { public static BoosterDraft createDraft(final IGuiBase gui, final LimitedPoolType draftType) {
BoosterDraft draft = new BoosterDraft(draftType); BoosterDraft draft = new BoosterDraft(draftType);
if (!draft.generateProduct()) { return null; } if (!draft.generateProduct(gui)) { return null; }
return draft; return draft;
} }
protected boolean generateProduct() { protected boolean generateProduct(final IGuiBase gui) {
switch (this.draftFormat) { switch (this.draftFormat) {
case Full: // Draft from all cards in Forge case Full: // Draft from all cards in Forge
Supplier<List<PaperCard>> s = new UnOpenedProduct(SealedProduct.Template.genericBooster); Supplier<List<PaperCard>> s = new UnOpenedProduct(SealedProduct.Template.genericBooster);
@@ -95,12 +96,12 @@ public class BoosterDraft implements IBoosterDraft {
} }
} }
final CardBlock block = SGuiChoose.oneOrNone("Choose Block", blocks); final CardBlock block = SGuiChoose.oneOrNone(gui, "Choose Block", blocks);
if (block == null) { return false; } if (block == null) { return false; }
final CardEdition[] cardSets = block.getSets(); final CardEdition[] cardSets = block.getSets();
if (cardSets.length == 0) { if (cardSets.length == 0) {
SOptionPane.showErrorDialog(block.toString() + " does not contain any set combinations."); SOptionPane.showErrorDialog(gui, block.toString() + " does not contain any set combinations.");
return false; return false;
} }
@@ -118,16 +119,16 @@ public class BoosterDraft implements IBoosterDraft {
final int nPacks = block.getCntBoostersDraft(); final int nPacks = block.getCntBoostersDraft();
if (sets.size() > 1) { if (sets.size() > 1) {
final Object p = SGuiChoose.oneOrNone("Choose Set Combination", getSetCombos(sets)); final Object p = SGuiChoose.oneOrNone(gui, "Choose Set Combination", getSetCombos(sets));
if (p == null) { return false; } if (p == null) { return false; }
final String[] pp = p.toString().split("/"); final String[] pp = p.toString().split("/");
for (int i = 0; i < nPacks; i++) { for (int i = 0; i < nPacks; i++) {
this.product.add(block.getBooster(pp[i])); this.product.add(block.getBooster(pp[i], gui));
} }
} }
else { else {
IUnOpenedProduct product1 = block.getBooster(sets.get(0)); IUnOpenedProduct product1 = block.getBooster(sets.get(0), gui);
for (int i = 0; i < nPacks; i++) { for (int i = 0; i < nPacks; i++) {
this.product.add(product1); this.product.add(product1);
@@ -141,10 +142,10 @@ public class BoosterDraft implements IBoosterDraft {
final List<CustomLimited> myDrafts = this.loadCustomDrafts(); final List<CustomLimited> myDrafts = this.loadCustomDrafts();
if (myDrafts.isEmpty()) { if (myDrafts.isEmpty()) {
SOptionPane.showMessageDialog("No custom draft files found."); SOptionPane.showMessageDialog(gui, "No custom draft files found.");
} }
else { else {
final CustomLimited customDraft = SGuiChoose.oneOrNone("Choose Custom Draft", myDrafts); final CustomLimited customDraft = SGuiChoose.oneOrNone(gui, "Choose Custom Draft", myDrafts);
if (customDraft == null) { return false; } if (customDraft == null) { return false; }
this.setupCustomDraft(customDraft); this.setupCustomDraft(customDraft);
@@ -159,13 +160,13 @@ public class BoosterDraft implements IBoosterDraft {
return true; return true;
} }
public static BoosterDraft createDraft(final LimitedPoolType draftType, final CardBlock block, final String[] boosters) { public static BoosterDraft createDraft(final IGuiBase gui, final LimitedPoolType draftType, final CardBlock block, final String[] boosters) {
BoosterDraft draft = new BoosterDraft(draftType); BoosterDraft draft = new BoosterDraft(draftType);
final int nPacks = boosters.length; final int nPacks = boosters.length;
for (int i = 0; i < nPacks; i++) { for (int i = 0; i < nPacks; i++) {
draft.product.add(block.getBooster(boosters[i])); draft.product.add(block.getBooster(boosters[i], gui));
} }
IBoosterDraft.LAND_SET_CODE[0] = block.getLandSet(); IBoosterDraft.LAND_SET_CODE[0] = block.getLandSet();

View File

@@ -17,7 +17,9 @@
*/ */
package forge.limited; package forge.limited;
import forge.GuiBase; import java.util.ArrayList;
import java.util.List;
import forge.deck.Deck; import forge.deck.Deck;
import forge.game.GameType; import forge.game.GameType;
import forge.game.player.RegisteredPlayer; import forge.game.player.RegisteredPlayer;
@@ -25,9 +27,6 @@ import forge.interfaces.IGuiBase;
import forge.model.FModel; import forge.model.FModel;
import forge.util.Aggregates; import forge.util.Aggregates;
import java.util.ArrayList;
import java.util.List;
/** /**
* <p> * <p>
* GauntletMini class. * GauntletMini class.
@@ -39,6 +38,7 @@ import java.util.List;
*/ */
public class GauntletMini { public class GauntletMini {
private final IGuiBase gui;
private int rounds; private int rounds;
private Deck humanDeck; private Deck humanDeck;
private int currentRound; private int currentRound;
@@ -48,6 +48,10 @@ public class GauntletMini {
private GameType gauntletType; private GameType gauntletType;
private List<RegisteredPlayer> aiOpponents = new ArrayList<RegisteredPlayer>(); private List<RegisteredPlayer> aiOpponents = new ArrayList<RegisteredPlayer>();
public GauntletMini(IGuiBase gui) {
this.gui = gui;
}
// private final String humanName; // private final String humanName;
/** /**
* TODO: Write javadoc for Constructor. * TODO: Write javadoc for Constructor.
@@ -81,7 +85,7 @@ public class GauntletMini {
} }
currentRound++; currentRound++;
GuiBase.getInterface().endCurrentGame(); gui.endCurrentGame();
startRound(); startRound();
} }
@@ -135,11 +139,10 @@ public class GauntletMini {
*/ */
private void startRound() { private void startRound() {
List<RegisteredPlayer> starter = new ArrayList<RegisteredPlayer>(); List<RegisteredPlayer> starter = new ArrayList<RegisteredPlayer>();
IGuiBase fc = GuiBase.getInterface(); starter.add(new RegisteredPlayer(humanDeck).setPlayer(gui.getGuiPlayer()));
starter.add(new RegisteredPlayer(humanDeck).setPlayer(fc.getGuiPlayer())); starter.add(aiOpponents.get(currentRound - 1).setPlayer(gui.createAiPlayer()));
starter.add(aiOpponents.get(currentRound - 1).setPlayer(fc.createAiPlayer()));
fc.startMatch(gauntletType, starter); gui.startMatch(gauntletType, starter);
} }
/** /**

View File

@@ -1,23 +1,25 @@
package forge.limited; package forge.limited;
import forge.GuiBase;
import forge.interfaces.IButton; import forge.interfaces.IButton;
import forge.interfaces.IGuiBase;
import forge.interfaces.IWinLoseView; import forge.interfaces.IWinLoseView;
import forge.model.FModel; import forge.model.FModel;
import forge.view.IGameView; import forge.view.IGameView;
public abstract class LimitedWinLoseController { public abstract class LimitedWinLoseController {
private final IGameView lastGame;
private final boolean wonMatch;
private final IWinLoseView<? extends IButton> view; private final IWinLoseView<? extends IButton> view;
private final IGameView lastGame;
private final IGuiBase gui;
private final boolean wonMatch;
private GauntletMini gauntlet; private GauntletMini gauntlet;
private boolean nextRound = false; private boolean nextRound = false;
public LimitedWinLoseController(IWinLoseView<? extends IButton> view0, final IGameView game0) { public LimitedWinLoseController(IWinLoseView<? extends IButton> view0, final IGameView game0, final IGuiBase gui) {
view = view0; view = view0;
lastGame = game0; lastGame = game0;
gauntlet = FModel.getGauntletMini(); this.gui = gui;
wonMatch = lastGame.isMatchWonBy(GuiBase.getInterface().getGuiPlayer()); gauntlet = FModel.getGauntletMini(gui);
wonMatch = lastGame.isMatchWonBy(gui.getGuiPlayer());
} }
public void showOutcome() { public void showOutcome() {
@@ -29,7 +31,7 @@ public abstract class LimitedWinLoseController {
resetView(); resetView();
nextRound = false; nextRound = false;
if (lastGame.isWinner(GuiBase.getInterface().getGuiPlayer())) { if (lastGame.isWinner(gui.getGuiPlayer())) {
gauntlet.addWin(); gauntlet.addWin();
} else { } else {
gauntlet.addLoss(); gauntlet.addLoss();

View File

@@ -26,6 +26,7 @@ import forge.deck.CardPool;
import forge.deck.Deck; import forge.deck.Deck;
import forge.deck.DeckGroup; import forge.deck.DeckGroup;
import forge.deck.DeckSection; import forge.deck.DeckSection;
import forge.interfaces.IGuiBase;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.item.SealedProduct; import forge.item.SealedProduct;
import forge.model.CardBlock; import forge.model.CardBlock;
@@ -66,12 +67,12 @@ public class SealedCardPoolGenerator {
/** The Land set code. */ /** The Land set code. */
private String landSetCode = null; private String landSetCode = null;
public static DeckGroup generateSealedDeck(boolean addBasicLands) { public static DeckGroup generateSealedDeck(final IGuiBase gui, final boolean addBasicLands) {
final String prompt = "Choose Sealed Deck Format"; final String prompt = "Choose Sealed Deck Format";
final LimitedPoolType poolType = SGuiChoose.oneOrNone(prompt, LimitedPoolType.values()); final LimitedPoolType poolType = SGuiChoose.oneOrNone(gui, prompt, LimitedPoolType.values());
if (poolType == null) { return null; } if (poolType == null) { return null; }
SealedCardPoolGenerator sd = new SealedCardPoolGenerator(poolType); SealedCardPoolGenerator sd = new SealedCardPoolGenerator(gui, poolType);
if (sd.isEmpty()) { return null; } if (sd.isEmpty()) { return null; }
final CardPool humanPool = sd.getCardPool(true); final CardPool humanPool = sd.getCardPool(true);
@@ -82,10 +83,10 @@ public class SealedCardPoolGenerator {
// This seems to be limited by the MAX_DRAFT_PLAYERS constant // This seems to be limited by the MAX_DRAFT_PLAYERS constant
// in DeckGroupSerializer.java. You could create more AI decks // in DeckGroupSerializer.java. You could create more AI decks
// but only the first seven would load. --BBU // but only the first seven would load. --BBU
Integer rounds = SGuiChoose.getInteger("How many opponents are you willing to face?", 1, 7); Integer rounds = SGuiChoose.getInteger(gui, "How many opponents are you willing to face?", 1, 7);
if (rounds == null) { return null; } if (rounds == null) { return null; }
final String sDeckName = SOptionPane.showInputDialog( final String sDeckName = SOptionPane.showInputDialog(gui,
"Save this card pool as:", "Save this card pool as:",
"Save Card Pool", "Save Card Pool",
FSkinProp.ICO_QUESTION); FSkinProp.ICO_QUESTION);
@@ -96,7 +97,7 @@ public class SealedCardPoolGenerator {
final IStorage<DeckGroup> sealedDecks = FModel.getDecks().getSealed(); final IStorage<DeckGroup> sealedDecks = FModel.getDecks().getSealed();
if (sealedDecks.contains(sDeckName)) { if (sealedDecks.contains(sDeckName)) {
if (!SOptionPane.showConfirmDialog( if (!SOptionPane.showConfirmDialog(gui,
"'" + sDeckName + "' already exists. Do you want to replace it?", "'" + sDeckName + "' already exists. Do you want to replace it?",
"Sealed Deck Game Exists")) { "Sealed Deck Game Exists")) {
return null; return null;
@@ -154,11 +155,11 @@ public class SealedCardPoolGenerator {
* @param poolType * @param poolType
* a {@link java.lang.String} object. * a {@link java.lang.String} object.
*/ */
private SealedCardPoolGenerator(final LimitedPoolType poolType) { private SealedCardPoolGenerator(final IGuiBase gui, final LimitedPoolType poolType) {
switch(poolType) { switch(poolType) {
case Full: case Full:
// Choose number of boosters // Choose number of boosters
if (!chooseNumberOfBoosters(new UnOpenedProduct(SealedProduct.Template.genericBooster))) { if (!chooseNumberOfBoosters(gui, new UnOpenedProduct(SealedProduct.Template.genericBooster))) {
return; return;
} }
landSetCode = CardEdition.Predicates.getRandomSetWithAllBasicLands(FModel.getMagicDb().getEditions()).getCode(); landSetCode = CardEdition.Predicates.getRandomSetWithAllBasicLands(FModel.getMagicDb().getEditions()).getCode();
@@ -172,7 +173,7 @@ public class SealedCardPoolGenerator {
blocks.add(b); blocks.add(b);
} }
final CardBlock block = SGuiChoose.oneOrNone("Choose Block", blocks); final CardBlock block = SGuiChoose.oneOrNone(gui, "Choose Block", blocks);
if (block == null) { return; } if (block == null) { return; }
final int nPacks = block.getCntBoostersSealed(); final int nPacks = block.getCntBoostersSealed();
@@ -192,7 +193,7 @@ public class SealedCardPoolGenerator {
throw new RuntimeException("Unsupported amount of packs (" + nPacks + ") in a Sealed Deck block!"); throw new RuntimeException("Unsupported amount of packs (" + nPacks + ") in a Sealed Deck block!");
} }
final String p = setCombos.size() > 1 ? SGuiChoose.oneOrNone("Choose packs to play with", setCombos) : setCombos.get(0); final String p = setCombos.size() > 1 ? SGuiChoose.oneOrNone(gui, "Choose packs to play with", setCombos) : setCombos.get(0);
if (p == null) { return; } if (p == null) { return; }
for (String pz : TextUtil.split(p, ',')) { for (String pz : TextUtil.split(p, ',')) {
@@ -200,12 +201,12 @@ public class SealedCardPoolGenerator {
String setCode = pps[pps.length - 1]; String setCode = pps[pps.length - 1];
int nBoosters = pps.length > 1 ? Integer.parseInt(pps[0]) : 1; int nBoosters = pps.length > 1 ? Integer.parseInt(pps[0]) : 1;
while (nBoosters-- > 0) { while (nBoosters-- > 0) {
this.product.add(block.getBooster(setCode)); this.product.add(block.getBooster(setCode, gui));
} }
} }
} }
else { else {
IUnOpenedProduct prod = block.getBooster(sets.get(0)); IUnOpenedProduct prod = block.getBooster(sets.get(0), gui);
for (int i = 0; i < nPacks; i++) { for (int i = 0; i < nPacks; i++) {
this.product.add(prod); this.product.add(prod);
} }
@@ -243,16 +244,16 @@ public class SealedCardPoolGenerator {
// present list to user // present list to user
if (customs.isEmpty()) { if (customs.isEmpty()) {
SOptionPane.showMessageDialog("No custom sealed files found."); SOptionPane.showMessageDialog(gui, "No custom sealed files found.");
return; return;
} }
final CustomLimited draft = SGuiChoose.oneOrNone("Choose Custom Sealed Pool", customs); final CustomLimited draft = SGuiChoose.oneOrNone(gui, "Choose Custom Sealed Pool", customs);
if (draft == null) { return; } if (draft == null) { return; }
UnOpenedProduct toAdd = new UnOpenedProduct(draft.getSealedProductTemplate(), draft.getCardPool()); UnOpenedProduct toAdd = new UnOpenedProduct(draft.getSealedProductTemplate(), draft.getCardPool());
toAdd.setLimitedPool(draft.isSingleton()); toAdd.setLimitedPool(draft.isSingleton());
if (!chooseNumberOfBoosters(toAdd)) { if (!chooseNumberOfBoosters(gui, toAdd)) {
return; return;
} }
@@ -261,8 +262,8 @@ public class SealedCardPoolGenerator {
} }
} }
private boolean chooseNumberOfBoosters(final IUnOpenedProduct product1) { private boolean chooseNumberOfBoosters(final IGuiBase gui, final IUnOpenedProduct product1) {
Integer boosterCount = SGuiChoose.getInteger("How many booster packs?", 3, 12); Integer boosterCount = SGuiChoose.getInteger(gui, "How many booster packs?", 3, 12);
if (boosterCount == null) { return false; } if (boosterCount == null) { return false; }
for (int i = 0; i < boosterCount; i++) { for (int i = 0; i < boosterCount; i++) {

View File

@@ -3,8 +3,10 @@ package forge.limited;
import com.google.common.base.Predicates; import com.google.common.base.Predicates;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import forge.deck.CardPool; import forge.deck.CardPool;
import forge.deck.Deck; import forge.deck.Deck;
import forge.interfaces.IGuiBase;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.util.MyRandom; import forge.util.MyRandom;
@@ -18,9 +20,9 @@ public class WinstonDraft extends BoosterDraft {
private Stack<PaperCard> deck; // main deck where all cards private Stack<PaperCard> deck; // main deck where all cards
private List<List<PaperCard>> piles; // 3 piles to draft from private List<List<PaperCard>> piles; // 3 piles to draft from
public static WinstonDraft createDraft(final LimitedPoolType draftType) { public static WinstonDraft createDraft(final IGuiBase gui, final LimitedPoolType draftType) {
WinstonDraft draft = new WinstonDraft(draftType); WinstonDraft draft = new WinstonDraft(draftType);
if (!draft.generateProduct()) { if (!draft.generateProduct(gui)) {
return null; return null;
} }
draft.initializeWinstonDraft(); draft.initializeWinstonDraft();

View File

@@ -1,31 +0,0 @@
package forge.match;
import forge.GuiBase;
import forge.game.Game;
import forge.game.player.Player;
import forge.match.input.Input;
import forge.match.input.InputPassPriority;
public class MatchUtil {
public static boolean undoLastAction() {
if (canUndoLastAction() && GuiBase.getInterface().getGame().stack.undo()) {
Input currentInput = GuiBase.getInterface().getInputQueue().getInput();
if (currentInput instanceof InputPassPriority) {
currentInput.showMessageInitial(); //ensure prompt updated if needed
}
return true;
}
return false;
}
public static boolean canUndoLastAction() {
Game game = GuiBase.getInterface().getGame();
if (game.stack.canUndo()) {
Player player = game.getPhaseHandler().getPriorityPlayer();
if (player != null && player.getLobbyPlayer() == GuiBase.getInterface().getGuiPlayer()) {
return true;
}
}
return false;
}
}

View File

@@ -17,29 +17,29 @@
*/ */
package forge.match.input; package forge.match.input;
import forge.GuiBase;
import forge.interfaces.IButton; import forge.interfaces.IButton;
import forge.interfaces.IGuiBase;
/** /**
* Manages match UI OK/Cancel button enabling and focus * Manages match UI OK/Cancel button enabling and focus
*/ */
public class ButtonUtil { public class ButtonUtil {
public static void update(boolean okEnabled, boolean cancelEnabled, boolean focusOk) { public static void update(final IGuiBase gui, boolean okEnabled, boolean cancelEnabled, boolean focusOk) {
update("OK", "Cancel", okEnabled, cancelEnabled, focusOk); update(gui, "OK", "Cancel", okEnabled, cancelEnabled, focusOk);
} }
public static void update(String okLabel, String cancelLabel, boolean okEnabled, boolean cancelEnabled, boolean focusOk) { public static void update(final IGuiBase gui, String okLabel, String cancelLabel, boolean okEnabled, boolean cancelEnabled, boolean focusOk) {
IButton btnOk = GuiBase.getInterface().getBtnOK(); IButton btnOk = gui.getBtnOK();
IButton btnCancel = GuiBase.getInterface().getBtnCancel(); IButton btnCancel = gui.getBtnCancel();
btnOk.setText(okLabel); btnOk.setText(okLabel);
btnCancel.setText(cancelLabel); btnCancel.setText(cancelLabel);
btnOk.setEnabled(okEnabled); btnOk.setEnabled(okEnabled);
btnCancel.setEnabled(cancelEnabled); btnCancel.setEnabled(cancelEnabled);
if (okEnabled && focusOk) { if (okEnabled && focusOk) {
GuiBase.getInterface().focusButton(btnOk); gui.focusButton(btnOk);
} }
else if (cancelEnabled) { else if (cancelEnabled) {
GuiBase.getInterface().focusButton(btnCancel); gui.focusButton(btnCancel);
} }
} }
} }

View File

@@ -17,9 +17,13 @@
*/ */
package forge.match.input; package forge.match.input;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import forge.GuiBase;
import forge.events.UiEventAttackerDeclared; import forge.events.UiEventAttackerDeclared;
import forge.game.GameEntity; import forge.game.GameEntity;
import forge.game.card.Card; import forge.game.card.Card;
@@ -31,13 +35,9 @@ import forge.game.combat.Combat;
import forge.game.combat.CombatUtil; import forge.game.combat.CombatUtil;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
/** /**
* <p> * <p>
* InputAttack class. * InputAttack class.
@@ -56,7 +56,8 @@ public class InputAttack extends InputSyncronizedBase {
private final Player playerAttacks; private final Player playerAttacks;
private AttackingBand activeBand = null; private AttackingBand activeBand = null;
public InputAttack(Player attacks0, Combat combat0) { public InputAttack(PlayerControllerHuman controller, Player attacks0, Combat combat0) {
super(controller);
playerAttacks = attacks0; playerAttacks = attacks0;
combat = combat0; combat = combat0;
defenders = combat.getDefenders(); defenders = combat.getDefenders();
@@ -77,7 +78,9 @@ public class InputAttack extends InputSyncronizedBase {
List<Pair<Card, GameEntity>> mandatoryAttackers = CombatUtil.getMandatoryAttackers(playerAttacks, combat, defenders); List<Pair<Card, GameEntity>> mandatoryAttackers = CombatUtil.getMandatoryAttackers(playerAttacks, combat, defenders);
for (Pair<Card, GameEntity> attacker : mandatoryAttackers) { for (Pair<Card, GameEntity> attacker : mandatoryAttackers) {
combat.addAttacker(attacker.getLeft(), attacker.getRight()); combat.addAttacker(attacker.getLeft(), attacker.getRight());
GuiBase.getInterface().fireEvent(new UiEventAttackerDeclared(attacker.getLeft(), attacker.getRight())); getGui().fireEvent(new UiEventAttackerDeclared(
getController().getCardView(attacker.getLeft()),
getController().getGameEntityView(attacker.getRight())));
} }
updateMessage(); updateMessage();
} }
@@ -94,10 +97,10 @@ public class InputAttack extends InputSyncronizedBase {
private void updatePrompt() { private void updatePrompt() {
if (canCallBackAttackers()) { if (canCallBackAttackers()) {
ButtonUtil.update("OK", "Call Back", true, true, true); ButtonUtil.update(getGui(), "OK", "Call Back", true, true, true);
} }
else { else {
ButtonUtil.update("OK", "Alpha Strike", true, true, true); ButtonUtil.update(getGui(), "OK", "Alpha Strike", true, true, true);
} }
} }
@@ -225,7 +228,9 @@ public class InputAttack extends InputSyncronizedBase {
combat.addAttacker(card, currentDefender, activeBand); combat.addAttacker(card, currentDefender, activeBand);
activateBand(activeBand); activateBand(activeBand);
GuiBase.getInterface().fireEvent(new UiEventAttackerDeclared(card, currentDefender)); getGui().fireEvent(new UiEventAttackerDeclared(
getController().getCardView(card),
getController().getGameEntityView(currentDefender)));
} }
private boolean canUndeclareAttacker(Card card) { private boolean canUndeclareAttacker(Card card) {
@@ -238,11 +243,12 @@ public class InputAttack extends InputSyncronizedBase {
if (canUndeclareAttacker(card)) { if (canUndeclareAttacker(card)) {
// TODO Is there no way to attacks each turn cards to attack Planeswalkers? // TODO Is there no way to attacks each turn cards to attack Planeswalkers?
combat.removeFromCombat(card); combat.removeFromCombat(card);
GuiBase.getInterface().setUsedToPay(card, false); getGui().setUsedToPay(getController().getCardView(card), false);
// When removing an attacker clear the attacking band // When removing an attacker clear the attacking band
activateBand(null); activateBand(null);
GuiBase.getInterface().fireEvent(new UiEventAttackerDeclared(card, null)); getGui().fireEvent(new UiEventAttackerDeclared(
getController().getCardView(card), null));
return true; return true;
} }
return false; return false;
@@ -252,10 +258,10 @@ public class InputAttack extends InputSyncronizedBase {
currentDefender = def; currentDefender = def;
for (final GameEntity ge : defenders) { for (final GameEntity ge : defenders) {
if (ge instanceof Card) { if (ge instanceof Card) {
GuiBase.getInterface().setUsedToPay((Card)ge, ge == def); getGui().setUsedToPay(getController().getCardView((Card) ge), ge == def);
} }
else if (ge instanceof Player) { else if (ge instanceof Player) {
GuiBase.getInterface().setHighlighted((Player) ge, ge == def); getGui().setHighlighted(getController().getPlayerView((Player) ge), ge == def);
} }
} }
@@ -265,14 +271,14 @@ public class InputAttack extends InputSyncronizedBase {
private final void activateBand(final AttackingBand band) { private final void activateBand(final AttackingBand band) {
if (activeBand != null) { if (activeBand != null) {
for (final Card card : activeBand.getAttackers()) { for (final Card card : activeBand.getAttackers()) {
GuiBase.getInterface().setUsedToPay(card, false); getGui().setUsedToPay(getController().getCardView(card), false);
} }
} }
activeBand = band; activeBand = band;
if (activeBand != null) { if (activeBand != null) {
for (final Card card : activeBand.getAttackers()) { for (final Card card : activeBand.getAttackers()) {
GuiBase.getInterface().setUsedToPay(card, true); getGui().setUsedToPay(getController().getCardView(card), true);
} }
} }
} }
@@ -296,6 +302,6 @@ public class InputAttack extends InputSyncronizedBase {
showMessage(message); showMessage(message);
updatePrompt(); updatePrompt();
GuiBase.getInterface().showCombat(combat); // redraw sword icons getGui().showCombat(getController().getCombat(combat)); // redraw sword icons
} }
} }

View File

@@ -21,12 +21,13 @@ import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.game.Game; import forge.game.Game;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.phase.PhaseHandler; import forge.game.phase.PhaseHandler;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.interfaces.IGuiBase;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
/** /**
@@ -40,13 +41,25 @@ import forge.util.ITriggerEvent;
public abstract class InputBase implements java.io.Serializable, Input { public abstract class InputBase implements java.io.Serializable, Input {
/** Constant <code>serialVersionUID=-6539552513871194081L</code>. */ /** Constant <code>serialVersionUID=-6539552513871194081L</code>. */
private static final long serialVersionUID = -6539552513871194081L; private static final long serialVersionUID = -6539552513871194081L;
private final PlayerControllerHuman controller;
public InputBase(final PlayerControllerHuman controller) {
this.controller = controller;
}
protected final PlayerControllerHuman getController() {
return this.controller;
}
protected IGuiBase getGui() {
return getController().getGui();
}
private boolean finished = false; private boolean finished = false;
protected final boolean isFinished() { return finished; } protected final boolean isFinished() { return finished; }
protected final void setFinished() { protected final void setFinished() {
finished = true; finished = true;
if (allowAwaitNextInput()) { if (allowAwaitNextInput()) {
awaitNextInput(); awaitNextInput(getGui());
} }
} }
@@ -57,18 +70,18 @@ public abstract class InputBase implements java.io.Serializable, Input {
private static final Timer awaitNextInputTimer = new Timer(); private static final Timer awaitNextInputTimer = new Timer();
private static TimerTask awaitNextInputTask; private static TimerTask awaitNextInputTask;
public static void awaitNextInput() { public static void awaitNextInput(final IGuiBase gui) {
//delay updating prompt to await next input briefly so buttons don't flicker disabled then enabled //delay updating prompt to await next input briefly so buttons don't flicker disabled then enabled
awaitNextInputTask = new TimerTask() { awaitNextInputTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
synchronized (awaitNextInputTimer) { synchronized (awaitNextInputTimer) {
if (awaitNextInputTask != null) { if (awaitNextInputTask != null) {
GuiBase.getInterface().showPromptMessage("Waiting for opponent..."); gui.showPromptMessage("Waiting for opponent...");
ButtonUtil.update(false, false, false); ButtonUtil.update(gui, false, false, false);
awaitNextInputTask = null; awaitNextInputTask = null;
} }
} }
@@ -137,11 +150,11 @@ public abstract class InputBase implements java.io.Serializable, Input {
// to remove need for CMatchUI dependence // to remove need for CMatchUI dependence
protected final void showMessage(final String message) { protected final void showMessage(final String message) {
GuiBase.getInterface().showPromptMessage(message); getGui().showPromptMessage(message);
} }
protected final void flashIncorrectAction() { protected final void flashIncorrectAction() {
GuiBase.getInterface().flashIncorrectAction(); getGui().flashIncorrectAction();
} }
protected String getTurnPhasePriorityMessage(final Game game) { protected String getTurnPhasePriorityMessage(final Game game) {

View File

@@ -18,7 +18,6 @@
package forge.match.input; package forge.match.input;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.events.UiEventBlockerAssigned; import forge.events.UiEventBlockerAssigned;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.card.CardLists; import forge.game.card.CardLists;
@@ -27,8 +26,10 @@ import forge.game.combat.Combat;
import forge.game.combat.CombatUtil; import forge.game.combat.CombatUtil;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import forge.util.gui.SGuiDialog; import forge.util.gui.SGuiDialog;
import forge.view.CardView;
/** /**
* <p> * <p>
@@ -47,7 +48,8 @@ public class InputBlock extends InputSyncronizedBase {
private final Combat combat; private final Combat combat;
private final Player defender; private final Player defender;
public InputBlock(Player defender0, Combat combat0) { public InputBlock(final PlayerControllerHuman controller, final Player defender0, final Combat combat0) {
super(controller);
defender = defender0; defender = defender0;
combat = combat0; combat = combat0;
@@ -55,7 +57,7 @@ public class InputBlock extends InputSyncronizedBase {
for (final Card attacker : combat.getAttackers()) { for (final Card attacker : combat.getAttackers()) {
for (final Card c : CardLists.filter(defender.getCardsIn(ZoneType.Battlefield), Presets.CREATURES)) { for (final Card c : CardLists.filter(defender.getCardsIn(ZoneType.Battlefield), Presets.CREATURES)) {
if (CombatUtil.canBlock(attacker, c, combat)) { if (CombatUtil.canBlock(attacker, c, combat)) {
FThreads.invokeInEdtNowOrLater(new Runnable() { //must set current attacker on EDT FThreads.invokeInEdtNowOrLater(getGui(), new Runnable() { //must set current attacker on EDT
@Override @Override
public void run() { public void run() {
setCurrentAttacker(attacker); setCurrentAttacker(attacker);
@@ -71,7 +73,7 @@ public class InputBlock extends InputSyncronizedBase {
@Override @Override
protected final void showMessage() { protected final void showMessage() {
// could add "Reset Blockers" button // could add "Reset Blockers" button
ButtonUtil.update(true, false, true); ButtonUtil.update(getGui(), true, false, true);
if (currentAttacker == null) { if (currentAttacker == null) {
showMessage("Select another attacker to declare blockers for."); showMessage("Select another attacker to declare blockers for.");
@@ -82,7 +84,7 @@ public class InputBlock extends InputSyncronizedBase {
showMessage(message); showMessage(message);
} }
GuiBase.getInterface().showCombat(combat); getGui().showCombat(getController().getCombat(combat));
} }
/** {@inheritDoc} */ /** {@inheritDoc} */
@@ -95,7 +97,7 @@ public class InputBlock extends InputSyncronizedBase {
stop(); stop();
} }
else { else {
SGuiDialog.message(blockErrors); SGuiDialog.message(getGui(), blockErrors);
} }
} }
@@ -105,7 +107,8 @@ public class InputBlock extends InputSyncronizedBase {
boolean isCorrectAction = false; boolean isCorrectAction = false;
if (triggerEvent != null && triggerEvent.getButton() == 3 && card.getController() == defender) { if (triggerEvent != null && triggerEvent.getButton() == 3 && card.getController() == defender) {
combat.removeFromCombat(card); combat.removeFromCombat(card);
GuiBase.getInterface().fireEvent(new UiEventBlockerAssigned(card, (Card)null)); getGui().fireEvent(new UiEventBlockerAssigned(
getController().getCardView(card), (CardView) null));
isCorrectAction = true; isCorrectAction = true;
} }
else { else {
@@ -120,14 +123,17 @@ public class InputBlock extends InputSyncronizedBase {
if (combat.isBlocking(card, currentAttacker)) { if (combat.isBlocking(card, currentAttacker)) {
//if creature already blocking current attacker, remove blocker from combat //if creature already blocking current attacker, remove blocker from combat
combat.removeBlockAssignment(currentAttacker, card); combat.removeBlockAssignment(currentAttacker, card);
GuiBase.getInterface().fireEvent(new UiEventBlockerAssigned(card, (Card)null)); getGui().fireEvent(new UiEventBlockerAssigned(
getController().getCardView(card), (CardView) null));
isCorrectAction = true; isCorrectAction = true;
} }
else { else {
isCorrectAction = CombatUtil.canBlock(currentAttacker, card, combat); isCorrectAction = CombatUtil.canBlock(currentAttacker, card, combat);
if (isCorrectAction) { if (isCorrectAction) {
combat.addBlocker(currentAttacker, card); combat.addBlocker(currentAttacker, card);
GuiBase.getInterface().fireEvent(new UiEventBlockerAssigned(card, currentAttacker)); getGui().fireEvent(new UiEventBlockerAssigned(
getController().getCardView(card),
getController().getCardView(currentAttacker)));
} }
} }
} }
@@ -141,10 +147,10 @@ public class InputBlock extends InputSyncronizedBase {
return isCorrectAction; return isCorrectAction;
} }
private void setCurrentAttacker(Card card) { private void setCurrentAttacker(final Card card) {
currentAttacker = card; currentAttacker = card;
for (Card c : combat.getAttackers()) { for (final Card c : combat.getAttackers()) {
GuiBase.getInterface().setUsedToPay(c, card == c); getGui().setUsedToPay(getController().getCardView(c), card == c);
} }
} }
} }

View File

@@ -17,6 +17,8 @@
*/ */
package forge.match.input; package forge.match.input;
import forge.player.PlayerControllerHuman;
/** /**
* <p> * <p>
* InputConfirm class. * InputConfirm class.
@@ -34,15 +36,16 @@ public class InputConfirm extends InputSyncronizedBase {
private final boolean defaultYes; private final boolean defaultYes;
private boolean result; private boolean result;
public InputConfirm(String message0) { public InputConfirm(final PlayerControllerHuman controller, String message0) {
this(message0, "Yes", "No", true); this(controller, message0, "Yes", "No", true);
} }
public InputConfirm(String message0, String yesButtonText0, String noButtonText0) { public InputConfirm(final PlayerControllerHuman controller, String message0, String yesButtonText0, String noButtonText0) {
this(message0, yesButtonText0, noButtonText0, true); this(controller, message0, yesButtonText0, noButtonText0, true);
} }
public InputConfirm(String message0, String yesButtonText0, String noButtonText0, boolean defaultYes0) { public InputConfirm(final PlayerControllerHuman controller, String message0, String yesButtonText0, String noButtonText0, boolean defaultYes0) {
super(controller);
message = message0; message = message0;
yesButtonText = yesButtonText0; yesButtonText = yesButtonText0;
noButtonText = noButtonText0; noButtonText = noButtonText0;
@@ -53,7 +56,7 @@ public class InputConfirm extends InputSyncronizedBase {
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override @Override
protected final void showMessage() { protected final void showMessage() {
ButtonUtil.update(yesButtonText, noButtonText, true, true, defaultYes); ButtonUtil.update(getGui(), yesButtonText, noButtonText, true, true, defaultYes);
showMessage(message); showMessage(message);
} }

View File

@@ -17,18 +17,19 @@
*/ */
package forge.match.input; package forge.match.input;
import forge.GuiBase; import java.util.ArrayList;
import java.util.List;
import forge.game.Game; import forge.game.Game;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import forge.util.Lang; import forge.util.Lang;
import forge.util.ThreadUtil; import forge.util.ThreadUtil;
import forge.util.gui.SGuiDialog; import forge.util.gui.SGuiDialog;
import forge.view.CardView;
import java.util.ArrayList;
import java.util.List;
/** /**
* <p> * <p>
@@ -49,7 +50,8 @@ public class InputConfirmMulligan extends InputSyncronizedBase {
private final Player player; private final Player player;
private final Player startingPlayer; private final Player startingPlayer;
public InputConfirmMulligan(Player humanPlayer, Player startsGame, boolean commander) { public InputConfirmMulligan(final PlayerControllerHuman controller, final Player humanPlayer, final Player startsGame, final boolean commander) {
super(controller);
player = humanPlayer; player = humanPlayer;
isCommander = commander; isCommander = commander;
startingPlayer = startsGame; startingPlayer = startsGame;
@@ -70,11 +72,11 @@ public class InputConfirmMulligan extends InputSyncronizedBase {
} }
if (isCommander) { if (isCommander) {
ButtonUtil.update("Keep", "Exile", true, false, true); ButtonUtil.update(getGui(), "Keep", "Exile", true, false, true);
sb.append("Will you keep your hand or choose some cards to exile those and draw one less card?"); sb.append("Will you keep your hand or choose some cards to exile those and draw one less card?");
} }
else { else {
ButtonUtil.update("Keep", "Mulligan", true, true, true); ButtonUtil.update(getGui(), "Keep", "Mulligan", true, true, true);
sb.append("Do you want to keep your hand?"); sb.append("Do you want to keep your hand?");
} }
@@ -98,8 +100,8 @@ public class InputConfirmMulligan extends InputSyncronizedBase {
private void done() { private void done() {
if (isCommander) { if (isCommander) {
// Clear the "selected" icon after clicking the done button // Clear the "selected" icon after clicking the done button
for (Card c : this.selected) { for (final Card c : this.selected) {
GuiBase.getInterface().setUsedToPay(c, false); getGui().setUsedToPay(getController().getCardView(c), false);
} }
} }
stop(); stop();
@@ -117,7 +119,8 @@ public class InputConfirmMulligan extends InputSyncronizedBase {
return false; return false;
} }
if (isSerumPowder && SGuiDialog.confirm(c0, "Use " + c0.getName() + "'s ability?")) { final CardView cView = getController().getCardView(c0);
if (isSerumPowder && SGuiDialog.confirm(getGui(), cView, "Use " + cView + "'s ability?")) {
cardSelectLocked = true; cardSelectLocked = true;
ThreadUtil.invokeInGameThread(new Runnable() { ThreadUtil.invokeInGameThread(new Runnable() {
public void run() { public void run() {
@@ -134,14 +137,14 @@ public class InputConfirmMulligan extends InputSyncronizedBase {
if (isCommander) { // allow to choose cards for partial paris if (isCommander) { // allow to choose cards for partial paris
if (selected.contains(c0)) { if (selected.contains(c0)) {
GuiBase.getInterface().setUsedToPay(c0, false); getGui().setUsedToPay(getController().getCardView(c0), false);
selected.remove(c0); selected.remove(c0);
} }
else { else {
GuiBase.getInterface().setUsedToPay(c0, true); getGui().setUsedToPay(getController().getCardView(c0), true);
selected.add(c0); selected.add(c0);
} }
ButtonUtil.update("Keep", "Exile", true, !selected.isEmpty(), true); ButtonUtil.update(getGui(), "Keep", "Exile", true, !selected.isEmpty(), true);
} }
return true; return true;
} }

View File

@@ -1,21 +1,28 @@
package forge.match.input; package forge.match.input;
import java.util.concurrent.atomic.AtomicInteger;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.game.Game; import forge.game.Game;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.interfaces.IGuiBase;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import forge.util.ThreadUtil; import forge.util.ThreadUtil;
import java.util.concurrent.atomic.AtomicInteger;
public class InputLockUI implements Input { public class InputLockUI implements Input {
private final AtomicInteger iCall = new AtomicInteger(); private final AtomicInteger iCall = new AtomicInteger();
public InputLockUI(InputQueue inputQueue) { private final IGuiBase gui;
private final Game game;
public InputLockUI(final IGuiBase gui, final Game game, final InputQueue inputQueue) {
this.gui = gui;
this.game = game;
}
private IGuiBase getGui() {
return gui;
} }
public void showMessageInitial() { public void showMessageInitial() {
@@ -39,24 +46,24 @@ public class InputLockUI implements Input {
public void run() { public void run() {
if ( ixCall != iCall.get() || !isActive()) // cancel the message if it's not from latest call or input is gone already if ( ixCall != iCall.get() || !isActive()) // cancel the message if it's not from latest call or input is gone already
return; return;
FThreads.invokeInEdtLater(showMessageFromEdt); FThreads.invokeInEdtLater(getGui(), showMessageFromEdt);
} }
}; };
private final Runnable showMessageFromEdt = new Runnable() { private final Runnable showMessageFromEdt = new Runnable() {
@Override @Override
public void run() { public void run() {
ButtonUtil.update("", "", false, false, false); ButtonUtil.update(getGui(), "", "", false, false, false);
showMessage("Waiting for actions..."); showMessage("Waiting for actions...");
} }
}; };
protected final boolean isActive() { protected final boolean isActive() {
return GuiBase.getInterface().getInputQueue().getInput() == this; return getGui().getInputQueue().getInput() == this;
} }
protected void showMessage(String message) { protected void showMessage(String message) {
GuiBase.getInterface().showPromptMessage(message); getGui().showPromptMessage(message);
} }
@Override @Override
@@ -75,7 +82,6 @@ public class InputLockUI implements Input {
@Override @Override
public void selectButtonCancel() { public void selectButtonCancel() {
//cancel auto pass for all players //cancel auto pass for all players
Game game = GuiBase.getInterface().getGame();
for (Player player : game.getPlayers()) { for (Player player : game.getPlayers()) {
player.getController().autoPassCancel(); player.getController().autoPassCancel();
} }

View File

@@ -17,20 +17,19 @@
*/ */
package forge.match.input; package forge.match.input;
import forge.GuiBase; import java.util.List;
import forge.game.Game; import forge.game.Game;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.match.MatchUtil;
import forge.model.FModel; import forge.model.FModel;
import forge.player.PlayerControllerHuman;
import forge.properties.ForgePreferences.FPref; import forge.properties.ForgePreferences.FPref;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import forge.util.ThreadUtil; import forge.util.ThreadUtil;
import forge.util.gui.SOptionPane; import forge.util.gui.SOptionPane;
import java.util.List;
/** /**
* <p> * <p>
* Input_PassPriority class. * Input_PassPriority class.
@@ -46,7 +45,8 @@ public class InputPassPriority extends InputSyncronizedBase {
private SpellAbility chosenSa; private SpellAbility chosenSa;
public InputPassPriority(Player human) { public InputPassPriority(final PlayerControllerHuman controller, final Player human) {
super(controller);
player = human; player = human;
} }
@@ -55,11 +55,11 @@ public class InputPassPriority extends InputSyncronizedBase {
public final void showMessage() { public final void showMessage() {
showMessage(getTurnPhasePriorityMessage(player.getGame())); showMessage(getTurnPhasePriorityMessage(player.getGame()));
chosenSa = null; chosenSa = null;
if (MatchUtil.canUndoLastAction()) { //allow undoing with cancel button if can undo last action if (getController().canUndoLastAction()) { //allow undoing with cancel button if can undo last action
ButtonUtil.update("OK", "Undo", true, true, true); ButtonUtil.update(getGui(), "OK", "Undo", true, true, true);
} }
else { //otherwise allow ending turn with cancel button else { //otherwise allow ending turn with cancel button
ButtonUtil.update("OK", "End Turn", true, true, true); ButtonUtil.update(getGui(), "OK", "End Turn", true, true, true);
} }
} }
@@ -77,7 +77,7 @@ public class InputPassPriority extends InputSyncronizedBase {
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override @Override
protected final void onCancel() { protected final void onCancel() {
if (!MatchUtil.undoLastAction()) { //undo if possible if (!getController().tryUndoLastAction()) { //undo if possible
//otherwise end turn //otherwise end turn
passPriority(new Runnable() { passPriority(new Runnable() {
@Override @Override
@@ -97,10 +97,10 @@ public class InputPassPriority extends InputSyncronizedBase {
private void passPriority(final Runnable runnable) { private void passPriority(final Runnable runnable) {
if (FModel.getPreferences().getPrefBoolean(FPref.UI_MANA_LOST_PROMPT)) { if (FModel.getPreferences().getPrefBoolean(FPref.UI_MANA_LOST_PROMPT)) {
//if gui player has mana floating that will be lost if phase ended right now, prompt before passing priority //if gui player has mana floating that will be lost if phase ended right now, prompt before passing priority
Game game = GuiBase.getInterface().getGame(); final Game game = player.getGame();
if (game.getStack().isEmpty()) { //phase can't end right now if stack isn't empty if (game.getStack().isEmpty()) { //phase can't end right now if stack isn't empty
Player player = game.getPhaseHandler().getPriorityPlayer(); Player player = game.getPhaseHandler().getPriorityPlayer();
if (player != null && player.getManaPool().willManaBeLostAtEndOfPhase() && player.getLobbyPlayer() == GuiBase.getInterface().getGuiPlayer()) { if (player != null && player.getManaPool().willManaBeLostAtEndOfPhase() && player.getLobbyPlayer() == getGui().getGuiPlayer()) {
ThreadUtil.invokeInGameThread(new Runnable() { //must invoke in game thread so dialog can be shown on mobile game ThreadUtil.invokeInGameThread(new Runnable() { //must invoke in game thread so dialog can be shown on mobile game
@Override @Override
public void run() { public void run() {
@@ -108,7 +108,7 @@ public class InputPassPriority extends InputSyncronizedBase {
if (FModel.getPreferences().getPrefBoolean(FPref.UI_MANABURN)) { if (FModel.getPreferences().getPrefBoolean(FPref.UI_MANABURN)) {
message += " You will take mana burn damage equal to the amount of floating mana lost this way."; message += " You will take mana burn damage equal to the amount of floating mana lost this way.";
} }
if (SOptionPane.showOptionDialog(message, "Mana Floating", SOptionPane.WARNING_ICON, new String[]{"OK", "Cancel"}) == 0) { if (SOptionPane.showOptionDialog(getGui(), message, "Mana Floating", SOptionPane.WARNING_ICON, new String[]{"OK", "Cancel"}) == 0) {
runnable.run(); runnable.run();
} }
} }

View File

@@ -1,7 +1,12 @@
package forge.match.input; package forge.match.input;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase;
import forge.ai.ComputerUtilMana; import forge.ai.ComputerUtilMana;
import forge.ai.PlayerControllerAi; import forge.ai.PlayerControllerAi;
import forge.card.ColorSet; import forge.card.ColorSet;
@@ -17,16 +22,11 @@ import forge.game.replacement.ReplacementEffect;
import forge.game.spellability.AbilityManaPart; import forge.game.spellability.AbilityManaPart;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.player.HumanPlay; import forge.player.HumanPlay;
import forge.player.PlayerControllerHuman;
import forge.util.Evaluator; import forge.util.Evaluator;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import forge.util.gui.SGuiChoose; import forge.util.gui.SGuiChoose;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public abstract class InputPayMana extends InputSyncronizedBase { public abstract class InputPayMana extends InputSyncronizedBase {
private static final long serialVersionUID = -9133423708688480255L; private static final long serialVersionUID = -9133423708688480255L;
@@ -45,20 +45,21 @@ public abstract class InputPayMana extends InputSyncronizedBase {
private boolean locked = false; private boolean locked = false;
protected InputPayMana(SpellAbility saPaidFor0, Player player0) { protected InputPayMana(final PlayerControllerHuman controller, final SpellAbility saPaidFor0, final Player player0) {
super(controller);
player = player0; player = player0;
game = player.getGame(); game = player.getGame();
saPaidFor = saPaidFor0; saPaidFor = saPaidFor0;
//if player is floating mana, show mana pool to make it easier to use that mana //if player is floating mana, show mana pool to make it easier to use that mana
wasFloatingMana = !player.getManaPool().isEmpty(); wasFloatingMana = !player.getManaPool().isEmpty();
zoneToRestore = wasFloatingMana ? GuiBase.getInterface().showManaPool(player) : null; zoneToRestore = wasFloatingMana ? getGui().showManaPool(getController().getPlayerView(player)) : null;
} }
@Override @Override
protected void onStop() { protected void onStop() {
if (wasFloatingMana) { //hide mana pool if it was shown due to floating mana if (wasFloatingMana) { //hide mana pool if it was shown due to floating mana
GuiBase.getInterface().hideManaPool(player, zoneToRestore); getGui().hideManaPool(getController().getPlayerView(player), zoneToRestore);
} }
} }
@@ -244,7 +245,7 @@ public abstract class InputPayMana extends InputSyncronizedBase {
final SpellAbility chosen; final SpellAbility chosen;
if (chosenAbility == null) { if (chosenAbility == null) {
chosen = abilities.size() > 1 && choice ? SGuiChoose.one("Choose mana ability", abilities) : abilities.get(0); chosen = abilities.size() > 1 && choice ? SGuiChoose.one(getGui(), "Choose mana ability", abilities) : abilities.get(0);
} }
else { else {
chosen = chosenAbility; chosen = chosenAbility;
@@ -256,7 +257,7 @@ public abstract class InputPayMana extends InputSyncronizedBase {
Runnable proc = new Runnable() { Runnable proc = new Runnable() {
@Override @Override
public void run() { public void run() {
HumanPlay.playSpellAbility(chosen.getActivatingPlayer(), chosen); HumanPlay.playSpellAbility(getController(), chosen.getActivatingPlayer(), chosen);
player.getManaPool().payManaFromAbility(saPaidFor, InputPayMana.this.manaCost, chosen); player.getManaPool().payManaFromAbility(saPaidFor, InputPayMana.this.manaCost, chosen);
onManaAbilityPaid(); onManaAbilityPaid();
@@ -370,10 +371,10 @@ public abstract class InputPayMana extends InputSyncronizedBase {
protected void updateButtons() { protected void updateButtons() {
if (supportAutoPay()) { if (supportAutoPay()) {
ButtonUtil.update("Auto", "Cancel", false, true, false); ButtonUtil.update(getGui(), "Auto", "Cancel", false, true, false);
} }
else { else {
ButtonUtil.update("", "Cancel", false, true, false); ButtonUtil.update(getGui(), "", "Cancel", false, true, false);
} }
} }
@@ -392,7 +393,7 @@ public abstract class InputPayMana extends InputSyncronizedBase {
canPayManaCost = proc.getResult(); canPayManaCost = proc.getResult();
} }
if (canPayManaCost) { //enabled Auto button if mana cost can be paid if (canPayManaCost) { //enabled Auto button if mana cost can be paid
ButtonUtil.update("Auto", "Cancel", true, true, true); ButtonUtil.update(getGui(), "Auto", "Cancel", true, true, true);
} }
} }
showMessage(getMessage()); showMessage(getMessage());
@@ -412,7 +413,7 @@ public abstract class InputPayMana extends InputSyncronizedBase {
stop(); stop();
} }
else { else {
FThreads.invokeInEdtNowOrLater(new Runnable() { FThreads.invokeInEdtNowOrLater(getGui(), new Runnable() {
@Override @Override
public void run() { public void run() {
updateMessage(); updateMessage();

View File

@@ -4,11 +4,12 @@ import forge.game.card.Card;
import forge.game.mana.ManaCostBeingPaid; import forge.game.mana.ManaCostBeingPaid;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
public class InputPayManaOfCostPayment extends InputPayMana { public class InputPayManaOfCostPayment extends InputPayMana {
public InputPayManaOfCostPayment(ManaCostBeingPaid cost, SpellAbility spellAbility, Player payer) { public InputPayManaOfCostPayment(final PlayerControllerHuman controller, ManaCostBeingPaid cost, SpellAbility spellAbility, Player payer) {
super(spellAbility, payer); super(controller, spellAbility, payer);
manaCost = cost; manaCost = cost;
} }

View File

@@ -23,6 +23,7 @@ import forge.game.card.Card;
import forge.game.mana.ManaCostBeingPaid; import forge.game.mana.ManaCostBeingPaid;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
//pays the cost of a card played from the player's hand //pays the cost of a card played from the player's hand
@@ -36,8 +37,8 @@ public class InputPayManaSimple extends InputPayMana {
private final Card originalCard; private final Card originalCard;
private final ManaCost originalManaCost; private final ManaCost originalManaCost;
public InputPayManaSimple(final Game game, final SpellAbility sa, final ManaCostBeingPaid manaCostToPay) { public InputPayManaSimple(final PlayerControllerHuman controller, final Game game, final SpellAbility sa, final ManaCostBeingPaid manaCostToPay) {
super(sa, sa.getActivatingPlayer()); super(controller, sa, sa.getActivatingPlayer());
this.originalManaCost = manaCostToPay.toManaCost(); this.originalManaCost = manaCostToPay.toManaCost();
this.originalCard = sa.getHostCard(); this.originalCard = sa.getHostCard();

View File

@@ -1,5 +1,10 @@
package forge.match.input; package forge.match.input;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import forge.card.ColorSet; import forge.card.ColorSet;
import forge.card.mana.ManaCost; import forge.card.mana.ManaCost;
import forge.card.mana.ManaCostParser; import forge.card.mana.ManaCostParser;
@@ -7,13 +12,9 @@ import forge.game.card.Card;
import forge.game.mana.Mana; import forge.game.mana.Mana;
import forge.game.mana.ManaCostBeingPaid; import forge.game.mana.ManaCostBeingPaid;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class InputPayManaX extends InputPayMana { public class InputPayManaX extends InputPayMana {
private static final long serialVersionUID = -6900234444347364050L; private static final long serialVersionUID = -6900234444347364050L;
private int xPaid = 0; private int xPaid = 0;
@@ -23,8 +24,8 @@ public class InputPayManaX extends InputPayMana {
private final boolean xCanBe0; private final boolean xCanBe0;
private boolean canceled = false; private boolean canceled = false;
public InputPayManaX(final SpellAbility sa0, final int amountX, final boolean xCanBe0) { public InputPayManaX(final PlayerControllerHuman controller, final SpellAbility sa0, final int amountX, final boolean xCanBe0) {
super(sa0, sa0.getActivatingPlayer()); super(controller, sa0, sa0.getActivatingPlayer());
xPaid = 0; xPaid = 0;
if (saPaidFor.hasParam("XColor")) { if (saPaidFor.hasParam("XColor")) {
@@ -82,7 +83,7 @@ public class InputPayManaX extends InputPayMana {
// Enable just cancel is full X value hasn't been paid for multiple X values // Enable just cancel is full X value hasn't been paid for multiple X values
// or X is 0, and x can't be 0 // or X is 0, and x can't be 0
ButtonUtil.update(isPaid(), true, true); ButtonUtil.update(getGui(), isPaid(), true, true);
return msg.toString(); return msg.toString();
} }

View File

@@ -1,22 +1,30 @@
package forge.match.input; package forge.match.input;
import forge.GuiBase;
import forge.control.FControlGamePlayback; import forge.control.FControlGamePlayback;
import forge.game.Game; import forge.game.Game;
import forge.game.phase.PhaseHandler; import forge.game.phase.PhaseHandler;
import forge.interfaces.IGuiBase;
public class InputPlaybackControl extends InputSyncronizedBase implements InputSynchronized { public class InputPlaybackControl extends InputSyncronizedBase implements InputSynchronized {
private static final long serialVersionUID = 7979208993306642072L; private static final long serialVersionUID = 7979208993306642072L;
FControlGamePlayback control; final FControlGamePlayback control;
private boolean isPaused = false; private boolean isPaused = false;
private boolean isFast = false; private boolean isFast = false;
public InputPlaybackControl(FControlGamePlayback fControlGamePlayback) { private final IGuiBase gui;
private final Game game;
public InputPlaybackControl(final IGuiBase gui, final Game game, final FControlGamePlayback fControlGamePlayback) {
super(null);
this.gui = gui;
this.game = game;
control = fControlGamePlayback; control = fControlGamePlayback;
} }
@Override
protected IGuiBase getGui() {
return gui;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see forge.gui.input.InputBase#showMessage() * @see forge.gui.input.InputBase#showMessage()
@@ -29,7 +37,6 @@ public class InputPlaybackControl extends InputSyncronizedBase implements InputS
//update message based on current turn and paused state //update message based on current turn and paused state
private int currentTurn; private int currentTurn;
public void updateTurnMessage() { public void updateTurnMessage() {
Game game = GuiBase.getInterface().getGame();
if (isPaused) { if (isPaused) {
showMessage(getTurnPhasePriorityMessage(game)); showMessage(getTurnPhasePriorityMessage(game));
currentTurn = 0; currentTurn = 0;
@@ -46,10 +53,10 @@ public class InputPlaybackControl extends InputSyncronizedBase implements InputS
private void setPause(boolean pause) { private void setPause(boolean pause) {
isPaused = pause; isPaused = pause;
if (isPaused) { if (isPaused) {
ButtonUtil.update("Resume", "Step", true, true, true); ButtonUtil.update(getGui(), "Resume", "Step", true, true, true);
} }
else { else {
ButtonUtil.update("Pause", isFast ? "1x Speed" : "10x Faster", true, true, true); ButtonUtil.update(getGui(), "Pause", isFast ? "1x Speed" : "10x Faster", true, true, true);
} }
} }

View File

@@ -1,22 +1,26 @@
package forge.match.input; package forge.match.input;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import forge.game.GameEntity; import forge.game.GameEntity;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.card.CounterType; import forge.game.card.CounterType;
import forge.game.player.Player; import forge.game.player.Player;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import forge.util.gui.SGuiChoose; import forge.util.gui.SGuiChoose;
import java.util.*;
import java.util.Map.Entry;
public final class InputProliferate extends InputSelectManyBase<GameEntity> { public final class InputProliferate extends InputSelectManyBase<GameEntity> {
private static final long serialVersionUID = -1779224307654698954L; private static final long serialVersionUID = -1779224307654698954L;
private Map<GameEntity, CounterType> chosenCounters = new HashMap<GameEntity, CounterType>(); private Map<GameEntity, CounterType> chosenCounters = new HashMap<GameEntity, CounterType>();
public InputProliferate() { public InputProliferate(final PlayerControllerHuman controller) {
super(1, Integer.MAX_VALUE); super(controller, 1, Integer.MAX_VALUE);
allowUnselect = true; allowUnselect = true;
} }
@@ -59,7 +63,7 @@ public final class InputProliferate extends InputSelectManyBase<GameEntity> {
} }
} }
CounterType toAdd = choices.size() == 1 ? choices.get(0) : SGuiChoose.one("Select counter type", choices); CounterType toAdd = choices.size() == 1 ? choices.get(0) : SGuiChoose.one(getGui(), "Select counter type", choices);
chosenCounters.put(card, toAdd); chosenCounters.put(card, toAdd);
} }

View File

@@ -22,13 +22,14 @@ import java.util.Observer;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase; import forge.interfaces.IGuiBase;
import forge.game.spellability.SpellAbility; import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import forge.util.gui.SOptionPane; import forge.util.gui.SOptionPane;
import forge.view.CardView; import forge.view.CardView;
import forge.view.IGameView; import forge.view.IGameView;
import forge.view.PlayerView; import forge.view.PlayerView;
import forge.view.SpellAbilityView;
/** /**
* <p> * <p>
@@ -46,22 +47,31 @@ public class InputProxy implements Observer {
// private static final boolean DEBUG_INPUT = true; // false; // private static final boolean DEBUG_INPUT = true; // false;
private final PlayerControllerHuman controller;
public InputProxy(final PlayerControllerHuman controller) {
this.controller = controller;
}
private IGuiBase getGui() {
return controller.getGui();
}
public void setGame(IGameView game0) { public void setGame(IGameView game0) {
game = game0; game = game0;
GuiBase.getInterface().getInputQueue().addObserver(this); getGui().getInputQueue().addObserver(this);
} }
public boolean passPriority() { public boolean passPriority() {
Input inp = getInput(); final Input inp = getInput();
if (inp != null && inp instanceof InputPassPriority) { if (inp instanceof InputPassPriority) {
inp.selectButtonOK(); inp.selectButtonOK();
return true; return true;
} }
FThreads.invokeInEdtNowOrLater(new Runnable() { FThreads.invokeInEdtNowOrLater(getGui(), new Runnable() {
@Override @Override
public void run() { public void run() {
SOptionPane.showMessageDialog("Cannot pass priority at this time."); SOptionPane.showMessageDialog(getGui(), "Cannot pass priority at this time.");
} }
}); });
return false; return false;
@@ -69,7 +79,7 @@ public class InputProxy implements Observer {
@Override @Override
public final void update(final Observable observable, final Object obj) { public final void update(final Observable observable, final Object obj) {
final Input nextInput = GuiBase.getInterface().getInputQueue().getActualInput(game); final Input nextInput = getGui().getInputQueue().getActualInput(game);
/* if(DEBUG_INPUT) /* if(DEBUG_INPUT)
System.out.printf("%s ... \t%s on %s, \tstack = %s%n", System.out.printf("%s ... \t%s on %s, \tstack = %s%n",
@@ -80,13 +90,13 @@ public class InputProxy implements Observer {
Runnable showMessage = new Runnable() { Runnable showMessage = new Runnable() {
@Override public void run() { @Override public void run() {
Input current = getInput(); Input current = getInput();
GuiBase.getInterface().getInputQueue().syncPoint(); getGui().getInputQueue().syncPoint();
//System.out.printf("\t%s > showMessage @ %s/%s during %s%n", FThreads.debugGetCurrThreadId(), nextInput.getClass().getSimpleName(), current.getClass().getSimpleName(), game.getPhaseHandler().debugPrintState()); //System.out.printf("\t%s > showMessage @ %s/%s during %s%n", FThreads.debugGetCurrThreadId(), nextInput.getClass().getSimpleName(), current.getClass().getSimpleName(), game.getPhaseHandler().debugPrintState());
current.showMessageInitial(); current.showMessageInitial();
} }
}; };
FThreads.invokeInEdtLater(showMessage); FThreads.invokeInEdtLater(getGui(), showMessage);
} }
/** /**
* <p> * <p>
@@ -123,7 +133,7 @@ public class InputProxy implements Observer {
public final void selectPlayer(final PlayerView player, final ITriggerEvent triggerEvent) { public final void selectPlayer(final PlayerView player, final ITriggerEvent triggerEvent) {
final Input inp = getInput(); final Input inp = getInput();
if (inp != null) { if (inp != null) {
inp.selectPlayer(player, triggerEvent); inp.selectPlayer(controller.getPlayer(player), triggerEvent);
} }
} }
@@ -139,15 +149,15 @@ public class InputProxy implements Observer {
public final boolean selectCard(final CardView cardView, final ITriggerEvent triggerEvent) { public final boolean selectCard(final CardView cardView, final ITriggerEvent triggerEvent) {
final Input inp = getInput(); final Input inp = getInput();
if (inp != null) { if (inp != null) {
return inp.selectCard(cardView, triggerEvent); return inp.selectCard(controller.getCard(cardView), triggerEvent);
} }
return false; return false;
} }
public final void selectAbility(final SpellAbility ab) { public final void selectAbility(final SpellAbilityView ab) {
final Input inp = getInput(); final Input inp = getInput();
if (inp != null) { if (inp != null) {
inp.selectAbility(ab); inp.selectAbility(controller.getSpellAbility(ab));
} }
} }

View File

@@ -17,12 +17,14 @@
*/ */
package forge.match.input; package forge.match.input;
import forge.view.IGameView;
import java.util.Observable; import java.util.Observable;
import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingDeque;
import forge.game.Game;
import forge.interfaces.IGuiBase;
import forge.view.IGameView;
/** /**
* <p> * <p>
* InputControl class. * InputControl class.
@@ -35,8 +37,8 @@ public class InputQueue extends Observable {
private final BlockingDeque<InputSynchronized> inputStack = new LinkedBlockingDeque<InputSynchronized>(); private final BlockingDeque<InputSynchronized> inputStack = new LinkedBlockingDeque<InputSynchronized>();
private final InputLockUI inputLock; private final InputLockUI inputLock;
public InputQueue() { public InputQueue(final IGuiBase gui, final Game game) {
inputLock = new InputLockUI(this); inputLock = new InputLockUI(gui, game, this);
} }
public final void updateObservers() { public final void updateObservers() {

View File

@@ -1,21 +1,22 @@
package forge.match.input; package forge.match.input;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.tuple.ImmutablePair;
import forge.card.mana.ManaCost; import forge.card.mana.ManaCost;
import forge.card.mana.ManaCostShard; import forge.card.mana.ManaCostShard;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.card.CardUtil; import forge.game.card.CardUtil;
import forge.game.mana.ManaCostBeingPaid; import forge.game.mana.ManaCostBeingPaid;
import forge.game.player.Player; import forge.game.player.Player;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import org.apache.commons.lang3.tuple.ImmutablePair;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public final class InputSelectCardsForConvoke extends InputSelectManyBase<Card> { public final class InputSelectCardsForConvoke extends InputSelectManyBase<Card> {
private static final long serialVersionUID = -1779224307654698954L; private static final long serialVersionUID = -1779224307654698954L;
@@ -24,8 +25,8 @@ public final class InputSelectCardsForConvoke extends InputSelectManyBase<Card>
private final Player player; private final Player player;
private final List<Card> availableCreatures; private final List<Card> availableCreatures;
public InputSelectCardsForConvoke(Player p, ManaCost cost, List<Card> untapped) { public InputSelectCardsForConvoke(final PlayerControllerHuman controller, final Player p, final ManaCost cost, final List<Card> untapped) {
super(0, Math.min(cost.getCMC(), untapped.size())); super(controller, 0, Math.min(cost.getCMC(), untapped.size()));
remainingCost = new ManaCostBeingPaid(cost); remainingCost = new ManaCostBeingPaid(cost);
player = p; player = p;
allowUnselect = true; allowUnselect = true;

View File

@@ -1,21 +1,22 @@
package forge.match.input; package forge.match.input;
import forge.game.card.Card;
import java.util.Collection; import java.util.Collection;
import forge.game.card.Card;
import forge.player.PlayerControllerHuman;
public class InputSelectCardsFromList extends InputSelectEntitiesFromList<Card> { public class InputSelectCardsFromList extends InputSelectEntitiesFromList<Card> {
private static final long serialVersionUID = 6230360322294805986L; private static final long serialVersionUID = 6230360322294805986L;
public InputSelectCardsFromList(int cnt, Collection<Card> validCards) { public InputSelectCardsFromList(final PlayerControllerHuman controller, final int cnt, final Collection<Card> validCards) {
super(cnt, cnt, validCards); // to avoid hangs super(controller, cnt, cnt, validCards); // to avoid hangs
} }
public InputSelectCardsFromList(int min, int max, Collection<Card> validCards) { public InputSelectCardsFromList(final PlayerControllerHuman controller, final int min, final int max, final Collection<Card> validCards) {
super(min, max, validCards); // to avoid hangs super(controller, min, max, validCards); // to avoid hangs
} }
public InputSelectCardsFromList(Collection<Card> validCards) { public InputSelectCardsFromList(final PlayerControllerHuman controller, final Collection<Card> validCards) {
super(1, 1, validCards); // to avoid hangs super(controller, 1, 1, validCards); // to avoid hangs
} }
} }

View File

@@ -1,27 +1,28 @@
package forge.match.input; package forge.match.input;
import forge.game.GameEntity;
import forge.game.card.Card;
import forge.game.player.Player;
import forge.util.ITriggerEvent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import forge.game.GameEntity;
import forge.game.card.Card;
import forge.game.player.Player;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent;
public class InputSelectEntitiesFromList<T extends GameEntity> extends InputSelectManyBase<T> { public class InputSelectEntitiesFromList<T extends GameEntity> extends InputSelectManyBase<T> {
private static final long serialVersionUID = -6609493252672573139L; private static final long serialVersionUID = -6609493252672573139L;
private final Collection<T> validChoices; private final Collection<T> validChoices;
protected final List<T> selected = new ArrayList<T>(); protected final List<T> selected = new ArrayList<T>();
public InputSelectEntitiesFromList(int min, int max, Collection<T> validChoices) { public InputSelectEntitiesFromList(final PlayerControllerHuman controller, final int min, final int max, final Collection<T> validChoices) {
super(Math.min(min, validChoices.size()), Math.min(max, validChoices.size())); super(controller, Math.min(min, validChoices.size()), Math.min(max, validChoices.size()));
this.validChoices = validChoices; this.validChoices = validChoices;
if ( min > validChoices.size() ) if (min > validChoices.size()) {
System.out.println(String.format("Trying to choose at least %d cards from a list with only %d cards!", min, validChoices.size())); System.out.println(String.format("Trying to choose at least %d cards from a list with only %d cards!", min, validChoices.size()));
}
} }
@Override @Override

View File

@@ -1,12 +1,12 @@
package forge.match.input; package forge.match.input;
import java.util.Collection;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import forge.GuiBase;
import forge.game.GameEntity; import forge.game.GameEntity;
import forge.game.card.Card; import forge.game.card.Card;
import forge.player.PlayerControllerHuman;
import java.util.Collection;
public abstract class InputSelectManyBase<T extends GameEntity> extends InputSyncronizedBase { public abstract class InputSelectManyBase<T extends GameEntity> extends InputSyncronizedBase {
private static final long serialVersionUID = -2305549394512889450L; private static final long serialVersionUID = -2305549394512889450L;
@@ -19,7 +19,8 @@ public abstract class InputSelectManyBase<T extends GameEntity> extends InputSyn
protected String message = "Source-Card-Name - Select %d more card(s)"; protected String message = "Source-Card-Name - Select %d more card(s)";
protected InputSelectManyBase(int min, int max) { protected InputSelectManyBase(final PlayerControllerHuman controller, final int min, final int max) {
super(controller);
if (min > max) { if (min > max) {
throw new IllegalArgumentException("Min must not be greater than Max"); throw new IllegalArgumentException("Min must not be greater than Max");
} }
@@ -44,7 +45,7 @@ public abstract class InputSelectManyBase<T extends GameEntity> extends InputSyn
@Override @Override
public final void showMessage() { public final void showMessage() {
showMessage(getMessage()); showMessage(getMessage());
ButtonUtil.update(hasEnoughTargets(), allowCancel, true); ButtonUtil.update(getGui(), hasEnoughTargets(), allowCancel, true);
} }
@Override @Override
@@ -72,16 +73,16 @@ public abstract class InputSelectManyBase<T extends GameEntity> extends InputSyn
this.message = message0; this.message = message0;
} }
protected void onSelectStateChanged(GameEntity c, boolean newState) { protected void onSelectStateChanged(final GameEntity c, final boolean newState) {
if (c instanceof Card) { if (c instanceof Card) {
GuiBase.getInterface().setUsedToPay((Card)c, newState); // UI supports card highlighting though this abstraction-breaking mechanism getGui().setUsedToPay(getController().getCardView((Card) c), newState); // UI supports card highlighting though this abstraction-breaking mechanism
} }
} }
protected void afterStop() { protected void afterStop() {
for (GameEntity c : getSelected()) { for (final GameEntity c : getSelected()) {
if (c instanceof Card) { if (c instanceof Card) {
GuiBase.getInterface().setUsedToPay((Card)c, false); getGui().setUsedToPay(getController().getCardView((Card) c), false);
} }
} }
} }

View File

@@ -1,6 +1,11 @@
package forge.match.input; package forge.match.input;
import forge.GuiBase; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import forge.game.GameEntity; import forge.game.GameEntity;
import forge.game.GameObject; import forge.game.GameObject;
import forge.game.ability.ApiType; import forge.game.ability.ApiType;
@@ -8,15 +13,10 @@ import forge.game.card.Card;
import forge.game.player.Player; import forge.game.player.Player;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.game.spellability.TargetRestrictions; import forge.game.spellability.TargetRestrictions;
import forge.player.PlayerControllerHuman;
import forge.util.ITriggerEvent; import forge.util.ITriggerEvent;
import forge.util.gui.SGuiChoose; import forge.util.gui.SGuiChoose;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public final class InputSelectTargets extends InputSyncronizedBase { public final class InputSelectTargets extends InputSyncronizedBase {
private final List<Card> choices; private final List<Card> choices;
@@ -43,7 +43,8 @@ public final class InputSelectTargets extends InputSyncronizedBase {
* @param sa * @param sa
* @param mandatory * @param mandatory
*/ */
public InputSelectTargets(List<Card> choices, SpellAbility sa, boolean mandatory) { public InputSelectTargets(final PlayerControllerHuman controller, final List<Card> choices, final SpellAbility sa, final boolean mandatory) {
super(controller);
this.choices = choices; this.choices = choices;
this.tgt = sa.getTargetRestrictions(); this.tgt = sa.getTargetRestrictions();
this.sa = sa; this.sa = sa;
@@ -77,19 +78,19 @@ public final class InputSelectTargets extends InputSyncronizedBase {
if (!tgt.isMinTargetsChosen(sa.getHostCard(), sa) || tgt.isDividedAsYouChoose()) { if (!tgt.isMinTargetsChosen(sa.getHostCard(), sa) || tgt.isDividedAsYouChoose()) {
if (mandatory && tgt.hasCandidates(sa, true)) { if (mandatory && tgt.hasCandidates(sa, true)) {
// Player has to click on a target // Player has to click on a target
ButtonUtil.update(false, false, false); ButtonUtil.update(getGui(), false, false, false);
} }
else { else {
ButtonUtil.update(false, true, false); ButtonUtil.update(getGui(), false, true, false);
} }
} }
else { else {
if (mandatory && tgt.hasCandidates(sa, true)) { if (mandatory && tgt.hasCandidates(sa, true)) {
// Player has to click on a target or ok // Player has to click on a target or ok
ButtonUtil.update(true, false, true); ButtonUtil.update(getGui(), true, false, true);
} }
else { else {
ButtonUtil.update(true, true, true); ButtonUtil.update(getGui(), true, true, true);
} }
} }
} }
@@ -176,7 +177,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append(apiBasedMessage); sb.append(apiBasedMessage);
sb.append(card.toString()); sb.append(card.toString());
Integer chosen = SGuiChoose.oneOrNone(sb.toString(), choices); Integer chosen = SGuiChoose.oneOrNone(getGui(), sb.toString(), choices);
if (chosen == null) { if (chosen == null) {
return true; //still return true since there was a valid choice return true; //still return true since there was a valid choice
} }
@@ -220,7 +221,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append(apiBasedMessage); sb.append(apiBasedMessage);
sb.append(player.getName()); sb.append(player.getName());
Integer chosen = SGuiChoose.oneOrNone(sb.toString(), choices); Integer chosen = SGuiChoose.oneOrNone(getGui(), sb.toString(), choices);
if (null == chosen) { if (null == chosen) {
return; return;
} }
@@ -234,13 +235,13 @@ public final class InputSelectTargets extends InputSyncronizedBase {
addTarget(player); addTarget(player);
} }
private void addTarget(GameEntity ge) { private void addTarget(final GameEntity ge) {
sa.getTargets().add(ge); sa.getTargets().add(ge);
if (ge instanceof Card) { if (ge instanceof Card) {
GuiBase.getInterface().setUsedToPay((Card) ge, true); getGui().setUsedToPay(getController().getCardView((Card) ge), true);
lastTarget = (Card) ge; lastTarget = (Card) ge;
} }
Integer val = targetDepth.get(ge); final Integer val = targetDepth.get(ge);
targetDepth.put(ge, val == null ? Integer.valueOf(1) : Integer.valueOf(val.intValue() + 1) ); targetDepth.put(ge, val == null ? Integer.valueOf(1) : Integer.valueOf(val.intValue() + 1) );
if(hasAllTargets()) { if(hasAllTargets()) {
@@ -252,9 +253,9 @@ public final class InputSelectTargets extends InputSyncronizedBase {
} }
private void done() { private void done() {
for (GameEntity c : targetDepth.keySet()) { for (final GameEntity c : targetDepth.keySet()) {
if (c instanceof Card) { if (c instanceof Card) {
GuiBase.getInterface().setUsedToPay((Card)c, false); getGui().setUsedToPay(getController().getCardView((Card) c), false);
} }
} }

View File

@@ -1,21 +1,22 @@
package forge.match.input; package forge.match.input;
import forge.FThreads;
import forge.GuiBase;
import forge.error.BugReporter;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import forge.FThreads;
import forge.error.BugReporter;
import forge.player.PlayerControllerHuman;
public abstract class InputSyncronizedBase extends InputBase implements InputSynchronized { public abstract class InputSyncronizedBase extends InputBase implements InputSynchronized {
private static final long serialVersionUID = 8756177361251703052L; private static final long serialVersionUID = 8756177361251703052L;
private final CountDownLatch cdlDone; private final CountDownLatch cdlDone;
public InputSyncronizedBase() { public InputSyncronizedBase(final PlayerControllerHuman controller) {
super(controller);
cdlDone = new CountDownLatch(1); cdlDone = new CountDownLatch(1);
} }
public void awaitLatchRelease() { public void awaitLatchRelease() {
FThreads.assertExecutedByEdt(false); FThreads.assertExecutedByEdt(getGui(), false);
try{ try{
cdlDone.await(); cdlDone.await();
} }
@@ -30,7 +31,7 @@ public abstract class InputSyncronizedBase extends InputBase implements InputSyn
public void showAndWait() { public void showAndWait() {
GuiBase.getInterface().getInputQueue().setInput(this); getGui().getInputQueue().setInput(this);
awaitLatchRelease(); awaitLatchRelease();
} }
@@ -38,7 +39,7 @@ public abstract class InputSyncronizedBase extends InputBase implements InputSyn
onStop(); onStop();
// ensure input won't accept any user actions. // ensure input won't accept any user actions.
FThreads.invokeInEdtNowOrLater(new Runnable() { FThreads.invokeInEdtNowOrLater(getGui(), new Runnable() {
@Override @Override
public void run() { public void run() {
setFinished(); setFinished();
@@ -46,7 +47,7 @@ public abstract class InputSyncronizedBase extends InputBase implements InputSyn
}); });
// thread irrelevant // thread irrelevant
GuiBase.getInterface().getInputQueue().removeInput(InputSyncronizedBase.this); getGui().getInputQueue().removeInput(InputSyncronizedBase.this);
cdlDone.countDown(); cdlDone.countDown();
} }

View File

@@ -19,13 +19,16 @@ package forge.model;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import forge.card.CardEdition; import forge.card.CardEdition;
import forge.card.IUnOpenedProduct; import forge.card.IUnOpenedProduct;
import forge.card.UnOpenedProduct; import forge.card.UnOpenedProduct;
import forge.interfaces.IGuiBase;
import forge.item.IPaperCard; import forge.item.IPaperCard;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.util.TextUtil; import forge.util.TextUtil;
import forge.util.storage.StorageReaderFile; import forge.util.storage.StorageReaderFile;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList; import java.util.ArrayList;
@@ -293,10 +296,12 @@ public final class CardBlock implements Comparable<CardBlock> {
* *
* @param code * @param code
* String, the MetaSet code * String, the MetaSet code
* @param gui
* the {@link IGuiBase} resolving any choices to be made.
* @return UnOpenedProduct, the created booster. * @return UnOpenedProduct, the created booster.
*/ */
public IUnOpenedProduct getBooster(final String code) { public IUnOpenedProduct getBooster(final String code, final IGuiBase gui) {
MetaSet ms = metaSets.get(code); MetaSet ms = metaSets.get(code);
return ms == null ? new UnOpenedProduct(FModel.getMagicDb().getBoosters().get(code)) : ms.getBooster(); return ms == null ? new UnOpenedProduct(FModel.getMagicDb().getBoosters().get(code)) : ms.getBooster(gui);
} }
} }

View File

@@ -22,9 +22,11 @@ import forge.deck.DeckGroup;
import forge.deck.io.DeckGroupSerializer; import forge.deck.io.DeckGroupSerializer;
import forge.deck.io.DeckStorage; import forge.deck.io.DeckStorage;
import forge.deck.io.OldDeckParser; import forge.deck.io.OldDeckParser;
import forge.interfaces.IGuiBase;
import forge.properties.ForgeConstants; import forge.properties.ForgeConstants;
import forge.util.storage.IStorage; import forge.util.storage.IStorage;
import forge.util.storage.StorageImmediatelySerialized; import forge.util.storage.StorageImmediatelySerialized;
import org.apache.commons.lang3.time.StopWatch; import org.apache.commons.lang3.time.StopWatch;
import java.io.File; import java.io.File;
@@ -48,7 +50,7 @@ public class CardCollections {
* *
* @param file the file * @param file the file
*/ */
public CardCollections() { public CardCollections(final IGuiBase gui) {
StopWatch sw = new StopWatch(); StopWatch sw = new StopWatch();
sw.start(); sw.start();
this.constructed = new StorageImmediatelySerialized<Deck>("Constructed decks", new DeckStorage(new File(ForgeConstants.DECK_CONSTRUCTED_DIR), true), true); this.constructed = new StorageImmediatelySerialized<Deck>("Constructed decks", new DeckStorage(new File(ForgeConstants.DECK_CONSTRUCTED_DIR), true), true);
@@ -64,7 +66,7 @@ public class CardCollections {
// int sum = constructed.size() + sealed.size() + draft.size() + cube.size() + scheme.size() + plane.size(); // int sum = constructed.size() + sealed.size() + draft.size() + cube.size() + scheme.size() + plane.size();
// FSkin.setProgessBarMessage(String.format("Loaded %d decks in %f sec", sum, sw.getTime() / 1000f )); // FSkin.setProgessBarMessage(String.format("Loaded %d decks in %f sec", sum, sw.getTime() / 1000f ));
// remove this after most people have been switched to new layout // remove this after most people have been switched to new layout
final OldDeckParser oldParser = new OldDeckParser(this.constructed, this.draft, this.sealed, this.cube); final OldDeckParser oldParser = new OldDeckParser(gui, this.constructed, this.draft, this.sealed, this.cube);
oldParser.tryParse(); oldParser.tryParse();
} }

View File

@@ -28,6 +28,7 @@ import forge.deck.io.DeckPreferences;
import forge.game.GameFormat; import forge.game.GameFormat;
import forge.game.card.CardUtil; import forge.game.card.CardUtil;
import forge.gauntlet.GauntletData; import forge.gauntlet.GauntletData;
import forge.interfaces.IGuiBase;
import forge.interfaces.IProgressBar; import forge.interfaces.IProgressBar;
import forge.itemmanager.ItemManagerConfig; import forge.itemmanager.ItemManagerConfig;
import forge.limited.GauntletMini; import forge.limited.GauntletMini;
@@ -74,7 +75,7 @@ public class FModel {
private static IStorage<QuestWorld> worlds; private static IStorage<QuestWorld> worlds;
private static GameFormat.Collection formats; private static GameFormat.Collection formats;
public static void initialize(final IProgressBar progressBar) { public static void initialize(final IGuiBase gui, final IProgressBar progressBar) {
// Instantiate preferences: quest and regular // Instantiate preferences: quest and regular
//Preferences are initialized first so that the splash screen can be translated. //Preferences are initialized first so that the splash screen can be translated.
@@ -92,7 +93,7 @@ public class FModel {
ProgressObserver.emptyObserver : new ProgressObserver() { ProgressObserver.emptyObserver : new ProgressObserver() {
@Override @Override
public void setOperationName(final String name, final boolean usePercents) { public void setOperationName(final String name, final boolean usePercents) {
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
progressBar.setDescription(name); progressBar.setDescription(name);
@@ -103,7 +104,7 @@ public class FModel {
@Override @Override
public void report(final int current, final int total) { public void report(final int current, final int total) {
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
progressBar.setMaximum(total); progressBar.setMaximum(total);
@@ -140,7 +141,7 @@ public class FModel {
loadDynamicGamedata(); loadDynamicGamedata();
if (progressBar != null) { if (progressBar != null) {
FThreads.invokeInEdtLater(new Runnable() { FThreads.invokeInEdtLater(gui, new Runnable() {
@Override @Override
public void run() { public void run() {
progressBar.setDescription(Localizer.getInstance().getMessage("splash.loading.decks")); progressBar.setDescription(Localizer.getInstance().getMessage("splash.loading.decks"));
@@ -148,8 +149,8 @@ public class FModel {
}); });
} }
decks = new CardCollections(); decks = new CardCollections(gui);
quest = new QuestController(); quest = new QuestController(gui);
CardPreferences.load(); CardPreferences.load();
DeckPreferences.load(); DeckPreferences.load();
@@ -264,9 +265,9 @@ public class FModel {
gauntletData = data0; gauntletData = data0;
} }
public static GauntletMini getGauntletMini() { public static GauntletMini getGauntletMini(final IGuiBase gui) {
if (gauntlet == null) { if (gauntlet == null) {
gauntlet = new GauntletMini(); gauntlet = new GauntletMini(gui);
} }
return gauntlet; return gauntlet;
} }

View File

@@ -22,6 +22,7 @@ import com.google.common.base.Predicate;
import forge.card.IUnOpenedProduct; import forge.card.IUnOpenedProduct;
import forge.card.UnOpenedProduct; import forge.card.UnOpenedProduct;
import forge.interfaces.IGuiBase;
import forge.item.IPaperCard; import forge.item.IPaperCard;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.item.SealedProduct; import forge.item.SealedProduct;
@@ -162,7 +163,7 @@ public class MetaSet {
* *
* @return UnOpenedProduct, the generated booster. * @return UnOpenedProduct, the generated booster.
*/ */
public IUnOpenedProduct getBooster() { public IUnOpenedProduct getBooster(final IGuiBase gui) {
switch(type) { switch(type) {
case Full: case Full:
@@ -181,7 +182,7 @@ public class MetaSet {
Predicate<PaperCard> predicate = IPaperCard.Predicates.printedInSets(data.split(" ")); Predicate<PaperCard> predicate = IPaperCard.Predicates.printedInSets(data.split(" "));
return new UnOpenedProduct(SealedProduct.Template.genericBooster, predicate); return new UnOpenedProduct(SealedProduct.Template.genericBooster, predicate);
case Choose: return UnOpenedMeta.choose(data); case Choose: return UnOpenedMeta.choose(data, gui);
case Random: return UnOpenedMeta.random(data); case Random: return UnOpenedMeta.random(data);
case Combo: return UnOpenedMeta.selectAll(data); case Combo: return UnOpenedMeta.selectAll(data);

View File

@@ -19,6 +19,7 @@
package forge.model; package forge.model;
import forge.card.IUnOpenedProduct; import forge.card.IUnOpenedProduct;
import forge.interfaces.IGuiBase;
import forge.item.PaperCard; import forge.item.PaperCard;
import forge.util.MyRandom; import forge.util.MyRandom;
import forge.util.TextUtil; import forge.util.TextUtil;
@@ -44,17 +45,22 @@ public class UnOpenedMeta implements IUnOpenedProduct {
private final ArrayList<MetaSet> metaSets; private final ArrayList<MetaSet> metaSets;
private final JoinOperation operation; private final JoinOperation operation;
private final Random generator = MyRandom.getRandom(); private final Random generator = MyRandom.getRandom();
private final IGuiBase gui;
/** /**
* Constructor for UnOpenedMeta. * Constructor for UnOpenedMeta.
*
* @param creationString * @param creationString
* String, is parsed for MetaSet info. * String, is parsed for MetaSet info.
* @param choose * @param choose
* sets the random/choice status. * sets the random/choice status.
* @param gui
* the gui.
*/ */
private UnOpenedMeta(final String creationString, final JoinOperation op) { private UnOpenedMeta(final String creationString, final JoinOperation op, final IGuiBase gui) {
metaSets = new ArrayList<MetaSet>(); metaSets = new ArrayList<MetaSet>();
operation = op; operation = op;
this.gui = gui;
for (String m : TextUtil.splitWithParenthesis(creationString, ';')) { for (String m : TextUtil.splitWithParenthesis(creationString, ';')) {
metaSets.add(new MetaSet(m, true)); metaSets.add(new MetaSet(m, true));
@@ -88,39 +94,39 @@ public class UnOpenedMeta implements IUnOpenedProduct {
if (isHuman) { if (isHuman) {
final MetaSet ms; final MetaSet ms;
if (allowCancel) { if (allowCancel) {
ms = SGuiChoose.oneOrNone("Choose Booster", metaSets); ms = SGuiChoose.oneOrNone(gui, "Choose Booster", metaSets);
if (ms == null) { if (ms == null) {
return null; return null;
} }
} }
else { else {
ms = SGuiChoose.one("Choose Booster", metaSets); ms = SGuiChoose.one(gui, "Choose Booster", metaSets);
} }
return ms.getBooster().get(); return ms.getBooster(gui).get();
} }
case RandomOne: // AI should fall though here from the case above case RandomOne: // AI should fall though here from the case above
int selected = generator.nextInt(metaSets.size()); int selected = generator.nextInt(metaSets.size());
final IUnOpenedProduct newBooster = metaSets.get(selected).getBooster(); final IUnOpenedProduct newBooster = metaSets.get(selected).getBooster(gui);
return newBooster.get(); return newBooster.get();
case SelectAll: case SelectAll:
List<PaperCard> allCards = new ArrayList<PaperCard>(); List<PaperCard> allCards = new ArrayList<PaperCard>();
for (MetaSet ms : metaSets) { for (MetaSet ms : metaSets) {
allCards.addAll(ms.getBooster().get()); allCards.addAll(ms.getBooster(gui).get());
} }
return allCards; return allCards;
} }
throw new IllegalStateException("Got wrong operation type in unopenedMeta - execution should never reach this point"); throw new IllegalStateException("Got wrong operation type in unopenedMeta - execution should never reach this point");
} }
public static UnOpenedMeta choose(String desc) { public static UnOpenedMeta choose(final String desc, final IGuiBase gui) {
return new UnOpenedMeta(desc, JoinOperation.ChooseOne); return new UnOpenedMeta(desc, JoinOperation.ChooseOne, gui);
} }
public static UnOpenedMeta random(String desc) { public static UnOpenedMeta random(final String desc) {
return new UnOpenedMeta(desc, JoinOperation.RandomOne); return new UnOpenedMeta(desc, JoinOperation.RandomOne, null);
} }
public static UnOpenedMeta selectAll(String desc) { public static UnOpenedMeta selectAll(final String desc) {
return new UnOpenedMeta(desc, JoinOperation.SelectAll); return new UnOpenedMeta(desc, JoinOperation.SelectAll, null);
} }
} }

View File

@@ -1,5 +1,6 @@
package forge.player; package forge.player;
import forge.interfaces.IGuiBase;
import forge.model.FModel; import forge.model.FModel;
import forge.properties.ForgePreferences; import forge.properties.ForgePreferences;
import forge.properties.ForgePreferences.FPref; import forge.properties.ForgePreferences.FPref;
@@ -12,42 +13,42 @@ public final class GamePlayerUtil {
private final static ForgePreferences prefs = FModel.getPreferences(); private final static ForgePreferences prefs = FModel.getPreferences();
public static void setPlayerName() { public static void setPlayerName(final IGuiBase gui) {
String oldPlayerName = prefs.getPref(FPref.PLAYER_NAME); String oldPlayerName = prefs.getPref(FPref.PLAYER_NAME);
String newPlayerName = null; String newPlayerName = null;
if (StringUtils.isBlank(oldPlayerName)) { if (StringUtils.isBlank(oldPlayerName)) {
newPlayerName = getVerifiedPlayerName(getPlayerNameUsingFirstTimePrompt(), oldPlayerName); newPlayerName = getVerifiedPlayerName(getPlayerNameUsingFirstTimePrompt(gui), oldPlayerName);
} else { } else {
newPlayerName = getVerifiedPlayerName(getPlayerNameUsingStandardPrompt(oldPlayerName), oldPlayerName); newPlayerName = getVerifiedPlayerName(getPlayerNameUsingStandardPrompt(gui, oldPlayerName), oldPlayerName);
} }
prefs.setPref(FPref.PLAYER_NAME, newPlayerName); prefs.setPref(FPref.PLAYER_NAME, newPlayerName);
prefs.save(); prefs.save();
if (StringUtils.isBlank(oldPlayerName) && newPlayerName != "Human") { if (StringUtils.isBlank(oldPlayerName) && newPlayerName != "Human") {
showThankYouPrompt(newPlayerName); showThankYouPrompt(gui, newPlayerName);
} }
} }
private static void showThankYouPrompt(String playerName) { private static void showThankYouPrompt(final IGuiBase gui, final String playerName) {
SOptionPane.showMessageDialog("Thank you, " + playerName + ". " SOptionPane.showMessageDialog(gui, "Thank you, " + playerName + ". "
+ "You will not be prompted again but you can change\n" + "You will not be prompted again but you can change\n"
+ "your name at any time using the \"Player Name\" setting in Preferences\n" + "your name at any time using the \"Player Name\" setting in Preferences\n"
+ "or via the constructed match setup screen\n"); + "or via the constructed match setup screen\n");
} }
private static String getPlayerNameUsingFirstTimePrompt() { private static String getPlayerNameUsingFirstTimePrompt(final IGuiBase gui) {
return SOptionPane.showInputDialog( return SOptionPane.showInputDialog(gui,
"By default, Forge will refer to you as the \"Human\" during gameplay.\n" + "By default, Forge will refer to you as the \"Human\" during gameplay.\n" +
"If you would prefer a different name please enter it now.", "If you would prefer a different name please enter it now.",
"Personalize Forge Gameplay", "Personalize Forge Gameplay",
SOptionPane.QUESTION_ICON); SOptionPane.QUESTION_ICON);
} }
private static String getPlayerNameUsingStandardPrompt(String playerName) { private static String getPlayerNameUsingStandardPrompt(final IGuiBase gui, final String playerName) {
return SOptionPane.showInputDialog( return SOptionPane.showInputDialog(gui,
"Please enter a new name. (alpha-numeric only)", "Please enter a new name. (alpha-numeric only)",
"Personalize Forge Gameplay", "Personalize Forge Gameplay",
null, null,

View File

@@ -18,6 +18,7 @@ import forge.game.player.Player;
import forge.game.spellability.SpellAbility; import forge.game.spellability.SpellAbility;
import forge.game.spellability.SpellAbilityStackInstance; import forge.game.spellability.SpellAbilityStackInstance;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import forge.interfaces.IGuiBase;
import forge.match.input.InputSelectCardsFromList; import forge.match.input.InputSelectCardsFromList;
import forge.match.input.InputSelectManyBase; import forge.match.input.InputSelectManyBase;
import forge.util.Aggregates; import forge.util.Aggregates;
@@ -25,21 +26,29 @@ import forge.util.ITriggerEvent;
import forge.util.Lang; import forge.util.Lang;
import forge.util.gui.SGuiChoose; import forge.util.gui.SGuiChoose;
import forge.util.gui.SGuiDialog; import forge.util.gui.SGuiDialog;
import forge.view.CardView;
import forge.view.PlayerView;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
public class HumanCostDecision extends CostDecisionMakerBase { public class HumanCostDecision extends CostDecisionMakerBase {
private final PlayerControllerHuman controller;
private final SpellAbility ability; private final SpellAbility ability;
private final Card source; private final Card source;
public HumanCostDecision(Player p, SpellAbility sa, Card source) { public HumanCostDecision(final PlayerControllerHuman controller, final Player p, final SpellAbility sa, final Card source) {
super(p); super(p);
this.controller = controller;
ability = sa; ability = sa;
this.source = source; this.source = source;
} }
private IGuiBase getGui() {
return this.controller.getGui();
}
protected int chooseXValue(final int maxValue) { protected int chooseXValue(final int maxValue) {
/*final String chosen = sa.getSVar("ChosenX"); /*final String chosen = sa.getSVar("ChosenX");
if (chosen.length() > 0) { if (chosen.length() > 0) {
@@ -63,7 +72,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
@Override @Override
public PaymentDecision visit(CostChooseCreatureType cost) { public PaymentDecision visit(CostChooseCreatureType cost) {
String choice = player.getController().chooseSomeType("Creature", ability, new ArrayList<String>(CardType.getCreatureTypes()), new ArrayList<String>(), true); String choice = controller.chooseSomeType("Creature", ability, new ArrayList<String>(CardType.getCreatureTypes()), new ArrayList<String>(), true);
if( null == choice ) if( null == choice )
return null; return null;
return PaymentDecision.type(choice); return PaymentDecision.type(choice);
@@ -122,7 +131,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (c == 0) { return PaymentDecision.card(Lists.<Card>newArrayList()); } if (c == 0) { return PaymentDecision.card(Lists.<Card>newArrayList()); }
List<Card> discarded = new ArrayList<Card>(); List<Card> discarded = new ArrayList<Card>();
while (c > 0) { while (c > 0) {
InputSelectCardsFromList inp = new InputSelectCardsFromList(1, 1, handList); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, 1, 1, handList);
inp.setMessage("Select one of the cards with the same name to discard. Already chosen: " + discarded); inp.setMessage("Select one of the cards with the same name to discard. Already chosen: " + discarded);
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
inp.showAndWait(); inp.showAndWait();
@@ -153,7 +162,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
} }
} }
InputSelectCardsFromList inp = new InputSelectCardsFromList(c, c, handList); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, c, c, handList);
inp.setMessage("Select %d more " + cost.getDescriptiveType() + " to discard."); inp.setMessage("Select %d more " + cost.getDescriptiveType() + " to discard.");
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
inp.showAndWait(); inp.showAndWait();
@@ -251,7 +260,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
} }
if (cost.from == ZoneType.Battlefield || cost.from == ZoneType.Hand) { if (cost.from == ZoneType.Battlefield || cost.from == ZoneType.Hand) {
InputSelectCardsFromList inp = new InputSelectCardsFromList(c, c, list); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, c, c, list);
inp.setMessage("Exile %d card(s) from your" + cost.from); inp.setMessage("Exile %d card(s) from your" + cost.from);
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
inp.showAndWait(); inp.showAndWait();
@@ -290,8 +299,9 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (nNeeded == 0) { if (nNeeded == 0) {
return PaymentDecision.number(0); return PaymentDecision.number(0);
} }
final PlayerView view = SGuiChoose.oneOrNone(getGui(), String.format("Exile from whose %s?", cost.getFrom()),
final Player p = SGuiChoose.oneOrNone(String.format("Exile from whose %s?", cost.getFrom()), payableZone); controller.getPlayerViews(payableZone));
final Player p = controller.getPlayer(view);
if (p == null) { if (p == null) {
return null; return null;
} }
@@ -301,7 +311,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if(count < nNeeded) if(count < nNeeded)
return null; return null;
List<Card> toExile = SGuiChoose.many("Exile from " + cost.getFrom(), "To be exiled", count - nNeeded, typeList, null); List<Card> toExile = SGuiChoose.many(getGui(), "Exile from " + cost.getFrom(), "To be exiled", count - nNeeded, typeList, null);
return PaymentDecision.card(toExile); return PaymentDecision.card(toExile);
} }
@@ -348,7 +358,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
List<SpellAbility> exiled = new ArrayList<SpellAbility>(); List<SpellAbility> exiled = new ArrayList<SpellAbility>();
for (int i = 0; i < c; i++) { for (int i = 0; i < c; i++) {
//Have to use the stack descriptions here because some copied spells have no description otherwise //Have to use the stack descriptions here because some copied spells have no description otherwise
final String o = SGuiChoose.oneOrNone("Exile from Stack", descList); final String o = SGuiChoose.oneOrNone(getGui(), "Exile from Stack", descList);
if (o != null) { if (o != null) {
final SpellAbility toExile = saList.get(descList.indexOf(o)); final SpellAbility toExile = saList.get(descList.indexOf(o));
@@ -382,7 +392,8 @@ public class HumanCostDecision extends CostDecisionMakerBase {
List<Card> exiled = new ArrayList<Card>(); List<Card> exiled = new ArrayList<Card>();
for (int i = 0; i < nNeeded; i++) { for (int i = 0; i < nNeeded; i++) {
final Card c = SGuiChoose.oneOrNone("Exile from " + cost.getFrom(), typeList); final CardView view = SGuiChoose.oneOrNone(getGui(), "Exile from " + cost.getFrom(), controller.getCardViews(typeList));
final Card c = controller.getCard(view);
if (c != null) { if (c != null) {
typeList.remove(c); typeList.remove(c);
@@ -416,7 +427,9 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (list.size() < c) if (list.size() < c)
return null; return null;
return PaymentDecision.card(SGuiChoose.many("Choose an exiled card to put into graveyard", "To graveyard", c, list, source)); final List<CardView> choice = SGuiChoose.many(getGui(), "Choose an exiled card to put into graveyard", "To graveyard", c,
controller.getCardViews(list), controller.getCardView(source));
return PaymentDecision.card(controller.getCards(choice));
} }
@Override @Override
@@ -447,7 +460,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
final List<Card> list = player.getCardsIn(ZoneType.Battlefield); final List<Card> list = player.getCardsIn(ZoneType.Battlefield);
List<Card> validCards = CardLists.getValidCards(list, cost.getType().split(";"), player, source); List<Card> validCards = CardLists.getValidCards(list, cost.getType().split(";"), player, source);
InputSelectCardsFromList inp = new InputSelectCardsFromList(c, validCards); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, c, validCards);
final String desc = cost.getTypeDescription() == null ? cost.getType() : cost.getTypeDescription(); final String desc = cost.getTypeDescription() == null ? cost.getType() : cost.getTypeDescription();
inp.setMessage("Gain control of %d " + desc); inp.setMessage("Gain control of %d " + desc);
inp.showAndWait(); inp.showAndWait();
@@ -487,7 +500,8 @@ public class HumanCostDecision extends CostDecisionMakerBase {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append(source.getName()).append(" - Choose an opponent to gain ").append(c).append(" life:"); sb.append(source.getName()).append(" - Choose an opponent to gain ").append(c).append(" life:");
final Player chosenToGain = SGuiChoose.oneOrNone(sb.toString(), oppsThatCanGainLife); final PlayerView chosenToGainView = SGuiChoose.oneOrNone(getGui(), sb.toString(), controller.getPlayerViews(oppsThatCanGainLife));
final Player chosenToGain = controller.getPlayer(chosenToGainView);
if (null == chosenToGain) if (null == chosenToGain)
return null; return null;
else else
@@ -568,7 +582,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
list = CardLists.getValidCards(list, cost.getType().split(";"), player, source); list = CardLists.getValidCards(list, cost.getType().split(";"), player, source);
if (cost.from == ZoneType.Hand) { if (cost.from == ZoneType.Hand) {
InputSelectCardsFromList inp = new InputSelectCardsFromList(c, c, list); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, c, c, list);
inp.setMessage("Put %d card(s) from your " + cost.from ); inp.setMessage("Put %d card(s) from your " + cost.from );
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
inp.showAndWait(); inp.showAndWait();
@@ -597,14 +611,16 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if(typeList.size() < nNeeded) if(typeList.size() < nNeeded)
return null; return null;
final List<CardView> viewList = controller.getCardViews(typeList);
List<Card> chosen = new ArrayList<>(); List<Card> chosen = new ArrayList<>();
for (int i = 0; i < nNeeded; i++) { for (int i = 0; i < nNeeded; i++) {
final Card c = SGuiChoose.oneOrNone("Put from " + fromZone + " to library", typeList); final CardView view = SGuiChoose.oneOrNone(getGui(), "Put from " + fromZone + " to library", viewList);
final Card c = controller.getCard(view);
if (c == null) if (c == null)
return null; return null;
typeList.remove(c); viewList.remove(view);
chosen.add(c); chosen.add(c);
} }
return PaymentDecision.card(chosen); return PaymentDecision.card(chosen);
@@ -615,21 +631,27 @@ public class HumanCostDecision extends CostDecisionMakerBase {
return PaymentDecision.number(0); return PaymentDecision.number(0);
} }
final Player p = SGuiChoose.oneOrNone(String.format("Put cards from whose %s?", fromZone), payableZone); final List<PlayerView> players = controller.getPlayerViews(payableZone);
final PlayerView pView = SGuiChoose.oneOrNone(getGui(), String.format("Put cards from whose %s?", fromZone), players);
final Player p = controller.getPlayer(pView);
if (p == null) { if (p == null) {
return null; return null;
} }
List<Card> typeList = CardLists.filter(list, CardPredicates.isOwner(p)); List<Card> typeList = CardLists.filter(list, CardPredicates.isOwner(p));
if(typeList.size() < nNeeded) if (typeList.size() < nNeeded)
return null; return null;
final List<CardView> viewList = controller.getCardViews(typeList);
List<Card> chosen = new ArrayList<>(); List<Card> chosen = new ArrayList<>();
for (int i = 0; i < nNeeded; i++) { for (int i = 0; i < nNeeded; i++) {
final Card c = SGuiChoose.oneOrNone("Put cards from " + fromZone + " to Library", typeList); final CardView view = SGuiChoose.oneOrNone(getGui(), "Put cards from " + fromZone + " to Library", viewList);
final Card c = controller.getCard(view);
if (c == null) if (c == null)
return null; return null;
typeList.remove(c);
viewList.remove(view);
chosen.add(c); chosen.add(c);
} }
return PaymentDecision.card(chosen); return PaymentDecision.card(chosen);
@@ -647,8 +669,8 @@ public class HumanCostDecision extends CostDecisionMakerBase {
// Cards to use this branch: Scarscale Ritual, Wandering Mage - each adds only one counter // Cards to use this branch: Scarscale Ritual, Wandering Mage - each adds only one counter
List<Card> typeList = CardLists.getValidCards(player.getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), player, ability.getHostCard()); List<Card> typeList = CardLists.getValidCards(player.getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), player, ability.getHostCard());
InputSelectCardsFromList inp = new InputSelectCardsFromList(1, 1, typeList); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, 1, 1, typeList);
inp.setMessage("Put " + Lang.nounWithAmount(c, cost.getCounter().getName() + " counter") + " on " +cost.getDescriptiveType()); inp.setMessage("Put " + Lang.nounWithAmount(c, cost.getCounter().getName() + " counter") + " on " + cost.getDescriptiveType());
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
inp.showAndWait(); inp.showAndWait();
@@ -676,13 +698,14 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (cost.payCostFromSource()) { if (cost.payCostFromSource()) {
final Card card = ability.getHostCard(); final Card card = ability.getHostCard();
if (card.getController() == player && card.isInPlay()) { if (card.getController() == player && card.isInPlay()) {
return player.getController().confirmPayment(cost, "Return " + card.getName() + " to hand?") ? PaymentDecision.card(card) : null; final CardView view = controller.getCardView(card);
return player.getController().confirmPayment(cost, "Return " + view + " to hand?") ? PaymentDecision.card(card) : null;
} }
} }
else { else {
List<Card> validCards = CardLists.getValidCards(ability.getActivatingPlayer().getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), ability.getActivatingPlayer(), ability.getHostCard()); List<Card> validCards = CardLists.getValidCards(ability.getActivatingPlayer().getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), ability.getActivatingPlayer(), ability.getHostCard());
InputSelectCardsFromList inp = new InputSelectCardsFromList(c, c, validCards); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, c, c, validCards);
inp.setMessage("Return %d " + cost.getType() + " " + cost.getType() + " card(s) to hand"); inp.setMessage("Return %d " + cost.getType() + " " + cost.getType() + " card(s) to hand");
inp.showAndWait(); inp.showAndWait();
if (inp.hasCancelled()) if (inp.hasCancelled())
@@ -723,7 +746,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (num == 0) if (num == 0)
return PaymentDecision.number(0); return PaymentDecision.number(0);
inp = new InputSelectCardsFromList(num, handList) { inp = new InputSelectCardsFromList(controller, num, handList) {
private static final long serialVersionUID = 8338626212893374798L; private static final long serialVersionUID = 8338626212893374798L;
@Override @Override
@@ -754,7 +777,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if ( num == 0 ) if ( num == 0 )
return PaymentDecision.number(0);; return PaymentDecision.number(0);;
inp = new InputSelectCardsFromList(num, num, handList); inp = new InputSelectCardsFromList(controller, num, num, handList);
inp.setMessage("Select %d more " + cost.getDescriptiveType() + " card(s) to reveal."); inp.setMessage("Select %d more " + cost.getDescriptiveType() + " card(s) to reveal.");
} }
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
@@ -784,7 +807,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
return card.hasCounters(); return card.hasCounters();
} }
}); });
InputSelectCardsFromList inp = new InputSelectCardsFromList(1, 1, list); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, 1, 1, list);
inp.setMessage("Select " + cost.getDescriptiveType() + " to remove a counter"); inp.setMessage("Select " + cost.getDescriptiveType() + " to remove a counter");
inp.setCancelAllowed(false); inp.setCancelAllowed(false);
inp.showAndWait(); inp.showAndWait();
@@ -798,7 +821,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
} }
String prompt = "Select type counters to remove"; String prompt = "Select type counters to remove";
cost.setCounterType(SGuiChoose.one(prompt, typeChoices)); cost.setCounterType(SGuiChoose.one(getGui(), prompt, typeChoices));
return PaymentDecision.card(selected, cost.getCounter()); return PaymentDecision.card(selected, cost.getCounter());
} }
@@ -810,8 +833,8 @@ public class HumanCostDecision extends CostDecisionMakerBase {
private final CounterType counterType; private final CounterType counterType;
private final List<Card> validChoices; private final List<Card> validChoices;
public InputSelectCardToRemoveCounter(int cntCounters, CounterType cType, List<Card> validCards) { public InputSelectCardToRemoveCounter(final PlayerControllerHuman controller, int cntCounters, CounterType cType, List<Card> validCards) {
super(cntCounters, cntCounters); super(controller, cntCounters, cntCounters);
this.validChoices = validCards; this.validChoices = validCards;
counterType = cType; counterType = cType;
cardsChosen = cntCounters > 0 ? new HashMap<Card, Integer>() : null; cardsChosen = cntCounters > 0 ? new HashMap<Card, Integer>() : null;
@@ -888,7 +911,8 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (cost.payCostFromSource()) { if (cost.payCostFromSource()) {
int maxCounters = source.getCounters(cost.counter); int maxCounters = source.getCounters(cost.counter);
if (amount.equals("All")) { if (amount.equals("All")) {
if (!SGuiDialog.confirm(ability.getHostCard(), "Remove all counters?")) { final CardView view = controller.getCardView(ability.getHostCard());
if (!SGuiDialog.confirm(getGui(), view, "Remove all counters?")) {
return null; return null;
} }
cntRemoved = maxCounters; cntRemoved = maxCounters;
@@ -914,7 +938,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
List<Card> validCards = CardLists.getValidCards(player.getCardsIn(cost.zone), type.split(";"), player, source); List<Card> validCards = CardLists.getValidCards(player.getCardsIn(cost.zone), type.split(";"), player, source);
if (cost.zone.equals(ZoneType.Battlefield)) { if (cost.zone.equals(ZoneType.Battlefield)) {
final InputSelectCardToRemoveCounter inp = new InputSelectCardToRemoveCounter(cntRemoved, cost.counter, validCards); final InputSelectCardToRemoveCounter inp = new InputSelectCardToRemoveCounter(controller, cntRemoved, cost.counter, validCards);
inp.setMessage("Remove %d " + cost.counter.getName() + " counters from " + cost.getDescriptiveType()); inp.setMessage("Remove %d " + cost.counter.getName() + " counters from " + cost.getDescriptiveType());
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
inp.showAndWait(); inp.showAndWait();
@@ -936,12 +960,13 @@ public class HumanCostDecision extends CostDecisionMakerBase {
} }
// Rift Elemental only - always removes 1 counter, so there will be no code for N counters. // Rift Elemental only - always removes 1 counter, so there will be no code for N counters.
List<Card> suspended = new ArrayList<Card>(); List<CardView> suspended = Lists.newArrayList();
for(Card crd : validCards) for (final Card crd : validCards)
if(crd.getCounters( cost.counter) > 0 ) if (crd.getCounters( cost.counter) > 0)
suspended.add(crd); suspended.add(controller.getCardView(crd));
final Card card = SGuiChoose.oneOrNone("Remove counter(s) from a card in " + cost.zone, suspended); final CardView view = SGuiChoose.oneOrNone(getGui(), "Remove counter(s) from a card in " + cost.zone, suspended);
final Card card = controller.getCard(view);
return null == card ? null : PaymentDecision.card(card, c); return null == card ? null : PaymentDecision.card(card, c);
} }
@@ -982,7 +1007,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (list.size() < c) { if (list.size() < c) {
return null; return null;
} }
InputSelectCardsFromList inp = new InputSelectCardsFromList(c, c, list); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, c, c, list);
inp.setMessage("Select a " + cost.getDescriptiveType() + " to sacrifice (%d left)"); inp.setMessage("Select a " + cost.getDescriptiveType() + " to sacrifice (%d left)");
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
inp.showAndWait(); inp.showAndWait();
@@ -1050,7 +1075,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (c == 0) return PaymentDecision.number(0); if (c == 0) return PaymentDecision.number(0);
List<Card> tapped = new ArrayList<Card>(); List<Card> tapped = new ArrayList<Card>();
while (c > 0) { while (c > 0) {
InputSelectCardsFromList inp = new InputSelectCardsFromList(1, 1, typeList); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, 1, 1, typeList);
inp.setMessage("Select one of the cards to tap. Already chosen: " + tapped); inp.setMessage("Select one of the cards to tap. Already chosen: " + tapped);
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
inp.showAndWait(); inp.showAndWait();
@@ -1072,7 +1097,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
if (totalPower) { if (totalPower) {
int i = Integer.parseInt(totalP); int i = Integer.parseInt(totalP);
InputSelectCardsFromList inp = new InputSelectCardsFromList(0, typeList.size(), typeList); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, 0, typeList.size(), typeList);
inp.setMessage("Select a card to tap."); inp.setMessage("Select a card to tap.");
inp.setUnselectAllowed(true); inp.setUnselectAllowed(true);
inp.setCancelAllowed(true); inp.setCancelAllowed(true);
@@ -1085,7 +1110,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
} }
} }
InputSelectCardsFromList inp = new InputSelectCardsFromList(c, c, typeList); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, c, c, typeList);
inp.setMessage("Select a " + cost.getDescriptiveType() + " to tap (%d left)"); inp.setMessage("Select a " + cost.getDescriptiveType() + " to tap (%d left)");
inp.showAndWait(); inp.showAndWait();
if ( inp.hasCancelled() ) if ( inp.hasCancelled() )
@@ -1113,7 +1138,7 @@ public class HumanCostDecision extends CostDecisionMakerBase {
c = AbilityUtils.calculateAmount(source, amount, ability); c = AbilityUtils.calculateAmount(source, amount, ability);
} }
} }
InputSelectCardsFromList inp = new InputSelectCardsFromList(c, c, typeList); InputSelectCardsFromList inp = new InputSelectCardsFromList(controller, c, c, typeList);
inp.setMessage("Select a " + cost.getDescriptiveType() + " to untap (%d left)"); inp.setMessage("Select a " + cost.getDescriptiveType() + " to untap (%d left)");
inp.showAndWait(); inp.showAndWait();
if( inp.hasCancelled() || inp.getSelected().size() != c ) if( inp.hasCancelled() || inp.getSelected().size() != c )

Some files were not shown because too many files have changed in this diff Show More