Search in sources :

Example 1 with UiContext

use of games.strategy.triplea.ui.UiContext in project triplea by triplea-game.

the class PlayerChatRenderer method setIconMap.

private void setIconMap() {
    final PlayerManager playerManager = game.getPlayerManager();
    PlayerList playerList;
    game.getData().acquireReadLock();
    try {
        playerList = game.getData().getPlayerList();
    } finally {
        game.getData().releaseReadLock();
    }
    // new HashSet removes duplicates
    for (final INode playerNode : new HashSet<>(playerManager.getPlayerMapping().values())) {
        final Set<String> players = playerManager.getPlayedBy(playerNode);
        if (players.size() > 0) {
            final List<Icon> icons = players.stream().filter(player -> uiContext != null && uiContext.getFlagImageFactory() != null).map(player -> new ImageIcon(uiContext.getFlagImageFactory().getSmallFlag(playerList.getPlayerId(player)))).collect(Collectors.toList());
            maxIconCounter = Math.max(maxIconCounter, icons.size());
            playerMap.put(playerNode.toString(), players);
            if (uiContext == null) {
                iconMap.put(playerNode.toString(), null);
            } else {
                iconMap.put(playerNode.toString(), icons);
            }
        }
    }
}
Also used : DefaultListCellRenderer(javax.swing.DefaultListCellRenderer) INode(games.strategy.net.INode) JList(javax.swing.JList) Set(java.util.Set) PlayerList(games.strategy.engine.data.PlayerList) HashMap(java.util.HashMap) Icon(javax.swing.Icon) Component(java.awt.Component) Collectors(java.util.stream.Collectors) SwingConstants(javax.swing.SwingConstants) PlayerManager(games.strategy.engine.data.PlayerManager) HashSet(java.util.HashSet) List(java.util.List) UiContext(games.strategy.triplea.ui.UiContext) IGame(games.strategy.engine.framework.IGame) ImageIcon(javax.swing.ImageIcon) Joiner(com.google.common.base.Joiner) ImageIcon(javax.swing.ImageIcon) INode(games.strategy.net.INode) PlayerManager(games.strategy.engine.data.PlayerManager) PlayerList(games.strategy.engine.data.PlayerList) Icon(javax.swing.Icon) ImageIcon(javax.swing.ImageIcon) HashSet(java.util.HashSet)

Example 2 with UiContext

use of games.strategy.triplea.ui.UiContext in project triplea by triplea-game.

the class ScreenshotExporter method save.

private void save(final GameData gameData, final HistoryNode node, final File file) throws IOException {
    // get round/step/player from history tree
    int round = 0;
    final Object[] pathFromRoot = node.getPath();
    for (final Object pathNode : pathFromRoot) {
        final HistoryNode curNode = (HistoryNode) pathNode;
        if (curNode instanceof Round) {
            round = ((Round) curNode).getRoundNo();
        }
    }
    final UiContext uiContext = frame.getUiContext();
    final double scale = uiContext.getScale();
    // print map panel to image
    final MapPanel mapPanel = frame.getMapPanel();
    final BufferedImage mapImage = Util.createImage((int) (scale * mapPanel.getImageWidth()), (int) (scale * mapPanel.getImageHeight()), false);
    final Graphics2D mapGraphics = mapImage.createGraphics();
    try {
        // workaround to get the whole map
        // (otherwise the map is cut if current window is not on top of map)
        final int offsetX = mapPanel.getXOffset();
        final int offsetY = mapPanel.getYOffset();
        mapPanel.setTopLeft(0, 0);
        mapPanel.drawMapImage(mapGraphics);
        mapPanel.setTopLeft(offsetX, offsetY);
        // overlay title
        Color titleColor = uiContext.getMapData().getColorProperty(MapData.PROPERTY_SCREENSHOT_TITLE_COLOR);
        if (titleColor == null) {
            titleColor = Color.BLACK;
        }
        final String encodedTitleX = uiContext.getMapData().getProperty(MapData.PROPERTY_SCREENSHOT_TITLE_X);
        final String encodedTitleY = uiContext.getMapData().getProperty(MapData.PROPERTY_SCREENSHOT_TITLE_Y);
        final String encodedTitleSize = uiContext.getMapData().getProperty(MapData.PROPERTY_SCREENSHOT_TITLE_FONT_SIZE);
        int titleX;
        int titleY;
        int titleSize;
        try {
            titleX = (int) (Integer.parseInt(encodedTitleX) * scale);
            titleY = (int) (Integer.parseInt(encodedTitleY) * scale);
            titleSize = Integer.parseInt(encodedTitleSize);
        } catch (final NumberFormatException nfe) {
            // choose safe defaults
            titleX = (int) (15 * scale);
            titleY = (int) (15 * scale);
            titleSize = 15;
        }
        // everything else should be scaled down onto map image
        final AffineTransform transform = new AffineTransform();
        transform.scale(scale, scale);
        mapGraphics.setTransform(transform);
        mapGraphics.setFont(new Font("Ariel", Font.BOLD, titleSize));
        mapGraphics.setColor(titleColor);
        if (uiContext.getMapData().getBooleanProperty(MapData.PROPERTY_SCREENSHOT_TITLE_ENABLED)) {
            mapGraphics.drawString(gameData.getGameName() + " Round " + round, titleX, titleY);
        }
        // save Image as .png
        ImageIO.write(mapImage, "png", file);
    } finally {
        // Clean up objects. There might be some overkill here,
        // but there were memory leaks that are fixed by some/all of these.
        mapImage.flush();
        mapGraphics.dispose();
    }
}
Also used : MapPanel(games.strategy.triplea.ui.MapPanel) Color(java.awt.Color) BufferedImage(java.awt.image.BufferedImage) Font(java.awt.Font) Graphics2D(java.awt.Graphics2D) HistoryNode(games.strategy.engine.history.HistoryNode) Round(games.strategy.engine.history.Round) AffineTransform(java.awt.geom.AffineTransform) UiContext(games.strategy.triplea.ui.UiContext)

Example 3 with UiContext

use of games.strategy.triplea.ui.UiContext in project triplea by triplea-game.

the class PlayerUnitsPanel method init.

/**
 * Sets up components to an initial state.
 */
public void init(final PlayerID id, final List<Unit> units, final boolean land) {
    isLand = land;
    categories = new ArrayList<>(categorize(id, units));
    categories.sort(Comparator.comparing(UnitCategory::getType, (ut1, ut2) -> {
        final UnitAttachment u1 = UnitAttachment.get(ut1);
        final UnitAttachment u2 = UnitAttachment.get(ut2);
        // For land battles, sort by land, air, can't combat move (AA), bombarding
        if (land) {
            if (u1.getIsSea() != u2.getIsSea()) {
                return u1.getIsSea() ? 1 : -1;
            }
            final boolean u1CanNotCombatMove = Matches.unitTypeCanNotMoveDuringCombatMove().test(ut1) || !Matches.unitTypeCanMove(id).test(ut1);
            final boolean u2CanNotCombatMove = Matches.unitTypeCanNotMoveDuringCombatMove().test(ut2) || !Matches.unitTypeCanMove(id).test(ut2);
            if (u1CanNotCombatMove != u2CanNotCombatMove) {
                return u1CanNotCombatMove ? 1 : -1;
            }
            if (u1.getIsAir() != u2.getIsAir()) {
                return u1.getIsAir() ? 1 : -1;
            }
        } else {
            if (u1.getIsSea() != u2.getIsSea()) {
                return u1.getIsSea() ? -1 : 1;
            }
        }
        return u1.getName().compareTo(u2.getName());
    }));
    removeAll();
    final Predicate<UnitType> predicate;
    if (land) {
        if (defender) {
            predicate = Matches.unitTypeIsNotSea();
        } else {
            predicate = Matches.unitTypeIsNotSea().or(Matches.unitTypeCanBombard(id));
        }
    } else {
        predicate = Matches.unitTypeIsSeaOrAir();
    }
    final IntegerMap<UnitType> costs;
    try {
        data.acquireReadLock();
        costs = TuvUtils.getCostsForTuv(id, data);
    } finally {
        data.releaseReadLock();
    }
    for (final UnitCategory category : categories) {
        if (predicate.test(category.getType())) {
            final UnitPanel upanel = new UnitPanel(uiContext, category, costs);
            upanel.addChangeListener(this::notifyListeners);
            add(upanel);
        }
    }
    // TODO: probably do not need to do this much revalidation.
    invalidate();
    validate();
    revalidate();
    getParent().invalidate();
}
Also used : UnitAttachment(games.strategy.triplea.attachments.UnitAttachment) NamedAttachable(games.strategy.engine.data.NamedAttachable) TuvUtils(games.strategy.triplea.util.TuvUtils) UnitSeperator(games.strategy.triplea.util.UnitSeperator) ArrayList(java.util.ArrayList) UnitCategory(games.strategy.triplea.util.UnitCategory) UiContext(games.strategy.triplea.ui.UiContext) UnitType(games.strategy.engine.data.UnitType) LinkedHashSet(java.util.LinkedHashSet) BoxLayout(javax.swing.BoxLayout) CollectionUtils(games.strategy.util.CollectionUtils) IntegerMap(games.strategy.util.IntegerMap) Unit(games.strategy.engine.data.Unit) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Territory(games.strategy.engine.data.Territory) Component(java.awt.Component) GameData(games.strategy.engine.data.GameData) List(java.util.List) PlayerID(games.strategy.engine.data.PlayerID) ProductionFrontier(games.strategy.engine.data.ProductionFrontier) Matches(games.strategy.triplea.delegate.Matches) ProductionRule(games.strategy.engine.data.ProductionRule) Comparator(java.util.Comparator) JPanel(javax.swing.JPanel) UnitAttachment(games.strategy.triplea.attachments.UnitAttachment) UnitType(games.strategy.engine.data.UnitType) UnitCategory(games.strategy.triplea.util.UnitCategory)

Example 4 with UiContext

use of games.strategy.triplea.ui.UiContext in project triplea by triplea-game.

the class HelpMenu method addUnitHelpMenu.

private void addUnitHelpMenu() {
    final String unitHelpTitle = "Unit Help";
    final JMenuItem unitMenuItem = add(SwingAction.of(unitHelpTitle, e -> {
        final JEditorPane editorPane = new JEditorPane();
        editorPane.setEditable(false);
        editorPane.setContentType("text/html");
        editorPane.setText(getUnitStatsTable(gameData, uiContext));
        editorPane.setCaretPosition(0);
        final JScrollPane scroll = new JScrollPane(editorPane);
        scroll.setBorder(BorderFactory.createEmptyBorder());
        final Dimension screenResolution = Toolkit.getDefaultToolkit().getScreenSize();
        // not only do we have a start bar, but we also have the message dialog to account for just the scroll bars plus
        // the window sides
        final int availHeight = screenResolution.height - 120;
        final int availWidth = screenResolution.width - 40;
        scroll.setPreferredSize(new Dimension((scroll.getPreferredSize().width > availWidth ? availWidth : (scroll.getPreferredSize().height > availHeight ? Math.min(availWidth, scroll.getPreferredSize().width + 22) : scroll.getPreferredSize().width)), (scroll.getPreferredSize().height > availHeight ? availHeight : (scroll.getPreferredSize().width > availWidth ? Math.min(availHeight, scroll.getPreferredSize().height + 22) : scroll.getPreferredSize().height))));
        final JDialog dialog = new JDialog((JFrame) null, unitHelpTitle);
        dialog.add(scroll, BorderLayout.CENTER);
        final JPanel buttons = new JPanel();
        final JButton button = new JButton(SwingAction.of("OK", event -> {
            dialog.setVisible(false);
            dialog.removeAll();
            dialog.dispose();
        }));
        buttons.add(button);
        dialog.getRootPane().setDefaultButton(button);
        dialog.add(buttons, BorderLayout.SOUTH);
        dialog.pack();
        dialog.addWindowListener(new WindowAdapter() {

            @Override
            public void windowOpened(final WindowEvent e) {
                scroll.getVerticalScrollBar().getModel().setValue(0);
                scroll.getHorizontalScrollBar().getModel().setValue(0);
                button.requestFocus();
            }
        });
        dialog.setVisible(true);
    }));
    unitMenuItem.setMnemonic(KeyEvent.VK_U);
    unitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
}
Also used : Color(java.awt.Color) Rectangle(java.awt.Rectangle) SystemProperties(games.strategy.engine.framework.system.SystemProperties) SwingComponents(games.strategy.ui.SwingComponents) JDialog(javax.swing.JDialog) URL(java.net.URL) TuvUtils(games.strategy.triplea.util.TuvUtils) SwingUtilities(javax.swing.SwingUtilities) JMenuItem(javax.swing.JMenuItem) Map(java.util.Map) Application(com.apple.eawt.Application) UiContext(games.strategy.triplea.ui.UiContext) JEditorPane(javax.swing.JEditorPane) UnitType(games.strategy.engine.data.UnitType) BorderLayout(java.awt.BorderLayout) JFrame(javax.swing.JFrame) ClientContext(games.strategy.engine.ClientContext) KeyStroke(javax.swing.KeyStroke) JButton(javax.swing.JButton) JLabelBuilder(swinglib.JLabelBuilder) UnitImageFactory(games.strategy.triplea.image.UnitImageFactory) JMenu(javax.swing.JMenu) BorderFactory(javax.swing.BorderFactory) KeyEvent(java.awt.event.KeyEvent) WindowAdapter(java.awt.event.WindowAdapter) JOptionPane(javax.swing.JOptionPane) WindowEvent(java.awt.event.WindowEvent) JScrollPane(javax.swing.JScrollPane) GameData(games.strategy.engine.data.GameData) Dimension(java.awt.Dimension) List(java.util.List) PlayerID(games.strategy.engine.data.PlayerID) ResourceCollection(games.strategy.engine.data.ResourceCollection) JLabel(javax.swing.JLabel) UrlConstants(games.strategy.triplea.UrlConstants) Optional(java.util.Optional) LocalizeHtml(games.strategy.util.LocalizeHtml) JPanel(javax.swing.JPanel) Toolkit(java.awt.Toolkit) SwingAction(games.strategy.ui.SwingAction) JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) JFrame(javax.swing.JFrame) WindowEvent(java.awt.event.WindowEvent) JEditorPane(javax.swing.JEditorPane) JButton(javax.swing.JButton) WindowAdapter(java.awt.event.WindowAdapter) Dimension(java.awt.Dimension) JMenuItem(javax.swing.JMenuItem) JDialog(javax.swing.JDialog)

Example 5 with UiContext

use of games.strategy.triplea.ui.UiContext in project triplea by triplea-game.

the class ExportMenu method addExportUnitStats.

private void addExportUnitStats() {
    final JMenuItem menuFileExport = new JMenuItem(SwingAction.of("Export Unit Charts", e -> {
        final JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        final File rootDir = new File(SystemProperties.getUserDir());
        String defaultFileName = gameData.getGameName() + "_unit_stats";
        defaultFileName = FileNameUtils.removeIllegalCharacters(defaultFileName);
        defaultFileName = defaultFileName + ".html";
        chooser.setSelectedFile(new File(rootDir, defaultFileName));
        if (chooser.showSaveDialog(frame) != JOptionPane.OK_OPTION) {
            return;
        }
        try (Writer writer = Files.newBufferedWriter(chooser.getSelectedFile().toPath(), StandardCharsets.UTF_8)) {
            writer.write(HelpMenu.getUnitStatsTable(gameData, uiContext).replaceAll("<p>", "<p>\r\n").replaceAll("</p>", "</p>\r\n").replaceAll("</tr>", "</tr>\r\n").replaceAll(LocalizeHtml.PATTERN_HTML_IMG_TAG, ""));
        } catch (final IOException e1) {
            ClientLogger.logQuietly("Failed to write unit stats: " + chooser.getSelectedFile().getAbsolutePath(), e1);
        }
    }));
    menuFileExport.setMnemonic(KeyEvent.VK_U);
    add(menuFileExport);
}
Also used : ExtendedStats(games.strategy.triplea.ui.ExtendedStats) Arrays(java.util.Arrays) Enumeration(java.util.Enumeration) GameDataUtils(games.strategy.engine.framework.GameDataUtils) HistoryNode(games.strategy.engine.history.HistoryNode) UnitAttachment(games.strategy.triplea.attachments.UnitAttachment) TripleAFrame(games.strategy.triplea.ui.TripleAFrame) GameDataExporter(games.strategy.engine.data.export.GameDataExporter) JFileChooser(javax.swing.JFileChooser) JFrame(javax.swing.JFrame) Round(games.strategy.engine.history.Round) ClientContext(games.strategy.engine.ClientContext) Collection(java.util.Collection) Set(java.util.Set) JMenu(javax.swing.JMenu) PlayerOrderComparator(games.strategy.triplea.util.PlayerOrderComparator) KeyEvent(java.awt.event.KeyEvent) StandardCharsets(java.nio.charset.StandardCharsets) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) HistoryPanel(games.strategy.triplea.ui.history.HistoryPanel) GameData(games.strategy.engine.data.GameData) List(java.util.List) PlayerID(games.strategy.engine.data.PlayerID) Writer(java.io.Writer) LocalizeHtml(games.strategy.util.LocalizeHtml) WindowConstants(javax.swing.WindowConstants) SwingAction(games.strategy.ui.SwingAction) SystemProperties(games.strategy.engine.framework.system.SystemProperties) SetupFrame(games.strategy.triplea.printgenerator.SetupFrame) TreeNode(javax.swing.tree.TreeNode) LocalDateTime(java.time.LocalDateTime) Action(javax.swing.Action) Resource(games.strategy.engine.data.Resource) ArrayList(java.util.ArrayList) JMenuItem(javax.swing.JMenuItem) UiContext(games.strategy.triplea.ui.UiContext) UnitType(games.strategy.engine.data.UnitType) LinkedHashSet(java.util.LinkedHashSet) JComponent(javax.swing.JComponent) Files(java.nio.file.Files) IOException(java.io.IOException) IStat(games.strategy.engine.stats.IStat) JOptionPane(javax.swing.JOptionPane) ScreenshotExporter(games.strategy.triplea.ui.export.ScreenshotExporter) File(java.io.File) ClientLogger(games.strategy.debug.ClientLogger) FileNameUtils(games.strategy.util.FileNameUtils) Step(games.strategy.engine.history.Step) DateTimeFormatter(java.time.format.DateTimeFormatter) EndRoundDelegate(games.strategy.triplea.delegate.EndRoundDelegate) ProductionRule(games.strategy.engine.data.ProductionRule) JFileChooser(javax.swing.JFileChooser) IOException(java.io.IOException) JMenuItem(javax.swing.JMenuItem) File(java.io.File) Writer(java.io.Writer)

Aggregations

UiContext (games.strategy.triplea.ui.UiContext)7 GameData (games.strategy.engine.data.GameData)4 List (java.util.List)4 PlayerID (games.strategy.engine.data.PlayerID)3 UnitType (games.strategy.engine.data.UnitType)3 SwingAction (games.strategy.ui.SwingAction)3 KeyEvent (java.awt.event.KeyEvent)3 Set (java.util.Set)3 JMenu (javax.swing.JMenu)3 JMenuItem (javax.swing.JMenuItem)3 JOptionPane (javax.swing.JOptionPane)3 JPanel (javax.swing.JPanel)3 ClientContext (games.strategy.engine.ClientContext)2 ProductionRule (games.strategy.engine.data.ProductionRule)2 IGame (games.strategy.engine.framework.IGame)2 SystemProperties (games.strategy.engine.framework.system.SystemProperties)2 HistoryNode (games.strategy.engine.history.HistoryNode)2 Round (games.strategy.engine.history.Round)2 UnitAttachment (games.strategy.triplea.attachments.UnitAttachment)2 TripleAFrame (games.strategy.triplea.ui.TripleAFrame)2