Example #1
0
class SelectTileDialogWithPreview(MfxDialog):

    def __init__(self, parent, title, app, manager, key=None, **kw):
        kw = self.initKw(kw)
        MfxDialog.__init__(self, parent, title, **kw)
        #
        top_box, bottom_box = self.createHBox()
        #
        if key is None:
            key = manager.getSelected()
        self.app = app
        self.manager = manager
        self.key = key
        self.preview_key = -1
        self.all_keys = []
        self.table_color = app.opt.colors['table']
        # paned
        hpaned = gtk.HPaned()
        self.hpaned = hpaned
        hpaned.show()
        top_box.pack_start(hpaned, expand=True, fill=True)
        #
        model = self._createStore(manager, key)
        treeview = PysolTreeView(self, model)
        self.treeview = treeview
        hpaned.pack1(treeview.scrolledwindow, True, True)
        treeview.treeview.expand_all()
        #
        self.preview = MfxCanvas(top_box)  # width=w2
        hpaned.pack2(self.preview, True, True)
        self.preview.show()
        hpaned.set_position(240)

        self.createButtons(bottom_box, kw)

        self.updatePreview(key)

        self.show_all()
        gtk.main()

    def rowActivated(self, w, row, col):
        # FIXME
        print('row-activated-event', row, col)

    def getSelected(self):
        index = self.treeview.getSelected()
        if index < 0:
            return None
        return self.all_keys[index]

    def showSelected(self, w):
        key = self.getSelected()
        self.updatePreview(key)

    def _createStore(self, manager, key):
        self.all_keys = []
        index = 0
        #
        model = gtk.TreeStore(gobject.TYPE_STRING,
                              gobject.TYPE_INT)
        #
        iter = model.append(None)
        model.set(iter, 0, _('Solid color'), 1, -1)
        for color, value in ((_('Blue'),   '#0082df'),
                             (_('Green'),  '#008200'),
                             (_('Navy'),   '#000086'),
                             (_('Olive'),  '#868200'),
                             (_('Orange'), '#f79600'),
                             (_('Teal'),   '#008286'),):
            child_iter = model.append(iter)
            model.set(child_iter, 0, color, 1, index)
            self.all_keys.append(value)
            index += 1
        #
        tiles = manager.getAllSortedByName()
        tiles = [obj for obj in tiles if not obj.error]
        tiles = [tile for tile in tiles if tile.index > 0 and tile.filename]
        #
        iter = model.append(None)
        model.set(iter, 0, _('All Backgrounds'), 1, -1)
        if tiles:
            for tile in tiles:
                child_iter = model.append(iter)
                model.set(child_iter, 0, tile.name, 1, index)
                self.all_keys.append(tile.index)
                index += 1
        else:
            child_iter = model.append(iter)
            model.set(child_iter, 0, _('(no tiles)'), 1, -1)

        return model

    def updatePreview(self, key):
        # print 'updatePreview:', key, type(key)
        if key is None:
            return
        if key == self.preview_key:
            return
        canvas = self.preview
        # canvas.deleteAllItems()
        if isinstance(key, str):
            # solid color
            canvas.setTile(self.app, 0, force=True)
            canvas.config(bg=key)
            # canvas.setTextColor(None)
            self.preview_key = key
            self.table_color = key
        else:
            # image
            if self.preview.setTile(self.app, key):
                self.preview_key = key
            else:
                self.preview_key = -1

    def initKw(self, kw):
        kwdefault(kw,
                  strings=(_('&OK'), _('&Solid color...'), _('&Cancel'),),
                  default=0,
                  resizable=1,
                  padx=10, pady=10,
                  width=600, height=400,
                  )
        return MfxDialog.initKw(self, kw)

    def _colorselOkClicked(self, w, d):
        c = d.colorsel.get_current_color()
        c = '#%02x%02x%02x' % (c.red//256, c.green//256, c.blue//256)
        d.destroy()
        self.updatePreview(c)
        self.treeview.unselectAll()

    def createColorsel(self):
        win = gtk.ColorSelectionDialog(_('Select table color'))
        win.help_button.destroy()
        win.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        if isinstance(self.preview_key, str):
            color = self.preview_key
        else:
            color = self.app.opt.colors['table']
        win.colorsel.set_current_color(gdk.color_parse(color))
        win.connect('delete_event', lambda w, e: win.destroy())
        win.ok_button.connect('clicked', self._colorselOkClicked, win)
        win.cancel_button.connect('clicked', lambda w: win.destroy())
        setTransient(win, self)
        win.show()

    def done(self, button):
        b = button.get_data('user_data')
        if b == 1:
            self.createColorsel()
            return
        if b == 0:
            self.key = self.getSelected()
            if not self.key:
                self.key = self.preview_key
        self.status = 0
        self.button = b
        # self.hide()
        self.quit()
Example #2
0
class SelectGameDialogWithPreview(MfxDialog):
    #Tree_Class = SelectGameTreeWithPreview
    game_store = None
    #
    _paned_position = 300
    _expanded_rows = []
    _geometry = None
    _selected_row = None
    _vadjustment_position = None

    def __init__(self, parent, title, app, gameid, bookmark=None, **kw):
        kw = self.initKw(kw)
        MfxDialog.__init__(self, parent, title, **kw)
        #
        self.app = app
        self.gameid = gameid
        self.bookmark = bookmark
        self.random = None
        #
        if self.game_store is None:
            self.createGameStore()
        #
        top_box, bottom_box = self.createHBox()
        # paned
        hpaned = gtk.HPaned()
        self.hpaned = hpaned
        hpaned.show()
        top_box.pack_start(hpaned, expand=True, fill=True)
        # left
        self.treeview = PysolTreeView(self, self.game_store)
        hpaned.pack1(self.treeview.scrolledwindow, True, True)
        # right
        table = gtk.Table(2, 2, False)
        table.show()
        hpaned.pack2(table, True, True)
        # frames
        frame = gtk.Frame(label=_('About game'))
        frame.show()
        table.attach(frame,
                     0, 1,      0, 1,
                     gtk.FILL,  gtk.FILL,
                     0,         0)
        frame.set_border_width(4)
        info_frame = gtk.Table(2, 7, False)
        info_frame.show()
        frame.add(info_frame)
        info_frame.set_border_width(4)
        #
        frame = gtk.Frame(label=_('Statistics'))
        frame.show()
        table.attach(frame,
                     1, 2,      0, 1,
                     gtk.FILL,  gtk.FILL,
                     0,         0)
        frame.set_border_width(4)
        stats_frame = gtk.Table(2, 6, False)
        stats_frame.show()
        frame.add(stats_frame)
        stats_frame.set_border_width(4)
        # info
        self.info_labels = {}
        i = 0
        for n, t, f, row in (
            ('name',        _('Name:'),             info_frame,   0),
            ('altnames',    _('Alternate names:'),  info_frame,   1),
            ('category',    _('Category:'),         info_frame,   2),
            ('type',        _('Type:'),             info_frame,   3),
            ('skill_level', _('Skill level:'),      info_frame,   4),
            ('decks',       _('Decks:'),            info_frame,   5),
            ('redeals',     _('Redeals:'),          info_frame,   6),
            #
            ('played',      _('Played:'),           stats_frame,  0),
            ('won',         _('Won:'),              stats_frame,  1),
            ('lost',        _('Lost:'),             stats_frame,  2),
            ('time',        _('Playing time:'),     stats_frame,  3),
            ('moves',       _('Moves:'),            stats_frame,  4),
            ('percent',     _('% won:'),            stats_frame,  5),
            ):
            title_label = gtk.Label()
            title_label.show()
            title_label.set_text(t)
            title_label.set_alignment(0., 0.)
            title_label.set_property('xpad', 2)
            title_label.set_property('ypad', 2)
            f.attach(title_label,
                     0, 1,      row, row+1,
                     gtk.FILL,  0,
                     0,         0)
            text_label = gtk.Label()
            text_label.show()
            text_label.set_alignment(0., 0.)
            text_label.set_property('xpad', 2)
            text_label.set_property('ypad', 2)
            f.attach(text_label,
                     1, 2,      row, row+1,
                     gtk.FILL,  0,
                     0,         0)
            self.info_labels[n] = (title_label, text_label)
        # canvas
        self.preview = MfxCanvas(self)
        self.preview.show()
        table.attach(self.preview,
            0, 2,                            1, 2,
            gtk.EXPAND|gtk.FILL|gtk.SHRINK,  gtk.EXPAND|gtk.FILL|gtk.SHRINK,
            0,                               0)
        self.preview.set_border_width(4)
        self.preview.setTile(app, app.tabletile_index, force=True)

        # set the scale factor
        self.preview.preview = 2
        # create a preview of the current game
        self.preview_key = -1
        self.preview_game = None
        self.preview_app = None
        ##~ self.updatePreview(gameid, animations=0)
        ##~ SelectGameTreeWithPreview.html_viewer = None

        self.connect('unrealize', self._unrealizeEvent)

        self.createButtons(bottom_box, kw)
        self._restoreSettings()
        self.show_all()
        gtk.main()


    def _addGamesFromData(self, data, store, root_iter, root_label, all_games):
        gl = []
        for label, selecter in data:
            games = self._selectGames(all_games, selecter)
            if games:
                gl.append((label, games))
        if not gl:
            return
        iter = store.append(root_iter)
        store.set(iter, 0, root_label, 1, -1)
        for label, games in gl:
            self._addGames(store, iter, label, games)


    def _addGames(self, store, root_iter, root_label, games):
        if not games:
            return
        iter = store.append(root_iter)
        store.set(iter, 0, root_label, 1, -1)
        for id, name in games:
            child_iter = store.append(iter)
            store.set(child_iter, 0, name, 1, id)


    def _selectGames(self, all_games, selecter):
        # return list of tuples (gameid, gamename)
        if selecter is None:
            return [(gi.id, gi.name) for gi in all_games]
        elif selecter == 'alt':
            return all_games
        return [(gi.id, gi.name) for gi in all_games if selecter(gi)]


    def createGameStore(self):
        store = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_INT)
        app = self.app
        gdb = app.gdb

        all_games = map(gdb.get, gdb.getGamesIdSortedByName())
        #
        alter_games = gdb.getGamesTuplesSortedByAlternateName()
        for label, games, selecter in (
            (_('All Games'),       all_games,   None),
            (_('Alternate Names'), alter_games, 'alt'),
            (_('Popular Games'),   all_games, lambda gi: gi.si.game_flags & GI.GT_POPULAR),
            ):
            games = self._selectGames(games, selecter)
            self._addGames(store, None, label, games)

        # by type
        games = self._selectGames(all_games,
                                  lambda gi: gi.si.game_type == GI.GT_MAHJONGG)
        self._addGames(store, None, _("Mahjongg Games"), games)
        self._addGamesFromData(GI.SELECT_ORIENTAL_GAME_BY_TYPE, store,
                               None, _("Oriental Games"), all_games)
        self._addGamesFromData(GI.SELECT_SPECIAL_GAME_BY_TYPE, store,
                               None, _("Special Games"), all_games)
        self._addGamesFromData(GI.SELECT_GAME_BY_TYPE, store,
                               None, _("French games"), all_games)
        # by skill level
        data = (
          (_('Luck only'),    lambda gi: gi.skill_level == GI.SL_LUCK),
          (_('Mostly luck'),  lambda gi: gi.skill_level == GI.SL_MOSTLY_LUCK),
          (_('Balanced'),     lambda gi: gi.skill_level == GI.SL_BALANCED),
          (_('Mostly skill'), lambda gi: gi.skill_level == GI.SL_MOSTLY_SKILL),
          (_('Skill only'),   lambda gi: gi.skill_level == GI.SL_SKILL),
          )
        self._addGamesFromData(data, store, None,
                               _("by Skill Level"), all_games)

        # by game feature
        root_iter = store.append(None)
        store.set(root_iter, 0, _('by Game Feature'), 1, -1)
        data = (
            (_("32 cards"),     lambda gi: gi.si.ncards == 32),
            (_("48 cards"),     lambda gi: gi.si.ncards == 48),
            (_("52 cards"),     lambda gi: gi.si.ncards == 52),
            (_("64 cards"),     lambda gi: gi.si.ncards == 64),
            (_("78 cards"),     lambda gi: gi.si.ncards == 78),
            (_("104 cards"),    lambda gi: gi.si.ncards == 104),
            (_("144 cards"),    lambda gi: gi.si.ncards == 144),
            (_("Other number"), lambda gi: gi.si.ncards not in (32, 48, 52, 64, 78, 104, 144)),)
        self._addGamesFromData(data, store, root_iter,
                             _("by Number of Cards"), all_games)
        data = (
            (_("1 deck games"), lambda gi: gi.si.decks == 1),
            (_("2 deck games"), lambda gi: gi.si.decks == 2),
            (_("3 deck games"), lambda gi: gi.si.decks == 3),
            (_("4 deck games"), lambda gi: gi.si.decks == 4),)
        self._addGamesFromData(data, store, root_iter,
                             _("by Number of Decks"), all_games)
        data = (
            (_("No redeal"), lambda gi: gi.si.redeals == 0),
            (_("1 redeal"),  lambda gi: gi.si.redeals == 1),
            (_("2 redeals"), lambda gi: gi.si.redeals == 2),
            (_("3 redeals"), lambda gi: gi.si.redeals == 3),
            (_("Unlimited redeals"), lambda gi: gi.si.redeals == -1),
            ##(_("Variable redeals"), lambda gi: gi.si.redeals == -2),
            (_("Other number of redeals"), lambda gi: gi.si.redeals not in (-1, 0, 1, 2, 3)),)
        self._addGamesFromData(data, store, root_iter,
                               _("by Number of Redeals"), all_games)

        data = []
        for label, vg in GI.GAMES_BY_COMPATIBILITY:
            selecter = lambda gi, vg=vg: gi.id in vg
            data.append((label, selecter))
        self._addGamesFromData(data, store, root_iter,
                               _("by Compatibility"), all_games)

        # by PySol version
        data = []
        for version, vg in GI.GAMES_BY_PYSOL_VERSION:
            selecter = lambda gi, vg=vg: gi.id in vg
            label = _("New games in v. ") + version
            data.append((label, selecter))
        self._addGamesFromData(data, store, None,
                               _("by PySol version"), all_games)

        #
        data = (
            (_("Games for Children (very easy)"), lambda gi: gi.si.game_flags & GI.GT_CHILDREN),
            (_("Games with Scoring"),  lambda gi: gi.si.game_flags & GI.GT_SCORE),
            (_("Games with Separate Decks"),  lambda gi: gi.si.game_flags & GI.GT_SEPARATE_DECKS),
            (_("Open Games (all cards visible)"), lambda gi: gi.si.game_flags & GI.GT_OPEN),
            (_("Relaxed Variants"),  lambda gi: gi.si.game_flags & GI.GT_RELAXED),)
        self._addGamesFromData(data, store, None,
                               _("Other Categories"), all_games)

        #
        self._addGamesFromData(GI.SELECT_ORIGINAL_GAME_BY_TYPE, store,
                               None, _("Original Games"), all_games)
        ##self._addGamesFromData(GI.SELECT_CONTRIB_GAME_BY_TYPE, store,
        ##              None, _("Contrib Game"), all_games)

        SelectGameDialogWithPreview.game_store = store
        return


    def initKw(self, kw):
        kwdefault(kw,
                  strings=(_("&Select"), _("&Rules"), _("&Cancel"),),
                  default=0,
                  width=600, height=400,
                  )
        return MfxDialog.initKw(self, kw)


    def _unrealizeEvent(self, w):
        self.deletePreview(destroy=1)
        #self.preview.unbind_all()
        self._saveSettings()


    def _saveSettings(self):
        SelectGameDialogWithPreview._geometry = self.get_size()
        SelectGameDialogWithPreview._paned_position = self.hpaned.get_position()


    def _restoreSettings(self):
        if self._geometry:
            self.resize(self._geometry[0], self._geometry[1])
        self.hpaned.set_position(self._paned_position)


    def getSelected(self):
        index = self.treeview.getSelected()
        if index < 0:
            return None
        return index

    def showSelected(self, w):
        id = self.getSelected()
        if id:
            self.updatePreview(id)


    def deletePreview(self, destroy=0):
        self.preview_key = -1
        # clean up the canvas
        if self.preview:
            unbind_destroy(self.preview)
            self.preview.deleteAllItems()
            ##~ if destroy:
            ##~     self.preview.delete("all")
        #
        #for l in self.info_labels.values():
        #    l.config(text='')
        # destruct the game
        if self.preview_game:
            self.preview_game.endGame()
            self.preview_game.destruct()
            destruct(self.preview_game)
        self.preview_game = None
        # destruct the app
        if destroy:
            if self.preview_app:
                destruct(self.preview_app)
            self.preview_app = None

    def updatePreview(self, gameid, animations=10):
        if gameid == self.preview_key:
            return
        self.deletePreview()
        canvas = self.preview
        #
        gi = self.app.gdb.get(gameid)
        if not gi:
            self.preview_key = -1
            return
        #
        if self.preview_app is None:
            self.preview_app = Struct(
                # variables
                audio = self.app.audio,
                canvas = canvas,
                cardset = self.app.cardset.copy(),
                comments = self.app.comments.new(),
                gamerandom = self.app.gamerandom,
                gdb = self.app.gdb,
                gimages = self.app.gimages,
                images = self.app.subsampled_images,
                menubar = None,
                miscrandom = self.app.miscrandom,
                opt = self.app.opt.copy(),
                startup_opt = self.app.startup_opt,
                stats = self.app.stats.new(),
                top = None,
                top_cursor = self.app.top_cursor,
                toolbar = None,
                # methods
                constructGame = self.app.constructGame,
                getFont = self.app.getFont,
            )
            self.preview_app.opt.shadow = 0
            self.preview_app.opt.shade = 0
        #
        self.preview_app.audio = None    # turn off audio for intial dealing
        if animations >= 0:
            self.preview_app.opt.animations = animations
        #
        if self.preview_game:
            self.preview_game.endGame()
            self.preview_game.destruct()
        ##self.top.wm_title("Select Game - " + self.app.getGameTitleName(gameid))
        title = self.app.getGameTitleName(gameid)
        self.set_title(_("Playable Preview - ") + title)
        #
        self.preview_game = gi.gameclass(gi)
        self.preview_game.createPreview(self.preview_app)
        tx, ty = 0, 0
        gw, gh = self.preview_game.width, self.preview_game.height
        ##~ canvas.config(scrollregion=(-tx, -ty, -tx, -ty))
        ##~ canvas.xview_moveto(0)
        ##~ canvas.yview_moveto(0)
        #
        random = None
        if gameid == self.gameid:
            random = self.app.game.random.copy()
        if gameid == self.gameid and self.bookmark:
            self.preview_game.restoreGameFromBookmark(self.bookmark)
        else:
            self.preview_game.newGame(random=random, autoplay=1)
        ##~ canvas.config(scrollregion=(-tx, -ty, gw, gh))
        #
        self.preview_app.audio = self.app.audio
        if self.app.opt.animations:
            self.preview_app.opt.animations = 10
        else:
            self.preview_app.opt.animations = 0
        # save seed
        self.random = self.preview_game.random.copy()
        self.random.origin = self.random.ORIGIN_PREVIEW
        self.preview_key = gameid
        #
        self.updateInfo(gameid)
        #
        rules_button = self.buttons[1]
        if self.app.getGameRulesFilename(gameid):
            rules_button.set_sensitive(True)
        else:
            rules_button.set_sensitive(False)

    def updateInfo(self, gameid):
        gi = self.app.gdb.get(gameid)
        # info
        name = gi.name
        altnames = '\n'.join(gi.altnames)
        category = _(CSI.TYPE[gi.category])
        type = ''
        if gi.si.game_type in GI.TYPE_NAMES:
            type = _(GI.TYPE_NAMES[gi.si.game_type])
        sl = {
            GI.SL_LUCK:         _('Luck only'),
            GI.SL_MOSTLY_LUCK:  _('Mostly luck'),
            GI.SL_BALANCED:     _('Balanced'),
            GI.SL_MOSTLY_SKILL: _('Mostly skill'),
            GI.SL_SKILL:        _('Skill only'),
            }
        skill_level = sl.get(gi.skill_level)
        if    gi.redeals == -2: redeals = _('variable')
        elif  gi.redeals == -1: redeals = _('unlimited')
        else:                   redeals = str(gi.redeals)
        # stats
        won, lost, time, moves = self.app.stats.getFullStats(self.app.opt.player, gameid)
        if won+lost > 0: percent = "%.1f" % (100.0*won/(won+lost))
        else: percent = "0.0"
        time = format_time(time)
        moves = str(round(moves, 1))
        for n, t in (
            ('name',        name),
            ('altnames',    altnames),
            ('category',    category),
            ('type',        type),
            ('skill_level', skill_level),
            ('decks',       gi.decks),
            ('redeals',     redeals),
            ('played',      won+lost),
            ('won',         won),
            ('lost',        lost),
            ('time',        time),
            ('moves',       moves),
            ('percent',     percent),
            ):
            title_label, text_label = self.info_labels[n]
            if t in ('', None):
                title_label.hide()
                text_label.hide()
            else:
                title_label.show()
                text_label.show()
            text_label.set_text(str(t))

    def done(self, button):
        button = button.get_data("user_data")
        print 'done', button
        if button == 0:                    # Ok or double click
            id = self.getSelected()
            if id:
                self.gameid = id
            ##~ self.tree.n_expansions = 1  # save xyview in any case
        if button == 1:                    # Rules
            id = self.getSelected()
            if id:
                doc = self.app.getGameRulesFilename(id)
                if not doc:
                    return
            dir = os.path.join("html", "rules")
            help_html(self.app, doc, dir, self)
            return

        self.status = 0
        self.button = button
        self.quit()
Example #3
0
class SelectGameDialogWithPreview(MfxDialog):
    # Tree_Class = SelectGameTreeWithPreview
    game_store = None
    #
    _paned_position = 300
    _expanded_rows = []
    _geometry = None
    _selected_row = None
    _vadjustment_position = None

    def __init__(self, parent, title, app, gameid, bookmark=None, **kw):
        kw = self.initKw(kw)
        MfxDialog.__init__(self, parent, title, **kw)
        #
        self.app = app
        self.gameid = gameid
        self.bookmark = bookmark
        self.random = None
        #
        if self.game_store is None:
            self.createGameStore()
        #
        top_box, bottom_box = self.createHBox()
        # paned
        hpaned = gtk.HPaned()
        self.hpaned = hpaned
        hpaned.show()
        top_box.pack_start(hpaned, expand=True, fill=True)
        # left
        self.treeview = PysolTreeView(self, self.game_store)
        hpaned.pack1(self.treeview.scrolledwindow, True, True)
        # right
        table = gtk.Table(2, 2, False)
        table.show()
        hpaned.pack2(table, True, True)
        # frames
        frame = gtk.Frame(label=_('About game'))
        frame.show()
        table.attach(frame,
                     0, 1,      0, 1,
                     gtk.FILL,  gtk.FILL,
                     0,         0)
        frame.set_border_width(4)
        info_frame = gtk.Table(2, 7, False)
        info_frame.show()
        frame.add(info_frame)
        info_frame.set_border_width(4)
        #
        frame = gtk.Frame(label=_('Statistics'))
        frame.show()
        table.attach(frame,
                     1, 2,      0, 1,
                     gtk.FILL,  gtk.FILL,
                     0,         0)
        frame.set_border_width(4)
        stats_frame = gtk.Table(2, 6, False)
        stats_frame.show()
        frame.add(stats_frame)
        stats_frame.set_border_width(4)
        # info
        self.info_labels = {}
        for n, t, f, row in (
            ('name',        _('Name:'),             info_frame,   0),
            ('altnames',    _('Alternate names:'),  info_frame,   1),
            ('category',    _('Category:'),         info_frame,   2),
            ('type',        _('Type:'),             info_frame,   3),
            ('skill_level', _('Skill level:'),      info_frame,   4),
            ('decks',       _('Decks:'),            info_frame,   5),
            ('redeals',     _('Redeals:'),          info_frame,   6),
            #
            ('played',      _('Played:'),           stats_frame,  0),
            ('won',         _('Won:'),              stats_frame,  1),
            ('lost',        _('Lost:'),             stats_frame,  2),
            ('time',        _('Playing time:'),     stats_frame,  3),
            ('moves',       _('Moves:'),            stats_frame,  4),
            ('percent',     _('% won:'),            stats_frame,  5),
                ):
            title_label = gtk.Label()
            title_label.show()
            title_label.set_text(t)
            title_label.set_alignment(0., 0.)
            title_label.set_property('xpad', 2)
            title_label.set_property('ypad', 2)
            f.attach(title_label,
                     0, 1,      row, row+1,
                     gtk.FILL,  0,
                     0,         0)
            text_label = gtk.Label()
            text_label.show()
            text_label.set_alignment(0., 0.)
            text_label.set_property('xpad', 2)
            text_label.set_property('ypad', 2)
            f.attach(text_label,
                     1, 2,      row, row+1,
                     gtk.FILL,  0,
                     0,         0)
            self.info_labels[n] = (title_label, text_label)
        # canvas
        self.preview = MfxCanvas(self)
        self.preview.show()
        table.attach(
            self.preview,
            0, 2,                            1, 2,
            gtk.EXPAND | gtk.FILL | gtk.SHRINK,
            gtk.EXPAND | gtk.FILL | gtk.SHRINK,
            0,                               0)
        self.preview.set_border_width(4)
        self.preview.setTile(app, app.tabletile_index, force=True)

        # set the scale factor
        self.preview.preview = 2
        # create a preview of the current game
        self.preview_key = -1
        self.preview_game = None
        self.preview_app = None
        # ~ self.updatePreview(gameid, animations=0)
        # ~ SelectGameTreeWithPreview.html_viewer = None

        self.connect('unrealize', self._unrealizeEvent)

        self.createButtons(bottom_box, kw)
        self._restoreSettings()
        self.show_all()
        gtk.main()

    def _addGamesFromData(self, data, store, root_iter, root_label, all_games):
        gl = []
        for label, selecter in data:
            games = self._selectGames(all_games, selecter)
            if games:
                gl.append((label, games))
        if not gl:
            return
        iter = store.append(root_iter)
        store.set(iter, 0, root_label, 1, -1)
        for label, games in gl:
            self._addGames(store, iter, label, games)

    def _addGames(self, store, root_iter, root_label, games):
        if not games:
            return
        iter = store.append(root_iter)
        store.set(iter, 0, root_label, 1, -1)
        for id, name in games:
            child_iter = store.append(iter)
            store.set(child_iter, 0, name, 1, id)

    def _selectGames(self, all_games, selecter):
        # return list of tuples (gameid, gamename)
        if selecter is None:
            return [(gi.id, gi.name) for gi in all_games]
        elif selecter == 'alt':
            return all_games
        return [(gi.id, gi.name) for gi in all_games if selecter(gi)]

    def createGameStore(self):
        store = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_INT)
        app = self.app
        gdb = app.gdb

        all_games = map(gdb.get, gdb.getGamesIdSortedByName())
        #
        alter_games = gdb.getGamesTuplesSortedByAlternateName()
        for label, games, selecter in (
            (_('All Games'),       all_games,   None),
            (_('Alternate Names'), alter_games, 'alt'),
            (_('Popular Games'),   all_games,
                lambda gi: gi.si.game_flags & GI.GT_POPULAR),
                ):
            games = self._selectGames(games, selecter)
            self._addGames(store, None, label, games)

        # by type
        games = self._selectGames(all_games,
                                  lambda gi: gi.si.game_type == GI.GT_MAHJONGG)
        self._addGames(store, None, _("Mahjongg Games"), games)
        self._addGamesFromData(GI.SELECT_ORIENTAL_GAME_BY_TYPE, store,
                               None, _("Oriental Games"), all_games)
        self._addGamesFromData(GI.SELECT_SPECIAL_GAME_BY_TYPE, store,
                               None, _("Special Games"), all_games)
        self._addGamesFromData(GI.SELECT_GAME_BY_TYPE, store,
                               None, _("French games"), all_games)
        # by skill level
        data = (
          (_('Luck only'), lambda gi: gi.skill_level == GI.SL_LUCK),
          (_('Mostly luck'), lambda gi: gi.skill_level == GI.SL_MOSTLY_LUCK),
          (_('Balanced'), lambda gi: gi.skill_level == GI.SL_BALANCED),
          (_('Mostly skill'), lambda gi: gi.skill_level == GI.SL_MOSTLY_SKILL),
          (_('Skill only'), lambda gi: gi.skill_level == GI.SL_SKILL),
          )
        self._addGamesFromData(data, store, None,
                               _("by Skill Level"), all_games)

        # by game feature
        root_iter = store.append(None)
        store.set(root_iter, 0, _('by Game Feature'), 1, -1)
        data = (
            (_("32 cards"), lambda gi: gi.si.ncards == 32),
            (_("48 cards"), lambda gi: gi.si.ncards == 48),
            (_("52 cards"), lambda gi: gi.si.ncards == 52),
            (_("64 cards"), lambda gi: gi.si.ncards == 64),
            (_("78 cards"), lambda gi: gi.si.ncards == 78),
            (_("104 cards"), lambda gi: gi.si.ncards == 104),
            (_("144 cards"), lambda gi: gi.si.ncards == 144),
            (_("Other number"),
                lambda gi: gi.si.ncards not in (32, 48, 52, 64, 78, 104, 144))
            )
        self._addGamesFromData(
            data, store, root_iter, _("by Number of Cards"), all_games)
        data = (
            (_("1 deck games"), lambda gi: gi.si.decks == 1),
            (_("2 deck games"), lambda gi: gi.si.decks == 2),
            (_("3 deck games"), lambda gi: gi.si.decks == 3),
            (_("4 deck games"), lambda gi: gi.si.decks == 4),)
        self._addGamesFromData(
            data, store, root_iter, _("by Number of Decks"), all_games)
        data = (
            (_("No redeal"), lambda gi: gi.si.redeals == 0),
            (_("1 redeal"), lambda gi: gi.si.redeals == 1),
            (_("2 redeals"), lambda gi: gi.si.redeals == 2),
            (_("3 redeals"), lambda gi: gi.si.redeals == 3),
            (_("Unlimited redeals"), lambda gi: gi.si.redeals == -1),
            # (_("Variable redeals"), lambda gi: gi.si.redeals == -2),
            (_("Other number of redeals"),
                lambda gi: gi.si.redeals not in (-1, 0, 1, 2, 3)),)
        self._addGamesFromData(data, store, root_iter,
                               _("by Number of Redeals"), all_games)

        data = []
        for label, vg in GI.GAMES_BY_COMPATIBILITY:
            def selecter(gi, vg=vg):
                return gi.id in vg
            data.append((label, selecter))
        self._addGamesFromData(data, store, root_iter,
                               _("by Compatibility"), all_games)

        # by PySol version
        data = []
        for version, vg in GI.GAMES_BY_PYSOL_VERSION:
            def selecter(gi, vg=vg):
                return gi.id in vg
            label = _("New games in v. %(version)s") % {'version': version}
            data.append((label, selecter))
        self._addGamesFromData(data, store, None,
                               _("by PySol version"), all_games)

        #
        data = (
            (_("Games for Children (very easy)"),
                lambda gi: gi.si.game_flags & GI.GT_CHILDREN),
            (_("Games with Scoring"),
                lambda gi: gi.si.game_flags & GI.GT_SCORE),
            (_("Games with Stripped Decks"),
                lambda gi: gi.si.game_flags & GI.GT_STRIPPED),
            (_("Games with Separate Decks"),
                lambda gi: gi.si.game_flags & GI.GT_SEPARATE_DECKS),
            (_("Open Games (all cards visible)"),
                lambda gi: gi.si.game_flags & GI.GT_OPEN),
            (_("Relaxed Variants"),
                lambda gi: gi.si.game_flags & GI.GT_RELAXED),)
        self._addGamesFromData(data, store, None,
                               _("Other Categories"), all_games)

        #
        self._addGamesFromData(GI.SELECT_ORIGINAL_GAME_BY_TYPE, store,
                               None, _("Original Games"), all_games)
        # self._addGamesFromData(GI.SELECT_CONTRIB_GAME_BY_TYPE, store,
        #               None, _("Contrib Game"), all_games)

        SelectGameDialogWithPreview.game_store = store
        return

    def initKw(self, kw):
        kwdefault(kw,
                  strings=(_("&Select"), _("&Rules"), _("&Cancel"),),
                  default=0,
                  width=600, height=400,
                  )
        return MfxDialog.initKw(self, kw)

    def _unrealizeEvent(self, w):
        self.deletePreview(destroy=1)
        # self.preview.unbind_all()
        self._saveSettings()

    def _saveSettings(self):
        SelectGameDialogWithPreview._geometry = self.get_size()
        SelectGameDialogWithPreview._paned_position = \
            self.hpaned.get_position()

    def _restoreSettings(self):
        if self._geometry:
            self.resize(self._geometry[0], self._geometry[1])
        self.hpaned.set_position(self._paned_position)

    def getSelected(self):
        index = self.treeview.getSelected()
        if index < 0:
            return None
        return index

    def showSelected(self, w):
        id = self.getSelected()
        if id:
            self.updatePreview(id)

    def deletePreview(self, destroy=0):
        self.preview_key = -1
        # clean up the canvas
        if self.preview:
            unbind_destroy(self.preview)
            self.preview.deleteAllItems()
            # ~ if destroy:
            # ~     self.preview.delete("all")
        #
        # for l in self.info_labels.values():
        #    l.config(text='')
        # destruct the game
        if self.preview_game:
            self.preview_game.endGame()
            self.preview_game.destruct()
            destruct(self.preview_game)
        self.preview_game = None
        # destruct the app
        if destroy:
            if self.preview_app:
                destruct(self.preview_app)
            self.preview_app = None

    def updatePreview(self, gameid, animations=10):
        if gameid == self.preview_key:
            return
        self.deletePreview()
        canvas = self.preview
        #
        gi = self.app.gdb.get(gameid)
        if not gi:
            self.preview_key = -1
            return
        #
        if self.preview_app is None:
            self.preview_app = Struct(
                # variables
                audio=self.app.audio,
                canvas=canvas,
                cardset=self.app.cardset.copy(),
                gamerandom=self.app.gamerandom,
                gdb=self.app.gdb,
                gimages=self.app.gimages,
                images=None,
                menubar=None,
                miscrandom=self.app.miscrandom,
                opt=self.app.opt.copy(),
                startup_opt=self.app.startup_opt,
                stats=self.app.stats.new(),
                top=None,
                top_cursor=self.app.top_cursor,
                toolbar=None,
                # methods
                constructGame=self.app.constructGame,
                getFont=self.app.getFont,
            )
            self.preview_app.opt.shadow = 0
            self.preview_app.opt.shade = 0
        #

        c = self.app.cardsets_cache.get(gi.category)
        if not c:
            cardset = self.app.cardset_manager.getByName(
                self.app.opt.cardset[gi.category][0])
            self.app.loadCardset(cardset, id=gi.category,
                                 tocache=True, noprogress=True)
            c = self.app.cardsets_cache.get(gi.category)
        if c:
            self.preview_app.images = c[2]
        else:
            self.preview_app.images = self.app.subsampled_images

        self.preview_app.audio = None    # turn off audio for initial dealing
        if animations >= 0:
            self.preview_app.opt.animations = animations
        #
        if self.preview_game:
            self.preview_game.endGame()
            self.preview_game.destruct()
        # self.top.wm_title(
        #   "Select Game - " + self.app.getGameTitleName(gameid))
        title = self.app.getGameTitleName(gameid)
        self.set_title(_("Select Game - %(game)s") % {'game': title})
        #
        self.preview_game = gi.gameclass(gi)
        self.preview_game.createPreview(self.preview_app)
        # tx, ty = 0, 0
        # gw, gh = self.preview_game.width, self.preview_game.height
        # ~ canvas.config(scrollregion=(-tx, -ty, -tx, -ty))
        # ~ canvas.xview_moveto(0)
        # ~ canvas.yview_moveto(0)
        #
        random = None
        if gameid == self.gameid:
            random = self.app.game.random.copy()
        if gameid == self.gameid and self.bookmark:
            self.preview_game.restoreGameFromBookmark(self.bookmark)
        else:
            self.preview_game.newGame(random=random, autoplay=1)
        # ~ canvas.config(scrollregion=(-tx, -ty, gw, gh))
        #
        self.preview_app.audio = self.app.audio
        if self.app.opt.animations:
            self.preview_app.opt.animations = 10
        else:
            self.preview_app.opt.animations = 0
        # save seed
        self.random = self.preview_game.random.copy()
        self.random.origin = self.random.ORIGIN_PREVIEW
        self.preview_key = gameid
        #
        self.updateInfo(gameid)
        #
        rules_button = self.buttons[1]
        if self.app.getGameRulesFilename(gameid):
            rules_button.set_sensitive(True)
        else:
            rules_button.set_sensitive(False)

    def updateInfo(self, gameid):
        gi = self.app.gdb.get(gameid)
        # info
        name = gi.name
        altnames = '\n'.join(gi.altnames)
        category = _(CSI.TYPE[gi.category])
        type = ''
        if gi.si.game_type in GI.TYPE_NAMES:
            type = _(GI.TYPE_NAMES[gi.si.game_type])
        sl = {
            GI.SL_LUCK:         _('Luck only'),
            GI.SL_MOSTLY_LUCK:  _('Mostly luck'),
            GI.SL_BALANCED:     _('Balanced'),
            GI.SL_MOSTLY_SKILL: _('Mostly skill'),
            GI.SL_SKILL:        _('Skill only'),
            }
        skill_level = sl.get(gi.skill_level)
        if gi.redeals == -2:
            redeals = _('variable')
        elif gi.redeals == -1:
            redeals = _('unlimited')
        else:
            redeals = str(gi.redeals)
        # stats
        won, lost, time, moves = self.app.stats.getFullStats(
            self.app.opt.player, gameid)
        if won+lost > 0:
            percent = "%.1f" % (100.0*won/(won+lost))
        else:
            percent = "0.0"
        time = format_time(time)
        moves = str(round(moves, 1))
        for n, t in (
            ('name',        name),
            ('altnames',    altnames),
            ('category',    category),
            ('type',        type),
            ('skill_level', skill_level),
            ('decks',       gi.decks),
            ('redeals',     redeals),
            ('played',      won+lost),
            ('won',         won),
            ('lost',        lost),
            ('time',        time),
            ('moves',       moves),
            ('percent',     percent),
                ):
            title_label, text_label = self.info_labels[n]
            if t in ('', None):
                title_label.hide()
                text_label.hide()
            else:
                title_label.show()
                text_label.show()
            text_label.set_text(str(t))

    def done(self, button):
        button = button.get_data("user_data")
        print('done', button)
        if button == 0:                    # Ok or double click
            id = self.getSelected()
            if id:
                self.gameid = id
            # ~ self.tree.n_expansions = 1  # save xyview in any case
        if button == 1:                    # Rules
            id = self.getSelected()
            if id:
                doc = self.app.getGameRulesFilename(id)
                if not doc:
                    return
            dir = os.path.join("html", "rules")
            help_html(self.app, doc, dir, self)
            return

        self.status = 0
        self.button = button
        self.quit()
Example #4
0
class SelectCardsetDialogWithPreview(MfxDialog):
    _cardset_store = None

    def __init__(self, parent, title, app, manager, key=None, **kw):
        kw = self.initKw(kw)
        MfxDialog.__init__(self, parent, title, **kw)
        #
        top_box, bottom_box = self.createHBox()
        #
        if key is None:
            key = manager.getSelected()
        self.app = app
        self.manager = manager
        self.key = key
        self.preview_key = -1
        self.all_keys = []

        if self._cardset_store is None:
            self._createStore()

        # padx, pady = kw.padx, kw.pady
        # left
        # paned
        hpaned = gtk.HPaned()
        self.hpaned = hpaned
        hpaned.show()
        top_box.pack_start(hpaned, expand=True, fill=True)
        # tree
        treeview = PysolTreeView(self, self._cardset_store)
        self.treeview = treeview
        hpaned.pack1(treeview.scrolledwindow, True, True)
        # treeview.treeview.expand_all()
        # right
        sw = gtk.ScrolledWindow()
        sw.show()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        hpaned.pack2(sw, True, True)
        # self.scrolledwindow = sw
        #
        self.preview = MfxCanvas(self)
        self.preview.show()
        sw.add(self.preview)
        # hpaned.pack2(self.preview, True, True)
        self.preview.setTile(app, app.tabletile_index, force=True)
        #
        hpaned.set_position(240)

        self.createButtons(bottom_box, kw)

        # ~self.updatePreview(key)

        self.show_all()
        gtk.main()

    def _selectCardset(self, all_cardsets, selecter):
        if selecter is None:
            return [(cs.index, cs.name) for cs in all_cardsets]
        return [(cs.index, cs.name) for cs in all_cardsets if selecter(cs)]

    def _addCardsets(self, store, root_iter, root_label, cardsets):
        iter = store.append(root_iter)
        store.set(iter, 0, root_label, 1, -1)
        for index, name in cardsets:
            child_iter = store.append(iter)
            # ~ name = _(name)
            store.set(child_iter, 0, name, 1, index)

    def _addCardsetsByType(self, store, root_label, all_cardsets,
                           cardset_types, selecter_type, registered):
        manager = self.manager
        root_iter = store.append(None)
        store.set(root_iter, 0, root_label, 1, -1)
        items = cardset_types.items()
        items.sort(key=lambda x: x[1])
        added = False
        for key, label in items:
            if key not in getattr(manager, registered):
                continue
            cardsets = []
            for cs in all_cardsets:
                si = getattr(cs.si, selecter_type)
                if isinstance(si, int):  # type
                    if key == si:
                        cardsets.append((cs.index, cs.name))
                else:  # style, nationality, date
                    if key in si:
                        cardsets.append((cs.index, cs.name))
            if cardsets:
                added = True
                self._addCardsets(store, root_iter, label, cardsets)
        if added:
            def selecter(cs, selecter_type=selecter_type):
                return getattr(cs.si, selecter_type)
            cs = self._selectCardset(all_cardsets, selecter)
            if cs:
                self._addCardsets(store, root_iter, _('Uncategorized'), cs)
        else:
            iter = store.append(root_iter)
            store.set(iter, 0, _('(no cardsets)'), 1, -1)

    def _createStore(self):
        store = gtk.TreeStore(gobject.TYPE_STRING,
                              gobject.TYPE_INT)
        manager = self.manager
        all_cardsets = manager.getAllSortedByName()
        all_cardsets = [obj for obj in all_cardsets if not obj.error]

        cs = self._selectCardset(all_cardsets, None)
        self._addCardsets(store, None, 'All cadsets', cs)

        root_iter = store.append(None)
        store.set(root_iter, 0, _('by Size'), 1, -1)
        for label, selecter in (
            (_("Tiny cardsets"), lambda cs: cs.si.size == CSI.SIZE_TINY),
            (_("Small cardsets"), lambda cs: cs.si.size == CSI.SIZE_SMALL),
            (_("Medium cardsets"), lambda cs: cs.si.size == CSI.SIZE_MEDIUM),
            (_("Large cardsets"), lambda cs: cs.si.size == CSI.SIZE_LARGE),
            (_("XLarge cardsets"), lambda cs: cs.si.size == CSI.SIZE_XLARGE),
                ):
            cs = self._selectCardset(all_cardsets, selecter)
            if cs:
                self._addCardsets(store, root_iter, label, cs)

        self._addCardsetsByType(store, _('by Type'), all_cardsets,
                                CSI.TYPE, 'type', 'registered_types')
        self._addCardsetsByType(store, _('by Style'), all_cardsets,
                                CSI.STYLE, 'styles', 'registered_styles')
        self._addCardsetsByType(store, _('by Nationality'), all_cardsets,
                                CSI.NATIONALITY, 'nationalities',
                                'registered_nationalities')
        self._addCardsetsByType(store, _('by Date'), all_cardsets,
                                CSI.DATE, 'dates', 'registered_dates')

        self._cardset_store = store

    def getSelected(self):
        index = self.treeview.getSelected()
        if index < 0:
            return None
        return index

    def showSelected(self, w):
        key = self.getSelected()
        if key is not None:
            self.updatePreview(key)
        pass

    def updatePreview(self, key):
        if key == self.preview_key:
            return
        canvas = self.preview
        canvas.deleteAllItems()
        self.preview_images = []
        cs = self.manager.get(key)
        if not cs:
            self.preview_key = -1
            return
        names, columns = cs.getPreviewCardNames()
        try:
            # ???names, columns = cs.getPreviewCardNames()
            for n in names:
                f = os.path.join(cs.dir, n + cs.ext)
                self.preview_images.append(loadImage(file=f))
        except Exception:
            self.preview_key = -1
            self.preview_images = []
            return
        i, x, y, sx, sy, dx, dy = 0, 10, 10, 0, 0, cs.CARDW + 10, cs.CARDH + 10
        for image in self.preview_images:
            MfxCanvasImage(canvas, x, y, anchor="nw", image=image)
            sx, sy = max(x, sx), max(y, sy)
            i += 1
            if i % columns == 0:
                x, y = 10, y + dy
            else:
                x += dx
        canvas.config(width=sx+dx, height=sy+dy)
        canvas.set_scroll_region(0, 0, sx+dx, sy+dy)
        self.preview_key = key

    def initKw(self, kw):
        kwdefault(kw,
                  strings=(_("&Load"), _("&Cancel"), _("&Info..."),),
                  default=1,
                  resizable=1,
                  padx=10, pady=10,
                  width=600, height=400,
                  )
        return MfxDialog.initKw(self, kw)

    def createInfo(self):
        pass

    def done(self, button):
        b = button.get_data('user_data')
        if b == 2:
            self.createInfo()
            return
        if b == 0:
            self.key = self.getSelected()
            if not self.key:
                self.key = self.preview_key
        self.status = 0
        self.button = b
        self.hide()
        self.quit()
class SelectTileDialogWithPreview(MfxDialog):

    def __init__(self, parent, title, app, manager, key=None, **kw):
        kw = self.initKw(kw)
        MfxDialog.__init__(self, parent, title, **kw)
        #
        top_box, bottom_box = self.createHBox()
        #
        if key is None:
            key = manager.getSelected()
        self.app = app
        self.manager = manager
        self.key = key
        self.preview_key = -1
        self.all_keys = []
        self.table_color = app.opt.colors['table']
        # paned
        hpaned = gtk.HPaned()
        self.hpaned = hpaned
        hpaned.show()
        top_box.pack_start(hpaned, expand=True, fill=True)
        #
        model = self._createStore(manager, key)
        treeview = PysolTreeView(self, model)
        self.treeview = treeview
        hpaned.pack1(treeview.scrolledwindow, True, True)
        treeview.treeview.expand_all()
        #
        self.preview = MfxCanvas(top_box)  # width=w2
        hpaned.pack2(self.preview, True, True)
        self.preview.show()
        hpaned.set_position(240)

        self.createButtons(bottom_box, kw)

        self.updatePreview(key)

        self.show_all()
        gtk.main()

    def rowActivated(self, w, row, col):
        # FIXME
        print('row-activated-event', row, col)

    def getSelected(self):
        index = self.treeview.getSelected()
        if index < 0:
            return None
        return self.all_keys[index]

    def showSelected(self, w):
        key = self.getSelected()
        self.updatePreview(key)

    def _createStore(self, manager, key):
        self.all_keys = []
        index = 0
        #
        model = gtk.TreeStore(gobject.TYPE_STRING,
                              gobject.TYPE_INT)
        #
        iter = model.append(None)
        model.set(iter, 0, _('Solid color'), 1, -1)
        for color, value in ((_('Blue'),   '#0082df'),
                             (_('Green'),  '#008200'),
                             (_('Navy'),   '#000086'),
                             (_('Olive'),  '#868200'),
                             (_('Orange'), '#f79600'),
                             (_('Teal'),   '#008286'),):
            child_iter = model.append(iter)
            model.set(child_iter, 0, color, 1, index)
            self.all_keys.append(value)
            index += 1
        #
        tiles = manager.getAllSortedByName()
        tiles = [obj for obj in tiles if not obj.error]
        tiles = [tile for tile in tiles if tile.index > 0 and tile.filename]
        #
        iter = model.append(None)
        model.set(iter, 0, _('All Backgrounds'), 1, -1)
        if tiles:
            for tile in tiles:
                child_iter = model.append(iter)
                model.set(child_iter, 0, tile.name, 1, index)
                self.all_keys.append(tile.index)
                index += 1
        else:
            child_iter = model.append(iter)
            model.set(child_iter, 0, _('(no tiles)'), 1, -1)

        return model

    def updatePreview(self, key):
        # print 'updatePreview:', key, type(key)
        if key is None:
            return
        if key == self.preview_key:
            return
        canvas = self.preview
        # canvas.deleteAllItems()
        if isinstance(key, str):
            # solid color
            canvas.setTile(self.app, 0, force=True)
            canvas.config(bg=key)
            # canvas.setTextColor(None)
            self.preview_key = key
            self.table_color = key
        else:
            # image
            if self.preview.setTile(self.app, key):
                self.preview_key = key
            else:
                self.preview_key = -1

    def initKw(self, kw):
        kwdefault(kw,
                  strings=(_('&OK'), _('&Solid color...'), _('&Cancel'),),
                  default=0,
                  resizable=1,
                  padx=10, pady=10,
                  width=600, height=400,
                  )
        return MfxDialog.initKw(self, kw)

    def _colorselOkClicked(self, w, d):
        c = d.colorsel.get_current_color()
        c = '#%02x%02x%02x' % (c.red//256, c.green//256, c.blue//256)
        d.destroy()
        self.updatePreview(c)
        self.treeview.unselectAll()

    def createColorsel(self):
        win = gtk.ColorSelectionDialog(_('Select table color'))
        win.help_button.destroy()
        win.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        if isinstance(self.preview_key, str):
            color = self.preview_key
        else:
            color = self.app.opt.colors['table']
        win.colorsel.set_current_color(gdk.color_parse(color))
        win.connect('delete_event', lambda w, e: win.destroy())
        win.ok_button.connect('clicked', self._colorselOkClicked, win)
        win.cancel_button.connect('clicked', lambda w: win.destroy())
        setTransient(win, self)
        win.show()

    def done(self, button):
        b = button.get_data('user_data')
        if b == 1:
            self.createColorsel()
            return
        if b == 0:
            self.key = self.getSelected()
            if not self.key:
                self.key = self.preview_key
        self.status = 0
        self.button = b
        # self.hide()
        self.quit()
Example #6
0
class SelectCardsetDialogWithPreview(MfxDialog):
    _cardset_store = None

    def __init__(self, parent, title, app, manager, key=None, **kw):
        kw = self.initKw(kw)
        MfxDialog.__init__(self, parent, title, **kw)
        #
        top_box, bottom_box = self.createHBox()
        #
        if key is None:
            key = manager.getSelected()
        self.app = app
        self.manager = manager
        self.key = key
        self.preview_key = -1
        self.all_keys = []

        if self._cardset_store is None:
            self._createStore()

        #padx, pady = kw.padx, kw.pady
        padx, pady = 5, 5
        # left
        # paned
        hpaned = gtk.HPaned()
        self.hpaned = hpaned
        hpaned.show()
        top_box.pack_start(hpaned, expand=True, fill=True)
        # tree
        treeview = PysolTreeView(self, self._cardset_store)
        self.treeview = treeview
        hpaned.pack1(treeview.scrolledwindow, True, True)
        ##treeview.treeview.expand_all()
        # right
        sw = gtk.ScrolledWindow()
        sw.show()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        hpaned.pack2(sw, True, True)
        ##self.scrolledwindow = sw
        #
        self.preview = MfxCanvas(self)
        self.preview.show()
        sw.add(self.preview)
        #hpaned.pack2(self.preview, True, True)
        self.preview.setTile(app, app.tabletile_index, force=True)
        #
        hpaned.set_position(240)

        self.createButtons(bottom_box, kw)

        ##~self.updatePreview(key)

        self.show_all()
        gtk.main()


    def _selectCardset(self, all_cardsets, selecter):
        if selecter is None:
            return [(cs.index, cs.name) for cs in all_cardsets]
        return [(cs.index, cs.name) for cs in all_cardsets if selecter(cs)]


    def _addCardsets(self, store, root_iter, root_label, cardsets):
        iter = store.append(root_iter)
        store.set(iter, 0, root_label, 1, -1)
        for index, name in cardsets:
            child_iter = store.append(iter)
            ##~ name = _(name)
            store.set(child_iter, 0, name, 1, index)


    def _addCardsetsByType(self, store, root_label, all_cardsets,
                           cardset_types, selecter_type, registered):
        manager = self.manager
        root_iter = store.append(None)
        store.set(root_iter, 0, root_label, 1, -1)
        items = cardset_types.items()
        items.sort(lambda a, b: cmp(a[1], b[1]))
        added = False
        for key, label in items:
            if key not in getattr(manager, registered):
                continue
            cardsets = []
            for cs in all_cardsets:
                si = getattr(cs.si, selecter_type)
                if isinstance(si, int): # type
                    if key == si:
                        cardsets.append((cs.index, cs.name))
                else: # style, nationality, date
                    if key in si:
                        cardsets.append((cs.index, cs.name))
            if cardsets:
                added = True
                self._addCardsets(store, root_iter, label, cardsets)
        if added:
            selecter = lambda cs, selecter_type=selecter_type: \
                           not getattr(cs.si, selecter_type)
            cs = self._selectCardset(all_cardsets, selecter)
            if cs:
                self._addCardsets(store, root_iter, _('Uncategorized'), cs)
        else:
            iter = store.append(root_iter)
            store.set(iter, 0, _('(no cardsets)'), 1, -1)

    def _createStore(self):
        store = gtk.TreeStore(gobject.TYPE_STRING,
                              gobject.TYPE_INT)
        manager = self.manager
        all_cardsets = manager.getAllSortedByName()
        all_cardsets = [obj for obj in all_cardsets if not obj.error]

        cs = self._selectCardset(all_cardsets, None)
        self._addCardsets(store, None, 'All cadsets', cs)

        root_iter = store.append(None)
        store.set(root_iter, 0, _('by Size'), 1, -1)
        for label, selecter in (
            (_("Tiny cardsets"),   lambda cs: cs.si.size == CSI.SIZE_TINY),
            (_("Small cardsets"),  lambda cs: cs.si.size == CSI.SIZE_SMALL),
            (_("Medium cardsets"), lambda cs: cs.si.size == CSI.SIZE_MEDIUM),
            (_("Large cardsets"),  lambda cs: cs.si.size == CSI.SIZE_LARGE),
            (_("XLarge cardsets"), lambda cs: cs.si.size == CSI.SIZE_XLARGE),):
            cs = self._selectCardset(all_cardsets, selecter)
            if cs:
                self._addCardsets(store, root_iter, label, cs)

        self._addCardsetsByType(store, _('by Type'), all_cardsets,
                                CSI.TYPE, 'type', 'registered_types')
        self._addCardsetsByType(store, _('by Style'), all_cardsets,
                                CSI.STYLE, 'styles', 'registered_styles')
        self._addCardsetsByType(store, _('by Nationality'), all_cardsets,
                                CSI.NATIONALITY, 'nationalities',
                                'registered_nationalities')
        self._addCardsetsByType(store, _('by Date'), all_cardsets,
                                CSI.DATE, 'dates', 'registered_dates')

        self._cardset_store = store


    def getSelected(self):
        index = self.treeview.getSelected()
        if index < 0:
            return None
        return index


    def showSelected(self, w):
        key = self.getSelected()
        if key is not None:
            self.updatePreview(key)
        pass


    def updatePreview(self, key):
        if key == self.preview_key:
            return
        canvas = self.preview
        canvas.deleteAllItems()
        self.preview_images = []
        cs = self.manager.get(key)
        if not cs:
            self.preview_key = -1
            return
        names, columns = cs.getPreviewCardNames()
        try:
            #???names, columns = cs.getPreviewCardNames()
            for n in names:
                f = os.path.join(cs.dir, n + cs.ext)
                self.preview_images.append(loadImage(file=f))
        except:
            self.preview_key = -1
            self.preview_images = []
            return
        i, x, y, sx, sy, dx, dy = 0, 10, 10, 0, 0, cs.CARDW + 10, cs.CARDH + 10
        for image in self.preview_images:
            MfxCanvasImage(canvas, x, y, anchor="nw", image=image)
            sx, sy = max(x, sx), max(y, sy)
            i = i + 1
            if i % columns == 0:
                x, y = 10, y + dy
            else:
                x = x + dx
        canvas.config(width=sx+dx, height=sy+dy)
        canvas.set_scroll_region(0, 0, sx+dx, sy+dy)
        self.preview_key = key


    def initKw(self, kw):
        kwdefault(kw,
                  strings=(_("&Load"), _("&Cancel"), _("&Info..."),),
                  default=1,
                  resizable=1,
                  padx=10, pady=10,
                  width=600, height=400,
                  )
        return MfxDialog.initKw(self, kw)


    def createInfo(self):
        pass


    def done(self, button):
        b = button.get_data('user_data')
        if b == 2:
            self.createInfo()
            return
        if b == 0:
            self.key = self.getSelected()
            if not self.key:
                self.key = self.preview_key
        self.status = 0
        self.button = b
        self.hide()
        self.quit()