Merge branch 'master' of git://git.assembla.com/free_poker_tools.git

Conflicts:
	pyfpdb/HUD_main.pyw
This commit is contained in:
Eric Blade 2010-12-05 16:39:13 -05:00
commit 301348eb5e
6 changed files with 162 additions and 138 deletions

234
pyfpdb/HUD_main.pyw Executable file → Normal file
View File

@ -23,16 +23,10 @@
Main for FreePokerTools HUD.
"""
# TODO allow window resizing
# Standard Library modules
import sys
import os
import Options
import traceback
(options, argv) = Options.fpdb_options()
import thread
import time
import string
@ -45,6 +39,9 @@ import gobject
import Configuration
import Database
import Hud
import Options
(options, argv) = Options.fpdb_options()
# get the correct module for the current os
if os.name == 'posix':
@ -76,22 +73,18 @@ class HUD_main(object):
# This class mainly provides state for controlling the multiple HUDs.
def __init__(self, db_name='fpdb'):
print _("\nHUD_main: starting ...")
self.db_name = db_name
self.config = c
print _("Logfile is ") + os.path.join(self.config.dir_log, 'HUD-log.txt')
log.info(_("HUD_main starting: using db name = %s") % (db_name))
log.info("HUD_main starting: using db name = %s" % (db_name))
try:
if not options.errorsToConsole:
fileName = os.path.join(self.config.dir_log, 'HUD-errors.txt')
print _("Note: error output is being diverted to:\n") + fileName \
+ _("\nAny major error will be reported there _only_.\n")
log.info(_("Note: error output is being diverted to:") + fileName)
log.info(_("Any major error will be reported there _only_."))
log.info("Note: error output is being diverted to:" + fileName)
log.info("Any major error will be reported there _only_.")
errorFile = open(fileName, 'w', 0)
sys.stderr = errorFile
sys.stderr.write(_("HUD_main: starting ...\n"))
sys.stderr.write("HUD_main: starting ...\n")
self.hud_dict = {}
self.hud_params = self.config.get_hud_ui_parameters()
@ -120,10 +113,10 @@ class HUD_main(object):
self.main_window.connect("table_changed", self.table_changed)
self.main_window.connect("destroy", self.destroy)
self.vb = gtk.VBox()
self.label = gtk.Label(_('Closing this window will exit from the HUD.'))
self.label = gtk.Label('Closing this window will exit from the HUD.')
self.vb.add(self.label)
self.main_window.add(self.vb)
self.main_window.set_title(_("HUD Main Window"))
self.main_window.set_title("HUD Main Window")
cards = os.path.join(os.getcwd(), '..','gfx','fpdb-cards.png')
if os.path.exists(cards):
self.main_window.set_icon_from_file(cards)
@ -136,99 +129,55 @@ class HUD_main(object):
gobject.timeout_add(100, self.check_tables)
except:
log.error("*** Exception in HUD_main.init() *** ")
for e in traceback.format_tb(sys.exc_info()[2]):
log.error(e)
log.exception("Error initializing main_window")
gtk.main_quit() # we're hosed, just terminate
def client_moved(self, widget, hud):
hud.up_update_table_position()
def client_resized(self, widget, hud):
pass
gobject.idle_add(idle_resize, hud)
def client_destroyed(self, widget, hud): # call back for terminating the main eventloop
self.kill_hud(None, hud.table.key)
def game_changed(self, widget, hud):
print _("hud_main: Game changed.")
print "hud_main: Game changed."
def table_changed(self, widget, hud):
self.kill_hud(None, hud.table.key)
def destroy(self, *args): # call back for terminating the main eventloop
log.info(_("Terminating normally."))
log.info("Terminating normally.")
gtk.main_quit()
def kill_hud(self, event, table):
# called by an event in the HUD, to kill this specific HUD
# This method can be called by either gui or non-gui thread. It doesn't
# cost much to always do it in a thread-safe manner.
def idle():
gtk.gdk.threads_enter()
try:
if table in self.hud_dict:
self.hud_dict[table].kill()
self.hud_dict[table].main_window.destroy()
self.vb.remove(self.hud_dict[table].tablehudlabel)
del(self.hud_dict[table])
self.main_window.resize(1, 1)
except:
pass
finally:
gtk.gdk.threads_leave()
gobject.idle_add(idle)
gobject.idle_add(idle_kill, self, table)
def check_tables(self):
for hud in self.hud_dict.keys():
self.hud_dict[hud].table.check_table(self.hud_dict[hud])
return True
def create_HUD(self, new_hand_id, table, table_name, max, poker_game, type, stat_dict, cards):
def create_HUD(self, new_hand_id, table, temp_key, max, poker_game, type, stat_dict, cards):
"""type is "ring" or "tour" used to set hud_params"""
def idle_func():
gtk.gdk.threads_enter()
try:
table.gdkhandle = gtk.gdk.window_foreign_new(table.number)
newlabel = gtk.Label("%s - %s" % (table.site, table_name))
self.vb.add(newlabel)
newlabel.show()
self.main_window.resize_children()
self.hud_dict[table.key].tablehudlabel = newlabel
self.hud_dict[table.key].create(new_hand_id, self.config, stat_dict, cards)
for m in self.hud_dict[table.key].aux_windows:
m.create()
m.update_gui(new_hand_id)
self.hud_dict[table.key].update(new_hand_id, self.config)
self.hud_dict[table.key].reposition_windows()
except:
log.error("*** Exception in HUD_main::idle_func() *** " + str(sys.exc_info()))
for e in traceback.format_tb(sys.exc_info()[2]):
log.error(e)
finally:
gtk.gdk.threads_leave()
return False
self.hud_dict[table.key] = Hud.Hud(self, table, max, poker_game, self.config, self.db_connection)
self.hud_dict[table.key].table_name = table_name
self.hud_dict[table.key].stat_dict = stat_dict
self.hud_dict[table.key].cards = cards
table.hud = self.hud_dict[table.key]
self.hud_dict[temp_key] = Hud.Hud(self, table, max, poker_game, self.config, self.db_connection)
self.hud_dict[temp_key].table_name = temp_key
self.hud_dict[temp_key].stat_dict = stat_dict
self.hud_dict[temp_key].cards = cards
table.hud = self.hud_dict[temp_key]
# set agg_bb_mult so that aggregate_tour and aggregate_ring can be ignored,
# agg_bb_mult == 1 means no aggregation after these if statements:
if type == "tour" and self.hud_params['aggregate_tour'] == False:
self.hud_dict[table.key].hud_params['agg_bb_mult'] = 1
self.hud_dict[temp_key].hud_params['agg_bb_mult'] = 1
elif type == "ring" and self.hud_params['aggregate_ring'] == False:
self.hud_dict[table.key].hud_params['agg_bb_mult'] = 1
self.hud_dict[temp_key].hud_params['agg_bb_mult'] = 1
if type == "tour" and self.hud_params['h_aggregate_tour'] == False:
self.hud_dict[table.key].hud_params['h_agg_bb_mult'] = 1
self.hud_dict[temp_key].hud_params['h_agg_bb_mult'] = 1
elif type == "ring" and self.hud_params['h_aggregate_ring'] == False:
self.hud_dict[table.key].hud_params['h_agg_bb_mult'] = 1
self.hud_dict[temp_key].hud_params['h_agg_bb_mult'] = 1
# sqlcoder: I forget why these are set to true (aren't they ignored from now on?)
# but I think it's needed:
self.hud_params['aggregate_ring'] = True
@ -237,28 +186,12 @@ class HUD_main(object):
self.hud_params['aggregate_tour'] = True
self.hud_params['h_aggregate_tour'] = True
[aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[table.key].aux_windows]
gobject.idle_add(idle_func)
[aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[temp_key].aux_windows]
gobject.idle_add(idle_create, self, new_hand_id, table, temp_key, max, poker_game, type, stat_dict, cards)
def update_HUD(self, new_hand_id, table_name, config):
"""Update a HUD gui from inside the non-gui read_stdin thread."""
# This is written so that only 1 thread can touch the gui--mainly
# for compatibility with Windows. This method dispatches the
# function idle_func() to be run by the gui thread, at its leisure.
def idle_func():
gtk.gdk.threads_enter()
try:
self.hud_dict[table_name].update(new_hand_id, config)
# The HUD could get destroyed in the above call ^^, which leaves us with a KeyError here vv
# if we ever get an error we need to expect ^^ then we need to handle it vv - Eric
[aw.update_gui(new_hand_id) for aw in self.hud_dict[table_name].aux_windows]
except KeyError:
pass
finally:
gtk.gdk.threads_leave()
return False
gobject.idle_add(idle_func)
gobject.idle_add(idle_update, self, new_hand_id, table_name, config)
def read_stdin(self): # This is the thread function
"""Do all the non-gui heavy lifting for the HUD program."""
@ -275,16 +208,17 @@ class HUD_main(object):
while 1: # wait for a new hand number on stdin
new_hand_id = sys.stdin.readline()
t0 = time.time()
t1 = t2 = t3 = t4 = t5 = t6 = t0
new_hand_id = string.rstrip(new_hand_id)
log.debug(_("Received hand no %s") % new_hand_id)
log.debug("Received hand no %s" % new_hand_id)
if new_hand_id == "": # blank line means quit
self.destroy()
break # this thread is not always killed immediately with gtk.main_quit()
# This block cannot be hoisted outside the while loop, because it would
# cause a problem when auto importing into an empty db.
# FIXME: This doesn't work in the case of the player playing on 2
# sites at once (???) Eratosthenes
if not found:
for site in self.config.get_supported_sites():
result = self.db_connection.get_site_id(site)
@ -299,17 +233,15 @@ class HUD_main(object):
# get basic info about the new hand from the db
# if there is a db error, complain, skip hand, and proceed
log.info(_("HUD_main.read_stdin: hand processing starting ..."))
log.info("HUD_main.read_stdin: hand processing starting ...")
try:
(table_name, max, poker_game, type, site_id, site_name, num_seats, tour_number, tab_number) = \
self.db_connection.get_table_info(new_hand_id)
except Exception:
log.error(_("db error: skipping %s" % new_hand_id))
log.exception("db error: skipping %s" % new_hand_id)
continue
t1 = time.time()
if type == "tour": # hand is from a tournament
# temp_key = tour_number
temp_key = "%s Table %s" % (tour_number, tab_number)
else:
temp_key = table_name
@ -319,26 +251,19 @@ class HUD_main(object):
# get stats using hud's specific params and get cards
self.db_connection.init_hud_stat_vars( self.hud_dict[temp_key].hud_params['hud_days']
, self.hud_dict[temp_key].hud_params['h_hud_days'])
t2 = time.time()
stat_dict = self.db_connection.get_stats_from_hand(new_hand_id, type, self.hud_dict[temp_key].hud_params,
self.hero_ids[site_id], num_seats)
t3 = time.time()
try:
self.hud_dict[temp_key].stat_dict = stat_dict
except KeyError: # HUD instance has been killed off, key is stale
log.error(_('hud_dict[%s] was not found\n') % temp_key)
log.error(_('will not send hand\n'))
log.error('hud_dict[%s] was not found\n' % temp_key)
log.error('will not send hand\n')
# Unlocks table, copied from end of function
self.db_connection.connection.rollback()
return
cards = self.db_connection.get_cards(new_hand_id)
t4 = time.time()
comm_cards = self.db_connection.get_common_cards(new_hand_id)
t5 = time.time()
if comm_cards != {}: # stud!
cards['common'] = comm_cards['common']
self.hud_dict[temp_key].cards = cards
self.hud_dict[temp_key].cards = self.get_cards(new_hand_id)
[aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[temp_key].aux_windows]
self.update_HUD(new_hand_id, temp_key, self.config)
@ -348,18 +273,14 @@ class HUD_main(object):
self.db_connection.init_hud_stat_vars( self.hud_params['hud_days'], self.hud_params['h_hud_days'] )
stat_dict = self.db_connection.get_stats_from_hand(new_hand_id, type, self.hud_params,
self.hero_ids[site_id], num_seats)
cards = self.db_connection.get_cards(new_hand_id)
comm_cards = self.db_connection.get_common_cards(new_hand_id)
if comm_cards != {}: # stud!
cards['common'] = comm_cards['common']
cards = self.get_cards(new_hand_id)
table_kwargs = dict(table_name=table_name, tournament=tour_number, table_number=tab_number)
tablewindow = Tables.Table(self.config, site_name, **table_kwargs)
if tablewindow is None:
# If no client window is found on the screen, complain and continue
if type == "tour":
table_name = "%s %s" % (tour_number, tab_number)
log.error(_("HUD create: table name %s not found, skipping.") % table_name)
log.error("HUD create: table name %s not found, skipping." % table_name)
else:
tablewindow.max = max
tablewindow.site = site_name
@ -374,13 +295,86 @@ class HUD_main(object):
log.info(_("HUD_main.read_stdin: hand read in %4.3f seconds (%4.3f,%4.3f,%4.3f,%4.3f,%4.3f,%4.3f)")
% (t6 - t0,t1 - t0,t2 - t0,t3 - t0,t4 - t0,t5 - t0,t6 - t0))
self.db_connection.connection.rollback()
if type == "tour":
try:
self.hud_dict[temp_key].table.check_table_no(self.hud_dict[temp_key])
except KeyError:
pass
def get_cards(self, new_hand_id):
cards = self.db_connection.get_cards(new_hand_id)
comm_cards = self.db_connection.get_common_cards(new_hand_id)
if comm_cards != {}: # stud!
cards['common'] = comm_cards['common']
return cards
######################################################################
# idle FUNCTIONS
#
# These are passed to the event loop by the non-gui thread to do
# gui things in a thread-safe way. They are passed to the event
# loop using the gobject.idle_add() function.
#
# A general rule for gtk is that only 1 thread should be messing
# with the gui.
def idle_resize(hud):
gtk.gdk.threads_enter()
try:
[aw.update_card_positions() for aw in hud.aux_windows]
hud.resize_windows()
except:
log.exception("Error resizing HUD for table: %s." % hud.table.title)
finally:
gtk.gdk.threads_leave()
def idle_kill(hud_main, table):
gtk.gdk.threads_enter()
try:
if table in hud_main.hud_dict:
hud_main.hud_dict[table].kill()
hud_main.hud_dict[table].main_window.destroy()
hud_main.vb.remove(hud_main.hud_dict[table].tablehudlabel)
del(hud_main.hud_dict[table])
hud_main.main_window.resize(1, 1)
except:
log.exception("Error killing HUD for table: %s." % table.title)
finally:
gtk.gdk.threads_leave()
def idle_create(hud_main, new_hand_id, table, temp_key, max, poker_game, type, stat_dict, cards):
gtk.gdk.threads_enter()
try:
table.gdkhandle = gtk.gdk.window_foreign_new(table.number)
newlabel = gtk.Label("%s - %s" % (table.site, temp_key))
hud_main.vb.add(newlabel)
newlabel.show()
hud_main.main_window.resize_children()
hud_main.hud_dict[temp_key].tablehudlabel = newlabel
hud_main.hud_dict[temp_key].create(new_hand_id, hud_main.config, stat_dict, cards)
for m in hud_main.hud_dict[temp_key].aux_windows:
m.create()
m.update_gui(new_hand_id)
hud_main.hud_dict[temp_key].update(new_hand_id, hud_main.config)
hud_main.hud_dict[temp_key].reposition_windows()
except:
log.exception("Error creating HUD for hand %s." % new_hand_id)
finally:
gtk.gdk.threads_leave()
return False
def idle_update(hud_main, new_hand_id, table_name, config):
gtk.gdk.threads_enter()
try:
hud_main.hud_dict[table_name].update(new_hand_id, config)
[aw.update_gui(new_hand_id) for aw in hud_main.hud_dict[table_name].aux_windows]
except:
log.exception("Error updating HUD for hand %s." % new_hand_id)
finally:
gtk.gdk.threads_leave()
return False
if __name__== "__main__":
# start the HUD_main object

View File

@ -664,7 +664,7 @@ or None if we fail to get the info """
def getTableTitleRe(type, table_name=None, tournament = None, table_number=None):
"Returns string to search in windows titles"
if type=="tour":
return "%s.+Table.+%s" % (tournament, table_number)
return "%s.+Table %s" % (tournament, table_number)
else:
return table_name

View File

@ -536,6 +536,16 @@ class Hud:
aux.destroy()
self.aux_windows = []
def resize_windows(self, *args):
for w in self.stat_windows.itervalues():
if type(w) == int:
continue
rel_x = (w.x - self.table.x) * self.table.width / self.table.oldwidth
rel_y = (w.y - self.table.y) * self.table.height / self.table.oldheight
w.x = self.table.x + rel_x
w.y = self.table.y + rel_y
w.window.move(w.x, w.y)
def reposition_windows(self, *args):
self.update_table_position()
for w in self.stat_windows.itervalues():

View File

@ -241,7 +241,9 @@ class Table_Window(object):
return "client_destroyed"
elif self.width != new_geo['width'] or self.height != new_geo['height']: # window resized
self.oldwidth = self.width
self.width = new_geo['width']
self.oldheight = self.height
self.height = new_geo['height']
return "client_resized"
return False # no change

View File

@ -30,6 +30,7 @@ import sys
import os
# pyGTK modules
import pygtk
import gtk
import gobject
@ -60,7 +61,7 @@ if __name__=="__main__":
self.main_window.set_title(_("Fake HUD Main Window"))
self.main_window.move(table.x + dx, table.y + dy)
self.main_window.show_all()
table.topify(self)
table.topify(self.main_window)
# These are the currently defined signals. Do this in the HUD.
self.main_window.connect("client_moved", self.client_moved)
@ -103,9 +104,12 @@ if __name__=="__main__":
table_kwargs = dict(table_name = table_name)
table = Tables.Table(config, "Full Tilt Poker", **table_kwargs)
table.gdkhandle = gtk.gdk.window_foreign_new(table.number)
print table
fake = fake_hud(table)
fake.parent = fake
gobject.timeout_add(1000, table.check_game, fake)
gobject.timeout_add(100, table.check_table, fake)
print "calling main"

View File

@ -66,27 +66,37 @@ class Table(Table_Window):
if self.number is None:
return None
self.window = self.get_window_from_xid(self.number)
self.parent = self.window.query_tree().parent
(self.window, self.parent) = self.get_window_from_xid(self.number)
def get_window_from_xid(self, id):
for outside in root.query_tree().children:
if outside.id == id:
return outside
return (outside, outside.query_tree().parent)
for inside in outside.query_tree().children:
if inside.id == id:
return inside
return None
if inside.id == id: # GNOME, Xfce
return (inside, inside.query_tree().parent)
for wayinside in inside.query_tree().children:
if wayinside.id == id: # KDE
parent = wayinside.query_tree().parent
return (wayinside, parent.query_tree().parent)
return (None, None)
def get_geometry(self):
try:
my_geo = self.window.get_geometry()
pa_geo = self.parent.get_geometry()
return {'x' : my_geo.x + pa_geo.x,
'y' : my_geo.y + pa_geo.y,
'width' : my_geo.width,
'height' : my_geo.height
}
if self.parent is None:
return {'x' : my_geo.x + pa_geo.x,
'y' : my_geo.y + pa_geo.y,
'width' : my_geo.width,
'height' : my_geo.height
}
else:
pa_geo = self.parent.get_geometry()
return {'x' : my_geo.x + pa_geo.x,
'y' : my_geo.y + pa_geo.y,
'width' : my_geo.width,
'height' : my_geo.height
}
except:
return None
@ -98,7 +108,11 @@ class Table(Table_Window):
except AttributeError:
return None
def topify(self, window):
# The idea here is to call set_transient_for on the HUD window, with the table window
# as the argument. This should keep the HUD window on top of the table window, as if
# the hud window was a dialog belonging to the table.
def topify(self, hud):
hud.main_window.gdkhandle = gtk.gdk.window_foreign_new(hud.main_window.window.xid)
hud.main_window.gdkhandle.set_transient_for(self.gdk_handle)
# This is the gdkhandle for the HUD window
gdkwindow = gtk.gdk.window_foreign_new(window.window.xid)
gdkwindow.set_transient_for(self.gdkhandle)