余録

#! /usr/bin/env python
# coding: utf-8
## ----------------------------------------
##
## (C) Copyright 2000-2010, 小粒ちゃん《監修》小泉ひよ子とタマゴ倶楽部
##
## ----------------------------------------
## History: Swing Example "2010 FIFA World Cup South Africa"
##      2003/07, Java/Jython
##      2006/07, Jython
##      2008/02, Jython 2.2.1
##      2010/06, Jython 2.5.0
#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
"""
>>> tips()

>>> ## ----------------------------------------
>>> None
version: #1.0.18
"""
from __init__ import *

## ----------------------------------------
## 気軽に Swing〔2〕JTextArea: 各チーム紹介
## Java.use(better,Jython=Swing) 〜 萬プログラマーのための Python 導入ガイド
## ----------------------------------------
## ----------------------------------------
## 2008/03/17《2.1》今回の課題:相手チームを知ろう
## ----------------------------------------
from os.path import dirname, exists
from sys import argv

from java.awt import BorderLayout
from java.awt import Font
from javax.swing import ImageIcon
from javax.swing import JFrame
from javax.swing import JLabel
from javax.swing import JPanel
from javax.swing import JScrollPane
from javax.swing import JSplitPane
from javax.swing import JTabbedPane
from javax.swing import JTable
from javax.swing import JTextArea
from javax.swing import ListSelectionModel
from javax.swing.table import DefaultTableModel

## ----------------------------------------
class GroupListPanel(JPanel):

    groupTabs = "ABCDEFGH"
    groups = {
        "A": [                          # Group A
            {"rsa": "South Africa"},
            {"mex": "Mexico"},
            {"uru": "Uruguay"},
            {"fra": "France"},
            ],
        "B": [                          # Group B
            {"arg": "Argentina"},
            {"nga": "Nigeria"},
            {"kor": "Korea Republic"},
            {"gre": "Greece"},
            ],
        "C": [                          # Group C
            {"eng": "England"},
            {"usa": "USA"},
            {"alg": "Algeria"},
            {"svn": "Slovenia"},
            ],
        "D": [                          # Group D
            {"ger": "Germany"},
            {"aus": "Australia"},
            {"srb": "Serbia"},
            {"gha": "Ghana"},
            ],
        "E": [                          # Group E
            {"ned": "Netherlands"},
            {"den": "Denmark"},
            {"jpn": "Japan"},
            {"cmr": "Cameroon"},
            ],
        "F": [                          # Group F
            {"ita": "Italy"},
            {"par": "Paraguay"},
            {"nzl": "New Zealand"},
            {"svk": "Slovakia"},
            ],
        "G": [                          # Group G
            {"bra": "Brazil"},
            {"prk": "Korea DPR"},
            {"civ": "Cote d'Ivoire"},
            {"por": "Portugal"},
            ],
        "H": [                          # Group H
            {"esp": "Spain"},
            {"sui": "Switzerland"},
            {"hon": "Honduras"},
            {"chi": "Chile"},
            ],
        }
    teamNames = dict*1

    ## ----------------------------------------
    def __init__(self, master, *args, **keys):
        self.teams = {}
        self.label = {}
        self.textArea = {}
        self.tab = None
        self.scores = self._scores()
        self.master = master

        self.table = {}

        def splitPane(group):
            controlPane = self._controlPane(
                group = group,
                minimumSize = (200,84),
                )
            canvasPane = self._canvasPane(
                group = group,
                minimumSize = (200,50),
                )
            return self._splitPane(
                leftComponent  = controlPane,
                rightComponent = canvasPane,
                )
        
        master.contentPane = self._tabbedPane(
            panes = dict((e, splitPane(e)) for e in self.groupTabs),
            )
        self._update("South Africa")

    ## ----------------------------------------
    def _scores(self):
        def valid(line):
            for prefix in "Group","Team","Details":
                if line.startswith(prefix):
                    return False
            else:
                return True

        scores = {}
        path = "%s/score/score.txt"%dirname(argv[-1])
        lines = open(path).readlines() if exists(path) else []
        for line in lines:
            if valid(line):
                s = line.split("\t")
                team = self.teamNames[s[0]]
                scores[team] = [int(e) for e in s[1:]]
        return scores

    ## ----------------------------------------
    def _controlPane(self, group, minimumSize, **keys):
        columnNames = "Team","MP","W","D","L","GF","GA","Pts",

        def teams(group):
            return [(k,v) for team in self.groups[group]
                for k,v in team.items()]

        def tableModel(group):
            self.teams[group] = \
            model = DefaultTableModel()
            for e in columnNames:
                model.addColumn(e)
            for k,v in teams(group):
                model.addRow([v]+list(self.scores[k]))
            return model

        def view(group):
            self.table[group] = \
            comp = JTable(
                model = tableModel(group),
                toolTipText = ",\t".join(columnNames),
                )
            comp.selectionModel.valueChanged = self

            model = comp.columnModel    ;print("model::",model)
            model.getColumn(0).preferredWidth = 100
            pass; print("getColumn(0)::",model.getColumn(0))
            for i in range(1, model.columnCount):
                model.getColumn(i).preferredWidth = 30
            return comp
        
        pane = JScrollPane(
            viewportView = view(group),
            minimumSize = minimumSize,
            )
        return pane

    ## ----------------------------------------
    def _canvasPane(self, group, minimumSize, **keys):
        comp = JPanel(
            layout = BorderLayout(),
            )
        for layout, e in [
            ("WEST"  , self._labelPane(group)            ),
            ("CENTER", self._textPane(group, minimumSize)),
            ]:
            comp.add(e, getattr(BorderLayout, layout))
        return comp

    def _labelPane(self, group, **keys):
        def view(group):
            self.label[group] = \
            comp = JLabel(
                horizontalAlignment = JLabel.CENTER,
                horizontalTextPosition = JLabel.CENTER,
                verticalTextPosition = JLabel.BOTTOM,
                preferredSize = (100,50),
                )
            comp.font = comp.font.deriveFont(Font.ITALIC)
            return comp        

        comp = view(group)
        return comp

    def _textPane(self, group, minimumSize, **keys):
        def view(group):
            self.textArea[group] = \
            comp = JTextArea(
                lineWrap = True,
                wrapStyleWord = True,
                )
            comp.font = comp.font.deriveFont(Font.ITALIC)
            return comp        

        comp = JScrollPane(
            viewportView = view(group),
            minimumSize = minimumSize,
            )
        return comp

    ## ----------------------------------------
    def _splitPane(self, **keys):
        comp = JSplitPane(
            orientation = JSplitPane.VERTICAL_SPLIT,
            oneTouchExpandable = True,
            dividerLocation = 90,
            **keys
            )
        return comp

    def _tabbedPane(self, panes, **keys):
        def stateChanged(e):
            index = e.source.selectedIndex
            self.tab = self.groupTabs[index]
            e.source.toolTipText = "group %s"%self.tab

        comp = JTabbedPane(
            stateChanged = stateChanged,
            )
        for e in self.groupTabs:
            comp.addTab(e, panes[e])
        return comp
        
    ## ----------------------------------------
    def __call__(self, e):    # ListSelectionListener.valueChanged
        row = e.source.leadSelectionIndex
        value = self.teams[self.tab].getValueAt(row, 0)
        self._update(value)

    def _update(self, value=None):
        def name(key):
            for group in self.groups.values():
                for team in group:
                    if key in team:
                        return team[key]
            else:
                return None

        def imageIcon(path):
            return ImageIcon(path) if exists(path) else None

        def update_label(tab, path):
            comp = self.label[tab]
            comp.icon = imageIcon(
                "%s/squad/%s.gif"%(path, self.teamNames[value]))
            comp.text = value
            comp.toolTipText = self.teamNames[value]

        def contents(path):
            return "".join([e for e in open(path)]) if exists(path) else None

        def update_textArea(tab, path):
            comp = self.textArea[tab]
            text = contents(
                "%s/profile/%s.txt"%(path, value))
            comp.text = text if text else "*** File not found ***"
            comp.caretPosition = 0
            comp.toolTipText = value

        def update_table(tab):
            comp = self.table[tab]
            comp.toolTipText = value

        tab = self.tab
        path = dirname(argv[-1])
        update_label(tab, path)
        update_textArea(tab, path)
        update_table(tab)

## ----------------------------------------
def tips():
    frame = JFrame(
        title = u"2010 FIFA World Cup South Africa™",
        size = (350,300),
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
        locationRelativeTo = None,
        )
    GroupListPanel(frame)
    frame.show()

## ----------------------------------------
from doctest import testmod

if __name__=='__main__':
    inform()
    testmod()

*1:v,k) for group in groups.values() for team in group for k,v in team.items(