Huge cleanup of gui and desktop code

- Remove lots of unused classes and methods
- Remove code related to transitioning deck format
- Refactor some interface structures
- General cleanup (imports, indentation etc.) thanks to Eclipse
- Some very minor bugfixes
This commit is contained in:
elcnesh
2015-05-01 19:27:48 +00:00
parent 9f499117dc
commit bfdcaa6a1a
258 changed files with 7349 additions and 19480 deletions

28
.gitattributes vendored
View File

@@ -786,18 +786,11 @@ forge-gui-desktop/src/main/config/forge.sh -text
forge-gui-desktop/src/main/config/forge_checks.xml -text
forge-gui-desktop/src/main/config/support/dmg-license.py -text
forge-gui-desktop/src/main/config/support/template.applescript -text
forge-gui-desktop/src/main/html/connectionTest.html -text
forge-gui-desktop/src/main/html/css/core.css -text
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/observable.js -text
forge-gui-desktop/src/main/html/js/socket.js -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/ImageLoader.java -text
forge-gui-desktop/src/main/java/forge/Singletons.java -text
forge-gui-desktop/src/main/java/forge/control/FControl.java -text
forge-gui-desktop/src/main/java/forge/control/GuiTimer.java -text
forge-gui-desktop/src/main/java/forge/control/KeyboardShortcuts.java -text
forge-gui-desktop/src/main/java/forge/control/RestartUtil.java -text
forge-gui-desktop/src/main/java/forge/control/package-info.java -text
@@ -818,7 +811,6 @@ forge-gui-desktop/src/main/java/forge/gui/CardListViewer.java -text
forge-gui-desktop/src/main/java/forge/gui/CardPicturePanel.java -text
forge-gui-desktop/src/main/java/forge/gui/DualListBox.java -text
forge-gui-desktop/src/main/java/forge/gui/FNetOverlay.java -text
forge-gui-desktop/src/main/java/forge/gui/ForgeAction.java -text
forge-gui-desktop/src/main/java/forge/gui/GuiChoose.java -text
forge-gui-desktop/src/main/java/forge/gui/GuiDialog.java -text
forge-gui-desktop/src/main/java/forge/gui/GuiProgressBarWindow.java -text
@@ -838,7 +830,6 @@ forge-gui-desktop/src/main/java/forge/gui/framework/DragTab.java -text
forge-gui-desktop/src/main/java/forge/gui/framework/EDocID.java -text
forge-gui-desktop/src/main/java/forge/gui/framework/FScreen.java -text
forge-gui-desktop/src/main/java/forge/gui/framework/ICDoc.java -text
forge-gui-desktop/src/main/java/forge/gui/framework/IDocIdList.java -text
forge-gui-desktop/src/main/java/forge/gui/framework/ILocalRepaint.java -text
forge-gui-desktop/src/main/java/forge/gui/framework/IVDoc.java -text
forge-gui-desktop/src/main/java/forge/gui/framework/IVTopLevelUI.java -text
@@ -874,7 +865,6 @@ forge-gui-desktop/src/main/java/forge/itemmanager/filters/DeckFormatFilter.java
forge-gui-desktop/src/main/java/forge/itemmanager/filters/DeckQuestWorldFilter.java -text
forge-gui-desktop/src/main/java/forge/itemmanager/filters/DeckSearchFilter.java -text
forge-gui-desktop/src/main/java/forge/itemmanager/filters/DeckSetFilter.java -text
forge-gui-desktop/src/main/java/forge/itemmanager/filters/DeckStatTypeFilter.java -text
forge-gui-desktop/src/main/java/forge/itemmanager/filters/FormatFilter.java -text
forge-gui-desktop/src/main/java/forge/itemmanager/filters/ItemFilter.java -text
forge-gui-desktop/src/main/java/forge/itemmanager/filters/ListLabelFilter.java -text
@@ -938,7 +928,6 @@ forge-gui-desktop/src/main/java/forge/screens/deckeditor/views/VStatistics.java
forge-gui-desktop/src/main/java/forge/screens/home/CHomeUI.java -text
forge-gui-desktop/src/main/java/forge/screens/home/CLobby.java -text
forge-gui-desktop/src/main/java/forge/screens/home/EMenuGroup.java -text
forge-gui-desktop/src/main/java/forge/screens/home/EMenuItem.java -text
forge-gui-desktop/src/main/java/forge/screens/home/IVSubmenu.java -text
forge-gui-desktop/src/main/java/forge/screens/home/LblGroup.java -text
forge-gui-desktop/src/main/java/forge/screens/home/LblHeader.java -text
@@ -973,7 +962,6 @@ forge-gui-desktop/src/main/java/forge/screens/home/quest/DialogChooseSets.java -
forge-gui-desktop/src/main/java/forge/screens/home/quest/PnlDraftEvent.java -text
forge-gui-desktop/src/main/java/forge/screens/home/quest/PnlEvent.java -text
forge-gui-desktop/src/main/java/forge/screens/home/quest/QuestFileLister.java -text
forge-gui-desktop/src/main/java/forge/screens/home/quest/QuestPreferencesHandler.java -text
forge-gui-desktop/src/main/java/forge/screens/home/quest/VSubmenuChallenges.java -text
forge-gui-desktop/src/main/java/forge/screens/home/quest/VSubmenuDuels.java -text
forge-gui-desktop/src/main/java/forge/screens/home/quest/VSubmenuQuestData.java -text
@@ -1104,13 +1092,11 @@ forge-gui-desktop/src/main/java/forge/toolbox/ToolTipListener.java -text
forge-gui-desktop/src/main/java/forge/toolbox/imaging/FImagePanel.java -text
forge-gui-desktop/src/main/java/forge/toolbox/imaging/FImageUtil.java -text
forge-gui-desktop/src/main/java/forge/toolbox/package-info.java -text
forge-gui-desktop/src/main/java/forge/toolbox/special/CardViewer.java -text
forge-gui-desktop/src/main/java/forge/toolbox/special/CardZoomer.java -text
forge-gui-desktop/src/main/java/forge/toolbox/special/PhaseIndicator.java -text
forge-gui-desktop/src/main/java/forge/toolbox/special/PhaseLabel.java -text
forge-gui-desktop/src/main/java/forge/toolbox/special/PlayerDetailsPanel.java -text
forge-gui-desktop/src/main/java/forge/toolbox/special/package-info.java -text
forge-gui-desktop/src/main/java/forge/util/AwtUtil.java -text
forge-gui-desktop/src/main/java/forge/view/FDialog.java -text
forge-gui-desktop/src/main/java/forge/view/FFrame.java -text
forge-gui-desktop/src/main/java/forge/view/FNavigationBar.java -text
@@ -1128,7 +1114,6 @@ forge-gui-desktop/src/main/java/forge/view/arcane/FloatingCardArea.java -text
forge-gui-desktop/src/main/java/forge/view/arcane/HandArea.java -text
forge-gui-desktop/src/main/java/forge/view/arcane/PlayArea.java -text
forge-gui-desktop/src/main/java/forge/view/arcane/ScaledImagePanel.java -text
forge-gui-desktop/src/main/java/forge/view/arcane/ViewPanel.java -text
forge-gui-desktop/src/main/java/forge/view/arcane/package-info.java -text
forge-gui-desktop/src/main/java/forge/view/arcane/util/Animation.java -text
forge-gui-desktop/src/main/java/forge/view/arcane/util/CardPanelMouseAdapter.java -text
@@ -1136,7 +1121,6 @@ forge-gui-desktop/src/main/java/forge/view/arcane/util/CardPanelMouseListener.ja
forge-gui-desktop/src/main/java/forge/view/arcane/util/OutlinedLabel.java -text
forge-gui-desktop/src/main/java/forge/view/arcane/util/package-info.java -text
forge-gui-desktop/src/main/java/forge/view/package-info.java -text
forge-gui-desktop/src/site/apt/index.apt -text
forge-gui-desktop/src/test/java/forge/BoosterDraft1Test.java -text
forge-gui-desktop/src/test/java/forge/BoosterDraftTest.java -text
forge-gui-desktop/src/test/java/forge/GuiDownloadPicturesLQTest.java -text
@@ -1228,7 +1212,6 @@ forge-gui-mobile/src/forge/animation/ForgeAnimation.java -text
forge-gui-mobile/src/forge/animation/ForgeTransition.java -text
forge-gui-mobile/src/forge/animation/GifAnimation.java -text
forge-gui-mobile/src/forge/animation/GifDecoder.java -text
forge-gui-mobile/src/forge/animation/GuiTimer.java -text
forge-gui-mobile/src/forge/assets/AssetsDownloader.java -text
forge-gui-mobile/src/forge/assets/BitmapFontWriter.java -text
forge-gui-mobile/src/forge/assets/FBufferedImage.java -text
@@ -17609,7 +17592,6 @@ forge-gui/src/main/java/forge/deck/DeckgenUtil.java -text
forge-gui/src/main/java/forge/deck/NetDeckCategory.java -text
forge-gui/src/main/java/forge/deck/RandomDeckGenerator.java -text
forge-gui/src/main/java/forge/deck/io/DeckPreferences.java -text
forge-gui/src/main/java/forge/deck/io/OldDeckParser.java -text
forge-gui/src/main/java/forge/download/GuiDownloadPicturesLQ.java -text
forge-gui/src/main/java/forge/download/GuiDownloadPrices.java -text
forge-gui/src/main/java/forge/download/GuiDownloadQuestImages.java -text
@@ -17631,17 +17613,17 @@ forge-gui/src/main/java/forge/gauntlet/GauntletWinLoseController.java -text
forge-gui/src/main/java/forge/interfaces/IButton.java -text
forge-gui/src/main/java/forge/interfaces/ICheckBox.java -text
forge-gui/src/main/java/forge/interfaces/IComboBox.java -text
forge-gui/src/main/java/forge/interfaces/IComponent.java -text
forge-gui/src/main/java/forge/interfaces/IDevModeCheats.java -text
forge-gui/src/main/java/forge/interfaces/IDeviceAdapter.java -text
forge-gui/src/main/java/forge/interfaces/IGameController.java -text
forge-gui/src/main/java/forge/interfaces/IGuiBase.java -text
forge-gui/src/main/java/forge/interfaces/IGuiGame.java -text
forge-gui/src/main/java/forge/interfaces/IGuiTimer.java -text
forge-gui/src/main/java/forge/interfaces/ILobby.java -text
forge-gui/src/main/java/forge/interfaces/ILobbyListener.java -text
forge-gui/src/main/java/forge/interfaces/IMayViewCards.java -text
forge-gui/src/main/java/forge/interfaces/IPlayerChangeListener.java -text
forge-gui/src/main/java/forge/interfaces/IProgressBar.java -text
forge-gui/src/main/java/forge/interfaces/ITextComponent.java -text
forge-gui/src/main/java/forge/interfaces/ITextField.java -text
forge-gui/src/main/java/forge/interfaces/IUpdateable.java -text
forge-gui/src/main/java/forge/interfaces/IWinLoseView.java -text
@@ -17682,8 +17664,6 @@ forge-gui/src/main/java/forge/match/HostedMatch.java -text
forge-gui/src/main/java/forge/match/LobbySlot.java -text
forge-gui/src/main/java/forge/match/LobbySlotType.java -text
forge-gui/src/main/java/forge/match/LocalLobby.java -text
forge-gui/src/main/java/forge/match/MatchButtonType.java -text
forge-gui/src/main/java/forge/match/MatchConstants.java -text
forge-gui/src/main/java/forge/match/NextGameDecision.java -text
forge-gui/src/main/java/forge/match/input/Input.java -text
forge-gui/src/main/java/forge/match/input/InputAttack.java -text
@@ -17712,10 +17692,8 @@ forge-gui/src/main/java/forge/model/CardBlock.java -text
forge-gui/src/main/java/forge/model/CardCollections.java -text
forge-gui/src/main/java/forge/model/FModel.java svneol=native#text/plain
forge-gui/src/main/java/forge/model/MetaSet.java -text
forge-gui/src/main/java/forge/model/MultipleForgeJarsFoundError.java -text
forge-gui/src/main/java/forge/model/UnOpenedMeta.java -text
forge-gui/src/main/java/forge/model/package-info.java svneol=native#text/plain
forge-gui/src/main/java/forge/net/GameProtocol.java -text
forge-gui/src/main/java/forge/net/GameProtocolHandler.java -text
forge-gui/src/main/java/forge/net/GameProtocolSender.java -text
forge-gui/src/main/java/forge/net/IRemote.java -text
@@ -17769,8 +17747,6 @@ 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/properties/ForgeConstants.java -text
forge-gui/src/main/java/forge/properties/ForgePreferences.java svneol=native#text/plain
forge-gui/src/main/java/forge/properties/Preferences.java svneol=native#text/plain
forge-gui/src/main/java/forge/properties/SavePreferencesListener.java svneol=native#text/plain
forge-gui/src/main/java/forge/properties/package-info.java svneol=native#text/plain
forge-gui/src/main/java/forge/quest/BoosterUtils.java svneol=native#text/plain
forge-gui/src/main/java/forge/quest/IQuestRewardCard.java -text

View File

@@ -17,24 +17,20 @@
*/
package forge.util.storage;
import com.google.common.base.Predicate;
import forge.util.IHasName;
import java.util.Collection;
/**
* TODO: Write javadoc for this type.
*
* @param <T> the generic type
*/
import com.google.common.base.Predicate;
import forge.util.IHasName;
public interface IStorage<T> extends Iterable<T>, IHasName {
T get(final String name);
T find(final Predicate<T> condition);
T get(String name);
T find(Predicate<T> condition);
Collection<String> getItemNames();
boolean contains(final String name);
boolean contains(String name);
int size();
void add(final T deck);
void delete(final String deckName);
void add(T item);
void delete(String deckName);
IStorage<IStorage<T>> getFolders();
IStorage<T> tryGetFolder(String path);
IStorage<T> getFolderOrCreate(String path);

View File

@@ -1,100 +0,0 @@
<html>
<head>
<title>Tail-based by Web Sockets</title>
<link href="css/core.css" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/observable.js"></script>
<script type="text/javascript" src="js/socket.js"></script>
<script type='text/javascript' src="js/main.js"></script>
</head>
<body>
<div class="wrap">
<div class="title">
<span>Your server: <b>ws://</b></span>
<input id="ws_uri" type="text" value="localhost:81/" name="uri"/>
<button id="connect" name="connect" class="cn">Connect</button>
<button id="disconn" name="disconn" class="dc" disabled="disabled">Disconnect</button>
</div>
<ul class="messages" id='messages'></ul>
<div class="packets" id='input'>
<span>Raw text to send:</span>
<input type="text" name="packet" value="" />
<button id="send" class="send">Send</button>
</div>
</div>
<script type="text/javascript">
if (!window.WebSocket)
alert("WebSocket not supported by this browser");
var server = Socket();
var listener = {
onOpen : function() {
$('#input').slideDown();
},
onMessage : function(m) {
if (m.data) {
addLi("incoming", m.data);
}
},
onClose : function(m) {
addLi("error", "Connection was closed (" + m.code + "): " + m.reason);
onDisconnectClicked();
$('#input').fadeOut();
}
};
server.addObserver(listener);
function addLi(className, text) {
var spanText = document.createElement('li');
spanText.className = className;
spanText.innerHTML = text;
var messageBox = $('#messages')[0];
messageBox.appendChild(spanText);
messageBox.scrollTop = messageBox.scrollHeight - messageBox.clientHeight;
}
function onConnectClicked() {
var uri = $("#ws_uri").val()
addLi("connecting", "Connecting to ws://" + uri + " ..." )
server.connect(uri);
$('#connect').attr("disabled", "disabled")
$('#disconn').removeAttr("disabled")
}
function onDisconnectClicked() {
server.close();
$('#disconn').attr("disabled", "disabled")
$('#connect').removeAttr("disabled")
}
function onSendClicked() {
var toSend = $("#input input").val();
$("#input input").val("");
addLi("outcoming", toSend);
server.send(toSend)
}
function onInputKey(event) {
if( event.keyCode == 13 )
onSendClicked();
}
function onReady() {
$('#connect').on("click", onConnectClicked);
$('#disconn').on("click", onDisconnectClicked);
$('#send').on("click", onSendClicked);
$("#input input").on("keypress", onInputKey);
}
$(onReady)
</script>
</body>
</html>

View File

@@ -1,23 +0,0 @@
ul, ol { margin: 0; }
div { border: 0px solid black; }
div.wrap { width: 640px; margin: 100px auto;}
.title { height: 24px; background-color: #ddd; padding: 4px; border: 1px solid black; border-bottom: 0px }
.title input {width: 300px; }
.title span { display: inline-block; width: 120px; text-align: right; }
.messages { height: 30ex; overflow: auto; background-color: #fff; padding: 4px; border: 1px solid black; list-style: none; }
.messages .incoming { color: #006; }
.messages .incoming:before { content: "<< "}
.messages .outcoming { color: #060; }
.messages .outcoming:before { content: ">> "}
.messages .error { color: #600; }
.messages li:nth-child(2n) { background-color: #f7f7f7; }
.packets { padding: 4px; background-color: #ddd; border: 1px solid black; border-top: 0px; display: none; }
.packets span { display: inline-block; width: 120px; text-align: right; }
.packets input {width: 400px; }
.packets button { width: 100px; }
span.alert { font-style: italic; }

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -1,23 +0,0 @@
var Observable = function(eventNames) {
var _t = {};
var observers = {};
_t.addObserver = function(obj) {
for(var i = 0; i < eventNames.length; i++) {
var evName = eventNames[i]
var method = obj["on" + evName];
if( typeof(method) === 'function') {
var handlers = observers[evName]
if( 'undefined' === typeof(handler))
handlers = observers[evName] = [];
handlers.push(obj);
}
}
}
_t.fireEvent = function() { // usually invoked as .apply(EventName, args)
var q = observers[this]
if ( q ) for( var i = 0; i < q.length; i++ ) q[i]['on'+ this].apply(q[i], arguments);
}
return _t;
}

View File

@@ -1,27 +0,0 @@
// There should be some kind of fallback to Flash-powered sockets (IE 9-, Opera with sockets switched off)
var Socket = function() {
var _t = Observable(["Open", "Message", "Close", "Error"]);
function onOpen() { _t.fireEvent.apply("Open", arguments); }
function onClose() { _t.fireEvent.apply("Close", arguments); }
function onError() { _t.fireEvent.apply("Error", arguments); }
function onMessage() { _t.fireEvent.apply("Message", arguments); }
var ws;
_t.connect = function(location) {
ws = new WebSocket("ws://" + location);
ws.onopen = onOpen;
ws.onmessage = onMessage;
ws.onclose = onClose;
ws.onerror = onError;
}
// _t.getWs = function() { return ws; }
_t.isOpen = function() { return ws && ws.readyState == ws.OPEN; }
_t.close = function() { ws && ws.close(); }
_t.send = function(text) { text != null && text.length > 0 && ws && ws.send(text); };
return _t;
};

View File

@@ -23,7 +23,6 @@ import com.google.common.base.Function;
import forge.assets.FSkinProp;
import forge.assets.ISkinImage;
import forge.control.GuiTimer;
import forge.download.GuiDownloadService;
import forge.download.GuiDownloader;
import forge.error.BugReportDialog;
@@ -33,7 +32,6 @@ import forge.gui.GuiChoose;
import forge.gui.framework.FScreen;
import forge.interfaces.IGuiBase;
import forge.interfaces.IGuiGame;
import forge.interfaces.IGuiTimer;
import forge.item.PaperCard;
import forge.match.HostedMatch;
import forge.model.FModel;
@@ -70,7 +68,7 @@ public class GuiDesktop implements IGuiBase {
}
@Override
public void invokeInEdtLater(Runnable proc) {
public void invokeInEdtLater(final Runnable proc) {
SwingUtilities.invokeLater(proc);
}
@@ -99,28 +97,23 @@ public class GuiDesktop implements IGuiBase {
}
@Override
public IGuiTimer createGuiTimer(Runnable proc, int interval) {
return new GuiTimer(proc, interval);
}
@Override
public ISkinImage getSkinIcon(FSkinProp skinProp) {
public ISkinImage getSkinIcon(final FSkinProp skinProp) {
if (skinProp == null) { return null; }
return FSkin.getIcon(skinProp);
}
@Override
public ISkinImage getUnskinnedIcon(String path) {
public ISkinImage getUnskinnedIcon(final String path) {
return new FSkin.UnskinnedIcon(path);
}
@Override
public ISkinImage getCardArt(PaperCard card) {
public ISkinImage getCardArt(final PaperCard card) {
return null; //TODO
}
@Override
public ISkinImage createLayeredImage(FSkinProp background, String overlayFilename, float opacity) {
public ISkinImage createLayeredImage(final FSkinProp background, final String overlayFilename, final float opacity) {
final BufferedImage image = new BufferedImage(background.getWidth(), background.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = image.createGraphics();
final FSkin.SkinImage backgroundImage = FSkin.getImage(background);
@@ -134,17 +127,17 @@ public class GuiDesktop implements IGuiBase {
}
@Override
public void showImageDialog(ISkinImage image, String message, String title) {
public void showImageDialog(final ISkinImage image, final String message, final String title) {
FOptionPane.showMessageDialog(message, title, (SkinImage)image);
}
@Override
public int showOptionDialog(String message, String title, FSkinProp icon, String[] options, int defaultOption) {
public int showOptionDialog(final String message, final String title, final FSkinProp icon, final String[] options, final int defaultOption) {
return FOptionPane.showOptionDialog(message, title, icon == null ? null : FSkin.getImage(icon), options, defaultOption);
}
@Override
public String showInputDialog(String message, String title, FSkinProp icon, String initialInput, String[] inputOptions) {
public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final String[] inputOptions) {
return FOptionPane.showInputDialog(message, title, icon == null ? null : FSkin.getImage(icon), initialInput, inputOptions);
}
@@ -192,7 +185,7 @@ public class GuiDesktop implements IGuiBase {
}
@Override
public String showFileDialog(String title, String defaultDir) {
public String showFileDialog(final String title, final String defaultDir) {
final JFileChooser fc = new JFileChooser(defaultDir);
final int rc = fc.showDialog(null, title);
if (rc != JFileChooser.APPROVE_OPTION) {
@@ -202,46 +195,46 @@ public class GuiDesktop implements IGuiBase {
}
@Override
public void showBugReportDialog(String title, String text, boolean showExitAppBtn) {
public void showBugReportDialog(final String title, final String text, final boolean showExitAppBtn) {
BugReportDialog.show(title, text, showExitAppBtn);
}
@Override
public File getSaveFile(File defaultFile) {
JFileChooser fc = new JFileChooser();
public File getSaveFile(final File defaultFile) {
final JFileChooser fc = new JFileChooser();
fc.setSelectedFile(defaultFile);
fc.showSaveDialog(null);
return fc.getSelectedFile();
}
@Override
public void download(GuiDownloadService service, Callback<Boolean> callback) {
new GuiDownloader(service, callback);
public void download(final GuiDownloadService service, final Callback<Boolean> callback) {
new GuiDownloader(service, callback).show();
}
@Override
public void copyToClipboard(String text) {
StringSelection ss = new StringSelection(text);
public void copyToClipboard(final String text) {
final StringSelection ss = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}
@Override
public void browseToUrl(String url) throws IOException, URISyntaxException {
public void browseToUrl(final String url) throws IOException, URISyntaxException {
Desktop.getDesktop().browse(new URI(url));
}
@Override
public IAudioClip createAudioClip(String filename) {
public IAudioClip createAudioClip(final String filename) {
return AudioClip.fileExists(filename) ? new AudioClip(filename) : null;
}
@Override
public IAudioMusic createAudioMusic(String filename) {
public IAudioMusic createAudioMusic(final String filename) {
return new AudioMusic(filename);
}
@Override
public void startAltSoundSystem(String filename, boolean isSynchronized) {
public void startAltSoundSystem(final String filename, final boolean isSynchronized) {
new AltSoundSystem(filename, isSynchronized).start();
}
@@ -263,6 +256,7 @@ public class GuiDesktop implements IGuiBase {
Singletons.getView().getFrame().validate();
}
@Override
public IGuiGame getNewGuiGame() {
return new CMatchUI();
}

View File

@@ -43,7 +43,6 @@ import forge.ImageCache;
import forge.LobbyPlayer;
import forge.Singletons;
import forge.assets.FSkinProp;
import forge.gui.GuiDialog;
import forge.gui.SOverlayUtils;
import forge.gui.framework.FScreen;
import forge.gui.framework.InvalidLayoutFileException;
@@ -62,6 +61,7 @@ import forge.quest.io.QuestDataIO;
import forge.screens.deckeditor.CDeckEditorUI;
import forge.toolbox.FOptionPane;
import forge.toolbox.FSkin;
import forge.util.gui.SOptionPane;
import forge.view.FFrame;
import forge.view.FView;
@@ -81,7 +81,7 @@ public enum FControl implements KeyEventDispatcher {
private FScreen currentScreen;
private boolean altKeyLastDown;
private CloseAction closeAction;
private List<HostedMatch> currentMatches = Lists.newArrayList();
private final List<HostedMatch> currentMatches = Lists.newArrayList();
public static enum CloseAction {
NONE,
@@ -126,8 +126,8 @@ public enum FControl implements KeyEventDispatcher {
public void windowClosing(final WindowEvent e) {
switch (closeAction) {
case NONE: //prompt user for close action if not previously specified
String[] options = {"Close Screen", "Exit Forge", "Cancel"};
int reply = FOptionPane.showOptionDialog(
final String[] options = {"Close Screen", "Exit Forge", "Cancel"};
final int reply = FOptionPane.showOptionDialog(
"Forge now supports navigation tabs which allow closing and switching between different screens with ease. "
+ "As a result, you no longer need to use the X button in the upper right to close the current screen and go back."
+ "\n\n"
@@ -300,8 +300,8 @@ public enum FControl implements KeyEventDispatcher {
screen.getController().register();
try {
SLayoutIO.loadLayout(null);
} catch (InvalidLayoutFileException ex) {
GuiDialog.message("Your " + screen.getTabCaption() + " layout file could not be read. It will be deleted after you press OK.\nThe game will proceed with default layout.");
} catch (final InvalidLayoutFileException ex) {
SOptionPane.showMessageDialog(String.format("Your %s layout file could not be read. It will be deleted after you press OK.\nThe game will proceed with default layout.", screen.getTabCaption()), "Warning!");
if (screen.deleteLayoutFile()) {
SLayoutIO.loadLayout(null); //try again
}
@@ -325,7 +325,7 @@ public enum FControl implements KeyEventDispatcher {
return FModel.getPreferences().getPrefBoolean(FPref.UI_MATCH_IMAGE_VISIBLE);
}
public boolean ensureScreenActive(FScreen screen) {
public boolean ensureScreenActive(final FScreen screen) {
if (currentScreen == screen) { return true; }
return setCurrentScreen(screen);
@@ -360,7 +360,7 @@ public enum FControl implements KeyEventDispatcher {
* @see java.awt.KeyEventDispatcher#dispatchKeyEvent(java.awt.event.KeyEvent)
*/
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
public boolean dispatchKeyEvent(final KeyEvent e) {
// Show Forge menu if Alt key pressed without modifiers and released without pressing any other keys in between
if (e.getKeyCode() == KeyEvent.VK_ALT) {
if (e.getID() == KeyEvent.KEY_RELEASED) {

View File

@@ -1,25 +0,0 @@
package forge.control;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import forge.interfaces.IGuiTimer;
@SuppressWarnings("serial")
public class GuiTimer extends Timer implements IGuiTimer {
public GuiTimer(final Runnable proc0, int interval0) {
super(interval0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
proc0.run();
}
});
}
@Override
public void setInterval(int interval0) {
setDelay(interval0);
}
}

View File

@@ -1,21 +1,22 @@
package forge.deckchooser;
import forge.deck.DeckType;
import forge.gui.MouseUtil;
import forge.toolbox.FComboBoxWrapper;
import forge.toolbox.FSkin;
import forge.toolbox.FComboBox.TextAlignment;
import javax.swing.*;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import com.google.common.collect.Lists;
import forge.deck.DeckType;
import forge.gui.MouseUtil;
import forge.toolbox.FComboBox.TextAlignment;
import forge.toolbox.FComboBoxWrapper;
import forge.toolbox.FSkin;
public class DecksComboBox extends FComboBoxWrapper<DeckType> {
private List<IDecksComboBoxListener> _listeners = new ArrayList<>();
private final List<IDecksComboBoxListener> _listeners = Lists.newArrayList();
private DeckType selectedDeckType = null;
public DecksComboBox() {
@@ -24,19 +25,18 @@ public class DecksComboBox extends FComboBoxWrapper<DeckType> {
addActionListener(getDeckTypeComboListener());
}
public void refresh(DeckType deckType) {
public void refresh(final DeckType deckType) {
setModel(new DefaultComboBoxModel<DeckType>(DeckType.values()));
setSelectedItem(deckType);
}
private ActionListener getDeckTypeComboListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object selectedItem = getSelectedItem();
@Override public void actionPerformed(final ActionEvent e) {
final Object selectedItem = getSelectedItem();
if (selectedItem instanceof DeckType) {
MouseUtil.setCursor(Cursor.WAIT_CURSOR);
DeckType newDeckType = (DeckType)selectedItem;
final DeckType newDeckType = (DeckType)selectedItem;
if (newDeckType != selectedDeckType) {
selectedDeckType = newDeckType;
notifyDeckTypeSelected(newDeckType);
@@ -47,17 +47,13 @@ public class DecksComboBox extends FComboBoxWrapper<DeckType> {
};
}
public synchronized void addListener(IDecksComboBoxListener obj) {
public synchronized void addListener(final IDecksComboBoxListener obj) {
_listeners.add(obj);
}
public synchronized void removeListener(IDecksComboBoxListener obj) {
_listeners.remove(obj);
}
private synchronized void notifyDeckTypeSelected(DeckType deckType) {
private synchronized void notifyDeckTypeSelected(final DeckType deckType) {
if (deckType != null) {
for (IDecksComboBoxListener listener : _listeners) {
for (final IDecksComboBoxListener listener : _listeners) {
listener.deckTypeSelected(new DecksComboBoxEvent(this, deckType));
}
}
@@ -67,13 +63,13 @@ public class DecksComboBox extends FComboBoxWrapper<DeckType> {
return selectedDeckType;
}
public void setDeckType(DeckType valueOf) {
public void setDeckType(final DeckType valueOf) {
selectedDeckType = valueOf;
setSelectedItem(selectedDeckType);
}
@Override
public void setText(String text0) {
public void setText(final String text0) {
selectedDeckType = null; //ensure selecting current deck type again raises event
super.setText(text0);
}

View File

@@ -17,23 +17,30 @@
*/
package forge.download;
import java.net.Proxy;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.gui.SOverlayUtils;
import forge.toolbox.*;
import forge.util.Callback;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.AbstractButton;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.miginfocom.swing.MigLayout;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.gui.SOverlayUtils;
import forge.toolbox.FButton;
import forge.toolbox.FLabel;
import forge.toolbox.FOverlay;
import forge.toolbox.FPanel;
import forge.toolbox.FProgressBar;
import forge.toolbox.FRadioButton;
import forge.toolbox.FSkin;
import forge.toolbox.FTextField;
import forge.toolbox.JXButtonPanel;
import forge.util.Callback;
@SuppressWarnings("serial")
public class GuiDownloader extends DefaultBoundedRangeModel {
public static final Proxy.Type[] TYPES = Proxy.Type.values();
// Swing components
private final FPanel pnlDialog = new FPanel(new MigLayout("insets 0, gap 0, wrap, ax center, ay center"));
private final FProgressBar progressBar = new FProgressBar();
@@ -42,8 +49,7 @@ public class GuiDownloader extends DefaultBoundedRangeModel {
private final FTextField txtPort = new FTextField.Builder().ghostText("Proxy Port").build();
private final UiCommand cmdClose = new UiCommand() {
@Override
public void run() {
@Override public void run() {
service.setCancel(true);
// Kill overlay
@@ -65,15 +71,15 @@ public class GuiDownloader extends DefaultBoundedRangeModel {
private final GuiDownloadService service;
private final Callback<Boolean> callback;
public GuiDownloader(GuiDownloadService service0) {
public GuiDownloader(final GuiDownloadService service0) {
this(service0, null);
}
public GuiDownloader(GuiDownloadService service0, Callback<Boolean> callback0) {
public GuiDownloader(final GuiDownloadService service0, final Callback<Boolean> callback0) {
service = service0;
callback = callback0;
String radConstraints = "w 100%!, h 30px!, gap 2% 0 0 10px";
JXButtonPanel grpPanel = new JXButtonPanel();
final String radConstraints = "w 100%!, h 30px!, gap 2% 0 0 10px";
final JXButtonPanel grpPanel = new JXButtonPanel();
grpPanel.add(radProxyNone, radConstraints);
grpPanel.add(radProxyHTTP, radConstraints);
grpPanel.add(radProxySocks, radConstraints);
@@ -98,7 +104,9 @@ public class GuiDownloader extends DefaultBoundedRangeModel {
pnlDialog.add(progressBar, "w 95%!, h 40px!, gap 2% 0 20px 0");
pnlDialog.add(btnStart, "w 200px!, h 40px!, gap 0 0 20px 0, ax center");
pnlDialog.add(btnClose, "w 20px!, h 20px!, pos 370px 10px");
}
public void show() {
final JPanel pnl = FOverlay.SINGLETON_INSTANCE.getPanel();
pnl.removeAll();
pnl.setLayout(new MigLayout("insets 0, gap 0, wrap, ax center, ay center"));
@@ -106,8 +114,7 @@ public class GuiDownloader extends DefaultBoundedRangeModel {
SOverlayUtils.showOverlay();
service.initialize(txtAddress, txtPort, progressBar, btnStart, cmdClose, null, new Runnable() {
@Override
public void run() {
@Override public void run() {
fireStateChanged();
}
});

View File

@@ -113,7 +113,7 @@ public class CardListViewer extends FDialog {
this.addWindowFocusListener(new CardListFocuser());
FButton btnOK = new FButton("OK");
final FButton btnOK = new FButton("OK");
btnOK.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {

View File

@@ -83,11 +83,11 @@ public final class CardPicturePanel extends JPanel {
return null;
}
private AutoSizeImageMode getAutoSizeImageMode() {
private static AutoSizeImageMode getAutoSizeImageMode() {
return (isUIScaleLarger() ? AutoSizeImageMode.PANEL : AutoSizeImageMode.SOURCE);
}
private boolean isUIScaleLarger() {
private static boolean isUIScaleLarger() {
return FModel.getPreferences().getPrefBoolean(FPref.UI_SCALE_LARGER);
}

View File

@@ -114,7 +114,7 @@ public enum FNetOverlay {
FScrollPane _operationLogScroller = new FScrollPane(txtLog, false);
_operationLogScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
new SmartScroller(_operationLogScroller);
new SmartScroller(_operationLogScroller).attach();
window.add(_operationLogScroller, "pushx, hmin 24, pushy, growy, growx, gap 2px 2px 2px 0, sx 2");
//txtInput.setBorder(new FSkin.LineSkinBorder(FSkin.getColor(FSkin.Colors.CLR_BORDERS)));

View File

@@ -1,37 +0,0 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.gui;
import javax.swing.*;
import forge.match.MatchConstants;
@SuppressWarnings("serial")
public abstract class ForgeAction extends AbstractAction {
public ForgeAction(MatchConstants property) {
super(property.button);
this.putValue("buttonText", property.button);
this.putValue("menuText", property.menu);
}
public <T extends AbstractButton> T setupButton(final T button) {
button.setAction(this);
button.setText((String) this.getValue(button instanceof JMenuItem ? "menuText" : "buttonText"));
return button;
}
}

View File

@@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
@@ -17,7 +16,6 @@ import javax.swing.event.ListSelectionListener;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import forge.FThreads;
import forge.game.card.Card;
@@ -60,69 +58,15 @@ public class GuiChoose {
return choice.isEmpty() ? null : choice.get(0);
} // getChoiceOptional(String,T...)
// returned Object will never be null
/**
* <p>
* getChoice.
* </p>
*
* @param <T>
* a T object.
* @param message
* a {@link java.lang.String} object.
* @param choices
* a T object.
* @return a T object.
*/
public static <T> T one(final String message, final T[] choices) {
final List<T> choice = GuiChoose.getChoices(message, 1, 1, choices);
assert choice.size() == 1;
return choice.get(0);
}
public static <T> T one(final String message, final Collection<T> choices) {
if (choices == null || choices.isEmpty())
return null;
if( choices.size() == 1)
return Iterables.getFirst(choices, null);
final List<T> choice = GuiChoose.getChoices(message, 1, 1, choices);
assert choice.size() == 1;
return choice.get(0);
}
public static <T> List<T> noneOrMany(final String message, final Collection<T> choices) {
return GuiChoose.getChoices(message, 0, choices.size(), choices, null, null);
}
// Nothing to choose here. Code uses this to just reveal one or more items
public static <T> void reveal(final String message, final T item) {
List<T> items = new ArrayList<T>();
items.add(item);
reveal(message, items);
}
public static <T> void reveal(final String message, final T[] items) {
GuiChoose.getChoices(message, -1, -1, items);
}
public static <T> void reveal(final String message, final Collection<T> items) {
GuiChoose.getChoices(message, -1, -1, items);
}
// Get Integer in range
public static Integer getInteger(final String message) {
return getInteger(message, 0, Integer.MAX_VALUE);
}
public static Integer getInteger(final String message, int min) {
return getInteger(message, min, Integer.MAX_VALUE);
}
public static Integer getInteger(final String message, int min, int max) {
public static Integer getInteger(final String message, final int min, final int max) {
if (max <= min) { return min; } //just return min if max <= min
//force cutting off after 100 numbers at most
if (max == Integer.MAX_VALUE) {
return getInteger(message, min, max, min + 99);
}
int count = max - min + 1;
final int count = max - min + 1;
if (count > 100) {
return getInteger(message, min, max, min + 99);
}
@@ -133,20 +77,20 @@ public class GuiChoose {
}
return GuiChoose.oneOrNone(message, choices);
}
public static Integer getInteger(final String message, int min, int max, int cutoff) {
public static Integer getInteger(final String message, final int min, final int max, final int cutoff) {
if (max <= min || cutoff < min) { return min; } //just return min if max <= min or cutoff < min
if (cutoff >= max) { //fallback to regular integer prompt if cutoff at or after max
return getInteger(message, min, max);
}
List<Object> choices = new ArrayList<Object>();
final List<Object> choices = new ArrayList<Object>();
for (int i = min; i <= cutoff; i++) {
choices.add(Integer.valueOf(i));
}
choices.add("Other...");
Object choice = GuiChoose.oneOrNone(message, choices);
final Object choice = GuiChoose.oneOrNone(message, choices);
if (choice instanceof Integer || choice == null) {
return (Integer)choice;
}
@@ -167,11 +111,11 @@ public class GuiChoose {
prompt += ":";
while (true) {
String str = FOptionPane.showInputDialog(prompt, message);
final String str = FOptionPane.showInputDialog(prompt, message);
if (str == null) { return null; } // that is 'cancel'
if (StringUtils.isNumeric(str)) {
Integer val = Integer.valueOf(str);
final Integer val = Integer.valueOf(str);
if (val >= min && val <= max) {
return val;
}
@@ -202,7 +146,7 @@ public class GuiChoose {
final Callable<List<T>> showChoice = new Callable<List<T>>() {
@Override
public List<T> call() {
ListChooser<T> c = new ListChooser<T>(message, min, max, choices, display);
final ListChooser<T> c = new ListChooser<T>(message, min, max, choices, display);
final JList<T> list = c.getLstChoices();
if (matchUI != null) {
list.addListSelectionListener(new ListSelectionListener() {
@@ -246,11 +190,11 @@ public class GuiChoose {
}
};
FutureTask<List<T>> future = new FutureTask<List<T>>(showChoice);
final FutureTask<List<T>> future = new FutureTask<List<T>>(showChoice);
FThreads.invokeInEdtAndWait(future);
try {
return future.get();
} catch (Exception e) { // should be no exception here
} catch (final Exception e) { // should be no exception here
e.printStackTrace();
}
return null;
@@ -266,18 +210,14 @@ public class GuiChoose {
final List<T> sourceChoices, final List<T> destChoices) {
return order(title, top, remainingObjectsMin, remainingObjectsMax, sourceChoices, destChoices, null, false, null);
}
public static <T> List<T> order(final String title, final String top, final int remainingObjectsMin, final int remainingObjectsMax,
final List<T> sourceChoices, final List<T> destChoices, final CardView referenceCard, final boolean sideboardingMode) {
return order(title, top, remainingObjectsMin, remainingObjectsMax, sourceChoices, destChoices, referenceCard, sideboardingMode, null);
}
public static <T> List<T> order(final String title, final String top, final int remainingObjectsMin, final int remainingObjectsMax,
final List<T> sourceChoices, final List<T> destChoices, final CardView referenceCard, final boolean sideboardingMode, final CMatchUI matchUI) {
// An input box for handling the order of choices.
Callable<List<T>> callable = new Callable<List<T>>() {
final Callable<List<T>> callable = new Callable<List<T>>() {
@Override
public List<T> call() throws Exception {
DualListBox<T> dual = new DualListBox<T>(remainingObjectsMin, remainingObjectsMax, sourceChoices, destChoices, matchUI);
final DualListBox<T> dual = new DualListBox<T>(remainingObjectsMin, remainingObjectsMax, sourceChoices, destChoices, matchUI);
dual.setSecondColumnLabelText(top);
dual.setSideboardMode(sideboardingMode);
@@ -291,7 +231,7 @@ public class GuiChoose {
}
dual.setVisible(true);
List<T> objects = dual.getOrderedList();
final List<T> objects = dual.getOrderedList();
dual.dispose();
if (matchUI != null) {
@@ -301,70 +241,15 @@ public class GuiChoose {
}
};
FutureTask<List<T>> ft = new FutureTask<List<T>>(callable);
final FutureTask<List<T>> ft = new FutureTask<List<T>>(callable);
FThreads.invokeInEdtAndWait(ft);
try {
return ft.get();
} catch (Exception e) { // we have waited enough
} catch (final Exception e) { // we have waited enough
e.printStackTrace();
}
return null;
}
// If comparer is NULL, T has to be comparable. Otherwise you'll get an exception from inside the Arrays.sort() routine
public static <T> T sortedOneOrNone(final String message, final T[] choices, Comparator<T> comparer) {
if ((choices == null) || (choices.length == 0)) {
return null;
}
final List<T> choice = GuiChoose.sortedGetChoices(message, 0, 1, choices, comparer);
return choice.isEmpty() ? null : choice.get(0);
} // getChoiceOptional(String,T...)
// If comparer is NULL, T has to be comparable. Otherwise you'll get an exception from inside the Arrays.sort() routine
public static <T> T sortedOneOrNone(final String message, final List<T> choices, Comparator<T> comparer) {
if ((choices == null) || choices.isEmpty()) {
return null;
}
final List<T> choice = GuiChoose.sortedGetChoices(message, 0, 1, choices, comparer);
return choice.isEmpty() ? null : choice.get(0);
} // getChoiceOptional(String,T...)
// If comparer is NULL, T has to be comparable. Otherwise you'll get an exception from inside the Arrays.sort() routine
public static <T> T sortedOne(final String message, final T[] choices, Comparator<T> comparer) {
final List<T> choice = GuiChoose.sortedGetChoices(message, 1, 1, choices, comparer);
assert choice.size() == 1;
return choice.get(0);
} // getChoice()
// If comparer is NULL, T has to be comparable. Otherwise you'll get an exception from inside the Arrays.sort() routine
public static <T> T sortedOne(final String message, final List<T> choices, Comparator<T> comparer) {
if ((choices == null) || (choices.size() == 0)) {
return null;
}
final List<T> choice = GuiChoose.sortedGetChoices(message, 1, 1, choices, comparer);
assert choice.size() == 1;
return choice.get(0);
}
// If comparer is NULL, T has to be comparable. Otherwise you'll get an exception from inside the Arrays.sort() routine
public static <T> List<T> sortedNoneOrMany(final String message, final List<T> choices, Comparator<T> comparer) {
return GuiChoose.sortedGetChoices(message, 0, choices.size(), choices, comparer);
}
// If comparer is NULL, T has to be comparable. Otherwise you'll get an exception from inside the Arrays.sort() routine
public static <T> List<T> sortedGetChoices(final String message, final int min, final int max, final T[] choices, Comparator<T> comparer) {
// You may create a copy of source array if callers expect the collection to be unchanged
Arrays.sort(choices, comparer);
return getChoices(message, min, max, choices);
}
// If comparer is NULL, T has to be comparable. Otherwise you'll get an exception from inside the Arrays.sort() routine
public static <T> List<T> sortedGetChoices(final String message, final int min, final int max, final List<T> choices, Comparator<T> comparer) {
// You may create a copy of source list if callers expect the collection to be unchanged
Collections.sort(choices, comparer);
return getChoices(message, min, max, choices);
}
}

View File

@@ -1,10 +1,9 @@
package forge.gui;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import javax.swing.UIManager;
import org.apache.commons.lang3.StringUtils;
import forge.FThreads;
@@ -19,63 +18,28 @@ import forge.toolbox.FOptionPane;
public class GuiDialog {
private static final String[] defaultConfirmOptions = { "Yes", "No" };
public static boolean confirm(final CardView c, final String question) {
return confirm(c, question, true, null);
}
public static boolean confirm(final CardView c, final String question, final boolean defaultChoice) {
return confirm(c, question, defaultChoice, null);
}
public static boolean confirm(final CardView c, final String question, String[] options) {
return confirm(c, question, true, options);
}
public static boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final String[] options) {
return confirm(c, question, defaultIsYes, options, null);
}
public static boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final String[] options, final CMatchUI matchUI) {
Callable<Boolean> confirmTask = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
final Callable<Boolean> confirmTask = new Callable<Boolean>() {
@Override public final Boolean call() {
if (matchUI != null && c != null) {
matchUI.setCard(c);
}
final String title = c == null ? "Question" : c + " - Ability";
String questionToUse = StringUtils.isBlank(question) ? "Activate card's ability?" : question;
String[] opts = options == null ? defaultConfirmOptions : options;
int answer = FOptionPane.showOptionDialog(questionToUse, title, FOptionPane.QUESTION_ICON, opts, defaultIsYes ? 0 : 1);
return answer == 0;
final String questionToUse = StringUtils.isBlank(question) ? "Activate card's ability?" : question;
final String[] opts = options == null ? defaultConfirmOptions : options;
final int answer = FOptionPane.showOptionDialog(questionToUse, title, FOptionPane.QUESTION_ICON, opts, defaultIsYes ? 0 : 1);
return Boolean.valueOf(answer == 0);
}};
FutureTask<Boolean> future = new FutureTask<Boolean>(confirmTask);
final FutureTask<Boolean> future = new FutureTask<Boolean>(confirmTask);
FThreads.invokeInEdtAndWait(future);
try {
return future.get().booleanValue();
}
catch (Exception e) { // should be no exception here
} catch (final InterruptedException | ExecutionException e) { // should be no exception here
e.printStackTrace();
}
return false;
}
/**
* <p>
* showInfoDialg.
* </p>
*
* @param message
* a {@link java.lang.String} object.
*/
public static void message(final String message) {
message(message, UIManager.getString("OptionPane.messageDialogTitle"));
}
public static void message(final String message, final String title) {
FThreads.invokeInEdtAndWait(new Runnable() {
@Override
public void run() {
FOptionPane.showMessageDialog(message, title, null);
}
});
}
}

View File

@@ -40,6 +40,10 @@ import javax.swing.KeyStroke;
* @version $Id: GuiUtils.java 24769 2014-02-09 13:56:04Z Hellfish $
*/
public final class GuiUtils {
/**
* Private constructor to prevent instantiation.
*/
private GuiUtils() {
throw new AssertionError();
}
@@ -49,8 +53,7 @@ public final class GuiUtils {
* exceptions found.
*
* @param filename
* String
* @return Font
* the name of the font file.
*/
public static Font newFont(final String filename) {
final File file = new File(filename);
@@ -69,7 +72,7 @@ public final class GuiUtils {
private static final int minItemWidth = 100;
private static final int itemHeight = 25;
public static void setMenuItemSize(JMenuItem item) {
public static void setMenuItemSize(final JMenuItem item) {
item.setPreferredSize(new Dimension(Math.max(item.getPreferredSize().width, minItemWidth), itemHeight));
}
@@ -77,19 +80,19 @@ public final class GuiUtils {
if (label.startsWith("<html>")) { //adjust label if HTML
label = "<html>" + "<div style='height: " + itemHeight + "px; margin-top: 6px;'>" + label.substring(6, label.length() - 7) + "</div></html>";
}
JMenu menu = new JMenu(label);
final JMenu menu = new JMenu(label);
setMenuItemSize(menu);
return menu;
}
public static JMenuItem createMenuItem(String label, KeyStroke accelerator, final Runnable onClick, boolean enabled, boolean bold) {
public static JMenuItem createMenuItem(String label, final KeyStroke accelerator, final Runnable onClick, final boolean enabled, final boolean bold) {
if (label.startsWith("<html>")) { //adjust label if HTML
label = "<html>" + "<div style='height: " + itemHeight + "px; margin-top: 6px;'>" + label.substring(6, label.length() - 7) + "</div></html>";
}
JMenuItem item = new JMenuItem(label);
final JMenuItem item = new JMenuItem(label);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
public void actionPerformed(final ActionEvent arg0) {
if (null != onClick) {
onClick.run();
}
@@ -104,35 +107,35 @@ public final class GuiUtils {
return item;
}
public static void addMenuItem(JPopupMenu parent, String label, KeyStroke accelerator, Runnable onClick) {
public static void addMenuItem(final JPopupMenu parent, final String label, final KeyStroke accelerator, final Runnable onClick) {
parent.add(createMenuItem(label, accelerator, onClick, true, false));
}
public static void addMenuItem(JMenuItem parent, String label, KeyStroke accelerator, Runnable onClick) {
public static void addMenuItem(final JMenuItem parent, final String label, final KeyStroke accelerator, final Runnable onClick) {
parent.add(createMenuItem(label, accelerator, onClick, true, false));
}
public static void addMenuItem(JPopupMenu parent, String label, KeyStroke accelerator, Runnable onClick, boolean enabled) {
public static void addMenuItem(final JPopupMenu parent, final String label, final KeyStroke accelerator, final Runnable onClick, final boolean enabled) {
parent.add(createMenuItem(label, accelerator, onClick, enabled, false));
}
public static void addMenuItem(JMenuItem parent, String label, KeyStroke accelerator, Runnable onClick, boolean enabled) {
public static void addMenuItem(final JMenuItem parent, final String label, final KeyStroke accelerator, final Runnable onClick, final boolean enabled) {
parent.add(createMenuItem(label, accelerator, onClick, enabled, false));
}
public static void addMenuItem(JPopupMenu parent, String label, KeyStroke accelerator, Runnable onClick, boolean enabled, boolean bold) {
public static void addMenuItem(final JPopupMenu parent, final String label, final KeyStroke accelerator, final Runnable onClick, final boolean enabled, final boolean bold) {
parent.add(createMenuItem(label, accelerator, onClick, enabled, bold));
}
public static void addMenuItem(JMenuItem parent, String label, KeyStroke accelerator, Runnable onClick, boolean enabled, boolean bold) {
public static void addMenuItem(final JMenuItem parent, final String label, final KeyStroke accelerator, final Runnable onClick, final boolean enabled, final boolean bold) {
parent.add(createMenuItem(label, accelerator, onClick, enabled, bold));
}
public static void addSeparator(JPopupMenu parent) {
public static void addSeparator(final JPopupMenu parent) {
parent.add(new JSeparator());
}
public static void addSeparator(JMenuItem parent) {
public static void addSeparator(final JMenuItem parent) {
parent.add(new JSeparator());
}
}

View File

@@ -17,25 +17,7 @@
*/
package forge.gui;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.error.BugReporter;
import forge.gui.ImportSourceAnalyzer.OpType;
import forge.properties.ForgeConstants;
import forge.toolbox.*;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
@@ -43,10 +25,53 @@ import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.error.BugReporter;
import forge.gui.ImportSourceAnalyzer.OpType;
import forge.properties.ForgeConstants;
import forge.toolbox.FButton;
import forge.toolbox.FCheckBox;
import forge.toolbox.FComboBoxWrapper;
import forge.toolbox.FLabel;
import forge.toolbox.FOptionPane;
import forge.toolbox.FOverlay;
import forge.toolbox.FPanel;
import forge.toolbox.FScrollPane;
import forge.toolbox.FSkin;
import forge.toolbox.FTextField;
import forge.toolbox.SmartScroller;
/**
* This class implements an overlay-based dialog that imports data from a user-selected directory
* into the correct locations in the user and cache directories. There is a lot of I/O and data
@@ -58,26 +83,32 @@ public class ImportDialog {
private final FLabel _btnChooseDir;
private final FPanel _topPanel;
private final JPanel _selectionPanel;
private final FTextField _txfSrc;
private final String forcedSrcDir;
private final boolean isMigration;
// volatile since it is checked from multiple threads
private volatile boolean _cancel;
@SuppressWarnings("serial")
public ImportDialog(String forcedSrcDir, final Runnable onDialogClose) {
public ImportDialog(final String forcedSrcDir, final Runnable onDialogClose) {
this.forcedSrcDir = forcedSrcDir;
_topPanel = new FPanel(new MigLayout("insets dialog, gap 0, center, wrap, fill"));
_topPanel.setOpaque(false);
_topPanel.setBackgroundTexture(FSkin.getIcon(FSkinProp.BG_TEXTURE));
final boolean isMigration = !StringUtils.isEmpty(forcedSrcDir);
isMigration = !StringUtils.isEmpty(forcedSrcDir);
// header
_topPanel.add(new FLabel.Builder().text((isMigration ? "Migrate" : "Import") + " profile data").fontSize(15).build(), "center");
// add some help text if this is for the initial data migration
if (isMigration) {
FPanel blurbPanel = new FPanel(new MigLayout("insets panel, gap 10, fill"));
final FPanel blurbPanel = new FPanel(new MigLayout("insets panel, gap 10, fill"));
blurbPanel.setOpaque(false);
JPanel blurbPanelInterior = new JPanel(new MigLayout("insets dialog, gap 10, center, wrap, fill"));
final JPanel blurbPanelInterior = new JPanel(new MigLayout("insets dialog, gap 10, center, wrap, fill"));
blurbPanelInterior.setOpaque(false);
blurbPanelInterior.add(new FLabel.Builder().text("<html><b>What's this?</b></html>").build(), "growx, w 50:50:");
blurbPanelInterior.add(new FLabel.Builder().text(
@@ -103,18 +134,18 @@ public class ImportDialog {
blurbPanelInterior.add(new FLabel.Builder().text(
"<html><b>Remember, your data won't be available until you complete this step!</b></html>").build(), "growx, w 50:50:");
FScrollPane blurbScroller = new FScrollPane(blurbPanelInterior, true,
final FScrollPane blurbScroller = new FScrollPane(blurbPanelInterior, true,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
blurbPanel.add(blurbScroller, "hmin 150, growy, growx, center, gap 0 0 5 5");
_topPanel.add(blurbPanel, "gap 10 10 20 0, growy, growx, w 50:50:");
}
// import source widgets
JPanel importSourcePanel = new JPanel(new MigLayout("insets 0, gap 10"));
final JPanel importSourcePanel = new JPanel(new MigLayout("insets 0, gap 10"));
importSourcePanel.setOpaque(false);
importSourcePanel.add(new FLabel.Builder().text("Import from:").build());
final FTextField txfSrc = new FTextField.Builder().readonly().build();
importSourcePanel.add(txfSrc, "pushx, growx");
_txfSrc = new FTextField.Builder().readonly().build();
importSourcePanel.add(_txfSrc, "pushx, growx");
_btnChooseDir = new FLabel.ButtonBuilder().text("Choose directory...").enabled(!isMigration).build();
final JFileChooser _fileChooser = new JFileChooser();
_fileChooser.setMultiSelectionEnabled(false);
@@ -124,12 +155,12 @@ public class ImportDialog {
// bring up a file open dialog and, if the OK button is selected, apply the filename
// to the import source text field
if (JFileChooser.APPROVE_OPTION == _fileChooser.showOpenDialog(JOptionPane.getRootFrame())) {
File f = _fileChooser.getSelectedFile();
final File f = _fileChooser.getSelectedFile();
if (!f.canRead()) {
FOptionPane.showErrorDialog("Cannot access selected directory (Permission denied).");
}
else {
txfSrc.setText(f.getAbsolutePath());
_txfSrc.setText(f.getAbsolutePath());
}
}
}
@@ -139,23 +170,24 @@ public class ImportDialog {
// add change handler to the import source text field that starts up a
// new analyzer. it also interacts with the current active analyzer,
// if any, to make sure it cancels out before the new one is initiated
txfSrc.getDocument().addDocumentListener(new DocumentListener() {
_txfSrc.getDocument().addDocumentListener(new DocumentListener() {
boolean _analyzerActive; // access synchronized on _onAnalyzerDone
String prevText;
private final Runnable _onAnalyzerDone = new Runnable() {
@Override
public synchronized void run() {
_analyzerActive = false;
notify();
}
};
@Override public void removeUpdate(DocumentEvent e) { }
@Override public void changedUpdate(DocumentEvent e) { }
@Override public void insertUpdate(DocumentEvent e) {
@Override public void removeUpdate(final DocumentEvent e) { }
@Override public void changedUpdate(final DocumentEvent e) { }
@Override public void insertUpdate(final DocumentEvent e) {
// text field is read-only, so the only time this will get updated
// is when _btnChooseDir does it
final String text = txfSrc.getText();
final String text = _txfSrc.getText();
if (text.equals(prevText)) {
// only restart the analyzer if the directory has changed
return;
@@ -174,7 +206,7 @@ public class ImportDialog {
_btnStart.setEnabled(false);
// we have to wait in a background thread since we can't block in the GUI thread
SwingWorker<Void, Void> analyzerStarter = new SwingWorker<Void, Void>() {
final SwingWorker<Void, Void> analyzerStarter = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
// wait for active analyzer (if any) to quit
@@ -192,7 +224,7 @@ public class ImportDialog {
_cancel = false;
synchronized (_onAnalyzerDone) {
// this will populate the panel with data selection widgets
_AnalyzerUpdater analyzer = new _AnalyzerUpdater(text, _onAnalyzerDone, isMigration);
final _AnalyzerUpdater analyzer = new _AnalyzerUpdater(text, _onAnalyzerDone, isMigration);
analyzer.run();
_analyzerActive = true;
}
@@ -222,7 +254,7 @@ public class ImportDialog {
_btnStart.setEnabled(false);
_btnCancel = new FButton("Cancel");
_btnCancel.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
@Override public void actionPerformed(final ActionEvent e) {
_cancel = true;
cleanup.run();
if (null != onDialogClose) {
@@ -231,13 +263,15 @@ public class ImportDialog {
}
});
JPanel southPanel = new JPanel(new MigLayout("ax center"));
final JPanel southPanel = new JPanel(new MigLayout("ax center"));
southPanel.setOpaque(false);
southPanel.add(_btnStart, "center, w pref+144!, h pref+12!");
southPanel.add(_btnCancel, "center, w pref+144!, h pref+12!, gap 72");
_topPanel.add(southPanel, "growx");
}
JPanel overlay = FOverlay.SINGLETON_INSTANCE.getPanel();
public void show() {
final JPanel overlay = FOverlay.SINGLETON_INSTANCE.getPanel();
overlay.setLayout(new MigLayout("insets 0, gap 0, wrap, ax center, ay center"));
overlay.add(_topPanel, "w 500::90%, h 100::90%");
SOverlayUtils.showOverlay();
@@ -249,8 +283,8 @@ public class ImportDialog {
// if our source dir is provided, set the text, which will fire off an analyzer
if (isMigration) {
File srcDirFile = new File(forcedSrcDir);
txfSrc.setText(srcDirFile.getAbsolutePath());
final File srcDirFile = new File(forcedSrcDir);
_txfSrc.setText(srcDirFile.getAbsolutePath());
}
}
@@ -260,7 +294,7 @@ public class ImportDialog {
public final String name;
public final String path;
public _UnknownDeckChoice(String name0, String path0) {
public _UnknownDeckChoice(final String name0, final String path0) {
name = name0;
path = path0;
}
@@ -278,7 +312,9 @@ public class ImportDialog {
// attached to all changeable widgets to keep the UI in sync
private final ChangeListener _stateChangedListener = new ChangeListener() {
@Override public void stateChanged(ChangeEvent arg0) { _updateUI(); }
@Override public void stateChanged(final ChangeEvent arg0) {
_updateUI();
}
};
private final String _srcDir;
@@ -295,7 +331,7 @@ public class ImportDialog {
// updates the _operationLog widget asynchronously to keep the UI responsive
private final _OperationLogAsyncUpdater _operationLogUpdater;
public _AnalyzerUpdater(String srcDir, Runnable onAnalyzerDone, boolean isMigration) {
public _AnalyzerUpdater(final String srcDir, final Runnable onAnalyzerDone, final boolean isMigration) {
_srcDir = srcDir;
_onAnalyzerDone = onAnalyzerDone;
_isMigration = isMigration;
@@ -303,11 +339,11 @@ public class ImportDialog {
_selectionPanel.removeAll();
_selectionPanel.setLayout(new MigLayout("insets 0, gap 5, wrap, fill"));
JPanel cbPanel = new JPanel(new MigLayout("insets 0, gap 5"));
final JPanel cbPanel = new JPanel(new MigLayout("insets 0, gap 5"));
cbPanel.setOpaque(false);
// add deck selections
JPanel knownDeckPanel = new JPanel(new MigLayout("insets 0, gap 5, wrap 2"));
final JPanel knownDeckPanel = new JPanel(new MigLayout("insets 0, gap 5, wrap 2"));
knownDeckPanel.setOpaque(false);
knownDeckPanel.add(new FLabel.Builder().text("Decks").build(), "wrap");
_addSelectionWidget(knownDeckPanel, OpType.CONSTRUCTED_DECK, "Constructed decks");
@@ -316,7 +352,7 @@ public class ImportDialog {
_addSelectionWidget(knownDeckPanel, OpType.SCHEME_DECK, "Scheme decks");
_addSelectionWidget(knownDeckPanel, OpType.SEALED_DECK, "Sealed decks");
_addSelectionWidget(knownDeckPanel, OpType.UNKNOWN_DECK, "Unknown decks");
JPanel unknownDeckPanel = new JPanel(new MigLayout("insets 0, gap 5"));
final JPanel unknownDeckPanel = new JPanel(new MigLayout("insets 0, gap 5"));
unknownDeckPanel.setOpaque(false);
_unknownDeckCombo = new FComboBoxWrapper<_UnknownDeckChoice>();
_unknownDeckCombo.addItem(new _UnknownDeckChoice("Constructed", ForgeConstants.DECK_CONSTRUCTED_DIR));
@@ -325,7 +361,9 @@ public class ImportDialog {
_unknownDeckCombo.addItem(new _UnknownDeckChoice("Scheme", ForgeConstants.DECK_SCHEME_DIR));
_unknownDeckCombo.addItem(new _UnknownDeckChoice("Sealed", ForgeConstants.DECK_SEALED_DIR));
_unknownDeckCombo.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent arg0) { _updateUI(); }
@Override public void actionPerformed(final ActionEvent arg0) {
_updateUI();
}
});
_unknownDeckLabel = new FLabel.Builder().text("Treat unknown decks as:").build();
unknownDeckPanel.add(_unknownDeckLabel);
@@ -334,7 +372,7 @@ public class ImportDialog {
cbPanel.add(knownDeckPanel, "aligny top");
// add other userDir data elements
JPanel dataPanel = new JPanel(new MigLayout("insets 0, gap 5, wrap"));
final JPanel dataPanel = new JPanel(new MigLayout("insets 0, gap 5, wrap"));
dataPanel.setOpaque(false);
dataPanel.add(new FLabel.Builder().text("Other data").build());
_addSelectionWidget(dataPanel, OpType.GAUNTLET_DATA, "Gauntlet data");
@@ -343,7 +381,7 @@ public class ImportDialog {
cbPanel.add(dataPanel, "aligny top");
// add cacheDir data elements
JPanel cachePanel = new JPanel(new MigLayout("insets 0, gap 5, wrap 2"));
final JPanel cachePanel = new JPanel(new MigLayout("insets 0, gap 5, wrap 2"));
cachePanel.setOpaque(false);
cachePanel.add(new FLabel.Builder().text("Cached data").build(), "wrap");
_addSelectionWidget(cachePanel, OpType.DEFAULT_CARD_PIC, "Default card pics");
@@ -362,7 +400,7 @@ public class ImportDialog {
_selectionPanel.add(cbPanel, "center");
// add move/copy and overwrite checkboxes
JPanel ioOptionPanel = new JPanel(new MigLayout("insets 0, gap 10"));
final JPanel ioOptionPanel = new JPanel(new MigLayout("insets 0, gap 10"));
ioOptionPanel.setOpaque(false);
_moveCheckbox = new FCheckBox("Remove source files after copy");
_moveCheckbox.setToolTipText("Move files into the data directories instead of just copying them");
@@ -385,7 +423,7 @@ public class ImportDialog {
// autoscroll when we set/add text unless the user has intentionally scrolled somewhere else
_operationLogScroller = new JScrollPane(_operationLog);
_operationLogScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
new SmartScroller(_operationLogScroller);
new SmartScroller(_operationLogScroller).attach();
_selectionPanel.add(_operationLogScroller, "w 400:400:, hmin 60, growy, growx");
// add progress bar
@@ -406,13 +444,13 @@ public class ImportDialog {
_selectionPanel.getParent().invalidate();
}
private void _addSelectionWidget(JPanel parent, OpType type, String name) {
private void _addSelectionWidget(final JPanel parent, final OpType type, final String name) {
_addSelectionWidget(parent, type, name, true, null, null);
}
private void _addSelectionWidget(JPanel parent, OpType type, String name, boolean selected,
String tooltip, String constraints) {
FCheckBox cb = new FCheckBox();
private void _addSelectionWidget(final JPanel parent, final OpType type, final String name, final boolean selected,
final String tooltip, final String constraints) {
final FCheckBox cb = new FCheckBox();
cb.setName(name);
cb.setSelected(selected);
cb.setToolTipText(tooltip);
@@ -428,10 +466,10 @@ public class ImportDialog {
// must be called from GUI event loop thread
private void _updateUI() {
// update checkbox text labels with current totals
Set<OpType> selectedOptions = new HashSet<OpType>();
for (Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : _selections.entrySet()) {
Pair<FCheckBox, ? extends Map<File, File>> selection = entry.getValue();
FCheckBox cb = selection.getLeft();
final Set<OpType> selectedOptions = new HashSet<OpType>();
for (final Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : _selections.entrySet()) {
final Pair<FCheckBox, ? extends Map<File, File>> selection = entry.getValue();
final FCheckBox cb = selection.getLeft();
if (cb.isSelected()) {
selectedOptions.add(entry.getKey());
@@ -442,7 +480,7 @@ public class ImportDialog {
// asynchronously update the text in the op log, which may be many tens of thousands of lines long
// if this were done synchronously the UI would slow to a crawl
_operationLogUpdater.requestUpdate(selectedOptions, (_UnknownDeckChoice)_unknownDeckCombo.getSelectedItem(),
_operationLogUpdater.requestUpdate(selectedOptions, _unknownDeckCombo.getSelectedItem(),
_moveCheckbox.isSelected(), _overwriteCheckbox.isSelected());
}
@@ -451,17 +489,17 @@ public class ImportDialog {
Timer timer = null;
try {
Map<OpType, Map<File, File>> selections = new HashMap<OpType, Map<File, File>>();
for (Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : _selections.entrySet()) {
final Map<OpType, Map<File, File>> selections = new HashMap<OpType, Map<File, File>>();
for (final Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : _selections.entrySet()) {
selections.put(entry.getKey(), entry.getValue().getRight());
}
ImportSourceAnalyzer.AnalysisCallback cb = new ImportSourceAnalyzer.AnalysisCallback() {
@Override
public boolean checkCancel() { return _cancel; }
final ImportSourceAnalyzer.AnalysisCallback cb = new ImportSourceAnalyzer.AnalysisCallback() {
@Override public boolean checkCancel() {
return _cancel;
}
@Override
public void addOp(OpType type, File src, File dest) {
@Override public void addOp(final OpType type, final File src, final File dest) {
// add to concurrent map
_selections.get(type).getRight().put(src, dest);
}
@@ -475,7 +513,7 @@ public class ImportDialog {
timer.setInitialDelay(100);
final Timer finalTimer = timer;
timer.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent arg0) {
@Override public void actionPerformed(final ActionEvent arg0) {
if (_cancel) {
finalTimer.stop();
return;
@@ -537,14 +575,14 @@ public class ImportDialog {
// clear any previously-set action listeners on the start button
// in case we've previously completed an analysis but changed the directory
// instead of starting the import
for (ActionListener a : _btnStart.getActionListeners()) {
for (final ActionListener a : _btnStart.getActionListeners()) {
_btnStart.removeActionListener(a);
}
// deselect and disable all options that have 0 operations associated with
// them to highlight the important options
for (Pair<FCheckBox, ? extends Map<File, File>> p : _selections.values()) {
FCheckBox cb = p.getLeft();
for (final Pair<FCheckBox, ? extends Map<File, File>> p : _selections.values()) {
final FCheckBox cb = p.getLeft();
if (0 == p.getRight().size()) {
cb.removeChangeListener(_stateChangedListener);
cb.setSelected(false);
@@ -559,31 +597,31 @@ public class ImportDialog {
// set up the start button to start the prepared import on click
_btnStart.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent arg0) {
@Override public void actionPerformed(final ActionEvent arg0) {
// if this is a migration, warn if active settings will not complete a migration and give the
// user an option to fix
if (_isMigration) {
// assemble a list of selections that need to be selected to complete a full migration
List<String> unselectedButShouldBe = new ArrayList<String>();
for (Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : _selections.entrySet()) {
final List<String> unselectedButShouldBe = new ArrayList<String>();
for (final Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : _selections.entrySet()) {
if (OpType.POSSIBLE_SET_CARD_PIC == entry.getKey()) {
continue;
}
// add name to list if checkbox is unselected, but contains operations
Pair<FCheckBox, ? extends Map<File, File>> p = entry.getValue();
FCheckBox cb = p.getLeft();
final Pair<FCheckBox, ? extends Map<File, File>> p = entry.getValue();
final FCheckBox cb = p.getLeft();
if (!cb.isSelected() && 0 < p.getRight().size()) {
unselectedButShouldBe.add(cb.getName());
}
}
if (!unselectedButShouldBe.isEmpty() || !_moveCheckbox.isSelected()) {
StringBuilder sb = new StringBuilder("<html>");
final StringBuilder sb = new StringBuilder("<html>");
if (!unselectedButShouldBe.isEmpty()) {
sb.append("It looks like the following options are not selected, which will result in an incomplete migration:");
sb.append("<ul>");
for (String cbName : unselectedButShouldBe) {
for (final String cbName : unselectedButShouldBe) {
sb.append("<li><b>").append(cbName).append("</b></li>");
}
sb.append("</ul>");
@@ -598,8 +636,8 @@ public class ImportDialog {
sb.append("will come up again the next time you start Forge in order to migrate the remaining files<br>");
sb.append("unless you move or delete them manually.</html>");
String[] options = { "Whoops, let me fix that!", "Continue with the import, I know what I'm doing." };
int chosen = FOptionPane.showOptionDialog(sb.toString(), "Migration warning", FOptionPane.WARNING_ICON, options);
final String[] options = { "Whoops, let me fix that!", "Continue with the import, I know what I'm doing." };
final int chosen = FOptionPane.showOptionDialog(sb.toString(), "Migration warning", FOptionPane.WARNING_ICON, options);
if (chosen != 1) {
// i.e. option 0 was chosen or the dialog was otherwise closed
@@ -612,7 +650,7 @@ public class ImportDialog {
_btnStart.setEnabled(false);
_btnChooseDir.setEnabled(false);
for (Pair<FCheckBox, ? extends Map<File, File>> selection : _selections.values()) {
for (final Pair<FCheckBox, ? extends Map<File, File>> selection : _selections.values()) {
selection.getLeft().setEnabled(false);
}
_unknownDeckCombo.setEnabled(false);
@@ -624,11 +662,11 @@ public class ImportDialog {
// jump to the bottom of the log text area so it starts autoscrolling again
// note that since it is controlled by a SmartScroller, just setting the caret position will not work
JScrollBar scrollBar = _operationLogScroller.getVerticalScrollBar();
final JScrollBar scrollBar = _operationLogScroller.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
// start importing!
_Importer importer = new _Importer(
final _Importer importer = new _Importer(
_srcDir, _selections, _unknownDeckCombo, _operationLog, _progressBar,
_moveCheckbox.isSelected(), _overwriteCheckbox.isSelected());
importer.run();
@@ -663,7 +701,7 @@ public class ImportDialog {
// only accessed from the event loop thread
int _maxLogLength = 0;
public _OperationLogAsyncUpdater(Map<OpType, Pair<FCheckBox, ? extends Map<File, File>>> selections, JTextArea operationLog) {
public _OperationLogAsyncUpdater(final Map<OpType, Pair<FCheckBox, ? extends Map<File, File>>> selections, final JTextArea operationLog) {
super("OperationLogUpdater");
setDaemon(true);
@@ -672,14 +710,13 @@ public class ImportDialog {
// remove references to FCheckBox when populating map -- we can't safely access it from a thread
// anyway and it's better to keep our data structure clean to prevent mistakes
for (Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : selections.entrySet()) {
for (final Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : selections.entrySet()) {
_selections.put(entry.getKey(), entry.getValue().getRight());
}
}
// updates the synchronized data with values for the next iteration in _run
public synchronized void requestUpdate(
Set<OpType> selectedOptions, _UnknownDeckChoice unknownDeckChoice, boolean isMove, boolean isOverwrite) {
public synchronized void requestUpdate(final Set<OpType> selectedOptions, final _UnknownDeckChoice unknownDeckChoice, final boolean isMove, final boolean isOverwrite) {
++_updateCallCnt;
_selectedOptions = selectedOptions;
_unknownDeckChoice = unknownDeckChoice;
@@ -726,11 +763,11 @@ public class ImportDialog {
// build operation log
final StringBuilder log = new StringBuilder();
int totalOps = 0;
for (OpType opType : selectedOptions) {
Map<File, File> ops = _selections.get(opType);
for (final OpType opType : selectedOptions) {
final Map<File, File> ops = _selections.get(opType);
totalOps += ops.size();
for (Map.Entry<File, File> op : ops.entrySet()) {
for (final Map.Entry<File, File> op : ops.entrySet()) {
File dest = op.getValue();
if (OpType.UNKNOWN_DECK == opType) {
dest = new File(unknownDeckChoice.path, dest.getName());
@@ -751,7 +788,7 @@ public class ImportDialog {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String logText = log.toString();
final String logText = log.toString();
// setText is thread-safe, but the resizing is not, so might as well do this in the swing event loop thread
_operationLog.setText(log.toString());
@@ -793,8 +830,8 @@ public class ImportDialog {
private final boolean _move;
private final boolean _overwrite;
public _Importer(String srcDir, Map<OpType, Pair<FCheckBox, ? extends Map<File, File>>> selections, FComboBoxWrapper<_UnknownDeckChoice> unknownDeckCombo,
JTextArea operationLog, JProgressBar progressBar, boolean move, boolean overwrite) {
public _Importer(final String srcDir, final Map<OpType, Pair<FCheckBox, ? extends Map<File, File>>> selections, final FComboBoxWrapper<_UnknownDeckChoice> unknownDeckCombo,
final JTextArea operationLog, final JProgressBar progressBar, final boolean move, final boolean overwrite) {
_srcDir = srcDir;
_operationLog = operationLog;
_progressBar = progressBar;
@@ -804,15 +841,15 @@ public class ImportDialog {
// build local operations map that only includes data that we can access from the background thread
// use a tree map to maintain alphabetical order
_operations = new TreeMap<File, File>();
for (Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : selections.entrySet()) {
Pair<FCheckBox, ? extends Map<File, File>> selection = entry.getValue();
for (final Map.Entry<OpType, Pair<FCheckBox, ? extends Map<File, File>>> entry : selections.entrySet()) {
final Pair<FCheckBox, ? extends Map<File, File>> selection = entry.getValue();
if (selection.getLeft().isSelected()) {
if (OpType.UNKNOWN_DECK != entry.getKey()) {
_operations.putAll(selection.getRight());
} else {
// map unknown decks to selected directory
for (Map.Entry<File, File> op : selection.getRight().entrySet()) {
_UnknownDeckChoice choice = (_UnknownDeckChoice)unknownDeckCombo.getSelectedItem();
for (final Map.Entry<File, File> op : selection.getRight().entrySet()) {
final _UnknownDeckChoice choice = unknownDeckCombo.getSelectedItem();
_operations.put(op.getKey(), new File(choice.path, op.getValue().getName()));
}
}
@@ -835,7 +872,7 @@ public class ImportDialog {
// update after only 100ms
final long updateIntervalMs = 500;
long lastUpdateTimestampMs = System.currentTimeMillis() - 400;
StringBuffer opLogBuf = new StringBuffer();
final StringBuffer opLogBuf = new StringBuffer();
// only update the progress bar when we expect the visual value to change
final long progressInterval = Math.max(1, _operations.size() / _progressBar.getWidth());
@@ -854,7 +891,7 @@ public class ImportDialog {
int numExisting = 0;
int numSucceeded = 0;
int numFailed = 0;
for (Map.Entry<File, File> op : _operations.entrySet()) {
for (final Map.Entry<File, File> op : _operations.entrySet()) {
if (_cancel) { break; }
final int curOpNum = ++numOps;
@@ -867,7 +904,7 @@ public class ImportDialog {
});
}
long curTimeMs = System.currentTimeMillis();
final long curTimeMs = System.currentTimeMillis();
if (updateIntervalMs <= curTimeMs - lastUpdateTimestampMs) {
lastUpdateTimestampMs = curTimeMs;
@@ -876,8 +913,8 @@ public class ImportDialog {
opLogBuf.setLength(0);
}
File srcFile = op.getKey();
File destFile = op.getValue();
final File srcFile = op.getKey();
final File destFile = op.getValue();
try {
// simplify logged source path and log next attempted operation
@@ -909,7 +946,7 @@ public class ImportDialog {
}
++numSucceeded;
} catch (IOException e) {
} catch (final IOException e) {
opLogBuf.append(" Operation failed: ").append(e.getMessage()).append("\n");
++numFailed;
}
@@ -956,7 +993,7 @@ public class ImportDialog {
}
// when copying is required, uses java nio classes for ultra-fast I/O
private static void _copyFile(File srcFile, File destFile, boolean deleteSrcAfter) throws IOException {
private static void _copyFile(final File srcFile, final File destFile, final boolean deleteSrcAfter) throws IOException {
destFile.getParentFile().mkdirs();
// if this is a move, try a simple rename first

View File

@@ -17,6 +17,15 @@
*/
package forge.gui;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
@@ -29,15 +38,6 @@ import forge.properties.ForgeConstants;
import forge.util.FileUtil;
import forge.util.ImageUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
public class ImportSourceAnalyzer {
public static enum OpType {
CONSTRUCTED_DECK,
@@ -68,7 +68,7 @@ public class ImportSourceAnalyzer {
private int _numFilesAnalyzed;
public ImportSourceAnalyzer(String source, AnalysisCallback cb) {
public ImportSourceAnalyzer(final String source, final AnalysisCallback cb) {
_source = new File(source);
_cb = cb;
@@ -82,10 +82,10 @@ public class ImportSourceAnalyzer {
_identifyAndAnalyze(_source);
}
private void _identifyAndAnalyze(File root) {
private void _identifyAndAnalyze(final File root) {
// see if we can figure out the likely identity of the source folder and
// dispatch to the best analysis subroutine to handle it
String dirname = root.getName();
final String dirname = root.getName();
if ("res".equalsIgnoreCase(dirname)) { _analyzeOldResDir(root); }
else if ("constructed".equalsIgnoreCase(dirname)) { _analyzeConstructedDeckDir(root); }
@@ -104,11 +104,11 @@ public class ImportSourceAnalyzer {
else {
// look at files in directory and make a semi-educated guess based on file extensions
int numUnhandledFiles = 0;
for (File file : root.listFiles()) {
for (final File file : root.listFiles()) {
if (_cb.checkCancel()) { return; }
if (file.isFile()) {
String filename = file.getName();
final String filename = file.getName();
if (StringUtils.endsWithIgnoreCase(filename, ".dck")) {
_analyzeDecksDir(root);
numUnhandledFiles = 0;
@@ -132,10 +132,10 @@ public class ImportSourceAnalyzer {
// pre-profile res dir
//
private void _analyzeOldResDir(File root) {
private void _analyzeOldResDir(final File root) {
_analyzeDir(root, new _Analyzer() {
@Override boolean onDir(File dir) {
String dirname = dir.getName();
@Override boolean onDir(final File dir) {
final String dirname = dir.getName();
if ("decks".equalsIgnoreCase(dirname)) {
_analyzeDecksDir(dir);
} else if ("gauntlet".equalsIgnoreCase(dirname)) {
@@ -162,19 +162,19 @@ public class ImportSourceAnalyzer {
// decks
//
private void _analyzeDecksDir(File root) {
private void _analyzeDecksDir(final File root) {
_analyzeDir(root, new _Analyzer() {
@Override void onFile(File file) {
@Override void onFile(final File file) {
// we don't really expect any files in here, but if we find a .dck file, add it to the unknown list
String filename = file.getName();
final String filename = file.getName();
if (StringUtils.endsWithIgnoreCase(filename, ".dck")) {
File targetFile = new File(_lcaseExt(filename));
final File targetFile = new File(_lcaseExt(filename));
_cb.addOp(OpType.UNKNOWN_DECK, file, targetFile);
}
}
@Override boolean onDir(File dir) {
String dirname = dir.getName();
@Override boolean onDir(final File dir) {
final String dirname = dir.getName();
if ("constructed".equalsIgnoreCase(dirname)) {
_analyzeConstructedDeckDir(dir);
} else if ("cube".equalsIgnoreCase(dirname)) {
@@ -195,39 +195,39 @@ public class ImportSourceAnalyzer {
});
}
private void _analyzeConstructedDeckDir(File root) {
private void _analyzeConstructedDeckDir(final File root) {
_analyzeKnownDeckDir(root, ForgeConstants.DECK_CONSTRUCTED_DIR, OpType.CONSTRUCTED_DECK);
}
private void _analyzeDraftDeckDir(File root) {
private void _analyzeDraftDeckDir(final File root) {
_analyzeKnownDeckDir(root, ForgeConstants.DECK_DRAFT_DIR, OpType.DRAFT_DECK);
}
private void _analyzePlanarDeckDir(File root) {
private void _analyzePlanarDeckDir(final File root) {
_analyzeKnownDeckDir(root, ForgeConstants.DECK_PLANE_DIR, OpType.PLANAR_DECK);
}
private void _analyzeSchemeDeckDir(File root) {
private void _analyzeSchemeDeckDir(final File root) {
_analyzeKnownDeckDir(root, ForgeConstants.DECK_SCHEME_DIR, OpType.SCHEME_DECK);
}
private void _analyzeSealedDeckDir(File root) {
private void _analyzeSealedDeckDir(final File root) {
_analyzeKnownDeckDir(root, ForgeConstants.DECK_SEALED_DIR, OpType.SEALED_DECK);
}
private void _analyzeKnownDeckDir(File root, final String targetDir, final OpType opType) {
private void _analyzeKnownDeckDir(final File root, final String targetDir, final OpType opType) {
_analyzeDir(root, new _Analyzer() {
@Override void onFile(File file) {
String filename = file.getName();
@Override void onFile(final File file) {
final String filename = file.getName();
if (StringUtils.endsWithIgnoreCase(filename, ".dck")) {
File targetFile = new File(targetDir, _lcaseExt(filename));
final File targetFile = new File(targetDir, _lcaseExt(filename));
if (!file.equals(targetFile)) {
_cb.addOp(opType, file, targetFile);
}
}
}
@Override boolean onDir(File dir) {
@Override boolean onDir(final File dir) {
// if there's a dir beneath a known directory, assume the same kind of decks are in there
_analyzeKnownDeckDir(dir, targetDir, opType);
return true;
@@ -239,13 +239,13 @@ public class ImportSourceAnalyzer {
// gauntlet
//
private void _analyzeGauntletDataDir(File root) {
private void _analyzeGauntletDataDir(final File root) {
_analyzeDir(root, new _Analyzer() {
@Override void onFile(File file) {
@Override void onFile(final File file) {
// find *.dat files, but exclude LOCKED_*
String filename = file.getName();
final String filename = file.getName();
if (StringUtils.endsWithIgnoreCase(filename, ".dat") && !filename.startsWith("LOCKED_")) {
File targetFile = new File(ForgeConstants.GAUNTLET_DIR.userPrefLoc, _lcaseExt(filename));
final File targetFile = new File(ForgeConstants.GAUNTLET_DIR.userPrefLoc, _lcaseExt(filename));
if (!file.equals(targetFile)) {
_cb.addOp(OpType.GAUNTLET_DATA, file, targetFile);
}
@@ -258,13 +258,13 @@ public class ImportSourceAnalyzer {
// layouts
//
private void _analyzeLayoutsDir(File root) {
private void _analyzeLayoutsDir(final File root) {
_analyzeDir(root, new _Analyzer() {
@Override void onFile(File file) {
@Override void onFile(final File file) {
// find *_preferred.xml files
String filename = file.getName();
final String filename = file.getName();
if (StringUtils.endsWithIgnoreCase(filename, "_preferred.xml")) {
File targetFile = new File(ForgeConstants.USER_PREFS_DIR,
final File targetFile = new File(ForgeConstants.USER_PREFS_DIR,
file.getName().toLowerCase(Locale.ENGLISH).replace("_preferred", ""));
_cb.addOp(OpType.PREFERENCE_FILE, file, targetFile);
}
@@ -276,10 +276,10 @@ public class ImportSourceAnalyzer {
// default card pics
//
private static String _oldCleanString(String in) {
private static String _oldCleanString(final String in) {
final StringBuffer out = new StringBuffer();
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
final char c = in.charAt(i);
if ((c == ' ') || (c == '-')) {
out.append('_');
} else if (Character.isLetterOrDigit(c) || (c == '_')) {
@@ -292,24 +292,26 @@ public class ImportSourceAnalyzer {
return out.toString().toLowerCase();
}
private void _addDefaultPicNames(PaperCard c, boolean backFace) {
CardRules card = c.getRules();
String urls = card.getPictureUrl(backFace);
private void _addDefaultPicNames(final PaperCard c, final boolean backFace) {
final CardRules card = c.getRules();
final String urls = card.getPictureUrl(backFace);
if (StringUtils.isEmpty(urls)) { return; }
int numPics = 1 + StringUtils.countMatches(urls, "\\");
final int numPics = 1 + StringUtils.countMatches(urls, "\\");
if (c.getArtIndex() > numPics) {
return;
}
String filenameBase = ImageUtil.getImageKey(c, backFace, false);
String filename = filenameBase + ".jpg";
boolean alreadyHadIt = null != _defaultPicNames.put(filename, filename);
if ( alreadyHadIt ) return;
final String filenameBase = ImageUtil.getImageKey(c, backFace, false);
final String filename = filenameBase + ".jpg";
final boolean alreadyHadIt = null != _defaultPicNames.put(filename, filename);
if ( alreadyHadIt ) {
return;
}
// Do you shift artIndex by one here?
String newLastSymbol = 0 == c.getArtIndex() ? "" : String.valueOf(c.getArtIndex() /* + 1 */);
String oldFilename = _oldCleanString(filenameBase.replaceAll("[0-9]?(\\.full)?$", "")) + newLastSymbol + ".jpg";
final String newLastSymbol = 0 == c.getArtIndex() ? "" : String.valueOf(c.getArtIndex() /* + 1 */);
final String oldFilename = _oldCleanString(filenameBase.replaceAll("[0-9]?(\\.full)?$", "")) + newLastSymbol + ".jpg";
//if ( numPics > 1 )
//System.out.printf("Will move %s -> %s%n", oldFilename, filename);
_defaultPicOldNameToCurrentName.put(oldFilename, filename);
@@ -318,35 +320,37 @@ public class ImportSourceAnalyzer {
private Map<String, String> _defaultPicNames;
private Map<String, String> _defaultPicOldNameToCurrentName;
private void _analyzeCardPicsDir(File root) {
private void _analyzeCardPicsDir(final File root) {
if (null == _defaultPicNames) {
_defaultPicNames = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
_defaultPicOldNameToCurrentName = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
for (PaperCard c : FModel.getMagicDb().getCommonCards().getAllCards()) {
for (final PaperCard c : FModel.getMagicDb().getCommonCards().getAllCards()) {
_addDefaultPicNames(c, false);
if (ImageUtil.hasBackFacePicture(c)) {
_addDefaultPicNames(c, true);
}
}
for (PaperCard c : FModel.getMagicDb().getVariantCards().getAllCards()) {
for (final PaperCard c : FModel.getMagicDb().getVariantCards().getAllCards()) {
_addDefaultPicNames(c, false);
// variants never have backfaces
}
}
_analyzeListedDir(root, ForgeConstants.CACHE_CARD_PICS_DIR, new _ListedAnalyzer() {
@Override public String map(String filename) {
@Override public String map(final String filename) {
if (_defaultPicOldNameToCurrentName.containsKey(filename)) {
return _defaultPicOldNameToCurrentName.get(filename);
}
return _defaultPicNames.get(filename);
}
@Override public OpType getOpType(String filename) { return OpType.DEFAULT_CARD_PIC; }
@Override public OpType getOpType(final String filename) {
return OpType.DEFAULT_CARD_PIC;
}
@Override boolean onDir(File dir) {
@Override boolean onDir(final File dir) {
if ("icons".equalsIgnoreCase(dir.getName())) {
_analyzeIconsPicsDir(dir);
} else if ("tokens".equalsIgnoreCase(dir.getName())) {
@@ -363,8 +367,8 @@ public class ImportSourceAnalyzer {
// set card pics
//
private static void _addSetCards(Map<String, String> cardFileNames, Iterable<PaperCard> library, Predicate<PaperCard> filter) {
for (PaperCard c : Iterables.filter(library, filter)) {
private static void _addSetCards(final Map<String, String> cardFileNames, final Iterable<PaperCard> library, final Predicate<PaperCard> filter) {
for (final PaperCard c : Iterables.filter(library, filter)) {
String filename = ImageUtil.getImageKey(c, false, true) + ".jpg";
cardFileNames.put(filename, filename);
if (ImageUtil.hasBackFacePicture(c)) {
@@ -376,12 +380,12 @@ public class ImportSourceAnalyzer {
Map<String, Map<String, String>> _cardFileNamesBySet;
Map<String, String> _nameUpdates;
private void _analyzeCardPicsSetDir(File root) {
private void _analyzeCardPicsSetDir(final File root) {
if (null == _cardFileNamesBySet) {
_cardFileNamesBySet = new TreeMap<String, Map<String, String>>(String.CASE_INSENSITIVE_ORDER);
for (CardEdition ce : FModel.getMagicDb().getEditions()) {
Map<String, String> cardFileNames = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
Predicate<PaperCard> filter = IPaperCard.Predicates.printedInSet(ce.getCode());
for (final CardEdition ce : FModel.getMagicDb().getEditions()) {
final Map<String, String> cardFileNames = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
final Predicate<PaperCard> filter = IPaperCard.Predicates.printedInSet(ce.getCode());
_addSetCards(cardFileNames, FModel.getMagicDb().getCommonCards().getAllCards(), filter);
_addSetCards(cardFileNames, FModel.getMagicDb().getVariantCards().getAllCards(), filter);
_cardFileNamesBySet.put(ce.getCode2(), cardFileNames);
@@ -389,14 +393,14 @@ public class ImportSourceAnalyzer {
// planar cards now don't have the ".full" part in their filenames
_nameUpdates = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
Predicate<PaperCard> predPlanes = new Predicate<PaperCard>() {
final Predicate<PaperCard> predPlanes = new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard arg0) {
public boolean apply(final PaperCard arg0) {
return arg0.getRules().getType().isPlane() || arg0.getRules().getType().isPhenomenon();
}
};
for (PaperCard c : Iterables.filter(FModel.getMagicDb().getVariantCards().getAllCards(), predPlanes)) {
for (final PaperCard c : Iterables.filter(FModel.getMagicDb().getVariantCards().getAllCards(), predPlanes)) {
String baseName = ImageUtil.getImageKey(c,false, true);
_nameUpdates.put(baseName + ".full.jpg", baseName + ".jpg");
if (ImageUtil.hasBackFacePicture(c)) {
@@ -406,9 +410,9 @@ public class ImportSourceAnalyzer {
}
}
CardEdition.Collection editions = FModel.getMagicDb().getEditions();
String editionCode = root.getName();
CardEdition edition = editions.get(editionCode);
final CardEdition.Collection editions = FModel.getMagicDb().getEditions();
final String editionCode = root.getName();
final CardEdition edition = editions.get(editionCode);
if (null == edition) {
// not a valid set name, skip
_numFilesAnalyzed += _countFiles(root);
@@ -431,7 +435,7 @@ public class ImportSourceAnalyzer {
}
return null;
}
@Override public OpType getOpType(String filename) {
@Override public OpType getOpType(final String filename) {
return validFilenames.containsKey(filename) ? OpType.SET_CARD_PIC : OpType.POSSIBLE_SET_CARD_PIC;
}
});
@@ -442,54 +446,54 @@ public class ImportSourceAnalyzer {
//
Map<String, String> _iconFileNames;
private void _analyzeIconsPicsDir(File root) {
private void _analyzeIconsPicsDir(final File root) {
if (null == _iconFileNames) {
_iconFileNames = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
for (Pair<String, String> nameurl : FileUtil.readNameUrlFile(ForgeConstants.IMAGE_LIST_QUEST_OPPONENT_ICONS_FILE)) {
for (final Pair<String, String> nameurl : FileUtil.readNameUrlFile(ForgeConstants.IMAGE_LIST_QUEST_OPPONENT_ICONS_FILE)) {
_iconFileNames.put(nameurl.getLeft(), nameurl.getLeft());
}
for (Pair<String, String> nameurl : FileUtil.readNameUrlFile(ForgeConstants.IMAGE_LIST_QUEST_PET_SHOP_ICONS_FILE)) {
for (final Pair<String, String> nameurl : FileUtil.readNameUrlFile(ForgeConstants.IMAGE_LIST_QUEST_PET_SHOP_ICONS_FILE)) {
_iconFileNames.put(nameurl.getLeft(), nameurl.getLeft());
}
}
_analyzeListedDir(root, ForgeConstants.CACHE_ICON_PICS_DIR, new _ListedAnalyzer() {
@Override public String map(String filename) { return _iconFileNames.containsKey(filename) ? _iconFileNames.get(filename) : null; }
@Override public OpType getOpType(String filename) { return OpType.QUEST_PIC; }
@Override public String map(final String filename) { return _iconFileNames.containsKey(filename) ? _iconFileNames.get(filename) : null; }
@Override public OpType getOpType(final String filename) { return OpType.QUEST_PIC; }
});
}
Map<String, String> _tokenFileNames;
Map<String, String> _questTokenFileNames;
private void _analyzeTokenPicsDir(File root) {
private void _analyzeTokenPicsDir(final File root) {
if (null == _tokenFileNames) {
_tokenFileNames = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
_questTokenFileNames = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
for (Pair<String, String> nameurl : FileUtil.readNameUrlFile(ForgeConstants.IMAGE_LIST_TOKENS_FILE)) {
for (final Pair<String, String> nameurl : FileUtil.readNameUrlFile(ForgeConstants.IMAGE_LIST_TOKENS_FILE)) {
_tokenFileNames.put(nameurl.getLeft(), nameurl.getLeft());
}
for (Pair<String, String> nameurl : FileUtil.readNameUrlFile(ForgeConstants.IMAGE_LIST_QUEST_TOKENS_FILE)) {
for (final Pair<String, String> nameurl : FileUtil.readNameUrlFile(ForgeConstants.IMAGE_LIST_QUEST_TOKENS_FILE)) {
_questTokenFileNames.put(nameurl.getLeft(), nameurl.getLeft());
}
}
_analyzeListedDir(root, ForgeConstants.CACHE_TOKEN_PICS_DIR, new _ListedAnalyzer() {
@Override public String map(String filename) {
@Override public String map(final String filename) {
if (_questTokenFileNames.containsKey(filename)) { return _questTokenFileNames.get(filename); }
if (_tokenFileNames.containsKey(filename)) { return _tokenFileNames.get(filename); }
return null;
}
@Override public OpType getOpType(String filename) {
@Override public OpType getOpType(final String filename) {
return _questTokenFileNames.containsKey(filename) ? OpType.QUEST_PIC : OpType.TOKEN_PIC;
}
});
}
private void _analyzeProductPicsDir(File root) {
private void _analyzeProductPicsDir(final File root) {
// we don't care about the files in the root dir -- the new booster files are .png, not the current .jpg ones
_analyzeDir(root, new _Analyzer() {
@Override boolean onDir(File dir) {
String dirName = dir.getName();
@Override boolean onDir(final File dir) {
final String dirName = dir.getName();
if ("booster".equalsIgnoreCase(dirName)) {
_analyzeSimpleListedDir(dir, ForgeConstants.IMAGE_LIST_QUEST_BOOSTERS_FILE, ForgeConstants.CACHE_BOOSTER_PICS_DIR, OpType.QUEST_PIC);
} else if ("fatpacks".equalsIgnoreCase(dirName)) {
@@ -512,12 +516,12 @@ public class ImportSourceAnalyzer {
// preferences
//
private void _analyzePreferencesDir(File root) {
private void _analyzePreferencesDir(final File root) {
_analyzeDir(root, new _Analyzer() {
@Override void onFile(File file) {
String filename = file.getName();
@Override void onFile(final File file) {
final String filename = file.getName();
if ("editor.preferences".equalsIgnoreCase(filename) || "forge.preferences".equalsIgnoreCase(filename)) {
File targetFile = new File(ForgeConstants.USER_PREFS_DIR, filename.toLowerCase(Locale.ENGLISH));
final File targetFile = new File(ForgeConstants.USER_PREFS_DIR, filename.toLowerCase(Locale.ENGLISH));
if (!file.equals(targetFile)) {
_cb.addOp(OpType.PREFERENCE_FILE, file, targetFile);
}
@@ -530,18 +534,18 @@ public class ImportSourceAnalyzer {
// quest data
//
private void _analyzeQuestDir(File root) {
private void _analyzeQuestDir(final File root) {
_analyzeDir(root, new _Analyzer() {
@Override void onFile(File file) {
String filename = file.getName();
@Override void onFile(final File file) {
final String filename = file.getName();
if ("all-prices.txt".equalsIgnoreCase(filename)) {
File targetFile = new File(ForgeConstants.DB_DIR, filename.toLowerCase(Locale.ENGLISH));
final File targetFile = new File(ForgeConstants.DB_DIR, filename.toLowerCase(Locale.ENGLISH));
if (!file.equals(targetFile)) {
_cb.addOp(OpType.DB_FILE, file, targetFile);
}
}
}
@Override boolean onDir(File dir) {
@Override boolean onDir(final File dir) {
if ("data".equalsIgnoreCase(dir.getName())) {
_analyzeQuestDataDir(dir);
return true;
@@ -551,12 +555,12 @@ public class ImportSourceAnalyzer {
});
}
private void _analyzeQuestDataDir(File root) {
private void _analyzeQuestDataDir(final File root) {
_analyzeDir(root, new _Analyzer() {
@Override void onFile(File file) {
String filename = file.getName();
@Override void onFile(final File file) {
final String filename = file.getName();
if (StringUtils.endsWithIgnoreCase(filename, ".dat")) {
File targetFile = new File(ForgeConstants.QUEST_SAVE_DIR, _lcaseExt(filename));
final File targetFile = new File(ForgeConstants.QUEST_SAVE_DIR, _lcaseExt(filename));
if (!file.equals(targetFile)) {
_cb.addOp(OpType.QUEST_DATA, file, targetFile);
}
@@ -570,14 +574,14 @@ public class ImportSourceAnalyzer {
//
private class _Analyzer {
void onFile(File file) { }
void onFile(final File file) { }
// returns whether the directory has been handled
boolean onDir(File dir) { return false; }
boolean onDir(final File dir) { return false; }
}
private void _analyzeDir(File root, _Analyzer analyzer) {
for (File file : root.listFiles()) {
private void _analyzeDir(final File root, final _Analyzer analyzer) {
for (final File file : root.listFiles()) {
if (_cb.checkCancel()) { return; }
if (file.isFile()) {
@@ -591,11 +595,11 @@ public class ImportSourceAnalyzer {
}
}
private Map<String, Map<String, String>> _fileNameDb = new HashMap<String, Map<String, String>>();
private void _analyzeSimpleListedDir(File root, String listFile, String targetDir, final OpType opType) {
private final Map<String, Map<String, String>> _fileNameDb = new HashMap<String, Map<String, String>>();
private void _analyzeSimpleListedDir(final File root, final String listFile, final String targetDir, final OpType opType) {
if (!_fileNameDb.containsKey(listFile)) {
Map<String, String> fileNames = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
for (Pair<String, String> nameurl : FileUtil.readNameUrlFile(listFile)) {
final Map<String, String> fileNames = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
for (final Pair<String, String> nameurl : FileUtil.readNameUrlFile(listFile)) {
// we use a map instead of a set since we need to match case-insensitively but still map to the correct case
fileNames.put(nameurl.getLeft(), nameurl.getLeft());
}
@@ -604,8 +608,8 @@ public class ImportSourceAnalyzer {
final Map<String, String> fileDb = _fileNameDb.get(listFile);
_analyzeListedDir(root, targetDir, new _ListedAnalyzer() {
@Override public String map(String filename) { return fileDb.containsKey(filename) ? fileDb.get(filename) : null; }
@Override public OpType getOpType(String filename) { return opType; }
@Override public String map(final String filename) { return fileDb.containsKey(filename) ? fileDb.get(filename) : null; }
@Override public OpType getOpType(final String filename) { return opType; }
});
}
@@ -614,28 +618,28 @@ public class ImportSourceAnalyzer {
abstract OpType getOpType(String filename);
// returns whether the directory has been handled
boolean onDir(File dir) { return false; }
boolean onDir(final File dir) { return false; }
}
private void _analyzeListedDir(File root, final String targetDir, final _ListedAnalyzer listedAnalyzer) {
private void _analyzeListedDir(final File root, final String targetDir, final _ListedAnalyzer listedAnalyzer) {
_analyzeDir(root, new _Analyzer() {
@Override void onFile(File file) {
String filename = listedAnalyzer.map(file.getName());
@Override void onFile(final File file) {
final String filename = listedAnalyzer.map(file.getName());
if (null != filename) {
File targetFile = new File(targetDir, filename);
final File targetFile = new File(targetDir, filename);
if (!file.equals(targetFile)) {
_cb.addOp(listedAnalyzer.getOpType(filename), file, targetFile);
}
}
}
@Override boolean onDir(File dir) { return listedAnalyzer.onDir(dir); }
@Override boolean onDir(final File dir) { return listedAnalyzer.onDir(dir); }
});
}
private int _countFiles(File root) {
private int _countFiles(final File root) {
int count = 0;
for (File file : root.listFiles()) {
for (final File file : root.listFiles()) {
if (_cb.checkCancel()) { return 0; }
if (file.isFile()) {
@@ -647,13 +651,13 @@ public class ImportSourceAnalyzer {
return count;
}
private String _lcaseExt(String filename) {
int lastDotIdx = filename.lastIndexOf('.');
private static String _lcaseExt(final String filename) {
final int lastDotIdx = filename.lastIndexOf('.');
if (0 > lastDotIdx) {
return filename;
}
String basename = filename.substring(0, lastDotIdx);
String ext = filename.substring(lastDotIdx).toLowerCase(Locale.ENGLISH);
final String basename = filename.substring(0, lastDotIdx);
final String ext = filename.substring(lastDotIdx).toLowerCase(Locale.ENGLISH);
if (filename.endsWith(ext)) {
return filename;
}

View File

@@ -18,6 +18,24 @@
package forge.gui;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
@@ -27,17 +45,6 @@ import forge.toolbox.FMouseAdapter;
import forge.toolbox.FOptionPane;
import forge.toolbox.FScrollPane;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.List;
/**
* A simple class that shows a list of choices in a dialog. Two properties
* influence the behavior of a list chooser: minSelection and maxSelection.
@@ -46,8 +53,8 @@ import java.util.List;
* and the choice doesn't matter.
* <ul>
* <li>If minSelection is 0, there will be a Cancel button.</li>
* <li>If minSelection is -1, 0 or 1, double-clicking a choice will also close the
* dialog.</li>
* <li>If minSelection is -1, 0 or 1, double-clicking a choice will also close
* the dialog.</li>
* <li>If the number of selections is out of bounds, the "OK" button is
* disabled.</li>
* <li>The dialog was "committed" if "OK" was clicked or a choice was double
@@ -64,15 +71,15 @@ import java.util.List;
*/
public class ListChooser<T> {
// Data and number of choices for the list
private List<T> list;
private int minChoices, maxChoices;
private final List<T> list;
private final int minChoices, maxChoices;
// Flag: was the dialog already shown?
private boolean called;
// initialized before; listeners may be added to it
private FList<T> lstChoices;
private FOptionPane optionPane;
private final FList<T> lstChoices;
private final FOptionPane optionPane;
public ListChooser(final String title, final int minChoices, final int maxChoices, final Collection<T> list, final Function<T, String> display) {
FThreads.assertExecutedByEdt(true);
@@ -97,7 +104,7 @@ public class ListChooser<T> {
this.lstChoices.setCellRenderer(new TransformedCellRenderer(display));
}
FScrollPane listScroller = new FScrollPane(this.lstChoices, true);
final FScrollPane listScroller = new FScrollPane(this.lstChoices, true);
int minWidth = this.lstChoices.getAutoSizeWidth();
if (this.lstChoices.getModel().getSize() > this.lstChoices.getVisibleRowCount()) {
minWidth += listScroller.getVerticalScrollBar().getPreferredSize().width;
@@ -120,16 +127,14 @@ public class ListChooser<T> {
}
this.lstChoices.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
@Override public void keyPressed(final KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
ListChooser.this.commit();
}
}
});
this.lstChoices.addMouseListener(new FMouseAdapter() {
@Override
public void onLeftClick(MouseEvent e) {
@Override public void onLeftClick(final MouseEvent e) {
if (e.getClickCount() == 2) {
ListChooser.this.commit();
}
@@ -250,7 +255,7 @@ public class ListChooser<T> {
if (!this.called) {
throw new IllegalStateException("not yet shown");
}
return (T) this.lstChoices.getSelectedValue();
return this.lstChoices.getSelectedValue();
}
/**
@@ -302,7 +307,7 @@ public class ListChooser<T> {
* @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
*/
@Override
public Component getListCellRendererComponent(JList<? extends T> list, T value, int index, boolean isSelected, boolean cellHasFocus) {
public Component getListCellRendererComponent(final JList<? extends T> list, final T value, final int index, final boolean isSelected, final boolean cellHasFocus) {
// TODO Auto-generated method stub
return defRenderer.getListCellRendererComponent(list, transformer.apply(value), index, isSelected, cellHasFocus);
}

View File

@@ -17,8 +17,10 @@
*/
package forge.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.Rectangle;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
/**
* A {@link JLabel} with support for multi-line text that wraps when the line

View File

@@ -17,12 +17,11 @@
*/
package forge.gui;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.LabelUI;
import javax.swing.plaf.basic.BasicLabelUI;
import javax.swing.text.*;
import java.awt.*;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.beans.PropertyChangeEvent;
@@ -30,6 +29,20 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.plaf.LabelUI;
import javax.swing.plaf.basic.BasicLabelUI;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.PlainDocument;
import javax.swing.text.Segment;
import javax.swing.text.Utilities;
import javax.swing.text.View;
/**
* Label UI delegate that supports multiple lines and line wrapping. Hard line
* breaks (<code>\n</code>) are preserved. If the dimensions of the label is too
@@ -95,17 +108,6 @@ public class MultiLineLabelUI extends BasicLabelUI implements ComponentListener
*/
private static int defaultSize = 4;
/**
* Get the shared UI instance.
*
* @param c
* the c
* @return a ComponentUI
*/
public static ComponentUI createUI(final JComponent c) {
return MultiLineLabelUI.getLabelUI();
}
/** {@inheritDoc} */
@Override
protected void uninstallDefaults(final JLabel c) {
@@ -590,16 +592,6 @@ public class MultiLineLabelUI extends BasicLabelUI implements ComponentListener
return MultiLineLabelUI.labelUI;
}
/**
* Sets the label ui.
*
* @param labelUI
* the new label ui
*/
public static void setLabelUI(final LabelUI labelUI) {
MultiLineLabelUI.labelUI = labelUI;
}
/**
* Static singleton {@link Segment} cache.
*

View File

@@ -2,14 +2,12 @@ package forge.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
import net.miginfocom.swing.MigLayout;
import forge.Singletons;
@@ -19,7 +17,6 @@ import forge.toolbox.FOverlay;
import forge.toolbox.FPanel;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinnedButton;
import forge.toolbox.FSkin.SkinnedLabel;
/**
* All overlay interaction is handled here.
@@ -27,7 +24,12 @@ import forge.toolbox.FSkin.SkinnedLabel;
* <br><br><i>(S at beginning of class name denotes a static factory.)</i>
*/
public final class SOverlayUtils {
private static int counter = 0;
/**
* Private constructor to prevent instantiation.
*/
private SOverlayUtils() {
}
/**
* A standardized overlay for a game start condition.
@@ -57,46 +59,6 @@ public final class SOverlayUtils {
overlay.add(pnl);
}
/**
* A standardized overlay for a loading condition (note: thread issues, as of 1-Mar-12).
* @param msg0 &emsp; {@link java.lang.String}
* @return {@link javax.swing.JPanel}
*/
// NOTE: This animation happens on the EDT; if the EDT is tied up doing something
// else, the animation is effectively frozen. So, this needs some work.
public static JPanel loadingOverlay(final String msg0) {
final JPanel overlay = SOverlayUtils.genericOverlay();
final FPanel pnlLoading = new FPanel();
final int w = overlay.getWidth();
final int h = overlay.getHeight();
final SkinnedLabel lblLoading = new SkinnedLabel("");
lblLoading.setOpaque(true);
lblLoading.setBackground(FSkin.getColor(FSkin.Colors.CLR_TEXT));
lblLoading.setMinimumSize(new Dimension(0, 20));
pnlLoading.setBounds(((w - 170) / 2), ((h - 80) / 2), 170, 80);
pnlLoading.setLayout(new MigLayout("wrap, align center"));
pnlLoading.add(new FLabel.Builder().fontSize(18)
.text(msg0).build(), "h 20px!, w 140px!, gap 0 0 5px 0");
pnlLoading.add(lblLoading, "gap 0 0 0 10px");
overlay.add(pnlLoading);
SOverlayUtils.counter = 0;
final Timer timer = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
lblLoading.setMinimumSize(new Dimension(10 * (SOverlayUtils.counter++), 20));
lblLoading.revalidate();
if (SOverlayUtils.counter > 13) { SOverlayUtils.counter = 0; }
}
});
timer.start();
return overlay;
}
/**
* A template overlay with close button, null layout, ready for anything.
* @return {@link javax.swing.JPanel}
@@ -113,7 +75,7 @@ public final class SOverlayUtils {
btnCloseTopRight.setBackground(new Color(0, 0, 0));
btnCloseTopRight.setFocusPainted(false);
btnCloseTopRight.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent arg0) { SOverlayUtils.hideOverlay(); } });
public void actionPerformed(final ActionEvent arg0) { SOverlayUtils.hideOverlay(); } });
overlay.removeAll();
overlay.setLayout(null);

View File

@@ -1,18 +1,21 @@
package forge.gui;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.ListModel;
import com.google.common.collect.Lists;
@SuppressWarnings("serial")
public class UnsortedListModel<T> extends AbstractListModel<T> {
List<T> model;
final List<T> model;
public UnsortedListModel() {
model = new ArrayList<T>();
model = Lists.newArrayList();
}
@Override
@@ -21,25 +24,17 @@ public class UnsortedListModel<T> extends AbstractListModel<T> {
}
@Override
public T getElementAt(int index) {
public T getElementAt(final int index) {
return model.get(index);
}
public void add(T element) {
public void add(final T element) {
model.add(element);
fireIntervalAdded(this, getSize() - 1, getSize() - 1);
fireContentsChanged(this, 0, getSize() - 1);
}
public void addAll(T[] elements) {
for (T e : elements) {
model.add(e);
}
fireIntervalAdded(this, getSize() - elements.length, getSize() - 1);
fireContentsChanged(this, 0, getSize() - 1);
}
public void addAll(Collection<T> elements) {
public void addAll(final Collection<T> elements) {
if (elements.isEmpty()) {
return;
}
@@ -48,23 +43,23 @@ public class UnsortedListModel<T> extends AbstractListModel<T> {
fireContentsChanged(this, 0, getSize() - 1);
}
public void addAll(ListModel<T> otherModel) {
Collection<T> elements = new ArrayList<T>();
int size = otherModel.getSize();
public void addAll(final ListModel<T> otherModel) {
final Collection<T> elements = new ArrayList<T>();
final int size = otherModel.getSize();
for (int i = 0; size > i; ++i) {
elements.add((T)otherModel.getElementAt(i));
elements.add(otherModel.getElementAt(i));
}
addAll(elements);
}
public void clear() {
int prevSize = getSize();
final int prevSize = getSize();
model.clear();
fireIntervalRemoved(this, 0, prevSize - 1);
fireContentsChanged(this, 0, prevSize - 1);
}
public boolean contains(Object element) {
public boolean contains(final Object element) {
return model.contains(element);
}
@@ -72,7 +67,7 @@ public class UnsortedListModel<T> extends AbstractListModel<T> {
return model.iterator();
}
public void removeElement(int idx) {
public void removeElement(final int idx) {
model.remove(idx);
fireIntervalRemoved(this, idx, idx);
fireContentsChanged(this, 0, getSize());

View File

@@ -1,7 +1,13 @@
package forge.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
/**
* FlowLayout subclass that fully supports wrapping of components.
@@ -24,7 +30,7 @@ public class WrapLayout extends FlowLayout {
* or <code>FlowLayout.RIGHT</code>.
* @param align the alignment value
*/
public WrapLayout(int align) {
public WrapLayout(final int align) {
super(align);
}
@@ -39,7 +45,7 @@ public class WrapLayout extends FlowLayout {
* @param hgap the horizontal gap between components
* @param vgap the vertical gap between components
*/
public WrapLayout(int align, int hgap, int vgap) {
public WrapLayout(final int align, final int hgap, final int vgap) {
super(align, hgap, vgap);
}
@@ -51,7 +57,7 @@ public class WrapLayout extends FlowLayout {
* subcomponents of the specified container
*/
@Override
public Dimension preferredLayoutSize(Container target) {
public Dimension preferredLayoutSize(final Container target) {
return layoutSize(target, true);
}
@@ -63,8 +69,8 @@ public class WrapLayout extends FlowLayout {
* subcomponents of the specified container
*/
@Override
public Dimension minimumLayoutSize(Container target) {
Dimension minimum = layoutSize(target, false);
public Dimension minimumLayoutSize(final Container target) {
final Dimension minimum = layoutSize(target, false);
minimum.width -= (getHgap() + 1);
return minimum;
}
@@ -77,7 +83,7 @@ public class WrapLayout extends FlowLayout {
* @param preferred should preferred size be calculated
* @return the dimension to layout the target container
*/
private Dimension layoutSize(Container target, boolean preferred) {
private Dimension layoutSize(final Container target, final boolean preferred) {
synchronized (target.getTreeLock()) {
// Each row must fit with the width allocated to the container.
// When the container width = 0, the preferred width of the container
@@ -85,26 +91,26 @@ public class WrapLayout extends FlowLayout {
// than we need so that it gets recalculated later when the widget is
// shown.
int hgap = getHgap();
Insets insets = target.getInsets();
int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
int targetWidth = Math.max(horizontalInsetsAndGap, target.getSize().width);
int maxWidth = targetWidth - horizontalInsetsAndGap;
final int hgap = getHgap();
final Insets insets = target.getInsets();
final int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
final int targetWidth = Math.max(horizontalInsetsAndGap, target.getSize().width);
final int maxWidth = targetWidth - horizontalInsetsAndGap;
// Fit components into the allowed width
Dimension dim = new Dimension(0, 0);
final Dimension dim = new Dimension(0, 0);
int rowWidth = 0;
int rowHeight = 0;
final int nmembers = target.getComponentCount();
for (int i = 0; i < nmembers; i++) {
Component m = target.getComponent(i);
final Component m = target.getComponent(i);
if (!m.isVisible()) {
continue;
}
Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
final Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
// can't add the component to current row. Start a new row if
// there's at least one component in this row.
@@ -134,7 +140,7 @@ public class WrapLayout extends FlowLayout {
// target container so shrinking the container size works
// correctly. Removing the horizontal gap is an easy way to do this.
Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
final Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
if (scrollPane != null) {
dim.width -= (hgap + 1);
@@ -152,7 +158,7 @@ public class WrapLayout extends FlowLayout {
* @param rowWidth the width of the row to add
* @param rowHeight the height of the row to add
*/
private void addRow(Dimension dim, int rowWidth, int rowHeight) {
private void addRow(final Dimension dim, final int rowWidth, final int rowHeight) {
dim.width = Math.max(dim.width, rowWidth);
if (dim.height > 0) {

View File

@@ -1,21 +1,11 @@
package forge.gui.framework;
import forge.UiCommand;
/**
* An intentionally empty ICDoc to fill field slots unused
* by the current layout of a match UI.
*/
public class CEmptyDoc implements ICDoc {
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
@Override
public void register() {
}

View File

@@ -1,5 +1,20 @@
package forge.gui.framework;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import com.google.common.collect.Lists;
import forge.assets.FSkinProp;
@@ -10,15 +25,6 @@ import forge.toolbox.FPanel;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinImage;
import forge.view.FView;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
/**
* Top-level container in drag layout. A cell holds
@@ -49,9 +55,6 @@ public final class DragCell extends JPanel implements ILocalRepaint {
private final JLabel lblOverflow = new JLabel();
private IVDoc<? extends ICDoc> docSelected = null;
/**
*
*/
public DragCell() {
super(new MigLayout("insets 0, gap 0, wrap 2"));
@@ -89,10 +92,10 @@ public final class DragCell extends JPanel implements ILocalRepaint {
* <p>
* Primarily used to toggle visibility of tabs.
*/
public void doCellLayout(boolean showTabs) {
public void doCellLayout(final boolean showTabs) {
this.removeAll();
int borderT = SLayoutConstants.BORDER_T;
int headH = ((showTabs || allDocs.size() > 1) ? SLayoutConstants.HEAD_H : 0);
final int borderT = SLayoutConstants.BORDER_T;
final int headH = ((showTabs || allDocs.size() > 1) ? SLayoutConstants.HEAD_H : 0);
this.add(pnlHead,
"w 100% - " + borderT + "px!" + ", " + "h " + headH + "px!");
this.add(pnlBorderRight,
@@ -109,8 +112,8 @@ public final class DragCell extends JPanel implements ILocalRepaint {
/**
* Determines visibility of tabs on game screen.
*/
private boolean showGameTabs() {
ForgePreferences prefs = FModel.getPreferences();
private static boolean showGameTabs() {
final ForgePreferences prefs = FModel.getPreferences();
return !prefs.getPrefBoolean(FPref.UI_HIDE_GAME_TABS);
}
@@ -229,7 +232,7 @@ public final class DragCell extends JPanel implements ILocalRepaint {
* @param w0 &emsp; double
* @param h0 &emsp; double
*/
public void setRoughBounds(RectangleOfDouble rectangleOfDouble) {
public void setRoughBounds(final RectangleOfDouble rectangleOfDouble) {
this.roughSize = rectangleOfDouble;
}
@@ -283,7 +286,7 @@ public final class DragCell extends JPanel implements ILocalRepaint {
/** Removes a document from the layout and tabs.
* @param doc0 &emsp; {@link forge.gui.framework.IVDoc} */
public void removeDoc(final IVDoc<? extends ICDoc> doc0) {
boolean wasSelected = (docSelected == doc0);
final boolean wasSelected = (docSelected == doc0);
allDocs.remove(doc0);
pnlHead.remove(doc0.getTabLabel());
if (wasSelected) { //after removing selected doc, select most recent doc if possible
@@ -342,32 +345,6 @@ public final class DragCell extends JPanel implements ILocalRepaint {
return docSelected;
}
/**
* Enable/disable resize on the X axis for this cell.
*
* @param enable0 &emsp; boolean
*/
public void toggleResizeX(final boolean enable0) {
this.removeMouseListener(SResizingUtil.getResizeXListener());
if (enable0) {
this.addMouseListener(SResizingUtil.getResizeXListener());
}
}
/**
* Enable/disable resize on the Y axis for this cell.
*
* @param enable0 &emsp; boolean
*/
public void toggleResizeY(final boolean enable0) {
this.removeMouseListener(SResizingUtil.getResizeYListener());
if (enable0) {
this.addMouseListener(SResizingUtil.getResizeYListener());
}
}
/**
* Refreshes visual display of head bar.
*/

View File

@@ -81,15 +81,6 @@ public class FScreen {
"Close Editor",
ForgeConstants.EDITOR_LAYOUT_FILE,
false);
public static final FScreen DECK_EDITOR_VANGUARD = new FScreen(
VDeckEditorUI.SINGLETON_INSTANCE,
CDeckEditorUI.SINGLETON_INSTANCE,
"Vanguard Deck Editor",
FSkin.getImage(FSkinProp.IMG_PACK),
true,
"Close Editor",
ForgeConstants.EDITOR_LAYOUT_FILE,
false);
public static final FScreen DECK_EDITOR_DRAFT = new FScreen(
VDeckEditorUI.SINGLETON_INSTANCE,
CDeckEditorUI.SINGLETON_INSTANCE,
@@ -226,7 +217,7 @@ public class FScreen {
return closeButtonTooltip;
}
public boolean onSwitching(FScreen toScreen) {
public boolean onSwitching(final FScreen toScreen) {
return view.onSwitching(this, toScreen);
}
@@ -247,7 +238,7 @@ public class FScreen {
}
private static boolean deleteLayoutFile(final FileLocation file) {
try {
File f = new File(file.userPrefLoc);
final File f = new File(file.userPrefLoc);
f.delete();
return true;
} catch (final Exception e) {
@@ -258,10 +249,6 @@ public class FScreen {
}
public void open() {
Singletons.getControl().setCurrentScreen(this);
}
public void close() {
Singletons.getView().getNavigationBar().closeTab(this);
}

View File

@@ -1,7 +1,5 @@
package forge.gui.framework;
import forge.UiCommand;
/**
* Dictates methods required for any controller of an
* {@link forge.gui.framework.IVDoc}.
@@ -12,14 +10,6 @@ import forge.UiCommand;
* <i>(C at beginning of class name denotes a controller class.)</i>
*/
public interface ICDoc {
/**
* Fires when this controller's view tab is selected. Since this method is
* fired when all tabs are first initialized, be wary of NPEs created by
* referring to non-existent components.
*
* @return {@link forge.UiCommand}
*/
UiCommand getCommandOnSelect();
/**
* Asks this controller to register its docs, so that a layout can be

View File

@@ -1,12 +0,0 @@
/**
*
*/
package forge.gui.framework;
/**
* This interface provides a unifying type to all enums
* used as tab identifiers in XML and card layouts.
*
* <br><br><i>(I at beginning of class name denotes an interface.)</i>
*/
public interface IDocIdList { }

View File

@@ -1,14 +1,25 @@
package forge.gui.framework;
import java.awt.Color;
import java.awt.Component;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import forge.FThreads;
import forge.view.FFrame;
import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;
/**
* Experimental static factory for generic operations carried out
* onto specific members of the framework. Doublestrike 11-04-12
@@ -55,21 +66,22 @@ public class SDisplayUtil {
}
final TimerTask tt = new TimerTask() {
@Override
public void run() {
@Override public final void run() {
counter++;
if (counter != (steps - 1)) {
SwingUtilities.invokeLater(new Runnable() { @Override
public void run() {
int r = newR == null ? oldR : newR[counter];
int a = newA == null ? oldA : newR[counter];
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
final int r = newR == null ? oldR : newR[counter];
final int a = newA == null ? oldA : newR[counter];
pnl.setBackground(new Color(r, oldG, oldB, a));
}
});
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
pnl.setBackground(new Color(oldR, oldG, oldB, oldA));
}
else {
SwingUtilities.invokeLater(new Runnable() { @Override
public void run() { pnl.setBackground(new Color(oldR, oldG, oldB, oldA)); } });
});
remindIsRunning = false;
timer1.cancel();
newR = null;
@@ -87,14 +99,14 @@ public class SDisplayUtil {
/** @param tab0 &emsp; {@link java.GuiBase.getInterface().framework.IVDoc} */
public static void showTab(final IVDoc<? extends ICDoc> tab0) {
Runnable showTabRoutine = new Runnable() {
@Override
public void run() {
final Runnable showTabRoutine = new Runnable() {
@Override public void run() {
// FThreads.assertExecutedByEdt(true); - always true
Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
DragCell dc = tab0.getParentCell();
if (dc != null)
final Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
final DragCell dc = tab0.getParentCell();
if (dc != null) {
dc.setSelected(tab0);
}
// set focus back to previous owner, if any
if (null != c) {
c.requestFocusInWindow();
@@ -104,9 +116,9 @@ public class SDisplayUtil {
FThreads.invokeInEdtLater(showTabRoutine);
}
public static GraphicsDevice getGraphicsDevice(Point point) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
for (GraphicsDevice gd : env.getScreenDevices()) {
public static GraphicsDevice getGraphicsDevice(final Point point) {
final GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
for (final GraphicsDevice gd : env.getScreenDevices()) {
if (gd.getDefaultConfiguration().getBounds().contains(point)) {
return gd;
}
@@ -114,12 +126,12 @@ public class SDisplayUtil {
return null;
}
public static GraphicsDevice getGraphicsDevice(Rectangle rect) {
public static GraphicsDevice getGraphicsDevice(final Rectangle rect) {
return getGraphicsDevice(new Point(rect.x + (rect.width / 2), rect.y + (rect.height / 2)));
}
public static Rectangle getScreenBoundsForPoint(Point point) {
GraphicsDevice gd = getGraphicsDevice(point);
public static Rectangle getScreenBoundsForPoint(final Point point) {
final GraphicsDevice gd = getGraphicsDevice(point);
if (gd == null) {
//return bounds of default monitor if point not on any screen
return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
@@ -127,16 +139,16 @@ public class SDisplayUtil {
return gd.getDefaultConfiguration().getBounds();
}
public static Rectangle getScreenMaximizedBounds(Rectangle rect) {
GraphicsDevice gd = getGraphicsDevice(rect);
public static Rectangle getScreenMaximizedBounds(final Rectangle rect) {
final GraphicsDevice gd = getGraphicsDevice(rect);
if (gd == null) {
//return bounds of default monitor if center of rect not on any screen
return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
}
GraphicsConfiguration config = gd.getDefaultConfiguration();
Rectangle bounds = config.getBounds();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(config);
final GraphicsConfiguration config = gd.getDefaultConfiguration();
final Rectangle bounds = config.getBounds();
final Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(config);
bounds.x += screenInsets.left;
bounds.y += screenInsets.top;
bounds.width -= screenInsets.left + screenInsets.right;
@@ -144,15 +156,11 @@ public class SDisplayUtil {
return bounds;
}
public static boolean setFullScreenWindow(FFrame frame, boolean fullScreen) {
public static boolean setFullScreenWindow(final FFrame frame, final boolean fullScreen) {
return setFullScreenWindow(getGraphicsDevice(frame.getNormalBounds()), frame, fullScreen);
}
public static boolean setFullScreenWindow(Window window, boolean fullScreen) {
return setFullScreenWindow(getGraphicsDevice(window.getBounds()), window, fullScreen);
}
private static boolean setFullScreenWindow(GraphicsDevice gd, Window window, boolean fullScreen) {
private static boolean setFullScreenWindow(final GraphicsDevice gd, final Window window, final boolean fullScreen) {
if (gd != null && gd.isFullScreenSupported()) {
if (fullScreen) {
gd.setFullScreenWindow(window);

View File

@@ -78,8 +78,7 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
this.gameType = gt;
this.addSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
@Override public void valueChanged(final ListSelectionEvent e) {
if (cmdSelect != null) {
cmdSelect.run();
}
@@ -94,18 +93,19 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
});
}
@Override
public GameType getGameType() {
return gameType;
}
@Override
public void setup(ItemManagerConfig config0) {
boolean wasStringOnly = (this.getConfig() == ItemManagerConfig.STRING_ONLY);
boolean isStringOnly = (config0 == ItemManagerConfig.STRING_ONLY);
public void setup(final ItemManagerConfig config0) {
final boolean wasStringOnly = (this.getConfig() == ItemManagerConfig.STRING_ONLY);
final boolean isStringOnly = (config0 == ItemManagerConfig.STRING_ONLY);
Map<ColumnDef, ItemTableColumn> colOverrides = null;
if (config0.getCols().containsKey(ColumnDef.DECK_ACTIONS)) {
ItemTableColumn column = new ItemTableColumn(new ItemColumn(config0.getCols().get(ColumnDef.DECK_ACTIONS)));
final ItemTableColumn column = new ItemTableColumn(new ItemColumn(config0.getCols().get(ColumnDef.DECK_ACTIONS)));
column.setCellRenderer(new DeckActionsRenderer());
colOverrides = new HashMap<ColumnDef, ItemTableColumn>();
colOverrides.put(ColumnDef.DECK_ACTIONS, column);
@@ -148,17 +148,17 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
}
@Override
protected void buildAddFilterMenu(JMenu menu) {
protected void buildAddFilterMenu(final JMenu menu) {
GuiUtils.addSeparator(menu); //separate from current search item
Set<String> folders = new HashSet<String>();
final Set<String> folders = new HashSet<String>();
for (final Entry<DeckProxy, Integer> deckEntry : getPool()) {
String path = deckEntry.getKey().getPath();
final String path = deckEntry.getKey().getPath();
if (StringUtils.isNotEmpty(path)) { //don't include root folder as option
folders.add(path);
}
}
JMenu folder = GuiUtils.createMenu("Folder");
final JMenu folder = GuiUtils.createMenu("Folder");
if (folders.size() > 0) {
for (final String f : folders) {
GuiUtils.addMenuItem(folder, f, null, new Runnable() {
@@ -174,7 +174,7 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
}
menu.add(folder);
JMenu fmt = GuiUtils.createMenu("Format");
final JMenu fmt = GuiUtils.createMenu("Format");
for (final GameFormat f : FModel.getFormats().getOrderedList()) {
GuiUtils.addMenuItem(fmt, f.getName(), null, new Runnable() {
@Override
@@ -186,18 +186,15 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
menu.add(fmt);
GuiUtils.addMenuItem(menu, "Sets...", null, new Runnable() {
@Override
public void run() {
DeckSetFilter existingFilter = getFilter(DeckSetFilter.class);
@Override public void run() {
final DeckSetFilter existingFilter = getFilter(DeckSetFilter.class);
if (existingFilter != null) {
existingFilter.edit();
}
else {
} else {
final DialogChooseSets dialog = new DialogChooseSets(null, null, true);
dialog.setOkCallback(new Runnable() {
@Override
public void run() {
List<String> sets = dialog.getSelectedSets();
@Override public void run() {
final List<String> sets = dialog.getSelectedSets();
if (!sets.isEmpty()) {
addFilter(new DeckSetFilter(DeckManager.this, sets, dialog.getWantReprints()));
}
@@ -207,11 +204,10 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
}
});
JMenu world = GuiUtils.createMenu("Quest world");
final JMenu world = GuiUtils.createMenu("Quest world");
for (final QuestWorld w : FModel.getWorlds()) {
GuiUtils.addMenuItem(world, w.getName(), null, new Runnable() {
@Override
public void run() {
@Override public void run() {
addFilter(new DeckQuestWorldFilter(DeckManager.this, w));
}
}, DeckQuestWorldFilter.canAddQuestWorld(w, getFilter(DeckQuestWorldFilter.class)));
@@ -272,7 +268,7 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
CDeckEditorUI.SINGLETON_INSTANCE.getCurrentEditorController().getDeckController().load(deck.getPath(), deck.getName());
}
public boolean deleteDeck(DeckProxy deck) {
public boolean deleteDeck(final DeckProxy deck) {
if (deck == null) { return false; }
if (!FOptionPane.showConfirmDialog(
@@ -305,7 +301,7 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
}
public class DeckActionsRenderer extends ItemCellRenderer {
private int overActionIndex = -1;
private final int overActionIndex = -1;
private static final int imgSize = 20;
@Override
@@ -329,11 +325,11 @@ public final class DeckManager extends ItemManager<DeckProxy> implements IHasGam
@Override
public <T extends InventoryItem> void processMouseEvent(final MouseEvent e, final ItemListView<T> listView, final Object value, final int row, final int column) {
Rectangle cellBounds = listView.getTable().getCellRect(row, column, false);
int x = e.getX() - cellBounds.x;
final Rectangle cellBounds = listView.getTable().getCellRect(row, column, false);
final int x = e.getX() - cellBounds.x;
if (e.getID() == MouseEvent.MOUSE_PRESSED && e.getButton() == 1) {
DeckProxy deck = (DeckProxy) value;
final DeckProxy deck = (DeckProxy) value;
if (x >= 0 && x < imgSize) { //delete button
if (DeckManager.this.deleteDeck(deck)) {

View File

@@ -17,6 +17,33 @@
*/
package forge.itemmanager;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import net.miginfocom.swing.MigLayout;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
@@ -25,34 +52,24 @@ import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.gui.GuiUtils;
import forge.item.InventoryItem;
import forge.itemmanager.ColumnDef;
import forge.itemmanager.IItemManager;
import forge.itemmanager.ItemManagerConfig;
import forge.itemmanager.ItemManagerModel;
import forge.itemmanager.filters.ItemFilter;
import forge.itemmanager.views.*;
import forge.itemmanager.views.ImageView;
import forge.itemmanager.views.ItemListView;
import forge.itemmanager.views.ItemTableColumn;
import forge.itemmanager.views.ItemView;
import forge.screens.match.controllers.CDetailPicture;
import forge.toolbox.*;
import forge.toolbox.ContextMenuBuilder;
import forge.toolbox.FLabel;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.Colors;
import forge.toolbox.FSkin.SkinIcon;
import forge.toolbox.FSkin.SkinnedCheckBox;
import forge.toolbox.FSkin.SkinnedPanel;
import forge.toolbox.FTextField;
import forge.toolbox.LayoutHelper;
import forge.util.Aggregates;
import forge.util.ItemPool;
import forge.util.ReflectionUtil;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.util.Map.Entry;
/**
* ItemManager.
@@ -108,7 +125,8 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
private static final SkinIcon VIEW_OPTIONS_ICON = FSkin.getIcon(FSkinProp.ICO_SETTINGS).resize(20, 20);
private final FLabel btnViewOptions = new FLabel.Builder()
.hoverable().selectable(true)
.hoverable()
.selectable(true)
.icon(VIEW_OPTIONS_ICON).iconScaleAuto(false)
.tooltip("Toggle to show/hide options for current view")
.build();
@@ -167,11 +185,10 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
this.chkEnableFilters.setText("(*)");
this.chkEnableFilters.setSelected(true);
this.chkEnableFilters.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent arg0) {
@Override public void itemStateChanged(final ItemEvent arg0) {
lockFiltering = true;
boolean enabled = chkEnableFilters.isSelected();
for (ItemFilter<? extends T> filter : orderedFilters) {
final boolean enabled = chkEnableFilters.isSelected();
for (final ItemFilter<? extends T> filter : orderedFilters) {
filter.setEnabled(enabled);
}
txtFilterLogic.setEnabled(enabled);
@@ -194,7 +211,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
this.add(this.btnFilters);
this.add(this.lblCaption);
this.add(this.lblRatio);
for (ItemView<T> view : this.views) {
for (final ItemView<T> view : this.views) {
this.add(view.getButton());
view.getButton().setSelected(view == this.currentView);
}
@@ -204,9 +221,8 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
this.add(this.currentView.getScroller());
final Runnable cmdAddCurrentSearch = new Runnable() {
@Override
public void run() {
ItemFilter<? extends T> searchFilter = mainSearchFilter.createCopy();
@Override public void run() {
final ItemFilter<? extends T> searchFilter = mainSearchFilter.createCopy();
if (searchFilter != null) {
lockFiltering = true; //prevent updating filtering from this change
addFilter(searchFilter);
@@ -216,8 +232,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
}
};
final Runnable cmdResetFilters = new Runnable() {
@Override
public void run() {
@Override public void run() {
resetFilters();
SwingUtilities.invokeLater(new Runnable() {
@Override
@@ -228,8 +243,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
}
};
final Runnable cmdHideFilters = new Runnable() {
@Override
public void run() {
@Override public void run() {
setHideFilters(!getHideFilters());
SwingUtilities.invokeLater(new Runnable() {
@Override
@@ -241,8 +255,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
};
this.mainSearchFilter.getMainComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
@Override public void keyPressed(final KeyEvent e) {
if (e.getKeyCode() == 10) {
if (e.isControlDown() || e.isMetaDown()) {
cmdAddCurrentSearch.run();
@@ -253,14 +266,12 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
//setup command for btnFilters
final UiCommand cmdBuildFilterMenu = new UiCommand() {
@Override
public void run() {
JPopupMenu menu = new JPopupMenu("FilterMenu");
@Override public void run() {
final JPopupMenu menu = new JPopupMenu("FilterMenu");
if (hideFilters) {
GuiUtils.addMenuItem(menu, "Show Filters", null, cmdHideFilters);
}
else {
JMenu addMenu = GuiUtils.createMenu("Add");
} else {
final JMenu addMenu = GuiUtils.createMenu("Add");
if (mainSearchFilter.isEnabled()) {
GuiUtils.addMenuItem(addMenu, "Current text search",
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
@@ -268,8 +279,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
if (config != ItemManagerConfig.STRING_ONLY) {
buildAddFilterMenu(addMenu);
}
}
else {
} else {
addMenu.setEnabled(false);
}
menu.add(addMenu);
@@ -284,8 +294,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
this.btnFilters.setRightClickCommand(cmdBuildFilterMenu); //show menu on right-click too
this.btnViewOptions.setCommand(new Runnable() {
@Override
public void run() {
@Override public void run() {
currentView.getPnlOptions().setVisible(!currentView.getPnlOptions().isVisible());
revalidate();
}
@@ -302,26 +311,28 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
}
}
@Override
public ItemManagerConfig getConfig() {
return this.config;
}
public void setup(ItemManagerConfig config0) {
@Override
public void setup(final ItemManagerConfig config0) {
this.setup(config0, null);
}
public void setup(ItemManagerConfig config0, Map<ColumnDef, ItemTableColumn> colOverrides) {
public void setup(final ItemManagerConfig config0, final Map<ColumnDef, ItemTableColumn> colOverrides) {
this.config = config0;
this.setWantUnique(config0.getUniqueCardsOnly());
for (ItemView<T> view : this.views) {
for (final ItemView<T> view : this.views) {
view.setup(config0, colOverrides);
}
this.setViewIndex(config0.getViewIndex());
this.setHideFilters(config0.getHideFilters());
}
public void setViewIndex(int viewIndex) {
public void setViewIndex(final int viewIndex) {
if (viewIndex < 0 || viewIndex >= this.views.size()) { return; }
ItemView<T> view = this.views.get(viewIndex);
final ItemView<T> view = this.views.get(viewIndex);
if (this.currentView == view) { return; }
if (this.config != null) {
@@ -355,19 +366,19 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
this.focus();
}
public void setHideViewOptions(int viewIndex, boolean hideViewOptions) {
public void setHideViewOptions(final int viewIndex, final boolean hideViewOptions) {
if (viewIndex < 0 || viewIndex >= this.views.size()) { return; }
this.views.get(viewIndex).getPnlOptions().setVisible(!hideViewOptions);
}
@Override
public void doLayout() {
int buttonPanelHeight = 32;
LayoutHelper helper = new LayoutHelper(this);
final int buttonPanelHeight = 32;
final LayoutHelper helper = new LayoutHelper(this);
boolean showButtonPanel = false;
if (this.pnlButtons.isVisible()) {
for (Component comp : this.pnlButtons.getComponents()) {
for (final Component comp : this.pnlButtons.getComponents()) {
if (comp.isVisible()) {
showButtonPanel = true;
break;
@@ -379,15 +390,13 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
if (showButtonPanel) {
helper.offset(0, -4);
helper.fillLine(this.pnlButtons, buttonPanelHeight);
}
else {
} else {
this.pnlButtons.setBounds(0, 0, 0, 0); //prevent horizontal line appearing
}
}
else {
} else {
int number = 0;
StringBuilder logicBuilder = new StringBuilder();
for (ItemFilter<? extends T> filter : this.orderedFilters) {
final StringBuilder logicBuilder = new StringBuilder();
for (final ItemFilter<? extends T> filter : this.orderedFilters) {
filter.setNumber(++number);
logicBuilder.append(number + "&");
helper.fillLine(filter.getPanel(), ItemFilter.PANEL_HEIGHT);
@@ -405,20 +414,19 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
helper.offset(1, 0); //align filters button with expand/collapse all button
helper.include(this.btnFilters, 61, FTextField.HEIGHT);
int captionWidth = this.lblCaption.getAutoSizeWidth();
int ratioWidth = this.lblRatio.getAutoSizeWidth();
int viewButtonWidth = FTextField.HEIGHT;
int viewButtonCount = this.views.size() + 1;
int availableCaptionWidth = helper.getParentWidth() - viewButtonWidth * viewButtonCount - ratioWidth - helper.getX() - (viewButtonCount + 2) * helper.getGapX();
final int ratioWidth = this.lblRatio.getAutoSizeWidth();
final int viewButtonWidth = FTextField.HEIGHT;
final int viewButtonCount = this.views.size() + 1;
final int availableCaptionWidth = helper.getParentWidth() - viewButtonWidth * viewButtonCount - ratioWidth - helper.getX() - (viewButtonCount + 2) * helper.getGapX();
if (captionWidth > availableCaptionWidth) { //truncate caption if not enough room for it
this.lblCaption.setToolTipText(this.lblCaption.getText());
captionWidth = availableCaptionWidth;
}
else {
} else {
this.lblCaption.setToolTipText(null);
}
helper.include(this.lblCaption, captionWidth, FTextField.HEIGHT);
helper.fillLine(this.lblRatio, FTextField.HEIGHT, (viewButtonWidth + helper.getGapX()) * viewButtonCount - viewButtonCount + 1); //leave room for view buttons
for (ItemView<T> view : this.views) {
for (final ItemView<T> view : this.views) {
helper.include(view.getButton(), viewButtonWidth, FTextField.HEIGHT);
helper.offset(-1, 0);
}
@@ -436,6 +444,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return generic type of items
*/
@Override
public Class<T> getGenericType() {
return this.genericType;
}
@@ -446,6 +455,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return caption to display before ratio
*/
@Override
public String getCaption() {
return this.lblCaption.getText();
}
@@ -456,7 +466,8 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param caption - caption to display before ratio
*/
public void setCaption(String caption) {
@Override
public void setCaption(final String caption) {
this.lblCaption.setText(caption);
}
@@ -466,6 +477,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return ItemPoolView
*/
@Override
public ItemPool<T> getPool() {
return this.pool;
}
@@ -476,6 +488,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param items
*/
@Override
public void setPool(final Iterable<T> items) {
this.setPool(ItemPool.createFrom(items, this.genericType), false);
}
@@ -487,10 +500,12 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
* @param poolView
* @param infinite
*/
public void setPool(final ItemPool<T> poolView, boolean infinite) {
@Override
public void setPool(final ItemPool<T> poolView, final boolean infinite) {
this.setPoolImpl(ItemPool.createFrom(poolView, this.genericType), infinite);
}
@Override
public void setPool(final ItemPool<T> pool0) {
this.setPoolImpl(pool0, false);
}
@@ -502,7 +517,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
* @param pool0
* @param infinite
*/
private void setPoolImpl(final ItemPool<T> pool0, boolean infinite) {
private void setPoolImpl(final ItemPool<T> pool0, final boolean infinite) {
this.model.clear();
this.pool = pool0;
this.model.addItems(this.pool);
@@ -520,6 +535,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return int
*/
@Override
public int getItemCount() {
return this.currentView.getCount();
}
@@ -530,6 +546,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return int
*/
@Override
public int getSelectionCount() {
return this.currentView.getSelectionCount();
}
@@ -540,6 +557,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return T
*/
@Override
public T getSelectedItem() {
return this.currentView.getSelectedItem();
}
@@ -550,6 +568,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return Iterable<T>
*/
@Override
public Collection<T> getSelectedItems() {
return this.currentView.getSelectedItems();
}
@@ -560,9 +579,10 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return ItemPool<T>
*/
@Override
public ItemPool<T> getSelectedItemPool() {
ItemPool<T> selectedItemPool = new ItemPool<T>(this.genericType);
for (T item : getSelectedItems()) {
final ItemPool<T> selectedItemPool = new ItemPool<T>(this.genericType);
for (final T item : getSelectedItems()) {
selectedItemPool.add(item, getItemCount(item));
}
return selectedItemPool;
@@ -574,7 +594,8 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param item - Item to select
*/
public boolean setSelectedItem(T item) {
@Override
public boolean setSelectedItem(final T item) {
return this.currentView.setSelectedItem(item);
}
@@ -584,7 +605,8 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param items - Items to select
*/
public boolean setSelectedItems(Iterable<T> items) {
@Override
public boolean setSelectedItems(final Iterable<T> items) {
return this.currentView.setSelectedItems(items);
}
@@ -594,10 +616,13 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param str - String to get item corresponding to
*/
public T stringToItem(String str) {
if (this.pool == null) { return null; }
@Override
public T stringToItem(final String str) {
if (this.pool == null) {
return null;
}
for (Entry<T, Integer> itemEntry : this.pool) {
for (final Entry<T, Integer> itemEntry : this.pool) {
if (itemEntry.getKey().toString().equals(str)) {
return itemEntry.getKey();
}
@@ -611,8 +636,9 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param str - String to select
*/
public boolean setSelectedString(String str) {
T item = stringToItem(str);
@Override
public boolean setSelectedString(final String str) {
final T item = stringToItem(str);
if (item != null) {
return this.setSelectedItem(item);
}
@@ -625,10 +651,11 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param strings - Strings to select
*/
public boolean setSelectedStrings(Iterable<String> strings) {
List<T> items = new ArrayList<T>();
for (String str : strings) {
T item = stringToItem(str);
@Override
public boolean setSelectedStrings(final Iterable<String> strings) {
final List<T> items = new ArrayList<T>();
for (final String str : strings) {
final T item = stringToItem(str);
if (item != null) {
items.add(item);
}
@@ -642,9 +669,10 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param itemEntrys - Item entrys to select
*/
public boolean selectItemEntrys(Iterable<Entry<T, Integer>> itemEntrys) {
List<T> items = new ArrayList<T>();
for (Entry<T, Integer> itemEntry : itemEntrys) {
@Override
public boolean selectItemEntrys(final Iterable<Entry<T, Integer>> itemEntrys) {
final List<T> items = new ArrayList<T>();
for (final Entry<T, Integer> itemEntry : itemEntrys) {
items.add(itemEntry.getKey());
}
return this.setSelectedItems(items);
@@ -655,6 +683,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
* selectAll.
*
*/
@Override
public void selectAll() {
this.currentView.selectAll();
}
@@ -665,6 +694,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return T
*/
@Override
public int getSelectedIndex() {
return this.currentView.getSelectedIndex();
}
@@ -675,6 +705,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return Iterable<Integer>
*/
@Override
public Iterable<Integer> getSelectedIndices() {
return this.currentView.getSelectedIndices();
}
@@ -685,7 +716,8 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param index - Index to select
*/
public void setSelectedIndex(int index) {
@Override
public void setSelectedIndex(final int index) {
this.currentView.setSelectedIndex(index);
}
@@ -695,10 +727,13 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param indices - Indices to select
*/
public void setSelectedIndices(Integer[] indices) {
@Override
public void setSelectedIndices(final Integer[] indices) {
this.currentView.setSelectedIndices(Arrays.asList(indices));
}
public void setSelectedIndices(Iterable<Integer> indices) {
@Override
public void setSelectedIndices(final Iterable<Integer> indices) {
this.currentView.setSelectedIndices(indices);
}
@@ -709,12 +744,13 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
* @param item
* @param qty
*/
public void addItem(final T item, int qty) {
@Override
public void addItem(final T item, final int qty) {
this.pool.add(item, qty);
if (this.isUnfiltered()) {
this.model.addItem(item, qty);
}
List<T> items = new ArrayList<T>();
final List<T> items = new ArrayList<T>();
items.add(item);
this.updateView(false, items);
}
@@ -725,14 +761,15 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param itemsToAdd
*/
public void addItems(Iterable<Entry<T, Integer>> itemsToAdd) {
@Override
public void addItems(final Iterable<Entry<T, Integer>> itemsToAdd) {
this.pool.addAll(itemsToAdd);
if (this.isUnfiltered()) {
this.model.addItems(itemsToAdd);
}
List<T> items = new ArrayList<T>();
for (Map.Entry<T, Integer> item : itemsToAdd) {
final List<T> items = new ArrayList<T>();
for (final Map.Entry<T, Integer> item : itemsToAdd) {
items.add(item.getKey());
}
this.updateView(false, items);
@@ -745,7 +782,8 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
* @param item
* @param qty
*/
public void removeItem(final T item, int qty) {
@Override
public void removeItem(final T item, final int qty) {
final Iterable<T> itemsToSelect = this.currentView == this.listView ? this.getSelectedItems() : null;
this.pool.remove(item, qty);
@@ -761,10 +799,11 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param itemsToRemove
*/
public void removeItems(Iterable<Map.Entry<T, Integer>> itemsToRemove) {
@Override
public void removeItems(final Iterable<Map.Entry<T, Integer>> itemsToRemove) {
final Iterable<T> itemsToSelect = this.currentView == this.listView ? this.getSelectedItems() : null;
for (Map.Entry<T, Integer> item : itemsToRemove) {
for (final Map.Entry<T, Integer> item : itemsToRemove) {
this.pool.remove(item.getKey(), item.getValue());
if (this.isUnfiltered()) {
this.model.removeItem(item.getKey(), item.getValue());
@@ -778,6 +817,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
* removeAllItems.
*
*/
@Override
public void removeAllItems() {
this.pool.clear();
this.model.clear();
@@ -789,6 +829,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
* scrollSelectionIntoView.
*
*/
@Override
public void scrollSelectionIntoView() {
this.currentView.scrollSelectionIntoView();
}
@@ -799,6 +840,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param item
*/
@Override
public int getItemCount(final T item) {
return this.model.isInfinite() ? Integer.MAX_VALUE : this.pool.count(item);
}
@@ -808,6 +850,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return ItemPoolView<T>
*/
@Override
public ItemPool<T> getFilteredItems() {
return this.model.getItems();
}
@@ -816,7 +859,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
protected abstract ItemFilter<? extends T> createSearchFilter();
protected abstract void buildAddFilterMenu(JMenu menu);
protected <F extends ItemFilter<? extends T>> F getFilter(Class<F> filterClass) {
protected <F extends ItemFilter<? extends T>> F getFilter(final Class<F> filterClass) {
return ReflectionUtil.safeCast(this.filters.get(filterClass), filterClass);
}
@@ -844,7 +887,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
orderedFilters.add(filter);
this.add(filter.getPanel());
boolean visible = !this.hideFilters;
final boolean visible = !this.hideFilters;
filter.getPanel().setVisible(visible);
if (visible && this.initialized) {
this.revalidate();
@@ -872,7 +915,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
public void restoreDefaultFilters() {
lockFiltering = true;
for (ItemFilter<? extends T> filter : this.orderedFilters) {
for (final ItemFilter<? extends T> filter : this.orderedFilters) {
this.remove(filter.getPanel());
}
this.filters.clear();
@@ -884,7 +927,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
}
@SuppressWarnings("unchecked")
public void removeFilter(ItemFilter<? extends T> filter) {
public void removeFilter(final ItemFilter<? extends T> filter) {
final Class<? extends ItemFilter<? extends T>> filterClass = (Class<? extends ItemFilter<? extends T>>) filter.getClass();
final List<ItemFilter<? extends T>> classFilters = this.filters.get(filterClass);
if (classFilters != null && classFilters.remove(filter)) {
@@ -898,11 +941,12 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
}
}
@Override
public boolean applyFilters() {
if (this.lockFiltering || !this.initialized) { return false; }
List<Predicate<? super T>> predicates = new ArrayList<Predicate<? super T>>();
for (ItemFilter<? extends T> filter : this.orderedFilters) { //TODO: Support custom filter logic
final List<Predicate<? super T>> predicates = new ArrayList<Predicate<? super T>>();
for (final ItemFilter<? extends T> filter : this.orderedFilters) { //TODO: Support custom filter logic
if (filter.isEnabled() && !filter.isEmpty()) {
predicates.add(filter.buildPredicate(this.genericType));
}
@@ -911,7 +955,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
predicates.add(mainSearchFilter.buildPredicate(this.genericType));
}
Predicate<? super T> newFilterPredicate = predicates.size() == 0 ? null : Predicates.and(predicates);
final Predicate<? super T> newFilterPredicate = predicates.size() == 0 ? null : Predicates.and(predicates);
if (this.filterPredicate == newFilterPredicate) { return false; }
this.filterPredicate = newFilterPredicate;
@@ -946,12 +990,12 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param hideFilters0 - if true, hide the filters, otherwise show them
*/
public void setHideFilters(boolean hideFilters0) {
public void setHideFilters(final boolean hideFilters0) {
if (this.hideFilters == hideFilters0) { return; }
this.hideFilters = hideFilters0;
boolean visible = !hideFilters0;
for (ItemFilter<? extends T> filter : this.orderedFilters) {
final boolean visible = !hideFilters0;
for (final ItemFilter<? extends T> filter : this.orderedFilters) {
filter.getPanel().setVisible(visible);
}
this.chkEnableFilters.setVisible(visible);
@@ -981,7 +1025,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*/
public void resetFilters() {
lockFiltering = true; //prevent updating filtering from this change until all filters reset
for (ItemFilter<? extends T> filter : orderedFilters) {
for (final ItemFilter<? extends T> filter : orderedFilters) {
filter.setEnabled(true);
filter.reset();
}
@@ -1003,7 +1047,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
this.updateView(true, this.getSelectedItems());
}
protected Iterable<Entry<T, Integer>> getUnique(Iterable<Entry<T, Integer>> items) {
protected Iterable<Entry<T, Integer>> getUnique(final Iterable<Entry<T, Integer>> items) {
return Aggregates.uniqueByLast(items, this.pool.FN_GET_NAME);
}
@@ -1021,16 +1065,16 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
}
if (useFilter && this.wantUnique) {
Predicate<Entry<T, Integer>> filterForPool = Predicates.compose(this.filterPredicate, this.pool.FN_GET_KEY);
Iterable<Entry<T, Integer>> items = getUnique(Iterables.filter(this.pool, filterForPool));
final Predicate<Entry<T, Integer>> filterForPool = Predicates.compose(this.filterPredicate, this.pool.FN_GET_KEY);
final Iterable<Entry<T, Integer>> items = getUnique(Iterables.filter(this.pool, filterForPool));
this.model.addItems(items);
}
else if (useFilter) {
Predicate<Entry<T, Integer>> pred = Predicates.compose(this.filterPredicate, this.pool.FN_GET_KEY);
final Predicate<Entry<T, Integer>> pred = Predicates.compose(this.filterPredicate, this.pool.FN_GET_KEY);
this.model.addItems(Iterables.filter(this.pool, pred));
}
else if (this.wantUnique) {
Iterable<Entry<T, Integer>> items = getUnique(this.pool);
final Iterable<Entry<T, Integer>> items = getUnique(this.pool);
this.model.addItems(items);
}
else if (!useFilter && forceFilter) {
@@ -1039,7 +1083,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
this.currentView.refresh(itemsToSelect, this.getSelectedIndex(), forceFilter ? 0 : this.currentView.getScrollValue());
for (ItemFilter<? extends T> filter : this.orderedFilters) {
for (final ItemFilter<? extends T> filter : this.orderedFilters) {
filter.afterFiltersApplied();
}
@@ -1050,8 +1094,8 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
}
else if (this.wantUnique) {
total = 0;
Iterable<Entry<T, Integer>> items = Aggregates.uniqueByLast(this.pool, this.pool.FN_GET_NAME);
for (Entry<T, Integer> entry : items) {
final Iterable<Entry<T, Integer>> items = Aggregates.uniqueByLast(this.pool, this.pool.FN_GET_NAME);
for (final Entry<T, Integer> entry : items) {
total += entry.getValue();
}
}
@@ -1097,7 +1141,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param unique - if true, the editor will be set to the "unique item names only" mode.
*/
public void setWantUnique(boolean unique) {
public void setWantUnique(final boolean unique) {
this.wantUnique = this.alwaysNonUnique ? false : unique;
}
@@ -1117,7 +1161,7 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @param nonUniqueOnly - if true, this editor must always show non-unique items (e.g. quest editor).
*/
public void setAlwaysNonUnique(boolean nonUniqueOnly) {
public void setAlwaysNonUnique(final boolean nonUniqueOnly) {
this.alwaysNonUnique = nonUniqueOnly;
}
@@ -1137,10 +1181,10 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
*
* @return allowMultipleSelections0 - if true, multiple items can be selected at once
*/
public void setAllowMultipleSelections(boolean allowMultipleSelections0) {
public void setAllowMultipleSelections(final boolean allowMultipleSelections0) {
if (this.allowMultipleSelections == allowMultipleSelections0) { return; }
this.allowMultipleSelections = allowMultipleSelections0;
for (ItemView<T> view : views) {
for (final ItemView<T> view : views) {
view.setAllowMultipleSelections(allowMultipleSelections0);
}
}
@@ -1174,20 +1218,16 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
this.mainSearchFilter.getMainComponent().requestFocusInWindow();
}
public void addSelectionListener(ListSelectionListener listener) {
public void addSelectionListener(final ListSelectionListener listener) {
selectionListeners.remove(listener); //ensure listener not added multiple times
selectionListeners.add(listener);
}
public void removeSelectionListener(ListSelectionListener listener) {
selectionListeners.remove(listener);
}
public Iterable<ListSelectionListener> getSelectionListeners() {
return selectionListeners;
}
public void setItemActivateCommand(UiCommand itemActivateCommand0) {
public void setItemActivateCommand(final UiCommand itemActivateCommand0) {
this.itemActivateCommand = itemActivateCommand0;
}
@@ -1197,21 +1237,21 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
}
}
public void setContextMenuBuilder(ContextMenuBuilder contextMenuBuilder0) {
public void setContextMenuBuilder(final ContextMenuBuilder contextMenuBuilder0) {
this.contextMenuBuilder = contextMenuBuilder0;
}
public void showContextMenu(MouseEvent e) {
public void showContextMenu(final MouseEvent e) {
showContextMenu(e, null);
}
public void showContextMenu(MouseEvent e, final Runnable onClose) {
public void showContextMenu(final MouseEvent e, final Runnable onClose) {
//ensure the item manager has focus
this.focus();
//if item under the cursor is not selected, select it
int index = this.currentView.getIndexAtPoint(e.getPoint());
final int index = this.currentView.getIndexAtPoint(e.getPoint());
boolean needSelection = true;
for (Integer selectedIndex : this.getSelectedIndices()) {
for (final Integer selectedIndex : this.getSelectedIndices()) {
if (selectedIndex == index) {
needSelection = false;
break;
@@ -1228,23 +1268,23 @@ public abstract class ItemManager<T extends InventoryItem> extends JPanel implem
return;
}
JPopupMenu menu = new JPopupMenu("ItemManagerContextMenu");
final JPopupMenu menu = new JPopupMenu("ItemManagerContextMenu");
this.contextMenuBuilder.buildContextMenu(menu);
if (onClose != null) {
menu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuCanceled(PopupMenuEvent arg0) {
public void popupMenuCanceled(final PopupMenuEvent arg0) {
onClose.run();
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
public void popupMenuWillBecomeInvisible(final PopupMenuEvent arg0) {
onClose.run();
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
public void popupMenuWillBecomeVisible(final PopupMenuEvent arg0) {
}
});
}

View File

@@ -1,22 +1,22 @@
package forge.itemmanager.filters;
import java.util.HashSet;
import java.util.Set;
import forge.game.GameFormat;
import forge.item.PaperCard;
import forge.itemmanager.ItemManager;
import forge.model.FModel;
import forge.quest.QuestWorld;
import java.util.HashSet;
import java.util.Set;
public class CardQuestWorldFilter extends CardFormatFilter {
private final Set<QuestWorld> questWorlds = new HashSet<QuestWorld>();
public CardQuestWorldFilter(ItemManager<? super PaperCard> itemManager0) {
public CardQuestWorldFilter(final ItemManager<? super PaperCard> itemManager0) {
super(itemManager0);
}
public CardQuestWorldFilter(ItemManager<? super PaperCard> itemManager0, QuestWorld questWorld0) {
public CardQuestWorldFilter(final ItemManager<? super PaperCard> itemManager0, final QuestWorld questWorld0) {
super(itemManager0);
this.questWorlds.add(questWorld0);
this.formats.add(getQuestWorldFormat(questWorld0));
@@ -24,9 +24,9 @@ public class CardQuestWorldFilter extends CardFormatFilter {
@Override
public ItemFilter<PaperCard> createCopy() {
CardQuestWorldFilter copy = new CardQuestWorldFilter(itemManager);
final CardQuestWorldFilter copy = new CardQuestWorldFilter(itemManager);
copy.questWorlds.addAll(this.questWorlds);
for (QuestWorld w : this.questWorlds) {
for (final QuestWorld w : this.questWorlds) {
copy.formats.add(getQuestWorldFormat(w));
}
return copy;
@@ -38,7 +38,7 @@ public class CardQuestWorldFilter extends CardFormatFilter {
super.reset();
}
public static boolean canAddQuestWorld(QuestWorld questWorld, ItemFilter<PaperCard> existingFilter) {
public static boolean canAddQuestWorld(final QuestWorld questWorld, final ItemFilter<PaperCard> existingFilter) {
if (questWorld.getFormat() == null && FModel.getQuest().getMainFormat() == null) {
return false; //must have format
}
@@ -51,10 +51,10 @@ public class CardQuestWorldFilter extends CardFormatFilter {
* @return true if filter merged in or to suppress adding a new filter, false to allow adding new filter
*/
@Override
public boolean merge(ItemFilter<?> filter) {
CardQuestWorldFilter cardQuestWorldFilter = (CardQuestWorldFilter)filter;
public boolean merge(final ItemFilter<?> filter) {
final CardQuestWorldFilter cardQuestWorldFilter = (CardQuestWorldFilter)filter;
this.questWorlds.addAll(cardQuestWorldFilter.questWorlds);
for (QuestWorld w : cardQuestWorldFilter.questWorlds) {
for (final QuestWorld w : cardQuestWorldFilter.questWorlds) {
this.formats.add(getQuestWorldFormat(w));
}
return true;
@@ -72,14 +72,14 @@ public class CardQuestWorldFilter extends CardFormatFilter {
@Override
protected Iterable<String> getList() {
Set<String> strings = new HashSet<String>();
for (QuestWorld w : this.questWorlds) {
final Set<String> strings = new HashSet<String>();
for (final QuestWorld w : this.questWorlds) {
strings.add(w.getName());
}
return strings;
}
private GameFormat getQuestWorldFormat(QuestWorld w) {
private static GameFormat getQuestWorldFormat(final QuestWorld w) {
GameFormat format = w.getFormat();
if (format == null) {
//assumes that no world other than the main world will have a null format

View File

@@ -1,22 +1,22 @@
package forge.itemmanager.filters;
import forge.game.GameFormat;
import forge.itemmanager.ItemManager;
import forge.deck.DeckProxy;
import forge.model.FModel;
import forge.quest.QuestWorld;
import java.util.HashSet;
import java.util.Set;
import forge.deck.DeckProxy;
import forge.game.GameFormat;
import forge.itemmanager.ItemManager;
import forge.model.FModel;
import forge.quest.QuestWorld;
public class DeckQuestWorldFilter extends DeckFormatFilter {
private final Set<QuestWorld> questWorlds = new HashSet<QuestWorld>();
public DeckQuestWorldFilter(ItemManager<? super DeckProxy> itemManager0) {
public DeckQuestWorldFilter(final ItemManager<? super DeckProxy> itemManager0) {
super(itemManager0);
}
public DeckQuestWorldFilter(ItemManager<? super DeckProxy> itemManager0, QuestWorld questWorld0) {
public DeckQuestWorldFilter(final ItemManager<? super DeckProxy> itemManager0, final QuestWorld questWorld0) {
super(itemManager0);
this.questWorlds.add(questWorld0);
this.formats.add(getQuestWorldFormat(questWorld0));
@@ -24,9 +24,9 @@ public class DeckQuestWorldFilter extends DeckFormatFilter {
@Override
public ItemFilter<DeckProxy> createCopy() {
DeckQuestWorldFilter copy = new DeckQuestWorldFilter(itemManager);
final DeckQuestWorldFilter copy = new DeckQuestWorldFilter(itemManager);
copy.questWorlds.addAll(this.questWorlds);
for (QuestWorld w : this.questWorlds) {
for (final QuestWorld w : this.questWorlds) {
copy.formats.add(getQuestWorldFormat(w));
}
return copy;
@@ -38,7 +38,7 @@ public class DeckQuestWorldFilter extends DeckFormatFilter {
super.reset();
}
public static boolean canAddQuestWorld(QuestWorld questWorld, ItemFilter<DeckProxy> existingFilter) {
public static boolean canAddQuestWorld(final QuestWorld questWorld, final ItemFilter<DeckProxy> existingFilter) {
if (questWorld.getFormat() == null && FModel.getQuest().getMainFormat() == null) {
return false; //must have format
}
@@ -51,10 +51,10 @@ public class DeckQuestWorldFilter extends DeckFormatFilter {
* @return true if filter merged in or to suppress adding a new filter, false to allow adding new filter
*/
@Override
public boolean merge(ItemFilter<?> filter) {
DeckQuestWorldFilter cardQuestWorldFilter = (DeckQuestWorldFilter)filter;
public boolean merge(final ItemFilter<?> filter) {
final DeckQuestWorldFilter cardQuestWorldFilter = (DeckQuestWorldFilter)filter;
this.questWorlds.addAll(cardQuestWorldFilter.questWorlds);
for (QuestWorld w : cardQuestWorldFilter.questWorlds) {
for (final QuestWorld w : cardQuestWorldFilter.questWorlds) {
this.formats.add(getQuestWorldFormat(w));
}
return true;
@@ -72,14 +72,14 @@ public class DeckQuestWorldFilter extends DeckFormatFilter {
@Override
protected Iterable<String> getList() {
Set<String> strings = new HashSet<String>();
for (QuestWorld w : this.questWorlds) {
final Set<String> strings = new HashSet<String>();
for (final QuestWorld w : this.questWorlds) {
strings.add(w.getName());
}
return strings;
}
private GameFormat getQuestWorldFormat(QuestWorld w) {
private static GameFormat getQuestWorldFormat(final QuestWorld w) {
GameFormat format = w.getFormat();
if (format == null) {
//assumes that no world other than the main world will have a null format

View File

@@ -1,37 +0,0 @@
package forge.itemmanager.filters;
import com.google.common.base.Predicates;
import forge.deck.DeckProxy;
import forge.item.InventoryItem;
import forge.item.PaperCard;
import forge.itemmanager.ItemManager;
import forge.itemmanager.SItemManagerUtil.StatTypes;
import forge.toolbox.FLabel;
import forge.util.ItemPool;
import java.util.Map;
public abstract class DeckStatTypeFilter extends StatTypeFilter<DeckProxy> {
public DeckStatTypeFilter(ItemManager<? super DeckProxy> itemManager0) {
super(itemManager0);
}
@Override
protected <U extends InventoryItem> boolean showUnsupportedItem(U item) {
return false;
}
@Override
public void afterFiltersApplied() {
final ItemPool<? super DeckProxy> items = itemManager.getFilteredItems();
for (Map.Entry<StatTypes, FLabel> btn : buttonMap.entrySet()) {
if (btn.getKey().predicate != null) {
int count = items.countAll(DeckProxy.createPredicate(Predicates.compose(btn.getKey().predicate, PaperCard.FN_GET_RULES)), DeckProxy.class);
btn.getValue().setText(String.valueOf(count));
}
}
getWidget().revalidate();
}
}

View File

@@ -17,17 +17,18 @@
*/
package forge.itemmanager.views;
import forge.item.InventoryItem;
import forge.itemmanager.ColumnDef;
import forge.toolbox.FSkin;
import java.awt.Component;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.MouseEvent;
import forge.item.InventoryItem;
import forge.itemmanager.ColumnDef;
import forge.toolbox.FSkin;
/**
* Base cell renderer class for item tables
@@ -36,7 +37,7 @@ import java.awt.event.MouseEvent;
public class ItemCellRenderer extends DefaultTableCellRenderer {
private static final Border DEFAULT_BORDER = new EmptyBorder(1, 1, 1, 1);
public static ItemCellRenderer getColumnDefRenderer(ColumnDef columnDef) {
public static ItemCellRenderer getColumnDefRenderer(final ColumnDef columnDef) {
switch (columnDef) {
case POWER:
case TOUGHNESS:
@@ -66,12 +67,12 @@ public class ItemCellRenderer extends DefaultTableCellRenderer {
return false;
}
public <T extends InventoryItem> void processMouseEvent(final MouseEvent e, final ItemListView<T> listView, final Object value, final int row, final int column) {
protected <T extends InventoryItem> void processMouseEvent(final MouseEvent e, final ItemListView<T> listView, final Object value, final int row, final int column) {
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
final JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
lbl.setBorder(DEFAULT_BORDER); //prevent selected cell having inner border
if (isSelected) {
lbl.setBackground(table.getSelectionBackground());

View File

@@ -17,6 +17,56 @@
*/
package forge.itemmanager.views;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.apache.commons.lang3.StringUtils;
import forge.assets.FSkinProp;
import forge.gui.MouseUtil;
import forge.item.InventoryItem;
@@ -29,34 +79,12 @@ import forge.itemmanager.ItemManagerModel;
import forge.toolbox.FCheckBox;
import forge.toolbox.FMouseAdapter;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.*;
import org.apache.commons.lang3.StringUtils;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.*;
import java.util.List;
import java.util.Map.Entry;
import forge.toolbox.FSkin.SkinBorder;
import forge.toolbox.FSkin.SkinColor;
import forge.toolbox.FSkin.SkinFont;
import forge.toolbox.FSkin.SkinImage;
import forge.toolbox.FSkin.SkinnedTable;
import forge.toolbox.FSkin.SkinnedTableHeader;
/**
@@ -91,7 +119,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
* @param itemManager0
* @param model0
*/
public ItemListView(ItemManager<T> itemManager0, ItemManagerModel<T> model0) {
public ItemListView(final ItemManager<T> itemManager0, final ItemManagerModel<T> model0) {
super(itemManager0, model0);
this.tableModel = new ItemTableModel(model0);
this.setAllowMultipleSelections(false);
@@ -99,11 +127,10 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
// use different selection highlight colors for focused vs. unfocused tables
this.table.addMouseListener(new FMouseAdapter() {
@Override
public void onLeftDoubleClick(MouseEvent e) {
@Override public void onLeftDoubleClick(final MouseEvent e) {
if (e.isConsumed()) { return; } //don't activate if inline button double clicked
int clickedIndex = table.rowAtPoint(e.getPoint());
final int clickedIndex = table.rowAtPoint(e.getPoint());
itemManager.activateSelectedItems();
@@ -112,8 +139,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
}
@Override
public void onRightClick(MouseEvent e) {
@Override public void onRightClick(final MouseEvent e) {
itemManager.showContextMenu(e);
}
});
@@ -124,13 +150,13 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public void setup(ItemManagerConfig config, Map<ColumnDef, ItemTableColumn> colOverrides) {
public void setup(final ItemManagerConfig config, final Map<ColumnDef, ItemTableColumn> colOverrides) {
final Iterable<T> selectedItemsBefore = getSelectedItems();
final DefaultTableColumnModel colmodel = new DefaultTableColumnModel();
//ensure columns ordered properly
final List<ItemTableColumn> columns = new LinkedList<ItemTableColumn>();
for (ItemColumnConfig colConfig : config.getCols().values()) {
for (final ItemColumnConfig colConfig : config.getCols().values()) {
if (colOverrides == null || !colOverrides.containsKey(colConfig.getDef())) {
columns.add(new ItemTableColumn(new ItemColumn(colConfig)));
}
@@ -139,14 +165,13 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
}
Collections.sort(columns, new Comparator<ItemTableColumn>() {
@Override
public int compare(ItemTableColumn arg0, ItemTableColumn arg1) {
@Override public int compare(final ItemTableColumn arg0, final ItemTableColumn arg1) {
return Integer.compare(arg0.getIndex(), arg1.getIndex());
}
});
//hide table header if only showing single string column
boolean hideHeader = (config.getCols().size() == 1 && config.getCols().containsKey(ColumnDef.STRING));
final boolean hideHeader = (config.getCols().size() == 1 && config.getCols().containsKey(ColumnDef.STRING));
getPnlOptions().removeAll();
@@ -155,9 +180,8 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
chkBox.setFont(ROW_FONT);
chkBox.setToolTipText("Toggle whether to show unique cards only");
chkBox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
boolean wantUnique = chkBox.isSelected();
@Override public void stateChanged(final ChangeEvent arg0) {
final boolean wantUnique = chkBox.isSelected();
if (itemManager.getWantUnique() == wantUnique) { return; }
itemManager.setWantUnique(wantUnique);
itemManager.refresh();
@@ -181,9 +205,8 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
chkBox.setFont(ROW_FONT);
chkBox.setToolTipText(col.getLongName());
chkBox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
boolean visible = chkBox.isSelected();
@Override public void stateChanged(final ChangeEvent arg0) {
final boolean visible = chkBox.isSelected();
if (col.isVisible() == visible) { return; }
col.setVisible(visible);
@@ -191,7 +214,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
colmodel.addColumn(col);
//move column into proper position
int oldIndex = colmodel.getColumnCount() - 1;
final int oldIndex = colmodel.getColumnCount() - 1;
int newIndex = col.getIndex();
for (int i = 0; i < col.getIndex(); i++) {
if (!columns.get(i).isVisible()) {
@@ -252,7 +275,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public void setAllowMultipleSelections(boolean allowMultipleSelections) {
public void setAllowMultipleSelections(final boolean allowMultipleSelections) {
this.table.setSelectionMode(allowMultipleSelections ? ListSelectionModel.MULTIPLE_INTERVAL_SELECTION : ListSelectionModel.SINGLE_SELECTION);
}
@@ -263,8 +286,8 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
@Override
public Iterable<Integer> getSelectedIndices() {
List<Integer> indices = new ArrayList<Integer>();
int[] selectedRows = this.table.getSelectedRows();
final List<Integer> indices = new ArrayList<Integer>();
final int[] selectedRows = this.table.getSelectedRows();
for (int i = 0; i < selectedRows.length; i++) {
indices.add(selectedRows[i]);
}
@@ -272,23 +295,23 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
protected void onSetSelectedIndex(int index) {
protected void onSetSelectedIndex(final int index) {
this.table.setRowSelectionInterval(index, index);
}
@Override
protected void onSetSelectedIndices(Iterable<Integer> indices) {
protected void onSetSelectedIndices(final Iterable<Integer> indices) {
this.table.clearSelection();
for (Integer index : indices) {
for (final Integer index : indices) {
this.table.addRowSelectionInterval(index, index);
}
}
@Override
protected void onScrollSelectionIntoView(JViewport viewport) {
protected void onScrollSelectionIntoView(final JViewport viewport) {
// compute where we're going and where we are
Rectangle targetRect = this.table.getCellRect(this.getSelectedIndex(), 0, true);
Rectangle curViewRect = viewport.getViewRect();
final Rectangle targetRect = this.table.getCellRect(this.getSelectedIndex(), 0, true);
final Rectangle curViewRect = viewport.getViewRect();
// if the target cell is not visible, attempt to jump to a location where it is
// visible but not on the edge of the viewport
@@ -310,13 +333,13 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public int getIndexOfItem(T item) {
public int getIndexOfItem(final T item) {
return this.tableModel.itemToRow(item);
}
@Override
public T getItemAtIndex(int index) {
Entry<T, Integer> itemEntry = this.tableModel.rowToItem(index);
public T getItemAtIndex(final int index) {
final Entry<T, Integer> itemEntry = this.tableModel.rowToItem(index);
return itemEntry != null ? itemEntry.getKey() : null;
}
@@ -331,7 +354,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public int getIndexAtPoint(Point p) {
public int getIndexAtPoint(final Point p) {
return this.table.rowAtPoint(p);
}
@@ -355,7 +378,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
this.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
public void focusGained(final FocusEvent e) {
setSelectionBackground(SEL_ACTIVE_COLOR);
// if nothing selected when we gain focus, select the first row (if exists)
if (getSelectedIndex() == -1 && getCount() > 0) {
@@ -364,7 +387,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public void focusLost(FocusEvent e) {
public void focusLost(final FocusEvent e) {
if (!e.isTemporary()) {
setSelectionBackground(SEL_INACTIVE_COLOR);
}
@@ -382,7 +405,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
public void actionPerformed(final ActionEvent e) {
final StringBuilder sb = new StringBuilder();
for (final int row : getSelectedRows()) {
Entry<T, Integer> item = tableModel.rowToItem(row);
final Entry<T, Integer> item = tableModel.rowToItem(row);
sb.append(item.getValue().toString());
sb.append(' ');
sb.append(item.getKey().toString());
@@ -399,12 +422,12 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
protected JTableHeader createDefaultTableHeader() {
SkinnedTableHeader header = new SkinnedTableHeader(columnModel) {
final SkinnedTableHeader header = new SkinnedTableHeader(columnModel) {
@Override
public String getToolTipText(MouseEvent e) {
int col = columnModel.getColumnIndexAtX(e.getPoint().x);
public String getToolTipText(final MouseEvent e) {
final int col = columnModel.getColumnIndexAtX(e.getPoint().x);
if (col < 0) { return null; }
ItemTableColumn tableColumn = (ItemTableColumn) columnModel.getColumn(col);
final ItemTableColumn tableColumn = (ItemTableColumn) columnModel.getColumn(col);
if (tableColumn.getLongName().isEmpty()) {
return null;
}
@@ -418,9 +441,9 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
final DefaultTableCellRenderer renderer = ((DefaultTableCellRenderer)header.getDefaultRenderer());
header.setDefaultRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel lbl = (JLabel) renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
public Component getTableCellRendererComponent(final JTable table,
final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
final JLabel lbl = (JLabel) renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
lbl.setHorizontalAlignment(SwingConstants.LEFT);
FSkin.setTempBorder(lbl, HEADER_BORDER);
return lbl;
@@ -429,39 +452,40 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
return header;
}
public void processMouseEvent(MouseEvent e) {
Point p = e.getPoint();
int row = rowAtPoint(p);
int col = columnAtPoint(p);
@Override
public void processMouseEvent(final MouseEvent e) {
final Point p = e.getPoint();
final int row = rowAtPoint(p);
final int col = columnAtPoint(p);
if (col < 0 || col >= getColumnCount() || row < 0 || row >= getRowCount()) {
return;
}
Object val = getValueAt(row, col);
final Object val = getValueAt(row, col);
if (val == null) {
return;
}
ItemCellRenderer renderer = (ItemCellRenderer)getCellRenderer(row, col);
final ItemCellRenderer renderer = (ItemCellRenderer)getCellRenderer(row, col);
if (renderer != null) {
renderer.processMouseEvent(e, ItemListView.this, val, row, col); //give renderer a chance to process the mouse event
}
try {
super.processMouseEvent(e);
}
catch (Exception ex) { //trap error thrown by weird tooltip issue
catch (final Exception ex) { //trap error thrown by weird tooltip issue
ex.printStackTrace();
}
}
private String getCellTooltip(TableCellRenderer renderer, int row, int col, Object val) {
Component cell = renderer.getTableCellRendererComponent(this, val, false, false, row, col);
private String getCellTooltip(final TableCellRenderer renderer, final int row, final int col, final Object val) {
final Component cell = renderer.getTableCellRendererComponent(this, val, false, false, row, col);
// use a pre-set tooltip if it exists
if (cell instanceof JComponent) {
JComponent jcell = (JComponent)cell;
String tip = jcell.getToolTipText();
final JComponent jcell = (JComponent)cell;
final String tip = jcell.getToolTipText();
if (tip != null && !tip.isEmpty()) {
return tip;
}
@@ -470,7 +494,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
// if we're conditionally showing the tooltip, check to see
// if we shouldn't show it
if (val == null) { return null; }
String text = val.toString();
final String text = val.toString();
if (text.isEmpty()) { return null; }
if (!(renderer instanceof ItemCellRenderer) || !((ItemCellRenderer)renderer).alwaysShowTooltip()) {
@@ -478,8 +502,8 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
// we use '>' here instead of '>=' since that seems to be the
// threshold for where the ellipses appear for the default
// JTable renderer
int requiredWidth = cell.getPreferredSize().width;
TableColumn tableColumn = this.getColumnModel().getColumn(col);
final int requiredWidth = cell.getPreferredSize().width;
final TableColumn tableColumn = this.getColumnModel().getColumn(col);
if (tableColumn.getWidth() > requiredWidth) {
return null;
}
@@ -490,16 +514,16 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public String getToolTipText(MouseEvent e) {
Point p = e.getPoint();
int row = rowAtPoint(p);
int col = columnAtPoint(p);
public String getToolTipText(final MouseEvent e) {
final Point p = e.getPoint();
final int row = rowAtPoint(p);
final int col = columnAtPoint(p);
if (col >= getColumnCount() || row >= getRowCount()) {
return null;
}
Object val = getValueAt(row, col);
final Object val = getValueAt(row, col);
if (val == null) {
return null;
}
@@ -512,7 +536,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
private Point lastTooltipPt;
@Override
public Point getToolTipLocation(MouseEvent e) {
public Point getToolTipLocation(final MouseEvent e) {
Point p = e.getPoint();
final int row = rowAtPoint(p);
final int col = columnAtPoint(p);
@@ -556,7 +580,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
model.getCascadeManager().reset();
for (int i = sortcols.length - 1; i >= 0; i--) {
ItemTableColumn col = sortcols[i];
final ItemTableColumn col = sortcols[i];
if (col != null) {
model.getCascadeManager().add(col.getItemColumn(), true);
}
@@ -608,11 +632,11 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
private ItemTableColumn resizeColumn;
@Override
public void onLeftMouseDown(MouseEvent e) {
public void onLeftMouseDown(final MouseEvent e) {
focus();
if (Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) == table.getTableHeader().getCursor()) {
final TableColumnModel colModel = table.getColumnModel();
int index = colModel.getColumnIndexAtX(e.getX() - 3); //-3 to ensure we get column left of resizer
final int index = colModel.getColumnIndexAtX(e.getX() - 3); //-3 to ensure we get column left of resizer
if (index >= 0) {
resizeColumn = (ItemTableColumn) colModel.getColumn(index);
resizeColumn.startResize();
@@ -622,7 +646,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public void onLeftMouseUp(MouseEvent e) {
public void onLeftMouseUp(final MouseEvent e) {
if (resizeColumn != null) {
MouseUtil.unlockCursor();
resizeColumn.endResize();
@@ -631,7 +655,7 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public void onLeftClick(MouseEvent e) {
public void onLeftClick(final MouseEvent e) {
if (Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) == table.getTableHeader().getCursor()) {
return;
}
@@ -655,9 +679,9 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public void onLeftMouseDragDrop(MouseEvent e) { //save preferences after column moved/resized
public void onLeftMouseDragDrop(final MouseEvent e) { //save preferences after column moved/resized
for (int i = 0; i < table.getColumnCount(); i++) {
ItemTableColumn column = (ItemTableColumn) table.getColumnModel().getColumn(i);
final ItemTableColumn column = (ItemTableColumn) table.getColumnModel().getColumn(i);
column.updatePreferredWidth();
column.setIndex(i);
}
@@ -665,14 +689,14 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
}
@Override
public void onMouseExit(MouseEvent e) {
public void onMouseExit(final MouseEvent e) {
MouseUtil.resetCursor();
}
};
private final MouseMotionAdapter headerMouseMotionAdapter = new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent arg0) {
public void mouseMoved(final MouseEvent arg0) {
MouseUtil.setCursor(table.getTableHeader().getCursor());
}
};
@@ -724,8 +748,8 @@ public final class ItemListView<T extends InventoryItem> extends ItemView<T> {
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
@Override
public Object getValueAt(int iRow, int iCol) {
Entry<T, Integer> card = this.rowToItem(iRow);
public Object getValueAt(final int iRow, final int iCol) {
final Entry<T, Integer> card = this.rowToItem(iRow);
if (null == card) {
return null;
}

View File

@@ -17,6 +17,11 @@
*/
package forge.itemmanager.views;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.table.TableColumn;
import com.google.common.base.Function;
import forge.item.InventoryItem;
@@ -26,11 +31,6 @@ import forge.itemmanager.ItemColumnConfig;
import forge.itemmanager.ItemColumnConfig.SortState;
import forge.itemmanager.ItemManagerConfig;
import javax.swing.table.TableColumn;
import java.util.Map;
import java.util.Map.Entry;
/**
* A column object in a EditorTableModel in the card editor.
* Requires a sorting function and a display function
@@ -41,15 +41,15 @@ public class ItemTableColumn extends TableColumn {
private final ItemColumn itemColumn;
public ItemTableColumn(ItemColumn itemColumn0) {
public ItemTableColumn(final ItemColumn itemColumn0) {
super();
itemColumn = itemColumn0;
ColumnDef def = itemColumn.getConfig().getDef();
final ColumnDef def = itemColumn.getConfig().getDef();
this.setIdentifier(def);
this.setHeaderValue(def.shortName);
int width = itemColumn.getConfig().getPreferredWidth();
final int width = itemColumn.getConfig().getPreferredWidth();
this.setPreferredWidth(width);
if (def.isWidthFixed) {
this.setMinWidth(width);
@@ -102,7 +102,7 @@ public class ItemTableColumn extends TableColumn {
return itemColumn.getConfig().isVisible();
}
public void setVisible(boolean visible0) {
public void setVisible(final boolean visible0) {
itemColumn.getConfig().setVisible(visible0);
}
@@ -125,7 +125,7 @@ public class ItemTableColumn extends TableColumn {
public void endResize() {
//restore min/max width after resize to prevent table auto-scaling fixed width columns
if (itemColumn.getConfig().getDef().isWidthFixed) {
int width = this.getWidth();
final int width = this.getWidth();
this.setMinWidth(width);
this.setMaxWidth(width);
}
@@ -140,13 +140,13 @@ public class ItemTableColumn extends TableColumn {
return itemColumn.toString();
}
public static void addColOverride(ItemManagerConfig config, Map<ColumnDef, ItemTableColumn> colOverrides, ColumnDef colDef) {
ItemColumnConfig colConfig = config.getCols().get(colDef);
public static void addColOverride(final ItemManagerConfig config, final Map<ColumnDef, ItemTableColumn> colOverrides, final ColumnDef colDef) {
final ItemColumnConfig colConfig = config.getCols().get(colDef);
addColOverride(config, colOverrides, colDef, colConfig.getFnSort(), colConfig.getFnDisplay());
}
public static void addColOverride(ItemManagerConfig config, Map<ColumnDef, ItemTableColumn> colOverrides, ColumnDef colDef,
Function<Entry<InventoryItem, Integer>, Comparable<?>> fnSort0,
Function<Entry<? extends InventoryItem, Integer>, Object> fnDisplay0) {
public static void addColOverride(final ItemManagerConfig config, final Map<ColumnDef, ItemTableColumn> colOverrides, final ColumnDef colDef,
final Function<Entry<InventoryItem, Integer>, Comparable<?>> fnSort0,
final Function<Entry<? extends InventoryItem, Integer>, Object> fnDisplay0) {
colOverrides.put(colDef, new ItemTableColumn(new ItemColumn(config.getCols().get(colDef), fnSort0, fnDisplay0)));
}
}

View File

@@ -70,7 +70,7 @@ public abstract class ItemView<T extends InventoryItem> {
this.model = model0;
this.scroller = new FScrollPane(false) {
@Override
protected void processMouseWheelEvent(MouseWheelEvent e) {
protected void processMouseWheelEvent(final MouseWheelEvent e) {
if (e.isControlDown()) {
onMouseWheelZoom(e);
return;
@@ -81,9 +81,13 @@ public abstract class ItemView<T extends InventoryItem> {
this.pnlOptions.setOpaque(false);
this.pnlOptions.setBorder(new FSkin.MatteSkinBorder(1, 0, 0, 0, BORDER_COLOR));
this.scroller.setBorder(new FSkin.LineSkinBorder(BORDER_COLOR));
this.button = new FLabel.Builder().hoverable().selectable(true)
.icon(getIcon()).iconScaleAuto(false)
.tooltip(getCaption()).build();
this.button = new FLabel.Builder()
.hoverable()
.selectable(true)
.icon(getIcon())
.iconScaleAuto(false)
.tooltip(getCaption())
.build();
}
public void initialize(final int index) {
@@ -92,16 +96,14 @@ public abstract class ItemView<T extends InventoryItem> {
//hook incremental search functionality
final IncrementalSearch incrementalSearch = new IncrementalSearch();
comp.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent arg0) {
@Override public void focusLost(final FocusEvent arg0) {
incrementalSearch.cancel();
}
});
comp.addKeyListener(incrementalSearch);
this.button.setCommand(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (button.isSelected()) {
itemManager.setViewIndex(index);
}
@@ -114,11 +116,10 @@ public abstract class ItemView<T extends InventoryItem> {
this.scroller.setViewportView(comp);
this.scroller.getVerticalScrollBar().addAdjustmentListener(new ToolTipListener());
this.scroller.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
@Override public void componentResized(final ComponentEvent e) {
onResize();
//scroll selection into view whenever view height changes
int height = e.getComponent().getHeight();
final int height = e.getComponent().getHeight();
if (height != heightBackup) {
heightBackup = height;
scrollSelectionIntoView();
@@ -143,11 +144,11 @@ public abstract class ItemView<T extends InventoryItem> {
return scroller.getVerticalScrollBar().getValue();
}
public void setScrollValue(int value) {
public void setScrollValue(final int value) {
scroller.getVerticalScrollBar().setValue(value);
}
protected void onMouseWheelZoom(MouseWheelEvent e) {
protected void onMouseWheelZoom(final MouseWheelEvent e) {
}
public boolean isIncrementalSearchActive() {
@@ -178,9 +179,9 @@ public abstract class ItemView<T extends InventoryItem> {
}
public final Collection<T> getSelectedItems() {
List<T> items = new ArrayList<T>();
for (Integer i : getSelectedIndices()) {
T item = getItemAtIndex(i);
final List<T> items = new ArrayList<T>();
for (final Integer i : getSelectedIndices()) {
final T item = getItemAtIndex(i);
if (item != null) {
items.add(item);
}
@@ -188,11 +189,11 @@ public abstract class ItemView<T extends InventoryItem> {
return items;
}
public final boolean setSelectedItem(T item) {
public final boolean setSelectedItem(final T item) {
return setSelectedItem(item, true);
}
public final boolean setSelectedItem(T item, boolean scrollIntoView) {
int index = getIndexOfItem(item);
public final boolean setSelectedItem(final T item, final boolean scrollIntoView) {
final int index = getIndexOfItem(item);
if (index != -1) {
setSelectedIndex(index, scrollIntoView);
return true;
@@ -200,13 +201,13 @@ public abstract class ItemView<T extends InventoryItem> {
return false;
}
public final boolean setSelectedItems(Iterable<T> items) {
public final boolean setSelectedItems(final Iterable<T> items) {
return setSelectedItems(items, true);
}
public final boolean setSelectedItems(Iterable<T> items, boolean scrollIntoView) {
List<Integer> indices = new ArrayList<Integer>();
for (T item : items) {
int index = getIndexOfItem(item);
public final boolean setSelectedItems(final Iterable<T> items, final boolean scrollIntoView) {
final List<Integer> indices = new ArrayList<Integer>();
for (final T item : items) {
final int index = getIndexOfItem(item);
if (index != -1) {
indices.add(index);
}
@@ -221,11 +222,11 @@ public abstract class ItemView<T extends InventoryItem> {
return false;
}
public void setSelectedIndex(int index) {
public void setSelectedIndex(final int index) {
setSelectedIndex(index, true);
}
public void setSelectedIndex(int index, boolean scrollIntoView) {
int count = getCount();
public void setSelectedIndex(int index, final boolean scrollIntoView) {
final int count = getCount();
if (count == 0) { return; }
if (index < 0) {
@@ -241,22 +242,22 @@ public abstract class ItemView<T extends InventoryItem> {
}
}
public void setSelectedIndices(Iterable<Integer> indices) {
public void setSelectedIndices(final Iterable<Integer> indices) {
setSelectedIndices(indices, true);
}
public void setSelectedIndices(Iterable<Integer> indices, boolean scrollIntoView) {
int count = getCount();
public void setSelectedIndices(final Iterable<Integer> indices, final boolean scrollIntoView) {
final int count = getCount();
if (count == 0) { return; }
List<Integer> indexList = new ArrayList<Integer>();
for (Integer index : indices) {
final List<Integer> indexList = new ArrayList<Integer>();
for (final Integer index : indices) {
if (index >= 0 && index < count) {
indexList.add(index);
}
}
if (indexList.isEmpty()) { //if no index in range, set selected index based on first index
for (Integer index : indices) {
for (final Integer index : indices) {
setSelectedIndex(index);
return;
}
@@ -272,15 +273,15 @@ public abstract class ItemView<T extends InventoryItem> {
protected void onSelectionChange() {
final int index = getSelectedIndex();
if (index != -1) {
ListSelectionEvent event = new ListSelectionEvent(itemManager, index, index, false);
for (ListSelectionListener listener : itemManager.getSelectionListeners()) {
final ListSelectionEvent event = new ListSelectionEvent(itemManager, index, index, false);
for (final ListSelectionListener listener : itemManager.getSelectionListeners()) {
listener.valueChanged(event);
}
}
}
public void scrollSelectionIntoView() {
Container parent = getComponent().getParent();
final Container parent = getComponent().getParent();
if (parent instanceof JViewport) {
onScrollSelectionIntoView((JViewport)parent);
}
@@ -334,13 +335,13 @@ public abstract class ItemView<T extends InventoryItem> {
private void setPopupSize() {
// resize popup to size of label (ensure there's room for the next character so the label
// doesn't show '...' in the time between when we set the text and when we increase the size
Dimension labelDimension = popupLabel.getPreferredSize();
Dimension popupDimension = new Dimension(labelDimension.width + 12, labelDimension.height + 4);
final Dimension labelDimension = popupLabel.getPreferredSize();
final Dimension popupDimension = new Dimension(labelDimension.width + 12, labelDimension.height + 4);
SwingUtilities.getRoot(popupLabel).setSize(popupDimension);
}
private void findNextMatch(int startIdx, boolean reverse) {
int numItems = itemManager.getItemCount();
private void findNextMatch(int startIdx, final boolean reverse) {
final int numItems = itemManager.getItemCount();
if (0 == numItems) {
cancel();
return;
@@ -349,11 +350,11 @@ public abstract class ItemView<T extends InventoryItem> {
// find the next item that matches the string
startIdx %= numItems;
final int increment = reverse ? numItems - 1 : 1;
int stopIdx = (startIdx + numItems - increment) % numItems;
String searchStr = str.toString();
final int stopIdx = (startIdx + numItems - increment) % numItems;
final String searchStr = str.toString();
boolean found = false;
for (int idx = startIdx;; idx = (idx + increment) % numItems) {
T item = ItemView.this.getItemAtIndex(idx);
final T item = ItemView.this.getItemAtIndex(idx);
if (item == null) {
break;
}
@@ -388,14 +389,13 @@ public abstract class ItemView<T extends InventoryItem> {
popupTimer.restart();
}
else {
PopupFactory factory = PopupFactory.getSharedInstance();
Point tableLoc = ItemView.this.getLocationOnScreen();
final PopupFactory factory = PopupFactory.getSharedInstance();
final Point tableLoc = ItemView.this.getLocationOnScreen();
popup = factory.getPopup(null, popupLabel, tableLoc.x + 10, tableLoc.y + 10);
FSkin.setTempBackground(SwingUtilities.getRoot(popupLabel), FSkin.getColor(FSkin.Colors.CLR_INACTIVE));
popupTimer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@Override public void actionPerformed(final ActionEvent e) {
cancel();
}
});
@@ -424,14 +424,14 @@ public abstract class ItemView<T extends InventoryItem> {
}
@Override
public void keyPressed(KeyEvent e) {
public void keyPressed(final KeyEvent e) {
if (popupShowing) {
if (KeyEvent.VK_ESCAPE == e.getKeyCode()) {
cancel();
}
}
else {
for (KeyListener keyListener : itemManager.getKeyListeners()) {
for (final KeyListener keyListener : itemManager.getKeyListeners()) {
keyListener.keyPressed(e);
if (e.isConsumed()) { return; }
}
@@ -445,9 +445,9 @@ public abstract class ItemView<T extends InventoryItem> {
}
@Override
public void keyTyped(KeyEvent e) {
public void keyTyped(final KeyEvent e) {
if (!popupShowing) {
for (KeyListener keyListener : itemManager.getKeyListeners()) {
for (final KeyListener keyListener : itemManager.getKeyListeners()) {
keyListener.keyTyped(e);
if (e.isConsumed()) { return; }
}
@@ -492,9 +492,9 @@ public abstract class ItemView<T extends InventoryItem> {
}
@Override
public void keyReleased(KeyEvent e) {
public void keyReleased(final KeyEvent e) {
if (!popupShowing) {
for (KeyListener keyListener : itemManager.getKeyListeners()) {
for (final KeyListener keyListener : itemManager.getKeyListeners()) {
keyListener.keyReleased(e);
if (e.isConsumed()) { return; }
}

View File

@@ -38,12 +38,12 @@ public final class LayoutMenu {
private FScreen currentScreen;
private static final ForgePreferences prefs = FModel.getPreferences();
private boolean showIcons = false;
private final boolean showIcons = false;
public JMenu getMenu() {
currentScreen = Singletons.getControl().getCurrentScreen();
JMenu menu = new JMenu("Layout");
final JMenu menu = new JMenu("Layout");
menu.setMnemonic(KeyEvent.VK_L);
if (currentScreen != FScreen.HOME_SCREEN) {
menu.add(getMenu_ViewOptions());
@@ -60,7 +60,7 @@ public final class LayoutMenu {
}
private JMenu getMenu_ViewOptions() {
JMenu menu = new JMenu("View");
final JMenu menu = new JMenu("View");
menu.add(getMenuItem_ShowTabs());
if (currentScreen != null && currentScreen.isMatchScreen()) {
menu.add(getMenuItem_ShowBackgroundImage());
@@ -69,18 +69,18 @@ public final class LayoutMenu {
}
private JMenu getMenu_FileOptions() {
JMenu menu = new JMenu("File");
final JMenu menu = new JMenu("File");
menu.add(getMenuItem_OpenLayout());
menu.add(getMenuItem_SaveLayout());
return menu;
}
private static JMenu getMenu_ThemeOptions() {
JMenu menu = new JMenu("Theme");
final JMenu menu = new JMenu("Theme");
JRadioButtonMenuItem menuItem;
ButtonGroup group = new ButtonGroup();
String currentSkin = prefs.getPref(FPref.UI_SKIN);
for (String skin : FSkin.getAllSkins()) {
final ButtonGroup group = new ButtonGroup();
final String currentSkin = prefs.getPref(FPref.UI_SKIN);
for (final String skin : FSkin.getAllSkins()) {
menuItem = new JRadioButtonMenuItem(skin);
group.add(menuItem);
if (skin.equals(currentSkin)) {
@@ -94,8 +94,7 @@ public final class LayoutMenu {
}
private static final ActionListener changeSkin = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@Override public void actionPerformed(final ActionEvent e) {
MouseUtil.setCursor(Cursor.WAIT_CURSOR);
FSkin.changeSkin(e.getActionCommand());
MouseUtil.resetCursor();
@@ -111,9 +110,8 @@ public final class LayoutMenu {
private static ActionListener getShowBackgroundImageAction(final JCheckBoxMenuItem menuItem) {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean isVisible = menuItem.getState();
@Override public void actionPerformed(final ActionEvent e) {
final boolean isVisible = menuItem.getState();
prefs.setPref(FPref.UI_MATCH_IMAGE_VISIBLE, isVisible);
if (isVisible) {
FView.SINGLETON_INSTANCE.getPnlInsets().setForegroundImage(FSkin.getIcon(FSkinProp.BG_MATCH));
@@ -134,9 +132,8 @@ public final class LayoutMenu {
}
private static ActionListener getShowTabsAction(final JCheckBoxMenuItem menuItem) {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean showTabs = menuItem.getState();
@Override public void actionPerformed(final ActionEvent e) {
final boolean showTabs = menuItem.getState();
FView.SINGLETON_INSTANCE.refreshAllCellLayouts(showTabs);
prefs.setPref(FPref.UI_HIDE_GAME_TABS, !showTabs);
prefs.save();
@@ -145,67 +142,63 @@ public final class LayoutMenu {
}
private JMenuItem getMenuItem_SaveLayout() {
SkinnedMenuItem menuItem = new SkinnedMenuItem("Save Current Layout");
final SkinnedMenuItem menuItem = new SkinnedMenuItem("Save Current Layout");
menuItem.setIcon((showIcons ? MenuUtil.getMenuIcon(FSkinProp.ICO_SAVELAYOUT) : null));
menuItem.addActionListener(getSaveLayoutAction());
return menuItem;
}
private ActionListener getSaveLayoutAction() {
private static ActionListener getSaveLayoutAction() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@Override public void actionPerformed(final ActionEvent e) {
SLayoutIO.saveLayout();
}
};
}
private JMenuItem getMenuItem_OpenLayout() {
SkinnedMenuItem menuItem = new SkinnedMenuItem("Open...");
final SkinnedMenuItem menuItem = new SkinnedMenuItem("Open...");
menuItem.setIcon((showIcons ? MenuUtil.getMenuIcon(FSkinProp.ICO_OPENLAYOUT) : null));
menuItem.addActionListener(getOpenLayoutAction());
return menuItem;
}
private ActionListener getOpenLayoutAction() {
private static ActionListener getOpenLayoutAction() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@Override public void actionPerformed(final ActionEvent e) {
SLayoutIO.openLayout();
}
};
}
private JMenuItem getMenuItem_RevertLayout() {
SkinnedMenuItem menuItem = new SkinnedMenuItem("Refresh");
final SkinnedMenuItem menuItem = new SkinnedMenuItem("Refresh");
menuItem.setIcon((showIcons ? MenuUtil.getMenuIcon(FSkinProp.ICO_REVERTLAYOUT) : null));
menuItem.addActionListener(getRevertLayoutAction());
return menuItem;
}
private ActionListener getRevertLayoutAction() {
private static ActionListener getRevertLayoutAction() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@Override public void actionPerformed(final ActionEvent e) {
SLayoutIO.revertLayout();
}
};
}
private static JMenuItem getMenuItem_SetWindowSize() {
JMenuItem menuItem = new JMenuItem("Set Window Size");
final JMenuItem menuItem = new JMenuItem("Set Window Size");
menuItem.addActionListener(getSetWindowSizeAction());
return menuItem;
}
private static ActionListener getSetWindowSizeAction() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String[] options = {"800x600", "1024x768", "1280x720"};
@Override public void actionPerformed(final ActionEvent e) {
final String[] options = {"800x600", "1024x768", "1280x720"};
final String choice = GuiChoose.oneOrNone("Choose new window size", options);
if (choice != null) {
String[] dims = choice.split("x");
final String[] dims = choice.split("x");
Singletons.getView().getFrame().setSize(Integer.parseInt(dims[0]), Integer.parseInt(dims[1]));
}
}
@@ -225,8 +218,7 @@ public final class LayoutMenu {
}
private static ActionListener getFullScreenAction() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@Override public void actionPerformed(final ActionEvent e) {
final FFrame frame = Singletons.getView().getFrame();
frame.setFullScreen(!frame.isFullScreen());
}

View File

@@ -1,21 +1,18 @@
package forge.screens.bazaar;
import javax.swing.SwingUtilities;
import com.google.common.collect.Iterables;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
import forge.quest.bazaar.QuestBazaarManager;
import forge.toolbox.FLabel;
import javax.swing.*;
/**
* TODO: Write javadoc for this type.
*
*/
public enum CBazaarUI implements ICDoc {
SINGLETON_INSTANCE;
private final VBazaarUI view = VBazaarUI.SINGLETON_INSTANCE;
/**
* Controls top-level instance of bazaar.
* @param v0 &emsp; {@link forge.screens.bazaar.VBazaarUI}
@@ -25,32 +22,22 @@ public enum CBazaarUI implements ICDoc {
}
/** Populate all stalls, and select first one. */
public void initBazaar(QuestBazaarManager bazaar) {
VBazaarUI.SINGLETON_INSTANCE.populateStalls();
((FLabel) VBazaarUI.SINGLETON_INSTANCE.getPnlAllStalls().getComponent(0)).setSelected(true);
public void initBazaar(final QuestBazaarManager bazaar) {
view.populateStalls();
((FLabel) view.getPnlAllStalls().getComponent(0)).setSelected(true);
showStall(Iterables.get(bazaar.getStallNames(), 0), bazaar);
}
/** @param s0 &emsp; {@link java.lang.String} */
public void showStall(final String s0, final QuestBazaarManager bazaar) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
VBazaarUI.SINGLETON_INSTANCE.getPnlSingleStall().setStall(bazaar.getStall(s0));
VBazaarUI.SINGLETON_INSTANCE.getPnlSingleStall().updateStall();
@Override public void run() {
view.getPnlSingleStall().setStall(bazaar.getStall(s0));
view.getPnlSingleStall().updateStall();
}
});
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
// TODO Auto-generated method stub
return null;
}
@Override
public void register() {
}
@@ -60,8 +47,6 @@ public enum CBazaarUI implements ICDoc {
*/
@Override
public void initialize() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
@@ -69,7 +54,5 @@ public enum CBazaarUI implements ICDoc {
*/
@Override
public void update() {
// TODO Auto-generated method stub
}
}

View File

@@ -92,7 +92,7 @@ public enum CDeckEditorUI implements ICDoc {
return !deckController.isSaved();
}
public boolean canSwitchAway(boolean isClosing) {
public boolean canSwitchAway(final boolean isClosing) {
if (this.childController != null) {
if (!this.childController.canSwitchAway(isClosing)) {
return false;
@@ -117,8 +117,8 @@ public enum CDeckEditorUI implements ICDoc {
/**
* Set controller for a given editor screen.
*/
public void setEditorController(ACEditorBase<? extends InventoryItem, ? extends DeckBase> childController0) {
FScreen screen = childController0.getScreen();
public void setEditorController(final ACEditorBase<? extends InventoryItem, ? extends DeckBase> childController0) {
final FScreen screen = childController0.getScreen();
screenChildControllers.put(screen, childController0);
if (screen == Singletons.getControl().getCurrentScreen()) {
setCurrentEditorController(childController0);
@@ -126,18 +126,18 @@ public enum CDeckEditorUI implements ICDoc {
}
@SuppressWarnings("unchecked")
public <T extends InventoryItem> void incrementDeckQuantity(T item, int delta) {
public <T extends InventoryItem> void incrementDeckQuantity(final T item, final int delta) {
if (item == null || delta == 0) { return; }
if (delta > 0) { //add items
int qty = Math.min(delta, ((ItemManager<T>)childController.getCatalogManager()).getItemCount(item));
final int qty = Math.min(delta, ((ItemManager<T>)childController.getCatalogManager()).getItemCount(item));
if (qty == 0) { return; }
((ACEditorBase<T, ?>)childController).addItem(item, qty, false);
((ACEditorBase<T, ?>)childController).addItem(item, qty);
}
else { //remove items
int qty = Math.min(-delta, ((ItemManager<T>)childController.getDeckManager()).getItemCount(item));
final int qty = Math.min(-delta, ((ItemManager<T>)childController.getDeckManager()).getItemCount(item));
if (qty == 0) { return; }
((ACEditorBase<T, ?>)childController).removeItem(item, qty, false);
((ACEditorBase<T, ?>)childController).removeItem(item, qty);
}
CStatistics.SINGLETON_INSTANCE.update();
@@ -148,12 +148,12 @@ public enum CDeckEditorUI implements ICDoc {
public <T extends InventoryItem> void move(Iterable<Entry<T, Integer>> items);
}
private <T extends InventoryItem> void moveSelectedItems(ItemManager<T> itemManager, _MoveAction moveAction, int maxQty) {
private <T extends InventoryItem> void moveSelectedItems(final ItemManager<T> itemManager, final _MoveAction moveAction, final int maxQty) {
if (maxQty == 0) { return; }
ItemPool<T> items = new ItemPool<T>(itemManager.getGenericType());
for (T item : itemManager.getSelectedItems()) {
int qty = Math.min(maxQty, itemManager.getItemCount(item));
final ItemPool<T> items = new ItemPool<T>(itemManager.getGenericType());
for (final T item : itemManager.getSelectedItems()) {
final int qty = Math.min(maxQty, itemManager.getItemCount(item));
if (qty > 0) {
items.add(item, qty);
}
@@ -167,42 +167,28 @@ public enum CDeckEditorUI implements ICDoc {
}
@SuppressWarnings("unchecked")
public void addSelectedCards(final boolean toAlternate, int number) {
public void addSelectedCards(final boolean toAlternate, final int number) {
moveSelectedItems(childController.getCatalogManager(), new _MoveAction() {
@Override
public <T extends InventoryItem> void move(Iterable<Entry<T, Integer>> items) {
@Override public <T extends InventoryItem> void move(final Iterable<Entry<T, Integer>> items) {
((ACEditorBase<T, ?>)childController).addItems(items, toAlternate);
}
}, number);
}
@SuppressWarnings("unchecked")
public void removeSelectedCards(final boolean toAlternate, int number) {
public void removeSelectedCards(final boolean toAlternate, final int number) {
moveSelectedItems(childController.getDeckManager(), new _MoveAction() {
@Override
public <T extends InventoryItem> void move(Iterable<Entry<T, Integer>> items) {
@Override public <T extends InventoryItem> void move(final Iterable<Entry<T, Integer>> items) {
((ACEditorBase<T, ?>)childController).removeItems(items, toAlternate);
}
}, number);
}
@SuppressWarnings("unchecked")
public void removeAllCards(final boolean toAlternate) {
ItemManager<?> v = childController.getDeckManager();
v.selectAll();
moveSelectedItems(v, new _MoveAction() {
@Override
public <T extends InventoryItem> void move(Iterable<Entry<T, Integer>> items) {
((ACEditorBase<T, ?>)childController).removeItems(items, toAlternate);
}
}, Integer.MAX_VALUE);
}
/**
* Set current editor controller
*/
@SuppressWarnings("serial")
private void setCurrentEditorController(ACEditorBase<? extends InventoryItem, ? extends DeckBase> childController0) {
private void setCurrentEditorController(final ACEditorBase<? extends InventoryItem, ? extends DeckBase> childController0) {
this.childController = childController0;
Singletons.getControl().getForgeMenu().setProvider(childController0);
@@ -216,8 +202,7 @@ public enum CDeckEditorUI implements ICDoc {
if (!childController.listenersHooked) { //hook listeners the first time the controller is updated
catView.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
@Override public void keyPressed(final KeyEvent e) {
if (!catView.isIncrementalSearchActive() && KeyEvent.VK_SPACE == e.getKeyCode()) {
addSelectedCards(e.isControlDown() || e.isMetaDown(), e.isShiftDown() ? 4: 1);
}
@@ -229,8 +214,7 @@ public enum CDeckEditorUI implements ICDoc {
});
deckView.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
@Override public void keyPressed(final KeyEvent e) {
if (!catView.isIncrementalSearchActive() && KeyEvent.VK_SPACE == e.getKeyCode()) {
removeSelectedCards(e.isControlDown() || e.isMetaDown(), e.isShiftDown() ? 4: 1);
}
@@ -265,15 +249,13 @@ public enum CDeckEditorUI implements ICDoc {
//set card when selection changes
catView.addSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
@Override public void valueChanged(final ListSelectionEvent e) {
setCard(catView.getSelectedItem());
}
});
deckView.addSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
@Override public void valueChanged(final ListSelectionEvent e) {
setCard(deckView.getSelectedItem());
}
});
@@ -296,14 +278,6 @@ public enum CDeckEditorUI implements ICDoc {
});
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
@Override
public void register() {
EDocID.CARD_PICTURE.setDoc(cDetailPicture.getCPicture().getView());
@@ -316,17 +290,16 @@ public enum CDeckEditorUI implements ICDoc {
@Override
public void initialize() {
//change to previously open child controller based on screen
FScreen screen = Singletons.getControl().getCurrentScreen();
ACEditorBase<? extends InventoryItem, ? extends DeckBase> screenChildController = screenChildControllers.get(screen);
final FScreen screen = Singletons.getControl().getCurrentScreen();
final ACEditorBase<? extends InventoryItem, ? extends DeckBase> screenChildController = screenChildControllers.get(screen);
if (screenChildController != null) {
setCurrentEditorController(screenChildController);
}
else if (screen == FScreen.DECK_EDITOR_CONSTRUCTED) {
} else if (screen == FScreen.DECK_EDITOR_CONSTRUCTED) {
setEditorController(new CEditorConstructed(cDetailPicture)); //ensure Constructed deck editor controller initialized
String currentDeckStr = DeckPreferences.getCurrentDeck();
final String currentDeckStr = DeckPreferences.getCurrentDeck();
if (currentDeckStr != null) {
DeckProxy deck = vAllDecks.getLstDecks().stringToItem(currentDeckStr);
final DeckProxy deck = vAllDecks.getLstDecks().stringToItem(currentDeckStr);
if (deck != null) {
vAllDecks.getLstDecks().setSelectedItem(deck);
childController.getDeckController().load(deck.getPath(), deck.getName());

View File

@@ -17,6 +17,15 @@
*/
package forge.screens.deckeditor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import forge.deck.Deck;
import forge.deck.DeckBase;
import forge.deck.DeckImportController;
@@ -24,17 +33,16 @@ import forge.deck.DeckRecognizer;
import forge.deck.DeckRecognizer.TokenType;
import forge.item.InventoryItem;
import forge.screens.deckeditor.controllers.ACEditorBase;
import forge.toolbox.*;
import forge.toolbox.FButton;
import forge.toolbox.FCheckBox;
import forge.toolbox.FComboBox;
import forge.toolbox.FHtmlViewer;
import forge.toolbox.FLabel;
import forge.toolbox.FScrollPane;
import forge.toolbox.FSkin;
import forge.toolbox.FTextArea;
import forge.view.FDialog;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.util.List;
/**
*
* Dialog for quick import of decks.
@@ -87,7 +95,7 @@ public class DeckImport<TItem extends InventoryItem, TModel extends DeckBase> ex
private final ACEditorBase<TItem, TModel> host;
public DeckImport(final ACEditorBase<TItem, TModel> g, boolean allowCardsFromAllSets) {
public DeckImport(final ACEditorBase<TItem, TModel> g, final boolean allowCardsFromAllSets) {
this.controller = new DeckImportController(!g.getDeckController().isEmpty(),
newEditionCheck, dateTimeCheck, onlyCoreExpCheck, monthDropdown, yearDropdown);
this.host = g;
@@ -102,7 +110,7 @@ public class DeckImport<TItem extends InventoryItem, TModel extends DeckBase> ex
txtInput.setFocusable(true);
txtInput.setEditable(true);
FSkin.SkinColor foreColor = FSkin.getColor(FSkin.Colors.CLR_TEXT);
final FSkin.SkinColor foreColor = FSkin.getColor(FSkin.Colors.CLR_TEXT);
this.scrollInput.setBorder(new FSkin.TitledSkinBorder(BorderFactory.createEtchedBorder(), "Paste or type a decklist", foreColor));
this.scrollOutput.setBorder(new FSkin.TitledSkinBorder(BorderFactory.createEtchedBorder(), "Expect the recognized lines to appear", foreColor));
this.scrollInput.setViewportBorder(BorderFactory.createLoweredBevelBorder());
@@ -144,10 +152,9 @@ public class DeckImport<TItem extends InventoryItem, TModel extends DeckBase> ex
}
});
ActionListener updateDateCheck = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean isSel = dateTimeCheck.isSelected();
final ActionListener updateDateCheck = new ActionListener() {
@Override public void actionPerformed(final ActionEvent e) {
final boolean isSel = dateTimeCheck.isSelected();
monthDropdown.setEnabled(isSel);
yearDropdown.setEnabled(isSel);
parseAndDisplay();
@@ -155,8 +162,10 @@ public class DeckImport<TItem extends InventoryItem, TModel extends DeckBase> ex
};
this.dateTimeCheck.addActionListener(updateDateCheck);
ActionListener reparse = new ActionListener() {
@Override public void actionPerformed(ActionEvent e) { parseAndDisplay(); }
final ActionListener reparse = new ActionListener() {
@Override public void actionPerformed(final ActionEvent e) {
parseAndDisplay();
}
};
this.newEditionCheck.addActionListener(reparse);
this.onlyCoreExpCheck.addActionListener(reparse);
@@ -192,12 +201,12 @@ public class DeckImport<TItem extends InventoryItem, TModel extends DeckBase> ex
}
private void parseAndDisplay() {
List<DeckRecognizer.Token> tokens = controller.parseInput(txtInput.getText());
final List<DeckRecognizer.Token> tokens = controller.parseInput(txtInput.getText());
displayTokens(tokens);
updateSummaries(tokens);
}
private void displayTokens(List<DeckRecognizer.Token> tokens) {
private void displayTokens(final List<DeckRecognizer.Token> tokens) {
if (tokens.isEmpty()) {
htmlOutput.setText(HTML_WELCOME_TEXT);
}
@@ -212,7 +221,7 @@ public class DeckImport<TItem extends InventoryItem, TModel extends DeckBase> ex
}
}
private void updateSummaries(List<DeckRecognizer.Token> tokens) {
private void updateSummaries(final List<DeckRecognizer.Token> tokens) {
final int[] cardsOk = new int[2];
final int[] cardsUnknown = new int[2];
int idx = 0;
@@ -232,7 +241,7 @@ public class DeckImport<TItem extends InventoryItem, TModel extends DeckBase> ex
cmdAccept.setEnabled(cardsOk[0] > 0);
}
private String makeHtmlViewOfToken(final DeckRecognizer.Token token) {
private static String makeHtmlViewOfToken(final DeckRecognizer.Token token) {
switch (token.getType()) {
case KnownCard:
return String.format("<div class='knowncard'>%s * %s [%s] %s</div>", token.getNumber(), token.getCard()

View File

@@ -17,6 +17,18 @@
*/
package forge.screens.deckeditor.controllers;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.deck.Deck;
@@ -24,7 +36,11 @@ import forge.deck.DeckBase;
import forge.deck.DeckSection;
import forge.gui.GuiChoose;
import forge.gui.GuiUtils;
import forge.gui.framework.*;
import forge.gui.framework.DragCell;
import forge.gui.framework.FScreen;
import forge.gui.framework.ICDoc;
import forge.gui.framework.IVDoc;
import forge.gui.framework.SRearrangingUtil;
import forge.item.InventoryItem;
import forge.item.PaperCard;
import forge.itemmanager.ItemManager;
@@ -43,15 +59,6 @@ import forge.toolbox.FSkin;
import forge.util.ItemPool;
import forge.view.FView;
import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
/**
* Maintains a generically typed architecture for various editing
* environments. A basic editor instance requires a card catalog, the
@@ -138,41 +145,35 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
return new CDeckEditorUIMenus().getMenus();
}
public final void addItem(TItem item) {
public final void addItem(final TItem item) {
onAddItems(createPoolForItem(item, 1), false);
}
public final void addItem(TItem item, int qty) {
public final void addItem(final TItem item, final int qty) {
onAddItems(createPoolForItem(item, qty), false);
}
public final void addItem(TItem item, int qty, boolean toAlternate) {
onAddItems(createPoolForItem(item, qty), toAlternate);
}
public final void removeItem(TItem item) {
public final void removeItem(final TItem item) {
onRemoveItems(createPoolForItem(item, 1), false);
}
public final void removeItem(TItem item, int qty) {
public final void removeItem(final TItem item, final int qty) {
onRemoveItems(createPoolForItem(item, qty), false);
}
public final void removeItem(TItem item, int qty, boolean toAlternate) {
onRemoveItems(createPoolForItem(item, qty), toAlternate);
}
@SuppressWarnings("unchecked")
private ItemPool<TItem> createPoolForItem(final TItem item, final int qty) {
if (item == null || qty <= 0) { return null; }
ItemPool<TItem> pool = new ItemPool<TItem>((Class<TItem>)item.getClass());
final ItemPool<TItem> pool = new ItemPool<TItem>((Class<TItem>)item.getClass());
pool.add(item, qty);
return pool;
}
public final void addItems(Iterable<Entry<TItem, Integer>> items, boolean toAlternate) {
public final void addItems(final Iterable<Entry<TItem, Integer>> items, final boolean toAlternate) {
if (items == null || !items.iterator().hasNext()) { return; } //do nothing if no items
onAddItems(items, toAlternate);
}
public final void removeItems(Iterable<Entry<TItem, Integer>> items, boolean toAlternate) {
public final void removeItems(final Iterable<Entry<TItem, Integer>> items, final boolean toAlternate) {
if (items == null || !items.iterator().hasNext()) { return; } //do nothing if no items
onRemoveItems(items, toAlternate);
}
@@ -189,15 +190,15 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
/**
* @return pool of additions allowed to deck
*/
protected ItemPool<TItem> getAllowedAdditions(Iterable<Entry<TItem, Integer>> itemsToAdd) {
ItemPool<TItem> additions = new ItemPool<TItem>(getCatalogManager().getGenericType());
CardLimit limit = getCardLimit();
DeckController<TModel> controller = getDeckController();
Deck deck = controller != null && controller.getModel() instanceof Deck ? (Deck)controller.getModel() : null;
protected ItemPool<TItem> getAllowedAdditions(final Iterable<Entry<TItem, Integer>> itemsToAdd) {
final ItemPool<TItem> additions = new ItemPool<TItem>(getCatalogManager().getGenericType());
final CardLimit limit = getCardLimit();
final DeckController<TModel> controller = getDeckController();
final Deck deck = controller != null && controller.getModel() instanceof Deck ? (Deck)controller.getModel() : null;
for (Entry<TItem, Integer> itemEntry : itemsToAdd) {
TItem item = itemEntry.getKey();
PaperCard card = item instanceof PaperCard ? (PaperCard)item : null;
for (final Entry<TItem, Integer> itemEntry : itemsToAdd) {
final TItem item = itemEntry.getKey();
final PaperCard card = item instanceof PaperCard ? (PaperCard)item : null;
int qty = itemEntry.getValue();
int max;
@@ -289,14 +290,12 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
this.deckManager = itemManager;
btnRemove.setCommand(new UiCommand() {
@Override
public void run() {
@Override public void run() {
CDeckEditorUI.SINGLETON_INSTANCE.removeSelectedCards(false, 1);
}
});
btnRemove4.setCommand(new UiCommand() {
@Override
public void run() {
@Override public void run() {
CDeckEditorUI.SINGLETON_INSTANCE.removeSelectedCards(false, 4);
}
});
@@ -324,14 +323,12 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
this.catalogManager = itemManager;
btnAdd.setCommand(new UiCommand() {
@Override
public void run() {
@Override public void run() {
CDeckEditorUI.SINGLETON_INSTANCE.addSelectedCards(false, 1);
}
});
btnAdd4.setCommand(new UiCommand() {
@Override
public void run() {
@Override public void run() {
CDeckEditorUI.SINGLETON_INSTANCE.addSelectedCards(false, 4);
}
});
@@ -342,7 +339,7 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
/**
* Removes the specified tab and returns its parent for later re-adding
*/
protected DragCell removeTab (IVDoc<? extends ICDoc> tab) {
protected DragCell removeTab (final IVDoc<? extends ICDoc> tab) {
final DragCell parent;
if (tab.getParentCell() == null) {
parent = null;
@@ -398,7 +395,7 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
public FLabel getBtnRemove4() { return btnRemove4; }
public FLabel getBtnCycleSection() { return btnCycleSection; }
public ContextMenuBuilder createContextMenuBuilder(boolean isAddContextMenu0) {
public ContextMenuBuilder createContextMenuBuilder(final boolean isAddContextMenu0) {
return new EditorContextMenuBuilder(isAddContextMenu0);
}
@@ -406,7 +403,7 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
private final boolean isAddContextMenu;
private JPopupMenu menu;
private EditorContextMenuBuilder(boolean isAddContextMenu0) {
private EditorContextMenuBuilder(final boolean isAddContextMenu0) {
isAddContextMenu = isAddContextMenu0;
}
@@ -419,7 +416,7 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
}
@Override
public void buildContextMenu(JPopupMenu menu) {
public void buildContextMenu(final JPopupMenu menu) {
this.menu = menu; //cache menu while controller populates menu
if (isAddContextMenu) {
buildAddContextMenu(this);
@@ -459,15 +456,14 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
});
}
private void addItem(String verb, String dest, final boolean toAlternate, final int qty, int shortcutModifiers) {
private void addItem(final String verb, final String dest, final boolean toAlternate, final int qty, final int shortcutModifiers) {
String label = verb + " " + SItemManagerUtil.getItemDisplayString(getItemManager().getSelectedItems(), qty, false);
if (dest != null && !dest.isEmpty()) {
label += " " + dest;
}
GuiUtils.addMenuItem(menu, label,
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, shortcutModifiers), new Runnable() {
@Override
public void run() {
@Override public void run() {
Integer quantity = qty;
if (quantity < 0) {
quantity = GuiChoose.getInteger("Choose a value for X", 1, -quantity, 20);
@@ -492,7 +488,7 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
return 0;
}
int max = Integer.MAX_VALUE;
for (Entry<TItem, Integer> itemEntry : selectedItemPool) {
for (final Entry<TItem, Integer> itemEntry : selectedItemPool) {
if (itemEntry.getValue() < max) {
max = itemEntry.getValue();
}
@@ -500,8 +496,8 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
return max;
}
private void addItems(String verb, String dest, boolean toAlternate, int shortcutModifiers1, int shortcutModifiers2, int shortcutModifiers3) {
int max = getMaxMoveQuantity();
private void addItems(final String verb, final String dest, final boolean toAlternate, final int shortcutModifiers1, final int shortcutModifiers2, final int shortcutModifiers3) {
final int max = getMaxMoveQuantity();
if (max == 0) { return; }
addItem(verb, dest, toAlternate, 1, shortcutModifiers1);
@@ -518,11 +514,11 @@ public abstract class ACEditorBase<TItem extends InventoryItem, TModel extends D
addItem(verb, dest, toAlternate, -max, shortcutModifiers3); //pass -max as quantity to indicate to prompt for specific quantity
}
public void addMoveItems(String verb, String dest) {
public void addMoveItems(final String verb, final String dest) {
addItems(verb, dest, false, 0, InputEvent.SHIFT_DOWN_MASK, InputEvent.ALT_MASK);
}
public void addMoveAlternateItems(String verb, String dest) {
public void addMoveAlternateItems(final String verb, final String dest) {
if (this.menu.getComponentCount() > 0) {
this.menu.addSeparator();
}

View File

@@ -1,6 +1,5 @@
package forge.screens.deckeditor.controllers;
import forge.UiCommand;
import forge.deck.DeckProxy;
import forge.gui.framework.ICDoc;
import forge.itemmanager.ItemManagerConfig;
@@ -13,18 +12,11 @@ import forge.screens.deckeditor.views.VAllDecks;
*
*/
public enum CAllDecks implements ICDoc {
/** */
SINGLETON_INSTANCE;
//========== Overridden methods
private final VAllDecks view = VAllDecks.SINGLETON_INSTANCE;
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
//========== Overridden methods
@Override
public void register() {
@@ -39,7 +31,7 @@ public enum CAllDecks implements ICDoc {
}
public void refresh() {
VAllDecks.SINGLETON_INSTANCE.getLstDecks().setPool(DeckProxy.getAllConstructedDecks());
view.getLstDecks().setPool(DeckProxy.getAllConstructedDecks());
}
/* (non-Javadoc)
@@ -47,6 +39,6 @@ public enum CAllDecks implements ICDoc {
*/
@Override
public void update() {
VAllDecks.SINGLETON_INSTANCE.getLstDecks().setup(ItemManagerConfig.CONSTRUCTED_DECKS);
view.getLstDecks().setup(ItemManagerConfig.CONSTRUCTED_DECKS);
}
}

View File

@@ -1,6 +1,5 @@
package forge.screens.deckeditor.controllers;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
/**
@@ -18,14 +17,6 @@ public enum CCardCatalog implements ICDoc {
//========== Overridden methods
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
@Override
public void register() {
}

View File

@@ -1,7 +1,16 @@
package forge.screens.deckeditor.controllers;
import forge.UiCommand;
import java.awt.Dialog.ModalityType;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import forge.Singletons;
import forge.UiCommand;
import forge.deck.Deck;
import forge.deck.DeckBase;
import forge.deck.io.DeckSerializer;
@@ -14,14 +23,6 @@ import forge.screens.deckeditor.DeckImport;
import forge.screens.deckeditor.SEditorIO;
import forge.screens.deckeditor.views.VCurrentDeck;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.Dialog.ModalityType;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
/**
* Controls the "current deck" panel in the deck editor UI.
*
@@ -29,30 +30,26 @@ import java.io.File;
*
*/
public enum CCurrentDeck implements ICDoc {
/** */
SINGLETON_INSTANCE;
private static File previousDirectory;
private JFileChooser fileChooser = new JFileChooser(ForgeConstants.DECK_BASE_DIR);
private final JFileChooser fileChooser = new JFileChooser(ForgeConstants.DECK_BASE_DIR);
//========== Overridden methods
private CCurrentDeck() {
FileFilter[] defaultFilters = fileChooser.getChoosableFileFilters();
for(FileFilter defFilter : defaultFilters)
{
final FileFilter[] defaultFilters = fileChooser.getChoosableFileFilters();
for (final FileFilter defFilter : defaultFilters) {
fileChooser.removeChoosableFileFilter(defFilter);
}
FileFilter DCK_FILTER = new FileFilter() {
@Override
public boolean accept(final File f) {
final FileFilter DCK_FILTER = new FileFilter() {
@Override public final boolean accept(final File f) {
return f.getName().endsWith(DeckStorage.FILE_EXTENSION) || f.isDirectory();
}
@Override
public String getDescription() {
@Override public final String getDescription() {
return "Simple Deck File .dck";
}
};
@@ -60,14 +57,6 @@ public enum CCurrentDeck implements ICDoc {
fileChooser.addChoosableFileFilter(DCK_FILTER);
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
@Override
public void register() {
}
@@ -117,7 +106,7 @@ public enum CCurrentDeck implements ICDoc {
});
VCurrentDeck.SINGLETON_INSTANCE.getTxfTitle().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
public void keyPressed(final KeyEvent e) {
if (Character.isLetterOrDigit(e.getKeyChar())) {
CDeckEditorUI.SINGLETON_INSTANCE.getCurrentEditorController().getDeckController().notifyModelChanged();
}
@@ -204,7 +193,7 @@ public enum CCurrentDeck implements ICDoc {
/** */
@SuppressWarnings("unchecked")
private void exportDeck() {
DeckController<Deck> controller = (DeckController<Deck>)
final DeckController<Deck> controller = (DeckController<Deck>)
CDeckEditorUI.SINGLETON_INSTANCE.getCurrentEditorController().getDeckController();
final File filename = this.getExportFilename();
@@ -215,7 +204,7 @@ public enum CCurrentDeck implements ICDoc {
//create copy of deck to save under new name
String name = filename.getName();
name = name.substring(0, name.lastIndexOf(".")); //remove extension
Deck deck = (Deck)controller.getModel().copyTo(name);
final Deck deck = (Deck)controller.getModel().copyTo(name);
try {
DeckSerializer.writeDeck(deck, filename);

View File

@@ -4,15 +4,19 @@ import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import forge.UiCommand;
import forge.Singletons;
import forge.UiCommand;
import forge.card.CardDb;
import forge.card.CardRulesPredicates;
import forge.card.MagicColor;
import forge.deck.Deck;
import forge.deck.DeckBase;
import forge.deck.DeckFormat;
import forge.deck.generation.*;
import forge.deck.generation.DeckGenerator2Color;
import forge.deck.generation.DeckGenerator3Color;
import forge.deck.generation.DeckGenerator5Color;
import forge.deck.generation.DeckGeneratorBase;
import forge.deck.generation.DeckGeneratorMonoColor;
import forge.gui.framework.ICDoc;
import forge.item.InventoryItem;
import forge.item.PaperCard;
@@ -36,14 +40,6 @@ public enum CDeckgen implements ICDoc {
//========== Overridden methods
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
@Override
public void register() {
}
@@ -94,11 +90,11 @@ public enum CDeckgen implements ICDoc {
final Deck randomDeck = new Deck();
Predicate<PaperCard> notBasicLand = Predicates.not(Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard.FN_GET_RULES));
Iterable<PaperCard> source = Iterables.filter(FModel.getMagicDb().getCommonCards().getUniqueCards(), notBasicLand);
final Predicate<PaperCard> notBasicLand = Predicates.not(Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard.FN_GET_RULES));
final Iterable<PaperCard> source = Iterables.filter(FModel.getMagicDb().getCommonCards().getUniqueCards(), notBasicLand);
randomDeck.getMain().addAllFlat(Aggregates.random(source, 15 * 5));
for(String landName : MagicColor.Constant.BASIC_LANDS) {
for(final String landName : MagicColor.Constant.BASIC_LANDS) {
randomDeck.getMain().add(landName, 1);
}
randomDeck.getMain().add("Terramorphic Expanse", 1);
@@ -114,7 +110,7 @@ public enum CDeckgen implements ICDoc {
if (!SEditorIO.confirmSaveChanges(Singletons.getControl().getCurrentScreen(), true)) { return; }
final Deck genConstructed = new Deck();
CardDb cardDb = FModel.getMagicDb().getCommonCards();
final CardDb cardDb = FModel.getMagicDb().getCommonCards();
DeckGeneratorBase gen = null;
switch (colorCount0) {
case 1: gen = new DeckGeneratorMonoColor(cardDb, DeckFormat.Constructed, null); break;

View File

@@ -17,6 +17,12 @@
*/
package forge.screens.deckeditor.controllers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
@@ -42,14 +48,6 @@ import forge.screens.home.quest.CSubmenuQuestDecks;
import forge.screens.match.controllers.CDetailPicture;
import forge.util.ItemPool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
//import forge.quest.data.QuestBoosterPack;
/**
* Child controller for quest deck editor UI.
* <br><br>
@@ -121,16 +119,6 @@ public final class CEditorQuest extends ACEditorBase<PaperCard, Deck> {
this.controller = new DeckController<Deck>(questData0.getMyDecks(), this, newCreator);
}
/**
* Adds any card to the catalog and data pool.
*
* @param card {@link forge.item.PaperCard}
*/
public void addCheatCard(final PaperCard card, int qty) {
this.getCatalogManager().addItem(card, qty);
this.questData.getCards().getCardpool().add(card, qty);
}
// fills number of decks using each card
private Map<PaperCard, Integer> countDecksForEachCard() {
final Map<PaperCard, Integer> result = new HashMap<PaperCard, Integer>();
@@ -158,7 +146,7 @@ public final class CEditorQuest extends ACEditorBase<PaperCard, Deck> {
* @see forge.gui.deckeditor.ACEditorBase#onAddItems()
*/
@Override
protected void onAddItems(Iterable<Entry<PaperCard, Integer>> items, boolean toAlternate) {
protected void onAddItems(final Iterable<Entry<PaperCard, Integer>> items, final boolean toAlternate) {
CEditorConstructed.onAddItems(this, items, toAlternate);
}
@@ -166,7 +154,7 @@ public final class CEditorQuest extends ACEditorBase<PaperCard, Deck> {
* @see forge.gui.deckeditor.ACEditorBase#onRemoveItems()
*/
@Override
protected void onRemoveItems(Iterable<Entry<PaperCard, Integer>> items, boolean toAlternate) {
protected void onRemoveItems(final Iterable<Entry<PaperCard, Integer>> items, final boolean toAlternate) {
CEditorConstructed.onRemoveItems(this, items, toAlternate);
}
@@ -174,7 +162,7 @@ public final class CEditorQuest extends ACEditorBase<PaperCard, Deck> {
* @see forge.gui.deckeditor.ACEditorBase#buildAddContextMenu()
*/
@Override
protected void buildAddContextMenu(EditorContextMenuBuilder cmb) {
protected void buildAddContextMenu(final EditorContextMenuBuilder cmb) {
CEditorConstructed.buildAddContextMenu(cmb, sectionMode);
}
@@ -182,7 +170,7 @@ public final class CEditorQuest extends ACEditorBase<PaperCard, Deck> {
* @see forge.gui.deckeditor.ACEditorBase#buildRemoveContextMenu()
*/
@Override
protected void buildRemoveContextMenu(EditorContextMenuBuilder cmb) {
protected void buildRemoveContextMenu(final EditorContextMenuBuilder cmb) {
CEditorConstructed.buildRemoveContextMenu(cmb, sectionMode);
}
@@ -263,18 +251,17 @@ public final class CEditorQuest extends ACEditorBase<PaperCard, Deck> {
this.getBtnCycleSection().setVisible(true);
this.getBtnCycleSection().setCommand(new UiCommand() {
@Override
public void run() {
@Override public void run() {
cycleEditorMode();
} });
}
});
deckGenParent = removeTab(VDeckgen.SINGLETON_INSTANCE);
allDecksParent = removeTab(VAllDecks.SINGLETON_INSTANCE);
if (this.controller.getModel() == null) {
this.getDeckController().setModel(new Deck());
}
else {
} else {
this.controller.refreshModel();
}
}
@@ -283,7 +270,7 @@ public final class CEditorQuest extends ACEditorBase<PaperCard, Deck> {
* @see forge.gui.deckeditor.controllers.ACEditorBase#canSwitchAway()
*/
@Override
public boolean canSwitchAway(boolean isClosing) {
public boolean canSwitchAway(final boolean isClosing) {
if (SEditorIO.confirmSaveChanges(FScreen.DECK_EDITOR_QUEST, isClosing)) {
FModel.getQuest().save();
return true;
@@ -306,11 +293,4 @@ public final class CEditorQuest extends ACEditorBase<PaperCard, Deck> {
}
}
/**
* TODO: Write javadoc for this method.
* @param d0
*/
public void load(Deck deck) {
controller.setModel(deck);
}
}

View File

@@ -48,8 +48,6 @@ import forge.screens.deckeditor.views.VDeckgen;
import forge.screens.home.quest.CSubmenuQuestDecks;
import forge.screens.match.controllers.CDetailPicture;
//import forge.quest.data.QuestBoosterPack;
/**
* Child controller for quest deck editor UI.
* <br><br>
@@ -124,16 +122,6 @@ public final class CEditorQuestLimited extends ACEditorBase<PaperCard, DeckGroup
}
/**
* Adds any card to the catalog and data pool.
*
* @param card {@link forge.item.PaperCard}
*/
public void addCheatCard(final PaperCard card, int qty) {
this.getCatalogManager().addItem(card, qty);
this.questData.getCards().getCardpool().add(card, qty);
}
// fills number of decks using each card
private Map<PaperCard, Integer> countDecksForEachCard() {
final Map<PaperCard, Integer> result = new HashMap<PaperCard, Integer>();
@@ -161,8 +149,10 @@ public final class CEditorQuestLimited extends ACEditorBase<PaperCard, DeckGroup
* @see forge.gui.deckeditor.ACEditorBase#onAddItems()
*/
@Override
protected void onAddItems(Iterable<Entry<PaperCard, Integer>> items, boolean toAlternate) {
if (toAlternate) { return; }
protected void onAddItems(final Iterable<Entry<PaperCard, Integer>> items, final boolean toAlternate) {
if (toAlternate) {
return;
}
// update view
this.getDeckManager().addItems(items);
@@ -174,8 +164,10 @@ public final class CEditorQuestLimited extends ACEditorBase<PaperCard, DeckGroup
* @see forge.gui.deckeditor.ACEditorBase#onRemoveItems()
*/
@Override
protected void onRemoveItems(Iterable<Entry<PaperCard, Integer>> items, boolean toAlternate) {
if (toAlternate) { return; }
protected void onRemoveItems(final Iterable<Entry<PaperCard, Integer>> items, final boolean toAlternate) {
if (toAlternate) {
return;
}
// update view
this.getCatalogManager().addItems(items);
@@ -187,7 +179,7 @@ public final class CEditorQuestLimited extends ACEditorBase<PaperCard, DeckGroup
* @see forge.gui.deckeditor.ACEditorBase#buildAddContextMenu()
*/
@Override
protected void buildAddContextMenu(EditorContextMenuBuilder cmb) {
protected void buildAddContextMenu(final EditorContextMenuBuilder cmb) {
cmb.addMoveItems("Move", "to deck");
}
@@ -195,7 +187,7 @@ public final class CEditorQuestLimited extends ACEditorBase<PaperCard, DeckGroup
* @see forge.gui.deckeditor.ACEditorBase#buildRemoveContextMenu()
*/
@Override
protected void buildRemoveContextMenu(EditorContextMenuBuilder cmb) {
protected void buildRemoveContextMenu(final EditorContextMenuBuilder cmb) {
cmb.addMoveItems("Move", "to sideboard");
}
@@ -266,7 +258,7 @@ public final class CEditorQuestLimited extends ACEditorBase<PaperCard, DeckGroup
* @see forge.gui.deckeditor.controllers.ACEditorBase#canSwitchAway()
*/
@Override
public boolean canSwitchAway(boolean isClosing) {
public boolean canSwitchAway(final boolean isClosing) {
if (SEditorIO.confirmSaveChanges(FScreen.DECK_EDITOR_QUEST_TOURNAMENT, isClosing)) {
FModel.getQuest().save();
return true;
@@ -290,11 +282,4 @@ public final class CEditorQuestLimited extends ACEditorBase<PaperCard, DeckGroup
}
}
/**
* TODO: Write javadoc for this method.
* @param d0
*/
/*public void load(Deck deck) {
controller.setModel(deck);
}*/
}

View File

@@ -1,5 +1,12 @@
package forge.screens.deckeditor.controllers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import forge.UiCommand;
import forge.deck.DeckBase;
import forge.gui.framework.ICDoc;
@@ -10,8 +17,6 @@ import forge.screens.deckeditor.views.VProbabilities;
import forge.util.ItemPool;
import forge.util.MyRandom;
import java.util.*;
/**
* Controls the "analysis" panel in the deck editor UI.
*
@@ -24,14 +29,6 @@ public enum CProbabilities implements ICDoc {
//========== Overridden methods
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
@Override
public void register() {
}
@@ -84,11 +81,10 @@ public enum CProbabilities implements ICDoc {
// Formulas is (remaining instances of this card / total cards remaining)
final Iterator<PaperCard> itr = shuffled.iterator();
PaperCard tmp;
// int prob;
while (itr.hasNext()) {
tmp = itr.next();
// prob = SEditorUtil.calculatePercentage(
// int prob = SEditorUtil.calculatePercentage(
// cardTotals.get(tmp), shuffled.size());
cardTotals.put(tmp, cardTotals.get(tmp) - 1);

View File

@@ -1,9 +1,12 @@
package forge.screens.deckeditor.controllers;
import java.util.Map.Entry;
import javax.swing.JLabel;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import forge.UiCommand;
import forge.card.CardRules;
import forge.card.CardRulesPredicates;
import forge.card.MagicColor;
@@ -16,11 +19,6 @@ import forge.screens.deckeditor.CDeckEditorUI;
import forge.screens.deckeditor.views.VStatistics;
import forge.util.ItemPool;
import javax.swing.*;
import java.util.Map.Entry;
/**
* Controls the "analysis" panel in the deck editor UI.
*
@@ -33,14 +31,6 @@ public enum CStatistics implements ICDoc {
//========== Overridden methods
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
@Override
public void register() {
}
@@ -60,8 +50,8 @@ public enum CStatistics implements ICDoc {
analyze();
}
private void setLabelValue(JLabel label, ItemPool<PaperCard> deck, Predicate<CardRules> predicate, int total) {
int tmp = deck.countAll(Predicates.compose(predicate, PaperCard.FN_GET_RULES));
private void setLabelValue(final JLabel label, final ItemPool<PaperCard> deck, final Predicate<CardRules> predicate, final int total) {
final int tmp = deck.countAll(Predicates.compose(predicate, PaperCard.FN_GET_RULES));
label.setText(tmp + " (" + calculatePercentage(tmp, total) + "%)");
}
@@ -76,7 +66,7 @@ public enum CStatistics implements ICDoc {
final ItemPool<PaperCard> deck = ItemPool.createFrom(ed.getDeckManager().getPool(), PaperCard.class);
int total = deck.countAll();
int[] shardCount = calculateShards(deck);
final int[] shardCount = calculateShards(deck);
// Hack-ish: avoid /0 cases, but still populate labels :)
if (total == 0) { total = 1; }
@@ -115,7 +105,7 @@ public enum CStatistics implements ICDoc {
for (final Entry<PaperCard, Integer> e : deck) {
tmc += e.getKey().getRules().getManaCost().getCMC() * e.getValue();
}
double amc = Math.round((double) tmc / (double) total * 100) / 100.0d;
final double amc = Math.round((double) tmc / (double) total * 100) / 100.0d;
VStatistics.SINGLETON_INSTANCE.getLblTotal().setText("TOTAL CARDS: " + deck.countAll());
VStatistics.SINGLETON_INSTANCE.getLblTMC().setText("TOTAL MANA COST: " + tmc);
@@ -133,10 +123,10 @@ public enum CStatistics implements ICDoc {
return (int) Math.round((double) (x0 * 100) / (double) y0);
}
public static int[] calculateShards(ItemPool<PaperCard> deck) {
int[] counts = new int[5]; // in WUBRG order
for (PaperCard c : deck.toFlatList()) {
int[] cShards = c.getRules().getManaCost().getColorShardCounts();
public static int[] calculateShards(final ItemPool<PaperCard> deck) {
final int[] counts = new int[5]; // in WUBRG order
for (final PaperCard c : deck.toFlatList()) {
final int[] cShards = c.getRules().getManaCost().getColorShardCounts();
for (int i = 0; i < 5; i++) {
counts[i] += cShards[i];
}

View File

@@ -27,11 +27,6 @@ import forge.screens.deckeditor.views.VCurrentDeck;
import forge.screens.home.sanctioned.VSubmenuConstructed;
import forge.util.storage.IStorage;
/**
* TODO: Write javadoc for this type.
*
* @param <T> the generic type
*/
public class DeckController<T extends DeckBase> {
private T model;
private boolean saved;
@@ -99,8 +94,7 @@ public class DeckController<T extends DeckBase> {
else {
this.notifyModelChanged();
}
}
else { //TODO: Make this smarter
} else { //TODO: Make this smarter
this.currentFolder = this.rootFolder;
this.modelPath = "";
this.setSaved(true);
@@ -142,7 +136,7 @@ public class DeckController<T extends DeckBase> {
}
}
private void setSaved(boolean val) {
private void setSaved(final boolean val) {
saved = val;
updateCaptions();
}
@@ -151,7 +145,7 @@ public class DeckController<T extends DeckBase> {
* Reload current model
*/
public void reload() {
String name = this.getModelName();
final String name = this.getModelName();
if (name.isEmpty()) {
newModel();
}
@@ -178,7 +172,7 @@ public class DeckController<T extends DeckBase> {
*/
@SuppressWarnings("unchecked")
private void load(final String name) {
T newModel = this.currentFolder.get(name);
final T newModel = this.currentFolder.get(name);
if (newModel != null) {
this.setModel((T) newModel.copyTo(name), true);
}
@@ -236,15 +230,6 @@ public class DeckController<T extends DeckBase> {
return this.currentFolder.contains(deckName);
}
/**
* Import deck.
*
* @param newDeck the new deck
*/
public void importDeck(final T newDeck) {
this.setModel(newDeck);
}
/**
* Refresh current model or create new one if none
*/
@@ -272,7 +257,7 @@ public class DeckController<T extends DeckBase> {
public void updateCaptions() {
String tabCaption = "Current Deck";
String title = this.getModelName();
final String title = this.getModelName();
String itemManagerCaption = title.isEmpty() ? "[Untitled]" : title;
if (!saved) {

View File

@@ -1,5 +1,16 @@
package forge.screens.deckeditor.controllers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import forge.deck.Deck;
import forge.item.PaperCard;
import forge.properties.ForgeConstants;
@@ -9,13 +20,6 @@ import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
public class DeckHtmlSerializer {
public static void writeDeckHtml(final Deck d, final File f) {
try {
@@ -39,7 +43,7 @@ public class DeckHtmlSerializer {
* @throws java.io.IOException
* if any.
*/
private static void writeDeckHtml(final Deck d, final BufferedWriter out) throws IOException {
private static void writeDeckHtml(final Deck d, final BufferedWriter out) {
Template temp = null;
final int cardBorder = 0;
final int height = 319;
@@ -70,8 +74,8 @@ public class DeckHtmlSerializer {
for (final Entry<PaperCard, Integer> card : d.getMain()) {
// System.out.println(card.getSets().get(card.getSets().size() - 1).URL);
for (int i = card.getValue().intValue(); i > 0; --i ) {
PaperCard r = card.getKey();
String url = ForgeConstants.URL_PIC_DOWNLOAD + ImageUtil.getDownloadUrl(r, false);
final PaperCard r = card.getKey();
final String url = ForgeConstants.URL_PIC_DOWNLOAD + ImageUtil.getDownloadUrl(r, false);
list.add(url);
}
}

View File

@@ -1,5 +1,8 @@
package forge.screens.deckeditor.views;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import forge.gui.framework.DragCell;
import forge.gui.framework.DragTab;
import forge.gui.framework.EDocID;
@@ -8,9 +11,6 @@ import forge.item.InventoryItem;
import forge.itemmanager.ItemManager;
import forge.itemmanager.ItemManagerContainer;
import forge.screens.deckeditor.controllers.CCardCatalog;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
/**
* Assembles Swing components of card catalog in deck editor.
@@ -19,11 +19,8 @@ import javax.swing.*;
*
*/
public enum VCardCatalog implements IVDoc<CCardCatalog> {
/** */
SINGLETON_INSTANCE;
public static final int SEARCH_MODE_INVERSE_INDEX = 1;
// Fields used with interface IVDoc
private DragCell parentCell;
private final DragTab tab = new DragTab("Card Catalog");
@@ -54,7 +51,7 @@ public enum VCardCatalog implements IVDoc<CCardCatalog> {
}
@Override
public void setParentCell(DragCell cell0) {
public void setParentCell(final DragCell cell0) {
this.parentCell = cell0;
}
@@ -65,7 +62,7 @@ public enum VCardCatalog implements IVDoc<CCardCatalog> {
@Override
public void populate() {
JPanel parentBody = parentCell.getBody();
final JPanel parentBody = parentCell.getBody();
parentBody.setLayout(new MigLayout("insets 5, gap 0, wrap, hidemode 3"));
parentBody.add(itemManagerContainer, "push, grow");
}

View File

@@ -1,5 +1,9 @@
package forge.screens.deckeditor.views;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import forge.assets.FSkinProp;
import forge.gui.framework.DragCell;
import forge.gui.framework.DragTab;
@@ -12,10 +16,6 @@ import forge.screens.deckeditor.controllers.CCurrentDeck;
import forge.toolbox.FLabel;
import forge.toolbox.FSkin;
import forge.toolbox.FTextField;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
/**
* Assembles Swing components of current deck being edited in deck editor.
@@ -23,7 +23,6 @@ import javax.swing.*;
* <br><br><i>(V at beginning of class name denotes a view class.)</i>
*/
public enum VCurrentDeck implements IVDoc<CCurrentDeck> {
/** */
SINGLETON_INSTANCE;
// Fields used with interface IVDoc
@@ -211,7 +210,6 @@ public enum VCurrentDeck implements IVDoc<CCurrentDeck> {
* @return
*/
public FLabel getBtnImport() {
// TODO Auto-generated method stub
return (FLabel) btnImport;
return btnImport;
}
}

View File

@@ -1,5 +1,15 @@
package forge.screens.deckeditor.views;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import forge.deck.DeckBase;
import forge.gui.framework.DragCell;
import forge.gui.framework.DragTab;
@@ -13,14 +23,6 @@ import forge.screens.deckeditor.controllers.CProbabilities;
import forge.toolbox.FLabel;
import forge.toolbox.FScrollPane;
import forge.toolbox.FSkin;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
/**
* Assembles Swing components of deck editor analysis tab.
@@ -152,7 +154,7 @@ public enum VProbabilities implements IVDoc<CProbabilities> {
pnlLibrary.validate();
}
private <T extends InventoryItem, TModel extends DeckBase> JLabel buildLabel(final boolean zebra) {
private static <T extends InventoryItem, TModel extends DeckBase> JLabel buildLabel(final boolean zebra) {
final FLabel lbl = new FLabel.Builder().text("--")
.fontAlign(SwingConstants.CENTER).fontSize(13)
.build();
@@ -168,7 +170,7 @@ public enum VProbabilities implements IVDoc<CProbabilities> {
final String name1 = lbl.getText();
String name2;
for (PaperCard c : cards) {
for (final PaperCard c : cards) {
name2 = c.getName();
if (name2.length() > name1.length()) { continue; }

View File

@@ -1,5 +1,10 @@
package forge.screens.deckeditor.views;
import java.awt.Font;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import forge.gui.framework.DragCell;
import forge.gui.framework.DragTab;
import forge.gui.framework.EDocID;
@@ -10,11 +15,6 @@ import forge.toolbox.FLabel;
import forge.toolbox.FScrollPane;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinImage;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;
/**
* Assembles Swing components of deck editor analysis tab.
@@ -279,7 +279,7 @@ public enum VStatistics implements IVDoc<CStatistics> {
//========== Other methods
private FLabel buildLabel(SkinImage icon, boolean zebra) {
private static FLabel buildLabel(final SkinImage icon, final boolean zebra) {
final FLabel lbl = new FLabel.Builder().text("0 (0%)")
.icon(icon).iconScaleAuto(false)
.fontSize(11).build();
@@ -292,7 +292,7 @@ public enum VStatistics implements IVDoc<CStatistics> {
return lbl;
}
private FLabel buildLabel(StatTypes statType, boolean zebra) {
private static FLabel buildLabel(final StatTypes statType, final boolean zebra) {
return buildLabel(FSkin.getImage(statType.skinProp, 18, 18), zebra);
}
}

View File

@@ -5,7 +5,6 @@ import java.util.List;
import javax.swing.JMenu;
import forge.Singletons;
import forge.UiCommand;
import forge.gui.framework.EDocID;
import forge.gui.framework.ICDoc;
import forge.menus.IMenuProvider;
@@ -32,7 +31,7 @@ public enum CHomeUI implements ICDoc, IMenuProvider {
/** Programatically selects a menu item.
* @param id0 {@link forge.gui.framework.EDocID} */
public void itemClick(EDocID id0) {
public void itemClick(final EDocID id0) {
final ForgePreferences prefs = FModel.getPreferences();
if (lblSelected != null) {
@@ -89,14 +88,6 @@ public enum CHomeUI implements ICDoc, IMenuProvider {
public void update() {
}
/* (non-Javadoc)
* @see forge.view.home.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
/**
* Pulls previous menu selection from preferences
* and clicks it programatically.

View File

@@ -1,27 +0,0 @@
package forge.screens.home;
/**
* These are the identifiers for topics found in home screen submenus.
*
* <br><br><i>(E at beginning of class name denotes an enum.)</i>
*
*/
public enum EMenuItem { /** */
CONSTRUCTED, /** */
LIMITED_DRAFT, /** */
LIMITED_SEALED, /** */
LIMITED_WINSTON,
QUEST_CHALLENGES, /** */
QUEST_DUELS, /** */
QUEST_DATA, /** */
QUEST_DECKS, /** */
QUEST_PREFS, /** */
SETTINGS_PREFS, /** */
SETTINGS_AVATARS, /** */
UTILITIES_EDITOR, /** */
UTILITIES_DOWNLOADS, /** */
UTILITIES_EXIT
}

View File

@@ -74,8 +74,8 @@ public class PlayerPanel extends FPanel {
private FRadioButton radioOpen;
private FCheckBox chkReady;
private FComboBoxWrapper<Object> teamComboBox = new FComboBoxWrapper<Object>();
private FComboBoxWrapper<Object> aeTeamComboBox = new FComboBoxWrapper<Object>();
private final FComboBoxWrapper<Object> teamComboBox = new FComboBoxWrapper<Object>();
private final FComboBoxWrapper<Object> aeTeamComboBox = new FComboBoxWrapper<Object>();
private final FLabel closeBtn;
private final FLabel deckBtn = new FLabel.ButtonBuilder().text("Select a deck").build();
@@ -236,18 +236,18 @@ public class PlayerPanel extends FPanel {
* Listens to name text fields and gives the appropriate player focus. Also
* saves the name preference when leaving player one's text field.
*/
private FocusAdapter nameFocusListener = new FocusAdapter() {
private final FocusAdapter nameFocusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
public void focusGained(final FocusEvent e) {
lobby.changePlayerFocus(index);
}
@Override
public void focusLost(FocusEvent e) {
public void focusLost(final FocusEvent e) {
final Object source = e.getSource();
if (source instanceof FTextField) { // the text box
FTextField nField = (FTextField)source;
String newName = nField.getText().trim();
final FTextField nField = (FTextField)source;
final String newName = nField.getText().trim();
if (index == 0 && !StringUtils.isBlank(newName)
&& StringUtils.isAlphanumericSpace(newName) && prefs.getPref(FPref.PLAYER_NAME) != newName) {
prefs.setPref(FPref.PLAYER_NAME, newName);
@@ -259,14 +259,14 @@ public class PlayerPanel extends FPanel {
};
/** Listens to avatar buttons and gives the appropriate player focus. */
private FocusAdapter avatarFocusListener = new FocusAdapter() {
private final FocusAdapter avatarFocusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
public void focusGained(final FocusEvent e) {
lobby.changePlayerFocus(index);
}
};
private FMouseAdapter avatarMouseListener = new FMouseAdapter() {
private final FMouseAdapter avatarMouseListener = new FMouseAdapter() {
@Override public final void onLeftClick(final MouseEvent e) {
if (!avatarLabel.isEnabled()) {
return;
@@ -297,6 +297,7 @@ public class PlayerPanel extends FPanel {
lobby.firePlayerChangeListener(index);
}
@Override public final void onRightClick(final MouseEvent e) {
if (!avatarLabel.isEnabled()) {
return;
@@ -314,13 +315,13 @@ public class PlayerPanel extends FPanel {
};
private void updateVariantControlsVisibility() {
boolean isCommanderApplied = mayEdit && (lobby.hasVariant(GameType.Commander) || lobby.hasVariant(GameType.TinyLeaders));
boolean isPlanechaseApplied = mayEdit && lobby.hasVariant(GameType.Planechase);
boolean isVanguardApplied = mayEdit && lobby.hasVariant(GameType.Vanguard);
boolean isArchenemyApplied = mayEdit && lobby.hasVariant(GameType.Archenemy);
boolean archenemyVisiblity = mayEdit && lobby.hasVariant(GameType.ArchenemyRumble) || (isArchenemyApplied && isArchenemy());
final boolean isCommanderApplied = mayEdit && (lobby.hasVariant(GameType.Commander) || lobby.hasVariant(GameType.TinyLeaders));
final boolean isPlanechaseApplied = mayEdit && lobby.hasVariant(GameType.Planechase);
final boolean isVanguardApplied = mayEdit && lobby.hasVariant(GameType.Vanguard);
final boolean isArchenemyApplied = mayEdit && lobby.hasVariant(GameType.Archenemy);
final boolean archenemyVisiblity = mayEdit && lobby.hasVariant(GameType.ArchenemyRumble) || (isArchenemyApplied && isArchenemy());
// Commander deck building replaces normal one, so hide it
boolean isDeckBuildingAllowed = mayEdit && !isCommanderApplied && !lobby.hasVariant(GameType.MomirBasic);
final boolean isDeckBuildingAllowed = mayEdit && !isCommanderApplied && !lobby.hasVariant(GameType.MomirBasic);
deckLabel.setVisible(isDeckBuildingAllowed);
deckBtn.setVisible(isDeckBuildingAllowed);
@@ -344,7 +345,7 @@ public class PlayerPanel extends FPanel {
}
@Override
public void paintComponent(Graphics g) {
public void paintComponent(final Graphics g) {
super.paintComponent(g);
if (!hasFocusInLobby()) {
FSkin.setGraphicsColor(g, unfocusedPlayerOverlay);
@@ -356,10 +357,6 @@ public class PlayerPanel extends FPanel {
return lobby.hasFocus(index);
}
int getIndex() {
return index;
}
LobbySlotType getType() {
return type;
}
@@ -417,11 +414,11 @@ public class PlayerPanel extends FPanel {
}
}
public void setVanguardButtonText(String text) {
public void setVanguardButtonText(final String text) {
vgdSelectorBtn.setText(text);
}
public void setDeckSelectorButtonText(String text) {
public void setDeckSelectorButtonText(final String text) {
deckBtn.setText(text);
}
@@ -439,7 +436,7 @@ public class PlayerPanel extends FPanel {
teamComboBox.setEnabled(true);
}
private ActionListener teamListener = new ActionListener() {
private final ActionListener teamListener = new ActionListener() {
@SuppressWarnings("unchecked")
@Override public final void actionPerformed(final ActionEvent e) {
final FComboBox<Object> cb = (FComboBox<Object>) e.getSource();
@@ -460,7 +457,7 @@ public class PlayerPanel extends FPanel {
// Archenemy buttons
scmDeckSelectorBtn.setCommand(new Runnable() {
@Override public final void run() {
lobby.setCurrentGameMode(lobby.getVntArchenemy().isSelected() ? GameType.Archenemy : GameType.ArchenemyRumble);
lobby.setCurrentGameMode(lobby.hasVariant(GameType.Archenemy) ? GameType.Archenemy : GameType.ArchenemyRumble);
scmDeckSelectorBtn.requestFocusInWindow();
lobby.changePlayerFocus(index);
}
@@ -469,8 +466,8 @@ public class PlayerPanel extends FPanel {
scmDeckEditor.setCommand(new UiCommand() {
@Override
public void run() {
lobby.setCurrentGameMode(lobby.getVntArchenemy().isSelected() ? GameType.Archenemy : GameType.ArchenemyRumble);
Predicate<PaperCard> predSchemes = new Predicate<PaperCard>() {
lobby.setCurrentGameMode(lobby.hasVariant(GameType.Archenemy) ? GameType.Archenemy : GameType.ArchenemyRumble);
final Predicate<PaperCard> predSchemes = new Predicate<PaperCard>() {
@Override public final boolean apply(final PaperCard arg0) {
return arg0.getRules().getType().isScheme();
}
@@ -486,7 +483,7 @@ public class PlayerPanel extends FPanel {
cmdDeckSelectorBtn.setCommand(new Runnable() {
@Override
public void run() {
lobby.setCurrentGameMode(lobby.getVntTinyLeaders().isSelected() ? GameType.TinyLeaders : GameType.Commander);
lobby.setCurrentGameMode(lobby.hasVariant(GameType.TinyLeaders) ? GameType.TinyLeaders : GameType.Commander);
cmdDeckSelectorBtn.requestFocusInWindow();
lobby.changePlayerFocus(index);
}
@@ -495,7 +492,7 @@ public class PlayerPanel extends FPanel {
cmdDeckEditor.setCommand(new UiCommand() {
@Override
public void run() {
lobby.setCurrentGameMode(lobby.getVntTinyLeaders().isSelected() ? GameType.TinyLeaders : GameType.Commander);
lobby.setCurrentGameMode(lobby.hasVariant(GameType.TinyLeaders) ? GameType.TinyLeaders : GameType.Commander);
Singletons.getControl().setCurrentScreen(FScreen.DECK_EDITOR_COMMANDER);
CDeckEditorUI.SINGLETON_INSTANCE.setEditorController(new CEditorCommander(CDeckEditorUI.SINGLETON_INSTANCE.getCDetailPicture()));
}
@@ -515,9 +512,9 @@ public class PlayerPanel extends FPanel {
@Override
public void run() {
lobby.setCurrentGameMode(GameType.Planechase);
Predicate<PaperCard> predPlanes = new Predicate<PaperCard>() {
final Predicate<PaperCard> predPlanes = new Predicate<PaperCard>() {
@Override
public boolean apply(PaperCard arg0) {
public boolean apply(final PaperCard arg0) {
return arg0.getRules().getType().isPlane() || arg0.getRules().getType().isPhenomenon();
}
};
@@ -600,7 +597,7 @@ public class PlayerPanel extends FPanel {
newNameBtn.setCommand(new UiCommand() {
@Override
public void run() {
String newName = lobby.getNewName();
final String newName = lobby.getNewName();
if (null == newName) {
return;
}
@@ -656,7 +653,7 @@ public class PlayerPanel extends FPanel {
}
private void createAvatar() {
String[] currentPrefs = FModel.getPreferences().getPref(FPref.UI_AVATARS).split(",");
final String[] currentPrefs = FModel.getPreferences().getPref(FPref.UI_AVATARS).split(",");
if (index < currentPrefs.length) {
avatarIndex = Integer.parseInt(currentPrefs[index]);
avatarLabel.setIcon(FSkin.getAvatars().get(avatarIndex));
@@ -690,7 +687,7 @@ public class PlayerPanel extends FPanel {
private final FSkin.LineSkinBorder focusedBorder = new FSkin.LineSkinBorder(FSkin.getColor(FSkin.Colors.CLR_BORDERS).alphaColor(255), 3);
private final FSkin.LineSkinBorder defaultBorder = new FSkin.LineSkinBorder(FSkin.getColor(FSkin.Colors.CLR_THEME).alphaColor(200), 2);
public void setFocused(boolean focused) {
public void setFocused(final boolean focused) {
avatarLabel.setBorder(focused ? focusedBorder : defaultBorder);
}

View File

@@ -24,9 +24,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import forge.AIOption;
import forge.GuiBase;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.deck.CardPool;
import forge.deck.Deck;
import forge.deck.DeckProxy;
@@ -60,6 +58,7 @@ import forge.toolbox.FTextField;
import forge.util.Aggregates;
import forge.util.Lang;
import forge.util.NameGenerator;
import forge.util.gui.SOptionPane;
import forge.util.storage.IStorage;
/**
@@ -200,6 +199,7 @@ public class VLobby implements IUpdateable {
getPlayerPanelWithFocus().focusOnAvatar();
}
@Override
public void update(final boolean fullUpdate) {
activePlayersNum = lobby.getNumberOfSlots();
addPlayerBtn.setEnabled(activePlayersNum < MAX_PLAYERS);
@@ -275,7 +275,7 @@ public class VLobby implements IUpdateable {
void setReady(final int index, final boolean ready) {
if (ready && decks[index] == null) {
GuiBase.getInterface().showOptionDialog("Select a deck before readying!", "Error", FSkinProp.ICO_WARNING, new String[] { "Ok" }, 0);
SOptionPane.showErrorDialog("Select a deck before readying!");
update(false);
return;
}
@@ -391,7 +391,7 @@ public class VLobby implements IUpdateable {
planarDeckPanels.add(planarDeckPanel);
// Vanguard avatar list
FPanel vgdDeckPanel = new FPanel();
final FPanel vgdDeckPanel = new FPanel();
vgdDeckPanel.setBorderToggle(false);
final FList<Object> vgdAvatarList = new FList<Object>();
@@ -624,14 +624,6 @@ public class VLobby implements IUpdateable {
/** Gets the random deck checkbox for Artifacts. */
FCheckBox getCbArtifacts() { return cbArtifacts; }
FCheckBox getVntArchenemy() { return vntArchenemy; }
FCheckBox getVntArchenemyRumble() { return vntArchenemyRumble; }
FCheckBox getVntCommander() { return vntCommander; }
FCheckBox getVntMomirBasic() { return vntMomirBasic; }
FCheckBox getVntPlanechase() { return vntPlanechase; }
FCheckBox getVntTinyLeaders() { return vntTinyLeaders; }
FCheckBox getVntVanguard() { return vntVanguard; }
public final List<PlayerPanel> getPlayerPanels() {
return playerPanels;
}
@@ -642,7 +634,7 @@ public class VLobby implements IUpdateable {
return iPlayer == playerWithFocus;
}
public final FDeckChooser getDeckChooser(int playernum) {
public final FDeckChooser getDeckChooser(final int playernum) {
return deckChoosers.get(playernum);
}
@@ -663,7 +655,7 @@ public class VLobby implements IUpdateable {
}
/** Revalidates the player and deck sections. Necessary after adding or hiding any panels. */
private void refreshPanels(boolean refreshPlayerFrame, boolean refreshDeckFrame) {
private void refreshPanels(final boolean refreshPlayerFrame, final boolean refreshDeckFrame) {
if (refreshPlayerFrame) {
playersScroll.validate();
playersScroll.repaint();
@@ -674,11 +666,11 @@ public class VLobby implements IUpdateable {
}
}
public void changePlayerFocus(int newFocusOwner) {
public void changePlayerFocus(final int newFocusOwner) {
changePlayerFocus(newFocusOwner, lobby.getGameType());
}
void changePlayerFocus(int newFocusOwner, GameType gType) {
void changePlayerFocus(final int newFocusOwner, final GameType gType) {
final PlayerPanel oldFocus = getPlayerPanelWithFocus();
if (oldFocus != null) {
oldFocus.setFocused(false);
@@ -695,15 +687,15 @@ public class VLobby implements IUpdateable {
/** Saves avatar prefs for players one and two. */
void updateAvatarPrefs() {
int pOneIndex = playerPanels.get(0).getAvatarIndex();
int pTwoIndex = playerPanels.get(1).getAvatarIndex();
final int pOneIndex = playerPanels.get(0).getAvatarIndex();
final int pTwoIndex = playerPanels.get(1).getAvatarIndex();
prefs.setPref(FPref.UI_AVATARS, pOneIndex + "," + pTwoIndex);
prefs.save();
}
/** Adds a pre-styled FLabel component with the specified title. */
FLabel newLabel(String title) {
FLabel newLabel(final String title) {
return new FLabel.Builder().text(title).fontSize(14).fontStyle(Font.ITALIC).build();
}
@@ -735,7 +727,7 @@ public class VLobby implements IUpdateable {
final String type = typeOptions[typeIndex];
String confirmMsg, newName;
List<String> usedNames = getPlayerNames();
final List<String> usedNames = getPlayerNames();
do {
newName = NameGenerator.getRandomName(gender, type, usedNames);
confirmMsg = "Would you like to use the name \"" + newName + "\", or try again?";
@@ -745,8 +737,8 @@ public class VLobby implements IUpdateable {
}
List<String> getPlayerNames() {
List<String> names = new ArrayList<String>();
for (PlayerPanel pp : playerPanels) {
final List<String> names = new ArrayList<String>();
for (final PlayerPanel pp : playerPanels) {
names.add(pp.getPlayerName());
}
return names;
@@ -776,8 +768,8 @@ public class VLobby implements IUpdateable {
final ActionListener nameListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FTextField nField = (FTextField)e.getSource();
public void actionPerformed(final ActionEvent e) {
final FTextField nField = (FTextField)e.getSource();
nField.transferFocus();
}
};
@@ -812,7 +804,7 @@ public class VLobby implements IUpdateable {
/** Return all the Vanguard avatars. */
public Iterable<PaperCard> getAllAvatars() {
if (vgdAllAvatars.isEmpty()) {
for (PaperCard c : FModel.getMagicDb().getVariantCards().getAllCards()) {
for (final PaperCard c : FModel.getMagicDb().getVariantCards().getAllCards()) {
if (c.getRules().getType().isVanguard()) {
vgdAllAvatars.add(c);
}
@@ -842,7 +834,7 @@ public class VLobby implements IUpdateable {
humanListData.add("Random");
aiListData.add("Use deck's default avatar (random if unavailable)");
aiListData.add("Random");
for (PaperCard cp : getAllAvatars()) {
for (final PaperCard cp : getAllAvatars()) {
humanListData.add(cp);
if (!cp.getRules().getAiHints().getRemRandomDecks()) {
nonRandomHumanAvatars.add(cp);
@@ -858,9 +850,9 @@ public class VLobby implements IUpdateable {
}
/** update vanguard list. */
public void updateVanguardList(int playerIndex) {
FList<Object> vgdList = getVanguardLists().get(playerIndex);
Object lastSelection = vgdList.getSelectedValue();
public void updateVanguardList(final int playerIndex) {
final FList<Object> vgdList = getVanguardLists().get(playerIndex);
final Object lastSelection = vgdList.getSelectedValue();
vgdList.setListData(isPlayerAI(playerIndex) ? aiListData : humanListData);
if (null != lastSelection) {
vgdList.setSelectedValue(lastSelection, true);

View File

@@ -1,5 +1,16 @@
package forge.screens.home.gauntlet;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import org.apache.commons.lang3.ArrayUtils;
import forge.UiCommand;
import forge.deck.Deck;
import forge.gauntlet.GauntletData;
@@ -8,15 +19,6 @@ import forge.gui.framework.ICDoc;
import forge.properties.ForgeConstants;
import forge.toolbox.FOptionPane;
import org.apache.commons.lang3.ArrayUtils;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Controls the "build gauntlet" submenu in the home UI.
*
@@ -30,7 +32,7 @@ public enum CSubmenuGauntletBuild implements ICDoc {
private final VSubmenuGauntletBuild view = VSubmenuGauntletBuild.SINGLETON_INSTANCE;
private final List<Deck> workingDecks = new ArrayList<Deck>();
private File openStartDir = new File(ForgeConstants.GAUNTLET_DIR.userPrefLoc);
private final File openStartDir = new File(ForgeConstants.GAUNTLET_DIR.userPrefLoc);
private final FileFilter filterDAT = new FileFilter() {
@Override
@@ -39,7 +41,7 @@ public enum CSubmenuGauntletBuild implements ICDoc {
return true;
}
String filename = f.getName();
final String filename = f.getName();
return (!filename.startsWith(GauntletIO.PREFIX_QUICK) && filename.endsWith(GauntletIO.SUFFIX_DATA));
}
@@ -49,29 +51,41 @@ public enum CSubmenuGauntletBuild implements ICDoc {
}
};
//private final KeyAdapter kadSearch = new KeyAdapter() { @Override
//public void keyPressed(final KeyEvent e) { search(); } };
private final UiCommand cmdAddDeck = new UiCommand() { @Override
public void run() { addDeck(); } };
private final UiCommand cmdRemoveDeck = new UiCommand() { @Override
public void run() { removeDeck(); } };
private final UiCommand cmdDeckUp = new UiCommand() { @Override
public void run() { deckUp(); } };
private final UiCommand cmdDeckDown = new UiCommand() { @Override
public void run() { deckDown(); } };
private final UiCommand cmdSave = new UiCommand() { @Override
public void run() { saveGauntlet(); } };
private final UiCommand cmdNew = new UiCommand() { @Override
public void run() { newGauntlet(); } };
private final UiCommand cmdOpen = new UiCommand() { @Override
public void run() { openGauntlet(); } };
private final UiCommand cmdAddDeck = new UiCommand() {
@Override public void run() {
addDeck();
}
};
private final UiCommand cmdRemoveDeck = new UiCommand() {
@Override public void run() {
removeDeck();
}
};
private final UiCommand cmdDeckUp = new UiCommand() {
@Override public void run() {
deckUp();
}
};
private final UiCommand cmdDeckDown = new UiCommand() {
@Override public void run() {
deckDown();
}
};
private final UiCommand cmdSave = new UiCommand() {
@Override public void run() {
saveGauntlet();
}
};
private final UiCommand cmdNew = new UiCommand() {
@Override public void run() {
newGauntlet();
}
};
private final UiCommand cmdOpen = new UiCommand() {
@Override public void run() {
openGauntlet();
}
};
/* (non-Javadoc)
* @see forge.gui.home.ICSubmenu#initialize()
@@ -107,18 +121,11 @@ public enum CSubmenuGauntletBuild implements ICDoc {
// updateDecks();
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
private void addDeck() {
final Deck deckToAdd = view.getLstLeft().getPlayer().getDeck();
if ( null == deckToAdd ) return;
if ( null == deckToAdd ) {
return;
}
workingDecks.add(deckToAdd);
view.getLblSave().setVisible(false);
dumpDecksIntoList();

View File

@@ -1,7 +1,14 @@
package forge.screens.home.gauntlet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingUtilities;
import forge.GuiBase;
import forge.UiCommand;
import forge.deck.Deck;
import forge.game.GameType;
import forge.game.player.RegisteredPlayer;
@@ -13,14 +20,6 @@ import forge.match.HostedMatch;
import forge.model.FModel;
import forge.player.GamePlayerUtil;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Controls the "gauntlet contests" submenu in the home UI.
*
@@ -28,7 +27,6 @@ import java.util.List;
*
*/
@SuppressWarnings("serial")
public enum CSubmenuGauntletContests implements ICDoc {
/** */
SINGLETON_INSTANCE;
@@ -37,7 +35,7 @@ public enum CSubmenuGauntletContests implements ICDoc {
private final ActionListener actStartGame = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
public void actionPerformed(final ActionEvent arg0) {
startGame();
}
};
@@ -73,7 +71,7 @@ public enum CSubmenuGauntletContests implements ICDoc {
final File[] files = GauntletIO.getGauntletFilesLocked();
final List<GauntletData> data = new ArrayList<GauntletData>();
for (final File f : files) {
GauntletData gd = GauntletIO.loadGauntlet(f);
final GauntletData gd = GauntletIO.loadGauntlet(f);
if (gd != null) {
data.add(gd);
}
@@ -124,16 +122,4 @@ public enum CSubmenuGauntletContests implements ICDoc {
});
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return new UiCommand() {
@Override
public void run() {
updateData();
}
};
}
}

View File

@@ -1,5 +1,14 @@
package forge.screens.home.gauntlet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import forge.GuiBase;
import forge.UiCommand;
import forge.deck.Deck;
@@ -15,14 +24,6 @@ import forge.match.HostedMatch;
import forge.model.FModel;
import forge.player.GamePlayerUtil;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Controls the "quick gauntlet" submenu in the home UI.
*
@@ -32,8 +33,11 @@ import java.util.List;
public enum CSubmenuGauntletLoad implements ICDoc {
SINGLETON_INSTANCE;
private final ActionListener actStartGame = new ActionListener() { @Override
public void actionPerformed(ActionEvent arg0) { startGame(); } };
private final ActionListener actStartGame = new ActionListener() {
@Override public final void actionPerformed(final ActionEvent arg0) {
startGame();
}
};
private final VSubmenuGauntletLoad view = VSubmenuGauntletLoad.SINGLETON_INSTANCE;
@@ -49,7 +53,7 @@ public enum CSubmenuGauntletLoad implements ICDoc {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JButton btnStart = view.getBtnStart();
final JButton btnStart = view.getBtnStart();
if (btnStart.isEnabled()) {
view.getBtnStart().requestFocusInWindow();
}
@@ -94,7 +98,7 @@ public enum CSubmenuGauntletLoad implements ICDoc {
final List<GauntletData> data = new ArrayList<GauntletData>();
for (final File f : files) {
GauntletData gd = GauntletIO.loadGauntlet(f);
final GauntletData gd = GauntletIO.loadGauntlet(f);
if (gd != null) {
data.add(gd);
}
@@ -153,17 +157,4 @@ public enum CSubmenuGauntletLoad implements ICDoc {
});
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
@SuppressWarnings("serial")
public UiCommand getCommandOnSelect() {
return new UiCommand() {
@Override
public void run() {
updateData();
}
};
}
}

View File

@@ -1,6 +1,12 @@
package forge.screens.home.gauntlet;
import forge.UiCommand;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingUtilities;
import forge.deck.DeckType;
import forge.game.player.RegisteredPlayer;
import forge.gauntlet.GauntletData;
@@ -9,13 +15,6 @@ import forge.gui.SOverlayUtils;
import forge.gui.framework.ICDoc;
import forge.player.GamePlayerUtil;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
/**
* Controls the "quick gauntlet" submenu in the home UI.
*
@@ -27,8 +26,11 @@ public enum CSubmenuGauntletQuick implements ICDoc {
/** */
SINGLETON_INSTANCE;
private final ActionListener actStartGame = new ActionListener() { @Override
public void actionPerformed(ActionEvent arg0) { startGame(); } };
private final ActionListener actStartGame = new ActionListener() {
@Override public void actionPerformed(final ActionEvent arg0) {
startGame();
}
};
private final VSubmenuGauntletQuick view = VSubmenuGauntletQuick.SINGLETON_INSTANCE;
@@ -90,11 +92,4 @@ public enum CSubmenuGauntletQuick implements ICDoc {
});
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -1,17 +1,6 @@
package forge.screens.home.gauntlet;
import forge.UiCommand;
import forge.gauntlet.GauntletData;
import forge.gauntlet.GauntletIO;
import forge.toolbox.FLabel;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinnedPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
@@ -19,6 +8,17 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import forge.UiCommand;
import forge.gauntlet.GauntletData;
import forge.gauntlet.GauntletIO;
import forge.toolbox.FLabel;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinnedPanel;
/**
* Creates file list/table for quick deleting, editing, and basic info.
*
@@ -31,7 +31,6 @@ public class ContestGauntletLister extends JPanel {
private final Color clrDefault;
private final FSkin.SkinColor clrHover, clrActive, clrBorders;
/** */
public ContestGauntletLister() {
super();
this.clrDefault = new Color(0, 0, 0, 0);
@@ -43,12 +42,11 @@ public class ContestGauntletLister extends JPanel {
this.setLayout(new MigLayout("insets 0, gap 0, wrap"));
}
/** @param gd0 &emsp; {@link forge.gauntlet.GauntletData}[] */
public void setGauntlets(List<GauntletData> gd0) {
public void setGauntlets(final List<GauntletData> gd0) {
this.removeAll();
List<RowPanel> tempRows = new ArrayList<RowPanel>();
List<GauntletData> sorted = new ArrayList<GauntletData>();
for (GauntletData gd : gd0) { sorted.add(gd); }
final List<RowPanel> tempRows = new ArrayList<RowPanel>();
final List<GauntletData> sorted = new ArrayList<GauntletData>();
for (final GauntletData gd : gd0) { sorted.add(gd); }
Collections.sort(sorted, new Comparator<GauntletData>() {
@Override
public int compare(final GauntletData x, final GauntletData y) {
@@ -77,7 +75,7 @@ public class ContestGauntletLister extends JPanel {
RowPanel row;
String name;
String progress;
for (GauntletData gd : sorted) {
for (final GauntletData gd : sorted) {
name = gd.getName();
name = name.substring(GauntletIO.PREFIX_LOCKED.length());
@@ -109,7 +107,6 @@ public class ContestGauntletLister extends JPanel {
revalidate();
}
/** @return {@link forge.deck.Deck} */
public GauntletData getSelectedGauntlet() {
if (previousSelect == null) {
return null;
@@ -121,9 +118,9 @@ public class ContestGauntletLister extends JPanel {
private class RowPanel extends SkinnedPanel {
private boolean selected = false;
private GauntletData gauntletData;
private final GauntletData gauntletData;
public RowPanel(GauntletData gd0) {
public RowPanel(final GauntletData gd0) {
super();
setOpaque(false);
setBackground(new Color(0, 0, 0, 0));
@@ -133,27 +130,27 @@ public class ContestGauntletLister extends JPanel {
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
public void mouseEntered(final MouseEvent e) {
if (!selected) {
RowPanel.this.setBackground(clrHover);
RowPanel.this.setOpaque(true);
}
}
@Override
public void mouseExited(MouseEvent e) {
public void mouseExited(final MouseEvent e) {
if (!selected) {
RowPanel.this.setBackground(clrDefault);
RowPanel.this.setOpaque(false);
}
}
@Override
public void mousePressed(MouseEvent e) {
public void mousePressed(final MouseEvent e) {
selectHandler(RowPanel.this);
}
});
}
public void setSelected(boolean b0) {
public void setSelected(final boolean b0) {
selected = b0;
setOpaque(b0);
this.setBackground(b0 ? clrActive : clrHover);
@@ -168,7 +165,6 @@ public class ContestGauntletLister extends JPanel {
}
}
/** @return {@link java.lang.Integer} */
public int getSelectedIndex() {
for (int i = 0; i < rows.length; i++) {
if (rows[i].isSelected()) { return i; }
@@ -180,32 +176,18 @@ public class ContestGauntletLister extends JPanel {
* @param i0 &emsp; int
* @return boolean success
*/
public boolean setSelectedIndex(int i0) {
public boolean setSelectedIndex(final int i0) {
if (i0 >= rows.length) { return false; }
selectHandler(rows[i0]);
return true;
}
/**
* @param qd0 &emsp; Gauntlet data object to select (if exists in list)
* @return boolean success
*/
public boolean setSelectedGauntletData(GauntletData qd0) {
/*for (RowPanel r : rows) {
if (r.getQuestData().getName().equals(qd0.getName())) {
selectHandler(r);
return true;
}
}*/
return false;
}
/** @param c0 &emsp; {@link forge.UiCommand} command executed on row select. */
public void setSelectCommand(UiCommand c0) {
public void setSelectCommand(final UiCommand c0) {
this.cmdRowSelect = c0;
}
private void selectHandler(RowPanel r0) {
private void selectHandler(final RowPanel r0) {
if (previousSelect != null) {
previousSelect.setSelected(false);
}

View File

@@ -1,5 +1,18 @@
package forge.screens.home.gauntlet;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import net.miginfocom.swing.MigLayout;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.gauntlet.GauntletData;
@@ -12,26 +25,13 @@ import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinIcon;
import forge.toolbox.FSkin.SkinnedButton;
import forge.toolbox.FSkin.SkinnedPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Creates file list/table for quick deleting, editing, and basic info.
*
*/
@SuppressWarnings("serial")
public class QuickGauntletLister extends JPanel {
private SkinIcon icoDelete, icoDeleteOver, icoEdit, icoEditOver;
private final SkinIcon icoDelete, icoDeleteOver, icoEdit, icoEditOver;
private RowPanel previousSelect;
private RowPanel[] rows;
private UiCommand cmdRowSelect, cmdRowDelete, cmdRowActivate;
@@ -39,7 +39,6 @@ public class QuickGauntletLister extends JPanel {
private final FSkin.SkinColor clrHover, clrActive, clrBorders;
private List<GauntletData> gauntlets;
/** */
public QuickGauntletLister() {
super();
@@ -57,17 +56,16 @@ public class QuickGauntletLister extends JPanel {
icoEditOver = FSkin.getIcon(FSkinProp.ICO_EDIT_OVER);
}
/** @param gd0 &emsp; {@link forge.gauntlet.GauntletData}[] */
public void setGauntlets(List<GauntletData> gd0) {
public void setGauntlets(final List<GauntletData> gd0) {
gauntlets = gd0;
refresh();
}
public void refresh() {
this.removeAll();
List<RowPanel> tempRows = new ArrayList<RowPanel>();
List<GauntletData> sorted = new ArrayList<GauntletData>();
for (GauntletData gd : gauntlets) { sorted.add(gd); }
final List<RowPanel> tempRows = new ArrayList<RowPanel>();
final List<GauntletData> sorted = new ArrayList<GauntletData>();
for (final GauntletData gd : gauntlets) { sorted.add(gd); }
Collections.sort(sorted, new Comparator<GauntletData>() {
@Override
public int compare(final GauntletData x, final GauntletData y) {
@@ -95,7 +93,7 @@ public class QuickGauntletLister extends JPanel {
RowPanel row;
String name;
for (GauntletData gd : sorted) {
for (final GauntletData gd : sorted) {
name = gd.getName();
row = new RowPanel(gd);
@@ -124,7 +122,6 @@ public class QuickGauntletLister extends JPanel {
revalidate();
}
/** @return {@link forge.deck.Deck} */
public File getSelectedGauntletFile() {
if (previousSelect == null) {
return null;
@@ -149,21 +146,21 @@ public class QuickGauntletLister extends JPanel {
this.addMouseListener(new FMouseAdapter() {
@Override
public void onMouseEnter(MouseEvent e) {
public void onMouseEnter(final MouseEvent e) {
if (!r0.selected) {
r0.setBackground(clrHover);
r0.setOpaque(true);
}
}
@Override
public void onMouseExit(MouseEvent e) {
public void onMouseExit(final MouseEvent e) {
if (!r0.selected) {
r0.setBackground(clrDefault);
r0.setOpaque(false);
}
}
@Override
public void onLeftClick(MouseEvent e) {
public void onLeftClick(final MouseEvent e) {
deleteFile(r0);
}
});
@@ -185,21 +182,21 @@ public class QuickGauntletLister extends JPanel {
this.addMouseListener(new FMouseAdapter() {
@Override
public void onMouseEnter(MouseEvent e) {
public void onMouseEnter(final MouseEvent e) {
if (!r0.selected) {
r0.setBackground(clrHover);
r0.setOpaque(true);
}
}
@Override
public void onMouseExit(MouseEvent e) {
public void onMouseExit(final MouseEvent e) {
if (!r0.selected) {
r0.setBackground(clrDefault);
r0.setOpaque(false);
}
}
@Override
public void onLeftClick(MouseEvent e) {
public void onLeftClick(final MouseEvent e) {
renameGauntlet(r0.getGauntletData());
}
});
@@ -209,9 +206,9 @@ public class QuickGauntletLister extends JPanel {
private class RowPanel extends SkinnedPanel {
private boolean selected = false;
private boolean hovered = false;
private GauntletData gauntletData;
private final GauntletData gauntletData;
public RowPanel(GauntletData gd0) {
public RowPanel(final GauntletData gd0) {
super();
setOpaque(false);
setBackground(new Color(0, 0, 0, 0));
@@ -267,7 +264,6 @@ public class QuickGauntletLister extends JPanel {
}
}
/** @return {@link java.lang.Integer} */
public int getSelectedIndex() {
for (int i = 0; i < rows.length; i++) {
if (rows[i].isSelected()) { return i; }
@@ -279,42 +275,28 @@ public class QuickGauntletLister extends JPanel {
* @param i0 &emsp; int
* @return boolean success
*/
public boolean setSelectedIndex(int i0) {
public boolean setSelectedIndex(final int i0) {
if (i0 >= rows.length) { return false; }
selectHandler(rows[Math.max(0, i0)]);
return true;
}
/**
* @param qd0 &emsp; Gauntlet data object to select (if exists in list)
* @return boolean success
*/
public boolean setSelectedGauntletData(GauntletData qd0) {
/*for (RowPanel r : rows) {
if (r.getQuestData().getName().equals(qd0.getName())) {
selectHandler(r);
return true;
}
}*/
return false;
}
/** @param c0 &emsp; {@link forge.UiCommand} command executed on row select. */
public void setCmdSelect(UiCommand c0) {
public void setCmdSelect(final UiCommand c0) {
this.cmdRowSelect = c0;
}
/** @param c0 &emsp; {@link forge.UiCommand} command executed on row delete. */
public void setCmdDelete(UiCommand c0) {
public void setCmdDelete(final UiCommand c0) {
this.cmdRowDelete = c0;
}
/** @param c0 &emsp; {@link forge.UiCommand} command executed on row activate. */
public void setCmdActivate(UiCommand c0) {
public void setCmdActivate(final UiCommand c0) {
this.cmdRowActivate = c0;
}
private void selectHandler(RowPanel r0) {
private void selectHandler(final RowPanel r0) {
if (previousSelect != null) {
previousSelect.setSelected(false);
}
@@ -324,9 +306,9 @@ public class QuickGauntletLister extends JPanel {
if (cmdRowSelect != null) { cmdRowSelect.run(); }
}
private void renameGauntlet(GauntletData gauntlet) {
private void renameGauntlet(final GauntletData gauntlet) {
String gauntletName;
String oldGauntletName = gauntlet.getName();
final String oldGauntletName = gauntlet.getName();
while (true) {
gauntletName = FOptionPane.showInputDialog("Rename gauntlet to:", "Gauntlet Rename", null, oldGauntletName);
if (gauntletName == null) { return; }
@@ -340,7 +322,7 @@ public class QuickGauntletLister extends JPanel {
}
boolean exists = false;
for (RowPanel r : rows) {
for (final RowPanel r : rows) {
if (r.getGauntletData().getName().equalsIgnoreCase(gauntletName)) {
exists = true;
break;
@@ -357,7 +339,7 @@ public class QuickGauntletLister extends JPanel {
refresh();
}
private void deleteFile(RowPanel r0) {
private void deleteFile(final RowPanel r0) {
final GauntletData gd = r0.getGauntletData();
if (!FOptionPane.showConfirmDialog(

View File

@@ -1,6 +1,5 @@
package forge.screens.home.online;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
import forge.screens.home.CLobby;
import forge.screens.home.VLobby;
@@ -10,7 +9,7 @@ public enum COnlineLobby implements ICDoc {
private CLobby lobby;
void setLobby(VLobby lobbyView) {
void setLobby(final VLobby lobbyView) {
lobby = new CLobby(lobbyView);
initialize();
}
@@ -39,12 +38,4 @@ public enum COnlineLobby implements ICDoc {
}
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -5,9 +5,10 @@ import java.util.List;
import javax.swing.JMenu;
import org.apache.commons.lang3.StringUtils;
import forge.GuiBase;
import forge.Singletons;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.gui.FNetOverlay;
import forge.gui.framework.FScreen;
@@ -29,6 +30,7 @@ import forge.net.event.NetEvent;
import forge.net.event.UpdateLobbyPlayerEvent;
import forge.net.server.FServerManager;
import forge.net.server.ServerGameLobby;
import forge.player.GamePlayerUtil;
import forge.properties.ForgePreferences.FPref;
import forge.screens.home.VLobby;
import forge.screens.home.sanctioned.ConstructedGameMenu;
@@ -38,6 +40,8 @@ public enum CSubmenuOnlineLobby implements ICDoc, IMenuProvider {
SINGLETON_INSTANCE;
final void host(final int portNumber) {
promptNameIfNeeded();
final FServerManager server = FServerManager.getInstance();
final ServerGameLobby lobby = new ServerGameLobby();
final VLobby view = VOnlineLobby.SINGLETON_INSTANCE.setLobby(lobby);
@@ -91,6 +95,8 @@ public enum CSubmenuOnlineLobby implements ICDoc, IMenuProvider {
}
final void join(final String hostname, final int port) {
promptNameIfNeeded();
final IGuiGame gui = GuiBase.getInterface().getNewGuiGame();
final FGameClient client = new FGameClient(FModel.getPreferences().getPref(FPref.PLAYER_NAME), "0", gui);
VOnlineLobby.SINGLETON_INSTANCE.setClient(client);
@@ -123,6 +129,13 @@ public enum CSubmenuOnlineLobby implements ICDoc, IMenuProvider {
FNetOverlay.SINGLETON_INSTANCE.showUp(String.format("Connected to %s:%d", hostname, port));
}
private static void promptNameIfNeeded() {
//prompt user for player one name if needed
if (StringUtils.isBlank(FModel.getPreferences().getPref(FPref.PLAYER_NAME))) {
GamePlayerUtil.setPlayerName();
}
}
@Override
public void register() {
}
@@ -142,20 +155,12 @@ public enum CSubmenuOnlineLobby implements ICDoc, IMenuProvider {
public void initialize() {
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
/* (non-Javadoc)
* @see forge.gui.menubar.IMenuProvider#getMenus()
*/
@Override
public List<JMenu> getMenus() {
List<JMenu> menus = new ArrayList<JMenu>();
final List<JMenu> menus = new ArrayList<JMenu>();
menus.add(ConstructedGameMenu.getMenu());
return menus;
}

View File

@@ -34,9 +34,6 @@ public enum VOnlineLobby implements IVDoc<COnlineLobby>, IVTopLevelUI {
private VOnlineLobby() {
}
VLobby getLobby() {
return lobby;
}
VLobby setLobby(final GameLobby lobby) {
this.lobby = new VLobby(lobby);
getLayoutControl().setLobby(this.lobby);

View File

@@ -1,8 +1,22 @@
package forge.screens.home.quest;
import forge.UiCommand;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import forge.Singletons;
import forge.gui.framework.EDocID;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
import forge.model.FModel;
import forge.quest.QuestController;
@@ -10,18 +24,9 @@ import forge.quest.QuestEventChallenge;
import forge.quest.QuestUtil;
import forge.quest.bazaar.QuestItemType;
import forge.quest.bazaar.QuestPetController;
import forge.screens.home.CHomeUI;
import forge.toolbox.FLabel;
import forge.toolbox.JXButtonPanel;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
/**
* Controls the quest challenges submenu in the home UI.
*
@@ -64,7 +69,7 @@ public enum CSubmenuChallenges implements ICDoc {
new ActionListener() { @Override
public void actionPerformed(final ActionEvent e) { QuestUtil.startGame(); } });
((FLabel) view.getLblZep()).setCommand(
view.getLblZep().setCommand(
new UiCommand() {
@Override
public void run() {
@@ -80,7 +85,7 @@ public enum CSubmenuChallenges implements ICDoc {
final QuestController quest = FModel.getQuest();
view.getCbPlant().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
public void actionPerformed(final ActionEvent arg0) {
quest.selectPet(0, view.getCbPlant().isSelected() ? "Plant" : null);
quest.save();
}
@@ -88,11 +93,11 @@ public enum CSubmenuChallenges implements ICDoc {
view.getCbxPet().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
public void actionPerformed(final ActionEvent arg0) {
final int slot = 1;
final int index = view.getCbxPet().getSelectedIndex();
List<QuestPetController> pets = quest.getPetsStorage().getAvaliablePets(slot, quest.getAssets());
String petName = index <= 0 || index > pets.size() ? null : pets.get(index - 1).getName();
final List<QuestPetController> pets = quest.getPetsStorage().getAvaliablePets(slot, quest.getAssets());
final String petName = index <= 0 || index > pets.size() ? null : pets.get(index - 1).getName();
quest.selectPet(slot, petName);
quest.save();
}
@@ -100,7 +105,7 @@ public enum CSubmenuChallenges implements ICDoc {
view.getCbCharm().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
public void actionPerformed(final ActionEvent arg0) {
quest.setCharmState(view.getCbCharm().isSelected());
quest.save();
}
@@ -109,7 +114,7 @@ public enum CSubmenuChallenges implements ICDoc {
private final KeyAdapter _startOnEnter = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
public void keyPressed(final KeyEvent e) {
if (KeyEvent.VK_ENTER == e.getKeyChar()) {
VSubmenuChallenges.SINGLETON_INSTANCE.getBtnStart().doClick();
}
@@ -117,7 +122,7 @@ public enum CSubmenuChallenges implements ICDoc {
};
private final MouseAdapter _startOnDblClick = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
public void mouseClicked(final MouseEvent e) {
if (MouseEvent.BUTTON1 == e.getButton() && 2 == e.getClickCount()) {
VSubmenuChallenges.SINGLETON_INSTANCE.getBtnStart().doClick();
}
@@ -134,21 +139,23 @@ public enum CSubmenuChallenges implements ICDoc {
final VSubmenuChallenges view = VSubmenuChallenges.SINGLETON_INSTANCE;
final QuestController qCtrl = FModel.getQuest();
if (qCtrl.getAchievements() == null) return;
if (qCtrl.getAchievements() == null) {
return;
}
view.getLblTitle().setText("Challenges: " + qCtrl.getRank());
view.getPnlChallenges().removeAll();
qCtrl.regenerateChallenges();
final List<QuestEventChallenge> challenges = new ArrayList<QuestEventChallenge>();
for(Object id : qCtrl.getAchievements().getCurrentChallenges()) {
for(final Object id : qCtrl.getAchievements().getCurrentChallenges()) {
challenges.add(qCtrl.getChallenges().get(id.toString()));
}
JXButtonPanel grpPanel = new JXButtonPanel();
final JXButtonPanel grpPanel = new JXButtonPanel();
boolean haveAnyChallenges = true;
for (QuestEventChallenge qc : challenges) {
for (final QuestEventChallenge qc : challenges) {
final PnlEvent temp = new PnlEvent(qc);
final JRadioButton rad = temp.getRad();
if (haveAnyChallenges) {
@@ -182,20 +189,4 @@ public enum CSubmenuChallenges implements ICDoc {
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@SuppressWarnings("serial")
@Override
public UiCommand getCommandOnSelect() {
final QuestController qc = FModel.getQuest();
return new UiCommand() {
@Override
public void run() {
if (qc.getAchievements() == null) {
CHomeUI.SINGLETON_INSTANCE.itemClick(EDocID.HOME_QUESTDATA);
}
}
};
}
}

View File

@@ -1,21 +1,25 @@
package forge.screens.home.quest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import forge.UiCommand;
import forge.gui.framework.EDocID;
import forge.gui.framework.ICDoc;
import forge.model.FModel;
import forge.quest.QuestController;
import forge.quest.QuestEventDuel;
import forge.quest.QuestUtil;
import forge.quest.bazaar.QuestPetController;
import forge.screens.home.CHomeUI;
import forge.toolbox.JXButtonPanel;
import javax.swing.*;
import java.awt.event.*;
import java.util.List;
/**
* Controls the quest duels submenu in the home UI.
*
@@ -61,7 +65,7 @@ public enum CSubmenuDuels implements ICDoc {
final QuestController quest = FModel.getQuest();
view.getCbPlant().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
public void actionPerformed(final ActionEvent arg0) {
quest.selectPet(0, view.getCbPlant().isSelected() ? "Plant" : null);
quest.save();
}
@@ -69,7 +73,7 @@ public enum CSubmenuDuels implements ICDoc {
view.getCbCharm().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
public void actionPerformed(final ActionEvent arg0) {
quest.setCharmState(view.getCbCharm().isSelected());
quest.save();
}
@@ -77,11 +81,11 @@ public enum CSubmenuDuels implements ICDoc {
view.getCbxPet().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
public void actionPerformed(final ActionEvent arg0) {
final int slot = 1;
final int index = view.getCbxPet().getSelectedIndex();
List<QuestPetController> pets = quest.getPetsStorage().getAvaliablePets(slot, quest.getAssets());
String petName = index <= 0 || index > pets.size() ? null : pets.get(index - 1).getName();
final List<QuestPetController> pets = quest.getPetsStorage().getAvaliablePets(slot, quest.getAssets());
final String petName = index <= 0 || index > pets.size() ? null : pets.get(index - 1).getName();
quest.selectPet(slot, petName);
quest.save();
}
@@ -103,7 +107,7 @@ public enum CSubmenuDuels implements ICDoc {
private final KeyAdapter _startOnEnter = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
public void keyPressed(final KeyEvent e) {
if (KeyEvent.VK_ENTER == e.getKeyChar()) {
VSubmenuDuels.SINGLETON_INSTANCE.getBtnStart().doClick();
}
@@ -111,7 +115,7 @@ public enum CSubmenuDuels implements ICDoc {
};
private final MouseAdapter _startOnDblClick = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
public void mouseClicked(final MouseEvent e) {
if (MouseEvent.BUTTON1 == e.getButton() && 2 == e.getClickCount()) {
VSubmenuDuels.SINGLETON_INSTANCE.getBtnStart().doClick();
}
@@ -133,7 +137,7 @@ public enum CSubmenuDuels implements ICDoc {
view.getPnlDuels().removeAll();
final List<QuestEventDuel> duels = FModel.getQuest().getDuelsManager().generateDuels();
JXButtonPanel grpPanel = new JXButtonPanel();
final JXButtonPanel grpPanel = new JXButtonPanel();
for (int i = 0; i < duels.size(); i++) {
final PnlEvent temp = new PnlEvent(duels.get(i));
@@ -152,20 +156,4 @@ public enum CSubmenuDuels implements ICDoc {
}
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@SuppressWarnings("serial")
@Override
public UiCommand getCommandOnSelect() {
final QuestController qc = FModel.getQuest();
return new UiCommand() {
@Override
public void run() {
if (qc.getAchievements() == null) {
CHomeUI.SINGLETON_INSTANCE.itemClick(EDocID.HOME_QUESTDATA);
}
}
};
}
}

View File

@@ -1,5 +1,17 @@
package forge.screens.home.quest;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.swing.SwingUtilities;
import forge.UiCommand;
import forge.deck.Deck;
import forge.deck.DeckSection;
@@ -8,20 +20,18 @@ import forge.gui.framework.ICDoc;
import forge.item.PaperCard;
import forge.model.FModel;
import forge.properties.ForgeConstants;
import forge.quest.*;
import forge.quest.QuestController;
import forge.quest.QuestMode;
import forge.quest.QuestUtil;
import forge.quest.QuestWorld;
import forge.quest.StartingPoolPreferences;
import forge.quest.StartingPoolType;
import forge.quest.data.GameFormatQuest;
import forge.quest.data.QuestData;
import forge.quest.data.QuestPreferences.QPref;
import forge.quest.io.QuestDataIO;
import forge.toolbox.FOptionPane;
import javax.swing.*;
import java.io.File;
import java.io.FilenameFilter;
import java.util.*;
import java.util.Map.Entry;
/**
* Controls the quest data submenu in the home UI.
*
@@ -30,7 +40,6 @@ import java.util.Map.Entry;
*/
@SuppressWarnings("serial")
public enum CSubmenuQuestData implements ICDoc {
/** */
SINGLETON_INSTANCE;
private final Map<String, QuestData> arrQuests = new HashMap<String, QuestData>();
@@ -39,11 +48,16 @@ public enum CSubmenuQuestData implements ICDoc {
private final List<String> customFormatCodes = new ArrayList<String>();
private final List<String> customPrizeFormatCodes = new ArrayList<String>();
private final UiCommand cmdQuestSelect = new UiCommand() { @Override
public void run() { changeQuest(); } };
private final UiCommand cmdQuestUpdate = new UiCommand() { @Override
public void run() { update(); } };
private final UiCommand cmdQuestSelect = new UiCommand() {
@Override public final void run() {
changeQuest();
}
};
private final UiCommand cmdQuestUpdate = new UiCommand() {
@Override public final void run() {
update();
}
};
@Override
public void register() {
@@ -99,15 +113,15 @@ public enum CSubmenuQuestData implements ICDoc {
final QuestController qc = FModel.getQuest();
// Iterate over files and load quest data for each.
FilenameFilter takeDatFiles = new FilenameFilter() {
final FilenameFilter takeDatFiles = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return name.endsWith(".dat");
}
};
File[] arrFiles = dirQuests.listFiles(takeDatFiles);
final File[] arrFiles = dirQuests.listFiles(takeDatFiles);
arrQuests.clear();
for (File f : arrFiles) {
for (final File f : arrFiles) {
arrQuests.put(f.getName(), QuestDataIO.loadData(f));
}
@@ -147,15 +161,15 @@ public enum CSubmenuQuestData implements ICDoc {
*/
private void newQuest() {
final VSubmenuQuestData view = VSubmenuQuestData.SINGLETON_INSTANCE;
int difficulty = view.getSelectedDifficulty();
final int difficulty = view.getSelectedDifficulty();
final QuestMode mode = view.isFantasy() ? QuestMode.Fantasy : QuestMode.Classic;
Deck dckStartPool = null;
GameFormat fmtStartPool = null;
QuestWorld startWorld = FModel.getWorlds().get(view.getStartingWorldName());
final QuestWorld startWorld = FModel.getWorlds().get(view.getStartingWorldName());
GameFormat worldFormat = (startWorld == null ? null : startWorld.getFormat());
final GameFormat worldFormat = (startWorld == null ? null : startWorld.getFormat());
if (worldFormat == null) {
switch(view.getStartingPoolType()) {
@@ -200,16 +214,16 @@ public enum CSubmenuQuestData implements ICDoc {
// The starting QuestWorld format should NOT affect what you get if you travel to a world that doesn't have one...
// if (worldFormat == null) {
StartingPoolType prizedPoolType = view.getPrizedPoolType();
final StartingPoolType prizedPoolType = view.getPrizedPoolType();
if (null == prizedPoolType) {
fmtPrizes = fmtStartPool;
if (null == fmtPrizes && dckStartPool != null) { // build it form deck
Set<String> sets = new HashSet<String>();
for (Entry<PaperCard, Integer> c : dckStartPool.getMain()) {
final Set<String> sets = new HashSet<String>();
for (final Entry<PaperCard, Integer> c : dckStartPool.getMain()) {
sets.add(c.getKey().getEdition());
}
if (dckStartPool.has(DeckSection.Sideboard)) {
for (Entry<PaperCard, Integer> c : dckStartPool.get(DeckSection.Sideboard)) {
for (final Entry<PaperCard, Integer> c : dckStartPool.get(DeckSection.Sideboard)) {
sets.add(c.getKey().getEdition());
}
}
@@ -259,7 +273,7 @@ public enum CSubmenuQuestData implements ICDoc {
break;
}
QuestController qc = FModel.getQuest();
final QuestController qc = FModel.getQuest();
qc.newGame(questName, difficulty, mode, fmtPrizes, view.isUnlockSetsAllowed(), dckStartPool, fmtStartPool, view.getStartingWorldName(), userPrefs);
FModel.getQuest().save();
@@ -294,11 +308,4 @@ public enum CSubmenuQuestData implements ICDoc {
return arrQuests;
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -5,7 +5,6 @@ import javax.swing.SwingUtilities;
import forge.Singletons;
import forge.UiCommand;
import forge.deck.DeckProxy;
import forge.gui.framework.EDocID;
import forge.gui.framework.FScreen;
import forge.gui.framework.ICDoc;
import forge.itemmanager.ItemManagerConfig;
@@ -15,7 +14,6 @@ import forge.quest.QuestUtil;
import forge.quest.data.QuestPreferences.QPref;
import forge.screens.deckeditor.CDeckEditorUI;
import forge.screens.deckeditor.controllers.CEditorQuest;
import forge.screens.home.CHomeUI;
/**
* Controls the quest decks submenu in the home UI.
@@ -30,7 +28,7 @@ public enum CSubmenuQuestDecks implements ICDoc {
private final UiCommand cmdDeckSelect = new UiCommand() {
@Override
public void run() {
DeckProxy deck = VSubmenuQuestDecks.SINGLETON_INSTANCE.getLstDecks().getSelectedItem();
final DeckProxy deck = VSubmenuQuestDecks.SINGLETON_INSTANCE.getLstDecks().getSelectedItem();
if (deck != null) {
FModel.getQuestPreferences().setPref(QPref.CURRENT_DECK, deck.toString());
}
@@ -80,7 +78,7 @@ public enum CSubmenuQuestDecks implements ICDoc {
view.getLstDecks().setDeleteCommand(null);
final QuestController qData = FModel.getQuest();
boolean hasQuest = qData.getAssets() != null;
final boolean hasQuest = qData.getAssets() != null;
// Retrieve and set all decks
view.getLstDecks().setPool(DeckProxy.getAllQuestDecks(hasQuest ? qData.getMyDecks() : null));
view.getLstDecks().setup(ItemManagerConfig.QUEST_DECKS);
@@ -106,19 +104,4 @@ public enum CSubmenuQuestDecks implements ICDoc {
});
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
final QuestController qc = FModel.getQuest();
return new UiCommand() {
@Override
public void run() {
if (qc.getAchievements() == null) {
CHomeUI.SINGLETON_INSTANCE.itemClick(EDocID.HOME_QUESTDATA);
}
}
};
}
}

View File

@@ -23,7 +23,6 @@ import forge.gui.BoxedProductCardListViewer;
import forge.gui.CardListChooser;
import forge.gui.CardListViewer;
import forge.gui.GuiChoose;
import forge.gui.framework.EDocID;
import forge.gui.framework.FScreen;
import forge.gui.framework.ICDoc;
import forge.interfaces.IGuiGame;
@@ -34,7 +33,6 @@ import forge.limited.BoosterDraft;
import forge.model.CardBlock;
import forge.model.FModel;
import forge.properties.ForgePreferences.FPref;
import forge.quest.QuestController;
import forge.quest.QuestDraftUtils;
import forge.quest.QuestEventDraft;
import forge.quest.QuestUtil;
@@ -43,7 +41,6 @@ import forge.screens.deckeditor.CDeckEditorUI;
import forge.screens.deckeditor.controllers.CEditorQuestDraftingProcess;
import forge.screens.deckeditor.controllers.CEditorQuestLimited;
import forge.screens.deckeditor.views.VCurrentDeck;
import forge.screens.home.CHomeUI;
import forge.screens.home.quest.VSubmenuQuestDraft.Mode;
import forge.screens.home.sanctioned.CSubmenuDraft;
import forge.screens.match.controllers.CDetailPicture;
@@ -59,7 +56,6 @@ import forge.toolbox.JXButtonPanel;
*
*/
public enum CSubmenuQuestDraft implements ICDoc {
SINGLETON_INSTANCE;
private static final DecimalFormat NUMBER_FORMATTER = new DecimalFormat("#,###");
@@ -81,23 +77,28 @@ public enum CSubmenuQuestDraft implements ICDoc {
view.getBtnStartTournament().addActionListener(prepareDeckStart);
view.getBtnStartMatch().addActionListener(nextMatchStart);
view.getBtnStartMatchSmall().setCommand(
new UiCommand() { @Override
public void run() { CSubmenuQuestDraft.this.startNextMatch(); } });
view.getBtnStartMatchSmall().setCommand(new UiCommand() {
@Override public void run() {
CSubmenuQuestDraft.this.startNextMatch();
}
});
view.getBtnSpendToken().setCommand(new UiCommand() {
@Override public void run() {
CSubmenuQuestDraft.this.spendToken();
}
});
view.getBtnEditDeck().setCommand(new UiCommand() {
@Override public void run() {
CSubmenuQuestDraft.this.editDeck();
}
});
view.getBtnLeaveTournament().setCommand(new UiCommand() {
@Override public void run() {
CSubmenuQuestDraft.this.endTournamentAndAwardPrizes();
}
});
view.getBtnSpendToken().setCommand(
new UiCommand() { @Override
public void run() { CSubmenuQuestDraft.this.spendToken(); } });
view.getBtnEditDeck().setCommand(
new UiCommand() { @Override
public void run() { CSubmenuQuestDraft.this.editDeck(); } });
view.getBtnLeaveTournament().setCommand(
new UiCommand() { @Override
public void run() { CSubmenuQuestDraft.this.endTournamentAndAwardPrizes(); } });
QuestAchievements achievements = FModel.getQuest().getAchievements();
final QuestAchievements achievements = FModel.getQuest().getAchievements();
FModel.getQuest().getDraftDecks();
if (achievements == null) {
@@ -132,11 +133,11 @@ public enum CSubmenuQuestDraft implements ICDoc {
}
private void endTournamentAndAwardPrizes() {
QuestEventDraft draft = FModel.getQuest().getAchievements().getCurrentDraft();
final QuestEventDraft draft = FModel.getQuest().getAchievements().getCurrentDraft();
if (!draft.isStarted()) {
boolean shouldQuit = FOptionPane.showOptionDialog("If you leave now, this tournament will be forever gone."
final boolean shouldQuit = FOptionPane.showOptionDialog("If you leave now, this tournament will be forever gone."
+ "\nYou will keep the cards you drafted, but will receive no other prizes."
+ "\n\nWould you still like to quit the tournament?", "Really Quit?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2.0), new String[] { "Yes", "No" }, 1) == 0;
if (!shouldQuit) {
@@ -146,7 +147,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
} else {
if (draft.playerHasMatchesLeft()) {
boolean shouldQuit = FOptionPane.showOptionDialog("You have matches left to play!\nLeaving the tournament early will forfeit your potential future winnings."
final boolean shouldQuit = FOptionPane.showOptionDialog("You have matches left to play!\nLeaving the tournament early will forfeit your potential future winnings."
+ "\nYou will still receive winnings as if you conceded your next match and you will keep the cards you drafted."
+ "\n\nWould you still like to quit the tournament?", "Really Quit?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2.0), new String[] { "Yes", "No" }, 1) == 0;
if (!shouldQuit) {
@@ -154,9 +155,9 @@ public enum CSubmenuQuestDraft implements ICDoc {
}
}
String placement = draft.getPlacementString();
final String placement = draft.getPlacementString();
QuestEventDraft.QuestDraftPrizes prizes = draft.collectPrizes();
final QuestEventDraft.QuestDraftPrizes prizes = draft.collectPrizes();
if (prizes.hasCredits()) {
FOptionPane.showMessageDialog("For placing " + placement + ", you have been awarded " + prizes.credits + " credits!", "Credits Awarded", FSkin.getImage(FSkinProp.ICO_QUEST_GOLD));
@@ -170,20 +171,20 @@ public enum CSubmenuQuestDraft implements ICDoc {
if (prizes.hasBoosterPacks()) {
String packPlural = (prizes.boosterPacks.size() == 1) ? "" : "s";
final String packPlural = (prizes.boosterPacks.size() == 1) ? "" : "s";
FOptionPane.showMessageDialog("For placing " + placement + ", you have been awarded " + prizes.boosterPacks.size() + " booster pack" + packPlural + "!", "Booster Pack" + packPlural + " Awarded", FSkin.getImage(FSkinProp.ICO_QUEST_BOX));
if (FModel.getPreferences().getPrefBoolean(FPref.UI_OPEN_PACKS_INDIV) && prizes.boosterPacks.size() > 1) {
boolean skipTheRest = false;
List<PaperCard> remainingCards = new ArrayList<>();
int totalPacks = prizes.boosterPacks.size();
final List<PaperCard> remainingCards = new ArrayList<>();
final int totalPacks = prizes.boosterPacks.size();
int currentPack = 0;
while (prizes.boosterPacks.size() > 0) {
BoosterPack pack = prizes.boosterPacks.remove(0);
final BoosterPack pack = prizes.boosterPacks.remove(0);
currentPack++;
if (skipTheRest) {
@@ -206,10 +207,10 @@ public enum CSubmenuQuestDraft implements ICDoc {
} else {
List<PaperCard> cards = new ArrayList<>();
final List<PaperCard> cards = new ArrayList<>();
while (prizes.boosterPacks.size() > 0) {
BoosterPack pack = prizes.boosterPacks.remove(0);
final BoosterPack pack = prizes.boosterPacks.remove(0);
cards.addAll(pack.getCards());
}
@@ -225,7 +226,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
FOptionPane.showMessageDialog("For placing " + placement + ", you may select a rare or mythic rare card from the drafted block.", "Rare Awarded", FSkin.getImage(FSkinProp.ICO_QUEST_STAKES));
CardListChooser cardListChooser = new CardListChooser("Select a Card", "Select a card to keep:", prizes.selectRareCards);
final CardListChooser cardListChooser = new CardListChooser("Select a Card", "Select a card to keep:", prizes.selectRareCards);
cardListChooser.setVisible(true);
cardListChooser.dispose();
prizes.addSelectedCard(cardListChooser.getSelectedCard());
@@ -241,7 +242,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
}
boolean saveDraft = FOptionPane.showOptionDialog("Would you like to save this draft to the regular draft mode?", "Save Draft?", FSkin.getImage(FSkinProp.ICO_QUESTION).scale(2.0), new String[] { "Yes", "No" }, 0) == 0;
final boolean saveDraft = FOptionPane.showOptionDialog("Would you like to save this draft to the regular draft mode?", "Save Draft?", FSkin.getImage(FSkinProp.ICO_QUESTION).scale(2.0), new String[] { "Yes", "No" }, 0) == 0;
if (saveDraft) {
draft.saveToRegularDraft();
@@ -250,7 +251,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
draft.addToQuestDecks();
VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
final VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
CSubmenuQuestDraft.SINGLETON_INSTANCE.update();
view.populate();
@@ -260,28 +261,28 @@ public enum CSubmenuQuestDraft implements ICDoc {
private final ActionListener selectTournamentStart = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
public void actionPerformed(final ActionEvent event) {
CSubmenuQuestDraft.this.startDraft();
}
};
private final ActionListener prepareDeckStart = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
public void actionPerformed(final ActionEvent event) {
CSubmenuQuestDraft.this.startTournament();
}
};
private final ActionListener nextMatchStart = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
public void actionPerformed(final ActionEvent event) {
CSubmenuQuestDraft.this.startNextMatch();
}
};
private final KeyAdapter startOnEnter = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
public void keyPressed(final KeyEvent e) {
if (KeyEvent.VK_ENTER == e.getKeyChar()) {
VSubmenuQuestDraft.SINGLETON_INSTANCE.getBtnStartDraft().doClick();
}
@@ -290,7 +291,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
private final MouseAdapter startOnDblClick = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
public void mouseClicked(final MouseEvent e) {
if (MouseEvent.BUTTON1 == e.getButton() && 2 == e.getClickCount()) {
VSubmenuQuestDraft.SINGLETON_INSTANCE.getBtnStartDraft().doClick();
}
@@ -299,7 +300,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
private void spendToken() {
QuestAchievements achievements = FModel.getQuest().getAchievements();
final QuestAchievements achievements = FModel.getQuest().getAchievements();
if (achievements != null) {
@@ -321,14 +322,14 @@ public enum CSubmenuQuestDraft implements ICDoc {
@Override
public void update() {
VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
final VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
if (FModel.getQuest().getAchievements() == null) {
view.setMode(Mode.EMPTY);
return;
}
QuestAchievements achievements = FModel.getQuest().getAchievements();
final QuestAchievements achievements = FModel.getQuest().getAchievements();
achievements.generateDrafts();
if (FModel.getQuest().getAchievements().getDraftEvents().isEmpty()) {
@@ -372,21 +373,21 @@ public enum CSubmenuQuestDraft implements ICDoc {
private void updateSelectTournament() {
VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
final VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
view.getLblCredits().setText("Available Credits: " + NUMBER_FORMATTER.format(FModel.getQuest().getAssets().getCredits()));
QuestAchievements achievements = FModel.getQuest().getAchievements();
final QuestAchievements achievements = FModel.getQuest().getAchievements();
achievements.generateDrafts();
view.getPnlTournaments().removeAll();
JXButtonPanel grpPanel = new JXButtonPanel();
final JXButtonPanel grpPanel = new JXButtonPanel();
boolean firstPanel = true;
for (QuestEventDraft draft : FModel.getQuest().getAchievements().getDraftEvents()) {
for (final QuestEventDraft draft : FModel.getQuest().getAchievements().getDraftEvents()) {
PnlDraftEvent draftPanel = new PnlDraftEvent(draft);
final PnlDraftEvent draftPanel = new PnlDraftEvent(draft);
final JRadioButton button = draftPanel.getRadioButton();
if (firstPanel) {
@@ -412,8 +413,8 @@ public enum CSubmenuQuestDraft implements ICDoc {
private void updatePlacementLabelsText() {
VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
QuestAchievements achievements = FModel.getQuest().getAchievements();
final VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
final QuestAchievements achievements = FModel.getQuest().getAchievements();
if (view.getMode().equals(Mode.EMPTY)) {
view.getPnlTournaments().removeAll();
@@ -434,7 +435,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
private void updateTournamentActive() {
VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
final VSubmenuQuestDraft view = VSubmenuQuestDraft.SINGLETON_INSTANCE;
if (FModel.getQuest().getAchievements().getCurrentDraft() == null) {
return;
@@ -463,8 +464,8 @@ public enum CSubmenuQuestDraft implements ICDoc {
break;
}
boolean first = i % 2 == 0;
int box = i / 2;
final boolean first = i % 2 == 0;
final int box = i / 2;
SkinImage icon = FSkin.getAvatars().get(iconID);
@@ -488,7 +489,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
}
public void setCompletedDraft(DeckGroup finishedDraft) {
public void setCompletedDraft(final DeckGroup finishedDraft) {
QuestDraftUtils.completeDraft(finishedDraft);
@@ -548,7 +549,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
FModel.getQuest().save();
String message = GameType.QuestDraft.getDeckFormat().getDeckConformanceProblem(FModel.getQuest().getAssets().getDraftDeckStorage().get(QuestEventDraft.DECK_NAME).getHumanDeck());
final String message = GameType.QuestDraft.getDeckFormat().getDeckConformanceProblem(FModel.getQuest().getAssets().getDraftDeckStorage().get(QuestEventDraft.DECK_NAME).getHumanDeck());
if (message != null && FModel.getPreferences().getPrefBoolean(FPref.ENFORCE_DECK_LEGALITY)) {
FOptionPane.showMessageDialog(message, "Deck Invalid");
return;
@@ -577,18 +578,4 @@ public enum CSubmenuQuestDraft implements ICDoc {
}
@Override
public UiCommand getCommandOnSelect() {
final QuestController qc = FModel.getQuest();
return new UiCommand() {
private static final long serialVersionUID = 6153589785507038445L;
@Override
public void run() {
if (qc.getAchievements() == null) {
CHomeUI.SINGLETON_INSTANCE.itemClick(EDocID.HOME_QUESTDATA);
}
}
};
}
}

View File

@@ -4,7 +4,6 @@ import javax.swing.SwingUtilities;
import com.google.common.primitives.Ints;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
import forge.model.FModel;
import forge.quest.data.QuestPreferences;
@@ -102,11 +101,4 @@ public enum CSubmenuQuestPrefs implements ICDoc {
view.getLblErrShop().setVisible(false);
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -1,394 +0,0 @@
package forge.screens.home.quest;
import forge.assets.FSkinProp;
import forge.model.FModel;
import forge.quest.data.QuestPreferences;
import forge.quest.data.QuestPreferences.QPref;
import forge.toolbox.FLabel;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinnedPanel;
import forge.toolbox.FSkin.SkinnedTextField;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
@SuppressWarnings("serial")
public class QuestPreferencesHandler extends SkinnedPanel {
private final QuestPreferences prefs;
private final JPanel pnlDifficulty, pnlBooster, pnlRewards, pnlShop;
private final FLabel lblErrRewards, lblErrBooster, lblErrDifficulty, lblErrShop;
private String constraints1, constraints2;
private enum ErrType {
REWARDS,
DIFFICULTY,
BOOSTER,
SHOP
}
/** */
public QuestPreferencesHandler() {
this.setOpaque(false);
this.setLayout(new MigLayout("insets 0, gap 0, wrap"));
this.prefs = FModel.getQuestPreferences();
pnlRewards = new JPanel();
pnlDifficulty = new JPanel();
pnlBooster = new JPanel();
pnlShop = new JPanel();
lblErrRewards = new FLabel.Builder().text("Rewards Error").fontStyle(Font.BOLD).build();
lblErrDifficulty = new FLabel.Builder().text("Difficulty Error").fontStyle(Font.BOLD).build();
lblErrBooster = new FLabel.Builder().text("Booster Error").fontStyle(Font.BOLD).build();
lblErrShop = new FLabel.Builder().text("Shop Error").fontStyle(Font.BOLD).build();
lblErrRewards.setForeground(Color.red);
lblErrDifficulty.setForeground(Color.red);
lblErrBooster.setForeground(Color.red);
lblErrShop.setForeground(Color.red);
// Rewards panel
pnlRewards.setOpaque(false);
pnlRewards.setLayout(new MigLayout("insets 0, gap 0, wrap 2"));
pnlRewards.add(new FLabel.Builder().text("Rewards")
.icon(FSkin.getImage(FSkinProp.ICO_QUEST_COIN)).build(),
"w 100%!, h 30px!, span 2 1");
pnlRewards.add(lblErrRewards, "w 100%!, h 30px!, span 2 1");
constraints1 = "w 60px, h 26px!";
constraints2 = "w 150px!, h 26px!";
pnlRewards.add(new FLabel.Builder().text("Base winnings").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_BASE, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("No losses").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_UNDEFEATED, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("Poison win").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_POISON, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("Milling win").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_MILLED, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("Mulligan 0 win").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_MULLIGAN0, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("Alternative win").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_ALTERNATIVE, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("Win by turn 15").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_TURN15, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("Win by turn 10").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_TURN10, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("Win by turn 5").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_TURN5, ErrType.REWARDS), constraints1);
pnlRewards.add(new FLabel.Builder().text("First turn win").build(), constraints2);
pnlRewards.add(new PrefInput(QPref.REWARDS_TURN1, ErrType.REWARDS), constraints1);
// Difficulty table panel
pnlDifficulty.setOpaque(false);
pnlDifficulty.setLayout(new MigLayout("insets 0, gap 0, wrap 5"));
pnlDifficulty.add(new FLabel.Builder().text("Difficulty Adjustments").icon(FSkin.getImage(FSkinProp.ICO_QUEST_NOTES)).build(), "w 100%!, h 30px!, span 5 1");
pnlDifficulty.add(lblErrDifficulty, "w 100%!, h 30px!, span 5 1");
constraints1 = "w 60px!, h 26px!";
constraints2 = "w 150px!, h 26px!";
pnlDifficulty.add(new FLabel.Builder().text("").build(), constraints2);
pnlDifficulty.add(new FLabel.Builder().text("Easy").build(), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Medium").build(), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Hard").build(), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Expert").build(), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Wins For Booster").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.WINS_BOOSTER_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_BOOSTER_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_BOOSTER_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_BOOSTER_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Wins For Rank Increase").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.WINS_RANKUP_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_RANKUP_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_RANKUP_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_RANKUP_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Wins For Medium AI").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.WINS_MEDIUMAI_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_MEDIUMAI_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_MEDIUMAI_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_MEDIUMAI_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Wins For Hard AI").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.WINS_HARDAI_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_HARDAI_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_HARDAI_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_HARDAI_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Wins For Expert AI").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.WINS_EXPERTAI_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_EXPERTAI_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_EXPERTAI_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.WINS_EXPERTAI_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Starting commons").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.STARTING_COMMONS_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_COMMONS_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_COMMONS_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_COMMONS_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Starting uncommons").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.STARTING_UNCOMMONS_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_UNCOMMONS_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_UNCOMMONS_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_UNCOMMONS_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Starting rares").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.STARTING_RARES_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_RARES_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_RARES_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_RARES_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Starting credits").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.STARTING_CREDITS_EASY, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_CREDITS_MEDIUM, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_CREDITS_HARD, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new PrefInput(QPref.STARTING_CREDITS_EXPERT, ErrType.DIFFICULTY), constraints1);
pnlDifficulty.add(new FLabel.Builder().text("Starting basic lands").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.STARTING_BASIC_LANDS, ErrType.DIFFICULTY), constraints1 + ", wrap");
pnlDifficulty.add(new FLabel.Builder().text("Starting snow lands").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.STARTING_SNOW_LANDS, ErrType.DIFFICULTY), constraints1 + ", wrap");
pnlDifficulty.add(new FLabel.Builder().text("Color bias (1-10)").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.STARTING_POOL_COLOR_BIAS, ErrType.DIFFICULTY), constraints1 + ", wrap");
pnlDifficulty.add(new FLabel.Builder().text("Penalty for loss").build(), constraints2);
pnlDifficulty.add(new PrefInput(QPref.PENALTY_LOSS, ErrType.DIFFICULTY), constraints1 + ", wrap");
// Booster breakdown panel
pnlBooster.setOpaque(false);
pnlBooster.setLayout(new MigLayout("insets 0, gap 0, wrap 2"));
pnlBooster.add(new FLabel.Builder().text("Booster Pack Ratios")
.icon(FSkin.getImage(FSkinProp.ICO_QUEST_BOOK)).build(),
"w 100%!, h 30px!, span 2 1");
pnlBooster.add(lblErrBooster, "w 100%!, h 30px!, span 2 1");
constraints1 = "w 60px!, h 26px!";
constraints2 = "w 150px!, h 26px!";
pnlBooster.add(new FLabel.Builder().text("Common").build(), constraints2);
pnlBooster.add(new PrefInput(QPref.BOOSTER_COMMONS, ErrType.BOOSTER), constraints1);
pnlBooster.add(new FLabel.Builder().text("Uncommon").build(), constraints2);
pnlBooster.add(new PrefInput(QPref.BOOSTER_UNCOMMONS, ErrType.BOOSTER), constraints1);
pnlBooster.add(new FLabel.Builder().text("Rare").build(), constraints2);
pnlBooster.add(new PrefInput(QPref.BOOSTER_RARES, ErrType.BOOSTER), constraints1);
// Shop panel
pnlShop.setOpaque(false);
pnlShop.setLayout(new MigLayout("insets 0, gap 0, wrap 2"));
pnlShop.add(new FLabel.Builder().text("Shop Preferences")
.icon(FSkin.getImage(FSkinProp.ICO_QUEST_COIN)).build(), "w 100%!, h 30px!, span 2 1");
pnlShop.add(lblErrShop, "w 100%!, h 30px!, span 2 1");
constraints1 = "w 60px, h 26px!";
constraints2 = "w 150px!, h 26px!";
pnlShop.add(new FLabel.Builder().text("Maximum Packs").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_MAX_PACKS, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Minimum Packs").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_MIN_PACKS, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Starting Packs").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_STARTING_PACKS, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Wins for Pack").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_WINS_FOR_ADDITIONAL_PACK, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Wins per Set Unlock").build(), constraints2);
pnlShop.add(new PrefInput(QPref.WINS_UNLOCK_SET, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Common Singles").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_SINGLES_COMMON, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Uncommon Singles").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_SINGLES_UNCOMMON, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Rare Singles").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_SINGLES_RARE, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Card Sale Price Cap").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_MAX_SELLING_PRICE, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Wins to Uncap Sale Price").build(), constraints2);
pnlShop.add(new PrefInput(QPref.SHOP_WINS_FOR_NO_SELL_LIMIT, ErrType.SHOP), constraints1);
pnlShop.add(new FLabel.Builder().text("Item Level Restriction").build(), constraints2);
pnlShop.add(new PrefInput(QPref.ITEM_LEVEL_RESTRICTION, ErrType.SHOP), constraints1);
constraints1 = "w 100%!, gap 0 0 20px 0";
this.add(pnlRewards, constraints1);
this.add(pnlDifficulty, constraints1);
this.add(pnlBooster, constraints1);
this.add(pnlShop, constraints1);
resetErrors();
}
private class PrefInput extends SkinnedTextField {
private final QPref qpref;
private final ErrType err;
private final FSkin.SkinColor clrHover, clrActive, clrText;
private boolean isFocus = false;
private String previousText = "";
/**
* @param qp1 &emsp; {@link forge.quest.data.QuestPreferences.QPref}
* preferences ident enum
* @param e0 &emsp; {@link forge.view.home.ViewQuestPreference.ErrType}
* where error should display to
*/
public PrefInput(QPref qp0, ErrType e0) {
super();
this.qpref = qp0;
this.err = e0;
this.clrHover = FSkin.getColor(FSkin.Colors.CLR_HOVER);
this.clrActive = FSkin.getColor(FSkin.Colors.CLR_ACTIVE);
this.clrText = FSkin.getColor(FSkin.Colors.CLR_TEXT);
this.setOpaque(false);
this.setBorder((Border)null);
this.setFont(FSkin.getFont(13));
this.setForeground(clrText);
this.setCaretColor(clrText);
this.setBackground(clrHover);
this.setHorizontalAlignment(SwingConstants.CENTER);
this.setText(prefs.getPref(qpref));
this.setPreviousText(prefs.getPref(qpref));
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
if (isFocus) { return; }
setOpaque(true);
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
if (isFocus) { return; }
setOpaque(false);
repaint();
}
});
this.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
isFocus = true;
setOpaque(true);
setBackground(clrActive);
}
@Override
public void focusLost(FocusEvent e) {
isFocus = false;
setOpaque(false);
setBackground(clrHover);
// TODO for slight performance improvement
// check if value has changed before validating
validateAndSave(PrefInput.this);
}
});
}
public QPref getQPref() {
return this.qpref;
}
public ErrType getErrType() {
return this.err;
}
public String getPreviousText() {
return this.previousText;
}
public void setPreviousText(String s0) {
this.previousText = s0;
}
}
/**
* Checks validity of values entered into prefInputs.
* @param i0 &emsp; a PrefInput object
*/
private void validateAndSave(PrefInput i0) {
if (i0.getText().equals(i0.getPreviousText())) { return; }
int val = Integer.parseInt(i0.getText());
resetErrors();
String validationError = prefs.validatePreference(i0.getQPref(), val);
if (validationError != null) {
showError(i0, validationError);
return;
}
prefs.setPref(i0.getQPref(), i0.getText());
prefs.save();
i0.setPreviousText(i0.getText());
}
private void showError(PrefInput i0, String s0) {
String s = "Save failed: " + s0;
switch(i0.getErrType()) {
case BOOSTER:
lblErrBooster.setVisible(true);
lblErrBooster.setText(s);
break;
case DIFFICULTY:
lblErrDifficulty.setVisible(true);
lblErrDifficulty.setText(s);
break;
case REWARDS:
lblErrRewards.setVisible(true);
lblErrRewards.setText(s);
break;
case SHOP:
lblErrShop.setVisible(true);
lblErrShop.setText(s);
break;
default:
}
i0.setText(i0.getPreviousText());
}
private void resetErrors() {
lblErrBooster.setVisible(false);
lblErrDifficulty.setVisible(false);
lblErrRewards.setVisible(false);
lblErrShop.setVisible(false);
}
}

View File

@@ -1,17 +1,29 @@
package forge.screens.home.quest;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import forge.assets.FSkinProp;
import forge.gui.framework.DragCell;
import forge.gui.framework.DragTab;
import forge.gui.framework.EDocID;
import forge.quest.IVQuestStats;
import forge.screens.home.*;
import forge.toolbox.*;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;
import forge.screens.home.EMenuGroup;
import forge.screens.home.IVSubmenu;
import forge.screens.home.LblHeader;
import forge.screens.home.StartButton;
import forge.screens.home.VHomeUI;
import forge.toolbox.FCheckBox;
import forge.toolbox.FComboBoxWrapper;
import forge.toolbox.FLabel;
import forge.toolbox.FScrollPanel;
import forge.toolbox.FSkin;
/**
* Assembles Swing components of quest challenges submenu singleton.
@@ -268,7 +280,7 @@ public enum VSubmenuChallenges implements IVSubmenu<CSubmenuChallenges>, IVQuest
* @see forge.gui.framework.IVDoc#setParentCell(forge.gui.framework.DragCell)
*/
@Override
public void setParentCell(DragCell cell0) {
public void setParentCell(final DragCell cell0) {
this.parentCell = cell0;
}
@@ -283,6 +295,7 @@ public enum VSubmenuChallenges implements IVSubmenu<CSubmenuChallenges>, IVQuest
/**
* @return the cbCharm
*/
@Override
public FCheckBox getCbCharm() {
return cbCharm;
}

View File

@@ -1,18 +1,30 @@
package forge.screens.home.quest;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import forge.assets.FSkinProp;
import forge.gui.framework.DragCell;
import forge.gui.framework.DragTab;
import forge.gui.framework.EDocID;
import forge.interfaces.IButton;
import forge.quest.IVQuestStats;
import forge.screens.home.*;
import forge.toolbox.*;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;
import forge.screens.home.EMenuGroup;
import forge.screens.home.IVSubmenu;
import forge.screens.home.LblHeader;
import forge.screens.home.StartButton;
import forge.screens.home.VHomeUI;
import forge.toolbox.FCheckBox;
import forge.toolbox.FComboBoxWrapper;
import forge.toolbox.FLabel;
import forge.toolbox.FScrollPanel;
import forge.toolbox.FSkin;
/**
* Assembles Swing components of quest duels submenu singleton.
@@ -20,7 +32,6 @@ import java.awt.*;
* <br><br><i>(V at beginning of class name denotes a view class.)</i>
*/
public enum VSubmenuDuels implements IVSubmenu<CSubmenuDuels>, IVQuestStats {
/** */
SINGLETON_INSTANCE;
// Fields used with interface IVDoc
@@ -274,7 +285,7 @@ public enum VSubmenuDuels implements IVSubmenu<CSubmenuDuels>, IVQuestStats {
* @see forge.gui.framework.IVDoc#setParentCell(forge.gui.framework.DragCell)
*/
@Override
public void setParentCell(DragCell cell0) {
public void setParentCell(final DragCell cell0) {
this.parentCell = cell0;
}
@@ -289,6 +300,7 @@ public enum VSubmenuDuels implements IVSubmenu<CSubmenuDuels>, IVQuestStats {
/**
* @return the cbCharm
*/
@Override
public FCheckBox getCbCharm() {
return cbCharm;
}

View File

@@ -1,5 +1,20 @@
package forge.screens.home.quest;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.text.WordUtils;
import forge.card.MagicColor;
import forge.deck.Deck;
import forge.deck.DeckGroup;
@@ -17,20 +32,14 @@ import forge.quest.StartingPoolType;
import forge.screens.home.EMenuGroup;
import forge.screens.home.IVSubmenu;
import forge.screens.home.VHomeUI;
import forge.toolbox.*;
import forge.toolbox.FCheckBox;
import forge.toolbox.FComboBoxWrapper;
import forge.toolbox.FLabel;
import forge.toolbox.FRadioButton;
import forge.toolbox.FScrollPane;
import forge.toolbox.FSkin;
import forge.toolbox.JXButtonPanel;
import forge.util.storage.IStorage;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.text.WordUtils;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
/**
* Assembles Swing components of quest data submenu singleton.
@@ -115,8 +124,8 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
private final ActionListener alStartingPool = new ActionListener() {
@SuppressWarnings("incomplete-switch")
@Override
public void actionPerformed(ActionEvent e) {
StartingPoolType newVal = getStartingPoolType();
public void actionPerformed(final ActionEvent e) {
final StartingPoolType newVal = getStartingPoolType();
lblUnrestricted.setVisible(newVal == StartingPoolType.Complete);
lblPreconDeck.setVisible(newVal == StartingPoolType.Precon);
@@ -128,22 +137,22 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
btnDefineCustomFormat.setVisible(newVal == StartingPoolType.CustomFormat);
boolean usesDeckList = newVal == StartingPoolType.SealedDeck || newVal == StartingPoolType.DraftDeck || newVal == StartingPoolType.Cube;
final boolean usesDeckList = newVal == StartingPoolType.SealedDeck || newVal == StartingPoolType.DraftDeck || newVal == StartingPoolType.Cube;
lblCustomDeck.setVisible(usesDeckList);
cbxCustomDeck.setVisible(usesDeckList);
if (usesDeckList) {
cbxCustomDeck.removeAllItems();
CardCollections decks = FModel.getDecks();
final CardCollections decks = FModel.getDecks();
switch (newVal) {
case SealedDeck:
for (DeckGroup d : decks.getSealed()) { cbxCustomDeck.addItem(d.getHumanDeck()); }
for (final DeckGroup d : decks.getSealed()) { cbxCustomDeck.addItem(d.getHumanDeck()); }
break;
case DraftDeck:
for (DeckGroup d : decks.getDraft()) { cbxCustomDeck.addItem(d.getHumanDeck()); }
for (final DeckGroup d : decks.getDraft()) { cbxCustomDeck.addItem(d.getHumanDeck()); }
break;
case Cube:
for (Deck d : decks.getCubes()) { cbxCustomDeck.addItem(d); }
for (final Deck d : decks.getCubes()) { cbxCustomDeck.addItem(d); }
break;
}
}
@@ -153,8 +162,8 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
/* Listeners */
private final ActionListener alPrizesPool = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StartingPoolType newVal = getPrizedPoolType();
public void actionPerformed(final ActionEvent e) {
final StartingPoolType newVal = getPrizedPoolType();
lblPrizeUnrestricted.setVisible(newVal == StartingPoolType.Complete);
cboAllowUnlocks.setVisible(newVal != StartingPoolType.Complete);
@@ -168,7 +177,7 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
/* Listeners */
private final ActionListener alStartingWorld = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
public void actionPerformed(final ActionEvent e) {
updateEnabledFormats();
}
};
@@ -226,7 +235,7 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
cbxPrizedCards.addItem(StartingPoolType.CustomFormat);
cbxPrizedCards.addActionListener(alPrizesPool);
for (GameFormat gf : FModel.getFormats().getOrderedList()) {
for (final GameFormat gf : FModel.getFormats().getOrderedList()) {
cbxFormat.addItem(gf);
cbxPrizeFormat.addItem(gf);
}
@@ -241,7 +250,7 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
cbxPreferredColor.addItem(MagicColor.Constant.GREEN + stringBias);
cbxPreferredColor.addItem(MagicColor.Constant.COLORLESS + stringBias);
for (QuestWorld qw : FModel.getWorlds()) {
for (final QuestWorld qw : FModel.getWorlds()) {
cbxStartingWorld.addItem(qw);
}
// Default to 'Main world'
@@ -253,13 +262,13 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
cboAllowUnlocks.setSelected(true);
final Map<String, String> preconDescriptions = new HashMap<String, String>();
IStorage<PreconDeck> preconDecks = QuestController.getPrecons();
final IStorage<PreconDeck> preconDecks = QuestController.getPrecons();
for (PreconDeck preconDeck : preconDecks) {
for (final PreconDeck preconDeck : preconDecks) {
if (QuestController.getPreconDeals(preconDeck).getMinWins() > 0) {
continue;
}
String name = preconDeck.getName();
final String name = preconDeck.getName();
cbxPreconDeck.addItem(name);
String description = preconDeck.getDescription();
description = "<html>" + WordUtils.wrap(description, 40, "<br>", false) + "</html>";
@@ -273,11 +282,11 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
@SuppressWarnings("rawtypes")
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component defaultComponent =
final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) {
final Component defaultComponent =
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (-1 < index && null != value) {
String val = (String) value;
final String val = (String) value;
list.setToolTipText(preconDescriptions.get(val));
}
return defaultComponent;
@@ -294,14 +303,14 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
pnlOptions.setOpaque(false);
pnlOptions.setLayout(new MigLayout("insets 0, gap 10px, fillx, wrap 2"));
JPanel pnlDifficultyMode = new JPanel(new MigLayout("insets 0, gap 1%, flowy"));
final JPanel pnlDifficultyMode = new JPanel(new MigLayout("insets 0, gap 1%, flowy"));
pnlDifficultyMode.add(difficultyPanel, "gapright 4%");
pnlDifficultyMode.add(boxFantasy, difficulty_constraints + ", gapright 4%");
pnlDifficultyMode.setOpaque(false);
pnlOptions.add(pnlDifficultyMode, "w 40%");
JPanel pnlRestrictions = new JPanel();
final JPanel pnlRestrictions = new JPanel();
final String constraints = "h 27px!, ";
final String lblWidth = "w 40%, ";
final String hidemode = "hidemode 3, ";
@@ -442,7 +451,7 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
* @see forge.gui.framework.IVDoc#setParentCell(forge.gui.framework.DragCell)
*/
@Override
public void setParentCell(DragCell cell0) {
public void setParentCell(final DragCell cell0) {
this.parentCell = cell0;
}
@@ -472,7 +481,7 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
}
public Deck getSelectedDeck() {
Object sel = cbxCustomDeck.getSelectedItem();
final Object sel = cbxCustomDeck.getSelectedItem();
return sel instanceof Deck ? (Deck) sel : null;
}
@@ -481,11 +490,11 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
}
public StartingPoolType getStartingPoolType() {
return (StartingPoolType) cbxStartingPool.getSelectedItem();
return cbxStartingPool.getSelectedItem();
}
public StartingPoolType getPrizedPoolType() {
Object v = cbxPrizedCards.getSelectedItem();
final Object v = cbxPrizedCards.getSelectedItem();
return v instanceof StartingPoolType ? (StartingPoolType) v : null;
}
@@ -514,11 +523,11 @@ public enum VSubmenuQuestData implements IVSubmenu<CSubmenuQuestData> {
}
public GameFormat getRotatingFormat() {
return (GameFormat) cbxFormat.getSelectedItem();
return cbxFormat.getSelectedItem();
}
public GameFormat getPrizedRotatingFormat() {
return (GameFormat) cbxPrizeFormat.getSelectedItem();
return cbxPrizeFormat.getSelectedItem();
}
public FLabel getBtnCustomFormat() {

View File

@@ -1,5 +1,15 @@
package forge.screens.home.sanctioned;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import forge.gui.WrapLayout;
import forge.toolbox.FLabel;
import forge.toolbox.FScrollPane;
@@ -7,17 +17,9 @@ import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinImage;
import forge.view.FDialog;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@SuppressWarnings("serial")
public class AvatarSelector extends FDialog {
private List<FLabel> selectables = new ArrayList<FLabel>();
private final List<FLabel> selectables = new ArrayList<FLabel>();
private final Map<Integer, SkinImage> avatarMap = FSkin.getAvatars();
public AvatarSelector(final String playerName, final int currentIndex, final Collection<Integer> usedIndices) {
@@ -28,7 +30,7 @@ public class AvatarSelector extends FDialog {
pnlAvatarPics.setOpaque(false);
pnlAvatarPics.setOpaque(false);
FLabel initialSelection = makeAvatarLabel(avatarMap.get(currentIndex), currentIndex, currentIndex);
final FLabel initialSelection = makeAvatarLabel(avatarMap.get(currentIndex), currentIndex, currentIndex);
pnlAvatarPics.add(initialSelection);
for (final Integer i : avatarMap.keySet()) {
//if (!usedIndices.contains(i)) { // Decided to allow duplicate avatars when manually selecting
@@ -42,7 +44,7 @@ public class AvatarSelector extends FDialog {
this.setPreferredSize(new Dimension(width, height));
this.setSize(width, height);
FScrollPane scroller = new FScrollPane(pnlAvatarPics, false);
final FScrollPane scroller = new FScrollPane(pnlAvatarPics, false);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
this.add(scroller, "w 100%-24px!, pushy, growy, gap 12px 0 0 0");
this.setDefaultFocus(initialSelection);

View File

@@ -5,7 +5,6 @@ import java.util.List;
import javax.swing.JMenu;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
import forge.menus.IMenuProvider;
import forge.menus.MenuUtil;
@@ -45,20 +44,12 @@ public enum CSubmenuConstructed implements ICDoc, IMenuProvider {
lobby.initialize();
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
/* (non-Javadoc)
* @see forge.gui.menubar.IMenuProvider#getMenus()
*/
@Override
public List<JMenu> getMenus() {
List<JMenu> menus = new ArrayList<JMenu>();
final List<JMenu> menus = new ArrayList<JMenu>();
menus.add(ConstructedGameMenu.getMenu());
return menus;
}

View File

@@ -35,11 +35,9 @@ import forge.toolbox.FOptionPane;
* Controls the draft submenu in the home UI.
*
* <br><br><i>(C at beginning of class name denotes a control class.)</i>
*
*/
@SuppressWarnings("serial")
public enum CSubmenuDraft implements ICDoc {
/** */
SINGLETON_INSTANCE;
private final UiCommand cmdDeckSelect = new UiCommand() {
@@ -114,7 +112,7 @@ public enum CSubmenuDraft implements ICDoc {
}
if (FModel.getPreferences().getPrefBoolean(FPref.ENFORCE_DECK_LEGALITY)) {
String errorMessage = gameType.getDeckFormat().getDeckConformanceProblem(humanDeck.getDeck());
final String errorMessage = gameType.getDeckFormat().getDeckConformanceProblem(humanDeck.getDeck());
if (null != errorMessage) {
FOptionPane.showErrorDialog("Your deck " + errorMessage + " Please edit or choose a different deck.", "Invalid Deck");
return;
@@ -124,7 +122,7 @@ public enum CSubmenuDraft implements ICDoc {
FModel.getGauntletMini().resetGauntletDraft();
if (gauntlet) {
int rounds = FModel.getDecks().getDraft().get(humanDeck.getName()).getAiDecks().size();
final int rounds = FModel.getDecks().getDraft().get(humanDeck.getName()).getAiDecks().size();
FModel.getGauntletMini().launch(rounds, humanDeck.getDeck(), gameType);
return;
}
@@ -147,7 +145,7 @@ public enum CSubmenuDraft implements ICDoc {
final RegisteredPlayer human = new RegisteredPlayer(humanDeck.getDeck()).setPlayer(GamePlayerUtil.getGuiPlayer());
starter.add(human);
starter.add(new RegisteredPlayer(aiDeck).setPlayer(GamePlayerUtil.createAiPlayer()));
for (RegisteredPlayer pl : starter) {
for (final RegisteredPlayer pl : starter) {
pl.assignConspiracies();
}
@@ -168,7 +166,7 @@ public enum CSubmenuDraft implements ICDoc {
final LimitedPoolType poolType = GuiChoose.oneOrNone("Choose Draft Format", LimitedPoolType.values());
if (poolType == null) { return; }
BoosterDraft draft = BoosterDraft.createDraft(poolType);
final BoosterDraft draft = BoosterDraft.createDraft(poolType);
if (draft == null) { return; }
final CEditorDraftingProcess draftController = new CEditorDraftingProcess(CDeckEditorUI.SINGLETON_INSTANCE.getCDetailPicture());
@@ -178,11 +176,4 @@ public enum CSubmenuDraft implements ICDoc {
CDeckEditorUI.SINGLETON_INSTANCE.setEditorController(draftController);
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -88,7 +88,7 @@ public enum CSubmenuSealed implements ICDoc {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JButton btnStart = view.getBtnStart();
final JButton btnStart = view.getBtnStart();
if (btnStart.isEnabled()) {
view.getBtnStart().requestFocusInWindow();
} else {
@@ -107,14 +107,14 @@ public enum CSubmenuSealed implements ICDoc {
}
if (FModel.getPreferences().getPrefBoolean(FPref.ENFORCE_DECK_LEGALITY)) {
String errorMessage = gameType.getDeckFormat().getDeckConformanceProblem(human.getDeck());
final String errorMessage = gameType.getDeckFormat().getDeckConformanceProblem(human.getDeck());
if (null != errorMessage) {
FOptionPane.showErrorDialog("Your deck " + errorMessage + " Please edit or choose a different deck.", "Invalid Deck");
return;
}
}
int matches = FModel.getDecks().getSealed().get(human.getName()).getAiDecks().size();
final int matches = FModel.getDecks().getSealed().get(human.getName()).getAiDecks().size();
FModel.getGauntletMini().launch(matches, human.getDeck(), gameType);
}
@@ -131,11 +131,4 @@ public enum CSubmenuSealed implements ICDoc {
editor.getDeckController().setModel((T) sealed);
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -113,7 +113,7 @@ public enum CSubmenuWinston implements ICDoc {
}
if (FModel.getPreferences().getPrefBoolean(FPref.ENFORCE_DECK_LEGALITY)) {
String errorMessage = gameType.getDeckFormat().getDeckConformanceProblem(humanDeck.getDeck());
final String errorMessage = gameType.getDeckFormat().getDeckConformanceProblem(humanDeck.getDeck());
if (null != errorMessage) {
FOptionPane.showErrorDialog("Your deck " + errorMessage + " Please edit or choose a different deck.", "Invalid Deck");
return;
@@ -156,7 +156,7 @@ public enum CSubmenuWinston implements ICDoc {
final LimitedPoolType poolType = GuiChoose.oneOrNone("Choose Draft Format", LimitedPoolType.values());
if (poolType == null) { return; }
WinstonDraft draft = WinstonDraft.createDraft(poolType);
final WinstonDraft draft = WinstonDraft.createDraft(poolType);
if (draft == null) { return; }
final CEditorWinstonProcess draftController = new CEditorWinstonProcess(CDeckEditorUI.SINGLETON_INSTANCE.getCDetailPicture());
@@ -166,11 +166,4 @@ public enum CSubmenuWinston implements ICDoc {
CDeckEditorUI.SINGLETON_INSTANCE.setEditorController(draftController);
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -1,6 +1,5 @@
package forge.screens.home.settings;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
/**
@@ -31,11 +30,4 @@ public enum CSubmenuAchievements implements ICDoc {
public void update() {
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -1,9 +1,8 @@
package forge.screens.home.settings;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
import javax.swing.SwingUtilities;
import javax.swing.*;
import forge.gui.framework.ICDoc;
/**
* Controls the avatars submenu in the home UI.
@@ -24,15 +23,11 @@ public enum CSubmenuAvatars implements ICDoc {
@Override
public void update() {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
@Override public final void run() {
view.refreshAvatarFromPrefs(0);
view.refreshAvatarFromPrefs(1);
view.focusHuman(); }
});
}
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -1,5 +1,7 @@
package forge.screens.home.settings;
import javax.swing.SwingUtilities;
import forge.UiCommand;
import forge.download.GuiDownloadPicturesLQ;
import forge.download.GuiDownloadPrices;
@@ -10,8 +12,6 @@ import forge.error.BugReporter;
import forge.gui.ImportDialog;
import forge.gui.framework.ICDoc;
import javax.swing.*;
/**
* Controls the utilities submenu in the home UI.
*
@@ -22,22 +22,45 @@ import javax.swing.*;
public enum CSubmenuDownloaders implements ICDoc {
SINGLETON_INSTANCE;
private final UiCommand cmdLicensing = new UiCommand() { @Override
public void run() { VSubmenuDownloaders.SINGLETON_INSTANCE.showLicensing(); } };
private final UiCommand cmdPicDownload = new UiCommand() { @Override
public void run() { new GuiDownloader(new GuiDownloadPicturesLQ()); } };
private final UiCommand cmdSetDownload = new UiCommand() { @Override
public void run() { new GuiDownloader(new GuiDownloadSetPicturesLQ()); } };
private final UiCommand cmdQuestImages = new UiCommand() { @Override
public void run() { new GuiDownloader(new GuiDownloadQuestImages()); } };
private final UiCommand cmdDownloadPrices = new UiCommand() { @Override
public void run() { new GuiDownloader(new GuiDownloadPrices()); } };
private final UiCommand cmdHowToPlay = new UiCommand() { @Override
public void run() { VSubmenuDownloaders.SINGLETON_INSTANCE.showHowToPlay(); } };
private final UiCommand cmdImportPictures = new UiCommand() { @Override
public void run() { new ImportDialog(null, null); } };
private final UiCommand cmdReportBug = new UiCommand() { @Override
public void run() { BugReporter.reportBug(null); }
private final UiCommand cmdLicensing = new UiCommand() {
@Override public void run() {
VSubmenuDownloaders.SINGLETON_INSTANCE.showLicensing();
}
};
private final UiCommand cmdPicDownload = new UiCommand() {
@Override public void run() {
new GuiDownloader(new GuiDownloadPicturesLQ()).show();
}
};
private final UiCommand cmdSetDownload = new UiCommand() {
@Override public void run() {
new GuiDownloader(new GuiDownloadSetPicturesLQ()).show();
}
};
private final UiCommand cmdQuestImages = new UiCommand() {
@Override public void run() {
new GuiDownloader(new GuiDownloadQuestImages()).show();
}
};
private final UiCommand cmdDownloadPrices = new UiCommand() {
@Override public void run() {
new GuiDownloader(new GuiDownloadPrices()).show();
}
};
private final UiCommand cmdHowToPlay = new UiCommand() {
@Override public void run() {
VSubmenuDownloaders.SINGLETON_INSTANCE.showHowToPlay();
}
};
private final UiCommand cmdImportPictures = new UiCommand() {
@Override public void run() {
new ImportDialog(null, null).show();
}
};
private final UiCommand cmdReportBug = new UiCommand() {
@Override public void run() {
BugReporter.reportBug(null);
}
};
@Override
@@ -73,11 +96,4 @@ public enum CSubmenuDownloaders implements ICDoc {
});
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
}

View File

@@ -1,7 +1,20 @@
package forge.screens.home.settings;
import forge.UiCommand;
import java.awt.Desktop;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.SwingUtilities;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import forge.Singletons;
import forge.UiCommand;
import forge.ai.AiProfileUtil;
import forge.control.FControl.CloseAction;
import forge.control.RestartUtil;
@@ -10,27 +23,15 @@ import forge.gui.framework.FScreen;
import forge.gui.framework.ICDoc;
import forge.model.FModel;
import forge.player.GamePlayerUtil;
import forge.properties.ForgeConstants;
import forge.properties.ForgePreferences;
import forge.properties.ForgePreferences.FPref;
import forge.properties.ForgeConstants;
import forge.sound.SoundSystem;
import forge.toolbox.FComboBox;
import forge.toolbox.FComboBoxPanel;
import forge.toolbox.FLabel;
import forge.toolbox.FOptionPane;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import javax.swing.*;
import java.awt.Desktop;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Controls the preferences submenu in the home UI.
*
@@ -191,7 +192,7 @@ public enum CSubmenuPreferences implements ICDoc {
view.getCbDevMode().setSelected(ForgePreferences.DEV_MODE);
view.getCbEnableMusic().setSelected(prefs.getPrefBoolean(FPref.UI_ENABLE_MUSIC));
for(Pair<JCheckBox, FPref> kv: lstControls) {
for(final Pair<JCheckBox, FPref> kv: lstControls) {
kv.getKey().setSelected(prefs.getPrefBoolean(kv.getValue()));
}
view.reloadShortcuts();
@@ -203,20 +204,12 @@ public enum CSubmenuPreferences implements ICDoc {
updating = false;
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
private void resetForgeSettingsToDefault() {
String userPrompt =
final String userPrompt =
"This will reset all preferences to their defaults and restart Forge.\n\n" +
"Reset and restart Forge?";
if (FOptionPane.showConfirmDialog(userPrompt, "Reset Settings")) {
ForgePreferences prefs = FModel.getPreferences();
final ForgePreferences prefs = FModel.getPreferences();
prefs.reset();
prefs.save();
update();
@@ -225,7 +218,7 @@ public enum CSubmenuPreferences implements ICDoc {
}
private void resetDeckEditorLayout() {
String userPrompt =
final String userPrompt =
"This will reset the Deck Editor screen layout.\n" +
"All tabbed views will be restored to their default positions.\n\n" +
"Reset layout?";
@@ -237,7 +230,7 @@ public enum CSubmenuPreferences implements ICDoc {
}
private void resetWorkshopLayout() {
String userPrompt =
final String userPrompt =
"This will reset the Workshop screen layout.\n" +
"All tabbed views will be restored to their default positions.\n\n" +
"Reset layout?";
@@ -249,7 +242,7 @@ public enum CSubmenuPreferences implements ICDoc {
}
private void resetMatchScreenLayout() {
String userPrompt =
final String userPrompt =
"This will reset the layout of the Match screen.\n" +
"If you want to save the current layout first, please use " +
"the Dock tab -> Save Layout option in the Match screen.\n\n" +
@@ -266,8 +259,7 @@ public enum CSubmenuPreferences implements ICDoc {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(new File(ForgeConstants.USER_DIR));
}
}
catch(Exception e) {
} catch(final Exception e) {
System.out.println("Unable to open Directory: " + e.toString());
}
}
@@ -277,17 +269,16 @@ public enum CSubmenuPreferences implements ICDoc {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(new File(ForgeConstants.CACHE_DIR));
}
}
catch(Exception e) {
} catch(final Exception e) {
System.out.println("Unable to open Directory: " + e.toString());
}
}
private void initializeGameLogVerbosityComboBox() {
FPref userSetting = FPref.DEV_LOG_ENTRY_TYPE;
FComboBoxPanel<GameLogEntryType> panel = this.view.getGameLogVerbosityComboBoxPanel();
FComboBox<GameLogEntryType> comboBox = createComboBox(GameLogEntryType.values(), userSetting);
GameLogEntryType selectedItem = GameLogEntryType.valueOf(this.prefs.getPref(userSetting));
final FPref userSetting = FPref.DEV_LOG_ENTRY_TYPE;
final FComboBoxPanel<GameLogEntryType> panel = this.view.getGameLogVerbosityComboBoxPanel();
final FComboBox<GameLogEntryType> comboBox = createComboBox(GameLogEntryType.values(), userSetting);
final GameLogEntryType selectedItem = GameLogEntryType.valueOf(this.prefs.getPref(userSetting));
panel.setComboBox(comboBox, selectedItem);
}
@@ -295,23 +286,22 @@ public enum CSubmenuPreferences implements ICDoc {
final FComboBoxPanel<CloseAction> panel = this.view.getCloseActionComboBoxPanel();
final FComboBox<CloseAction> comboBox = new FComboBox<CloseAction>(CloseAction.values());
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(final ItemEvent e) {
Singletons.getControl().setCloseAction((CloseAction) comboBox.getSelectedItem());
@Override public void itemStateChanged(final ItemEvent e) {
Singletons.getControl().setCloseAction(comboBox.getSelectedItem());
}
});
panel.setComboBox(comboBox, Singletons.getControl().getCloseAction());
}
private void initializeAiProfilesComboBox() {
FPref userSetting = FPref.UI_CURRENT_AI_PROFILE;
FComboBoxPanel<String> panel = this.view.getAiProfilesComboBoxPanel();
FComboBox<String> comboBox = createComboBox(AiProfileUtil.getProfilesArray(), userSetting);
String selectedItem = this.prefs.getPref(userSetting);
final FPref userSetting = FPref.UI_CURRENT_AI_PROFILE;
final FComboBoxPanel<String> panel = this.view.getAiProfilesComboBoxPanel();
final FComboBox<String> comboBox = createComboBox(AiProfileUtil.getProfilesArray(), userSetting);
final String selectedItem = this.prefs.getPref(userSetting);
panel.setComboBox(comboBox, selectedItem);
}
private <E> FComboBox<E> createComboBox(E[] items, final ForgePreferences.FPref setting) {
private <E> FComboBox<E> createComboBox(final E[] items, final ForgePreferences.FPref setting) {
final FComboBox<E> comboBox = new FComboBox<E>(items);
addComboBoxListener(comboBox, setting);
return comboBox;
@@ -319,9 +309,8 @@ public enum CSubmenuPreferences implements ICDoc {
private <E> void addComboBoxListener(final FComboBox<E> comboBox, final ForgePreferences.FPref setting) {
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(final ItemEvent e) {
E selectedType = (E) comboBox.getSelectedItem();
@Override public void itemStateChanged(final ItemEvent e) {
final E selectedType = comboBox.getSelectedItem();
CSubmenuPreferences.this.prefs.setPref(setting, selectedType.toString());
CSubmenuPreferences.this.prefs.save();
}
@@ -329,22 +318,21 @@ public enum CSubmenuPreferences implements ICDoc {
}
private void initializePlayerNameButton() {
FLabel btn = view.getBtnPlayerName();
final FLabel btn = view.getBtnPlayerName();
setPlayerNameButtonText();
btn.setCommand(getPlayerNameButtonCommand());
}
private void setPlayerNameButtonText() {
FLabel btn = view.getBtnPlayerName();
String name = prefs.getPref(FPref.PLAYER_NAME);
final FLabel btn = view.getBtnPlayerName();
final String name = prefs.getPref(FPref.PLAYER_NAME);
btn.setText(StringUtils.isBlank(name) ? "Human" : name);
}
@SuppressWarnings("serial")
private UiCommand getPlayerNameButtonCommand() {
return new UiCommand() {
@Override
public void run() {
@Override public void run() {
GamePlayerUtil.setPlayerName();
setPlayerNameButtonText();
}

View File

@@ -18,7 +18,6 @@
package forge.screens.home.settings;
import forge.UiCommand;
import forge.gui.framework.ICDoc;
import forge.properties.ForgeConstants;
import forge.util.FileUtil;
@@ -67,21 +66,13 @@ public enum CSubmenuReleaseNotes implements ICDoc {
}
}
/* (non-Javadoc)
* @see forge.gui.framework.ICDoc#getCommandOnSelect()
*/
@Override
public UiCommand getCommandOnSelect() {
return null;
}
/**
* Returns content of CHANGES.txt.
*/
private String getReleaseNotes() {
private static String getReleaseNotes() {
// !! Linux is case-sensitive so file name and extension need to match exactly !!
String filename = ForgeConstants.CHANGES_FILE;
String filePath = FileUtil.pathCombine(System.getProperty("user.dir"), filename);
final String filename = ForgeConstants.CHANGES_FILE;
final String filePath = FileUtil.pathCombine(System.getProperty("user.dir"), filename);
String notes;
if (FileUtil.doesFileExist(filePath)) {

View File

@@ -126,7 +126,7 @@ public enum VSubmenuAchievements implements IVSubmenu<CSubmenuAchievements> {
cbCollections.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setAchievements((AchievementCollection)cbCollections.getSelectedItem());
setAchievements(cbCollections.getSelectedItem());
}
});
cbCollections.setSelectedIndex(0);

View File

@@ -42,7 +42,6 @@ import forge.FThreads;
import forge.ImageCache;
import forge.LobbyPlayer;
import forge.Singletons;
import forge.UiCommand;
import forge.assets.FSkinProp;
import forge.control.KeyboardShortcuts;
import forge.deck.CardPool;
@@ -117,7 +116,7 @@ public final class CMatchUI
implements ICDoc, IMenuProvider {
private final FScreen screen;
private VMatchUI view;
private final VMatchUI view;
private final CMatchUIMenus menus = new CMatchUIMenus(this);
private final Map<EDocID, IVDoc<? extends ICDoc>> myDocs;
private final TargetingOverlay targetingOverlay = new TargetingOverlay(this);
@@ -241,7 +240,7 @@ public final class CMatchUI
return ImageCache.getIcon(avatarImages.get(p.getLobbyPlayerName()));
}
int avatarIdx = p.getAvatarIndex();
final int avatarIdx = p.getAvatarIndex();
return FSkin.getAvatars().get(avatarIdx >= 0 ? avatarIdx : defaultIndex);
}
@@ -335,7 +334,7 @@ public final class CMatchUI
cDetailPicture.showItem(item);
}
private int getPlayerIndex(PlayerView player) {
private int getPlayerIndex(final PlayerView player) {
return sortedPlayers.indexOf(player);
}
@@ -344,7 +343,7 @@ public final class CMatchUI
final CombatView combat = getGameView().getCombat();
if (combat != null && combat.getNumAttackers() > 0 && getGameView().peekStack() == null) {
if (selectedDocBeforeCombat == null) {
IVDoc<? extends ICDoc> combatDoc = EDocID.REPORT_COMBAT.getDoc();
final IVDoc<? extends ICDoc> combatDoc = EDocID.REPORT_COMBAT.getDoc();
if (combatDoc.getParentCell() != null) {
selectedDocBeforeCombat = combatDoc.getParentCell().getSelected();
if (selectedDocBeforeCombat != combatDoc) {
@@ -458,11 +457,6 @@ public final class CMatchUI
return menus.getMenus();
}
@Override
public UiCommand getCommandOnSelect() {
return null;
}
@Override
public void register() {
initHandViews();
@@ -554,6 +548,7 @@ public final class CMatchUI
return null;
}
@Override
public void updateButtons(final PlayerView owner, final String label1, final String label2, final boolean enable1, final boolean enable2, final boolean focus1) {
final FButton btn1 = view.getBtnOK(), btn2 = view.getBtnCancel();
btn1.setText(label1);
@@ -574,7 +569,7 @@ public final class CMatchUI
@Override
public void flashIncorrectAction() {
SDisplayUtil.remind(getCPrompt().getView());
getCPrompt().remind();
}
@Override
@@ -591,7 +586,7 @@ public final class CMatchUI
@Override
public void updateTurn(final PlayerView player) {
VField nextField = getFieldViewFor(player);
final VField nextField = getFieldViewFor(player);
SDisplayUtil.showTab(nextField);
cPrompt.updateText();
repaintCardOverlays();
@@ -622,7 +617,7 @@ public final class CMatchUI
FloatingCardArea.closeAll(); //ensure floating card areas cleared and closed after the game
final GameView gameView = getGameView();
if (hasLocalPlayers() || gameView.isMatchOver()) {
new ViewWinLose(gameView, this);
new ViewWinLose(gameView, this).show();
}
if (showOverlay) {
SOverlayUtils.showOverlay();
@@ -759,6 +754,7 @@ public final class CMatchUI
cPrompt.setMessage(message);
}
@Override
public Object showManaPool(final PlayerView player) {
return null; //not needed since mana pool icons are always visible
}
@@ -809,12 +805,6 @@ public final class CMatchUI
Singletons.getControl().setCurrentScreen(screen);
SDisplayUtil.showTab(EDocID.REPORT_LOG.getDoc());
// per player observers were set in CMatchUI.SINGLETON_INSTANCE.initMatch
//Set Field shown to current player.
//if (util.getHumanCount() > 0) {
final VField nextField = getFieldViewFor(gameView.getPlayers().get(0));
SDisplayUtil.showTab(nextField);
//}
SOverlayUtils.hideOverlay();
}
@@ -951,7 +941,7 @@ public final class CMatchUI
final List<VField> fieldViews = getFieldViews();
// Human field is at index [0]
PhaseIndicator fvHuman = fieldViews.get(0).getPhaseIndicator();
final PhaseIndicator fvHuman = fieldViews.get(0).getPhaseIndicator();
fvHuman.getLblUpkeep().setEnabled(prefs.getPrefBoolean(FPref.PHASE_HUMAN_UPKEEP));
fvHuman.getLblDraw().setEnabled(prefs.getPrefBoolean(FPref.PHASE_HUMAN_DRAW));
fvHuman.getLblMain1().setEnabled(prefs.getPrefBoolean(FPref.PHASE_HUMAN_MAIN1));
@@ -967,7 +957,7 @@ public final class CMatchUI
// AI field is at index [1], ...
for (int i = 1; i < fieldViews.size(); i++) {
PhaseIndicator fvAi = fieldViews.get(i).getPhaseIndicator();
final PhaseIndicator fvAi = fieldViews.get(i).getPhaseIndicator();
fvAi.getLblUpkeep().setEnabled(prefs.getPrefBoolean(FPref.PHASE_AI_UPKEEP));
fvAi.getLblDraw().setEnabled(prefs.getPrefBoolean(FPref.PHASE_AI_DRAW));
fvAi.getLblMain1().setEnabled(prefs.getPrefBoolean(FPref.PHASE_AI_MAIN1));
@@ -981,17 +971,15 @@ public final class CMatchUI
fvAi.getLblEndTurn().setEnabled(prefs.getPrefBoolean(FPref.PHASE_AI_EOT));
fvAi.getLblCleanup().setEnabled(prefs.getPrefBoolean(FPref.PHASE_AI_CLEANUP));
}
//Singletons.getView().getViewMatch().setLayoutParams(prefs.getPref(FPref.UI_LAYOUT_PARAMS));
}
@Override
public void message(String message, String title) {
public void message(final String message, final String title) {
SOptionPane.showMessageDialog(message, title);
}
@Override
public void showErrorDialog(String message, String title) {
public void showErrorDialog(final String message, final String title) {
SOptionPane.showErrorDialog(message, title);
}

View File

@@ -1,20 +1,30 @@
package forge.screens.match;
import java.awt.AWTEvent;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JLayer;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.Scrollable;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.LayerUI;
import net.miginfocom.swing.MigLayout;
import forge.gui.MouseUtil;
import forge.toolbox.FScrollPane;
import forge.toolbox.FSkin;
import forge.toolbox.FSkin.SkinFont;
import forge.toolbox.FSkin.SkinnedTextArea;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.LayerUI;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
@SuppressWarnings("serial")
public class GameLogPanel extends JPanel {
@@ -22,7 +32,7 @@ public class GameLogPanel extends JPanel {
private MyScrollablePanel scrollablePanel;
private SkinFont textFont = FSkin.getFont();
private LayerUI<FScrollPane> layerUI = new GameLogPanelLayerUI();
private final LayerUI<FScrollPane> layerUI = new GameLogPanelLayerUI();
private JLayer<FScrollPane> layer;
private boolean isScrollBarVisible = false;
@@ -55,7 +65,7 @@ public class GameLogPanel extends JPanel {
private void setResizeListener() {
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent arg0) {
public void componentResized(final ComponentEvent arg0) {
forceVerticalScrollbarToMax();
}
});
@@ -101,7 +111,7 @@ public class GameLogPanel extends JPanel {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JScrollBar scrollbar = scrollPane.getVerticalScrollBar();
final JScrollBar scrollbar = scrollPane.getVerticalScrollBar();
scrollbar.setValue(scrollbar.getMaximum());
// This is needed to ensure scrollbar is set to max correctly.
scrollPane.validate();
@@ -131,11 +141,11 @@ public class GameLogPanel extends JPanel {
}
public void setTextFont(SkinFont newFont) {
public void setTextFont(final SkinFont newFont) {
this.textFont = newFont;
}
private JTextArea createNewLogEntryJTextArea(String text, boolean useAlternateBackColor) {
private JTextArea createNewLogEntryJTextArea(final String text, final boolean useAlternateBackColor) {
final SkinnedTextArea tar = new SkinnedTextArea(text);
tar.setFont(textFont);
tar.setBorder(new EmptyBorder(3, 4, 3, 4));
@@ -155,23 +165,28 @@ public class GameLogPanel extends JPanel {
protected final class MyScrollablePanel extends JPanel implements Scrollable {
@Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
@Override
public int getScrollableUnitIncrement(final Rectangle visibleRect, final int orientation, final int direction) {
return textFont.getSize();
}
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
@Override
public int getScrollableBlockIncrement(final Rectangle visibleRect, final int orientation, final int direction) {
return textFont.getSize();
}
@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
// we don't want to track the height, because we want to scroll vertically.
@Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
@@ -181,25 +196,25 @@ public class GameLogPanel extends JPanel {
@SuppressWarnings("unchecked")
@Override
public void installUI(JComponent c) {
public void installUI(final JComponent c) {
super.installUI(c);
JLayer<FScrollPane> l = (JLayer<FScrollPane>)c;
final JLayer<FScrollPane> l = (JLayer<FScrollPane>)c;
l.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK);
}
@SuppressWarnings("unchecked")
@Override
public void uninstallUI(JComponent c) {
public void uninstallUI(final JComponent c) {
super.uninstallUI(c);
JLayer<FScrollPane> l = (JLayer<FScrollPane>)c;
final JLayer<FScrollPane> l = (JLayer<FScrollPane>)c;
l.setLayerEventMask(0);
}
@Override
protected void processMouseEvent(MouseEvent e, JLayer<? extends FScrollPane> l) {
protected void processMouseEvent(final MouseEvent e, final JLayer<? extends FScrollPane> l) {
boolean isScrollBarRequired = scrollPane.getVerticalScrollBar().getMaximum() > getHeight();
boolean isHoveringOverLogEntry = e.getSource() instanceof JTextArea;
final boolean isScrollBarRequired = scrollPane.getVerticalScrollBar().getMaximum() > getHeight();
final boolean isHoveringOverLogEntry = e.getSource() instanceof JTextArea;
switch (e.getID()) {
case MouseEvent.MOUSE_ENTERED:

View File

@@ -19,17 +19,12 @@ package forge.screens.match;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import forge.Singletons;
import forge.assets.FSkinProp;
import forge.game.GameView;
import forge.gui.SOverlayUtils;
import forge.gui.framework.FScreen;
import forge.match.NextGameDecision;
import forge.model.FModel;
import forge.quest.QuestController;
import forge.quest.QuestDraftUtils;
import forge.screens.home.quest.CSubmenuChallenges;
import forge.screens.home.quest.CSubmenuDuels;
import forge.screens.home.quest.CSubmenuQuestDraft;
import forge.screens.home.quest.VSubmenuQuestDraft;
import forge.toolbox.FOptionPane;
@@ -46,7 +41,6 @@ import forge.toolbox.FSkin;
*/
public class QuestDraftWinLose extends ControlWinLose {
private final transient ViewWinLose view;
private final transient QuestController qData;
/**
* Instantiates a new quest win lose handler.
@@ -57,7 +51,6 @@ public class QuestDraftWinLose extends ControlWinLose {
public QuestDraftWinLose(final ViewWinLose view0, final GameView game0, final CMatchUI matchUI) {
super(view0, game0, matchUI);
this.view = view0;
qData = FModel.getQuest();
}
/**
@@ -71,7 +64,7 @@ public class QuestDraftWinLose extends ControlWinLose {
*/
@Override
public final boolean populateCustomPanel() {
QuestController quest = FModel.getQuest();
final QuestController quest = FModel.getQuest();
final boolean gameHadHumanPlayer = matchUI.hasLocalPlayers();
if (lastGame.isMatchOver()) {
@@ -125,17 +118,4 @@ public class QuestDraftWinLose extends ControlWinLose {
return false; //We're not awarding anything, so never display the custom panel.
}
public final void actionOnQuitMatch() {
CSubmenuDuels.SINGLETON_INSTANCE.update();
CSubmenuChallenges.SINGLETON_INSTANCE.update();
qData.setCurrentEvent(null);
qData.save();
FModel.getQuestPreferences().save();
matchUI.writeMatchPreferences();
Singletons.getControl().setCurrentScreen(FScreen.HOME_SCREEN);
SOverlayUtils.hideOverlay();
}
}

View File

@@ -41,6 +41,7 @@ import forge.toolbox.FTextArea;
public class ViewWinLose implements IWinLoseView<FButton> {
private final ControlWinLose control;
private final FScrollPane scrLog;
private final FButton btnContinue, btnRestart, btnQuit;
private final SkinnedPanel pnlCustom;
@@ -128,14 +129,14 @@ public class ViewWinLose implements IWinLoseView<FButton> {
txtLog.setFont(FSkin.getFont(14));
txtLog.setFocusable(true); // allow highlighting and copying of log
FLabel btnCopyLog = new FLabel.ButtonBuilder().text("Copy to clipboard").build();
final FLabel btnCopyLog = new FLabel.ButtonBuilder().text("Copy to clipboard").build();
btnCopyLog.setCommand(new UiCommand() {
@Override
public void run() {
StringSelection ss = new StringSelection(txtLog.getText());
final StringSelection ss = new StringSelection(txtLog.getText());
try {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
} catch (IllegalStateException ex) {
} catch (final IllegalStateException ex) {
// ignore; may be unavailable on some platforms
}
}
@@ -172,7 +173,7 @@ public class ViewWinLose implements IWinLoseView<FButton> {
pnlLeft.add(pnlButtons, "w 100%!");
final JPanel pnlLog = new JPanel(new MigLayout("insets 0, wrap, ax center"));
final FScrollPane scrLog = new FScrollPane(txtLog, false);
scrLog = new FScrollPane(txtLog, false);
pnlLog.setOpaque(false);
pnlLog.add(
@@ -184,7 +185,9 @@ public class ViewWinLose implements IWinLoseView<FButton> {
pnlLeft.add(pnlLog, "w 100%!");
lblTitle.setText(composeTitle(game0));
}
public final void show() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
@@ -207,7 +210,7 @@ public class ViewWinLose implements IWinLoseView<FButton> {
return control;
}
private String composeTitle(final GameView game) {
private static String composeTitle(final GameView game) {
final String winner = game.getWinningPlayerName();
final int winningTeam = game.getWinningTeam();
if (winner == null) {
@@ -220,16 +223,19 @@ public class ViewWinLose implements IWinLoseView<FButton> {
}
/** @return {@link forge.toolbox.FButton} */
@Override
public FButton getBtnContinue() {
return this.btnContinue;
}
/** @return {@link forge.toolbox.FButton} */
@Override
public FButton getBtnRestart() {
return this.btnRestart;
}
/** @return {@link forge.toolbox.FButton} */
@Override
public FButton getBtnQuit() {
return this.btnQuit;
}
@@ -251,7 +257,7 @@ public class ViewWinLose implements IWinLoseView<FButton> {
}
}
private String removePlayerTypeFromLogMessage(String message) {
private static String removePlayerTypeFromLogMessage(final String message) {
return message.replaceAll("\\[[^\\]]*\\]", "");
}
@@ -261,12 +267,12 @@ public class ViewWinLose implements IWinLoseView<FButton> {
}
@Override
public void showRewards(Runnable runnable) {
public void showRewards(final Runnable runnable) {
runnable.run(); //just run on GUI thread
}
@Override
public void showCards(String title, List<PaperCard> cards) {
public void showCards(final String title, final List<PaperCard> cards) {
final QuestWinLoseCardViewer cv = new QuestWinLoseCardViewer(cards);
getPnlCustom().add(new TitleLabel(title), CONSTRAINTS_TITLE);
if (FModel.getPreferences().getPrefBoolean(FPref.UI_LARGE_CARD_VIEWERS)) {
@@ -278,13 +284,13 @@ public class ViewWinLose implements IWinLoseView<FButton> {
}
@Override
public void showMessage(String message, String title, FSkinProp icon) {
SkinIcon icoTemp = FSkin.getIcon(icon).scale(0.5);
public void showMessage(String message, final String title, final FSkinProp icon) {
final SkinIcon icoTemp = FSkin.getIcon(icon).scale(0.5);
if (message.contains("\n")) { //ensure new line characters are encoded
message = "<html>" + message.replace("\n", "<br>") + "</html>";
}
SkinnedLabel lblMessage = new SkinnedLabel(message);
final SkinnedLabel lblMessage = new SkinnedLabel(message);
lblMessage.setFont(FSkin.getFont(14));
lblMessage.setForeground(FORE_COLOR);
lblMessage.setHorizontalAlignment(SwingConstants.CENTER);
@@ -297,7 +303,6 @@ public class ViewWinLose implements IWinLoseView<FButton> {
/**
* JLabel header between reward sections.
*
*/
@SuppressWarnings("serial")
private class TitleLabel extends SkinnedLabel {

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