def __init__(self, values_map, default, var_name, label, widget='menu'): self.values_map = values_map self.default = default ##self.values_dict = dict(self.values_map) self.translation_map = {} # for backward translation if widget == 'menu': self.values = [] for k, v in self.values_map: self.values.append(k) self.translation_map[_(k)] = k assert self.default in self.values elif widget == 'preset': self.values = [] for v in self.values_map: self.values.append(v) self.translation_map[_(v)] = v assert self.default in self.values else: self.values = self.values_map self.var_name = var_name self.label = label self.widget = widget self.variable = None # Tk variable self.current_value = None
def help_credits(app, timeout=0, sound=True): if sound: app.audio.playSample("credits") t = "" if TOOLKIT == "tk": t = "Tcl/Tk" elif TOOLKIT == "gtk": t = "PyGTK" elif TOOLKIT == "kde": t = "pyKDE" elif TOOLKIT == "wx": t = "wxPython" elif TOOLKIT == "kivy": t = "kivy" d = MfxMessageDialog( app.top, title=_("Credits"), timeout=timeout, text=TITLE+_(''' credits go to: Volker Weidner for getting me into Solitaire Guido van Rossum for the initial example program T. Kirk for lots of contributed games and cardsets Carl Larsson for the background music The Gnome AisleRiot team for parts of the documentation Natascha The Python, %s, SDL & Linux crews for making this program possible''') % t, image=app.gimages.logos[3], image_side="right", separator=True) return d.status
def __init__(self, parent, title, app, **kw): kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, **kw) # top_box, bottom_box = self.createVBox() # label = gtk.Label('Please enter your name') label.show() top_box.pack_start(label) self.player_entry = gtk.Entry() self.player_entry.show() top_box.pack_start(self.player_entry, expand=False) completion = gtk.EntryCompletion() self.player_entry.set_completion(completion) model = gtk.ListStore(gobject.TYPE_STRING) for name in app.getAllUserNames(): iter = model.append() model.set(iter, 0, name) completion.set_model(model) completion.set_text_column(0) self.player_entry.set_text(app.opt.player) # self.confirm_quit_check = gtk.CheckButton(_('Confirm quit')) self.confirm_quit_check.show() top_box.pack_start(self.confirm_quit_check) self.confirm_quit_check.set_active(app.opt.confirm != 0) # self.update_stats_check = gtk.CheckButton(_('Update statistics and logs')) self.update_stats_check.show() top_box.pack_start(self.update_stats_check) self.update_stats_check.set_active(app.opt.update_player_stats != 0) # self.createButtons(bottom_box, kw) self.show_all() gtk.main()
def _calc_tabs(self): # font = self.tk_font t0 = 160 t = '' for i in (_("Won:"), _("Lost:"), _("Total:")): if len(i) > len(t): t = i t1 = font.measure(t) # t1 = max(font.measure(_("Won:")), # font.measure(_("Lost:")), # font.measure(_("Total:"))) t1 += 10 # t2 = font.measure('99999')+10 t2 = 45 # t3 = font.measure('100%')+10 t3 = 45 tx = (t0, t0+t1+t2, t0+t1+t2+t3) # ls = self.font_metrics['linespace'] ls += 5 ls = max(ls, 20) ty = (ls, 2*ls, 3*ls+15, 3*ls+25) # self.tab_x, self.tab_y = tx, ty
def initKw(self, kw): kw = KwStruct( kw, strings=(_("&OK"), (_("&Full log..."), 103), (_("&Save to file"), 204)), default=0,) return FullLog_StatsDialog.initKw(self, kw)
def initKw(self, kw): kw = KwStruct(kw, strings=(_('&OK'), _('&Cancel')), default=0, separator=False, ) return MfxDialog.initKw(self, kw)
def initKw(self, kw): strings = [_('&Start'), _('&Play'), _('&New'), 'sep', _('&Close'), ] kw = KwStruct(kw, strings=strings, default=0, ) return self._calc_MfxDialog().initKw(self, kw)
def initKw(self, kw): kw = KwStruct(kw, strings=((_("&Rules"), 10), 'sep', _("&Select"), _("&Cancel"),), default=0, ) return SelectGameDialog.initKw(self, kw)
def initKw(self, kw): kwdefault(kw, strings=(_("&Select"), _("&Rules"), _("&Cancel"),), default=0, width=600, height=400, ) return MfxDialog.initKw(self, kw)
def initKw(self, kw): strings=[_('&Start'), _('&Play'), _('&New'), _('&Close'),] kw = KwStruct(kw, strings=strings, default=0, ) return MfxDialog.initKw(self, kw)
def mEditGameComment(self, *args): if self._cancelDrag(break_pause=False): return game, gi = self.game, self.game.gameinfo t = " " + game.getGameNumber(format=1) cc = _("Comments for %s:\n\n") % (gi.name + t) c = game.gsaveinfo.comment or cc d = EditTextDialog(game.top, _("Comments for ")+t, text=c) if d.status == 0 and d.button == 0: text = d.text if text.strip() == cc.strip(): game.gsaveinfo.comment = "" else: game.gsaveinfo.comment = d.text # save to file fn = os.path.join(self.app.dn.config, "comments.txt") fn = os.path.normpath(fn) if not text.endswith(os.linesep): text += os.linesep enc = locale.getpreferredencoding() try: fd = open(fn, 'a') fd.write(text.encode(enc, 'replace')) except Exception, err: d = MfxExceptionDialog(self.top, err, text=_("Error while writing to file")) else: if fd: fd.close() d = MfxMessageDialog(self.top, title=TITLE+_(" Info"), bitmap="info", text=_("Comments were appended to\n\n") + fn)
def _createLogList(self, name): # treeview = self.widgets_tree.get_widget(name) n = 0 for label in ( _('Game'), _('Game number'), _('Started at'), _('Status'), ): column = gtk.TreeViewColumn(label, gtk.CellRendererText(), text=n) column.set_resizable(True) column.set_sort_column_id(n) treeview.append_column(column) n += 1 # store = gtk.ListStore(gobject.TYPE_STRING, # game name gobject.TYPE_STRING, # game number gobject.TYPE_STRING, # started at gobject.TYPE_STRING, # status gobject.TYPE_INT, # gameid ) treeview.set_model(store) treeview.set_rules_hint(True) return store
def initKw(self, kw): strings = [_("&OK"), _("&Apply"), _("&Cancel"), ] kw = KwStruct(kw, strings=strings, default=0, ) return MfxDialog.initKw(self, kw)
def initKw(self, kw): kw = KwStruct(kw, strings=(_("&OK"), (_("Session &log..."), 104), (_("&Save to file"), 203)), default=0, width=76*self.CHAR_W, ) return AllGames_StatsDialog.initKw(self, kw)
def __init__(self, parent, app=None, home=None): self.parent = parent self.app = app self.home = home self.url = None self.history = Struct( list = [], index = 0, ) self.visited_urls = [] self.images = {} # need to keep a reference because of garbage collection self.defcursor = parent["cursor"] ##self.defcursor = 'xterm' self.handcursor = "hand2" # create buttons button_width = 8 self.homeButton = Tkinter.Button(parent, text=_("Index"), width=button_width, command=self.goHome) self.homeButton.grid(row=0, column=0, sticky='w') self.backButton = Tkinter.Button(parent, text=_("Back"), width=button_width, command=self.goBack) self.backButton.grid(row=0, column=1, sticky='w') self.forwardButton = Tkinter.Button(parent, text=_("Forward"), width=button_width, command=self.goForward) self.forwardButton.grid(row=0, column=2, sticky='w') self.closeButton = Tkinter.Button(parent, text=_("Close"), width=button_width, command=self.destroy) self.closeButton.grid(row=0, column=3, sticky='e') # create text widget text_frame = Tkinter.Frame(parent) text_frame.grid(row=1, column=0, columnspan=4, sticky='nsew') text_frame.grid_propagate(False) vbar = Tkinter.Scrollbar(text_frame) vbar.pack(side='right', fill='y') self.text = Tkinter.Text(text_frame, fg='black', bg='white', bd=1, relief='sunken', cursor=self.defcursor, wrap='word', padx=10) self.text.pack(side='left', fill='both', expand=True) self.text["yscrollcommand"] = vbar.set vbar["command"] = self.text.yview # statusbar self.statusbar = HtmlStatusbar(parent, row=2, column=0, columnspan=4) parent.columnconfigure(2, weight=1) parent.rowconfigure(1, weight=1) # load images for name, fn in self.symbols_fn.items(): self.symbols_img[name] = self.getImage(fn) self.initBindings()
def __init__(self, parent, title, app, player, gameid, **kw): self.app = app self.selected_game = None kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.top_frame = top_frame self.createBitmaps(top_frame, kw) # self.player = player or _("Demo games") self.top.wm_minsize(200, 200) self.button = kw.default # # createChart = self.create3DBarChart createChart = self.createPieChart # createChart = self.createSimpleChart # if parent.winfo_screenwidth() < 800 or parent.winfo_screenheight() < # 600: # createChart = self.createPieChart # createChart = self.createSimpleChart # self.font = self.app.getFont("default") self.tk_font = tkinter_font.Font(self.top, self.font) self.font_metrics = self.tk_font.metrics() self._calc_tabs() # won, lost = app.stats.getStats(player, gameid) createChart(app, won, lost, _("Total")) won, lost = app.stats.getSessionStats(player, gameid) createChart(app, won, lost, _("Current session")) # focus = self.createButtons(bottom_frame, kw) self.mainloop(focus, kw.timeout)
def startSolving(self): from gettext import ungettext self._reset() game = self.app.game solver = game.Solver_Class(game, self) # create solver instance game.solver = solver preset = self.preset_var.get() max_iters = self._getMaxIters() progress = self.app.opt.solver_show_progress solver.config(preset=preset, max_iters=max_iters, progress=progress) try: solver.computeHints() except RuntimeError: self.result_label['text'] = _('Solver not found in the PATH') return hints_len = len(solver.hints)-1 if hints_len > 0: t = ungettext('This game is solvable in %d move.', 'This game is solvable in %d moves.', hints_len) % hints_len self.result_label['text'] = t self.play_button.config(state='normal') else: self.result_label['text'] = \ (_('I could not solve this game.') if solver.solver_state == 'unsolved' else _('Iterations count exceeded (Intractable)')) self.play_button.config(state='disabled')
def _createChartTexts(self, tx, ty, won, lost): c, tfont, fg = self.canvas, self.font, self.fg pwon, plost = self._getPwon(won, lost) # x = tx[0] dy = int(self.font_metrics['ascent']) - 10 dy = dy / 2 c.create_text(x, ty[0] - dy, text=_("Won:"), anchor="nw", font=tfont, fill=fg) c.create_text(x, ty[1] - dy, text=_("Lost:"), anchor="nw", font=tfont, fill=fg) c.create_text(x, ty[2] - dy, text=_("Total:"), anchor="nw", font=tfont, fill=fg) x = tx[1] - 16 c.create_text(x, ty[0] - dy, text="%d" % won, anchor="ne", font=tfont, fill=fg) c.create_text(x, ty[1] - dy, text="%d" % lost, anchor="ne", font=tfont, fill=fg) c.create_text(x, ty[2] - dy, text="%d" % (won + lost), anchor="ne", font=tfont, fill=fg) y = ty[2] - 11 c.create_line(tx[0], y, x, y, fill=fg) if won + lost > 0: x = tx[2] pw = int(round(100.0 * pwon)) c.create_text(x, ty[0] - dy, text="%d%%" % pw, anchor="ne", font=tfont, fill=fg) c.create_text(x, ty[1] - dy, text="%d%%" % (100 - pw), anchor="ne", font=tfont, fill=fg)
def _calc_tabs(self): # font = self.dialog.tkfont t0 = self.oval_width+70 t = '' for i in (_("Won:"), _("Lost:"), _("Total:")): if len(i) > len(t): t = i t1 = font.measure(t) # t1 = max(font.measure(_("Won:")), # font.measure(_("Lost:")), # font.measure(_("Total:"))) t1 += 10 # t2 = font.measure('99999')+10 t2 = 45 # t3 = font.measure('100%')+10 t3 = 45 tx = (t0, t0+t1+t2, t0+t1+t2+t3, t0+t1+t2+t3+20) # ls = self.dialog.font_metrics['linespace'] ls += 5 # ls = max(ls, 20) ty = (5, 5+ls, 5+2*ls+15, max(85, 5+3*ls+15)) # self.tab_x, self.tab_y = tx, ty
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 _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 _mahjonggShuffle(self): talon = self.s.talon rows = [] cards = [] for r in self.s.rows: if r.cards: rows.append(r) cards.append(r.cards[0]) if not rows: return if self.app.opt.mahjongg_create_solvable == 0: self.playSample('turnwaste') old_state = self.enterState(self.S_FILL) self.saveSeedMove() for r in rows: self.moveMove(1, r, talon, frames=0) self.shuffleStackMove(talon) for r in rows: self.moveMove(1, talon, r, frames=0) self.leaveState(old_state) self.finishMove() return self.playSample('turnwaste') old_state = self.enterState(self.S_FILL) self.saveSeedMove() new_cards = self._shuffleHook2(rows, cards) if new_cards is None: if TOOLKIT != 'kivy': MfxMessageDialog(self.top, title=_('Warning'), text=_('''\ Sorry, I can\'t find a solvable configuration.'''), bitmap='warning') self.leaveState(old_state) # self.finishMove() # hack am = self.moves.current[0] am.undo(self) # restore random self.moves.current = [] return self.stats.shuffle_moves += 1 # move new_cards to talon for c in new_cards: for r in rows: if r.cards and r.cards[0] is c: self.moveMove(1, r, talon, frames=0) break # deal for r in rows: self.moveMove(1, talon, r, frames=0) self.leaveState(old_state) self.finishMove()
def mOptSoundDirectX(self, *event): ##print self.sound_mode.get() d = MfxMessageDialog(self.top, title=_("Sound preferences info"), text=_("""\ Changing DirectX settings will take effect the next time you restart """)+TITLE, bitmap="warning", default=0, strings=(_("&OK"),))
def initKw(self, kw): kw = KwStruct(kw, strings=(_("&OK"), _("&Cancel")), default=-1, resizable=False, separator=False, ) return MfxDialog.initKw(self, kw)
def initKw(self, kw): kw = KwStruct(kw, strings=(_("&OK"), _("&Cancel")), default=-1, resizable=self._calc_Resizable(), separator=False, ) return self._calc_MfxDialog().initKw(self, kw)
def initKw(self, kw): kw = KwStruct(kw, strings=(_("&OK"), _("&Cancel")), default=0, padx=10, pady=10, buttonpadx=10, buttonpady=5, ) return MfxDialog.initKw(self, kw)
def mRestart(self, *args): if self._cancelDrag(): return if self.game.moves.index == 0: return if self.changed(restart=1): if not self.game.areYouSure(_("Restart game"), _("Restart this game ?")): return self.game.restartGame()
def mClearBookmarks(self, *args): if self._cancelDrag(): return if not self.app.opt.bookmarks: return if not self.game.gsaveinfo.bookmarks: return if not self.game.areYouSure(_("Clear bookmarks"), _("Clear all bookmarks ?")): return self.game.gsaveinfo.bookmarks = {} self.game.updateMenus()
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 __init__(self, parent, title, top, **kw): kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) cnf = {'master': top_frame, 'highlightthickness': 1, 'highlightbackground': 'black', } frame = tkinter.Frame(**cnf) frame.pack(expand=True, fill='both', padx=10, pady=10) frame.columnconfigure(0, weight=1) cnf['master'] = frame cnf['text'] = _('N') label = tkinter.Label(**cnf) label.grid(row=0, column=0, sticky='ew') cnf['text'] = _('Game number') label = tkinter.Label(**cnf) label.grid(row=0, column=1, sticky='ew') cnf['text'] = _('Started at') label = tkinter.Label(**cnf) label.grid(row=0, column=2, sticky='ew') cnf['text'] = _('Result') label = tkinter.Label(**cnf) label.grid(row=0, column=3, sticky='ew') row = 1 for i in top: # N cnf['text'] = str(row) label = tkinter.Label(**cnf) label.grid(row=row, column=0, sticky='ew') # Game number cnf['text'] = '#'+str(i.game_number) label = tkinter.Label(**cnf) label.grid(row=row, column=1, sticky='ew') # Start time t = time.strftime( '%Y-%m-%d %H:%M', time.localtime(i.game_start_time)) cnf['text'] = t label = tkinter.Label(**cnf) label.grid(row=row, column=2, sticky='ew') # Result if isinstance(i.value, float): # time s = format_time(i.value) else: # moves s = str(i.value) cnf['text'] = s label = tkinter.Label(**cnf) label.grid(row=row, column=3, sticky='ew') row += 1 focus = self.createButtons(bottom_frame, kw) self.mainloop(focus, kw.timeout)
def writeSessionLog(self, player): if player is None: player = _('Demo') header = _("Session log for %(player)s") % {'player': player} prev_games = self.app.stats.session_games.get(player) return self.writeLog(player, header, prev_games)
def display(self, url, add=1, relpath=1, position=(0, 0)): # print 'display:', url, position # for some reason we have to stop the PySol demo # (is this a multithread problem with tkinter ?) try: # self.app.game.stopDemo() # self.app.game._cancelDrag() pass except Exception: pass # ftp: and http: would work if we use urllib, but this widget is # far too limited to display anything but our documentation... for p in REMOTE_PROTOCOLS: if url.startswith(p): if not openURL(url): self.errorDialog(_('''%(app)s HTML limitation: The %(protocol)s protocol is not supported yet. Please use your standard web browser to open the following URL: %(url)s ''') % {'app': TITLE, 'protocol': p, 'url': url}) return # locate the file relative to the current url url = self.basejoin(url, relpath=relpath) # read the file try: file = None if 0: import urllib file = urllib.urlopen(url) else: file, url = self.openfile(url) data = file.read() file.close() file = None except Exception as ex: if file: file.close() self.errorDialog( _('Unable to service request:\n') + url + '\n\n' + str(ex)) return except Exception: if file: file.close() self.errorDialog(_('Unable to service request:\n') + url) return self.url = url if self.home is None: self.home = self.url if add: self.addHistory(self.url, position=position) # print self.history.index, self.history.list if self.history.index > 1: self.backButton.set_sensitive(True) else: self.backButton.set_sensitive(False) if self.history.index < len(self.history.list): self.forwardButton.set_sensitive(True) else: self.forwardButton.set_sensitive(False) start, end = self.textbuffer.get_bounds() self.textbuffer.delete(start, end) writer = tkHTMLWriter(self.textbuffer, self, self.app) fmt = pysollib.formatter.AbstractFormatter(writer) parser = tkHTMLParser(fmt) parser.feed(data) parser.close() self.set_position(position) self.parent.set_title(parser.title)
def errorDialog(self, msg): MfxMessageDialog( self.parent, title=TITLE+' HTML Problem', text=msg, bitmap='warning', strings=(_('&OK'),), default=0)
def __init__(self, parent, title, app, manager, key=None, **kw): kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) # if key is None: key = manager.getSelected() self.manager = manager self.key = key self.app = app self.cardset_values = None # padx, pady = kw.padx, kw.pady padx, pady = 5, 5 if self.TreeDataHolder_Class.data is None: self.TreeDataHolder_Class.data = self.TreeData_Class(manager, key) # self.top.wm_minsize(400, 200) if self.top.winfo_screenwidth() >= 800: w1, w2 = 240, 400 else: w1, w2 = 200, 300 paned_window = ttk.PanedWindow(top_frame, orient='horizontal') paned_window.pack(expand=True, fill='both') left_frame = ttk.Frame(paned_window) right_frame = ttk.Frame(paned_window) paned_window.add(left_frame) paned_window.add(right_frame) font = app.getFont("default") self.tree = self.Tree_Class(self, left_frame, key=key, default=kw.default, font=font, width=w1) self.tree.frame.grid(row=0, column=0, sticky='nsew', padx=padx, pady=pady) if USE_PIL: # var = tkinter.DoubleVar() var.set(app.opt.scale_x) self.scale_x = PysolScale(left_frame, label=_('Scale X:'), from_=0.5, to=4.0, resolution=0.1, orient='horizontal', variable=var, value=app.opt.scale_x, command=self._updateScale) self.scale_x.grid(row=1, column=0, sticky='ew', padx=padx, pady=pady) # var = tkinter.DoubleVar() var.set(app.opt.scale_y) self.scale_y = PysolScale(left_frame, label=_('Scale Y:'), from_=0.5, to=4.0, resolution=0.1, orient='horizontal', variable=var, value=app.opt.scale_y, command=self._updateScale) self.scale_y.grid(row=2, column=0, sticky='ew', padx=padx, pady=pady) # self.auto_scale = tkinter.BooleanVar() self.auto_scale.set(app.opt.auto_scale) check = ttk.Checkbutton(left_frame, text=_('Auto scaling'), variable=self.auto_scale, takefocus=False, command=self._updateAutoScale) check.grid(row=3, column=0, columnspan=2, sticky='ew', padx=padx, pady=pady) # self.preserve_aspect = tkinter.BooleanVar() self.preserve_aspect.set(app.opt.preserve_aspect_ratio) self.aspect_check = ttk.Checkbutton( left_frame, text=_('Preserve aspect ratio'), variable=self.preserve_aspect, takefocus=False, # command=self._updateScale ) self.aspect_check.grid(row=4, column=0, sticky='ew', padx=padx, pady=pady) self._updateAutoScale() # left_frame.rowconfigure(0, weight=1) left_frame.columnconfigure(0, weight=1) # self.preview = MfxScrolledCanvas(right_frame, width=w2) self.preview.setTile(app, app.tabletile_index, force=True) self.preview.pack(fill='both', expand=True, padx=padx, pady=pady) self.preview.canvas.preview = 1 # create a preview of the current state self.preview_key = -1 self.preview_images = [] self.scale_images = [] self.updatePreview(key) # focus = self.createButtons(bottom_frame, kw) focus = self.tree.frame self.mainloop(focus, kw.timeout)
def __init__(self, parent, title, cardset, images, **kw): kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) frame = ttk.Frame(top_frame) frame.pack(fill="both", expand=True, padx=5, pady=10) # # row = 0 info_frame = ttk.LabelFrame(frame, text=_('About cardset')) info_frame.grid(row=row, column=0, columnspan=2, sticky='ew', padx=0, pady=5, ipadx=5, ipady=5) row += 1 styles = nationalities = year = None if cardset.si.styles: styles = '\n'.join([CSI.STYLE[i] for i in cardset.si.styles]) if cardset.si.nationalities: nationalities = '\n'.join( [CSI.NATIONALITY[i] for i in cardset.si.nationalities]) if cardset.year: year = str(cardset.year) frow = 0 for n, t in ( # ('Version:', str(cardset.version)), (_('Type:'), CSI.TYPE[cardset.type]), (_('Styles:'), styles), (_('Nationality:'), nationalities), (_('Year:'), year), # (_('Number of cards:'), str(cardset.ncards)), (_('Size:'), '%d x %d' % (cardset.CARDW, cardset.CARDH)), ): if t is not None: label = ttk.Label(info_frame, text=n, anchor='w', justify='left') label.grid(row=frow, column=0, sticky='nw', padx=4) label = ttk.Label(info_frame, text=t, anchor='w', justify='left') label.grid(row=frow, column=1, sticky='nw', padx=4) frow += 1 if images: try: from random import choice im = choice(images) f = os.path.join(cardset.dir, cardset.backname) self.back_image = loadImage(file=f) # store the image label = ttk.Label(info_frame, image=im, padding=5) label.grid(row=0, column=2, rowspan=frow + 1, sticky='ne') label = ttk.Label(info_frame, image=self.back_image, padding=(0, 5, 5, 5)) # left margin = 0 label.grid(row=0, column=3, rowspan=frow + 1, sticky='ne') info_frame.columnconfigure(2, weight=1) info_frame.rowconfigure(frow, weight=1) except Exception: pass if USE_PIL: padx = 4 pady = 0 settings_frame = ttk.LabelFrame(frame, text=_('Settings')) settings_frame.grid(row=row, column=0, columnspan=2, sticky='ew', padx=0, pady=5, ipadx=5, ipady=5) row += 1 var = tkinter.IntVar() self.x_offset = PysolScale( settings_frame, label=_('X offset:'), from_=5, to=40, resolution=1, orient='horizontal', variable=var, value=cardset.CARD_XOFFSET, # command=self._updateScale ) self.x_offset.grid(row=0, column=0, sticky='ew', padx=padx, pady=pady) var = tkinter.IntVar() self.y_offset = PysolScale( settings_frame, label=_('Y offset:'), from_=5, to=40, resolution=1, orient='horizontal', variable=var, value=cardset.CARD_YOFFSET, # command=self._updateScale ) self.y_offset.grid(row=1, column=0, sticky='ew', padx=padx, pady=pady) row += 1 # bg = top_frame["bg"] bg = 'white' text_w = tkinter.Text(frame, bd=1, relief="sunken", wrap="word", padx=4, width=64, height=16, bg=bg) text_w.grid(row=row, column=0, sticky='nsew') sb = ttk.Scrollbar(frame) sb.grid(row=row, column=1, sticky='ns') text_w.configure(yscrollcommand=sb.set) sb.configure(command=text_w.yview) frame.columnconfigure(0, weight=1) frame.rowconfigure(1, weight=1) # text = '' f = os.path.join(cardset.dir, "COPYRIGHT") try: text = open(f).read() except Exception: pass if text: text_w.config(state="normal") text_w.insert("insert", text) text_w.config(state="disabled") # focus = self.createButtons(bottom_frame, kw) # focus = text_w self.mainloop(focus, kw.timeout)
def __init__(self, manager, key): SelectDialogTreeData.__init__(self) self.all_objects = manager.getAllSortedByName() self.all_objects = [obj for obj in self.all_objects if not obj.error] self.no_contents = [ SelectCardsetLeaf(None, None, _("(no cardsets)"), key=None), ] # select_by_type = None items = list(CSI.TYPE.items()) items.sort(key=lambda x: x[1]) nodes = [] for key, name in items: if manager.registered_types.get(key): nodes.append( SelectCardsetNode(None, name, lambda cs, key=key: key == cs.si.type)) if nodes: select_by_type = SelectCardsetNode(None, _("by Type"), tuple(nodes), expanded=1) # select_by_style = None items = list(CSI.STYLE.items()) items.sort(key=lambda x: x[1]) nodes = [] for key, name in items: if manager.registered_styles.get(key): nodes.append( SelectCardsetNode(None, name, lambda cs, key=key: key in cs.si.styles)) if nodes: nodes.append( SelectCardsetNode(None, _("Uncategorized"), lambda cs: not cs.si.styles)) select_by_style = SelectCardsetNode(None, _("by Style"), tuple(nodes)) # select_by_nationality = None items = list(CSI.NATIONALITY.items()) items.sort(key=lambda x: x[1]) nodes = [] for key, name in items: if manager.registered_nationalities.get(key): nodes.append( SelectCardsetNode( None, name, lambda cs, key=key: key in cs.si.nationalities)) if nodes: nodes.append( SelectCardsetNode(None, _("Uncategorized"), lambda cs: not cs.si.nationalities)) select_by_nationality = SelectCardsetNode(None, _("by Nationality"), tuple(nodes)) # select_by_date = None items = list(CSI.DATE.items()) items.sort(key=lambda x: x[1]) nodes = [] for key, name in items: if manager.registered_dates.get(key): nodes.append( SelectCardsetNode(None, name, lambda cs, key=key: key in cs.si.dates)) if nodes: nodes.append( SelectCardsetNode(None, _("Uncategorized"), lambda cs: not cs.si.dates)) select_by_date = SelectCardsetNode(None, _("by Date"), tuple(nodes)) # self.rootnodes = [ _f for _f in ( SelectCardsetNode(None, _("All Cardsets"), lambda cs: 1, expanded=len(self.all_objects) <= 12), SelectCardsetNode(None, _("by Size"), ( SelectCardsetNode( None, _("Tiny cardsets"), lambda cs: cs.si.size == CSI.SIZE_TINY), SelectCardsetNode( None, _("Small cardsets"), lambda cs: cs.si.size == CSI.SIZE_SMALL), SelectCardsetNode( None, _("Medium cardsets"), lambda cs: cs.si.size == CSI.SIZE_MEDIUM), SelectCardsetNode( None, _("Large cardsets"), lambda cs: cs.si.size == CSI.SIZE_LARGE), SelectCardsetNode( None, _("XLarge cardsets"), lambda cs: cs.si.size == CSI.SIZE_XLARGE), ), expanded=1), select_by_type, select_by_style, select_by_date, select_by_nationality, ) if _f ]
def mPlayerStats(self, *args, **kw): wasPaused = False if not self.game.pause: self.game.doPause() wasPaused = True mode = kw.get("mode", 101) demo = 0 gameid = None while mode > 0: if mode > 1000: demo = not demo mode = mode % 1000 # d = Struct(status=-1, button=-1) if demo: player = None else: player = self.app.opt.player n = self.game.gameinfo.name # translation keywords transkw = {'app': TITLE, 'player': player, 'game': n, 'tops': TOP_SIZE} # if mode == 100: d = Status_StatsDialog(self.top, game=self.game) elif mode == 101: header = (_("%(app)s Demo Statistics for %(game)s") if demo else _("Statistics for %(game)s")) % transkw d = SingleGame_StatsDialog( self.top, header, self.app, player, gameid=self.game.id) gameid = d.selected_game elif mode == 102: header = (_("%(app)s Demo Statistics") if demo else _("Statistics for %(player)s")) % transkw d = AllGames_StatsDialog(self.top, header, self.app, player) gameid = d.selected_game elif mode == 103: header = (_("%(app)s Demo Full log") if demo else _("Full log for %(player)s")) % transkw d = FullLog_StatsDialog(self.top, header, self.app, player) elif mode == 104: header = (_("%(app)s Demo Session log") if demo else _("Session log for %(player)s")) % transkw d = SessionLog_StatsDialog(self.top, header, self.app, player) elif mode == 105: # TRANSLATORS: eg. top 10 or top 5 results for a certain game header = (_("%(app)s Demo Top %(tops)d for %(game)s") if demo else _("Top %(tops)d for %(game)s")) % transkw d = Top_StatsDialog( self.top, header, self.app, player, gameid=self.game.id) elif mode == 106: header = _("Game Info") d = GameInfoDialog(self.top, header, self.app) elif mode == 107: header = _("Statistics progression") d = ProgressionDialog( self.top, header, self.app, player, gameid=self.game.id) elif mode == 202: # print stats to file write_method = FileStatsFormatter.writeStats self._mStatsSave(player, "stats", write_method) elif mode == 203: # print full log to file write_method = FileStatsFormatter.writeFullLog self._mStatsSave(player, "log", write_method) elif mode == 204: # print session log to file write_method = FileStatsFormatter.writeSessionLog self._mStatsSave(player, "log", write_method) elif mode == 301: # reset all player stats if self.game.areYouSure( _("Reset all statistics"), _("Reset ALL statistics and logs for player\n" + "%(player)s?") % transkw, confirm=1, default=1 ): self.app.stats.resetStats(player, 0) self.game.updateStatus(stats=self.app.stats.getStats( self.app.opt.player, self.game.id)) elif mode == 302: # reset player stats for current game if self.game.areYouSure( _("Reset game statistics"), _('Reset statistics and logs for player\n%(player)s\n' 'and game\n%(game)s?') % transkw, confirm=1, default=1 ): self.app.stats.resetStats(player, self.game.id) self.game.updateStatus(stats=self.app.stats.getStats( self.app.opt.player, self.game.id)) elif mode == 401: # start a new game with a gameid if gameid and gameid != self.game.id: self.game.endGame() self.game.quitGame(gameid) elif mode == 402: # start a new game with a gameid / gamenumber # TODO pass else: print_err("stats problem: %s %s %s" % (mode, demo, player)) pass if d.status != 0: break mode = d.button if self.game.pause: if wasPaused: self.game.doPause()
self.translation_map[_(v)] = v assert self.default in self.values else: self.values = self.values_map self.var_name = var_name self.label = label self.widget = widget self.variable = None # Tk variable self.current_value = None WizardPresets = WizSetting( values_map=list(presets.keys()), default='None', widget='preset', label=_('Initial setting:'), var_name='preset', ) GameName = WizSetting( values_map=(), default=_('My Game'), widget='entry', label=_('Name:'), var_name='name', ) SkillLevel = WizSetting( values_map=( (n_('Luck only'), GI.SL_LUCK), (n_('Mostly luck'), GI.SL_MOSTLY_LUCK), (n_('Balanced'), GI.SL_BALANCED), (n_('Mostly skill'), GI.SL_MOSTLY_SKILL),
def __init__(self, parent, title, app, gameid, bookmark=None, **kw): kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) # self.app = app self.gameid = gameid self.bookmark = bookmark self.random = None if self.TreeDataHolder_Class.data is None: self.TreeDataHolder_Class.data = self.TreeData_Class(app) # sw = self.top.winfo_screenwidth() sh = self.top.winfo_screenheight() h = int(sh * .8) w = int(sw * .8) w1 = int(min(275, sw / 2.5)) geometry = ("%dx%d+%d+%d" % (w, h, (sw - w) / 2, (sh - h) / 2)) self.top.wm_minsize(400, 200) # print sw, w1, w2 # w2 = max(200, min(w2, 10 + 12 * (app.subsampled_images.CARDW + 10))) # print sw, w1, w2 # padx, pady = kw.padx, kw.pady # padx, pady = kw.padx/2, kw.pady/2 padx, pady = 4, 4 # PanedWindow paned_window = ttk.PanedWindow(top_frame, orient='horizontal') paned_window.pack(expand=True, fill='both', padx=8, pady=8) left_frame = ttk.Frame(paned_window) right_frame = ttk.Frame(paned_window) paned_window.add(left_frame) paned_window.add(right_frame) notebook = ttk.Notebook(left_frame) notebook.pack(expand=True, fill='both') tree_frame = ttk.Frame(notebook) notebook.add(tree_frame, text=_('Tree View')) search_frame = ttk.Frame(notebook) notebook.add(search_frame, text=_('Search')) # Tree font = app.getFont("default") self.tree = self.Tree_Class(self, tree_frame, key=gameid, default=kw.default, font=font, width=w1) self.tree.frame.pack(padx=padx, pady=pady, expand=True, fill='both') # Search searchText = tkinter.StringVar() self.list_searchlabel = tkinter.Label(search_frame, text="Search:", justify='left', anchor='w') self.list_searchlabel.pack(side="top", fill='both', ipadx=1) self.list_searchtext = tkinter.Entry(search_frame, textvariable=searchText) self.list_searchtext.pack(side="top", fill='both', padx=padx, pady=pady, ipadx=1) searchText.trace('w', self.performSearch) self.list_scrollbar = tkinter.Scrollbar(search_frame) self.list_scrollbar.pack(side="right", fill='both') self.createBitmaps(search_frame, kw) self.list = tkinter.Listbox(search_frame, exportselection=False) self.list.pack(padx=padx, pady=pady, expand=True, side='left', fill='both', ipadx=1) self.updateSearchList("") bind(self.list, '<<ListboxSelect>>', self.selectSearchResult) bind(self.list, '<FocusOut>', lambda e: self.list.selection_clear(0, 'end')) self.list.config(yscrollcommand=self.list_scrollbar.set) self.list_scrollbar.config(command=self.list.yview) # LabelFrame info_frame = ttk.LabelFrame(right_frame, text=_('About game')) info_frame.grid(row=0, column=0, padx=padx, pady=pady, ipadx=4, ipady=4, sticky='nws') stats_frame = ttk.LabelFrame(right_frame, text=_('Statistics')) stats_frame.grid(row=0, column=1, padx=padx, pady=pady, ipadx=4, ipady=4, sticky='nws') # 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 = ttk.Label(f, text=t, justify='left', anchor='w') title_label.grid(row=row, column=0, sticky='nw', padx=4) text_label = ttk.Label(f, justify='left', anchor='w') text_label.grid(row=row, column=1, sticky='nw', padx=4) self.info_labels[n] = (title_label, text_label) # info_frame.columnconfigure(1, weight=1) info_frame.rowconfigure(6, weight=1) stats_frame.rowconfigure(6, weight=1) # Canvas self.preview = MfxScrolledCanvas(right_frame) self.preview.setTile(app, app.tabletile_index, force=True) self.preview.grid(row=1, column=0, columnspan=3, padx=padx, pady=pady, sticky='nsew') right_frame.columnconfigure(1, weight=1) right_frame.rowconfigure(1, weight=1) # focus = self.createButtons(bottom_frame, kw) # set the scale factor self.preview.canvas.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) # focus = self.tree.frame self.mainloop(focus, kw.timeout, geometry=geometry)
def updatePreview(self, gameid, animations=10): if gameid == self.preview_key: return self.deletePreview() canvas = self.preview.canvas # 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.top.wm_title(_("Select Game - %(game)s") % {'game': title}) # self.preview_game = gi.gameclass(gi) self.preview_game.createPreview(self.preview_app) # 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) gw, gh = self.preview_game.width, self.preview_game.height canvas.config(scrollregion=(0, 0, gw, gh)) canvas.xview_moveto(0) canvas.yview_moveto(0) # 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[0] if self.app.getGameRulesFilename(gameid): rules_button.config(state="normal") else: rules_button.config(state="disabled")
def __init__(self, parent, app=None, home=None): self.parent = parent self.app = app self.home = home self.url = None self.history = Struct( list=[], index=0, ) self.visited_urls = [] self.images = {} self.anchor_tags = {} # create buttons vbox = gtk.VBox() parent.table.attach( vbox, 0, 1, 0, 1, gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL | gtk.SHRINK, 0, 0) buttons_box = gtk.HBox() vbox.pack_start(buttons_box, fill=True, expand=False) for name, label, callback in ( ('homeButton', _('Index'), self.goHome), ('backButton', _('Back'), self.goBack), ('forwardButton', _('Forward'), self.goForward), ('closeButton', _('Close'), self.destroy) ): button = gtk.Button(label) button.show() button.connect('clicked', callback) buttons_box.pack_start(button, fill=True, expand=False) button.set_property('can-focus', False) setattr(self, name, button) # create text widget self.textview = gtk.TextView() self.textview.show() self.textview.set_left_margin(10) self.textview.set_right_margin(10) self.textview.set_cursor_visible(False) self.textview.set_editable(False) self.textview.set_wrap_mode(gtk.WRAP_WORD) self.textbuffer = self.textview.get_buffer() sw = gtk.ScrolledWindow() sw.set_property('hscrollbar-policy', gtk.POLICY_AUTOMATIC) sw.set_property('vscrollbar-policy', gtk.POLICY_AUTOMATIC) sw.set_property('border-width', 0) sw.add(self.textview) sw.show() vbox.pack_start(sw, fill=True, expand=True) self.vadjustment = sw.get_vadjustment() self.hadjustment = sw.get_hadjustment() # statusbar self.statusbar = gtk.Statusbar() self.statusbar.show() vbox.pack_start(self.statusbar, fill=True, expand=False) # load images for name, fn in self.symbols_fn.items(): self.symbols_img[name] = self.getImage(fn) # bindings parent.connect('key-press-event', self.key_press_event) parent.connect('destroy', self.destroy) self.textview.connect('motion-notify-event', self.motion_notify_event) self.textview.connect('leave-notify-event', self.leave_event) self.textview.connect('enter-notify-event', self.motion_notify_event) self._changed_cursor = False self.createFontMap() # cursor self.defcursor = gdk.XTERM self.handcursor = gdk.HAND2 # self.textview.realize() # window = self.textview.get_window(gtk.TEXT_WINDOW_TEXT) # window.set_cursor(gdk.Cursor(self.defcursor)) parent.set_default_size(600, 440) parent.show_all() gobject.idle_add(gtk.main)
def getLogHeader(self): return _("Game"), _("Game number"), _("Started at"), _("Status")
def getStatHeader(self): return (_("Game"), _("Played"), _("Won"), _("Lost"), _('Playing time'), _('Moves'), _("% won"))