Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Andy Fries 2015-11-29 11:20:45 -08:00
commit 59733e38bf
4720 changed files with 228701 additions and 37406 deletions

7
.gitignore vendored
View file

@ -18,6 +18,7 @@ Mage.Server.Plugins/Mage.Deck.Limited/target
Mage.Server.Plugins/Mage.Game.CommanderDuel/target
Mage.Server.Plugins/Mage.Game.CommanderFreeForAll/target/
Mage.Server.Plugins/Mage.Game.FreeForAll/target
Mage.Server.Plugins/Mage.Game.MomirDuel/target
Mage.Server.Plugins/Mage.Game.TinyLeadersDuel/target
Mage.Server.Plugins/Mage.Game.TwoPlayerDuel/target
Mage.Server.Plugins/Mage.Player.AI.DraftBot/target
@ -50,7 +51,7 @@ Mage.Updater/target
mage.updater.client/target
releases
Utils/author.txt
Utils/author.txt
.DS_Store
.metadata
.project
@ -88,4 +89,6 @@ Mage.Server.Plugins/Mage.Draft.8PlayerBooster/target
/Utils/*_unimplemented.txt
*.netbeans_automatic_build
*.txt
Mage.Client/serverlist.txt
Mage.Client/serverlist.txt
/bin/
/target/

View file

@ -6,7 +6,7 @@
<parent>
<groupId>org.mage</groupId>
<artifactId>mage-root</artifactId>
<version>1.4.3</version>
<version>1.4.5</version>
</parent>
<groupId>org.mage</groupId>

View file

@ -0,0 +1,78 @@
1 [C15:77] Open the Vaults
1 [C15:76] Monk Idealist
1 [C15:75] Mesa Enchantress
1 [C15:74] Marshal's Anthem
1 [C15:73] Kor Sanctifiers
1 [C15:281] Command Tower
1 [C15:72] Karmic Justice
1 [C15:283] Evolving Wilds
1 [C15:70] Ghostblade Eidolon
1 [C15:285] Ghost Quarter
1 [C15:121] Doomwake Giant
1 [C15:122] Dreadbringer Lampads
1 [C15:320] Vivid Meadow
1 [C15:125] Fallen Ideal
11 [C15:323] Plains
1 [C15:126] Fate Unraveler
1 [C15:79] Seal of Cleansing
1 [C15:248] Burnished Hart
1 [C15:127] Gild
1 [C15:128] Grave Peril
1 [C15:129] Nighthowler
1 [C15:80] Sigil of the Empty Throne
1 [C15:84] Vow of Duty
1 [C15:81] Silent Sentinel
1 [C15:274] Wayfarer's Bauble
1 [C15:277] Barren Moor
1 [C15:234] Teysa, Envoy of Ghosts
1 [C15:311] Tainted Field
1 [C15:235] Treasury Thrull
1 [C15:114] Ancient Craving
1 [C15:46] Karlov of the Ghost Council
1 [C15:313] Temple of the False God
1 [C15:237] Underworld Coinsmith
1 [C15:116] Black Market
1 [C15:314] Terramorphic Expanse
1 [C15:319] Vivid Marsh
1 [C15:55] Thought Vessel
1 [C15:52] Sandstone Oracle
1 [C15:261] Orzhov Cluestone
1 [C15:140] Vow of Malice
1 [C15:262] Orzhov Signet
1 [C15:19] Deadly Tempest
1 [C15:18] Daxos's Torment
1 [C15:17] Corpse Augur
1 [C15:16] Banshee of the Dread Choir
1 [C15:268] Sol Ring
1 [C15:301] Reliquary Tower
1 [C15:57] Ajani's Chosen
1 [C15:302] Scoured Barrens
1 [C15:303] Secluded Steppe
1 [C15:229] Necromancer's Covenant
1 [C15:22] Thief of Blood
1 [C15:66] Dawn to Dusk
1 [C15:64] Celestial Archon
1 [C15:63] Celestial Ancient
1 [C15:62] Cage of Hands
1 [C15:61] Banishing Light
1 [C15:250] Crystal Chimes
1 [C15:60] Aura of Silence
1 [C15:130] Phyrexian Arena
1 [C15:295] New Benalia
1 [C15:133] Phyrexian Reclamation
1 [C15:298] Orzhov Basilica
13 [C15:331] Swamp
1 [C15:299] Orzhov Guildgate
1 [C15:135] Seal of Doom
1 [C15:257] Lightning Greaves
1 [C15:8] Shielded by Faith
1 [C15:68] Dictate of Heliod
1 [C15:67] Dawnglare Invoker
1 [C15:138] Underworld Connections
1 [C15:7] Righteous Confluence
1 [C15:215] Death Grasp
1 [C15:6] Oreskos Explorer
1 [C15:4] Herald of the Host
1 [C15:3] Grasp of Fate
1 [C15:1] Bastion Protector
SB: 1 [C15:43] Daxos the Returned

View file

@ -0,0 +1,77 @@
1 [C15:33] Bloodspore Thrinax
1 [C15:281] Command Tower
1 [C15:283] Evolving Wilds
1 [C15:120] Diabolic Servitude
1 [C15:286] Golgari Guildgate
1 [C15:39] Skullwinder
1 [C15:287] Golgari Rot Farm
1 [C15:200] Sakura-Tribe Elder
1 [C15:38] Pathbreaker Ibex
1 [C15:123] Eater of Hope
1 [C15:288] Grim Backwoods
1 [C15:201] Satyr Wayfinder
1 [C15:37] Great Oak Guardian
1 [C15:124] Extractor Demon
1 [C15:245] Bonehoard
1 [C15:289] High Market
1 [C15:202] Spider Spawning
1 [C15:35] Centaur Vinecrasher
1 [C15:34] Caller of the Pack
1 [C15:204] Terastodon
1 [C15:206] Tribute to the Wild
1 [C15:207] Verdant Force
1 [C15:208] Viridian Emissary
1 [C15:191] Mulch
1 [C15:192] Mycoloth
1 [C15:196] Overwhelming Stampede
1 [C15:198] Primal Growth
1 [C15:232] Putrefy
1 [C15:112] Altar's Reap
1 [C15:48] Mazirek, Kraul Death Priest
1 [C15:113] Ambition's Cost
1 [C15:312] Tainted Wood
1 [C15:115] Barter in Blood
1 [C15:314] Terramorphic Expanse
1 [C15:117] Blood Bairn
1 [C15:238] Vulturous Zombie
1 [C15:118] Butcher of Malakir
1 [C15:119] Champion of Stray Souls
1 [C15:318] Vivid Grove
1 [C15:319] Vivid Marsh
1 [C15:55] Thought Vessel
1 [C15:183] Eternal Witness
1 [C15:186] Indrik Stomphowler
1 [C15:187] Kessig Cagebreakers
1 [C15:17] Corpse Augur
1 [C15:221] Golgari Charm
1 [C15:16] Banshee of the Dread Choir
1 [C15:222] Grisly Salvage
1 [C15:223] Jarad, Golgari Lich Lord
1 [C15:267] Skullclamp
1 [C15:300] Polluted Mire
1 [C15:224] Korozda Guildmage
1 [C15:268] Sol Ring
1 [C15:226] Lotleth Troll
1 [C15:307] Slippery Karst
1 [C15:22] Thief of Blood
1 [C15:21] Scourge of Nel Toth
1 [C15:20] Dread Summons
1 [C15:292] Jungle Hollow
1 [C15:173] Acidic Slime
1 [C15:131] Phyrexian Plaguelord
1 [C15:132] Phyrexian Rager
1 [C15:253] Eldrazi Monument
1 [C15:210] Viridian Zealot
13 [C15:331] Swamp
1 [C15:211] Wall of Blossoms
1 [C15:255] Golgari Signet
1 [C15:134] Rise from the Grave
1 [C15:212] Wood Elves
1 [C15:179] Cloudthresher
1 [C15:257] Lightning Greaves
1 [C15:136] Sever the Bloodline
1 [C15:137] Shriekmaw
1 [C15:23] Wretched Confluence
1 [C15:139] Victimize
12 [C15:339] Forest
SB: 1 [C15:49] Meren of Clan Nel Toth

View file

@ -0,0 +1,75 @@
1 [C15:31] Warchief Giant
1 [C15:30] Rite of the Raging Storm
1 [C15:281] Command Tower
1 [C15:162] Magmaquake
1 [C15:283] Evolving Wilds
1 [C15:163] Mizzium Mortars
1 [C15:240] Call the Skybreaker
1 [C15:169] Urza's Rage
14 [C15:327] Island
1 [C15:88] Blue Sun's Zenith
1 [C15:87] Blatant Thievery
1 [C15:42] Arjun, the Shifting Flame
1 [C15:85] AEtherize
1 [C15:151] Dragon Mage
1 [C15:153] Faithless Looting
1 [C15:275] Worn Powerstone
1 [C15:110] Thought Reflection
1 [C15:231] Prophetic Bolt
1 [C15:111] Windfall
1 [C15:233] Steam Augury
1 [C15:310] Swiftwater Cliffs
1 [C15:313] Temple of the False God
1 [C15:89] Blustersquall
1 [C15:314] Terramorphic Expanse
1 [C15:316] Vivid Crag
1 [C15:317] Vivid Creek
1 [C15:90] Brainstorm
1 [C15:11] Gigantoplasm
1 [C15:55] Thought Vessel
1 [C15:10] Broodbirth Viper
1 [C15:54] Seal of the Guildpact
1 [C15:98] Mystic Retrieval
1 [C15:96] Lone Revenant
1 [C15:95] Jace's Archivist
1 [C15:94] Fact or Fiction
1 [C15:93] Echoing Truth
1 [C15:141] Act of Aggression
1 [C15:92] Dominate
1 [C15:263] Psychosis Crawler
1 [C15:220] Goblin Electromancer
1 [C15:144] Chain Reaction
1 [C15:145] Charmbreaker Devils
1 [C15:101] Preordain
1 [C15:146] Comet Storm
1 [C15:268] Sol Ring
1 [C15:103] Reins of Power
1 [C15:14] Mystic Confluence
1 [C15:301] Reliquary Tower
1 [C15:302] Rogue's Passage
1 [C15:13] Mirror Match
1 [C15:104] Repeal
1 [C15:12] Illusory Ambusher
1 [C15:149] Desperate Ravings
1 [C15:105] Rite of Replication
1 [C15:227] Melek, Izzet Paragon
1 [C15:106] Sleep
1 [C15:107] Stolen Goods
1 [C15:108] Stroke of Genius
1 [C15:109] Talrand, Sky Summoner
1 [C15:309] Spinerock Knoll
1 [C15:290] Izzet Boilerworks
1 [C15:170] Vandalblast
1 [C15:291] Izzet Guildgate
1 [C15:172] Word of Seizing
1 [C15:29] Mizzix's Mastery
1 [C15:28] Meteor Blast
1 [C15:256] Izzet Signet
1 [C15:9] AEthersnatch
1 [C15:24] Awaken the Sky Tyrant
1 [C15:214] Counterflux
13 [C15:335] Mountain
1 [C15:216] Epic Experiment
1 [C15:217] Etherium-Horn Sorcerer
1 [C15:218] Firemind's Foresight
SB: 1 [C15:50] Mizzix of the Izmagnus

View file

@ -0,0 +1,77 @@
1 [C15:32] Arachnogenesis
1 [C15:281] Command Tower
1 [C15:283] Evolving Wilds
1 [C15:241] Cold-Eyed Selkie
1 [C15:242] Snakeform
1 [C15:39] Skullwinder
1 [C15:243] Wistful Selkie
1 [C15:200] Sakura-Tribe Elder
1 [C15:37] Great Oak Guardian
1 [C15:289] High Market
1 [C15:322] Zoetic Cavern
1 [C15:36] Ezuri's Predation
1 [C15:203] Stingerfling Spider
1 [C15:34] Caller of the Pack
1 [C15:205] Thelonite Hermit
11 [C15:327] Island
1 [C15:209] Viridian Shaman
1 [C15:190] Loaming Shaman
1 [C15:86] Bident of Thassa
1 [C15:193] Noble Quarry
1 [C15:40] Verdant Confluence
1 [C15:194] Ohran Viper
1 [C15:271] Swiftfoot Boots
1 [C15:272] Sword of Vengeance
1 [C15:195] Overrun
1 [C15:197] Patagia Viper
1 [C15:230] Prime Speaker Zegana
1 [C15:199] Rampant Growth
1 [C15:47] Kaseto, Orochi Archmage
1 [C15:236] Trygon Predator
1 [C15:314] Terramorphic Expanse
1 [C15:315] Thornwood Falls
1 [C15:239] Biomantic Mastery
1 [C15:317] Vivid Creek
1 [C15:318] Vivid Grove
1 [C15:91] Day of the Dragons
1 [C15:99] Ninja of the Deep Hours
1 [C15:55] Thought Vessel
1 [C15:10] Broodbirth Viper
1 [C15:97] Mulldrifter
1 [C15:53] Scytheclaw
1 [C15:180] Cobra Trap
1 [C15:181] Desert Twister
1 [C15:182] Elvish Visionary
1 [C15:183] Eternal Witness
1 [C15:260] Orochi Hatchery
1 [C15:184] Experiment One
1 [C15:185] Forgotten Ancient
1 [C15:100] Plaxmanta
1 [C15:265] Simic Keyrune
1 [C15:188] Kodama's Reach
1 [C15:266] Simic Signet
1 [C15:189] Krosan Grip
1 [C15:102] Rapid Hybridization
1 [C15:15] Synthetic Destiny
1 [C15:268] Sol Ring
1 [C15:301] Reliquary Tower
1 [C15:225] Lorescale Coatl
1 [C15:269] Solemn Simulacrum
1 [C15:13] Mirror Match
1 [C15:12] Illusory Ambusher
1 [C15:56] Command Beacon
1 [C15:228] Mystic Snake
1 [C15:305] Simic Growth Chamber
1 [C15:306] Simic Guildgate
1 [C15:293] Llanowar Reborn
1 [C15:294] Mosswort Bridge
1 [C15:174] Arbor Colossus
1 [C15:175] Bane of Progress
1 [C15:296] Novijen, Heart of Progress
1 [C15:176] Beastmaster Ascension
1 [C15:297] Oran-Rief, the Vastwood
1 [C15:177] Caller of the Claw
1 [C15:178] Chameleon Colossus
1 [C15:213] Coiling Oracle
14 [C15:339] Forest
SB: 1 [C15:44] Ezuri, Claw of Progress

View file

@ -0,0 +1,77 @@
1 [C15:31] Warchief Giant
1 [C15:30] Rite of the Raging Storm
1 [C15:280] Boros Guildgate
1 [C15:160] Inferno Titan
1 [C15:281] Command Tower
1 [C15:161] Magma Giant
1 [C15:282] Drifting Meadow
1 [C15:71] Jareth, Leonine Titan
1 [C15:283] Evolving Wilds
1 [C15:284] Forgotten Cave
1 [C15:164] Stinkdrinker Daredevil
1 [C15:165] Stoneshock Giant
1 [C15:166] Sunrise Sovereign
1 [C15:320] Vivid Meadow
1 [C15:167] Taurean Mauler
1 [C15:244] Basalt Monolith
1 [C15:321] Wind-Scarred Crag
1 [C15:168] Thundercloud Shaman
1 [C15:246] Boros Cluestone
11 [C15:323] Plains
1 [C15:247] Boros Signet
1 [C15:78] Orim's Thunder
1 [C15:249] Coldsteel Heart
1 [C15:41] Anya, Merciless Angel
1 [C15:270] Staff of Nin
1 [C15:83] Victory's Herald
1 [C15:150] Disaster Radius
1 [C15:82] Sun Titan
1 [C15:273] Urza's Incubator
1 [C15:152] Earthquake
1 [C15:275] Worn Powerstone
1 [C15:154] Fall of the Hammer
1 [C15:155] Fumiko the Lowblood
1 [C15:276] Ancient Amphitheater
1 [C15:156] Hamletback Goliath
1 [C15:157] Hammerfist Giant
1 [C15:278] Blasted Landscape
1 [C15:158] Hostility
1 [C15:279] Boros Garrison
1 [C15:159] Hunted Dragon
1 [C15:314] Terramorphic Expanse
1 [C15:316] Vivid Crag
1 [C15:55] Thought Vessel
1 [C15:52] Sandstone Oracle
1 [C15:51] Blade of Selves
1 [C15:142] Borderland Behemoth
1 [C15:264] Seer's Sundial
1 [C15:143] Breath of Darigaaz
1 [C15:59] Arbiter of Knollridge
1 [C15:58] Angel of Serenity
1 [C15:268] Sol Ring
1 [C15:147] Curse of the Nightly Hunt
1 [C15:148] Desolation Giant
1 [C15:303] Secluded Steppe
1 [C15:308] Smoldering Crater
1 [C15:65] Crib Swap
1 [C15:171] Warstorm Surge
1 [C15:61] Banishing Light
1 [C15:251] Darksteel Ingot
1 [C15:252] Dreamstone Hedron
1 [C15:254] Fellwar Stone
1 [C15:28] Meteor Blast
1 [C15:27] Magus of the Wheel
1 [C15:26] Fiery Confluence
1 [C15:25] Dream Pillager
1 [C15:257] Lightning Greaves
1 [C15:69] Faith's Fetters
1 [C15:258] Loxodon Warhammer
14 [C15:335] Mountain
1 [C15:67] Dawnglare Invoker
1 [C15:259] Mind Stone
1 [C15:6] Oreskos Explorer
1 [C15:5] Kalemne's Captain
1 [C15:4] Herald of the Host
1 [C15:219] Gisela, Blade of Goldnight
1 [C15:2] Dawnbreak Reclaimer
SB: 1 [C15:45] Kalemne, Disciple of Iroas

View file

@ -0,0 +1,23 @@
NAME:Mormir Basic
3 [BFZ:259] Island
3 [BFZ:261] Swamp
3 [BFZ:250] Plains
3 [BFZ:272] Forest
3 [BFZ:260] Swamp
3 [BFZ:271] Forest
3 [BFZ:270] Forest
3 [BFZ:265] Mountain
2 [BFZ:254] Plains
3 [BFZ:264] Swamp
3 [BFZ:274] Forest
1 [BFZ:252] Plains
3 [BFZ:262] Swamp
3 [BFZ:251] Plains
2 [BFZ:273] Forest
3 [BFZ:258] Island
2 [BFZ:269] Mountain
3 [BFZ:268] Mountain
3 [BFZ:257] Island
3 [BFZ:267] Mountain
3 [BFZ:266] Mountain
2 [BFZ:255] Island

View file

@ -1,7 +1,6 @@
XMage.de 1 (Europe/Germany) fast :xmage.de:17171
woogerworks (North America/USA) :xmage.woogerworks.info:17171
XMage.info 1 (Europe/France) slow :176.31.186.181:17171
XMage.info 2 (Europe/France) slow :176.31.186.181:17000
IceMage (Europe/Netherlands) :ring0.cc:17171
XMage.info 1 (Europe/France) new network code -> see forum :176.31.186.181:17171
XMage BR (South America/Brazil) :ec2-54-233-67-0.sa-east-1.compute.amazonaws.com:17171
Seedds Server (Asia) :115.29.203.80:17171
localhost -> connect to your local server (must be started):localhost:17171

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -83,7 +83,7 @@ import mage.cards.repository.CardCriteria;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.client.cards.BigCard;
import mage.client.chat.ChatPanel;
import mage.client.chat.ChatPanelBasic;
import mage.client.components.MageComponents;
import mage.client.components.MageDesktopManager;
import mage.client.components.MageJDesktop;
@ -165,7 +165,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
private static boolean grayMode = false;
private static boolean fullscreenMode = false;
private static final Map<UUID, ChatPanel> chats = new HashMap<>();
private static final Map<UUID, ChatPanelBasic> chats = new HashMap<>();
private static final Map<UUID, GamePanel> games = new HashMap<>();
private static final Map<UUID, DraftPanel> drafts = new HashMap<>();
private static final MageUI ui = new MageUI();
@ -358,6 +358,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
} else {
connectDialog.showDialog();
}
setWindowTitle();
}
});
@ -369,10 +370,10 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
}
}
public void setWindowTitle() {
private void setWindowTitle() {
setTitle(TITLE_NAME + " Client: "
+ version == null ? "<not available>" : version.toString() + " Server: "
+ ((session != null && session.isConnected()) ? session.getVersionInfo() : "<not connected>"));
+ (version == null ? "<not available>" : version.toString()) + " Server: "
+ ((session != null && session.isConnected()) ? session.getVersionInfo() : "<not connected>"));
}
private void addTooltipContainer() {
@ -959,12 +960,12 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
if (JOptionPane.showConfirmDialog(this, "Are you sure you want to disconnect?", "Confirm disconnect", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
session.disconnect(false);
tablesPane.clearChat();
setWindowTitle();
showMessage("You have disconnected");
}
} else {
connectDialog.showDialog();
}
setWindowTitle();
}//GEN-LAST:event_btnConnectActionPerformed
public void btnAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAboutActionPerformed
@ -1249,11 +1250,11 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
return ui;
}
public static ChatPanel getChat(UUID chatId) {
public static ChatPanelBasic getChat(UUID chatId) {
return chats.get(chatId);
}
public static void addChat(UUID chatId, ChatPanel chatPanel) {
public static void addChat(UUID chatId, ChatPanelBasic chatPanel) {
chats.put(chatId, chatPanel);
}

View file

@ -161,6 +161,7 @@ public class BigCard extends JComponent {
}
public void addJXPanel(UUID cardId, JXPanel jxPanel) {
this.cardId = cardId;
bigImage = null;
synchronized (this) {
if (this.panel != null) { remove(this.panel); }

View file

@ -1,45 +1,84 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
/*
* Card.java
*
* Created on 17-Dec-2009, 9:20:50 PM
*/
package mage.client.cards;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import mage.cards.CardDimensions;
import mage.cards.MagePermanent;
import mage.cards.Sets;
import mage.cards.TextPopup;
import mage.cards.action.ActionCallback;
import mage.client.MageFrame;
import static mage.client.constants.Constants.CONTENT_MAX_XOFFSET;
import static mage.client.constants.Constants.FRAME_MAX_HEIGHT;
import static mage.client.constants.Constants.FRAME_MAX_WIDTH;
import static mage.client.constants.Constants.NAME_FONT_MAX_SIZE;
import static mage.client.constants.Constants.NAME_MAX_YOFFSET;
import static mage.client.constants.Constants.POWBOX_TEXT_MAX_LEFT;
import static mage.client.constants.Constants.POWBOX_TEXT_MAX_TOP;
import static mage.client.constants.Constants.SYMBOL_MAX_XOFFSET;
import static mage.client.constants.Constants.SYMBOL_MAX_YOFFSET;
import static mage.client.constants.Constants.TYPE_MAX_YOFFSET;
import mage.client.game.PlayAreaPanel;
import mage.client.util.Config;
import mage.client.util.DefaultActionCallback;
@ -48,18 +87,11 @@ import mage.client.util.gui.ArrowBuilder;
import mage.constants.CardType;
import mage.constants.EnlargeMode;
import mage.remote.Session;
import mage.view.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static mage.client.constants.Constants.*;
import mage.view.AbilityView;
import mage.view.CardView;
import mage.view.CounterView;
import mage.view.PermanentView;
import mage.view.StackAbilityView;
/**
*
@ -77,15 +109,18 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
protected final UUID gameId;
protected final BigCard bigCard;
protected CardView card;
protected Popup popup;
protected boolean popupShowing;
protected Popup tooltipPopup;
protected boolean tooltipShowing;
protected TextPopup popupText = new TextPopup();
protected TextPopup tooltipText = new TextPopup();
protected BufferedImage background;
protected BufferedImage image = new BufferedImage(FRAME_MAX_WIDTH, FRAME_MAX_HEIGHT, BufferedImage.TYPE_INT_RGB);
protected BufferedImage small;
protected String backgroundName;
// if this is set, it's opened if the user right clicks on the card panel
private JPopupMenu popupMenu;
/**
* Creates new form Card
*
@ -126,7 +161,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
@Override
public void update(PermanentView permanent) {
this.update((CardView)permanent);
this.update((CardView) permanent);
}
@Override
@ -141,7 +176,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
background = ImageHelper.getBackground(card, backgroundName);
}
popupText.setText(getText(cardType));
tooltipText.setText(getText(cardType));
gImage.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gImage.setColor(Color.BLACK);
@ -159,8 +194,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
gImage.drawString(card.getName(), CONTENT_MAX_XOFFSET, NAME_MAX_YOFFSET);
if (card.getCardTypes().contains(CardType.CREATURE)) {
gImage.drawString(card.getPower() + "/" + card.getToughness(), POWBOX_TEXT_MAX_LEFT, POWBOX_TEXT_MAX_TOP);
}
else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
} else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
gImage.drawString(card.getLoyalty(), POWBOX_TEXT_MAX_LEFT, POWBOX_TEXT_MAX_TOP);
}
@ -174,8 +208,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
gSmall.drawString(card.getName(), Config.dimensions.contentXOffset, Config.dimensions.nameYOffset);
if (card.getCardTypes().contains(CardType.CREATURE)) {
gSmall.drawString(card.getPower() + "/" + card.getToughness(), Config.dimensions.powBoxTextLeft, Config.dimensions.powBoxTextTop);
}
else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
} else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
gSmall.drawString(card.getLoyalty(), Config.dimensions.powBoxTextLeft, Config.dimensions.powBoxTextTop);
}
@ -194,11 +227,10 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
protected String getText(String cardType) {
StringBuilder sb = new StringBuilder();
if (card instanceof StackAbilityView || card instanceof AbilityView) {
for (String rule: getRules()) {
for (String rule : getRules()) {
sb.append("\n").append(rule);
}
}
else {
} else {
sb.append(card.getName());
if (card.getManaCost().size() > 0) {
sb.append("\n").append(card.getManaCost());
@ -209,11 +241,10 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
}
if (card.getCardTypes().contains(CardType.CREATURE)) {
sb.append("\n").append(card.getPower()).append("/").append(card.getToughness());
}
else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
} else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
sb.append("\n").append(card.getLoyalty());
}
for (String rule: getRules()) {
for (String rule : getRules()) {
sb.append("\n").append(rule);
}
if (card.getExpansionSetCode() != null && card.getExpansionSetCode().length() > 0) {
@ -233,8 +264,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
StringBuilder sb = new StringBuilder();
if (card.getCardTypes().contains(CardType.LAND)) {
sb.append("land").append(card.getSuperTypes()).append(card.getSubTypes());
}
else if (card.getCardTypes() != null && (card.getCardTypes().contains(CardType.CREATURE) || card.getCardTypes().contains(CardType.PLANESWALKER))) {
} else if (card.getCardTypes() != null && (card.getCardTypes().contains(CardType.CREATURE) || card.getCardTypes().contains(CardType.PLANESWALKER))) {
sb.append("creature");
}
sb.append(card.getColor()).append(card.getRarity()).append(card.getExpansionSetCode());
@ -246,10 +276,11 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
StyledDocument doc = text.getStyledDocument();
try {
for (String rule: getRules()) {
for (String rule : getRules()) {
doc.insertString(doc.getLength(), rule + "\n", doc.getStyle("small"));
}
} catch (BadLocationException e) {}
} catch (BadLocationException e) {
}
text.setCaretPosition(0);
}
@ -257,12 +288,11 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
protected List<String> getRules() {
if (card.getCounters() != null) {
List<String> rules = new ArrayList<>(card.getRules());
for (CounterView counter: card.getCounters()) {
for (CounterView counter : card.getCounters()) {
rules.add(counter.getCount() + " x " + counter.getName());
}
return rules;
}
else {
} else {
return card.getRules();
}
}
@ -270,17 +300,17 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
protected String getType(CardView card) {
StringBuilder sbType = new StringBuilder();
for (String superType: card.getSuperTypes()) {
for (String superType : card.getSuperTypes()) {
sbType.append(superType).append(" ");
}
for (CardType cardType: card.getCardTypes()) {
for (CardType cardType : card.getCardTypes()) {
sbType.append(cardType.toString()).append(" ");
}
if (card.getSubTypes().size() > 0) {
sbType.append("- ");
for (String subType: card.getSubTypes()) {
for (String subType : card.getSubTypes()) {
sbType.append(subType).append(" ");
}
}
@ -288,10 +318,10 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
return sbType.toString();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -343,7 +373,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
@Override
public void mouseMoved(MouseEvent arg0) {
this.bigCard.showTextComponent();
this.bigCard.setCard(card.getId(), EnlargeMode.NORMAL, image, getRules());
this.bigCard.setCard(card.getId(), EnlargeMode.NORMAL, image, getRules());
}
@Override
@ -362,18 +392,18 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
@Override
public void mouseEntered(MouseEvent arg0) {
if (!popupShowing) {
if (popup != null) {
popup.hide();
if (!tooltipShowing) {
if (tooltipPopup != null) {
tooltipPopup.hide();
}
PopupFactory factory = PopupFactory.getSharedInstance();
popup = factory.getPopup(this, popupText, (int) this.getLocationOnScreen().getX() + Config.dimensions.frameWidth, (int) this.getLocationOnScreen().getY() + 40);
popup.show();
//hack to get popup to resize to fit text
popup.hide();
popup = factory.getPopup(this, popupText, (int) this.getLocationOnScreen().getX() + Config.dimensions.frameWidth, (int) this.getLocationOnScreen().getY() + 40);
popup.show();
popupShowing = true;
tooltipPopup = factory.getPopup(this, tooltipText, (int) this.getLocationOnScreen().getX() + Config.dimensions.frameWidth, (int) this.getLocationOnScreen().getY() + 40);
tooltipPopup.show();
//hack to get tooltipPopup to resize to fit text
tooltipPopup.hide();
tooltipPopup = factory.getPopup(this, tooltipText, (int) this.getLocationOnScreen().getX() + Config.dimensions.frameWidth, (int) this.getLocationOnScreen().getY() + 40);
tooltipPopup.show();
tooltipShowing = true;
// Draw Arrows for targets
List<UUID> targets = card.getTargets();
@ -383,14 +413,14 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
if (playAreaPanel != null) {
Point target = playAreaPanel.getLocationOnScreen();
Point me = this.getLocationOnScreen();
ArrowBuilder.getBuilder().addArrow(gameId, (int)me.getX() + 35, (int)me.getY(), (int)target.getX() + 40, (int)target.getY() - 40, Color.red, ArrowBuilder.Type.TARGET);
ArrowBuilder.getBuilder().addArrow(gameId, (int) me.getX() + 35, (int) me.getY(), (int) target.getX() + 40, (int) target.getY() - 40, Color.red, ArrowBuilder.Type.TARGET);
} else {
for (PlayAreaPanel pa : MageFrame.getGame(gameId).getPlayers().values()) {
MagePermanent permanent = pa.getBattlefieldPanel().getPermanents().get(uuid);
if (permanent != null) {
Point target = permanent.getLocationOnScreen();
Point me = this.getLocationOnScreen();
ArrowBuilder.getBuilder().addArrow(gameId, (int)me.getX() + 35, (int)me.getY(), (int)target.getX() + 40, (int)target.getY() + 10, Color.red, ArrowBuilder.Type.TARGET);
ArrowBuilder.getBuilder().addArrow(gameId, (int) me.getX() + 35, (int) me.getY(), (int) target.getX() + 40, (int) target.getY() + 10, Color.red, ArrowBuilder.Type.TARGET);
}
}
}
@ -401,12 +431,12 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
@Override
public void mouseExited(MouseEvent arg0) {
if(getMousePosition(true) != null) {
if (getMousePosition(true) != null) {
return;
}
if (popup != null) {
popup.hide();
popupShowing = false;
if (tooltipPopup != null) {
tooltipPopup.hide();
tooltipShowing = false;
ArrowBuilder.getBuilder().removeArrowsByType(gameId, ArrowBuilder.Type.TARGET);
ArrowBuilder.getBuilder().removeArrowsByType(gameId, ArrowBuilder.Type.PAIRED);
ArrowBuilder.getBuilder().removeArrowsByType(gameId, ArrowBuilder.Type.SOURCE);
@ -421,8 +451,8 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
@Override
public void focusLost(FocusEvent arg0) {
if (popup != null) {
popup.hide();
if (tooltipPopup != null) {
tooltipPopup.hide();
}
this.repaint();
}
@ -437,42 +467,54 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
// End of variables declaration//GEN-END:variables
@Override
public void componentResized(ComponentEvent e) { }
public void componentResized(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) { }
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) { }
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
if (popup != null) {
popup.hide();
if (tooltipPopup != null) {
tooltipPopup.hide();
}
}
@Override
public List<MagePermanent> getLinks() {return null;}
public List<MagePermanent> getLinks() {
return null;
}
@Override
public boolean isTapped() {return false;}
public boolean isTapped() {
return false;
}
@Override
public boolean isFlipped() {return false;}
public boolean isFlipped() {
return false;
}
@Override
public void onBeginAnimation() {}
public void onBeginAnimation() {
}
@Override
public void onEndAnimation() {}
public void onEndAnimation() {
}
@Override
public void setAlpha(float transparency) {}
public void setAlpha(float transparency) {
}
@Override
public CardView getOriginal() {
return card;
return card;
}
@Override
@ -539,6 +581,14 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
public void setTextOffset(int yOffset) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public JPopupMenu getPopupMenu() {
return popupMenu;
}
@Override
public void setPopupMenu(JPopupMenu popupMenu) {
this.popupMenu = popupMenu;
}
}

View file

@ -1,56 +1,64 @@
/*
* Copyright 2012 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2012 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.cards;
import mage.cards.CardDimensions;
import mage.cards.MageCard;
import mage.client.plugins.impl.Plugins;
import mage.client.util.CardsViewUtil;
import mage.client.util.Config;
import mage.view.AbilityView;
import mage.view.CardView;
import mage.view.CardsView;
import mage.view.SimpleCardsView;
import org.mage.card.arcane.CardPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;
import java.util.UUID;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import mage.cards.CardDimensions;
import mage.cards.MageCard;
import mage.client.plugins.impl.Plugins;
import mage.client.util.Config;
import mage.client.util.Event;
import mage.client.util.Listener;
import mage.view.AbilityView;
import mage.view.CardView;
import mage.view.CardsView;
import mage.view.SimpleCardView;
import org.mage.card.arcane.CardPanel;
public class CardArea extends JPanel {
public class CardArea extends JPanel implements MouseListener {
protected CardEventSource cardEventSource = new CardEventSource();
private boolean reloaded = false;
private final javax.swing.JLayeredPane cardArea;
private final javax.swing.JScrollPane scrollPane;
private int yTextOffset;
private int yTextOffset;
/**
* Create the panel.
@ -68,28 +76,23 @@ public class CardArea extends JPanel {
}
public void cleanUp() {
for(Component comp: cardArea.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel) comp).cleanUp();
cardArea.remove(comp);
}
}
}
public void loadCards(SimpleCardsView showCards, BigCard bigCard, CardDimensions dimension, UUID gameId, MouseListener listener) {
loadCards(CardsViewUtil.convertSimple(showCards), bigCard, dimension, gameId, listener);
for (Component comp : cardArea.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel) comp).cleanUp();
cardArea.remove(comp);
}
}
}
public void loadCards(CardsView showCards, BigCard bigCard, CardDimensions dimension, UUID gameId, MouseListener listener) {
public void loadCards(CardsView showCards, BigCard bigCard, CardDimensions dimension, UUID gameId) {
this.reloaded = true;
cardArea.removeAll();
if (showCards != null && showCards.size() < 10) {
yTextOffset = 10;
loadCardsFew(showCards, bigCard, gameId, listener);
}
else {
loadCardsFew(showCards, bigCard, gameId);
} else {
yTextOffset = 0;
loadCardsMany(showCards, bigCard, gameId, listener, dimension);
loadCardsMany(showCards, bigCard, gameId, dimension);
}
cardArea.revalidate();
@ -97,28 +100,28 @@ public class CardArea extends JPanel {
this.repaint();
}
public void loadCardsNarrow(CardsView showCards, BigCard bigCard, CardDimensions dimension, UUID gameId, MouseListener listener) {
public void loadCardsNarrow(CardsView showCards, BigCard bigCard, CardDimensions dimension, UUID gameId) {
this.reloaded = true;
cardArea.removeAll();
yTextOffset = 0;
loadCardsMany(showCards, bigCard, gameId, listener, dimension);
yTextOffset = 0;
loadCardsMany(showCards, bigCard, gameId, dimension);
cardArea.revalidate();
this.revalidate();
this.repaint();
}
private void loadCardsFew(CardsView showCards, BigCard bigCard, UUID gameId, MouseListener listener) {
private void loadCardsFew(CardsView showCards, BigCard bigCard, UUID gameId) {
Rectangle rectangle = new Rectangle(Config.dimensions.frameWidth, Config.dimensions.frameHeight);
Dimension dimension = new Dimension(Config.dimensions.frameWidth, Config.dimensions.frameHeight);
for (CardView card : showCards.values()) {
addCard(card, bigCard, gameId, rectangle, dimension, Config.dimensions, listener);
addCard(card, bigCard, gameId, rectangle, dimension, Config.dimensions);
rectangle.translate(Config.dimensions.frameWidth, 0);
}
cardArea.setPreferredSize(new Dimension(Config.dimensions.frameWidth * showCards.size(), Config.dimensions.frameHeight));
}
private void addCard(CardView card, BigCard bigCard, UUID gameId, Rectangle rectangle, Dimension dimension, CardDimensions cardDimensions, MouseListener listener) {
private void addCard(CardView card, BigCard bigCard, UUID gameId, Rectangle rectangle, Dimension dimension, CardDimensions cardDimensions) {
if (card instanceof AbilityView) {
CardView tmp = ((AbilityView) card).getSourceCard();
tmp.overrideRules(card.getRules());
@ -127,28 +130,26 @@ public class CardArea extends JPanel {
tmp.setAbility(card); // cross-reference, required for ability picker
card = tmp;
}
MageCard cardImg = Plugins.getInstance().getMageCard(card, bigCard, dimension, gameId, true);
MageCard cardPanel = Plugins.getInstance().getMageCard(card, bigCard, dimension, gameId, true);
cardImg.setBounds(rectangle);
if (listener != null) {
cardImg.addMouseListener(listener);
}
cardArea.add(cardImg);
cardArea.moveToFront(cardImg);
cardImg.update(card);
cardImg.setCardBounds(rectangle.x, rectangle.y, cardDimensions.frameWidth, cardDimensions.frameHeight);
cardImg.setTextOffset(yTextOffset);
cardImg.showCardTitle();
cardPanel.setBounds(rectangle);
cardPanel.addMouseListener(this);
cardArea.add(cardPanel);
cardArea.moveToFront(cardPanel);
cardPanel.update(card);
cardPanel.setCardBounds(rectangle.x, rectangle.y, cardDimensions.frameWidth, cardDimensions.frameHeight);
cardPanel.setTextOffset(yTextOffset);
cardPanel.showCardTitle();
}
private void loadCardsMany(CardsView showCards, BigCard bigCard, UUID gameId, MouseListener listener, CardDimensions cardDimensions) {
private void loadCardsMany(CardsView showCards, BigCard bigCard, UUID gameId, CardDimensions cardDimensions) {
int columns = 1;
if (showCards != null && showCards.size() > 0) {
Rectangle rectangle = new Rectangle(cardDimensions.frameWidth, cardDimensions.frameHeight);
Dimension dimension = new Dimension(cardDimensions.frameWidth, cardDimensions.frameHeight);
int count = 0;
for (CardView card : showCards.values()) {
addCard(card, bigCard, gameId, rectangle, dimension, cardDimensions, listener);
addCard(card, bigCard, gameId, rectangle, dimension, cardDimensions);
if (count >= 20) {
rectangle.translate(cardDimensions.frameWidth, -400);
columns++;
@ -169,11 +170,11 @@ public class CardArea extends JPanel {
public void clearReloaded() {
this.reloaded = false;
}
public void selectCards(List<UUID> selected) {
for (Component component : cardArea.getComponents()) {
if (component instanceof MageCard) {
MageCard mageCard = (MageCard)component;
MageCard mageCard = (MageCard) component;
if (selected.contains(mageCard.getOriginal().getId())) {
mageCard.setSelected(true);
}
@ -184,7 +185,7 @@ public class CardArea extends JPanel {
public void markCards(List<UUID> marked) {
for (Component component : cardArea.getComponents()) {
if (component instanceof MageCard) {
MageCard mageCard = (MageCard)component;
MageCard mageCard = (MageCard) component;
if (marked.contains(mageCard.getOriginal().getId())) {
mageCard.setChoosable(true);
}
@ -192,4 +193,82 @@ public class CardArea extends JPanel {
}
}
public void setPopupMenu(JPopupMenu popupMenu) {
for (Component component : cardArea.getComponents()) {
if (component instanceof MageCard) {
MageCard mageCard = (MageCard) component;
mageCard.setPopupMenu(popupMenu);
}
}
}
public void addCardEventListener(Listener<Event> listener) {
cardEventSource.addListener(listener);
}
public void clearCardEventListeners() {
cardEventSource.clearListeners();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
if (e.getClickCount() >= 1 && !e.isConsumed()) {
Object obj = e.getSource();
if (e.getClickCount() == 2) {
e.consume();
if (obj instanceof Card) {
if (e.isAltDown()) {
cardEventSource.altDoubleClick(((Card) obj).getOriginal(), "alt-double-click");
} else {
cardEventSource.doubleClick(((Card) obj).getOriginal(), "double-click");
}
} else if (obj instanceof MageCard) {
if (e.isAltDown()) {
cardEventSource.altDoubleClick(((MageCard) obj).getOriginal(), "alt-double-click");
} else {
cardEventSource.doubleClick(((MageCard) obj).getOriginal(), "double-click");
}
}
}
if (obj instanceof MageCard) {
checkMenu(e, ((MageCard) obj).getOriginal());
} else {
checkMenu(e, null);
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (!e.isConsumed()) {
Object obj = e.getSource();
if (obj instanceof MageCard) {
checkMenu(e, ((MageCard) obj).getOriginal());
} else {
checkMenu(e, null);
}
} else {
cardEventSource.actionConsumedEvent("action-consumed");
}
}
private void checkMenu(MouseEvent Me, SimpleCardView card) {
if (Me.isPopupTrigger()) {
Me.consume();
cardEventSource.showPopupMenuEvent(card, Me.getComponent(), Me.getX(), Me.getY(), "show-popup-menu");
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}

View file

@ -1,49 +1,48 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.cards;
import java.awt.Component;
import java.io.Serializable;
import mage.client.util.Event;
import mage.client.util.EventDispatcher;
import mage.client.util.EventSource;
import mage.client.util.Listener;
import mage.view.SimpleCardView;
import java.io.Serializable;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class CardEventSource implements EventSource<Event>, Serializable {
protected final EventDispatcher<Event> dispatcher = new EventDispatcher<Event>() {};
protected final EventDispatcher<Event> dispatcher = new EventDispatcher<Event>() {
};
@Override
public void addListener(Listener<Event> listener) {
@ -74,6 +73,9 @@ public class CardEventSource implements EventSource<Event>, Serializable {
dispatcher.fireEvent(new Event(card, message, x, y, component));
}
public void actionConsumedEvent(String message) {
dispatcher.fireEvent(new Event(null, message));
}
@Override
public void clearListeners() {

View file

@ -1,16 +1,16 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
@ -20,7 +20,7 @@
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
@ -31,7 +31,6 @@
*
* Created on 30-Mar-2010, 9:25:40 PM
*/
package mage.client.cards;
import java.awt.Component;
@ -54,6 +53,7 @@ import mage.client.plugins.impl.Plugins;
import mage.client.util.Config;
import mage.client.util.Event;
import mage.client.util.Listener;
import mage.utils.CardUtil;
import mage.view.CardView;
import mage.view.CardsView;
import org.mage.card.arcane.CardPanel;
@ -82,7 +82,7 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
}
public void clear() {
for(MouseListener ml: this.getMouseListeners()) {
for (MouseListener ml : this.getMouseListeners()) {
this.removeMouseListener(ml);
}
this.clearCardEventListeners();
@ -101,7 +101,7 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
this.bigCard = bigCard;
this.gameId = gameId;
if (merge) {
for (CardView card: showCards.values()) {
for (CardView card : showCards.values()) {
if (!cards.containsKey(card.getId())) {
addCard(card, bigCard, gameId, drawImage);
}
@ -115,7 +115,7 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
}
} else {
this.clearCards();
for (CardView card: showCards.values()) {
for (CardView card : showCards.values()) {
addCard(card, bigCard, gameId, drawImage);
}
}
@ -144,7 +144,7 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
int curRow = 0;
if (cards.size() > 0) {
Rectangle rectangle = new Rectangle(Config.dimensions.frameWidth, Config.dimensions.frameHeight);
List<MageCard> sortedCards = new ArrayList<MageCard>(cards.values());
List<MageCard> sortedCards = new ArrayList<>(cards.values());
switch (sortSetting.getSortBy()) {
case NAME:
Collections.sort(sortedCards, new CardNameComparator());
@ -155,15 +155,16 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
case COLOR:
Collections.sort(sortedCards, new CardColorComparator());
break;
case COLOR_DETAILED:
Collections.sort(sortedCards, new CardColorDetailedComparator());
case COLOR_IDENTITY:
Collections.sort(sortedCards, new CardColorDetailedIdentity());
break;
case CASTING_COST:
Collections.sort(sortedCards, new CardCostComparator());
break;
}
MageCard lastCard = null;
for (MageCard cardImg: sortedCards) {
for (MageCard cardImg : sortedCards) {
if (sortSetting.isPilesToggle()) {
if (lastCard == null) {
lastCard = cardImg;
@ -187,8 +188,9 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
curRow = 0;
}
break;
case COLOR_DETAILED:
if (cardImg.getOriginal().getColor().hashCode() != lastCard.getOriginal().getColor().hashCode()) {
case COLOR_IDENTITY:
if (CardUtil.getColorIdentitySortValue(cardImg.getOriginal().getManaCost(), cardImg.getOriginal().getColor(), cardImg.getOriginal().getRules())
!= CardUtil.getColorIdentitySortValue(lastCard.getOriginal().getManaCost(), lastCard.getOriginal().getColor(), lastCard.getOriginal().getRules())) {
curColumn++;
curRow = 0;
}
@ -206,8 +208,7 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
moveToFront(cardImg);
curRow++;
lastCard = cardImg;
}
else {
} else {
rectangle.setLocation(curColumn * Config.dimensions.frameWidth, curRow * 20);
cardImg.setBounds(rectangle);
cardImg.setCardBounds(rectangle.x, rectangle.y, Config.dimensions.frameWidth, Config.dimensions.frameHeight);
@ -221,15 +222,15 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
}
}
resizeArea();
revalidate();
repaint();
revalidate();
repaint();
}
private void clearCards() {
// remove possible mouse listeners, preventing gc
for (MageCard mageCard: cards.values()) {
for (MageCard mageCard : cards.values()) {
if (mageCard instanceof CardPanel) {
((CardPanel)mageCard).cleanUp();
((CardPanel) mageCard).cleanUp();
}
}
this.cards.clear();
@ -237,7 +238,7 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
}
private void removeAllCardImg() {
for (Component comp: getComponents()) {
for (Component comp : getComponents()) {
if (comp instanceof Card || comp instanceof MageCard) {
remove(comp);
}
@ -245,14 +246,14 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
}
private void removeCardImg(UUID cardId) {
for (Component comp: getComponents()) {
for (Component comp : getComponents()) {
if (comp instanceof Card) {
if (((Card)comp).getCardId().equals(cardId)) {
if (((Card) comp).getCardId().equals(cardId)) {
remove(comp);
comp = null;
}
} else if (comp instanceof MageCard) {
if (((MageCard)comp).getOriginal().getId().equals(cardId)) {
if (((MageCard) comp).getOriginal().getId().equals(cardId)) {
remove(comp);
comp = null;
}
@ -275,10 +276,10 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
cardEventSource.clearListeners();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -296,10 +297,8 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && !e.isConsumed()) {
@ -322,22 +321,26 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
}
@Override
public void mousePressed(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {}
public void mouseExited(MouseEvent e) {
}
private void resizeArea() {
Dimension area = new Dimension(0, 0);
Dimension size = getPreferredSize();
for (Component comp: getComponents()) {
for (Component comp : getComponents()) {
Rectangle r = comp.getBounds();
if (r.x + r.width > area.width) {
area.width = r.x + r.width;
@ -348,13 +351,13 @@ public class CardGrid extends javax.swing.JLayeredPane implements MouseListener,
}
if (size.height != area.height || size.width != area.width) {
setPreferredSize(area);
}
}
}
@Override
public void refresh() {
revalidate();
repaint();
repaint();
}
@Override
@ -379,8 +382,7 @@ class CardRarityComparator implements Comparator<MageCard> {
int val = o1.getOriginal().getRarity().compareTo(o2.getOriginal().getRarity());
if (val == 0) {
return o1.getOriginal().getName().compareTo(o2.getOriginal().getName());
}
else {
} else {
return val;
}
}
@ -394,8 +396,7 @@ class CardCostComparator implements Comparator<MageCard> {
int val = Integer.valueOf(o1.getOriginal().getConvertedManaCost()).compareTo(Integer.valueOf(o2.getOriginal().getConvertedManaCost()));
if (val == 0) {
return o1.getOriginal().getName().compareTo(o2.getOriginal().getName());
}
else {
} else {
return val;
}
}
@ -409,23 +410,22 @@ class CardColorComparator implements Comparator<MageCard> {
int val = o1.getOriginal().getColor().compareTo(o2.getOriginal().getColor());
if (val == 0) {
return o1.getOriginal().getName().compareTo(o2.getOriginal().getName());
}
else {
} else {
return val;
}
}
}
class CardColorDetailedComparator implements Comparator<MageCard> {
class CardColorDetailedIdentity implements Comparator<MageCard> {
@Override
public int compare(MageCard o1, MageCard o2) {
int val = o1.getOriginal().getColor().hashCode() - o2.getOriginal().getColor().hashCode();
int val = CardUtil.getColorIdentitySortValue(o1.getOriginal().getManaCost(), o1.getOriginal().getColor(), o1.getOriginal().getRules())
- CardUtil.getColorIdentitySortValue(o2.getOriginal().getManaCost(), o2.getOriginal().getColor(), o2.getOriginal().getRules());
if (val == 0) {
return o1.getOriginal().getName().compareTo(o2.getOriginal().getName());
}
else {
} else {
return val;
}
}

View file

@ -1,37 +1,36 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
/*
* CardsList.java
*
* Created on Dec 18, 2009, 10:40:12 AM
*/
package mage.client.cards;
import java.awt.Color;
@ -59,7 +58,7 @@ import mage.client.constants.Constants.DeckEditorMode;
import mage.client.constants.Constants.SortBy;
import static mage.client.constants.Constants.SortBy.CASTING_COST;
import static mage.client.constants.Constants.SortBy.COLOR;
import static mage.client.constants.Constants.SortBy.COLOR_DETAILED;
import static mage.client.constants.Constants.SortBy.COLOR_IDENTITY;
import static mage.client.constants.Constants.SortBy.RARITY;
import mage.client.deckeditor.SortSetting;
import mage.client.deckeditor.table.TableModel;
@ -67,7 +66,7 @@ import mage.client.deckeditor.table.UpdateCountsCallback;
import mage.client.dialog.PreferencesDialog;
import mage.client.plugins.impl.Plugins;
import mage.client.util.CardViewColorComparator;
import mage.client.util.CardViewColorDetailedComparator;
import mage.client.util.CardViewColorIdentityComparator;
import mage.client.util.CardViewCostComparator;
import mage.client.util.CardViewNameComparator;
import mage.client.util.CardViewRarityComparator;
@ -86,7 +85,7 @@ import org.mage.card.arcane.CardPanel;
* @author BetaSteward_at_googlemail.com
*/
public class CardsList extends javax.swing.JPanel implements MouseListener, ICardGrid {
protected CardEventSource cardEventSource = new CardEventSource();
private Dimension cardDimension;
private CardsView cards;
@ -98,8 +97,10 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
private TableModel mainModel;
private JTable mainTable;
private ICardGrid currentView;
/** Creates new form Cards */
/**
* Creates new form Cards
*/
public CardsList() {
initComponents();
makeTransparent();
@ -115,22 +116,22 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
mainModel.removeTableModelListener(mainTable);
mainModel.clear();
}
if(cardArea != null) {
for(MouseListener ml: cardArea.getMouseListeners()) {
if (cardArea != null) {
for (MouseListener ml : cardArea.getMouseListeners()) {
cardArea.removeMouseListener(ml);
}
}
if(mainTable != null) {
for(MouseListener ml: mainTable.getMouseListeners()) {
if (mainTable != null) {
for (MouseListener ml : mainTable.getMouseListeners()) {
mainTable.removeMouseListener(ml);
}
}
if (currentView != null) {
currentView.clearCardEventListeners();
}
for (Component comp :cardArea.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel)comp).cleanUp();
for (Component comp : cardArea.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel) comp).cleanUp();
}
}
mageCards.clear();
@ -208,20 +209,20 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
// activate spinner for card number change
mainModel.setNumberEditable(true);
TableColumnModel tcm = mainTable.getColumnModel();
TableColumn tc = tcm.getColumn(0);
TableColumn tc = tcm.getColumn(0);
tc.setMaxWidth(55);
tc.setMinWidth(55);
tc.setPreferredWidth(55);
tc.setCellEditor(new TableSpinnerEditor(this));
tc.setCellEditor(new TableSpinnerEditor(this));
}
}
public void handleSetNumber(int number) {
if (mainTable.getSelectedRowCount() == 1) {
mainModel.setNumber(mainTable.getSelectedRow(), number);
}
}
}
public void handleDoubleClick() {
if (mainTable.getSelectedRowCount() > 0) {
int[] n = mainTable.getSelectedRows();
@ -232,7 +233,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
}
}
}
public void handleAltDoubleClick() {
if (mainTable.getSelectedRowCount() > 0) {
int[] n = mainTable.getSelectedRows();
@ -243,7 +244,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
}
}
}
public ICardGrid getMainModel() {
return mainModel;
}
@ -256,7 +257,6 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
return list;
}
public void loadCards(CardsView showCards, BigCard bigCard, UUID gameId) {
int selectedRow = -1;
if (currentView.equals(mainModel)) {
@ -270,7 +270,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
chkPiles.setSelected(sortSetting.isPilesToggle());
currentView.loadCards(showCards, sortSetting, bigCard, gameId);
if (selectedRow >= 0) {
selectedRow = Math.min(selectedRow, mainTable.getRowCount()-1);
selectedRow = Math.min(selectedRow, mainTable.getRowCount() - 1);
if (selectedRow >= 0) {
mainTable.setRowSelectionInterval(selectedRow, selectedRow);
}
@ -281,7 +281,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
if (cards == null) {
cards = new CardsView();
}
currentView.loadCards(cards, sortSetting, bigCard, gameId);
currentView.loadCards(cards, sortSetting, bigCard, gameId);
}
@Override
@ -295,22 +295,21 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
Comparator<CardView> comparator = null;
Map<UUID, MageCard> oldMageCards = mageCards;
mageCards = new LinkedHashMap<>();
//Find card view
for(UUID uuid : cards.keySet()){
if(oldMageCards.containsKey(uuid)){
for (UUID uuid : cards.keySet()) {
if (oldMageCards.containsKey(uuid)) {
mageCards.put(uuid, oldMageCards.get(uuid));
oldMageCards.remove(uuid);
}
else{
} else {
mageCards.put(uuid, addCard(cards.get(uuid), bigCard, gameId));
}
}
//Remove unused cards
for(MageCard card : oldMageCards.values()){
for (MageCard card : oldMageCards.values()) {
cardArea.remove(card);
}
if (cards != null && cards.size() > 0) {
Rectangle rectangle = new Rectangle(Config.dimensions.frameWidth, Config.dimensions.frameHeight);
List<CardView> sortedCards = new ArrayList<>(cards.values());
@ -324,25 +323,25 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
case COLOR:
comparator = new CardViewColorComparator();
break;
case COLOR_DETAILED:
comparator = new CardViewColorDetailedComparator();
case COLOR_IDENTITY:
comparator = new CardViewColorIdentityComparator();
break;
case CASTING_COST:
comparator = new CardViewCostComparator();
break;
}
if(comparator != null){
if (comparator != null) {
Collections.sort(sortedCards, new CardViewNameComparator());
Collections.sort(sortedCards, comparator);
}
CardView lastCard = null;
for (CardView card: sortedCards) {
for (CardView card : sortedCards) {
if (sortSetting.isPilesToggle()) {
if (lastCard == null) {
lastCard = card;
}
if(comparator != null){
if(comparator.compare(card, lastCard) > 0){
if (comparator != null) {
if (comparator.compare(card, lastCard) > 0) {
curColumn++;
maxRow = Math.max(maxRow, curRow);
curRow = 0;
@ -350,7 +349,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
}
rectangle.setLocation(curColumn * Config.dimensions.frameWidth, curRow * 20);
setCardBounds(mageCards.get(card.getId()), rectangle);
curRow++;
lastCard = card;
} else {
@ -368,21 +367,21 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
maxRow = Math.max(maxRow, curRow);
maxColumn = Math.max(maxColumn, curColumn);
updateCounts();
cardArea.setPreferredSize(new Dimension((maxColumn+1) * Config.dimensions.frameWidth, Config.dimensions.frameHeight + maxRow*20));
cardArea.setPreferredSize(new Dimension((maxColumn + 1) * Config.dimensions.frameWidth, Config.dimensions.frameHeight + maxRow * 20));
cardArea.revalidate();
this.revalidate();
this.repaint();
this.setVisible(true);
}
private void updateCounts(){
private void updateCounts() {
int landCount = 0;
int creatureCount = 0;
int sorceryCount = 0;
int instantCount = 0;
int enchantmentCount = 0;
for (CardView card: cards.values()) {
if (card.getCardTypes().contains(CardType.LAND)) {
for (CardView card : cards.values()) {
if (card.getCardTypes().contains(CardType.LAND)) {
landCount++;
}
if (card.getCardTypes().contains(CardType.CREATURE)) {
@ -398,7 +397,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
enchantmentCount++;
}
}
int count = cards != null ? cards.size() : 0;
this.lblCount.setText(Integer.toString(count));
this.lblCreatureCount.setText(Integer.toString(creatureCount));
@ -418,7 +417,6 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
cardImg.addMouseListener(this);
return cardImg;
}
private void setCardBounds(MageCard card, Rectangle rectangle) {
card.setBounds(rectangle);
@ -456,10 +454,10 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
mainModel.clearCardEventListeners();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -678,9 +676,9 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
currentView = mainModel;
panelCardArea.setViewportView(mainTable);
cbSortBy.setEnabled(false);
chkPiles.setEnabled(false);
chkPiles.setEnabled(false);
PreferencesDialog.saveValue(PreferencesDialog.KEY_DRAFT_VIEW, "listView");
redrawCards();
redrawCards();
}//GEN-LAST:event_jToggleListViewActionPerformed
private void cbSortByActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSortByActionPerformed
@ -698,8 +696,8 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
panelCardArea.setViewportView(cardArea);
cbSortBy.setEnabled(true);
chkPiles.setEnabled(true);
PreferencesDialog.saveValue(PreferencesDialog.KEY_DRAFT_VIEW, "cardView");
redrawCards();
PreferencesDialog.saveValue(PreferencesDialog.KEY_DRAFT_VIEW, "cardView");
redrawCards();
}//GEN-LAST:event_jToggleCardViewActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
@ -725,28 +723,26 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
@Override
public void mousePressed(MouseEvent e) {
if (e.getClickCount() >= 1 && !e.isConsumed()) {
if (e.getClickCount() >= 1 && !e.isConsumed()) {
Object obj = e.getSource();
if (e.getClickCount() == 2) {
e.consume();
if (obj instanceof Card) {
if (e.isAltDown()) {
cardEventSource.altDoubleClick(((Card)obj).getOriginal(), "alt-double-click");
}
else {
cardEventSource.doubleClick(((Card)obj).getOriginal(), "double-click");
cardEventSource.altDoubleClick(((Card) obj).getOriginal(), "alt-double-click");
} else {
cardEventSource.doubleClick(((Card) obj).getOriginal(), "double-click");
}
} else if (obj instanceof MageCard) {
if (e.isAltDown()) {
cardEventSource.altDoubleClick(((MageCard)obj).getOriginal(), "alt-double-click");
}
else {
cardEventSource.doubleClick(((MageCard)obj).getOriginal(), "double-click");
cardEventSource.altDoubleClick(((MageCard) obj).getOriginal(), "alt-double-click");
} else {
cardEventSource.doubleClick(((MageCard) obj).getOriginal(), "double-click");
}
}
}
if (obj instanceof MageCard) {
checkMenu(e, ((MageCard)obj).getOriginal());
checkMenu(e, ((MageCard) obj).getOriginal());
} else {
checkMenu(e, null);
}
@ -758,14 +754,14 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
if (!e.isConsumed()) {
Object obj = e.getSource();
if (obj instanceof MageCard) {
checkMenu(e, ((MageCard)obj).getOriginal());
checkMenu(e, ((MageCard) obj).getOriginal());
} else {
checkMenu(e, null);
}
}
}
private void checkMenu(MouseEvent Me, SimpleCardView card){
private void checkMenu(MouseEvent Me, SimpleCardView card) {
if (Me.isPopupTrigger()) {
Me.consume();
cardEventSource.showPopupMenuEvent(card, Me.getComponent(), Me.getX(), Me.getY(), "show-popup-menu");

View file

@ -254,20 +254,20 @@ public class Permanent extends Card {
@Override
public void mouseEntered(MouseEvent arg0) {
if (!popupShowing) {
if (popup != null) {
popup.hide();
if (!tooltipShowing) {
if (tooltipPopup != null) {
tooltipPopup.hide();
}
PopupFactory factory = PopupFactory.getSharedInstance();
int x = (int) this.getLocationOnScreen().getX() + (permanent.isTapped()?Config.dimensions.frameHeight:Config.dimensions.frameWidth);
int y = (int) this.getLocationOnScreen().getY() + 40;
popup = factory.getPopup(this, popupText, x, y);
popup.show();
//hack to get popup to resize to fit text
popup.hide();
popup = factory.getPopup(this, popupText, x, y);
popup.show();
popupShowing = true;
tooltipPopup = factory.getPopup(this, tooltipText, x, y);
tooltipPopup.show();
//hack to get tooltipPopup to resize to fit text
tooltipPopup.hide();
tooltipPopup = factory.getPopup(this, tooltipText, x, y);
tooltipPopup.show();
tooltipShowing = true;
}
}

View file

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.5" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="txtMessage" max="32767" attributes="0"/>
<Component id="jScrollPaneTxt" pref="193" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Component id="jScrollPaneTxt" pref="175" max="32767" attributes="0"/>
<EmptySpace min="0" pref="0" max="-2" attributes="0"/>
<Component id="txtMessage" min="-2" pref="30" max="-2" attributes="0"/>
<EmptySpace min="0" pref="0" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JScrollPane" name="jScrollPaneTxt">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="null"/>
</Property>
</Properties>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="mage.client.components.ColorPane" name="txtConversation">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo">
<EmptyBorder/>
</Border>
</Property>
<Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
<Font name="Arial" size="14" style="0"/>
</Property>
<Property name="focusCycleRoot" type="boolean" value="false"/>
<Property name="margin" type="java.awt.Insets" editor="org.netbeans.beaninfo.editors.InsetsEditor">
<Insets value="[2, 2, 2, 2]"/>
</Property>
<Property name="opaque" type="boolean" value="false"/>
</Properties>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JTextField" name="txtMessage">
<Events>
<EventHandler event="keyTyped" listener="java.awt.event.KeyListener" parameters="java.awt.event.KeyEvent" handler="txtMessageKeyTyped"/>
</Events>
</Component>
</SubComponents>
</Form>

View file

@ -35,82 +35,65 @@ package mage.client.chat;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import javax.swing.Icon;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import mage.client.MageFrame;
import static mage.client.dialog.PreferencesDialog.KEY_USERS_COLUMNS_ORDER;
import static mage.client.dialog.PreferencesDialog.KEY_USERS_COLUMNS_WIDTH;
import mage.client.util.MageTableRowSorter;
import mage.client.util.gui.TableUtil;
import mage.client.util.gui.countryBox.CountryCellRenderer;
import mage.remote.MageRemoteException;
import mage.remote.Session;
import mage.view.ChatMessage.MessageColor;
import mage.view.ChatMessage.MessageType;
import mage.view.RoomUsersView;
import mage.view.UsersView;
import org.mage.card.arcane.ManaSymbols;
/**
*
* @author BetaSteward_at_googlemail.com, nantuko
*/
public class ChatPanel extends javax.swing.JPanel {
public class ChatPanelBasic extends javax.swing.JPanel {
private UUID chatId;
private Session session;
private final List<String> players = new ArrayList<>();
private final UserTableModel userTableModel;
protected UUID chatId;
protected Session session;
/**
* Chat message color for opponents.
*/
private static final String OPPONENT_COLOR = "#FF7F50";
protected static final String OPPONENT_COLOR = "#FF7F50";
/**
* Chat message color for client player.
*/
private static final String MY_COLOR = "#7FFFD4";
protected static final String MY_COLOR = "#7FFFD4";
/**
* Chat message color for timestamps.
*/
private static final String TIMESTAMP_COLOR = "#CCCC33";
protected static final String TIMESTAMP_COLOR = "#CCCC33";
/**
* Chat message color for messages.
*/
private static final String MESSAGE_COLOR = "White";
protected static final String MESSAGE_COLOR = "White";
/**
* Chat message color for personal infos.
*/
private static final String USER_INFO_COLOR = "Yellow";
protected static final String USER_INFO_COLOR = "Yellow";
/**
* Chat message color for status infos.
*/
private static final String STATUS_COLOR = "#FFCC33";
protected static final String STATUS_COLOR = "#FFCC33";
/**
* Alpha value for transparency (255 = not transparent)
*/
private static final int ALPHA = 80;
public static final int CHAT_ALPHA = 80;
/**
* This will be a chat that will be connected to {this} and will handle
* redirected messages; Mostly used to redirect user messages to another
* window.
*/
private ChatPanel connectedChat;
protected ChatPanelBasic connectedChat;
/**
* Parent chat this chat connected to. Used to send messages using parent
* chat as it is the only one connected to server.
*/
private ChatPanel parentChatRef;
protected ChatPanelBasic parentChatRef;
/**
* Selected extended view mode.
*/
private VIEW_MODE extendedViewMode = VIEW_MODE.NONE;
protected VIEW_MODE extendedViewMode = VIEW_MODE.NONE;
public enum VIEW_MODE {
@ -120,57 +103,31 @@ public class ChatPanel extends javax.swing.JPanel {
* Controls the output start messages as the chat panel is created
*
*/
private ChatType chatType = ChatType.DEFAULT;
private static final int[] defaultColumnsWidth = {20, 100, 100, 80, 80};
protected ChatType chatType = ChatType.DEFAULT;
public enum ChatType {
DEFAULT, GAME, TABLES, TOURNAMENT
}
private boolean startMessageDone = false;
protected boolean startMessageDone = false;
/**
* Creates new form ChatPanel
*/
public ChatPanel() {
this(false);
}
/**
* @param addPlayersTab if true, adds chat/players tabs
*/
/**
*
* Creates new form ChatPanel
*
* @param addPlayersTab
*/
public ChatPanel(boolean addPlayersTab) {
userTableModel = new UserTableModel();
public ChatPanelBasic() {
initComponents();
setBackground(new Color(0, 0, 0, ALPHA));
jTablePlayers.setBackground(new Color(0, 0, 0, ALPHA));
jTablePlayers.setForeground(Color.white);
jTablePlayers.setRowSorter(new MageTableRowSorter(userTableModel));
TableUtil.setColumnWidthAndOrder(jTablePlayers, defaultColumnsWidth, KEY_USERS_COLUMNS_WIDTH, KEY_USERS_COLUMNS_ORDER);
jTablePlayers.setDefaultRenderer(Icon.class, new CountryCellRenderer());
setBackground(new Color(0, 0, 0, CHAT_ALPHA));
if (jScrollPaneTxt != null) {
jScrollPaneTxt.setBackground(new Color(0, 0, 0, ALPHA));
jScrollPaneTxt.getViewport().setBackground(new Color(0, 0, 0, ALPHA));
}
if (jScrollPanePlayers != null) {
jScrollPanePlayers.setBackground(new Color(0, 0, 0, ALPHA));
jScrollPanePlayers.getViewport().setBackground(new Color(0, 0, 0, ALPHA));
}
if (!addPlayersTab) {
simplifyComponents();
jScrollPaneTxt.setBackground(new Color(0, 0, 0, CHAT_ALPHA));
jScrollPaneTxt.getViewport().setBackground(new Color(0, 0, 0, CHAT_ALPHA));
}
}
public void cleanUp() {
TableUtil.saveColumnWidthAndOrderToPrefs(jTablePlayers, KEY_USERS_COLUMNS_WIDTH, KEY_USERS_COLUMNS_ORDER);
}
public ChatType getChatType() {
@ -254,7 +211,7 @@ public class ChatPanel extends javax.swing.JPanel {
this.txtConversation.append(text.toString());
}
private String getColoredText(String color, String text) {
protected String getColoredText(String color, String text) {
StringBuilder sb = new StringBuilder();
sb.append("<font color='");
sb.append(color);
@ -268,23 +225,23 @@ public class ChatPanel extends javax.swing.JPanel {
return txtConversation.getText();
}
public ChatPanel getConnectedChat() {
public ChatPanelBasic getConnectedChat() {
return connectedChat;
}
public void setConnectedChat(ChatPanel connectedChat) {
public void setConnectedChat(ChatPanelBasic connectedChat) {
this.connectedChat = connectedChat;
}
public void setParentChat(ChatPanel parentChatRef) {
public void setParentChat(ChatPanelBasic parentChatRef) {
this.parentChatRef = parentChatRef;
}
public ChatPanel getParentChatRef() {
public ChatPanelBasic getParentChatRef() {
return parentChatRef;
}
public void setParentChatRef(ChatPanel parentChatRef) {
public void setParentChatRef(ChatPanelBasic parentChatRef) {
this.parentChatRef = parentChatRef;
}
@ -303,104 +260,14 @@ public class ChatPanel extends javax.swing.JPanel {
case GAME:
case TABLES:
case DEFAULT:
alpha = ALPHA;
alpha = CHAT_ALPHA;
}
this.txtConversation.setExtBackgroundColor(new Color(0, 0, 0, alpha)); // Alpha = 255 not transparent
// this.txtConversation.setBackground(new Color(0, 0, 0, 0));
// this.txtConversation.setForeground(new Color(255, 255, 255));
this.txtConversation.setSelectionColor(Color.LIGHT_GRAY);
this.jScrollPaneTxt.setOpaque(alpha == 255);
this.jScrollPaneTxt.getViewport().setOpaque(!chatType.equals(ChatType.TABLES));
}
public void setSplitDividerLocation(int location) {
if (jSplitPane1 != null) {
jSplitPane1.setDividerLocation(location);
}
}
public int getSplitDividerLocation() {
if (jSplitPane1 == null) {
return 0;
}
return this.jSplitPane1.getDividerLocation();
}
class UserTableModel extends AbstractTableModel {
private final String[] columnNames = new String[]{"Loc", "Players", "Info", "Games", "Connection"};
private UsersView[] players = new UsersView[0];
public void loadData(Collection<RoomUsersView> roomUserInfoList) throws MageRemoteException {
RoomUsersView roomUserInfo = roomUserInfoList.iterator().next();
this.players = roomUserInfo.getUsersView().toArray(new UsersView[0]);
JTableHeader th = jTablePlayers.getTableHeader();
TableColumnModel tcm = th.getColumnModel();
tcm.getColumn(jTablePlayers.convertColumnIndexToView(1)).setHeaderValue("Players (" + this.players.length + ")");
tcm.getColumn(jTablePlayers.convertColumnIndexToView(3)).setHeaderValue(
"Games " + roomUserInfo.getNumberActiveGames()
+ (roomUserInfo.getNumberActiveGames() != roomUserInfo.getNumberGameThreads() ? " (T:" + roomUserInfo.getNumberGameThreads() : " (")
+ " limit: " + roomUserInfo.getNumberMaxGames() + ")");
th.repaint();
this.fireTableDataChanged();
}
@Override
public int getRowCount() {
return players.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int arg0, int arg1) {
switch (arg1) {
case 0:
return players[arg0].getFlagName();
case 1:
return players[arg0].getUserName();
case 2:
return players[arg0].getInfoState();
case 3:
return players[arg0].getInfoGames();
case 4:
return players[arg0].getInfoPing();
}
return "";
}
@Override
public String getColumnName(int columnIndex) {
String colName = "";
if (columnIndex <= getColumnCount()) {
colName = columnNames[columnIndex];
}
return colName;
}
@Override
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Icon.class;
default:
return String.class;
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
}
public void clear() {
this.txtConversation.setText("");
}
@ -414,18 +281,10 @@ public class ChatPanel extends javax.swing.JPanel {
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPaneTxt = new javax.swing.JScrollPane();
txtConversation = new mage.client.components.ColorPane();
jScrollPanePlayers = new javax.swing.JScrollPane();
jTablePlayers = new javax.swing.JTable();
txtMessage = new javax.swing.JTextField();
jSplitPane1.setBorder(null);
jSplitPane1.setDividerSize(10);
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jSplitPane1.setResizeWeight(0.25);
jScrollPaneTxt.setBorder(null);
txtConversation.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
@ -435,25 +294,6 @@ public class ChatPanel extends javax.swing.JPanel {
txtConversation.setOpaque(false);
jScrollPaneTxt.setViewportView(txtConversation);
jSplitPane1.setRightComponent(jScrollPaneTxt);
jScrollPanePlayers.setBorder(null);
jTablePlayers.setModel(this.userTableModel);
jTablePlayers.setToolTipText("Connected players");
jTablePlayers.setAutoscrolls(false);
jTablePlayers.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jTablePlayers.setFocusable(false);
jTablePlayers.setGridColor(new java.awt.Color(255, 255, 255));
jTablePlayers.setOpaque(false);
jTablePlayers.setRequestFocusEnabled(false);
jTablePlayers.setRowSelectionAllowed(false);
jTablePlayers.setUpdateSelectionOnSort(false);
jTablePlayers.setVerifyInputWhenFocusTarget(false);
jScrollPanePlayers.setViewportView(jTablePlayers);
jSplitPane1.setTopComponent(jScrollPanePlayers);
txtMessage.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtMessageKeyTyped(evt);
@ -464,36 +304,22 @@ public class ChatPanel extends javax.swing.JPanel {
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
.addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(txtMessage)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPaneTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
.addComponent(jScrollPaneTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
}// </editor-fold>//GEN-END:initComponents
private void simplifyComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtMessage, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)
.addComponent(jScrollPaneTxt, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPaneTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)));
jTablePlayers = null;
jScrollPanePlayers = null;
}
private void txtMessageKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMessageKeyTyped
public void handleKeyTyped(java.awt.event.KeyEvent evt) {
if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
if (parentChatRef != null) {
parentChatRef.session.sendChatMessage(parentChatRef.chatId, this.txtMessage.getText());
@ -503,20 +329,14 @@ public class ChatPanel extends javax.swing.JPanel {
this.txtMessage.setText("");
this.txtMessage.repaint();
}
}
private void txtMessageKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMessageKeyTyped
handleKeyTyped(evt);
}//GEN-LAST:event_txtMessageKeyTyped
public void setRoomUserInfo(List<Collection<RoomUsersView>> view) {
try {
userTableModel.loadData(view.get(0));
} catch (Exception ex) {
this.players.clear();
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPanePlayers;
private javax.swing.JScrollPane jScrollPaneTxt;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JTable jTablePlayers;
private mage.client.components.ColorPane txtConversation;
private javax.swing.JTextField txtMessage;
// End of variables declaration//GEN-END:variables

View file

@ -0,0 +1,108 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.chat;
import static mage.client.chat.ChatPanelBasic.TIMESTAMP_COLOR;
import mage.client.components.ColorPane;
import mage.view.ChatMessage;
import org.mage.card.arcane.ManaSymbols;
/**
*
* @author LevelX2
*/
public class ChatPanelSeparated extends ChatPanelBasic {
private ColorPane systemMessagesPane = null;
/**
* Display message in the chat. Use different colors for timestamp, username
* and message.
*
* @param username message sender
* @param message message itself
* @param time timestamp
* @param messageType
* @param color Preferred color. Not used.
*/
@Override
public void receiveMessage(String username, String message, String time, ChatMessage.MessageType messageType, ChatMessage.MessageColor color) {
switch (messageType) {
case TALK:
case WHISPER:
case USER_INFO:
super.receiveMessage(username, message, time, messageType, color);
return;
}
StringBuilder text = new StringBuilder();
if (time != null) {
text.append(getColoredText(TIMESTAMP_COLOR, time + ": "));
}
String userColor;
String textColor;
String userSeparator = " ";
switch (messageType) {
case STATUS: // a message to all chat user
textColor = STATUS_COLOR;
userColor = STATUS_COLOR;
break;
case USER_INFO: // a personal message
textColor = USER_INFO_COLOR;
userColor = USER_INFO_COLOR;
break;
default:
if (parentChatRef != null) {
userColor = parentChatRef.session.getUserName().equals(username) ? MY_COLOR : OPPONENT_COLOR;
} else {
userColor = session.getUserName().equals(username) ? MY_COLOR : OPPONENT_COLOR;
}
textColor = MESSAGE_COLOR;
userSeparator = ": ";
}
if (color.equals(ChatMessage.MessageColor.ORANGE)) {
textColor = "Orange";
}
if (color.equals(ChatMessage.MessageColor.YELLOW)) {
textColor = "Yellow";
}
if (username != null && !username.isEmpty()) {
text.append(getColoredText(userColor, username + userSeparator));
}
text.append(getColoredText(textColor, ManaSymbols.replaceSymbolsWithHTML(message, ManaSymbols.Type.PAY)));
this.systemMessagesPane.append(text.toString());
}
public ColorPane getSystemMessagesPane() {
return systemMessagesPane;
}
public void setSystemMessagesPane(ColorPane systemMessagesPane) {
this.systemMessagesPane = systemMessagesPane;
}
}

View file

@ -29,7 +29,7 @@ public class AbilityPicker extends JXPanel implements MouseWheelListener {
private static final int DIALOG_WIDTH = 440;
private static final int DIALOG_HEIGHT = 260;
private transient static final Logger log = Logger.getLogger(AbilityPicker.class);
private static final Logger log = Logger.getLogger(AbilityPicker.class);
private JList rows;
private List<Object> choices;

View file

@ -1,31 +1,30 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.constants;
import java.io.File;
@ -37,6 +36,7 @@ import javax.swing.border.Border;
* @author BetaSteward_at_googlemail.com
*/
public final class Constants {
private Constants() {
throw new AssertionError();
}
@ -69,7 +69,7 @@ public final class Constants {
public static final int POWBOX_TEXT_MAX_LEFT = 212;
public static final int DAMAGE_MAX_LEFT = 180;
public static final Border EMPTY_BORDER = BorderFactory.createEmptyBorder(2,2,2,2);
public static final Border EMPTY_BORDER = BorderFactory.createEmptyBorder(2, 2, 2, 2);
public static final double SCALE_FACTOR = 0.5;
@ -80,26 +80,29 @@ public final class Constants {
public static final String RESOURCE_PATH_SET = IO.imageBaseDir + "sets" + File.separator;
public static final String RESOURCE_PATH_SET_SMALL = RESOURCE_PATH_SET + File.separator + "small" + File.separator;
public static final String BASE_SOUND_PATH = "sounds" + File.separator;
public static final String BASE_MUSICS_PATH = "music" + File.separator ;
public static final String BASE_MUSICS_PATH = "music" + File.separator;
public interface IO {
String imageBaseDir = "plugins" + File.separator + "images" + File.separator;
String IMAGE_PROPERTIES_FILE = "image.url.properties";
}
public enum DeckEditorMode {
FREE_BUILDING,
LIMITED_BUILDING,
SIDEBOARDING
}
public enum SortBy {
CASTING_COST ("Casting Cost"),
RARITY ("Rarity"),
COLOR ("Color"),
COLOR_DETAILED ("Color Detailed"),
NAME ("Name"),
UNSORTED ("Unsorted");
CASTING_COST("Casting Cost"),
RARITY("Rarity"),
COLOR("Color"),
COLOR_IDENTITY("Color Identity"),
NAME("Name"),
UNSORTED("Unsorted");
private final String text;
@ -120,8 +123,8 @@ public final class Constants {
return RARITY;
case "Color":
return COLOR;
case "Color Detailed":
return COLOR_DETAILED;
case "Color Identity":
return COLOR_IDENTITY;
case "Name":
return NAME;
default:

View file

@ -27,21 +27,24 @@
*/
package mage.client.deck.generator;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import mage.cards.Card;
import mage.cards.decks.Deck;
import mage.cards.repository.CardCriteria;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.cards.repository.ExpansionInfo;
import mage.cards.repository.ExpansionRepository;
import mage.client.dialog.PreferencesDialog;
import mage.client.util.sets.ConstructedFormats;
import mage.constants.CardType;
import mage.constants.ColoredManaSymbol;
import mage.constants.Rarity;
import mage.util.TournamentUtil;
/**
* Generates random card pool and builds a deck.
@ -57,6 +60,7 @@ public class DeckGenerator {
/**
* Builds a deck out of the selected block/set/format.
*
* @return a path to the generated deck.
*/
public static String generateDeck() {
@ -70,7 +74,6 @@ public class DeckGenerator {
return PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_DECK_FILE, null);
}
protected static Deck buildDeck() {
String selectedColors = genDialog.getSelectedColors();
@ -100,6 +103,7 @@ public class DeckGenerator {
/**
* If the user has selected random colors, pick them randomly for the user.
*
* @param selectedColors a string of the colors selected.
* @return a String representation of the new colors chosen.
*/
@ -130,9 +134,10 @@ public class DeckGenerator {
}
/**
* Generates all the cards to use in the deck.
* Adds creatures, non-creatures, lands (including non-basic).
* Fixes the deck, adjusting for size and color of the cards retrieved.
* Generates all the cards to use in the deck. Adds creatures,
* non-creatures, lands (including non-basic). Fixes the deck, adjusting for
* size and color of the cards retrieved.
*
* @param deckSize how big the deck is to generate.
* @param allowedColors which colors are allowed in the deck.
* @param setsToUse which sets to use to retrieve cards for this deck.
@ -148,16 +153,18 @@ public class DeckGenerator {
creatureCriteria.setCodes(sets);
creatureCriteria.notTypes(CardType.LAND);
creatureCriteria.types(CardType.CREATURE);
if (!(genDialog.useArtifacts()))
if (!(genDialog.useArtifacts())) {
creatureCriteria.notTypes(CardType.ARTIFACT);
}
// Non-creatures (sorcery, instant, enchantment, artifact etc.)
final CardCriteria nonCreatureCriteria = new CardCriteria();
nonCreatureCriteria.setCodes(sets);
nonCreatureCriteria.notTypes(CardType.LAND);
nonCreatureCriteria.notTypes(CardType.CREATURE);
if (!(genDialog.useArtifacts()))
if (!(genDialog.useArtifacts())) {
nonCreatureCriteria.notTypes(CardType.ARTIFACT);
}
// Non-basic land
final CardCriteria nonBasicLandCriteria = new CardCriteria();
@ -176,15 +183,18 @@ public class DeckGenerator {
return genPool.getDeck();
}
/**
* Generates all spells for the deck.
* Each card is retrieved from the database and checked against the converted mana cost (CMC) needed for the current card pool.
* If a card's CMC matches the CMC range required by the pool, it is added to the deck.
* This ensures that the majority of cards fit a fixed mana curve for the deck, and it is playable.
* Creatures and non-creatures are retrieved separately to ensure the deck contains a reasonable mix of both.
* Generates all spells for the deck. Each card is retrieved from the
* database and checked against the converted mana cost (CMC) needed for the
* current card pool. If a card's CMC matches the CMC range required by the
* pool, it is added to the deck. This ensures that the majority of cards
* fit a fixed mana curve for the deck, and it is playable. Creatures and
* non-creatures are retrieved separately to ensure the deck contains a
* reasonable mix of both.
*
* @param criteria the criteria to search for in the database.
* @param spellCount the number of spells that match the criteria needed in the deck.
* @param spellCount the number of spells that match the criteria needed in
* the deck.
*/
private static void generateSpells(CardCriteria criteria, int spellCount) {
List<CardInfo> cardPool = CardRepository.instance.findCards(criteria);
@ -211,8 +221,9 @@ public class DeckGenerator {
} else {
if (reservesAdded < (genPool.getDeckSize() / 2)) {
added = genPool.tryAddReserve(card, cardCMC);
if(added)
if (added) {
reservesAdded++;
}
}
}
}
@ -230,11 +241,13 @@ public class DeckGenerator {
}
/**
* Generates all the lands for the deck.
* Generates non-basic if selected by the user and if the deck isn't monocolored.
* Will fetch non-basic lands if required and then fill up the remaining space with basic lands.
* Basic lands are adjusted according to the mana symbols seen in the cards used in this deck.
* Usually the lands will be well balanced relative to the color of cards.
* Generates all the lands for the deck. Generates non-basic if selected by
* the user and if the deck isn't monocolored. Will fetch non-basic lands if
* required and then fill up the remaining space with basic lands. Basic
* lands are adjusted according to the mana symbols seen in the cards used
* in this deck. Usually the lands will be well balanced relative to the
* color of cards.
*
* @param criteria the criteria of the lands to search for in the database.
* @param landsCount the amount of lands required for this deck.
* @param basicLands information about the basic lands from the sets used.
@ -280,47 +293,13 @@ public class DeckGenerator {
/**
* Returns a map of colored mana symbol to basic land cards of that color.
*
* @param setsToUse which sets to retrieve basic lands from.
* @return a map of color to basic lands.
*/
private static Map<String, List<CardInfo>> generateBasicLands(List<String> setsToUse) {
List<String> landSets = new LinkedList<>();
// decide from which sets basic lands are taken from
for (String setCode :setsToUse) {
ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode);
if (expansionInfo.hasBasicLands()) {
landSets.add(expansionInfo.getCode());
}
}
// if sets have no basic land, take land from block
if (landSets.isEmpty()) {
for (String setCode :setsToUse) {
ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode);
List<ExpansionInfo> blockSets = ExpansionRepository.instance.getSetsFromBlock(expansionInfo.getBlockName());
for (ExpansionInfo blockSet: blockSets) {
if (blockSet.hasBasicLands()) {
landSets.add(blockSet.getCode());
}
}
}
}
// if still no set with lands found, take one by random
if (landSets.isEmpty()) {
// if sets have no basic lands and also it has no parent or parent has no lands get last set with lands
// select a set with basic lands by random
Random generator = new Random();
List<ExpansionInfo> basicLandSets = ExpansionRepository.instance.getSetsWithBasicLandsByReleaseDate();
if (basicLandSets.size() > 0) {
landSets.add(basicLandSets.get(generator.nextInt(basicLandSets.size())).getCode());
}
}
if (landSets.isEmpty()) {
throw new IllegalArgumentException("No set with basic land was found");
}
Set<String> landSets = TournamentUtil.getLandSetCodeForDeckSets(setsToUse);
CardCriteria criteria = new CardCriteria();
if (!landSets.isEmpty()) {
@ -329,7 +308,7 @@ public class DeckGenerator {
Map<String, List<CardInfo>> basicLandMap = new HashMap<>();
for(ColoredManaSymbol c: ColoredManaSymbol.values()) {
for (ColoredManaSymbol c : ColoredManaSymbol.values()) {
String landName = DeckGeneratorPool.getBasicLandName(c.toString());
criteria.rarities(Rarity.LAND).name(landName);
List<CardInfo> cards = CardRepository.instance.findCards(criteria);
@ -339,11 +318,14 @@ public class DeckGenerator {
}
/**
* Once any non-basic lands are added, add basic lands until the deck is filled.
* Once any non-basic lands are added, add basic lands until the deck is
* filled.
*
* @param landsNeeded how many remaining lands are needed.
* @param percentage the percentage needed for each color in the final deck.
* @param count how many of each color can be produced by non-basic lands.
* @param basicLands list of information about basic lands from the database.
* @param basicLands list of information about basic lands from the
* database.
*/
private static void addBasicLands(int landsNeeded, Map<String, Double> percentage, Map<String, Integer> count, Map<String, List<CardInfo>> basicLands) {
int colorTotal = 0;
@ -369,8 +351,9 @@ public class DeckGenerator {
int currentCount = count.get(color.toString());
double thisPercentage = 0.0;
// Calculate the percentage of lands so far that produce this color
if (currentCount > 0)
if (currentCount > 0) {
thisPercentage = (currentCount / (double) colorTotal) * 100.0;
}
// Check if the color is the most "needed" (highest percentage) we have seen so far
if (neededPercentage - thisPercentage > minPercentage) {
// Put this color land forward to be added
@ -378,7 +361,7 @@ public class DeckGenerator {
minPercentage = (neededPercentage - thisPercentage);
}
}
if(colorToAdd != null) {
if (colorToAdd != null) {
genPool.addCard(getBasicLand(colorToAdd, basicLands));
count.put(colorToAdd.toString(), count.get(colorToAdd.toString()) + 1);
colorTotal++;
@ -389,15 +372,17 @@ public class DeckGenerator {
/**
* Return a random basic land of the chosen color.
*
* @param color the color the basic land should produce.
* @param basicLands list of information about basic lands from the database.
* @param basicLands list of information about basic lands from the
* database.
* @return a single basic land that produces the color needed.
*/
private static Card getBasicLand(ColoredManaSymbol color, Map<String, List<CardInfo>> basicLands) {
Random random = new Random();
String landName = DeckGeneratorPool.getBasicLandName(color.toString());
return basicLands.get(landName).get(random.nextInt(basicLands.size() - 1)).getMockCard().copy();
List<CardInfo> basicLandsInfo = basicLands.get(landName);
return basicLandsInfo.get(random.nextInt(basicLandsInfo.size() - 1)).getMockCard().copy();
}
}

View file

@ -385,6 +385,12 @@ public class DeckGeneratorPool
if(spellSize < nonLandSize) {
int spellsNeeded = nonLandSize-spellSize;
// If we haven't got enough spells in reserve to fulfil the amount we need, we can't continue.
if(reserveSpells.size() < spellsNeeded) {
throw new IllegalStateException("Not enough cards found to generate deck. Please try again");
}
List<Card> spellsToAdd = new ArrayList<>(spellsNeeded);
// Initial reservoir
@ -401,7 +407,6 @@ public class DeckGeneratorPool
// Add randomly selected spells needed
deckCards.addAll(spellsToAdd);
}
// More spells than needed
else if(spellSize > (deckSize - landCount)) {
@ -410,8 +415,11 @@ public class DeckGeneratorPool
deckCards.remove(random.nextInt(deckCards.size()));
}
}
if(deckCards.size() != nonLandSize)
// Not strictly necessary as we check when adding cards, but worth double checking anyway.
if(deckCards.size() != nonLandSize) {
throw new IllegalStateException("Not enough cards found to generate deck. Please try again");
}
// Return the fixed amount
return deckCards;

View file

@ -57,7 +57,7 @@ public class AddLandDialog extends MageDialog {
private static final Logger logger = Logger.getLogger(MageDialog.class);
private Deck deck;
private final Set<String> setCodesland = new HashSet<>();
private final Set<String> landSetCodes = new HashSet<>();
private static final int DEFAULT_SEALED_DECK_CARD_NUMBER = 40;
@ -71,27 +71,27 @@ public class AddLandDialog extends MageDialog {
public void showDialog(Deck deck, DeckEditorMode mode) {
this.deck = deck;
SortedSet<String> landSets = new TreeSet<>();
SortedSet<String> landSetNames = new TreeSet<>();
if (!mode.equals(DeckEditorMode.FREE_BUILDING)) {
// decide from which sets basic lands are taken from
for (String setCode : deck.getExpansionSetCodes()) {
ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode);
if (expansionInfo != null && expansionInfo.hasBasicLands()) {
this.setCodesland.add(expansionInfo.getCode());
landSets.add(expansionInfo.getName());
this.landSetCodes.add(expansionInfo.getCode());
landSetNames.add(expansionInfo.getName());
}
}
// if sets have no basic land, take land from block
if (this.setCodesland.isEmpty()) {
if (this.landSetCodes.isEmpty()) {
for (String setCode : deck.getExpansionSetCodes()) {
ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByCode(setCode);
if (expansionInfo != null) {
List<ExpansionInfo> blockSets = ExpansionRepository.instance.getSetsFromBlock(expansionInfo.getBlockName());
for (ExpansionInfo blockSet : blockSets) {
if (blockSet.hasBasicLands()) {
this.setCodesland.add(blockSet.getCode());
landSets.add(blockSet.getName());
this.landSetCodes.add(blockSet.getCode());
landSetNames.add(blockSet.getName());
}
}
}
@ -99,19 +99,19 @@ public class AddLandDialog extends MageDialog {
}
}
// if still no set with lands found, add list of all available
if (this.setCodesland.isEmpty()) {
if (this.landSetCodes.isEmpty()) {
List<ExpansionInfo> basicLandSets = ExpansionRepository.instance.getSetsWithBasicLandsByReleaseDate();
for (ExpansionInfo expansionInfo : basicLandSets) {
landSets.add(expansionInfo.getName());
landSetNames.add(expansionInfo.getName());
}
}
if (landSets.isEmpty()) {
if (landSetNames.isEmpty()) {
throw new IllegalArgumentException("No set with basic land was found");
}
if (landSets.size() > 1) {
landSets.add("<Random lands>");
if (landSetNames.size() > 1) {
landSetNames.add("<Random lands>");
}
cbLandSet.setModel(new DefaultComboBoxModel(landSets.toArray()));
cbLandSet.setModel(new DefaultComboBoxModel(landSetNames.toArray()));
MageFrame.getDesktop().add(this, JLayeredPane.PALETTE_LAYER);
this.setVisible(true);
@ -123,7 +123,7 @@ public class AddLandDialog extends MageDialog {
CardCriteria criteria = new CardCriteria();
if (landSetName.equals("<Random lands>")) {
criteria.setCodes(setCodesland.toArray(new String[setCodesland.size()]));
criteria.setCodes(landSetCodes.toArray(new String[landSetCodes.size()]));
} else {
ExpansionInfo expansionInfo = ExpansionRepository.instance.getSetByName(landSetName);
if (expansionInfo == null) {

View file

@ -36,8 +36,6 @@ package mage.client.dialog;
import java.awt.Point;
import java.beans.PropertyVetoException;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import javax.swing.event.InternalFrameAdapter;
@ -50,6 +48,7 @@ import mage.client.util.gui.GuiDisplayUtil;
import mage.view.CardsView;
import mage.view.ExileView;
import mage.view.SimpleCardsView;
import org.apache.log4j.Logger;
import org.mage.plugins.card.utils.impl.ImageManagerImpl;
/**
@ -58,6 +57,8 @@ import org.mage.plugins.card.utils.impl.ImageManagerImpl;
*/
public class CardInfoWindowDialog extends MageDialog {
private static final Logger logger = Logger.getLogger(CardInfoWindowDialog.class);
public static enum ShowType {
REVEAL, REVEAL_TOP_LIBRARY, LOOKED_AT, EXILE, GRAVEYARD, OTHER
@ -123,7 +124,7 @@ public class CardInfoWindowDialog extends MageDialog {
try {
this.setIcon(false);
} catch (PropertyVetoException ex) {
Logger.getLogger(CardInfoWindowDialog.class.getName()).log(Level.SEVERE, null, ex);
logger.error(null, ex);
}
}
} else {

View file

@ -1,46 +1,39 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
/*
* ConnectDialog.java
*
* Created on 20-Jan-2010, 9:37:07 PM
*/
package mage.client.dialog;
import mage.client.MageFrame;
import mage.client.util.Config;
import mage.remote.Connection;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
@ -63,10 +56,17 @@ import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import mage.client.MageFrame;
import static mage.client.dialog.PreferencesDialog.KEY_CONNECTION_URL_SERVER_LIST;
import static mage.client.dialog.PreferencesDialog.KEY_CONNECT_AUTO_CONNECT;
import static mage.client.dialog.PreferencesDialog.KEY_CONNECT_FLAG;
import mage.client.util.Config;
import mage.client.util.gui.countryBox.CountryItemEditor;
import mage.remote.Connection;
import mage.remote.Connection.ProxyType;
import org.apache.log4j.Logger;
/**
* @author BetaSteward_at_googlemail.com
@ -101,11 +101,11 @@ public class ConnectDialog extends MageDialog {
this.txtUserName.setText(MageFrame.getPreferences().get("userName", ""));
this.chkAutoConnect.setSelected(Boolean.parseBoolean(MageFrame.getPreferences().get(KEY_CONNECT_AUTO_CONNECT, "false")));
this.chkForceUpdateDB.setSelected(false); // has always to be set manually to force comparison
String selectedFlag = MageFrame.getPreferences().get(KEY_CONNECT_FLAG, "world");
// set the selected country/flag
for (int i = 0; i < cbFlag.getItemCount(); i++) {
String[] name = (String[])cbFlag.getItemAt(i);
String[] name = (String[]) cbFlag.getItemAt(i);
if (name[1].equals(selectedFlag)) {
cbFlag.setSelectedIndex(i);
break;
@ -124,10 +124,9 @@ public class ConnectDialog extends MageDialog {
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -293,7 +292,7 @@ public class ConnectDialog extends MageDialog {
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
MageFrame.getPreferences().put("autoConnect", Boolean.toString(chkAutoConnect.isSelected()));
MageFrame.getPreferences().put(KEY_CONNECT_FLAG, ((CountryItemEditor)cbFlag.getEditor()).getImageItem());
MageFrame.getPreferences().put(KEY_CONNECT_FLAG, ((CountryItemEditor) cbFlag.getEditor()).getImageItem());
if (task != null && !task.isDone()) {
task.cancel(true);
} else {
@ -329,7 +328,7 @@ public class ConnectDialog extends MageDialog {
connection.setPort(Integer.valueOf(this.txtPort.getText().trim()));
connection.setUsername(this.txtUserName.getText().trim());
connection.setForceDBComparison(this.chkForceUpdateDB.isSelected());
MageFrame.getPreferences().put(KEY_CONNECT_FLAG, ((CountryItemEditor)cbFlag.getEditor()).getImageItem());
MageFrame.getPreferences().put(KEY_CONNECT_FLAG, ((CountryItemEditor) cbFlag.getEditor()).getImageItem());
ProxyType configProxyType = Connection.ProxyType.valueByText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_TYPE, "None"));
@ -354,8 +353,8 @@ public class ConnectDialog extends MageDialog {
}
// pref settings
MageFrame.getInstance().setUserPrefsToConnection(connection);
MageFrame.getInstance().setUserPrefsToConnection(connection);
logger.debug("connecting: " + connection.getProxyType() + " " + connection.getProxyHost() + " " + connection.getProxyPort());
task = new ConnectTask();
task.execute();
@ -385,7 +384,7 @@ public class ConnectDialog extends MageDialog {
get(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
if (result) {
lblStatus.setText("");
lblStatus.setText("");
connected();
MageFrame.getInstance().showGames(false);
} else {
@ -412,7 +411,6 @@ public class ConnectDialog extends MageDialog {
this.hideDialog();
}
private void keyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyTyped
char c = evt.getKeyChar();
if (!Character.isDigit(c)) {
@ -428,8 +426,12 @@ public class ConnectDialog extends MageDialog {
private void findPublicServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
BufferedReader in = null;
try {
URL serverListURL = new URL(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CONNECTION_URL_SERVER_LIST, "http://xmage.de/files/server-list.txt"));
String serverUrl = PreferencesDialog.getCachedValue(KEY_CONNECTION_URL_SERVER_LIST, "http://xmage.de/files/server-list.txt");
if (serverUrl.contains("xmage.info/files/")) {
serverUrl = serverUrl.replace("xmage.info/files/", "xmage.de/files/"); // replace old URL if still saved
PreferencesDialog.saveValue(KEY_CONNECTION_URL_SERVER_LIST, serverUrl);
}
URL serverListURL = new URL(serverUrl);
Connection.ProxyType configProxyType = Connection.ProxyType.valueByText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_TYPE, "None"));
Proxy p = null;
@ -465,12 +467,12 @@ public class ConnectDialog extends MageDialog {
boolean URLNotFound = false;
try {
in = new BufferedReader(new InputStreamReader(serverListURL.openConnection(p).getInputStream()));
} catch (SocketTimeoutException |FileNotFoundException | UnknownHostException ex ) {
} catch (SocketTimeoutException | FileNotFoundException | UnknownHostException ex) {
logger.warn("Could not read serverlist from: " + serverListURL.toString());
File f = new File("serverlist.txt");
if (f.exists() && !f.isDirectory()) {
logger.info("Using buffered serverlist: serverlist.txt");
URLNotFound = true;
URLNotFound = true;
in = new BufferedReader(new FileReader("serverlist.txt"));
}
}
@ -518,7 +520,7 @@ public class ConnectDialog extends MageDialog {
JOptionPane.showMessageDialog(null, "Wrong server data format.");
}
}
} catch (Exception ex) {
logger.error(ex, ex);
} finally {
@ -539,7 +541,6 @@ public class ConnectDialog extends MageDialog {
// TODO add your handling code here:
}//GEN-LAST:event_chkForceUpdateDBActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnConnect;

View file

@ -40,7 +40,7 @@ import javax.swing.*;
*/
public class FeedbackDialog extends javax.swing.JDialog {
private static final transient Logger log = Logger.getLogger(PreferencesDialog.class);
private static final Logger log = Logger.getLogger(PreferencesDialog.class);
private String[] feedbackTypes = {"", "Bug or \"something doesn't work\"",
"Feature or \"I need that function\"",

View file

@ -1,30 +1,30 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.dialog;
import java.io.FileNotFoundException;
@ -71,7 +71,9 @@ public class NewTableDialog extends MageDialog {
private static final String LIMITED = "Limited";
/** Creates new form NewTableDialog */
/**
* Creates new form NewTableDialog
*/
public NewTableDialog() {
session = MageFrame.getSession();
lastSessionId = "";
@ -79,13 +81,13 @@ public class NewTableDialog extends MageDialog {
player1Panel.showLevel(false);
this.spnNumWins.setModel(new SpinnerNumberModel(1, 1, 5, 1));
this.spnFreeMulligans.setModel(new SpinnerNumberModel(0, 0, 5, 1));
MageFrame.getUI().addButton(MageComponents.NEW_TABLE_OK_BUTTON, btnOK);
MageFrame.getUI().addButton(MageComponents.NEW_TABLE_OK_BUTTON, btnOK);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -361,7 +363,7 @@ public class NewTableDialog extends MageDialog {
GameTypeView gameType = (GameTypeView) cbGameType.getSelectedItem();
MatchOptions options = new MatchOptions(this.txtName.getText(), gameType.getName());
options.getPlayerTypes().add("Human");
for (TablePlayerPanel player: players) {
for (TablePlayerPanel player : players) {
options.getPlayerTypes().add(player.getPlayerType());
}
options.setDeckType((String) this.cbDeckType.getSelectedItem());
@ -370,9 +372,9 @@ public class NewTableDialog extends MageDialog {
options.setAttackOption((MultiplayerAttackOption) this.cbAttackOption.getSelectedItem());
options.setSkillLevel((SkillLevel) this.cbSkillLevel.getSelectedItem());
options.setRange((RangeOfInfluence) this.cbRange.getSelectedItem());
options.setWinsNeeded((Integer)this.spnNumWins.getValue());
options.setWinsNeeded((Integer) this.spnNumWins.getValue());
options.setRollbackTurnsAllowed(chkRollbackTurnsAllowed.isSelected());
options.setFreeMulligans((Integer)this.spnFreeMulligans.getValue());
options.setFreeMulligans((Integer) this.spnFreeMulligans.getValue());
options.setPassword(this.txtPassword.getText());
if (!checkMatchOptions(options)) {
return;
@ -391,9 +393,8 @@ public class NewTableDialog extends MageDialog {
this.player1Panel.getPlayerName(),
"Human", 1,
DeckImporterUtil.importDeck(this.player1Panel.getDeckFile()),
this.txtPassword.getText())
) {
for (TablePlayerPanel player: players) {
this.txtPassword.getText())) {
for (TablePlayerPanel player : players) {
if (!player.getPlayerType().equals("Human")) {
if (!player.joinTable(roomId, table.getTableId())) {
// error message must be send by the server
@ -423,7 +424,7 @@ public class NewTableDialog extends MageDialog {
}//GEN-LAST:event_cbGameTypeActionPerformed
private void numPlayersChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_numPlayersChanged
int numPlayers = (Integer)this.spnNumPlayers.getValue() - 1;
int numPlayers = (Integer) this.spnNumPlayers.getValue() - 1;
createPlayers(numPlayers);
}//GEN-LAST:event_numPlayersChanged
@ -432,9 +433,10 @@ public class NewTableDialog extends MageDialog {
}//GEN-LAST:event_spnNumWinsnumPlayersChanged
/**
* Checks about not valid game option combinations and shows an error message
*
* @return
* Checks about not valid game option combinations and shows an error
* message
*
* @return
*/
private boolean checkMatchOptions(MatchOptions options) {
switch (options.getDeckType()) {
@ -451,11 +453,17 @@ public class NewTableDialog extends MageDialog {
return false;
}
break;
case "Variant Magic - Momir Basic":
if (!options.getGameType().startsWith("Momir Basic")) {
JOptionPane.showMessageDialog(MageFrame.getDesktop(), "Deck type Momir Basic needs also a Momir Basic game type", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
break;
}
switch (options.getGameType()) {
case "Commander Two Player Duel":
case "Commander Free For All":
if (!options.getDeckType().equals("Variant Magic - Commander") && !options.getDeckType().equals("Variant Magic - Duel Commander") ) {
if (!options.getDeckType().equals("Variant Magic - Commander") && !options.getDeckType().equals("Variant Magic - Duel Commander")) {
JOptionPane.showMessageDialog(MageFrame.getDesktop(), "Deck type Commander needs also a Commander game type", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
@ -466,16 +474,16 @@ public class NewTableDialog extends MageDialog {
return false;
}
break;
}
}
return true;
}
private void setGameOptions() {
GameTypeView gameType = (GameTypeView) cbGameType.getSelectedItem();
int oldValue = (Integer) this.spnNumPlayers.getValue();
this.spnNumPlayers.setModel(new SpinnerNumberModel(gameType.getMinPlayers(), gameType.getMinPlayers(), gameType.getMaxPlayers(), 1));
this.spnNumPlayers.setEnabled(gameType.getMinPlayers() != gameType.getMaxPlayers());
if (oldValue >= gameType.getMinPlayers() && oldValue <= gameType.getMaxPlayers()){
if (oldValue >= gameType.getMinPlayers() && oldValue <= gameType.getMaxPlayers()) {
this.spnNumPlayers.setValue(oldValue);
}
this.cbAttackOption.setEnabled(gameType.isUseAttackOption());
@ -495,17 +503,16 @@ public class NewTableDialog extends MageDialog {
playerPanel.init(players.size() + 2, playerType);
players.add(playerPanel);
playerPanel.addPlayerTypeEventListener(
new Listener<Event> () {
@Override
public void event(Event event) {
drawPlayers();
new Listener<Event>() {
@Override
public void event(Event event) {
drawPlayers();
}
}
}
);
}
}
// remove player panels no longer needed
} // remove player panels no longer needed
else if (numPlayers < players.size()) {
while (players.size() != numPlayers) {
players.remove(players.size() - 1);
@ -516,7 +523,7 @@ public class NewTableDialog extends MageDialog {
private void drawPlayers() {
this.pnlOtherPlayers.removeAll();
for (TablePlayerPanel panel: players) {
for (TablePlayerPanel panel : players) {
this.pnlOtherPlayers.add(panel);
}
this.pack();
@ -531,7 +538,7 @@ public class NewTableDialog extends MageDialog {
}
public void showDialog(UUID roomId) {
this.roomId = roomId;
this.roomId = roomId;
if (!lastSessionId.equals(MageFrame.getSession().getSessionId())) {
lastSessionId = session.getSessionId();
this.player1Panel.setPlayerName(session.getUserName());
@ -543,8 +550,8 @@ public class NewTableDialog extends MageDialog {
cbAttackOption.setModel(new DefaultComboBoxModel(MultiplayerAttackOption.values()));
cbSkillLevel.setModel(new DefaultComboBoxModel(SkillLevel.values()));
// Update the existing player panels (neccessary if server was changes = new session)
int i=2;
for (TablePlayerPanel tablePlayerPanel :players) {
int i = 2;
for (TablePlayerPanel tablePlayerPanel : players) {
tablePlayerPanel.init(i++, tablePlayerPanel.getPlayerType());
}
setGameSettingsFromPrefs();
@ -565,7 +572,7 @@ public class NewTableDialog extends MageDialog {
private void selectLimitedByDefault() {
for (int i = 0; i < cbDeckType.getItemCount(); i++) {
String name = (String)cbDeckType.getItemAt(i);
String name = (String) cbDeckType.getItemAt(i);
if (name.equals(LIMITED)) {
cbDeckType.setSelectedIndex(i);
break;
@ -574,9 +581,9 @@ public class NewTableDialog extends MageDialog {
}
/**
* set the table settings from java prefs
* set the table settings from java prefs
*/
private void setGameSettingsFromPrefs () {
private void setGameSettingsFromPrefs() {
txtName.setText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_NAME, "Game"));
txtPassword.setText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_PASSWORD, ""));
@ -585,7 +592,6 @@ public class NewTableDialog extends MageDialog {
prefPlayerTypes.addAll(Arrays.asList(playerTypes.split(",")));
this.spnNumPlayers.setValue(Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_NUMBER_PLAYERS, "2")));
String gameTypeName = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_GAME_TYPE, "Two Player Duel");
for (GameTypeView gtv : session.getGameTypes()) {
if (gtv.getName().equals(gameTypeName)) {
@ -594,7 +600,7 @@ public class NewTableDialog extends MageDialog {
}
}
int timeLimit = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_TIME_LIMIT, "1500"));
for (MatchTimeLimit mtl :MatchTimeLimit.values()) {
for (MatchTimeLimit mtl : MatchTimeLimit.values()) {
if (mtl.getTimeLimit() == timeLimit) {
this.cbTimeLimit.setSelectedItem(mtl);
break;
@ -608,32 +614,32 @@ public class NewTableDialog extends MageDialog {
this.spnNumWins.setValue(Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_NUMBER_OF_WINS, "2")));
this.chkRollbackTurnsAllowed.setSelected(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_ROLLBACK_TURNS_ALLOWED, "Yes").equals("Yes"));
int range = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_RANGE, "1"));
for (RangeOfInfluence roi :RangeOfInfluence.values()) {
for (RangeOfInfluence roi : RangeOfInfluence.values()) {
if (roi.getRange() == range) {
this.cbRange.setSelectedItem(roi);
break;
}
}
String attackOption = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_ATTACK_OPTION, "Attack Multiple Players");
for (MultiplayerAttackOption mao :MultiplayerAttackOption.values()) {
for (MultiplayerAttackOption mao : MultiplayerAttackOption.values()) {
if (mao.toString().equals(attackOption)) {
this.cbAttackOption.setSelectedItem(mao);
break;
}
}
String skillLevelDefault = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TABLE_SKILL_LEVEL, "Casual");
for (SkillLevel skillLevel :SkillLevel.values()) {
for (SkillLevel skillLevel : SkillLevel.values()) {
if (skillLevel.toString().equals(skillLevelDefault)) {
this.cbSkillLevel.setSelectedItem(skillLevel);
break;
}
}
}
}
/**
* Save the settings to java prefs to reload it next time the dialog will be created
* Save the settings to java prefs to reload it next time the dialog will be
* created
*
* @param options
* @param deckFile
@ -645,7 +651,7 @@ public class NewTableDialog extends MageDialog {
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_TIME_LIMIT, Integer.toString(options.getPriorityTime()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_GAME_TYPE, options.getGameType());
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_NUMBER_OF_WINS, Integer.toString(options.getWinsNeeded()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_ROLLBACK_TURNS_ALLOWED, options.isRollbackTurnsAllowed() ? "Yes": "No");
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_ROLLBACK_TURNS_ALLOWED, options.isRollbackTurnsAllowed() ? "Yes" : "No");
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_NUMBER_OF_FREE_MULLIGANS, Integer.toString(options.getFreeMulligans()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_DECK_FILE, deckFile);
PreferencesDialog.saveValue(PreferencesDialog.KEY_NEW_TABLE_NUMBER_PLAYERS, spnNumPlayers.getValue().toString());
@ -655,7 +661,7 @@ public class NewTableDialog extends MageDialog {
StringBuilder playerTypesString = new StringBuilder();
ListIterator iterator = players.listIterator();
while (iterator.hasNext()) {
if (playerTypesString.length()>0) {
if (playerTypesString.length() > 0) {
playerTypesString.append(",");
}
TablePlayerPanel tpp = (TablePlayerPanel) iterator.next();

View file

@ -1,33 +1,41 @@
/*
* Copyright 2012 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2012 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.UUID;
import javax.swing.JButton;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import mage.cards.CardDimensions;
import mage.client.MageFrame;
import mage.client.cards.BigCard;
@ -35,18 +43,12 @@ import mage.client.cards.CardArea;
import mage.client.util.SettingsManager;
import mage.client.util.gui.GuiDisplayUtil;
import mage.view.CardsView;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.UUID;
import org.mage.card.arcane.CardPanel;
/**
*
* @author BetaSteward_at_googlemail.com
*/
*
* @author BetaSteward_at_googlemail.com
*/
public class PickPileDialog extends MageDialog {
private final CardArea pile1;
@ -94,24 +96,24 @@ public class PickPileDialog extends MageDialog {
}
public void cleanUp() {
for(Component comp: pile1.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel) comp).cleanUp();
pile1.remove(comp);
}
}
for(Component comp: pile2.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel) comp).cleanUp();
pile2.remove(comp);
}
}
for (Component comp : pile1.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel) comp).cleanUp();
pile1.remove(comp);
}
}
for (Component comp : pile2.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel) comp).cleanUp();
pile2.remove(comp);
}
}
}
public void loadCards(String name, CardsView pile1, CardsView pile2, BigCard bigCard, CardDimensions dimension, UUID gameId) {
this.title = name;
this.pile1.loadCardsNarrow(pile1, bigCard, dimension, gameId, null);
this.pile2.loadCardsNarrow(pile2, bigCard, dimension, gameId, null);
this.pile1.loadCardsNarrow(pile1, bigCard, dimension, gameId);
this.pile2.loadCardsNarrow(pile2, bigCard, dimension, gameId);
if (getParent() != MageFrame.getDesktop() /*|| this.isClosed*/) {
MageFrame.getDesktop().add(this, JLayeredPane.MODAL_LAYER);

View file

@ -1,82 +1,76 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
/*
* ShowCardsDialog.java
*
* Created on 3-Feb-2010, 8:59:11 PM
*/
package mage.client.dialog;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;
import java.util.Map;
import java.util.UUID;
import javax.swing.ImageIcon;
import javax.swing.JLayeredPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import mage.cards.CardDimensions;
import mage.client.MageFrame;
import mage.client.cards.BigCard;
import mage.client.cards.CardArea;
import mage.client.util.CardsViewUtil;
import mage.client.util.Event;
import mage.client.util.Listener;
import mage.client.util.SettingsManager;
import mage.client.util.gui.GuiDisplayUtil;
import mage.game.events.PlayerQueryEvent.QueryType;
import mage.view.CardsView;
import mage.view.SimpleCardsView;
import org.mage.card.arcane.CardPanel;
import org.mage.plugins.card.utils.impl.ImageManagerImpl;
/**
* @author BetaSteward_at_googlemail.com
*/
public class ShowCardsDialog extends MageDialog implements MouseListener {
public class ShowCardsDialog extends MageDialog {
// remember if this dialog was already auto positioned, so don't do it after the first time
private boolean positioned;
/**
* Creates new form ShowCardsDialog
*/
public ShowCardsDialog() {
this.positioned = false;
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
initComponents();
this.setModal(false);
}
public void cleanUp() {
@ -89,33 +83,37 @@ public class ShowCardsDialog extends MageDialog implements MouseListener {
}
}
public void loadCards(String name, SimpleCardsView showCards, BigCard bigCard, CardDimensions dimension, UUID gameId, boolean modal) {
loadCards(name, CardsViewUtil.convertSimple(showCards), bigCard, dimension, gameId, modal);
}
public void loadCards(String name, CardsView showCards, BigCard bigCard, CardDimensions dimension, UUID gameId, boolean modal) {
loadCards(name, showCards, bigCard, dimension, gameId, modal, null);
}
public void loadCards(String name, CardsView showCards, BigCard bigCard, CardDimensions dimension, UUID gameId, boolean modal, Map<String, Serializable> options) {
public void loadCards(String name, CardsView showCards, BigCard bigCard,
CardDimensions dimension, UUID gameId, boolean modal, Map<String, Serializable> options,
JPopupMenu popupMenu, Listener<Event> eventListener) {
this.title = name;
this.setTitelBarToolTip(name);
cardArea.loadCards(showCards, bigCard, dimension, gameId, this);
cardArea.clearCardEventListeners();
cardArea.loadCards(showCards, bigCard, dimension, gameId);
if (options != null) {
if (options.containsKey("chosen")) {
java.util.List<UUID> chosenCards = (java.util.List<UUID>)options.get("chosen");
java.util.List<UUID> chosenCards = (java.util.List<UUID>) options.get("chosen");
cardArea.selectCards(chosenCards);
}
if (options.containsKey("choosable")) {
java.util.List<UUID> choosableCards = (java.util.List<UUID>)options.get("choosable");
java.util.List<UUID> choosableCards = (java.util.List<UUID>) options.get("choosable");
cardArea.markCards(choosableCards);
}
if (options.containsKey("queryType") && QueryType.PICK_ABILITY.equals(options.get("queryType"))) {
cardArea.setPopupMenu(popupMenu);
}
}
if (popupMenu != null) {
this.cardArea.setPopupMenu(popupMenu);
}
if (eventListener != null) {
this.cardArea.addCardEventListener(eventListener);
}
if (getParent() != MageFrame.getDesktop() /*|| this.isClosed*/) {
MageFrame.getDesktop().add(this, JLayeredPane.DEFAULT_LAYER);
}
pack();
pack();
this.revalidate();
this.repaint();
@ -147,36 +145,9 @@ public class ShowCardsDialog extends MageDialog implements MouseListener {
setResizable(true);
getContentPane().setLayout(new java.awt.BorderLayout());
getContentPane().add(cardArea, java.awt.BorderLayout.CENTER);
this.addMouseListener(this);
pack();
}
private CardArea cardArea;
@Override
public void mouseClicked(MouseEvent e) {
this.hideDialog();
}
@Override
public void mousePressed(MouseEvent e) {
// only hide dialog, if a cardPanel was selected
if (e.getSource() instanceof CardPanel) {
this.hideDialog();
}
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}

View file

@ -28,13 +28,13 @@
<Component id="btnMoveDown" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnMoveUp" min="-2" max="-2" attributes="0"/>
<EmptySpace pref="326" max="32767" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
<Component id="btnStart" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnCancel" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
<Component id="jSplitPane1" alignment="0" pref="644" max="32767" attributes="0"/>
<Component id="jSplitPane1" alignment="0" pref="500" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
@ -91,9 +91,10 @@
</Component>
<Container class="javax.swing.JSplitPane" name="jSplitPane1">
<Properties>
<Property name="dividerLocation" type="int" value="320"/>
<Property name="dividerLocation" type="int" value="300"/>
<Property name="dividerSize" type="int" value="3"/>
<Property name="resizeWeight" type="double" value="1.0"/>
<Property name="toolTipText" type="java.lang.String" value=""/>
</Properties>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout"/>
@ -122,10 +123,7 @@
</Component>
</SubComponents>
</Container>
<Component class="mage.client.chat.ChatPanel" name="chatPanel">
<AuxValues>
<AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new mage.client.chat.ChatPanel(false);"/>
</AuxValues>
<Component class="mage.client.chat.ChatPanelBasic" name="chatPanel">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
<JSplitPaneConstraints position="right"/>

View file

@ -41,7 +41,7 @@ import javax.swing.Icon;
import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;
import mage.client.MageFrame;
import mage.client.chat.ChatPanel;
import mage.client.chat.ChatPanelBasic;
import mage.client.components.MageComponents;
import mage.client.components.tray.MageTray;
import static mage.client.dialog.PreferencesDialog.KEY_TABLE_WAITING_COLUMNS_ORDER;
@ -86,7 +86,7 @@ public class TableWaitingDialog extends MageDialog {
this.setSize(prefWidth, prefHeight);
}
chatPanel.useExtendedView(ChatPanel.VIEW_MODE.NONE);
chatPanel.useExtendedView(ChatPanelBasic.VIEW_MODE.NONE);
tableSeats.createDefaultColumnsFromModel();
TableUtil.setColumnWidthAndOrder(tableSeats, defaultColumnsWidth, KEY_TABLE_WAITING_COLUMNS_WIDTH, KEY_TABLE_WAITING_COLUMNS_ORDER);
tableSeats.setDefaultRenderer(Icon.class, new CountryCellRenderer());
@ -183,7 +183,7 @@ public class TableWaitingDialog extends MageDialog {
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane1 = new javax.swing.JScrollPane();
tableSeats = new javax.swing.JTable();
chatPanel = new mage.client.chat.ChatPanel(false);
chatPanel = new mage.client.chat.ChatPanelBasic();
setResizable(true);
setTitle("Waiting for players");
@ -219,9 +219,10 @@ public class TableWaitingDialog extends MageDialog {
}
});
jSplitPane1.setDividerLocation(320);
jSplitPane1.setDividerLocation(300);
jSplitPane1.setDividerSize(3);
jSplitPane1.setResizeWeight(1.0);
jSplitPane1.setToolTipText("");
tableSeats.setModel(tableWaitModel);
tableSeats.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
@ -239,12 +240,12 @@ public class TableWaitingDialog extends MageDialog {
.addComponent(btnMoveDown)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnMoveUp)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 326, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnStart)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCancel)
.addContainerGap())
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 644, Short.MAX_VALUE)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
@ -308,7 +309,7 @@ public class TableWaitingDialog extends MageDialog {
private javax.swing.JButton btnMoveDown;
private javax.swing.JButton btnMoveUp;
private javax.swing.JButton btnStart;
private mage.client.chat.ChatPanel chatPanel;
private mage.client.chat.ChatPanelBasic chatPanel;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JTable tableSeats;

View file

@ -31,7 +31,6 @@
*
* Created on Jan 7, 2011, 2:15:48 PM
*/
package mage.client.draft;
import java.awt.Component;
@ -41,7 +40,16 @@ import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ -53,9 +61,12 @@ import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.client.MageFrame;
import mage.client.components.tray.MageTray;
import mage.client.deckeditor.SortSettingDraft;
import mage.client.dialog.PreferencesDialog;
import mage.client.plugins.impl.Plugins;
import mage.client.util.CardsViewUtil;
import mage.client.util.Event;
@ -69,6 +80,7 @@ import mage.view.DraftPickView;
import mage.view.DraftView;
import mage.view.SimpleCardView;
import mage.view.SimpleCardsView;
import org.apache.log4j.Logger;
/**
*
@ -76,6 +88,8 @@ import mage.view.SimpleCardsView;
*/
public class DraftPanel extends javax.swing.JPanel {
private static final Logger logger = Logger.getLogger(DraftPanel.class);
private UUID draftId;
private Session session;
private Timer countdown;
@ -94,16 +108,31 @@ public class DraftPanel extends javax.swing.JPanel {
// id of card with popup menu
protected UUID cardIdPopupMenu;
// Filename for the draft log (only updated if writing the log).
private String logFilename;
// Number of the current booster (for draft log writing).
private int packNo;
// Number of the current card pick (for draft log writing).
private int pickNo;
// Cached booster data to be written into the log (see logLastPick).
private String currentBoosterHeader;
private String[] currentBooster;
private static final CardsView emptyView = new CardsView();
/** Creates new form DraftPanel */
/**
* Creates new form DraftPanel
*/
public DraftPanel() {
initComponents();
draftBooster.setOpaque(false);
draftPicks.setSortSetting(SortSettingDraft.getInstance());
draftPicks.setOpaque(false);
popupMenuPickedArea = new JPopupMenu();
addPopupMenuPickArea();
this.add(popupMenuPickedArea);
@ -115,18 +144,17 @@ public class DraftPanel extends javax.swing.JPanel {
draftLeftPane.setOpaque(false);
countdown = new Timer(1000,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (--timeout > 0) {
setTimeout(timeout);
}
else {
setTimeout(0);
countdown.stop();
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (--timeout > 0) {
setTimeout(timeout);
} else {
setTimeout(0);
countdown.stop();
}
}
}
}
);
}
@ -149,15 +177,29 @@ public class DraftPanel extends javax.swing.JPanel {
if (!session.joinDraft(draftId)) {
hideDraft();
}
if (isLogging()) {
// If we are logging the draft create a file that will contain
// the log.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
logFilename = "Draft_" + sdf.format(new Date()) + "_" + draftId + ".txt";
try {
Files.write(pathToDraftLog(), "".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException ex) {
logger.error(null, ex);
}
} else {
logFilename = null;
}
}
public void updateDraft(DraftView draftView) {
if (draftView.getSets().size() != 3){
public void updateDraft(DraftView draftView) {
if (draftView.getSets().size() != 3) {
// Random draft
this.txtPack1.setText("Random Boosters");
this.txtPack2.setText("Random Boosters");
this.txtPack3.setText("Random Boosters");
}else{
} else {
this.txtPack1.setText(draftView.getSets().get(0));
this.txtPack2.setText(draftView.getSets().get(1));
this.txtPack3.setText(draftView.getSets().get(2));
@ -167,17 +209,20 @@ public class DraftPanel extends javax.swing.JPanel {
this.chkPack3.setSelected(draftView.getBoosterNum() > 2);
this.txtCardNo.setText(Integer.toString(draftView.getCardNum()));
packNo = draftView.getBoosterNum();
pickNo = draftView.getCardNum();
int right = draftView.getPlayers().size() / 2;
int left = draftView.getPlayers().size() - right;
int height = left * 18;
lblTableImage.setSize(new Dimension(lblTableImage.getWidth(), height));
Image tableImage = ImageHelper.getImageFromResources(draftView.getBoosterNum() == 2 ? "/draft/table_left.png":"/draft/table_right.png");
Image tableImage = ImageHelper.getImageFromResources(draftView.getBoosterNum() == 2 ? "/draft/table_left.png" : "/draft/table_right.png");
BufferedImage resizedTable = ImageHelper.getResizedImage(BufferedImageBuilder.bufferImage(tableImage, BufferedImage.TYPE_INT_ARGB), lblTableImage.getWidth());
lblTableImage.setIcon(new ImageIcon(resizedTable));
int count = 0;
int numberPlayers = draftView.getPlayers().size();
for(String playerName: draftView.getPlayers()) {
for (String playerName : draftView.getPlayers()) {
count++;
setPlayerNameToLabel(playerName, count, numberPlayers);
}
@ -188,13 +233,13 @@ public class DraftPanel extends javax.swing.JPanel {
int right = players / 2;
int left = players - right;
if (index <= left) {
// left side down (1 - 8)
// left side down (1 - 8)
tablePosition = index;
} else {
// right side up (16 - 9)
tablePosition = 9 + right - (index - left);
}
switch(tablePosition) {
switch (tablePosition) {
case 1:
lblPlayer01.setText(name);
break;
@ -247,50 +292,51 @@ public class DraftPanel extends javax.swing.JPanel {
}
public void loadBooster(DraftPickView draftPickView) {
logLastPick(draftPickView);
// upper area that shows the picks
loadCardsToPickedCardsArea(draftPickView.getPicks());
this.draftPicks.clearCardEventListeners();
this.draftPicks.addCardEventListener(new Listener<Event> () {
@Override
public void event(Event event) {
if (event.getEventName().equals("show-popup-menu")) {
if (event.getSource() != null) {
// Popup Menu Card
cardIdPopupMenu = ((SimpleCardView)event.getSource()).getId();
popupMenuCardPanel.show(event.getComponent(), event.getxPos(), event.getyPos());
} else {
// Popup Menu area
popupMenuPickedArea.show(event.getComponent(), event.getxPos(), event.getyPos());
}
this.draftPicks.addCardEventListener(new Listener<Event>() {
@Override
public void event(Event event) {
if (event.getEventName().equals("show-popup-menu")) {
if (event.getSource() != null) {
// Popup Menu Card
cardIdPopupMenu = ((SimpleCardView) event.getSource()).getId();
popupMenuCardPanel.show(event.getComponent(), event.getxPos(), event.getyPos());
} else {
// Popup Menu area
popupMenuPickedArea.show(event.getComponent(), event.getxPos(), event.getyPos());
}
}
}
}
);
// lower area that shows the booster
draftBooster.loadBooster(CardsViewUtil.convertSimple(draftPickView.getBooster()), bigCard);
this.draftBooster.clearCardEventListeners();
this.draftBooster.addCardEventListener(
new Listener<Event> () {
@Override
public void event(Event event) {
if (event.getEventName().equals("pick-a-card")) {
SimpleCardView source = (SimpleCardView) event.getSource();
DraftPickView view = session.sendCardPick(draftId, source.getId(), cardsHidden);
if (view != null) {
loadCardsToPickedCardsArea(view.getPicks());
draftBooster.loadBooster(emptyView, bigCard);
Plugins.getInstance().getActionCallback().hidePopup();
setMessage("Waiting for other players");
new Listener<Event>() {
@Override
public void event(Event event) {
if (event.getEventName().equals("pick-a-card")) {
SimpleCardView source = (SimpleCardView) event.getSource();
DraftPickView view = session.sendCardPick(draftId, source.getId(), cardsHidden);
if (view != null) {
loadCardsToPickedCardsArea(view.getPicks());
draftBooster.loadBooster(emptyView, bigCard);
Plugins.getInstance().getActionCallback().hideTooltipPopup();
setMessage("Waiting for other players");
}
}
if (event.getEventName().equals("mark-a-card")) {
SimpleCardView source = (SimpleCardView) event.getSource();
session.sendCardMark(draftId, source.getId());
}
}
if (event.getEventName().equals("mark-a-card")) {
SimpleCardView source = (SimpleCardView) event.getSource();
session.sendCardMark(draftId, source.getId());
}
}
}
);
setMessage("Pick a card");
if (!MageFrame.getInstance().isActive()) {
@ -307,7 +353,7 @@ public class DraftPanel extends javax.swing.JPanel {
private void loadCardsToPickedCardsArea(SimpleCardsView pickedCards) {
this.pickedCards = pickedCards;
for (Map.Entry<UUID,SimpleCardView> entry: pickedCards.entrySet()) {
for (Map.Entry<UUID, SimpleCardView> entry : pickedCards.entrySet()) {
if (!cardsHidden.contains(entry.getKey())) {
pickedCardsShown.put(entry.getKey(), entry.getValue());
}
@ -315,22 +361,22 @@ public class DraftPanel extends javax.swing.JPanel {
draftPicks.loadCards(CardsViewUtil.convertSimple(pickedCardsShown), bigCard, null);
}
private void setTimeout(int s){
int minute = s/60;
int second = s - (minute*60);
private void setTimeout(int s) {
int minute = s / 60;
int second = s - (minute * 60);
String text;
if(minute < 10){
if (minute < 10) {
text = "0" + Integer.toString(minute) + ":";
}else{
} else {
text = Integer.toString(minute) + ":";
}
if(second < 10){
if (second < 10) {
text = text + "0" + Integer.toString(second);
}else{
} else {
text = text + Integer.toString(second);
}
this.txtTimeRemaining.setText(text);
if (s==6 && !draftBooster.isEmptyGrid()) {
if (s == 6 && !draftBooster.isEmptyGrid()) {
AudioManager.playOnCountdown1();
}
}
@ -341,7 +387,7 @@ public class DraftPanel extends javax.swing.JPanel {
c = c.getParent();
}
if (c != null) {
((DraftPane)c).removeDraft();
((DraftPane) c).removeDraft();
}
}
@ -375,7 +421,6 @@ public class DraftPanel extends javax.swing.JPanel {
});
// popupMenuPickedArea.addSeparator();
}
private void addPopupMenuCardPanel() {
@ -394,7 +439,6 @@ public class DraftPanel extends javax.swing.JPanel {
});
// popupMenuCardPanel.addSeparator();
}
private void hideThisCard(UUID card) {
@ -413,10 +457,97 @@ public class DraftPanel extends javax.swing.JPanel {
draftPicks.loadCards(CardsViewUtil.convertSimple(pickedCardsShown), bigCard, null);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// Log the last card picked into the draft log together with booster
// contents.
// We don't get any event when the card is selected due to timeout
// that's why instead of proactively logging our pick we instead
// log *last* pick from the list of picks.
// To make this possible we cache the list of cards from the
// previous booster and it's sequence number (pack number / pick number)
// in fields currentBooster and currentBoosterHeader.
private void logLastPick(DraftPickView pickView) {
if (!isLogging()) {
return;
}
if (currentBooster != null) {
String lastPick = getCardName(getLastPick(pickView.getPicks().values()));
if (lastPick != null && currentBooster.length > 1) {
logPick(lastPick);
}
currentBooster = null;
}
setCurrentBoosterForLog(pickView.getBooster());
if (currentBooster.length == 1) {
logPick(currentBooster[0]);
}
}
private static boolean isLogging() {
String autoSave = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_DRAFT_LOG_AUTO_SAVE, "true");
return autoSave.equals("true");
}
private void setCurrentBoosterForLog(SimpleCardsView booster) {
LinkedList<String> cards = new LinkedList<>();
for (SimpleCardView simple : booster.values()) {
String cardName = getCardName(simple);
if (cardName != null) {
cards.add(cardName);
}
}
currentBoosterHeader = "Pack " + packNo + " pick " + pickNo + ":\n";
currentBooster = cards.toArray(new String[cards.size()]);
}
private void logPick(String pick) {
StringBuilder b = new StringBuilder();
b.append(currentBoosterHeader);
for (String name : currentBooster) {
b.append(pick.equals(name) ? "--> " : " ");
b.append(name);
b.append('\n');
}
b.append('\n');
appendToDraftLog(b.toString());
}
private Path pathToDraftLog() {
File saveDir = new File("gamelogs");
if (!saveDir.exists()) {
saveDir.mkdirs();
}
return new File(saveDir, logFilename).toPath();
}
private void appendToDraftLog(String data) {
try {
Files.write(pathToDraftLog(), data.getBytes(), StandardOpenOption.APPEND);
} catch (IOException ex) {
logger.error(null, ex);
}
}
private static SimpleCardView getLastPick(Collection<SimpleCardView> picks) {
SimpleCardView last = null;
for (SimpleCardView pick : picks) {
last = pick;
}
return last;
}
private static String getCardName(SimpleCardView card) {
if (card == null) {
return null;
}
CardInfo cardInfo = CardRepository.instance.findCard(card.getExpansionSetCode(), card.getCardNumber());
return cardInfo != null ? cardInfo.getName() : null;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents

View file

@ -42,12 +42,14 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import mage.client.MageFrame;
import mage.client.chat.ChatPanel;
import mage.client.chat.ChatPanelBasic;
import mage.client.components.MageTextArea;
import mage.client.dialog.MageDialog;
import mage.client.util.audio.AudioManager;
import mage.client.util.gui.ArrowBuilder;
import mage.constants.Constants;
import static mage.constants.Constants.Option.ORIGINAL_ID;
import static mage.constants.Constants.Option.SECOND_MESSAGE;
import static mage.constants.Constants.Option.SPECIAL_BUTTON;
import mage.constants.PlayerAction;
import mage.remote.Session;
import org.apache.log4j.Logger;
@ -69,7 +71,7 @@ public class FeedbackPanel extends javax.swing.JPanel {
private Session session;
private FeedbackMode mode;
private MageDialog connectedDialog;
private ChatPanel connectedChatPanel;
private ChatPanelBasic connectedChatPanel;
private int lastMessageId;
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
@ -85,6 +87,7 @@ public class FeedbackPanel extends javax.swing.JPanel {
public void init(UUID gameId) {
this.gameId = gameId;
session = MageFrame.getSession();
helper.init(gameId);
}
public void getFeedback(FeedbackMode mode, String message, boolean special, Map<String, Serializable> options, int messageId) {
@ -95,61 +98,42 @@ public class FeedbackPanel extends javax.swing.JPanel {
}
this.lastMessageId = messageId;
}
this.lblMessage.setText(message);
this.helper.setMessage(message);
this.helper.setBasicMessage(message);
this.helper.setOriginalId(null); // reference to the feedback causing ability
String lblText = addAdditionalText(message, options);
this.helper.setTextArea(lblText);
this.lblMessage.setText(lblText);
this.mode = mode;
switch (this.mode) {
case INFORM:
this.btnLeft.setVisible(false);
this.btnRight.setVisible(false);
this.helper.setState("", false, "", false);
setButtonState("", "", mode);
break;
case QUESTION:
this.btnLeft.setVisible(true);
this.btnLeft.setText("Yes");
this.btnRight.setVisible(true);
this.btnRight.setText("No");
this.helper.setState("Yes", true, "No", true);
setButtonState("Yes", "No", mode);
if (options != null && options.containsKey(ORIGINAL_ID)) {
this.helper.setOriginalId((UUID) options.get(ORIGINAL_ID));
}
break;
case CONFIRM:
this.btnLeft.setVisible(true);
this.btnLeft.setText("OK");
this.btnRight.setVisible(true);
this.btnRight.setText("Cancel");
this.helper.setState("Ok", true, "Cancel", true);
setButtonState("OK", "Cancel", mode);
break;
case CANCEL:
this.btnLeft.setVisible(false);
this.btnRight.setVisible(true);
this.btnRight.setText("Cancel");
this.helper.setState("", false, "Cancel", true);
setButtonState("", "Cancel", mode);
this.helper.setUndoEnabled(false);
break;
case SELECT:
this.btnLeft.setVisible(false);
this.btnRight.setVisible(true);
this.btnRight.setText("Done");
this.helper.setState("", false, "Done", true);
setButtonState("", "Done", mode);
break;
case END:
this.btnLeft.setVisible(false);
this.btnRight.setVisible(true);
this.btnRight.setText("Close game");
this.helper.setState("", false, "Close game", true);
setButtonState("", "Close game", mode);
ArrowBuilder.getBuilder().removeAllArrows(gameId);
endWithTimeout();
break;
}
if (options != null && options.containsKey(Constants.Option.SPECIAL_BUTTON)) {
String specialText = (String) options.get(Constants.Option.SPECIAL_BUTTON);
this.btnSpecial.setVisible(true);
this.btnSpecial.setText(specialText);
this.helper.setSpecial(specialText, true);
if (options != null && options.containsKey(SPECIAL_BUTTON)) {
this.setSpecial((String) options.get(SPECIAL_BUTTON), true);
} else {
this.btnSpecial.setVisible(special);
this.btnSpecial.setText("Special");
this.helper.setSpecial("Special", special);
this.setSpecial("Special", special);
}
requestFocusIfPossible();
@ -162,6 +146,32 @@ public class FeedbackPanel extends javax.swing.JPanel {
this.helper.setVisible(true);
}
private void setButtonState(String leftText, String rightText, FeedbackMode mode) {
btnLeft.setVisible(!leftText.isEmpty());
btnLeft.setText(leftText);
btnRight.setVisible(!rightText.isEmpty());
btnRight.setText(rightText);
this.helper.setState(leftText, !leftText.isEmpty(), rightText, !rightText.isEmpty(), mode);
}
private String addAdditionalText(String message, Map<String, Serializable> options) {
if (options != null && options.containsKey(SECOND_MESSAGE)) {
return message + getSmallText((String) options.get(SECOND_MESSAGE));
} else {
return message;
}
}
protected String getSmallText(String text) {
return "<div style='font-size:11pt'>" + text + "</div>";
}
private void setSpecial(String text, boolean visible) {
this.btnSpecial.setText(text);
this.btnSpecial.setVisible(visible);
this.helper.setSpecial(text, visible);
}
/**
* Close game window by pressing OK button after 8 seconds
*/
@ -313,7 +323,7 @@ public class FeedbackPanel extends javax.swing.JPanel {
return this.mode;
}
public void setConnectedChatPanel(ChatPanel chatPanel) {
public void setConnectedChatPanel(ChatPanelBasic chatPanel) {
this.connectedChatPanel = chatPanel;
}

View file

@ -66,8 +66,10 @@ import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.SwingWorker;
import javax.swing.border.Border;
@ -80,7 +82,7 @@ import mage.cards.action.ActionCallback;
import mage.choices.Choice;
import mage.client.MageFrame;
import mage.client.cards.BigCard;
import mage.client.chat.ChatPanel;
import mage.client.chat.ChatPanelBasic;
import mage.client.combat.CombatManager;
import mage.client.components.HoverButton;
import mage.client.components.MageComponents;
@ -100,7 +102,9 @@ import mage.client.plugins.adapters.MageActionCallback;
import mage.client.plugins.impl.Plugins;
import mage.client.util.CardsViewUtil;
import mage.client.util.Config;
import mage.client.util.Event;
import mage.client.util.GameManager;
import mage.client.util.Listener;
import mage.client.util.audio.AudioManager;
import mage.client.util.gui.ArrowBuilder;
import mage.client.util.gui.MageDialogState;
@ -118,7 +122,13 @@ import static mage.constants.PhaseStep.FIRST_COMBAT_DAMAGE;
import static mage.constants.PhaseStep.UNTAP;
import static mage.constants.PhaseStep.UPKEEP;
import mage.constants.PlayerAction;
import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_ABILITY_FIRST;
import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_ABILITY_LAST;
import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_NAME_FIRST;
import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_NAME_LAST;
import static mage.constants.PlayerAction.TRIGGER_AUTO_ORDER_RESET_ALL;
import mage.constants.Zone;
import mage.game.events.PlayerQueryEvent;
import mage.remote.Session;
import mage.view.AbilityPickerView;
import mage.view.CardView;
@ -131,6 +141,7 @@ import mage.view.PlayerView;
import mage.view.RevealedView;
import mage.view.SimpleCardsView;
import org.apache.log4j.Logger;
import org.mage.card.arcane.CardPanel;
import org.mage.plugins.card.utils.impl.ImageManagerImpl;
/**
@ -143,6 +154,13 @@ public final class GamePanel extends javax.swing.JPanel {
private static final String YOUR_HAND = "Your hand";
private static final int X_PHASE_WIDTH = 55;
private static final int STACK_MIN_CARDS_OFFSET_Y = 7;
private static final String CMD_AUTO_ORDER_FIRST = "cmdAutoOrderFirst";
private static final String CMD_AUTO_ORDER_LAST = "cmdAutoOrderLast";
private static final String CMD_AUTO_ORDER_NAME_FIRST = "cmdAutoOrderNameFirst";
private static final String CMD_AUTO_ORDER_NAME_LAST = "cmdAutoOrderNameLast";
private static final String CMD_AUTO_ORDER_RESET_ALL = "cmdAutoOrderResetAll";
private final Map<UUID, PlayAreaPanel> players = new HashMap<>();
// non modal frames
@ -174,9 +192,22 @@ public final class GamePanel extends javax.swing.JPanel {
private MageDialogState choiceWindowState;
private enum PopUpMenuType {
TRIGGER_ORDER
}
// CardView popupMenu was invoked last
private CardView cardViewPopupMenu;
// popup menu for triggered abilities order
private JPopupMenu popupMenuTriggerOrder;
public GamePanel() {
initComponents();
initPopupMenuTriggerOrder();
//this.add(popupMenuTriggerOrder);
pickNumber = new PickNumberDialog();
MageFrame.getDesktop().add(pickNumber, JLayeredPane.MODAL_LAYER);
@ -281,7 +312,7 @@ public final class GamePanel extends javax.swing.JPanel {
pickTargetDialog.cleanUp();
pickTargetDialog.removeDialog();
}
Plugins.getInstance().getActionCallback().hidePopup();
Plugins.getInstance().getActionCallback().hideTooltipPopup();
try {
Component popupContainer = MageFrame.getUI().getComponent(MageComponents.POPUP_CONTAINER);
popupContainer.setVisible(false);
@ -957,31 +988,37 @@ public final class GamePanel extends javax.swing.JPanel {
* @param messageId
*/
public void pickTarget(String message, CardsView cardView, GameView gameView, Set<UUID> targets, boolean required, Map<String, Serializable> options, int messageId) {
ShowCardsDialog dialog = null;
if (options != null && options.containsKey("targetZone")) {
if (Zone.HAND.equals(options.get("targetZone"))) { // mark selectable target cards in hand
List<UUID> choosen = null;
if (options.containsKey("chosen")) {
choosen = (List<UUID>) options.get("chosen");
}
for (CardView card : gameView.getHand().values()) {
if (targets == null || targets.isEmpty()) {
card.setPlayable(false);
card.setChoosable(true);
} else if (targets.contains(card.getId())) {
card.setPlayable(false);
card.setChoosable(true);
PopUpMenuType popupMenuType = null;
if (options != null) {
if (options.containsKey("targetZone")) {
if (Zone.HAND.equals(options.get("targetZone"))) { // mark selectable target cards in hand
List<UUID> choosen = null;
if (options.containsKey("chosen")) {
choosen = (List<UUID>) options.get("chosen");
}
if (choosen != null && choosen.contains(card.getId())) {
card.setSelected(true);
for (CardView card : gameView.getHand().values()) {
if (targets == null || targets.isEmpty()) {
card.setPlayable(false);
card.setChoosable(true);
} else if (targets.contains(card.getId())) {
card.setPlayable(false);
card.setChoosable(true);
}
if (choosen != null && choosen.contains(card.getId())) {
card.setSelected(true);
}
}
}
}
if (options.containsKey("queryType") && PlayerQueryEvent.QueryType.PICK_ABILITY.equals(options.get("queryType"))) {
popupMenuType = PopUpMenuType.TRIGGER_ORDER;
}
}
updateGame(gameView);
Map<String, Serializable> options0 = options == null ? new HashMap<String, Serializable>() : options;
ShowCardsDialog dialog = null;
if (cardView != null && cardView.size() > 0) {
dialog = showCards(message, cardView, required, options0);
dialog = showCards(message, cardView, required, options0, popupMenuType);
options0.put("dialog", dialog);
}
this.feedbackPanel.getFeedback(required ? FeedbackMode.INFORM : FeedbackMode.CANCEL, message, gameView.getSpecial(), options0, messageId);
@ -1066,10 +1103,14 @@ public final class GamePanel extends javax.swing.JPanel {
((MageActionCallback) callback).hideGameUpdate(gameId);
}
private ShowCardsDialog showCards(String title, CardsView cards, boolean required, Map<String, Serializable> options) {
private ShowCardsDialog showCards(String title, CardsView cards, boolean required, Map<String, Serializable> options, PopUpMenuType popupMenuType) {
hideAll();
ShowCardsDialog showCards = new ShowCardsDialog();
showCards.loadCards(title, cards, bigCard, Config.dimensionsEnlarged, gameId, required, options);
JPopupMenu popupMenu = null;
if (PopUpMenuType.TRIGGER_ORDER.equals(popupMenuType)) {
popupMenu = popupMenuTriggerOrder;
}
showCards.loadCards(title, cards, bigCard, Config.dimensionsEnlarged, gameId, required, options, popupMenu, getShowCardsEventListener(showCards));
return showCards;
}
@ -1163,12 +1204,12 @@ public final class GamePanel extends javax.swing.JPanel {
btnSkipForward = new javax.swing.JButton();
btnPreviousPlay = new javax.swing.JButton();
pnlBattlefield = new javax.swing.JPanel();
gameChatPanel = new mage.client.chat.ChatPanel();
gameChatPanel.useExtendedView(ChatPanel.VIEW_MODE.GAME);
userChatPanel = new mage.client.chat.ChatPanel();
gameChatPanel = new mage.client.chat.ChatPanelBasic();
gameChatPanel.useExtendedView(ChatPanelBasic.VIEW_MODE.GAME);
userChatPanel = new mage.client.chat.ChatPanelBasic();
userChatPanel.setParentChat(gameChatPanel);
userChatPanel.useExtendedView(ChatPanel.VIEW_MODE.CHAT);
userChatPanel.setChatType(ChatPanel.ChatType.GAME);
userChatPanel.useExtendedView(ChatPanelBasic.VIEW_MODE.CHAT);
userChatPanel.setChatType(ChatPanelBasic.ChatType.GAME);
gameChatPanel.setConnectedChat(userChatPanel);
gameChatPanel.disableInput();
gameChatPanel.setMinimumSize(new java.awt.Dimension(100, 48));
@ -1942,6 +1983,106 @@ public final class GamePanel extends javax.swing.JPanel {
hoverButtons.put(name, button);
}
// Event listener for the ShowCardsDialog
private Listener<Event> getShowCardsEventListener(final ShowCardsDialog dialog) {
return new Listener<Event>() {
@Override
public void event(Event event) {
if (event.getEventName().equals("show-popup-menu")) {
if (event.getComponent() != null && event.getComponent() instanceof CardPanel) {
JPopupMenu menu = ((CardPanel) event.getComponent()).getPopupMenu();
if (menu != null) {
cardViewPopupMenu = ((CardView) event.getSource());
menu.show(event.getComponent(), event.getxPos(), event.getyPos());
}
}
}
if (event.getEventName().equals("action-consumed")) {
dialog.removeDialog();
}
}
};
}
public void handleTriggerOrderPopupMenuEvent(ActionEvent e) {
UUID abilityId = null;
String abilityRuleText = null;
if (cardViewPopupMenu instanceof CardView && cardViewPopupMenu.getAbility() != null) {
abilityId = cardViewPopupMenu.getAbility().getId();
if (!cardViewPopupMenu.getAbility().getRules().isEmpty()
&& !cardViewPopupMenu.getAbility().getRules().get(0).isEmpty()) {
abilityRuleText = cardViewPopupMenu.getAbility().getRules().get(0);
}
}
switch (e.getActionCommand()) {
case CMD_AUTO_ORDER_FIRST:
session.sendPlayerAction(TRIGGER_AUTO_ORDER_ABILITY_FIRST, gameId, abilityId);
session.sendPlayerUUID(gameId, abilityId);
break;
case CMD_AUTO_ORDER_LAST:
session.sendPlayerAction(TRIGGER_AUTO_ORDER_ABILITY_LAST, gameId, abilityId);
session.sendPlayerUUID(gameId, null); // Don't use this but refresh the displayed abilities
break;
case CMD_AUTO_ORDER_NAME_FIRST:
if (abilityRuleText != null) {
session.sendPlayerAction(TRIGGER_AUTO_ORDER_NAME_FIRST, gameId, abilityRuleText);
session.sendPlayerUUID(gameId, abilityId);
}
break;
case CMD_AUTO_ORDER_NAME_LAST:
if (abilityRuleText != null) {
session.sendPlayerAction(TRIGGER_AUTO_ORDER_NAME_LAST, gameId, abilityRuleText);
session.sendPlayerUUID(gameId, null); // Don't use this but refresh the displayed abilities
}
break;
case CMD_AUTO_ORDER_RESET_ALL:
session.sendPlayerAction(TRIGGER_AUTO_ORDER_RESET_ALL, gameId, null);
break;
}
for (ShowCardsDialog dialog : pickTarget) {
dialog.removeDialog();
}
}
private void initPopupMenuTriggerOrder() {
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleTriggerOrderPopupMenuEvent(e);
}
};
popupMenuTriggerOrder = new JPopupMenu();
// String tooltipText = "";
JMenuItem menuItem;
menuItem = new JMenuItem("Put this ability always first on the stack");
menuItem.setActionCommand(CMD_AUTO_ORDER_FIRST);
menuItem.addActionListener(actionListener);
popupMenuTriggerOrder.add(menuItem);
menuItem = new JMenuItem("Put this ability always last on the stack");
menuItem.setActionCommand(CMD_AUTO_ORDER_LAST);
menuItem.addActionListener(actionListener);
popupMenuTriggerOrder.add(menuItem);
menuItem = new JMenuItem("Put all abilities with that rule text always first on the stack");
menuItem.setActionCommand(CMD_AUTO_ORDER_NAME_FIRST);
menuItem.addActionListener(actionListener);
popupMenuTriggerOrder.add(menuItem);
menuItem = new JMenuItem("Put all abilities with that rule text always last on the stack");
menuItem.setActionCommand(CMD_AUTO_ORDER_NAME_LAST);
menuItem.addActionListener(actionListener);
popupMenuTriggerOrder.add(menuItem);
menuItem = new JMenuItem("Reset all order settings for triggered abilities");
menuItem.setActionCommand(CMD_AUTO_ORDER_RESET_ALL);
menuItem.addActionListener(actionListener);
popupMenuTriggerOrder.add(menuItem);
}
public String getGameLog() {
return gameChatPanel.getText();
}
@ -1984,9 +2125,9 @@ public final class GamePanel extends javax.swing.JPanel {
private javax.swing.JButton btnStopWatching;
private mage.client.chat.ChatPanel gameChatPanel;
private mage.client.chat.ChatPanelBasic gameChatPanel;
private mage.client.game.FeedbackPanel feedbackPanel;
private mage.client.chat.ChatPanel userChatPanel;
private mage.client.chat.ChatPanelBasic userChatPanel;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSplitPane jSplitPane0;

View file

@ -28,17 +28,34 @@
package mage.client.game;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.UUID;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import mage.client.MageFrame;
import mage.client.components.MageTextArea;
import mage.client.game.FeedbackPanel.FeedbackMode;
import static mage.client.game.FeedbackPanel.FeedbackMode.QUESTION;
import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_ID_NO;
import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_ID_YES;
import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_RESET_ALL;
import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_TEXT_NO;
import static mage.constants.PlayerAction.REQUEST_AUTO_ANSWER_TEXT_YES;
import mage.remote.Session;
/**
* Panel with buttons that copy the state of feedback panel.
@ -64,12 +81,34 @@ public class HelperPanel extends JPanel {
private final int defaultDismissTimeout = ToolTipManager.sharedInstance().getDismissDelay();
private final Object tooltipBackground = UIManager.get("info");
private static final String CMD_AUTO_ANSWER_ID_YES = "cmdAutoAnswerIdYes";
private static final String CMD_AUTO_ANSWER_ID_NO = "cmdAutoAnswerIdNo";
private static final String CMD_AUTO_ANSWER_NAME_YES = "cmdAutoAnswerNameYes";
private static final String CMD_AUTO_ANSWER_NAME_NO = "cmdAutoAnswerNameNo";
private static final String CMD_AUTO_ANSWER_RESET_ALL = "cmdAutoAnswerResetAll";
// popup menu for set automatic answers
private JPopupMenu popupMenuAskYes;
private JPopupMenu popupMenuAskNo;
// originalId of feedback causing ability
private UUID originalId;
private String message;
private UUID gameId;
private Session session;
public HelperPanel() {
initComponents();
}
private void initComponents() {
public void init(UUID gameId) {
this.gameId = gameId;
session = MageFrame.getSession();
}
private void initComponents() {
initPopupMenuTriggerOrder();
setBackground(new Color(0, 0, 0, 100));
//setLayout(new GridBagLayout());
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
@ -108,72 +147,44 @@ public class HelperPanel extends JPanel {
btnUndo.setVisible(false);
container.add(btnUndo);
btnLeft.addActionListener(new java.awt.event.ActionListener() {
MouseListener checkPopupAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
checkPopupMenu(me);
}
@Override
public void mouseReleased(MouseEvent me) {
checkPopupMenu(me);
}
};
btnLeft.addMouseListener(checkPopupAdapter);
btnLeft.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (linkLeft != null) {
{
Thread worker = new Thread() {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setState("", false, "", false);
setSpecial("", false);
linkLeft.doClick();
}
});
}
};
worker.start();
}
clickButton(linkLeft);
}
}
});
btnRight.addActionListener(new java.awt.event.ActionListener() {
btnRight.addMouseListener(checkPopupAdapter);
btnRight.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (linkRight != null) {
Thread worker = new Thread() {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setState("", false, "", false);
setSpecial("", false);
linkRight.doClick();
}
});
}
};
worker.start();
clickButton(linkRight);
}
}
});
btnSpecial.addActionListener(new java.awt.event.ActionListener() {
btnSpecial.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (linkSpecial != null) {
{
Thread worker = new Thread() {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setState("", false, "", false);
setSpecial("", false);
linkSpecial.doClick();
}
});
}
};
worker.start();
}
clickButton(linkSpecial);
}
}
});
@ -200,7 +211,7 @@ public class HelperPanel extends JPanel {
}
});
// sets a darker background and higher simiss time fpr tooltip in the feedback / helper panel
// sets a darker background and higher simiss time fur tooltip in the feedback / helper panel
textArea.addMouseListener(new MouseAdapter() {
@Override
@ -217,15 +228,50 @@ public class HelperPanel extends JPanel {
});
}
public void setState(String txtLeft, boolean leftVisible, String txtRight, boolean rightVisible) {
private void checkPopupMenu(MouseEvent me) {
if (me.isPopupTrigger()
&& originalId != null) { // only Yes/No requests from abilities can be automated
JButton source = (JButton) me.getSource();
if (source.getActionCommand().startsWith(QUESTION.toString())) {
showPopupMenu(me.getComponent(), source.getActionCommand());
me.consume();
}
}
}
private void clickButton(final JButton button) {
Thread worker = new Thread() {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setState("", false, "", false, null);
setSpecial("", false);
button.doClick();
}
});
}
};
worker.start();
}
public void setState(String txtLeft, boolean leftVisible, String txtRight, boolean rightVisible, FeedbackMode mode) {
this.btnLeft.setVisible(leftVisible);
if (!txtLeft.isEmpty()) {
this.btnLeft.setText(txtLeft);
if (mode != null) {
this.btnLeft.setActionCommand(mode.toString() + txtLeft);
}
}
this.btnRight.setVisible(rightVisible);
if (!txtRight.isEmpty()) {
this.btnRight.setText(txtRight);
if (mode != null) {
this.btnRight.setActionCommand(mode.toString() + txtRight);
}
}
}
public void setSpecial(String txtSpecial, boolean specialVisible) {
@ -251,25 +297,116 @@ public class HelperPanel extends JPanel {
this.linkUndo = undo;
}
public void setMessage(String message) {
// if (message.startsWith("Use alternative cost")) {
// message = "Use alternative cost?";
// } else if (message.contains("Use ")) {
// if (message.length() < this.getWidth() / 10) {
// message = getSmallText(message);
// } else {
// message = "Use ability?" + getSmallText(message.substring(0, this.getWidth() / 10));
// }
// }
textArea.setText(message, this.getWidth());
public void setOriginalId(UUID originalId) {
this.originalId = originalId;
}
protected String getSmallText(String text) {
return "<div style='font-size:11pt'>" + text + "</div>";
public void setBasicMessage(String message) {
this.message = message;
this.textArea.setText(message, this.getWidth());
}
public void setTextArea(String message) {
this.textArea.setText(message, this.getWidth());
}
@Override
public void requestFocus() {
this.btnRight.requestFocus();
}
private void initPopupMenuTriggerOrder() {
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleAutoAnswerPopupMenuEvent(e);
}
};
popupMenuAskYes = new JPopupMenu();
popupMenuAskNo = new JPopupMenu();
// String tooltipText = "";
JMenuItem menuItem;
menuItem = new JMenuItem("Always Yes for the same text and ability");
menuItem.setActionCommand(CMD_AUTO_ANSWER_ID_YES);
menuItem.addActionListener(actionListener);
menuItem.setToolTipText("<HTML>If the same question from the same ability would<br/>be asked again, it's automatically answered with <b>Yes</b>.");
popupMenuAskYes.add(menuItem);
menuItem = new JMenuItem("Always No for the same text and ability");
menuItem.setActionCommand(CMD_AUTO_ANSWER_ID_NO);
menuItem.setToolTipText("<HTML>If the same question from the same ability would<br/>be asked again, it's automatically answered with <b>No</b>.");
menuItem.addActionListener(actionListener);
popupMenuAskNo.add(menuItem);
menuItem = new JMenuItem("Always Yes for the same text");
menuItem.setActionCommand(CMD_AUTO_ANSWER_NAME_YES);
menuItem.setToolTipText("<HTML>If the same question would be asked again (regardless from which source),<br/> it's automatically answered with <b>Yes</b>.");
menuItem.addActionListener(actionListener);
popupMenuAskYes.add(menuItem);
menuItem = new JMenuItem("Always No for the same text");
menuItem.setActionCommand(CMD_AUTO_ANSWER_NAME_NO);
menuItem.setToolTipText("<HTML>If the same question would be asked again (regardless from which source),<br/> it's automatically answered with <b>No</b>.");
menuItem.addActionListener(actionListener);
popupMenuAskNo.add(menuItem);
menuItem = new JMenuItem("Delete all automatic Yes/No settings");
menuItem.setActionCommand(CMD_AUTO_ANSWER_RESET_ALL);
menuItem.addActionListener(actionListener);
popupMenuAskYes.add(menuItem);
menuItem = new JMenuItem("Delete all automatic Yes/No settings");
menuItem.setActionCommand(CMD_AUTO_ANSWER_RESET_ALL);
menuItem.addActionListener(actionListener);
popupMenuAskNo.add(menuItem);
}
public void handleAutoAnswerPopupMenuEvent(ActionEvent e) {
switch (e.getActionCommand()) {
case CMD_AUTO_ANSWER_ID_YES:
session.sendPlayerAction(REQUEST_AUTO_ANSWER_ID_YES, gameId, originalId.toString() + "#" + message);
clickButton(btnLeft);
break;
case CMD_AUTO_ANSWER_ID_NO:
session.sendPlayerAction(REQUEST_AUTO_ANSWER_ID_NO, gameId, originalId.toString() + "#" + message);
clickButton(btnRight);
break;
case CMD_AUTO_ANSWER_NAME_YES:
session.sendPlayerAction(REQUEST_AUTO_ANSWER_TEXT_YES, gameId, message);
clickButton(btnLeft);
break;
case CMD_AUTO_ANSWER_NAME_NO:
session.sendPlayerAction(REQUEST_AUTO_ANSWER_TEXT_NO, gameId, message);
clickButton(btnRight);
break;
case CMD_AUTO_ANSWER_RESET_ALL:
session.sendPlayerAction(REQUEST_AUTO_ANSWER_RESET_ALL, gameId, null);
break;
}
}
private void showPopupMenu(Component callingComponent, String actionCommand) {
// Get the location of the point 'on the screen'
Point p = callingComponent.getLocationOnScreen();
// Show the JPopupMenu via program
// Parameter desc
// ----------------
// this - represents current frame
// 0,0 is the co ordinate where the popup
// is shown
JPopupMenu menu;
if (actionCommand.endsWith("Yes")) {
menu = popupMenuAskYes;
} else {
menu = popupMenuAskNo;
}
menu.show(this, 0, 0);
// Now set the location of the JPopupMenu
// This location is relative to the screen
menu.setLocation(p.x, p.y + callingComponent.getHeight());
}
}

View file

@ -278,6 +278,30 @@ public class PlayAreaPanel extends javax.swing.JPanel {
}
});
menuItem = new JMenuItem("Triggered abilities - reset auto stack order");
menuItem.setMnemonic(KeyEvent.VK_T);
menuItem.setToolTipText("Deletes all triggered ability order settings you added during the game.");
automaticConfirmsMenu.add(menuItem);
// Reset the replacement effcts that were auto selected for the game
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gamePanel.getSession().sendPlayerAction(PlayerAction.TRIGGER_AUTO_ORDER_RESET_ALL, gameId, null);
}
});
menuItem = new JMenuItem("Use requests - reset automatic answers");
menuItem.setMnemonic(KeyEvent.VK_T);
menuItem.setToolTipText("Deletes all defined automatic answers for Yes/No usage requests.");
automaticConfirmsMenu.add(menuItem);
// Reset the replacement effcts that were auto selected for the game
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gamePanel.getSession().sendPlayerAction(PlayerAction.REQUEST_AUTO_ANSWER_RESET_ALL, gameId, null);
}
});
JMenu handCardsMenu = new JMenu("Cards on hand");
handCardsMenu.setMnemonic(KeyEvent.VK_H);
popupMenu.add(handCardsMenu);

View file

@ -69,6 +69,9 @@ import mage.client.util.ImageHelper;
import mage.client.util.gui.BufferedImageBuilder;
import mage.client.util.gui.countryBox.CountryUtil;
import mage.components.ImagePanel;
import static mage.constants.Constants.DEFAULT_AVATAR_ID;
import static mage.constants.Constants.MAX_AVATAR_ID;
import static mage.constants.Constants.MIN_AVATAR_ID;
import mage.constants.ManaType;
import mage.remote.Session;
import mage.utils.timer.PriorityTimer;
@ -92,7 +95,7 @@ public class PlayerPanelExt extends javax.swing.JPanel {
private static final int AVATAR_COUNT = 77;
private static final String DEFAULT_AVATAR_PATH = "/avatars/51.jpg";
private static final String DEFAULT_AVATAR_PATH = "/avatars/" + DEFAULT_AVATAR_ID + ".jpg";
private static final int PANEL_WIDTH = 94;
private static final int PANEL_HEIGHT = 242;
@ -105,6 +108,7 @@ public class PlayerPanelExt extends javax.swing.JPanel {
private int avatarId = -1;
private String flagName;
private String basicTooltipText;
private PriorityTimer timer;
@ -156,25 +160,7 @@ public class PlayerPanelExt extends javax.swing.JPanel {
public void update(PlayerView player) {
this.player = player;
if (flagName == null) { // do only once
avatar.setText(this.player.getName());
if (!player.getUserData().getFlagName().equals(flagName)) {
flagName = player.getUserData().getFlagName();
this.avatar.setTopTextImage(CountryUtil.getCountryFlagIcon(flagName).getImage());
}
// TODO: Add the wins to the tooltiptext of the avatar
String countryname = CountryUtil.getCountryName(flagName);
if (countryname == null) {
countryname = "Unknown";
}
String tooltip = "<HTML>Name: " + player.getName() + "<br/>Country: " + countryname;
avatar.setToolTipText(tooltip);
avatar.repaint();
// used if avatar image can't be used
this.btnPlayer.setText(player.getName());
this.btnPlayer.setToolTipText(tooltip);
}
updateAvatar();
int playerLife = player.getLife();
if (playerLife > 99) {
Font font = lifeLabel.getFont();
@ -238,8 +224,8 @@ public class PlayerPanelExt extends javax.swing.JPanel {
if (!MageFrame.isLite()) {
int id = player.getUserData().getAvatarId();
if (id <= 0) {
id = PreferencesDialog.DEFAULT_AVATAR_ID;
if (!(id >= 1000) && (id <= 0 || (id <= MIN_AVATAR_ID && id > MAX_AVATAR_ID))) {
id = DEFAULT_AVATAR_ID;
}
if (id != avatarId) {
avatarId = id;
@ -284,6 +270,39 @@ public class PlayerPanelExt extends javax.swing.JPanel {
update(player.getManaPool());
}
/**
* Updates the avatar image and tooltip text
*/
private void updateAvatar() {
if (flagName == null) { // do only once
avatar.setText(this.player.getName());
if (!player.getUserData().getFlagName().equals(flagName)) {
flagName = player.getUserData().getFlagName();
this.avatar.setTopTextImage(CountryUtil.getCountryFlagIcon(flagName).getImage());
}
// TODO: Add the wins to the tooltiptext of the avatar
String countryname = CountryUtil.getCountryName(flagName);
if (countryname == null) {
countryname = "Unknown";
}
basicTooltipText = "<HTML>Name: " + player.getName()
+ "<br/>Country: " + countryname
+ "<br/>Deck hash code: " + player.getDeckHashCode()
+ "<br/>Wins: " + player.getWins() + " of " + player.getWinsNeeded() + " (to win the match)";
}
// Extend tooltip
StringBuilder tooltipText = new StringBuilder(basicTooltipText);
if (player.getExperience() > 0) {
tooltipText.append("<br/>Experience counters: ").append(player.getExperience());
}
avatar.setToolTipText(tooltipText.toString());
avatar.repaint();
// used if avatar image can't be used
this.btnPlayer.setText(player.getName());
this.btnPlayer.setToolTipText(tooltipText.toString());
}
private String getPriorityTimeLeftString(PlayerView player) {
int priorityTimeLeft = player.getPriorityTimeLeft();
return getPriorityTimeLeftString(priorityTimeLeft);
@ -799,7 +818,7 @@ public class PlayerPanelExt extends javax.swing.JPanel {
}
private void btnCommandZoneActionPerformed(java.awt.event.ActionEvent evt) {
DialogManager.getManager(gameId).showEmblemsDialog(CardsViewUtil.convertCommandObject(player.getCommadObjectList()), bigCard, gameId);
DialogManager.getManager(gameId).showEmblemsDialog(CardsViewUtil.convertCommandObject(player.getCommandObjectList()), bigCard, gameId);
}
private void btnExileZoneActionPerformed(java.awt.event.ActionEvent evt) {

View file

@ -65,12 +65,12 @@ public class MageActionCallback implements ActionCallback {
public static final int MIN_X_OFFSET_REQUIRED = 20;
private Popup popup;
private Popup tooltipPopup;
private JPopupMenu jPopupMenu;
private BigCard bigCard;
protected static final DefaultActionCallback defaultCallback = DefaultActionCallback.getInstance();
protected static Session session = MageFrame.getSession();
private CardView popupCard;
private CardView tooltipCard;
private TransferData popupData;
private JComponent cardInfoPane;
private volatile boolean popupTextWindowOpen = false;
@ -92,7 +92,7 @@ public class MageActionCallback implements ActionCallback {
private boolean isDragging;
private Point initialCardPos;
private Point initialMousePos;
private Set<CardPanel> cardPanels = new HashSet<CardPanel>();
private final Set<CardPanel> cardPanels = new HashSet<>();
public MageActionCallback() {
enlargeMode = EnlargeMode.NORMAL;
@ -117,10 +117,10 @@ public class MageActionCallback implements ActionCallback {
@Override
public void mouseEntered(MouseEvent e, final TransferData data) {
hidePopup();
hideTooltipPopup();
cancelTimeout();
this.popupCard = data.card;
this.tooltipCard = data.card;
this.popupData = data;
Component parentComponent = SwingUtilities.getRoot(data.component);
@ -135,10 +135,10 @@ public class MageActionCallback implements ActionCallback {
ArrowUtil.drawArrowsForPairedCards(data, parentPoint);
ArrowUtil.drawArrowsForEnchantPlayers(data, parentPoint);
showPopup(data, parentComponent, parentPoint);
showTooltipPopup(data, parentComponent, parentPoint);
}
private void showPopup(final TransferData data, final Component parentComponent, final Point parentPoint) {
private void showTooltipPopup(final TransferData data, final Component parentComponent, final Point parentPoint) {
if (data.component != null) {
String showTooltips = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_SHOW_TOOLTIPS_ANY_ZONE, "true");
if (showTooltips.equals("false")) {
@ -154,12 +154,12 @@ public class MageActionCallback implements ActionCallback {
}
data.locationOnScreen = data.component.getLocationOnScreen();
}
popup = factory.getPopup(data.component, data.popupText, (int) data.locationOnScreen.getX() + data.popupOffsetX, (int) data.locationOnScreen.getY() + data.popupOffsetY + 40);
popup.show();
tooltipPopup = factory.getPopup(data.component, data.popupText, (int) data.locationOnScreen.getX() + data.popupOffsetX, (int) data.locationOnScreen.getY() + data.popupOffsetY + 40);
tooltipPopup.show();
// hack to get popup to resize to fit text
popup.hide();
popup = factory.getPopup(data.component, data.popupText, (int) data.locationOnScreen.getX() + data.popupOffsetX, (int) data.locationOnScreen.getY() + data.popupOffsetY + 40);
popup.show();
tooltipPopup.hide();
tooltipPopup = factory.getPopup(data.component, data.popupText, (int) data.locationOnScreen.getX() + data.popupOffsetX, (int) data.locationOnScreen.getY() + data.popupOffsetY + 40);
tooltipPopup.show();
} else {
sumbitShowPopupTask(data, parentComponent, parentPoint);
}
@ -171,7 +171,7 @@ public class MageActionCallback implements ActionCallback {
public void run() {
ThreadUtils.sleep(300);
if (popupCard == null || !popupCard.equals(data.card) || session == null || !popupTextWindowOpen || !enlargedWindowState.equals(EnlargedWindowState.CLOSED)) {
if (tooltipCard == null || !tooltipCard.equals(data.card) || session == null || !popupTextWindowOpen || !enlargedWindowState.equals(EnlargedWindowState.CLOSED)) {
return;
}
@ -229,13 +229,15 @@ public class MageActionCallback implements ActionCallback {
initialMousePos = new Point((int) mouse.getX(), (int) mouse.getY());
initialCardPos = data.component.getLocation();
// Closes popup & enlarged view if a card/Permanent is selected
hidePopup();
hideTooltipPopup();
}
@Override
public void mouseReleased(MouseEvent e, TransferData transferData) {
CardPanel card = ((CardPanel) transferData.component);
if (card.getZone() != null && card.getZone().equalsIgnoreCase("hand")) {
if (e.isPopupTrigger() /*&& card.getPopupMenu() != null*/) {
hideTooltipPopup();
} else if (card.getZone() != null && card.getZone().equalsIgnoreCase("hand")) {
int maxXOffset = 0;
if (isDragging) {
Point mouse = new Point(e.getX(), e.getY());
@ -250,13 +252,15 @@ public class MageActionCallback implements ActionCallback {
transferData.component.requestFocusInWindow();
defaultCallback.mouseClicked(e, transferData.gameId, session, transferData.card);
// Closes popup & enlarged view if a card/Permanent is selected
hidePopup();
hideTooltipPopup();
}
e.consume();
} else {
transferData.component.requestFocusInWindow();
defaultCallback.mouseClicked(e, transferData.gameId, session, transferData.card);
// Closes popup & enlarged view if a card/Permanent is selected
hidePopup();
hideTooltipPopup();
e.consume();
}
}
@ -264,7 +268,7 @@ public class MageActionCallback implements ActionCallback {
if (this.startedDragging && prevCard != null && card != null) {
for (Component component : card.getCardArea().getComponents()) {
if (component instanceof CardPanel) {
if (cardPanels.contains(component)) {
if (cardPanels.contains((CardPanel) component)) {
component.setLocation(component.getLocation().x, component.getLocation().y - GO_DOWN_ON_DRAG_Y_OFFSET);
}
}
@ -288,6 +292,10 @@ public class MageActionCallback implements ActionCallback {
// drag'n'drop is allowed for HAND zone only
return;
}
if (!SwingUtilities.isLeftMouseButton(e)) {
// only allow draging with the left mouse button
return;
}
isDragging = true;
prevCard = card;
Point p = card.getCardLocation();
@ -323,7 +331,7 @@ public class MageActionCallback implements ActionCallback {
for (Component component : container.getComponents()) {
if (component instanceof CardPanel) {
if (!component.equals(card)) {
if (!cardPanels.contains(component)) {
if (!cardPanels.contains((CardPanel) component)) {
component.setLocation(component.getLocation().x, component.getLocation().y + GO_DOWN_ON_DRAG_Y_OFFSET);
}
cardPanels.add((CardPanel) component);
@ -405,10 +413,10 @@ public class MageActionCallback implements ActionCallback {
*
*/
@Override
public void hidePopup() {
this.popupCard = null;
if (popup != null) {
popup.hide();
public void hideTooltipPopup() {
this.tooltipCard = null;
if (tooltipPopup != null) {
tooltipPopup.hide();
}
if (jPopupMenu != null) {
jPopupMenu.setVisible(false);
@ -421,7 +429,7 @@ public class MageActionCallback implements ActionCallback {
Component popupContainer = MageFrame.getUI().getComponent(MageComponents.POPUP_CONTAINER);
popupContainer.setVisible(false);
} catch (Exception e2) {
e2.printStackTrace();
logger.warn("Can't set tooltip to visible = false", e2);
}
}
@ -433,7 +441,7 @@ public class MageActionCallback implements ActionCallback {
}
public void hideAll(UUID gameId) {
hidePopup();
hideTooltipPopup();
startHideTimeout();
this.popupTextWindowOpen = false;
if (gameId != null) {
@ -483,7 +491,7 @@ public class MageActionCallback implements ActionCallback {
cardView = popupData.card;
}
if (this.popupTextWindowOpen) {
hidePopup();
hideTooltipPopup();
}
if (cardView != null) {
if (cardView.isToRotate()) {
@ -506,7 +514,7 @@ public class MageActionCallback implements ActionCallback {
cardPreviewContainer.setVisible(false);
} catch (InterruptedException e) {
e.printStackTrace();
logger.warn("Can't hide enlarged card", e);
}
}
}
@ -582,7 +590,7 @@ public class MageActionCallback implements ActionCallback {
}
} catch (Exception e) {
e.printStackTrace();
logger.warn("Problem dring display of enlarged card", e);
}
}
});

View file

@ -58,7 +58,6 @@ public class Plugins implements MagePlugins {
pm.addPluginsFrom(new File(PLUGINS_DIRECTORY).toURI());
this.cardPlugin = new CardPluginImpl();
this.counterPlugin = pm.getPlugin(CounterPlugin.class);
//this.themePlugin = pm.getPlugin(ThemePlugin.class);
this.themePlugin = new ThemePluginImpl();
logger.info("Done.");
}

View file

@ -33,9 +33,7 @@ import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import mage.cards.decks.Deck;
import mage.client.MageFrame;
import mage.client.chat.ChatPanel;
import static mage.client.chat.ChatPanel.ChatType.TABLES;
import static mage.client.chat.ChatPanel.ChatType.TOURNAMENT;
import mage.client.chat.ChatPanelBasic;
import mage.client.constants.Constants.DeckEditorMode;
import mage.client.draft.DraftPanel;
import mage.client.game.GamePanel;
@ -116,9 +114,9 @@ public class CallbackClientImpl implements CallbackClient {
break;
case "chatMessage": {
ChatMessage message = (ChatMessage) callback.getData();
ChatPanel panel = MageFrame.getChat(callback.getObjectId());
ChatPanelBasic panel = MageFrame.getChat(callback.getObjectId());
if (panel != null) {
// play the to the message connected sound
// play the sound related to the message
if (message.getSoundToPlay() != null) {
switch (message.getSoundToPlay()) {
case PlayerLeft:
@ -383,9 +381,9 @@ public class CallbackClientImpl implements CallbackClient {
});
}
private void createChatStartMessage(ChatPanel chatPanel) {
private void createChatStartMessage(ChatPanelBasic chatPanel) {
chatPanel.setStartMessageDone(true);
ChatPanel usedPanel = chatPanel;
ChatPanelBasic usedPanel = chatPanel;
if (chatPanel.getConnectedChat() != null) {
usedPanel = chatPanel.getConnectedChat();
}

View file

@ -16,16 +16,14 @@
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="txtMessage" alignment="0" pref="203" max="32767" attributes="0"/>
<Component id="jSplitPane1" alignment="0" pref="0" max="32767" attributes="0"/>
<Component id="jSplitPane1" alignment="0" pref="350" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Component id="jSplitPane1" pref="288" max="32767" attributes="0"/>
<Component id="jSplitPane1" max="32767" attributes="0"/>
<EmptySpace min="0" pref="0" max="-2" attributes="0"/>
<Component id="txtMessage" min="-2" pref="30" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
@ -43,39 +41,6 @@
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout"/>
<SubComponents>
<Container class="javax.swing.JScrollPane" name="jScrollPaneTxt">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="null"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
<JSplitPaneConstraints position="right"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="mage.client.components.ColorPane" name="txtConversation">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo">
<EmptyBorder/>
</Border>
</Property>
<Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
<Font name="Arial" size="14" style="0"/>
</Property>
<Property name="focusCycleRoot" type="boolean" value="false"/>
<Property name="margin" type="java.awt.Insets" editor="org.netbeans.beaninfo.editors.InsetsEditor">
<Insets value="[2, 2, 2, 2]"/>
</Property>
<Property name="opaque" type="boolean" value="false"/>
</Properties>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JScrollPane" name="jScrollPanePlayers">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
@ -119,12 +84,16 @@
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JTabbedPane" name="jTabbedPaneText">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
<JSplitPaneConstraints position="right"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout"/>
</Container>
</SubComponents>
</Container>
<Component class="javax.swing.JTextField" name="txtMessage">
<Events>
<EventHandler event="keyTyped" listener="java.awt.event.KeyListener" parameters="java.awt.event.KeyEvent" handler="txtMessageKeyTyped"/>
</Events>
</Component>
</SubComponents>
</Form>

View file

@ -0,0 +1,278 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
/*
* ChatPanel.java
*
* Created on 15-Dec-2009, 11:04:31 PM
*/
package mage.client.table;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.swing.Icon;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import mage.client.chat.ChatPanelBasic;
import static mage.client.chat.ChatPanelBasic.CHAT_ALPHA;
import mage.client.chat.ChatPanelSeparated;
import mage.client.components.ColorPane;
import static mage.client.dialog.PreferencesDialog.KEY_USERS_COLUMNS_ORDER;
import static mage.client.dialog.PreferencesDialog.KEY_USERS_COLUMNS_WIDTH;
import mage.client.util.MageTableRowSorter;
import mage.client.util.gui.TableUtil;
import mage.client.util.gui.countryBox.CountryCellRenderer;
import mage.remote.MageRemoteException;
import mage.view.RoomUsersView;
import mage.view.UsersView;
/**
*
* @author BetaSteward_at_googlemail.com, nantuko
*/
public class PlayersChatPanel extends javax.swing.JPanel {
private final List<String> players = new ArrayList<>();
private final UserTableModel userTableModel;
private final ChatPanelSeparated userChatPanel;
private final ColorPane systemMessagesPane;
private static final int[] defaultColumnsWidth = {20, 100, 100, 80, 80};
/*
* Creates new form ChatPanel
*
*/
public PlayersChatPanel() {
userTableModel = new UserTableModel(); // needs to be set before initComponents();
initComponents();
setBackground(new Color(0, 0, 0, CHAT_ALPHA));
jTablePlayers.setBackground(new Color(0, 0, 0, CHAT_ALPHA));
jTablePlayers.setForeground(Color.white);
jTablePlayers.setRowSorter(new MageTableRowSorter(userTableModel));
TableUtil.setColumnWidthAndOrder(jTablePlayers, defaultColumnsWidth, KEY_USERS_COLUMNS_WIDTH, KEY_USERS_COLUMNS_ORDER);
jTablePlayers.setDefaultRenderer(Icon.class, new CountryCellRenderer());
systemMessagesPane = new ColorPane();
userChatPanel = new ChatPanelSeparated();
userChatPanel.setSystemMessagesPane(systemMessagesPane);
if (jTabbedPaneText != null) {
jTabbedPaneText.setBackground(new Color(0, 0, 0, CHAT_ALPHA));
if (userChatPanel != null) {
userChatPanel.setBackground(new Color(0, 0, 0, CHAT_ALPHA));
jTabbedPaneText.addTab("Talk", userChatPanel);
}
if (systemMessagesPane != null) {
systemMessagesPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
systemMessagesPane.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
systemMessagesPane.setFocusCycleRoot(false);
systemMessagesPane.setMargin(new java.awt.Insets(2, 2, 2, 2));
systemMessagesPane.setOpaque(false);
systemMessagesPane.setExtBackgroundColor(new Color(0, 0, 0, CHAT_ALPHA)); // Alpha = 255 not transparent
systemMessagesPane.setSelectionColor(Color.LIGHT_GRAY);
jTabbedPaneText.addTab("System", systemMessagesPane);
}
}
if (jScrollPanePlayers != null) {
jScrollPanePlayers.setBackground(new Color(0, 0, 0, CHAT_ALPHA));
jScrollPanePlayers.getViewport().setBackground(new Color(0, 0, 0, CHAT_ALPHA));
}
}
public ChatPanelBasic getUserChatPanel() {
return userChatPanel;
}
public void cleanUp() {
TableUtil.saveColumnWidthAndOrderToPrefs(jTablePlayers, KEY_USERS_COLUMNS_WIDTH, KEY_USERS_COLUMNS_ORDER);
userChatPanel.cleanUp();
}
public void setSplitDividerLocation(int location) {
if (jSplitPane1 != null) {
jSplitPane1.setDividerLocation(location);
}
}
public int getSplitDividerLocation() {
if (jSplitPane1 == null) {
return 0;
}
return this.jSplitPane1.getDividerLocation();
}
class UserTableModel extends AbstractTableModel {
private final String[] columnNames = new String[]{"Loc", "Players", "Info", "Games", "Connection"};
private UsersView[] players = new UsersView[0];
public void loadData(Collection<RoomUsersView> roomUserInfoList) throws MageRemoteException {
RoomUsersView roomUserInfo = roomUserInfoList.iterator().next();
this.players = roomUserInfo.getUsersView().toArray(new UsersView[0]);
JTableHeader th = jTablePlayers.getTableHeader();
TableColumnModel tcm = th.getColumnModel();
tcm.getColumn(jTablePlayers.convertColumnIndexToView(1)).setHeaderValue("Players (" + this.players.length + ")");
tcm.getColumn(jTablePlayers.convertColumnIndexToView(3)).setHeaderValue(
"Games " + roomUserInfo.getNumberActiveGames()
+ (roomUserInfo.getNumberActiveGames() != roomUserInfo.getNumberGameThreads() ? " (T:" + roomUserInfo.getNumberGameThreads() : " (")
+ " limit: " + roomUserInfo.getNumberMaxGames() + ")");
th.repaint();
this.fireTableDataChanged();
}
@Override
public int getRowCount() {
return players.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int arg0, int arg1) {
switch (arg1) {
case 0:
return players[arg0].getFlagName();
case 1:
return players[arg0].getUserName();
case 2:
return players[arg0].getInfoState();
case 3:
return players[arg0].getInfoGames();
case 4:
return players[arg0].getInfoPing();
}
return "";
}
@Override
public String getColumnName(int columnIndex) {
String colName = "";
if (columnIndex <= getColumnCount()) {
colName = columnNames[columnIndex];
}
return colName;
}
@Override
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Icon.class;
default:
return String.class;
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPanePlayers = new javax.swing.JScrollPane();
jTablePlayers = new javax.swing.JTable();
jTabbedPaneText = new javax.swing.JTabbedPane();
jSplitPane1.setBorder(null);
jSplitPane1.setDividerSize(10);
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jSplitPane1.setResizeWeight(0.25);
jScrollPanePlayers.setBorder(null);
jTablePlayers.setModel(this.userTableModel);
jTablePlayers.setToolTipText("Connected players");
jTablePlayers.setAutoscrolls(false);
jTablePlayers.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jTablePlayers.setFocusable(false);
jTablePlayers.setGridColor(new java.awt.Color(255, 255, 255));
jTablePlayers.setOpaque(false);
jTablePlayers.setRequestFocusEnabled(false);
jTablePlayers.setRowSelectionAllowed(false);
jTablePlayers.setUpdateSelectionOnSort(false);
jTablePlayers.setVerifyInputWhenFocusTarget(false);
jScrollPanePlayers.setViewportView(jTablePlayers);
jSplitPane1.setTopComponent(jScrollPanePlayers);
jSplitPane1.setRightComponent(jTabbedPaneText);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jSplitPane1)
.addGap(0, 0, 0))
);
}// </editor-fold>//GEN-END:initComponents
public void setRoomUserInfo(List<Collection<RoomUsersView>> view) {
try {
userTableModel.loadData(view.get(0));
} catch (Exception ex) {
this.players.clear();
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPanePlayers;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JTabbedPane jTabbedPaneText;
private javax.swing.JTable jTablePlayers;
// End of variables declaration//GEN-END:variables
}

View file

@ -503,7 +503,7 @@
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<Component id="jButton1" min="-2" pref="65" max="-2" attributes="0"/>
<Component id="jButtonNext" min="-2" pref="65" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
@ -516,7 +516,7 @@
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jButton1" alignment="3" min="-2" pref="17" max="-2" attributes="0"/>
<Component id="jButtonNext" alignment="3" min="-2" pref="17" max="-2" attributes="0"/>
<Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
@ -540,7 +540,7 @@
<Property name="text" type="java.lang.String" value="You are playing Mage version 0.7.5. Welcome! -- Mage dev team --"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="jButton1">
<Component class="javax.swing.JButton" name="jButtonNext">
<Properties>
<Property name="text" type="java.lang.String" value="Next"/>
<Property name="maximumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
@ -554,7 +554,7 @@
</Property>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonNextActionPerformed"/>
</Events>
</Component>
</SubComponents>
@ -570,21 +570,6 @@
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout"/>
<SubComponents>
<Component class="mage.client.chat.ChatPanel" name="chatPanel">
<Properties>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[100, 43]"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new mage.client.chat.ChatPanel(true);"/>
</AuxValues>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
<JSplitPaneConstraints position="right"/>
</Constraint>
</Constraints>
</Component>
<Container class="javax.swing.JPanel" name="jPanel3">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
@ -595,7 +580,7 @@
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jSplitPane2" alignment="0" pref="798" max="32767" attributes="0"/>
<Component id="jSplitPane2" alignment="0" pref="810" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
@ -679,7 +664,14 @@
</Container>
</SubComponents>
</Container>
<Component class="mage.client.table.PlayersChatPanel" name="chatPanelMain">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
<JSplitPaneConstraints position="right"/>
</Constraint>
</Constraints>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Form>
</Form>

View file

@ -69,7 +69,7 @@ import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;
import mage.cards.decks.importer.DeckImporterUtil;
import mage.client.MageFrame;
import mage.client.chat.ChatPanel;
import mage.client.chat.ChatPanelBasic;
import mage.client.components.MageComponents;
import mage.client.dialog.JoinTableDialog;
import mage.client.dialog.NewTableDialog;
@ -143,16 +143,16 @@ public class TablesPanel extends javax.swing.JPanel {
tableCompleted.setRowSorter(new MageTableRowSorter(matchesModel));
chatPanel.useExtendedView(ChatPanel.VIEW_MODE.NONE);
chatPanel.setBorder(null);
chatPanel.setChatType(ChatPanel.ChatType.TABLES);
chatPanelMain.getUserChatPanel().useExtendedView(ChatPanelBasic.VIEW_MODE.NONE);
chatPanelMain.getUserChatPanel().setBorder(null);
chatPanelMain.getUserChatPanel().setChatType(ChatPanelBasic.ChatType.TABLES);
filterButtons = new JToggleButton[]{btnStateWaiting, btnStateActive, btnStateFinished,
btnTypeMatch, btnTypeTourneyConstructed, btnTypeTourneyLimited,
btnFormatBlock, btnFormatStandard, btnFormatModern, btnFormatLegacy, btnFormatVintage, btnFormatCommander, btnFormatTinyLeader, btnFormatLimited, btnFormatOther,
btnSkillBeginner, btnSkillCasual, btnSkillSerious};
JComponent[] components = new JComponent[]{chatPanel, jSplitPane1, jScrollPane1, jScrollPane2, topPanel, jPanel3};
JComponent[] components = new JComponent[]{chatPanelMain, jSplitPane1, jScrollPane1, jScrollPane2, topPanel, jPanel3};
for (JComponent component : components) {
component.setOpaque(false);
}
@ -274,7 +274,7 @@ public class TablesPanel extends javax.swing.JPanel {
public void cleanUp() {
saveSettings();
chatPanel.cleanUp();
chatPanelMain.cleanUp();
}
private void saveDividerLocations() {
@ -284,7 +284,7 @@ public class TablesPanel extends javax.swing.JPanel {
PreferencesDialog.saveValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, sb);
PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.getDividerLocation()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_2, Integer.toString(this.jSplitPane2.getDividerLocation()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_3, Integer.toString(chatPanel.getSplitDividerLocation()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_3, Integer.toString(chatPanelMain.getSplitDividerLocation()));
}
private void restoreSettings() {
@ -333,8 +333,8 @@ public class TablesPanel extends javax.swing.JPanel {
}
}
location = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_3, null);
if (location != null && chatPanel != null) {
chatPanel.setSplitDividerLocation(Integer.parseInt(location));
if (location != null && chatPanelMain != null) {
chatPanelMain.setSplitDividerLocation(Integer.parseInt(location));
}
}
}
@ -376,7 +376,7 @@ public class TablesPanel extends javax.swing.JPanel {
updateTablesTask.execute();
}
if (updatePlayersTask == null || updatePlayersTask.isDone()) {
updatePlayersTask = new UpdatePlayersTask(session, roomId, this.chatPanel);
updatePlayersTask = new UpdatePlayersTask(session, roomId, this.chatPanelMain);
updatePlayersTask.execute();
}
if (this.btnStateFinished.isSelected()) {
@ -426,7 +426,7 @@ public class TablesPanel extends javax.swing.JPanel {
MageFrame.getDesktop().add(joinTableDialog, JLayeredPane.MODAL_LAYER);
}
if (chatRoomId != null) {
this.chatPanel.connect(chatRoomId);
this.chatPanelMain.getUserChatPanel().connect(chatRoomId);
startTasks();
this.setVisible(true);
this.repaint();
@ -461,7 +461,7 @@ public class TablesPanel extends javax.swing.JPanel {
} else {
this.jPanel2.setVisible(true);
this.jLabel2.setText(serverMessages.get(0));
this.jButton1.setVisible(serverMessages.size() > 1);
this.jButtonNext.setVisible(serverMessages.size() > 1);
}
}
@ -473,7 +473,7 @@ public class TablesPanel extends javax.swing.JPanel {
}
}
stopTasks();
this.chatPanel.disconnect();
this.chatPanelMain.getUserChatPanel().disconnect();
Component c = this.getParent();
while (c != null && !(c instanceof TablesPane)) {
@ -484,8 +484,8 @@ public class TablesPanel extends javax.swing.JPanel {
}
}
public ChatPanel getChatPanel() {
return this.chatPanel;
public ChatPanelBasic getChatPanel() {
return chatPanelMain.getUserChatPanel();
}
private void setTableFilter() {
@ -501,7 +501,7 @@ public class TablesPanel extends javax.swing.JPanel {
// type
List<RowFilter<Object, Object>> typeFilterList = new ArrayList<>();
if (btnTypeMatch.isSelected()) {
typeFilterList.add(RowFilter.regexFilter("Two|Commander|Free|Tiny", TableTableModel.COLUMN_GAME_TYPE));
typeFilterList.add(RowFilter.regexFilter("Two|Commander|Free|Tiny|Momir", TableTableModel.COLUMN_GAME_TYPE));
}
if (btnTypeTourneyConstructed.isSelected()) {
typeFilterList.add(RowFilter.regexFilter("Constructed", TableTableModel.COLUMN_GAME_TYPE));
@ -537,7 +537,7 @@ public class TablesPanel extends javax.swing.JPanel {
formatFilterList.add(RowFilter.regexFilter("^Limited", TableTableModel.COLUMN_DECK_TYPE));
}
if (btnFormatOther.isSelected()) {
formatFilterList.add(RowFilter.regexFilter("^Constructed - Pauper|^Constructed - Extended|^Constructed - Historical|^Constructed - Super", TableTableModel.COLUMN_DECK_TYPE));
formatFilterList.add(RowFilter.regexFilter("^Momir Basic|^Constructed - Pauper|^Constructed - Extended|^Constructed - Historical|^Constructed - Super", TableTableModel.COLUMN_DECK_TYPE));
}
List<RowFilter<Object, Object>> skillFilterList = new ArrayList<>();
@ -628,15 +628,15 @@ public class TablesPanel extends javax.swing.JPanel {
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButtonNext = new javax.swing.JButton();
jSplitPane1 = new javax.swing.JSplitPane();
chatPanel = new mage.client.chat.ChatPanel(true);
jPanel3 = new javax.swing.JPanel();
jSplitPane2 = new javax.swing.JSplitPane();
jScrollPane1 = new javax.swing.JScrollPane();
tableTables = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
tableCompleted = new javax.swing.JTable();
chatPanelMain = new mage.client.table.PlayersChatPanel();
topPanel.setBackground(java.awt.Color.white);
topPanel.setOpaque(false);
@ -1022,13 +1022,13 @@ public class TablesPanel extends javax.swing.JPanel {
jLabel2.setText("You are playing Mage version 0.7.5. Welcome! -- Mage dev team --");
jButton1.setText("Next");
jButton1.setMaximumSize(new java.awt.Dimension(55, 25));
jButton1.setMinimumSize(new java.awt.Dimension(55, 25));
jButton1.setPreferredSize(new java.awt.Dimension(55, 25));
jButton1.addActionListener(new java.awt.event.ActionListener() {
jButtonNext.setText("Next");
jButtonNext.setMaximumSize(new java.awt.Dimension(55, 25));
jButtonNext.setMinimumSize(new java.awt.Dimension(55, 25));
jButtonNext.setPreferredSize(new java.awt.Dimension(55, 25));
jButtonNext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jButtonNextActionPerformed(evt);
}
});
@ -1037,7 +1037,7 @@ public class TablesPanel extends javax.swing.JPanel {
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonNext, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
@ -1048,7 +1048,7 @@ public class TablesPanel extends javax.swing.JPanel {
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonNext, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
@ -1058,9 +1058,6 @@ public class TablesPanel extends javax.swing.JPanel {
jSplitPane1.setDividerSize(10);
jSplitPane1.setResizeWeight(1.0);
chatPanel.setMinimumSize(new java.awt.Dimension(100, 43));
jSplitPane1.setRightComponent(chatPanel);
jSplitPane2.setBorder(null);
jSplitPane2.setDividerSize(10);
jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
@ -1085,7 +1082,7 @@ public class TablesPanel extends javax.swing.JPanel {
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 798, Short.MAX_VALUE)
.addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 810, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
@ -1093,6 +1090,7 @@ public class TablesPanel extends javax.swing.JPanel {
);
jSplitPane1.setLeftComponent(jPanel3);
jSplitPane1.setRightComponent(chatPanelMain);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
@ -1154,7 +1152,7 @@ public class TablesPanel extends javax.swing.JPanel {
newTableDialog.showDialog(roomId);
}//GEN-LAST:event_btnNewTableActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNextActionPerformed
synchronized (this) {
if (messages != null && !messages.isEmpty()) {
currentMessage++;
@ -1164,7 +1162,7 @@ public class TablesPanel extends javax.swing.JPanel {
this.jLabel2.setText(messages.get(currentMessage));
}
}
}//GEN-LAST:event_jButton1ActionPerformed
}//GEN-LAST:event_jButtonNextActionPerformed
private void btnFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFilterActionPerformed
setTableFilter();
@ -1206,10 +1204,10 @@ public class TablesPanel extends javax.swing.JPanel {
private javax.swing.JToggleButton btnTypeMatch;
private javax.swing.JToggleButton btnTypeTourneyConstructed;
private javax.swing.JToggleButton btnTypeTourneyLimited;
private mage.client.chat.ChatPanel chatPanel;
private mage.client.table.PlayersChatPanel chatPanelMain;
private javax.swing.JToolBar filterBar1;
private javax.swing.JToolBar filterBar2;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButtonNext;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel2;
@ -1413,11 +1411,11 @@ class UpdatePlayersTask extends SwingWorker<Void, Collection<RoomUsersView>> {
private final Session session;
private final UUID roomId;
private final ChatPanel chat;
private final PlayersChatPanel chat;
private static final Logger logger = Logger.getLogger(UpdatePlayersTask.class);
UpdatePlayersTask(Session session, UUID roomId, ChatPanel chat) {
UpdatePlayersTask(Session session, UUID roomId, PlayersChatPanel chat) {
this.session = session;
this.roomId = roomId;
this.chat = chat;

View file

@ -349,10 +349,7 @@
</Container>
</SubComponents>
</Container>
<Component class="mage.client.chat.ChatPanel" name="chatPanel1">
<Properties>
<Property name="startMessageDone" type="boolean" value="true"/>
</Properties>
<Component class="mage.client.chat.ChatPanelBasic" name="chatPanel1">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
<JSplitPaneConstraints position="right"/>

View file

@ -49,7 +49,7 @@ import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;
import mage.client.MageFrame;
import mage.client.chat.ChatPanel;
import mage.client.chat.ChatPanelBasic;
import mage.client.dialog.PreferencesDialog;
import static mage.client.dialog.PreferencesDialog.KEY_TOURNAMENT_MATCH_COLUMNS_ORDER;
import static mage.client.dialog.PreferencesDialog.KEY_TOURNAMENT_MATCH_COLUMNS_WIDTH;
@ -105,8 +105,8 @@ public class TournamentPanel extends javax.swing.JPanel {
tableMatches.createDefaultColumnsFromModel();
TableUtil.setColumnWidthAndOrder(tableMatches, defaultColumnsWidthMatches, KEY_TOURNAMENT_MATCH_COLUMNS_WIDTH, KEY_TOURNAMENT_MATCH_COLUMNS_ORDER);
chatPanel1.useExtendedView(ChatPanel.VIEW_MODE.NONE);
chatPanel1.setChatType(ChatPanel.ChatType.TOURNAMENT);
chatPanel1.useExtendedView(ChatPanelBasic.VIEW_MODE.NONE);
chatPanel1.setChatType(ChatPanelBasic.ChatType.TOURNAMENT);
Action action = new AbstractAction() {
@Override
@ -317,7 +317,7 @@ public class TournamentPanel extends javax.swing.JPanel {
tablePlayers = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
tableMatches = new javax.swing.JTable();
chatPanel1 = new mage.client.chat.ChatPanel();
chatPanel1 = new mage.client.chat.ChatPanelBasic();
setPreferredSize(new java.awt.Dimension(908, 580));
@ -484,8 +484,6 @@ public class TournamentPanel extends javax.swing.JPanel {
jSplitPane1.setBottomComponent(jScrollPane2);
jSplitPane2.setLeftComponent(jSplitPane1);
chatPanel1.setStartMessageDone(true);
jSplitPane2.setRightComponent(chatPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
@ -524,7 +522,7 @@ public class TournamentPanel extends javax.swing.JPanel {
private javax.swing.JPanel actionPanel;
private javax.swing.JButton btnCloseWindow;
private javax.swing.JButton btnQuitTournament;
private mage.client.chat.ChatPanel chatPanel1;
private mage.client.chat.ChatPanelBasic chatPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSplitPane jSplitPane1;

View file

@ -36,7 +36,6 @@
package mage.client.unusedFiles;
import mage.client.cards.BigCard;
import mage.client.unusedFiles.CombatGroup;
import mage.view.CombatGroupView;
import javax.swing.*;
@ -44,9 +43,8 @@ import java.awt.*;
import java.beans.PropertyVetoException;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import mage.client.dialog.MageDialog;
import org.apache.log4j.Logger;
/**
*
@ -54,6 +52,8 @@ import mage.client.dialog.MageDialog;
*/
public class CombatDialog extends MageDialog {
private static final Logger logger = Logger.getLogger(CombatDialog.class);
private UUID gameId;
private BigCard bigCard;
private int lastX = 500;
@ -100,7 +100,7 @@ public class CombatDialog extends MageDialog {
try {
this.setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(CombatDialog.class.getName()).log(Level.SEVERE, null, ex);
logger.error(null, ex);
}
pack();
this.revalidate();

View file

@ -1,37 +1,36 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
/*
* PlayerPanel.java
*
* Created on Nov 18, 2009, 3:01:31 PM
*/
package mage.client.unusedFiles;
//package mage.client.game;
@ -58,7 +57,9 @@ public class PlayerPanel extends javax.swing.JPanel {
private ShowCardsDialog graveyard;
private BigCard bigCard;
/** Creates new form PlayerPanel */
/**
* Creates new form PlayerPanel
*/
public PlayerPanel() {
initComponents();
}
@ -79,19 +80,17 @@ public class PlayerPanel extends javax.swing.JPanel {
this.btnPlayerName.setText(player.getName());
if (player.isActive()) {
this.btnPlayerName.setBackground(Color.DARK_GRAY);
}
else if (player.hasLeft()) {
} else if (player.hasLeft()) {
this.btnPlayerName.setBackground(Color.RED);
}
else {
} else {
this.btnPlayerName.setBackground(Color.LIGHT_GRAY);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
@ -201,10 +200,9 @@ public class PlayerPanel extends javax.swing.JPanel {
if (graveyard == null) {
graveyard = new ShowCardsDialog();
}
graveyard.loadCards(player.getName() + " graveyard", player.getGraveyard(), bigCard, Config.dimensions, gameId, false);
graveyard.loadCards(player.getName() + " graveyard", player.getGraveyard(), bigCard, Config.dimensions, gameId, false, null, null, null);
}//GEN-LAST:event_btnGraveActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnGrave;
private javax.swing.JButton btnPlayerName;

View file

@ -25,21 +25,21 @@
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.util;
import java.util.Comparator;
import mage.utils.CardUtil;
import mage.view.CardView;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class CardViewColorDetailedComparator implements Comparator<CardView> {
public class CardViewColorIdentityComparator implements Comparator<CardView> {
@Override
public int compare(CardView o1, CardView o2) {
return o1.getColor().hashCode() - o2.getColor().hashCode();
return CardUtil.getColorIdentitySortValue(o1.getManaCost(), o1.getColor(), o1.getRules())
- CardUtil.getColorIdentitySortValue(o2.getManaCost(), o2.getColor(), o2.getRules());
}
}
}

View file

@ -1,16 +1,16 @@
/*
* Copyright 2011 BetaSteward_at_googlemail.com. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
@ -20,12 +20,11 @@
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.util;
import java.util.Comparator;
@ -39,7 +38,7 @@ public class CardViewCostComparator implements Comparator<CardView> {
@Override
public int compare(CardView o1, CardView o2) {
return Integer.valueOf(o1.getConvertedManaCost()).compareTo(Integer.valueOf(o2.getConvertedManaCost()));
return Integer.valueOf(o1.getConvertedManaCost()).compareTo(o2.getConvertedManaCost());
}
}

View file

@ -43,7 +43,7 @@ import org.apache.log4j.Logger;
*/
public class DeckUtil {
private static final transient Logger log = Logger.getLogger(DeckUtil.class);
private static final Logger log = Logger.getLogger(DeckUtil.class);
private DeckUtil() {
}

View file

@ -1,31 +1,30 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.client.util;
import java.io.Serializable;
@ -33,7 +32,9 @@ import java.io.Serializable;
/**
*
* @author BetaSteward_at_googlemail.com
* @param <E>
*/
public interface Listener<E extends Event> extends Serializable {
void event(E event);
}

View file

@ -303,7 +303,7 @@ public class AudioManager {
private static void checkAndPlayClip(MageClip mageClip) {
try {
if (mageClip != null) {
if (mageClip != null && mageClip.getClip() != null) {
boolean playSound = false;
switch (mageClip.getAudioGroup()) {
case GameSounds:

View file

@ -11,11 +11,11 @@ import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Arrow extends JPanel {
private static final long serialVersionUID = -4631054277822828303L;
private int startX;
@ -27,21 +27,25 @@ public class Arrow extends JPanel {
private Composite composite;
private Color color = Color.red;
public Arrow () {
public Arrow() {
setOpaque(false);
setOpacity(0.6f);
}
protected void paintComponent (Graphics g) {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
float ex = endX - startX;
float ey = endY - startY;
if (ex == 0 && ey == 0) return;
float length = (float)Math.sqrt(ex * ex + ey * ey);
float bendPercent = (float)Math.asin(ey / length);
if (endX > startX) bendPercent = -bendPercent;
if (ex == 0 && ey == 0) {
return;
}
float length = (float) Math.sqrt(ex * ex + ey * ey);
float bendPercent = (float) Math.asin(ey / length);
if (endX > startX) {
bendPercent = -bendPercent;
}
Area arrow = getArrow(length, bendPercent);
Graphics2D g2d = (Graphics2D)g;
Graphics2D g2d = (Graphics2D) g;
g2d.translate(startX, startY);
g2d.rotate(Math.atan2(ey, ex));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
@ -52,16 +56,16 @@ public class Arrow extends JPanel {
g2d.draw(arrow);
}
private Area getArrow (float length, float bendPercent) {
private Area getArrow(float length, float bendPercent) {
float p1x = 0, p1y = 0;
float p2x = length, p2y = 0;
float cx = length / 2, cy = length / 8f * bendPercent;
float adjSize, ex, ey, abs_e;
adjSize = (float)(bodyWidth / 2 / Math.sqrt(2));
adjSize = (float) (bodyWidth / 2 / Math.sqrt(2));
ex = p2x - cx;
ey = p2y - cy;
abs_e = (float)Math.sqrt(ex * ex + ey * ey);
abs_e = (float) Math.sqrt(ex * ex + ey * ey);
ex /= abs_e;
ey /= abs_e;
GeneralPath bodyPath = new GeneralPath();
@ -71,10 +75,10 @@ public class Arrow extends JPanel {
bodyPath.quadTo(cx, cy, p2x - (ey + ex) * adjSize, p2y + (ex - ey) * adjSize);
bodyPath.closePath();
adjSize = (float)(headSize / Math.sqrt(2));
adjSize = (float) (headSize / Math.sqrt(2));
ex = p2x - cx;
ey = p2y - cy;
abs_e = (float)Math.sqrt(ex * ex + ey * ey);
abs_e = (float) Math.sqrt(ex * ex + ey * ey);
ex /= abs_e;
ey /= abs_e;
GeneralPath headPath = new GeneralPath();
@ -88,23 +92,23 @@ public class Arrow extends JPanel {
return area;
}
public int getBodyWidth () {
public int getBodyWidth() {
return bodyWidth;
}
public void setBodyWidth (int bodyWidth) {
public void setBodyWidth(int bodyWidth) {
this.bodyWidth = bodyWidth;
}
public float getHeadSize () {
public float getHeadSize() {
return headSize;
}
public void setHeadSize (float headSize) {
public void setHeadSize(float headSize) {
this.headSize = headSize;
}
public void setArrowLocation (int startX, int startY, int endX, int endY) {
public void setArrowLocation(int startX, int startY, int endX, int endY) {
this.startX = startX;
this.startY = startY;
this.endX = endX;
@ -112,7 +116,7 @@ public class Arrow extends JPanel {
repaint();
}
public void setOpacity (float opacity) {
public void setOpacity(float opacity) {
composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity);
}
@ -120,7 +124,7 @@ public class Arrow extends JPanel {
this.color = color;
}
public static void main (String[] args) {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
@ -130,11 +134,13 @@ public class Arrow extends JPanel {
frame.setResizable(false);
frame.setVisible(true);
frame.getContentPane().addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved (MouseEvent e) {
@Override
public void mouseMoved(MouseEvent e) {
arrow.setArrowLocation(320, 240, e.getX(), e.getY());
}
public void mouseDragged (MouseEvent e) {
@Override
public void mouseDragged(MouseEvent e) {
}
});
}

View file

@ -29,6 +29,7 @@ import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import mage.cards.MagePermanent;
import mage.cards.TextPopup;
import mage.cards.action.ActionCallback;
@ -63,15 +64,16 @@ import org.mage.plugins.card.utils.impl.ImageManagerImpl;
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class CardPanel extends MagePermanent implements MouseListener, MouseMotionListener, MouseWheelListener, ComponentListener {
private static final long serialVersionUID = -3272134219262184410L;
private static final Logger log = Logger.getLogger(CardPanel.class);
private static final Logger logger = Logger.getLogger(CardPanel.class);
private static final int WIDTH_LIMIT = 90; // card width limit to create smaller counter
public static final double TAPPED_ANGLE = Math.PI / 2;
public static final double FLIPPED_ANGLE = Math.PI;
public static final float ASPECT_RATIO = 3.5f / 2.5f;
public static final int POPUP_X_GAP = 1; // prevent popup window from blinking
public static final int POPUP_X_GAP = 1; // prevent tooltip window from blinking
public static CardPanel dragAnimationPanel;
@ -120,7 +122,7 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
private GlowText ptText;
private boolean displayEnabled = true;
private boolean isAnimationPanel;
public int cardXOffset, cardYOffset, cardWidth, cardHeight;
public int cardXOffset, cardYOffset, cardWidth, cardHeight;
private boolean isSelected;
private boolean isPlayable;
@ -132,8 +134,8 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
private ActionCallback callback;
protected boolean popupShowing;
protected TextPopup popupText = new TextPopup();
protected boolean tooltipShowing;
protected TextPopup tooltipText = new TextPopup();
protected UUID gameId;
private TransferData data = new TransferData();
@ -152,6 +154,9 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
private int yTextOffset = 10;
// if this is set, it's opened if the user right clicks on the card panel
private JPopupMenu popupMenu;
public CardPanel(CardView newGameCard, UUID gameId, final boolean loadImage, ActionCallback callback, final boolean foil, Dimension dimension) {
this.gameCard = newGameCard;
this.callback = callback;
@ -165,7 +170,6 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
//for container debug (don't remove)
//setBorder(BorderFactory.createLineBorder(Color.green));
if (this.gameCard.canTransform()) {
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
@ -222,14 +226,14 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
}
if (newGameCard.isAbility()) {
if (AbilityType.TRIGGERED.equals(newGameCard.getAbilityType())) {
setTypeIcon(ImageManagerImpl.getInstance().getTriggeredAbilityImage(),"Triggered Ability");
setTypeIcon(ImageManagerImpl.getInstance().getTriggeredAbilityImage(), "Triggered Ability");
} else if (AbilityType.ACTIVATED.equals(newGameCard.getAbilityType())) {
setTypeIcon(ImageManagerImpl.getInstance().getActivatedAbilityImage(),"Activated Ability");
setTypeIcon(ImageManagerImpl.getInstance().getActivatedAbilityImage(), "Activated Ability");
}
}
if (this.gameCard.isToken()) {
setTypeIcon(ImageManagerImpl.getInstance().getTokenIconImage(),"Token Permanent");
setTypeIcon(ImageManagerImpl.getInstance().getTokenIconImage(), "Token Permanent");
}
// icon to inform about permanent is copying something
@ -299,7 +303,7 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
imagePanel.setScalingMultiPassType(MultipassType.none);
String cardType = getType(newGameCard);
popupText.setText(getText(cardType, newGameCard));
tooltipText.setText(getText(cardType, newGameCard));
Util.threadPool.submit(new Runnable() {
@Override
@ -326,9 +330,9 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
}
setText(gameCard);
} catch (Exception e) {
e.printStackTrace();
logger.fatal("Problem during image animation", e);
} catch (Error err) {
err.printStackTrace();
logger.error("Problem during image animation", err);
}
}
});
@ -344,7 +348,6 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
typeButton.setLocation(2, 2);
typeButton.setSize(25, 25);
iconPanel.setVisible(true);
typeButton.setIcon(new ImageIcon(bufferedImage));
if (toolTipText != null) {
@ -355,17 +358,17 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
public void cleanUp() {
if (dayNightButton != null) {
for(ActionListener al: dayNightButton.getActionListeners()) {
for (ActionListener al : dayNightButton.getActionListeners()) {
dayNightButton.removeActionListener(al);
}
}
for(MouseListener ml: this.getMouseListeners() ){
for (MouseListener ml : this.getMouseListeners()) {
this.removeMouseListener(ml);
}
for(MouseMotionListener ml: this.getMouseMotionListeners() ){
for (MouseMotionListener ml : this.getMouseMotionListeners()) {
this.removeMouseMotionListener(ml);
}
for(MouseWheelListener ml: this.getMouseWheelListeners() ){
for (MouseWheelListener ml : this.getMouseWheelListeners()) {
this.removeMouseWheelListener(ml);
}
// this holds reference to ActionCallback forever so set it to null to prevent
@ -394,7 +397,6 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
}
}
@Override
public void setZone(String zone) {
this.zone = zone;
@ -502,7 +504,7 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
} else if (isPlayable) {
g2d.setColor(new Color(153, 102, 204, 200));
//g2d.fillRoundRect(cardXOffset + 1, cardYOffset + 1, cardWidth - 2, cardHeight - 2, cornerSize, cornerSize);
g2d.fillRoundRect(cardXOffset, cardYOffset , cardWidth , cardHeight , cornerSize, cornerSize);
g2d.fillRoundRect(cardXOffset, cardYOffset, cardWidth, cardHeight, cornerSize, cornerSize);
}
if (canAttack) {
@ -512,10 +514,10 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
//TODO:uncomment
/*
if (gameCard.isAttacking()) {
g2d.setColor(new Color(200,10,10,200));
g2d.fillRoundRect(cardXOffset+1, cardYOffset+1, cardWidth-2, cardHeight-2, cornerSize, cornerSize);
}*/
if (gameCard.isAttacking()) {
g2d.setColor(new Color(200,10,10,200));
g2d.fillRoundRect(cardXOffset+1, cardYOffset+1, cardWidth-2, cardHeight-2, cornerSize, cornerSize);
}*/
}
@Override
@ -562,8 +564,7 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
if (counterPanel != null) {
counterPanel.setLocation(cardXOffset + borderSize, cardYOffset + borderSize);
counterPanel.setSize(cardWidth - borderSize * 2, cardHeight - borderSize * 2);
int size = cardWidth > WIDTH_LIMIT ? 40: 20;
int size = cardWidth > WIDTH_LIMIT ? 40 : 20;
minusCounterLabel.setLocation(counterPanel.getWidth() - size, counterPanel.getHeight() - size * 2);
minusCounterLabel.setSize(size, size);
@ -577,7 +578,6 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
otherCounterLabel.setLocation(5, counterPanel.getHeight() - size);
otherCounterLabel.setSize(size, size);
}
int fontHeight = Math.round(cardHeight * (27f / 680));
boolean showText = (!isAnimationPanel && fontHeight < 12);
@ -823,7 +823,7 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
this.gameCard = card;
String cardType = getType(card);
popupText.setText(getText(cardType, card));
tooltipText.setText(getText(cardType, card));
if (hasSickness && CardUtil.isCreature(gameCard) && isPermanent) {
overlayPanel.setVisible(true);
@ -864,11 +864,11 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
minusCounterLabel.setVisible(false);
loyaltyCounterLabel.setVisible(false);
otherCounterLabel.setVisible(false);
for (CounterView counterView:card.getCounters()) {
for (CounterView counterView : card.getCounters()) {
if (counterView.getCount() == 0) {
continue;
}
switch(counterView.getName()) {
switch (counterView.getName()) {
case "+1/+1":
if (counterView.getCount() != plusCounter) {
plusCounter = counterView.getCount();
@ -913,10 +913,10 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
}
private static ImageIcon getCounterImageWithAmount(int amount, BufferedImage image, int cardWidth) {
int factor = cardWidth > WIDTH_LIMIT ? 2 :1;
int factor = cardWidth > WIDTH_LIMIT ? 2 : 1;
int xOffset = amount > 9 ? 2 : 5;
int fontSize = factor == 1 ? amount < 10 ? 12 : amount < 100 ? 10 : amount < 1000 ? 7: 6
:amount < 10 ? 19 : amount < 100 ? 15 : amount < 1000 ? 12: amount < 10000 ?9 : 8;
int fontSize = factor == 1 ? amount < 10 ? 12 : amount < 100 ? 10 : amount < 1000 ? 7 : 6
: amount < 10 ? 19 : amount < 100 ? 15 : amount < 1000 ? 12 : amount < 10000 ? 9 : 8;
BufferedImage newImage;
if (cardWidth > WIDTH_LIMIT) {
newImage = ImageManagerImpl.deepCopy(image);
@ -925,7 +925,7 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
}
Graphics graphics = newImage.getGraphics();
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("Arial Black", amount > 100 ? Font.PLAIN : Font.BOLD, fontSize ));
graphics.setFont(new Font("Arial Black", amount > 100 ? Font.PLAIN : Font.BOLD, fontSize));
graphics.drawString(Integer.toString(amount), xOffset * factor, 11 * factor);
return new ImageIcon(newImage);
}
@ -977,12 +977,12 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
if (gameCard.hideInfo()) {
return;
}
if (!popupShowing) {
if (!tooltipShowing) {
synchronized (this) {
if (!popupShowing) {
if (!tooltipShowing) {
TransferData transferData = getTransferDataForMouseEntered();
if (this.isShowing()) {
popupShowing = true;
tooltipShowing = true;
callback.mouseEntered(e, transferData);
}
}
@ -1013,13 +1013,13 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
if (getMousePosition(true) != null) {
return;
}
if (popupShowing) {
if (tooltipShowing) {
synchronized (this) {
if (popupShowing) {
popupShowing = false;
if (tooltipShowing) {
tooltipShowing = false;
data.component = this;
data.card = this.gameCard;
data.popupText = popupText;
data.popupText = tooltipText;
callback.mouseExited(e, data);
}
}
@ -1047,7 +1047,7 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
private TransferData getTransferDataForMouseEntered() {
data.component = this;
data.card = this.gameCard;
data.popupText = popupText;
data.popupText = tooltipText;
data.gameId = this.gameId;
data.locationOnScreen = data.component.getLocationOnScreen(); // we need this for popup
data.popupOffsetX = isTapped() ? cardHeight + cardXOffset + POPUP_X_GAP : cardWidth + cardXOffset + POPUP_X_GAP;
@ -1145,7 +1145,7 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
dayNightButton.setIcon(new ImageIcon(night));
}
if (this.gameCard.getSecondCardFace() == null) {
log.error("no second side for card to transform!");
logger.error("no second side for card to transform!");
return;
}
if (!isPermanent) { // use only for custom transformation (when pressing day-night button)
@ -1210,5 +1210,14 @@ public class CardPanel extends MagePermanent implements MouseListener, MouseMoti
yTextOffset = yOffset;
}
@Override
public JPopupMenu getPopupMenu() {
return popupMenu;
}
@Override
public void setPopupMenu(JPopupMenu popupMenu) {
this.popupMenu = popupMenu;
}
}

View file

@ -81,6 +81,7 @@ public class CardPluginImpl implements CardPlugin {
@PluginLoaded
public void newPlugin(CardPlugin plugin) {
log.info(plugin.toString() + " has been loaded.");
}
@Override

View file

@ -9,7 +9,7 @@ import org.mage.plugins.card.images.CardDownloadData;
public interface CardImageSource {
String generateURL(CardDownloadData card) throws Exception;
String generateTokenUrl(CardDownloadData card);
String generateTokenUrl(CardDownloadData card) throws Exception;
String getSourceName();
Float getAverageSize();
}

View file

@ -36,7 +36,7 @@ public class GathererSets implements Iterable<DownloadJob> {
private static final String[] withMythics = {"M10", "M11", "M12", "M13", "M14", "M15", "ORI",
"DDF", "DDG", "DDH", "DDI", "DDJ", "DDK", "DDL", "DDM", "DDN",
"DD3", "DD3B", "DDO",
"DD3", "DD3B", "DDO", "DDP",
"FVD", "FVE", "FVL", "FVR",
"V12", "V13", "V14", "V15",
"ALA", "CON", "ARB",
@ -49,7 +49,7 @@ public class GathererSets implements Iterable<DownloadJob> {
"THS", "BNG", "JOU",
"CNS", "VMA", "TPR",
"KTK", "FRF", "DTK",
"BFZ"};
"BFZ", "EXP", "OGW"};
private static final HashMap<String, String> symbolsReplacements = new HashMap<>();
static {

View file

@ -13,9 +13,12 @@ import org.mage.plugins.card.utils.CardImageUtils;
public class MagicCardsImageSource implements CardImageSource {
private static CardImageSource instance = new MagicCardsImageSource();
private static final Map<String, String> setNameTokenReplacement = new HashMap<String, String>() {
{
put("C15", "commander-2015");
put("ORG", "oath-of-the-gatewatch");
put("EXP", "zendikar-expeditions");
put("BFZ", "battle-for-zendikar");
put("FVL", "from-the-vault-legends");
put("FVD", "from-the-vault-dragons");
@ -31,8 +34,8 @@ public class MagicCardsImageSource implements CardImageSource {
put("MM2", "modern-masters-2015");
put("PTC", "prerelease-events");
put("DTK", "dragons-of-tarkir");
put("GRC","wpngateway");
put("MBP","media-inserts");
put("GRC", "wpngateway");
put("MBP", "media-inserts");
put("MLP", "launch-party");
put("WMCQ", "world-magic-cup-qualifier");
put("GPX", "grand-prix");
@ -40,7 +43,7 @@ public class MagicCardsImageSource implements CardImageSource {
put("MGDC", "magic-game-day-cards");
put("FNMP", "friday-night-magic");
put("FRF", "fate-reforged");
put("C14", "commander-2014-edition");
put("C14", "commander-2014");
put("KTK", "khans-of-tarkir");
put("VMA", "vintage-masters");
put("CNS", "conspiracy");
@ -103,6 +106,7 @@ public class MagicCardsImageSource implements CardImageSource {
put("DDM", "duel-decks-jace-vs-vraska");
put("DDN", "duel-decks-speed-vs-cunning");
put("DDO", "duel-decks-elspeth-vs-kiora");
put("DDP", "duel-decks-zendikar-vs-eldrazi");
}
private static final long serialVersionUID = 1L;
};
@ -129,7 +133,7 @@ public class MagicCardsImageSource implements CardImageSource {
String set = CardImageUtils.updateSet(cardSet, true);
String preferedLanguage = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PREF_LANGUAGE, "en");
StringBuilder url = new StringBuilder("http://magiccards.info/scans/").append(preferedLanguage).append("/");
url.append(set.toLowerCase()).append("/").append(collectorId);
@ -153,7 +157,12 @@ public class MagicCardsImageSource implements CardImageSource {
@Override
public String generateTokenUrl(CardDownloadData card) {
String name = card.getName().replaceAll(" ", "-").replace(",", "").toLowerCase();
String name = card.getName();
// add type to name if it's not 0
if (card.getType() > 0) {
name = name + " " + card.getType();
}
name = name.replaceAll(" ", "-").replace(",", "").toLowerCase();
String set = "not-supported-set";
if (setNameTokenReplacement.containsKey(card.getSet())) {
set = setNameTokenReplacement.get(card.getSet());

View file

@ -36,7 +36,10 @@ import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.prefs.Preferences;
import mage.client.MageFrame;
import mage.remote.Connection;
@ -56,6 +59,7 @@ public class MythicspoilerComSource implements CardImageSource {
private static CardImageSource instance;
private static Map<String, String> setsAliases;
private static Map<String, String> cardNameAliases;
private static Map<String, Set<String>> cardNameAliasesStart;
private final Map<String, Map<String, String>> sets;
public static CardImageSource getInstance() {
@ -71,8 +75,9 @@ public class MythicspoilerComSource implements CardImageSource {
}
public MythicspoilerComSource() {
sets = new HashMap<>();
sets = new LinkedHashMap<>();
setsAliases = new HashMap<>();
setsAliases.put("exp", "bfz");
cardNameAliases = new HashMap<>();
// set+wrong name from web side => correct card name
cardNameAliases.put("MM2-otherwordlyjourney", "otherworldlyjourney");
@ -81,12 +86,24 @@ public class MythicspoilerComSource implements CardImageSource {
cardNameAliases.put("THS-soldierofpantheon", "soldierofthepantheon");
cardNameAliases.put("THS-vulpinegolaith", "vulpinegoliath");
cardNameAliases.put("ORI-kothopedhoarderofsouls", "kothophedsoulhoarder");
cardNameAliases.put("BFZ-unisonstrike", "tandemtactics");
cardNameAliases.put("BFZ-eldrazidevastator", "eldrazidevastator");
cardNameAliases.put("BFZ-kozliekschanneler", "kozilekschanneler");
cardNameAliasesStart = new HashMap<>();
HashSet<String> names = new HashSet<>();
names.add("eldrazidevastator.jpg");
cardNameAliasesStart.put("BFZ", names);
}
private Map<String, String> getSetLinks(String cardSet) {
Map<String, String> setLinks = new HashMap<>();
try {
String setNames = setsAliases.get(cardSet.toLowerCase());
Set<String> aliasesStart = new HashSet<>();
if (cardNameAliasesStart.containsKey(cardSet)) {
aliasesStart.addAll(cardNameAliasesStart.get(cardSet));
}
if (setNames == null) {
setNames = cardSet.toLowerCase();
}
@ -119,33 +136,42 @@ public class MythicspoilerComSource implements CardImageSource {
}
Elements cardsImages = doc.select("img[src^=cards/]"); // starts with cards/
if (!aliasesStart.isEmpty()) {
for (String text : aliasesStart) {
cardsImages.addAll(doc.select("img[src^=" + text + "]"));
}
}
if (cardsImages.isEmpty()) {
break;
}
for (Element cardsImage : cardsImages) {
String cardLink = cardsImage.attr("src");
String cardName = null;
if (cardLink.startsWith("cards/") && cardLink.endsWith(".jpg")) {
String cardName = cardLink.substring(6, cardLink.length() - 4);
if (cardName != null && !cardName.isEmpty()) {
if (cardNameAliases.containsKey(cardSet + "-" + cardName)) {
cardName = cardNameAliases.get(cardSet + "-" + cardName);
}
if (cardName.endsWith("1") || cardName.endsWith("2") || cardName.endsWith("3") || cardName.endsWith("4") || cardName.endsWith("5")) {
if (!cardName.startsWith("forest")
&& !cardName.startsWith("swamp")
&& !cardName.startsWith("mountain")
&& !cardName.startsWith("island")
&& !cardName.startsWith("plains")) {
cardName = cardName.substring(0, cardName.length() - 1);
}
}
setLinks.put(cardName, baseUrl + cardLink);
}
cardName = cardLink.substring(6, cardLink.length() - 4);
} else if (aliasesStart.contains(cardLink)) {
cardName = cardLink.substring(0, cardLink.length() - 4);;
}
if (cardName != null && !cardName.isEmpty()) {
if (cardNameAliases.containsKey(cardSet + "-" + cardName)) {
cardName = cardNameAliases.get(cardSet + "-" + cardName);
}
if (cardName.endsWith("1") || cardName.endsWith("2") || cardName.endsWith("3") || cardName.endsWith("4") || cardName.endsWith("5")) {
if (!cardName.startsWith("forest")
&& !cardName.startsWith("swamp")
&& !cardName.startsWith("mountain")
&& !cardName.startsWith("island")
&& !cardName.startsWith("plains")) {
cardName = cardName.substring(0, cardName.length() - 1);
}
}
setLinks.put(cardName, baseUrl + cardLink);
}
}
}
} catch (IOException ex) {
System.out.println("Exception when parsing the mythicspoiler page: " + ex.getMessage());
}

View file

@ -0,0 +1,324 @@
/*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package org.mage.plugins.card.dl.sources;
import org.apache.log4j.Logger;
import org.mage.plugins.card.images.CardDownloadData;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Quercitron
*/
public class TokensMtgImageSource implements CardImageSource {
private static final Logger logger = Logger.getLogger(TokensMtgImageSource.class);
private static CardImageSource instance = new TokensMtgImageSource();
public static CardImageSource getInstance() {
if (instance == null) {
instance = new TokensMtgImageSource();
}
return instance;
}
@Override
public String getSourceName() {
return "tokens.mtg.onl";
}
@Override
public Float getAverageSize() {
return 26.7f;
}
@Override
public String generateURL(CardDownloadData card) throws Exception {
return null;
}
private static final String[] EMBLEMS = {
"Ajani",
"Chandra",
"Dack",
"Daretti",
"Domri",
"Elspeth",
"Garruk",
"Gideon",
"Jace",
"Kiora",
"Koth",
"Liliana",
"Narset",
"Nixilis",
"Sarkhan",
"Sorin",
"Tamiyo",
"Teferi",
"Venser",
};
private static final Map<String, String> SET_NAMES_REPLACEMENT = new HashMap<String, String>() {
{
put("con", "CFX");
put("fnmp", "FNM");
}
};
@Override
public String generateTokenUrl(CardDownloadData card) throws IOException {
String name = card.getName();
String set = card.getSet();
int type = card.getType();
// handle emblems
if (name.toLowerCase().contains("emblem")) {
for (String emblem : EMBLEMS) {
if (name.toLowerCase().contains(emblem.toLowerCase())){
name = emblem + " Emblem";
break;
}
}
}
// we should replace some set names
if (SET_NAMES_REPLACEMENT.containsKey(set.toLowerCase())) {
set = SET_NAMES_REPLACEMENT.get(set.toLowerCase());
}
// Image URL contains token number
// e.g. http://tokens.mtg.onl/tokens/ORI_010-Thopter.jpg -- token number 010
// We don't know these numbers, but we can take them from a file
// with tokens information that can be downloaded from the site.
List<TokenData> tokensData = getTokensData();
if (tokensData.isEmpty()) {
return null;
}
List<TokenData> matchedTokens = new ArrayList<TokenData>();
for (TokenData token : tokensData) {
if (name.equalsIgnoreCase(token.getName()) && set.equalsIgnoreCase(token.getExpansionSetCode())) {
matchedTokens.add(token);
}
}
if (matchedTokens.isEmpty()) {
logger.info("Could not find data for token " + name + ", set " + set + ".");
return null;
}
TokenData tokenData;
if (type == 0) {
if (matchedTokens.size() > 1) {
logger.info("Multiple images were found for token " + name + ", set " + set + ".");
}
tokenData = matchedTokens.get(0);
} else {
if (type > matchedTokens.size()) {
logger.warn("Not enough images for token with type " + type + ", name " + name + ", set " + set + ".");
return null;
}
tokenData = matchedTokens.get(card.getType() - 1);
}
String url = "http://tokens.mtg.onl/tokens/" + tokenData.getExpansionSetCode().trim() + "_"
+ tokenData.getNumber().trim() + "-" + tokenData.getName().trim()+ ".jpg";
url = url.replace(' ', '-');
return url;
}
private List<TokenData> tokensData;
private final Object tokensDataSync = new Object();
private List<TokenData> getTokensData() throws IOException {
if (tokensData == null) {
synchronized (tokensDataSync) {
if (tokensData == null) {
tokensData = new ArrayList<TokenData>();
// get tokens data from resource file
InputStream inputStream = null;
try {
inputStream = this.getClass().getResourceAsStream("/tokens-mtg-onl-list.csv");
List<TokenData> fileTokensData = parseTokensData(inputStream);
tokensData.addAll(fileTokensData);
} catch (Exception exception) {
logger.warn("Failed to get tokens description from resource file tokens-mtg-onl-list.csv", exception);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
logger.error("Input stream close failed:", e);
}
}
}
// description on site may contain new information
// try to add it
try {
URL url = new URL("http://tokens.mtg.onl/data/SetsWithTokens.csv");
inputStream = url.openStream();
List<TokenData> siteTokensData = parseTokensData(inputStream);
List<TokenData> newTokensData = new ArrayList<TokenData>();
for (TokenData siteData : siteTokensData) {
boolean isNew = true;
for (TokenData fileData : tokensData) {
if (siteData.getName().equalsIgnoreCase(fileData.getName())
&& siteData.getNumber().equalsIgnoreCase(fileData.getNumber())
&& siteData.getExpansionSetCode().equalsIgnoreCase(fileData.getExpansionSetCode())) {
isNew = false;
break;
}
}
if (isNew) {
newTokensData.add(siteData);
}
}
tokensData.addAll(newTokensData);
} catch (Exception exception) {
logger.warn("Failed to get tokens description from tokens.mtg.onl", exception);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
logger.error("Input stream close failed:", e);
}
}
}
}
}
}
return tokensData;
}
private List<TokenData> parseTokensData(InputStream inputStream) throws IOException {
List<TokenData> tokensData = new ArrayList<TokenData>();
InputStreamReader inputReader = null;
BufferedReader reader = null;
try {
// we have to specify encoding to read special comma
inputReader = new InputStreamReader(inputStream, "Cp1252");
reader = new BufferedReader(inputReader);
reader.readLine(); // skip header
String line = reader.readLine();
// states
// 0 - wait set name
// 1 - wait cards
// 2 - process cards
int state = 0;
String set = null;
while (line != null) {
if (line.trim().isEmpty()) {
if (state == 2) {
state = 0;
}
} else {
if (state == 0) {
set = line.substring(0, 3);
state = 1;
} else {
if (state == 1) {
state = 2;
}
String[] split = line.split(",");
// replace special comma for cards like 'Ashaya the Awoken World'
String name = split[0].replace('', ',');
String number = split[1];
TokenData token = new TokenData(name, number, set);
tokensData.add(token);
}
}
line = reader.readLine();
}
} finally {
if (inputReader != null) {
try {
inputReader.close();
} catch (Exception e) {
logger.error("Input reader close failed:", e);
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
logger.error("Buffered reader close failed:", e);
}
}
}
return tokensData;
}
final class TokenData {
final private String name;
final private String number;
final private String expansionSetCode;
public TokenData(String name, String number, String expansionSetCode) {
this.name = name;
this.number = number;
this.expansionSetCode = expansionSetCode;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public String getExpansionSetCode() {
return expansionSetCode;
}
}
}

View file

@ -99,6 +99,7 @@ public class WizardCardsImageSource implements CardImageSource {
setsAliases.put("BTD", "Beatdown Box Set");
setsAliases.put("C13", "Commander 2013 Edition");
setsAliases.put("C14", "Commander 2014");
setsAliases.put("C15", "Commander 2015");
setsAliases.put("CHK", "Champions of Kamigawa");
setsAliases.put("CHR", "Chronicles");
setsAliases.put("CMD", "Magic: The Gathering-Commander");
@ -123,6 +124,7 @@ public class WizardCardsImageSource implements CardImageSource {
setsAliases.put("DDM", "Duel Decks: Jace vs. Vraska");
setsAliases.put("DDN", "Duel Decks: Speed vs. Cunning");
setsAliases.put("DDO", "Duel Decks: Elspeth vs. Kiora");
setsAliases.put("DDP", "Duel Decks: Zendikar vs. Eldrazi");
setsAliases.put("DGM", "Dragon's Maze");
setsAliases.put("DIS", "Dissension");
setsAliases.put("DKA", "Dark Ascension");

View file

@ -49,17 +49,12 @@ import mage.client.constants.Constants;
import mage.client.dialog.PreferencesDialog;
import mage.client.util.sets.ConstructedFormats;
import mage.remote.Connection;
import static mage.remote.Connection.ProxyType.HTTP;
import static mage.remote.Connection.ProxyType.SOCKS;
import net.java.truevfs.access.TFile;
import net.java.truevfs.access.TFileOutputStream;
import net.java.truevfs.access.TVFS;
import net.java.truevfs.kernel.spec.FsSyncException;
import org.apache.log4j.Logger;
import org.mage.plugins.card.dl.sources.CardImageSource;
import org.mage.plugins.card.dl.sources.MagicCardsImageSource;
import org.mage.plugins.card.dl.sources.MythicspoilerComSource;
import org.mage.plugins.card.dl.sources.WizardCardsImageSource;
import org.mage.plugins.card.dl.sources.*;
import org.mage.plugins.card.properties.SettingsManager;
import org.mage.plugins.card.utils.CardImageUtils;
@ -140,7 +135,16 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
p0.add(jLabel1);
p0.add(Box.createVerticalStrut(5));
ComboBoxModel jComboBox1Model = new DefaultComboBoxModel(new String[] { "magiccards.info", "wizards.com", "mythicspoiler.com" /*, "mtgimage.com (HQ)" , "mtgathering.ru HQ", "mtgathering.ru MQ", "mtgathering.ru LQ"*/});
ComboBoxModel jComboBox1Model = new DefaultComboBoxModel(new String[] {
"magiccards.info",
"wizards.com",
"mythicspoiler.com",
"tokens.mtg.onl",
//"mtgimage.com (HQ)",
//"mtgathering.ru HQ",
//"mtgathering.ru MQ",
//"mtgathering.ru LQ",
});
jComboBox1 = new JComboBox();
cardImageSource = MagicCardsImageSource.getInstance();
@ -161,6 +165,9 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
case 2:
cardImageSource = MythicspoilerComSource.getInstance();
break;
case 3:
cardImageSource = TokensMtgImageSource.getInstance();
break;
}
int count = DownloadPictures.this.cards.size();
float mb = (count * cardImageSource.getAverageSize()) / 1024;
@ -221,7 +228,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
// JOptionPane
Object[] options = { startDownloadButton, closeButton = new JButton("Cancel") };
dlg = new JOptionPane(p0, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
dlg = new JOptionPane(p0, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, options, options[1]);
}
public static boolean checkForNewCards(List<CardInfo> allCards) {
@ -363,23 +370,27 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
while (line != null) {
line = line.trim();
if (line.startsWith("|")) { // new format
String[] params = line.split("\\|");
if (params.length >= 4) {
String[] params = line.split("\\|", -1);
if (params.length >= 5) {
int type = 0;
if (params[4] != null && ! params[4].isEmpty()) {
type = Integer.parseInt(params[4].trim());
}
if (params[1].toLowerCase().equals("generate") && params[2].startsWith("TOK:")) {
String set = params[2].substring(4);
CardDownloadData card = new CardDownloadData(params[3], set, 0, false, 0, "", true);
CardDownloadData card = new CardDownloadData(params[3], set, 0, false, type, "", true);
list.add(card);
} else if (params[1].toLowerCase().equals("generate") && params[2].startsWith("EMBLEM:")) {
String set = params[2].substring(7);
CardDownloadData card = new CardDownloadData("Emblem " + params[3], set, 0, false,0, "", true);
CardDownloadData card = new CardDownloadData("Emblem " + params[3], set, 0, false, type, "", true);
list.add(card);
} else if (params[1].toLowerCase().equals("generate") && params[2].startsWith("EMBLEM-:")) {
String set = params[2].substring(8);
CardDownloadData card = new CardDownloadData(params[3] + " Emblem", set, 0, false, 0, "", true);
CardDownloadData card = new CardDownloadData(params[3] + " Emblem", set, 0, false, type, "", true);
list.add(card);
} else if (params[1].toLowerCase().equals("generate") && params[2].startsWith("EMBLEM!:")) {
String set = params[2].substring(8);
CardDownloadData card = new CardDownloadData(params[3], set, 0, false, 0, "", true);
CardDownloadData card = new CardDownloadData(params[3], set, 0, false, type, "", true);
list.add(card);
}
} else {

View file

@ -25,8 +25,8 @@ import org.mage.plugins.card.utils.CardImageUtils;
/**
* This class stores ALL card images in a cache with soft values. this means
* that the images may be garbage collected when they are not needed any more, but will
* be kept as long as possible.
* that the images may be garbage collected when they are not needed any more,
* but will be kept as long as possible.
*
* Key format: "<cardname>#<setname>#<type>#<collectorID>#<param>"
*
@ -46,8 +46,7 @@ public class ImageCache {
private static final Map<String, BufferedImage> imageCache;
/**
* Common pattern for keys.
* Format: "<cardname>#<setname>#<collectorID>"
* Common pattern for keys. Format: "<cardname>#<setname>#<collectorID>"
*/
private static final Pattern KEY_PATTERN = Pattern.compile("(.*)#(.*)#(.*)#(.*)#(.*)");
@ -104,16 +103,16 @@ public class ImageCache {
thumbnailFile = new TFile(thumbnailPath);
} catch (Exception ex) {
}
boolean exists =false;
boolean exists = false;
if (thumbnailFile != null) {
try {
exists = thumbnailFile.exists();
} catch(Exception ex) {
} catch (Exception ex) {
exists = false;
}
}
if (exists) {
log.debug("loading thumbnail for " + key + ", path="+thumbnailPath);
log.debug("loading thumbnail for " + key + ", path=" + thumbnailPath);
return loadImage(thumbnailFile);
} else {
BufferedImage image = loadImage(file);
@ -187,30 +186,15 @@ public class ImageCache {
}
public static BufferedImage getThumbnail(CardView card) {
String key = getKey(card) + "#thumb";
if (card.getUsesVariousArt()) {
key += "#usesVariousArt";
}
// log.debug("#key: " + key);
return getImage(key);
return getImage(getKey(card, card.getName(), "#thumb"));
}
public static BufferedImage getImageOriginal(CardView card) {
String key = getKey(card);
if (card.getUsesVariousArt()) {
key += "#usesVariousArt";
}
// log.warn("#key: " + key);
return getImage(key);
return getImage(getKey(card, card.getName(), ""));
}
public static BufferedImage getImageOriginalAlternateName(CardView card) {
String key = getKeyAlternateName(card, card.getAlternateName());
if (card.getUsesVariousArt()) {
key += "#usesVariousArt";
}
// log.warn("#key: " + key);
return getImage(key);
return getImage(getKey(card, card.getAlternateName(), ""));
}
/**
@ -230,7 +214,7 @@ public class ImageCache {
if (ex.getCause() instanceof NullPointerException) {
return null;
}
log.error(ex,ex);
log.error(ex, ex);
return null;
}
}
@ -238,32 +222,25 @@ public class ImageCache {
/**
* Returns the map key for a card, without any suffixes for the image size.
*/
private static String getKey(CardView card) {
StringBuilder sb = new StringBuilder(card.getName()).append("#");
sb.append(card.getExpansionSetCode()).append("#");
sb.append(card.getType()).append("#");
sb.append(card.getCardNumber()).append("#");
sb.append(card.getTokenSetCode() == null ? "":card.getTokenSetCode());
return sb.toString();
}
/**
* Returns the map key for the flip image of a card, without any suffixes for the image size.
*/
private static String getKeyAlternateName(CardView card, String alternateName) {
StringBuilder sb = new StringBuilder(alternateName).append("#");
sb.append(card.getExpansionSetCode()).append("#");
sb.append(card.getType()).append("#");
sb.append(card.getCardNumber()).append("#");
sb.append(card.getTokenSetCode() == null ? "":card.getTokenSetCode());
return sb.toString();
private static String getKey(CardView card, String name, String suffix) {
return name + "#" + card.getExpansionSetCode() + "#" + card.getType() + "#" + card.getCardNumber() + "#"
+ (card.getTokenSetCode() == null ? "" : card.getTokenSetCode())
+ suffix
+ (card.getUsesVariousArt() ? "#usesVariousArt" : "");
}
// /**
// * Returns the map key for the flip image of a card, without any suffixes for the image size.
// */
// private static String getKeyAlternateName(CardView card, String alternateName) {
// return alternateName + "#" + card.getExpansionSetCode() + "#" +card.getType()+ "#" + card.getCardNumber() + "#"
// + (card.getTokenSetCode() == null ? "":card.getTokenSetCode());
// }
/**
* Load image from file
*
* @param file
* file to load image from
* @param file file to load image from
* @return {@link BufferedImage}
*/
public static BufferedImage loadImage(TFile file) {
@ -297,7 +274,7 @@ public class ImageCache {
ImageIO.write(image, "jpg", outputStream);
}
} catch (IOException e) {
log.error(e,e);
log.error(e, e);
imageFile.delete();
}
return image;
@ -305,6 +282,7 @@ public class ImageCache {
/**
* Returns an image scaled to the size given
*
* @param original
* @return
*/
@ -344,6 +322,7 @@ public class ImageCache {
/**
* Returns an image scaled to the size appropriate for the card picture
* panel
*
* @param original
* @param sizeNeed
* @return
@ -356,6 +335,7 @@ public class ImageCache {
/**
* Returns the image appropriate to display the card in the picture panel
*
* @param card
* @param width
* @param height
@ -365,11 +345,7 @@ public class ImageCache {
if (Constants.THUMBNAIL_SIZE_FULL.width + 10 > width) {
return getThumbnail(card);
}
String key = getKey(card);
if (card.getUsesVariousArt()) {
key += "#usesVariousArt";
}
// log.warn("getImage: " + key);
String key = getKey(card, card.getName(), "");
BufferedImage original = getImage(key);
if (original == null) {
log.debug(key + " not found");

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