Expanded my entry in contributors.txt.
[fpdb-dooglus.git] / pyfpdb / TournamentTracker.py
blob614cf6b3dd7001b10cb975a17c335f89f65d3001
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """TourneyTracker.py
4 Based on HUD_main .. who knows if we want to actually use this or not
5 """
6 # Copyright (c) 2009-2011 Eric Blade, and the FPDB team.
8 #This program is free software: you can redistribute it and/or modify
9 #it under the terms of the GNU Affero General Public License as published by
10 #the Free Software Foundation, version 3 of the License.
12 #This program is distributed in the hope that it will be useful,
13 #but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 #GNU General Public License for more details.
17 #You should have received a copy of the GNU Affero General Public License
18 #along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #In the "official" distribution you can find the license in agpl-3.0.txt.
22 import L10n
23 _ = L10n.get_translation()
25 # to do allow window resizing
26 # to do hud to echo, but ignore non numbers
27 # to do no stat window for hero
28 # to do things to add to config.xml
30 # Standard Library modules
31 import sys
32 import os
33 import Options
34 import traceback
36 (options, argv) = Options.fpdb_options()
38 if not options.errorsToConsole:
39 print _("Note: error output is being diverted to fpdb-error-log.txt and HUD-error.txt. Any major error will be reported there _only_.")
40 errorFile = open('tourneyerror.txt', 'w', 0)
41 sys.stderr = errorFile
43 import thread
44 import time
45 import string
46 import re
48 # pyGTK modules
49 import pygtk
50 import gtk
51 import gobject
53 # FreePokerTools modules
54 import Configuration
55 import Database
56 import SummaryEverleaf
58 class Tournament:
59 """Tournament will hold the information about a tournament, I guess ? Remember I'm new to this language, so I don't know the best ways to do things"""
61 def __init__(self, parent, site, tid): # site should probably be something in the config object, but i don't know how the config object works right now, so we're going to make it a str ..
62 print "Tournament init"
63 self.parent = parent
64 self.window = None
65 self.site = site
66 self.id = tid
67 self.starttime = time.time()
68 self.endtime = None
69 self.game = None
70 self.structure = None
71 self.buyin = 0
72 self.fee = 0
73 self.rebuys = False
74 self.numrebuys = 0 # this should probably be attached to the players list...
75 self.numplayers = 0
76 self.prizepool = 0
77 self.players = {} # eventually i'd guess we'd probably want to fill this with playername:playerid's
78 self.results = {} # i'd guess we'd want to load this up with playerid's instead of playernames, too, as well, also
80 # if site == "Everleaf": # this should be attached to a button that says "retrieve tournament info" or something for sites that we know how to do it for
81 summary = SummaryEverleaf.EverleafSummary()
82 self.site = summary.parser.SiteName
83 self.id = summary.parser.TourneyId
84 self.starttime = summary.parser.TourneyStartTime
85 self.endtime = summary.parser.TourneyEndTime
86 self.game = summary.parser.TourneyGameType
87 self.structure = summary.parser.TourneyStructure
88 self.buyin = summary.parser.TourneyBuyIn # need to remember to parse the Fee out of this and move it to self.fee
89 self.rebuys = (summary.parser.TourneyRebuys == "yes")
90 self.prizepool = summary.parser.TourneyPool
91 self.numplayers = summary.parser.TourneysPlayers
93 self.openwindow() # let's start by getting any info we need.. meh
95 def openwindow(self, widget=None):
96 if self.window is not None:
97 self.window.show() # isn't there a better way to bring something to the front? not that GTK focus works right anyway, ever
98 else:
99 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
100 print _("tournament edit window="), self.window
101 self.window.connect("delete_event", self.delete_event)
102 self.window.connect("destroy", self.destroy)
103 self.window.set_title(_("FPDB Tournament Entry"))
104 self.window.set_border_width(1)
105 self.window.set_default_size(480,640)
106 self.window.set_resizable(True)
108 self.main_vbox = gtk.VBox(False, 1)
109 self.main_vbox.set_border_width(1)
110 self.window.add(self.main_vbox)
111 self.window.show()
113 def addrebuy(self, widget=None):
114 t = self
115 t.numrebuys += 1
116 t.mylabel.set_label("%s - %s - %s - %s - %s %s - %s - %s - %s - %s - %s" % (t.site, t.id, t.starttime, t.endtime, t.structure, t.game, t.buyin, t.fee, t.numrebuys, t.numplayers, t.prizepool))
118 def delete_event(self, widget, event, data=None):
119 return False
121 def destroy(self, widget, data=None):
122 return False
123 #end def destroy
126 class ttracker_main(object):
127 """A main() object to own both the read_stdin thread and the gui."""
128 # This class mainly provides state for controlling the multiple HUDs.
130 def __init__(self, db_name = 'fpdb'):
131 self.db_name = db_name
132 self.config = Configuration.Config(file=options.config, dbname=options.dbname)
133 self.tourney_list = []
135 # a thread to read stdin
136 gobject.threads_init() # this is required
137 thread.start_new_thread(self.read_stdin, ()) # starts the thread
139 # a main window
140 self.main_window = gtk.Window()
141 self.main_window.connect("destroy", self.destroy)
142 self.vb = gtk.VBox()
143 self.label = gtk.Label(_('Closing this window will stop the Tournament Tracker'))
144 self.vb.add(self.label)
145 self.addbutton = gtk.Button(label=_("Enter Tournament"))
146 self.addbutton.connect("clicked", self.addClicked, "add tournament")
147 self.vb.add(self.addbutton)
149 self.main_window.add(self.vb)
150 self.main_window.set_title(_("FPDB Tournament Tracker"))
151 self.main_window.show_all()
153 def addClicked(self, widget, data): # what is "data"? i'm guessing anything i pass in after the function name in connect() but unsure because the documentation sucks
154 print "addClicked", widget, data
155 t = Tournament(self, None, None)
156 if t is not None:
157 print "new tournament=", t
158 self.tourney_list.append(t)
159 mylabel = gtk.Label("%s - %s - %s - %s - %s %s - %s - %s - %s - %s - %s" % (t.site, t.id, t.starttime, t.endtime, t.structure, t.game, t.buyin, t.fee, t.numrebuys, t.numplayers, t.prizepool))
160 print "new label=", mylabel
161 editbutton = gtk.Button(label=_("Edit"))
162 print "new button=", editbutton
163 editbutton.connect("clicked", t.openwindow)
164 rebuybutton = gtk.Button(label=_("Rebuy"))
165 rebuybutton.connect("clicked", t.addrebuy)
166 self.vb.add(rebuybutton)
167 self.vb.add(editbutton) # These should probably be put in.. a.. h-box? i don't know..
168 self.vb.add(mylabel)
169 self.main_window.resize_children()
170 self.main_window.show()
171 mylabel.show()
172 editbutton.show()
173 rebuybutton.show()
174 t.mylabel = mylabel
175 t.editbutton = editbutton
176 t.rebuybutton = rebuybutton
177 self.vb.show()
178 print self.tourney_list
180 return True
181 else:
182 return False
183 # when we move the start command over to the main program, we can have the main program ask for the tourney id, and pipe it into the stdin here
184 # at least that was my initial thought on it
186 def destroy(*args): # call back for terminating the main eventloop
187 gtk.main_quit()
189 def create_HUD(self, new_hand_id, table, table_name, max, poker_game, stat_dict, cards):
191 def idle_func():
193 gtk.gdk.threads_enter()
194 try:
195 newlabel = gtk.Label("%s - %s" % (table.site, table_name))
196 self.vb.add(newlabel)
197 newlabel.show()
198 self.main_window.resize_children()
200 self.hud_dict[table_name].tablehudlabel = newlabel
201 self.hud_dict[table_name].create(new_hand_id, self.config, stat_dict, cards)
202 for m in self.hud_dict[table_name].aux_windows:
203 m.create()
204 m.update_gui(new_hand_id)
205 self.hud_dict[table_name].update(new_hand_id, self.config)
206 self.hud_dict[table_name].reposition_windows()
207 return False
208 finally:
209 gtk.gdk.threads_leave()
211 self.hud_dict[table_name] = Hud.Hud(self, table, max, poker_game, self.config, self.db_connection)
212 self.hud_dict[table_name].table_name = table_name
213 self.hud_dict[table_name].stat_dict = stat_dict
214 self.hud_dict[table_name].cards = cards
215 [aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[table_name].aux_windows]
216 gobject.idle_add(idle_func)
218 def update_HUD(self, new_hand_id, table_name, config):
219 """Update a HUD gui from inside the non-gui read_stdin thread."""
220 # This is written so that only 1 thread can touch the gui--mainly
221 # for compatibility with Windows. This method dispatches the
222 # function idle_func() to be run by the gui thread, at its leisure.
223 def idle_func():
224 gtk.gdk.threads_enter()
225 try:
226 self.hud_dict[table_name].update(new_hand_id, config)
227 [aw.update_gui(new_hand_id) for aw in self.hud_dict[table_name].aux_windows]
228 return False
229 finally:
230 gtk.gdk.threads_leave()
231 gobject.idle_add(idle_func)
233 def read_stdin(self): # This is the thread function
234 """Do all the non-gui heavy lifting for the HUD program."""
236 # This db connection is for the read_stdin thread only. It should not
237 # be passed to HUDs for use in the gui thread. HUD objects should not
238 # need their own access to the database, but should open their own
239 # if it is required.
240 self.db_connection = Database.Database(self.config, self.db_name, 'temp')
241 # self.db_connection.init_hud_stat_vars(hud_days)
242 tourny_finder = re.compile('(\d+) (\d+)')
244 while 1: # wait for a new hand number on stdin
245 new_hand_id = sys.stdin.readline()
246 new_hand_id = string.rstrip(new_hand_id)
247 if new_hand_id == "": # blank line means quit
248 self.destroy()
249 break # this thread is not always killed immediately with gtk.main_quit()
250 # get basic info about the new hand from the db
251 # if there is a db error, complain, skip hand, and proceed
252 try:
253 (table_name, max, poker_game, type, site_id, numseats) = self.db_connection.get_table_name(new_hand_id)
254 stat_dict = self.db_connection.get_stats_from_hand(new_hand_id, aggregate_stats[type]
255 ,hud_style, agg_bb_mult)
257 cards = self.db_connection.get_cards(new_hand_id)
258 comm_cards = self.db_connection.get_common_cards(new_hand_id)
259 if comm_cards != {}: # stud!
260 cards['common'] = comm_cards['common']
261 except Exception, err:
262 err = traceback.extract_tb(sys.exc_info()[2])[-1]
263 print _("db error: skipping ")+str(new_hand_id)+" "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1])
264 if new_hand_id: # new_hand_id is none if we had an error prior to the store
265 sys.stderr.write(_("Database error %s in hand %d. Skipping.\n") % (err, int(new_hand_id)))
266 continue
268 if type == "tour": # hand is from a tournament
269 mat_obj = tourny_finder.search(table_name)
270 if mat_obj:
271 (tour_number, tab_number) = mat_obj.group(1, 2)
272 temp_key = tour_number
273 else: # tourney, but can't get number and table
274 print _("could not find tournament: skipping")
275 sys.stderr.write(_("Could not find tournament %d in hand %d. Skipping.\n") % (int(tour_number), int(new_hand_id)))
276 continue
278 else:
279 temp_key = table_name
281 # Update an existing HUD
282 if temp_key in self.hud_dict:
283 self.hud_dict[temp_key].stat_dict = stat_dict
284 self.hud_dict[temp_key].cards = cards
285 [aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[temp_key].aux_windows]
286 self.update_HUD(new_hand_id, temp_key, self.config)
288 # Or create a new HUD
289 else:
290 if type == "tour":
291 tablewindow = Tables.discover_tournament_table(self.config, tour_number, tab_number)
292 else:
293 tablewindow = Tables.discover_table_by_name(self.config, table_name)
294 if tablewindow is None:
295 # If no client window is found on the screen, complain and continue
296 if type == "tour":
297 table_name = "%s %s" % (tour_number, tab_number)
298 sys.stderr.write(_("table name %s not found, skipping.\n")% table_name)
299 else:
300 self.create_HUD(new_hand_id, tablewindow, temp_key, max, poker_game, stat_dict, cards)
301 self.db_connection.connection.rollback()
303 if __name__== "__main__":
305 sys.stderr.write(_("Tournament tracker starting"))
306 sys.stderr.write(_("Using db name = %s") % (options.dbname))
308 # start the HUD_main object
309 hm = ttracker_main(db_name = options.dbname)
311 # start the event loop
312 gtk.main()