remove all occurences of assigning sys.argv

This commit is contained in:
Eric Blade 2009-11-22 16:40:56 -05:00
parent 19497dd480
commit 3e7a0ef53c
8 changed files with 222 additions and 229 deletions

View File

@ -26,7 +26,7 @@ except:
diaSQLLibMissing = gtk.Dialog(title="Fatal Error - SQL interface library missing", parent=None, flags=0, buttons=(gtk.STOCK_QUIT,gtk.RESPONSE_OK))
print "Please note that the CLI importer only works with MySQL, if you use PostgreSQL this error is expected."
import fpdb_import
import fpdb_db
@ -36,9 +36,9 @@ if __name__ == "__main__":
parser.add_option("-c", "--handCount", default="0", type="int",
help="Number of hands to import (default 0 means unlimited)")
parser.add_option("-d", "--database", default="fpdb", help="The MySQL database to use (default fpdb)")
parser.add_option("-e", "--errorFile", default="failed.txt",
parser.add_option("-e", "--errorFile", default="failed.txt",
help="File to store failed hands into. (default: failed.txt) Not implemented.")
parser.add_option("-f", "--inputFile", "--file", "--inputfile", default="stdin",
parser.add_option("-f", "--inputFile", "--file", "--inputfile", default="stdin",
help="The file you want to import (remember to use quotes if necessary)")
parser.add_option("-m", "--minPrint", "--status", default="50", type="int",
help="How often to print a one-line status report (0 means never, default is 50)")
@ -51,8 +51,8 @@ if __name__ == "__main__":
parser.add_option("-x", "--failOnError", action="store_true",
help="If this option is passed it quits when it encounters any error")
(options, sys.argv) = parser.parse_args()
(options, argv) = parser.parse_args()
settings={'callFpdbHud':False, 'db-backend':2}
settings['db-host']=options.server
settings['db-user']=options.user

View File

@ -55,19 +55,18 @@ def get_exec_path():
if hasattr(sys, "frozen"): # compiled by py2exe
return os.path.dirname(sys.executable)
else:
print "argv=", sys.argv
pathname = os.path.dirname(sys.argv[0])
return os.path.abspath(pathname)
def get_config(file_name, fallback = True):
"""Looks in cwd and in self.default_config_path for a config file."""
config_path = os.path.join(get_exec_path(), file_name)
print "config_path=", config_path
# print "config_path=", config_path
if os.path.exists(config_path): # there is a file in the cwd
return config_path # so we use it
else: # no file in the cwd, look where it should be in the first place
config_path = os.path.join(get_default_config_path(), file_name)
print "config path 2=", config_path
# print "config path 2=", config_path
if os.path.exists(config_path):
return config_path

View File

@ -1,6 +1,6 @@
"""Database manager
@todo: (gtk) how to validate user input in gtk.Dialog? as soon as the user clicks ok the dialog is dead. we use a while loop as workaround. not nice
@todo: (gtk) how to validate user input in gtk.Dialog? as soon as the user clicks ok the dialog is dead. we use a while loop as workaround. not nice
@todo: (fpdb) we need the application name 'fpdb' from somewhere to put it in dialog titles
@todo: (fpdb) config object should be initialized globally and accessible from all modules via Configuration.py
@ -24,10 +24,10 @@ import gobject
#*******************************************************************************************************
class DatabaseManager(gobject.GObject):
DatabaseTypes = {}
@classmethod
def from_fpdb(klass, data, defaultDatabaseType=None):
#NOTE: if no databases are present in config fpdb fails with
# Traceback (most recent call last):
# File "/home/me2/Scr/Repos/fpdb-mme/pyfpdb/DatabaseManager.py", line 783, in <module>
@ -38,12 +38,12 @@ class DatabaseManager(gobject.GObject):
# db = self.get_db_parameters()
# File "/home/me2/Scr/Repos/fpdb-mme/pyfpdb/Configuration.py", line 583, in get_db_parameters
# name = self.db_selected
# AttributeError: Config instance has no attribute 'db_selected'
# AttributeError: Config instance has no attribute 'db_selected'
import sys
import Options
import Configuration
#NOTE: fpdb should perform this globally
(options, sys.argv) = Options.fpdb_options()
(options, argv) = Options.fpdb_options()
config = Configuration.Config(file=options.config, dbname=options.dbname)
#TODO: handle no database present
defaultDatabaseName = config.get_db_parameters().get('db-databaseName', None)
@ -54,7 +54,7 @@ class DatabaseManager(gobject.GObject):
#NOTE: Config does not seem to validate user input, so anything may end up here
if databaseKlass is None:
raise ValueError('Unknown databasetype: %s' % fpdbDatabase.db_server)
database = databaseKlass()
if database.Type == 'sqlite':
database.name = fpdbDatabase.db_name
@ -66,17 +66,17 @@ class DatabaseManager(gobject.GObject):
database.port = int(fpdbDatabase.db_ip)
database.user = fpdbDatabase.db_user
database.password = fpdbDatabase.db_pass
databases.append(database)
databases.append(database)
return klass(databases=databases, defaultDatabaseType=defaultDatabaseType)
def to_fpdb(self):
pass
def __init__(self, databases=None, defaultDatabaseType=None):
gobject.GObject.__init__(self)
self._defaultDatabaseType = defaultDatabaseType
self._databases = [] if databases is None else list(databases)
self._activeDatabase = None
@ -98,21 +98,21 @@ class DatabaseManager(gobject.GObject):
self._databases.append(database)
def remove_database(self, database):
self._databases.remove(database)
def activate_database(self, database):
if self._activeDatabase is not None:
self._activeDatabase.status = self._activeDatabase.StatusInactive
#TODO: finalize database
self.emit('database-deactivated', self.database_id(self._activeDatabase) )
database.status = database.StatusActive
#TODO: activate database
self._activeDatabase = database
self.emit('database-activated', self.database_id(database) )
def active_database(self):
return self._activeDatabase
# register DatabaseManager signals
gobject.type_register(DatabaseManager)
gobject.signal_new('database-activated', DatabaseManager, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (int, ))
@ -134,20 +134,20 @@ class DatabaseTypeBase(object):
StatusActive = 'active'
StatusInactive = 'inactive'
StatusError = 'error' #TODO: not implemented
#TODO: not happy with returning error string. just being too lazy to impl dozens of error codes for later translation
def init_new_database(self):
"""initializes a new empty database
@return: (str) error if something goes wrong, None otherwise
"""
raise NotImplementedError()
def validate_database(self):
"""checks if the database is valid
@return: (str) error if something goes wrong, None otherwise
"""
raise NotImplementedError()
class DatabaseTypePostgres(DatabaseTypeBase):
Type = 'postgresql'
@classmethod
@ -161,15 +161,15 @@ class DatabaseTypePostgres(DatabaseTypeBase):
self.password = password
self.database = database
self.status = self.StatusInactive
#TODO: implement
def init_new_database(self):
pass
#TODO: implement
def validate_database(self):
pass
class DatabaseTypeMysql(DatabaseTypeBase):
Type = 'mysql'
@classmethod
@ -183,11 +183,11 @@ class DatabaseTypeMysql(DatabaseTypeBase):
self.password = password
self.database = database
self.status = self.StatusInactive
#TODO: implement
def init_new_database(self):
pass
#TODO: implement
def validate_database(self):
pass
@ -202,7 +202,7 @@ class DatabaseTypeSqLite(DatabaseTypeBase):
self.name = name
self.file = file
self.status = self.StatusInactive
def init_new_database(self):
# make shure all attrs are specified
if not self.file:
@ -212,15 +212,15 @@ class DatabaseTypeSqLite(DatabaseTypeBase):
open(self.file, 'w').close()
except IOError:
return 'can not write file'
#TODO: init tables (...)
def validate_database(self):
pass
#TODO: check if tables (...) exist
#TODO: how do we want to handle unsupported database types?
# ..uncomment to remove unsupported database types
@ -235,7 +235,7 @@ class DatabaseTypeSqLite(DatabaseTypeBase):
#TODO: there is no title (on linux), wtf?
def DialogError(parent=None, msg=''):
dlg = gtk.MessageDialog(
parent=parent,
parent=parent,
flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
type=gtk.MESSAGE_ERROR,
buttons=gtk.BUTTONS_OK,
@ -248,33 +248,33 @@ def DialogError(parent=None, msg=''):
#TODO: derrive from gtk.VBox?
class WidgetDatabaseProperties(gtk.VBox):
ModeNew = 0
ModeEdit = 1
ModeAdd = 2
class SqLiteFileChooserButton(gtk.HBox):
#NOTE: for some weird reason it is impossible to let the user choose a non exiting filename with gtk.FileChooserButton, so impl our own on the fly
def __init__(self, widgetDatabaseProperties, parentWidget):
gtk.HBox.__init__(self)
self.set_homogeneous(False)
self.parentWidget = parentWidget
self.widgetDatabaseProperties = widgetDatabaseProperties
self.entry = gtk.Entry()
self.button = gtk.Button('...')
self.button.connect('clicked', self.on_button_clicked)
# layout widgets
self.pack_start(self.entry, True, True)
self.pack_start(self.button, False, False)
def get_filename(self):
return self.entry.get_text()
def set_filename(self, name):
self.entry.set_text(name)
def on_button_clicked(self, button):
if self.widgetDatabaseProperties.mode == WidgetDatabaseProperties.ModeAdd:
action = gtk.FILE_CHOOSER_ACTION_OPEN
@ -283,13 +283,13 @@ class WidgetDatabaseProperties(gtk.VBox):
else:
raise ValueError('unsupported dialog mode')
dlg = gtk.FileChooserDialog(
title='Choose an exiting database file or type in name of a new one',
parent=self.parentWidget,
action=action,
title='Choose an exiting database file or type in name of a new one',
parent=self.parentWidget,
action=action,
buttons=(
gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_OK,
),
),
backend=None
)
dlg.set_default_response(gtk.RESPONSE_OK)
@ -298,8 +298,8 @@ class WidgetDatabaseProperties(gtk.VBox):
fileName = dlg.get_filename()
self.set_filename(fileName)
dlg.destroy()
#TODO: bit ugly this thingy. try to find a better way to map database attrs to gtk widgets
class FieldWidget(object):
def __init__(self, text='', attrDatabase='', widget=None, attrGet=None, attrSet=None, defaultValue=None, canEdit=False, tooltip=''):
@ -310,15 +310,15 @@ class WidgetDatabaseProperties(gtk.VBox):
self._attrDatabase = attrDatabase
self._widget = widget
self._defaultValue = defaultValue
self._attrGetter=None,
self._attrGet = attrGet
self._attrSet = attrSet
self._attrGetter=None,
self._attrGet = attrGet
self._attrSet = attrSet
self._canEdit = canEdit
self._label.set_tooltip_text(tooltip)
self._widget.set_tooltip_text(tooltip)
def widget(self):
def widget(self):
return self._widget
def label(self):
return self._label
@ -335,10 +335,10 @@ class WidgetDatabaseProperties(gtk.VBox):
setattr(database, self._attrDatabase, getattr(self._widget, self._attrGet)() )
def reset_value(self):
getattr(self._widget, self._attrSet)(self._defaultValue)
def __init__(self, databaseManager, database, mode=ModeEdit, parentWidget=None):
gtk.VBox.__init__(self)
self.databaseManager = databaseManager
self.database = database
self.mode = mode
@ -346,76 +346,76 @@ class WidgetDatabaseProperties(gtk.VBox):
self.fieldWidgets = (
self.FieldWidget(
text='Name:',
attrDatabase='name',
attrDatabase='name',
widget=gtk.Entry(),
defaultValue='',
attrGet='get_text',
attrSet='set_text',
attrGet='get_text',
attrSet='set_text',
canEdit=True,
tooltip='Any name you like to name the database '
),
self.FieldWidget(
text='File:',
attrDatabase='file',
widget=self.SqLiteFileChooserButton(self, self.parentWidget),
text='File:',
attrDatabase='file',
widget=self.SqLiteFileChooserButton(self, self.parentWidget),
defaultValue='',
attrGet='get_filename',
attrSet='set_filename',
canEdit=False,
attrGet='get_filename',
attrSet='set_filename',
canEdit=False,
tooltip='Fully qualified path of the file to hold the database '
),
self.FieldWidget(
text='Host:',
attrDatabase='host',
widget=gtk.Entry(),
text='Host:',
attrDatabase='host',
widget=gtk.Entry(),
defaultValue='',
attrGet='get_text',
attrSet='set_text',
canEdit=False,
attrGet='get_text',
attrSet='set_text',
canEdit=False,
tooltip='Host the database is located at'
),
self.FieldWidget(
text='Port:',
attrDatabase='port',
widget=gtk.SpinButton(adjustment=gtk.Adjustment(value=0, lower=0, upper=999999, step_incr=1, page_incr=10) ),
text='Port:',
attrDatabase='port',
widget=gtk.SpinButton(adjustment=gtk.Adjustment(value=0, lower=0, upper=999999, step_incr=1, page_incr=10) ),
defaultValue=0,
attrGet='get_value',
attrSet='set_value',
canEdit=False,
attrGet='get_value',
attrSet='set_value',
canEdit=False,
tooltip='Port to use to connect to the host'
),
self.FieldWidget(
text='User:',
attrDatabase='user',
widget=gtk.Entry(),
text='User:',
attrDatabase='user',
widget=gtk.Entry(),
defaultValue='',
attrGet='get_text',
attrSet='set_text',
canEdit=False,
attrGet='get_text',
attrSet='set_text',
canEdit=False,
tooltip='User name used to login to the host'
),
self.FieldWidget(
text='Pwd:',
attrDatabase='password',
widget=gtk.Entry(),
text='Pwd:',
attrDatabase='password',
widget=gtk.Entry(),
defaultValue='',
attrGet='get_text',
attrSet='set_text',
canEdit=False,
attrGet='get_text',
attrSet='set_text',
canEdit=False,
tooltip='Password used to login to the host'
),
self.FieldWidget(
text='Db:',
attrDatabase='database',
widget=gtk.Entry(),
text='Db:',
attrDatabase='database',
widget=gtk.Entry(),
defaultValue='',
attrGet='get_text',
attrSet='set_text',
attrGet='get_text',
attrSet='set_text',
canEdit=False,
tooltip='Name of the database'
),
)
# setup database type combo
self.comboType = gtk.ComboBox()
listStore= gtk.ListStore(str, str)
@ -424,7 +424,7 @@ class WidgetDatabaseProperties(gtk.VBox):
self.comboType.pack_start(cell, True)
self.comboType.add_attribute(cell, 'text', 0)
self.comboType.connect('changed', self.on_combo_type_changed)
# fill database type combo with available database klasses. we store (databaseDisplayName, databaseType) in our model for later lookup
iCurrentDatabase = 0
databaseTypes = [(klass.display_name(), klass.Type) for klass in databaseManager.DatabaseTypes.values()]
@ -435,7 +435,7 @@ class WidgetDatabaseProperties(gtk.VBox):
iCurrentDatabase = i
if self.mode == self.ModeEdit or len(databaseTypes) < 2:
self.comboType.set_button_sensitivity(gtk.SENSITIVITY_OFF)
# init and layout field widgets
self.pack_start(self.comboType, False, False, 2)
table = gtk.Table(rows=len(self.fieldWidgets) +1, columns=2, homogeneous=False)
@ -443,11 +443,11 @@ class WidgetDatabaseProperties(gtk.VBox):
for i,fieldWidget in enumerate(self.fieldWidgets):
table.attach(fieldWidget.label(), 0, 1, i, i+1, xoptions=gtk.FILL)
table.attach(fieldWidget.widget(), 1, 2, i, i+1)
# init widget
self.comboType.set_active(iCurrentDatabase)
self._adjust_widgets(self.database)
def _adjust_widgets(self, database):
for fieldWidget in self.fieldWidgets:
isSensitive = fieldWidget.is_sensitive(database)
@ -458,24 +458,24 @@ class WidgetDatabaseProperties(gtk.VBox):
if self.mode == self.ModeEdit:
isSensitive = isSensitive and fieldWidget.can_edit()
fieldWidget.set_sensitive(isSensitive)
def on_combo_type_changed(self, combo):
i = self.comboType.get_active()
if i < 0:
return
# check if we need to init a new database
currentDatabaseType = self.comboType.get_model()[i][1]
if currentDatabaseType == self.database.Type:
return
# create new empty database
#NOTE: we dont register it in DatabaseManager
self.database = self.databaseManager.DatabaseTypes[currentDatabaseType]()
self._adjust_widgets(self.database)
def get_database(self):
for fieldWidget in self.fieldWidgets:
if fieldWidget.is_sensitive(self.database):
@ -486,7 +486,7 @@ class WidgetDatabaseProperties(gtk.VBox):
class DialogDatabaseProperties(gtk.Dialog):
def __init__(self, databaseManager, database, parent=None, mode=WidgetDatabaseProperties.ModeEdit, title=''):
gtk.Dialog.__init__(self,
title=title,
title=title,
parent=parent,
flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
buttons=(
@ -495,7 +495,7 @@ class DialogDatabaseProperties(gtk.Dialog):
)
)
self.connect('response', self.on_dialog_response)
# setup widget
self.widgetDatabaseProperties = WidgetDatabaseProperties(databaseManager,database, mode=mode, parentWidget=self)
self.vbox.pack_start(self.widgetDatabaseProperties, True, True)
@ -503,23 +503,23 @@ class DialogDatabaseProperties(gtk.Dialog):
def get_widget_database_properties(self):
return self.widgetDatabaseProperties
def on_dialog_response(self, dlg, responseId):
if responseId == gtk.RESPONSE_REJECT:
pass
elif responseId == gtk.RESPONSE_ACCEPT:
pass
#TODO: derrive from gtk.VBox?
#TODO: derrive from gtk.VBox?
# ..is there a way to derrive from gtk.Widget or similar? this would make parentWidget kw obsolete
class WidgetDatabaseManager(gtk.VBox):
"""
"""
def __init__(self, databaseManager, parentWidget=None):
gtk.VBox.__init__(self)
self.parentWidget = parentWidget
self.databaseManager = databaseManager
self.databaseManager.connect('database-activated', self.on_database_manager_database_activated)
@ -529,17 +529,17 @@ class WidgetDatabaseManager(gtk.VBox):
DatabaseTypeBase.StatusInactive: 'Inactive',
DatabaseTypeBase.StatusError: 'Error',
}
#TODO: dono how to make word wrap work as expected
self.labelInfo = gtk.Label('database management')
self.labelInfo.set_line_wrap(True)
self.labelInfo.set_selectable(True)
self.labelInfo.set_single_line_mode(False)
self.labelInfo.set_alignment(0, 0)
# database management buttons
#TODO: bit messy the distinction New/Add/Edit. we'd have to pass three flags to DialogDatabaseProperties
# to handle this. maybe drop Edit (is just a Remove + Add), to keep things simple
self.buttonDatabaseActivate = gtk.Button("Activate")
@ -560,13 +560,13 @@ class WidgetDatabaseManager(gtk.VBox):
self.buttonDatabaseRemove.set_tooltip_text('removes the database from the list')
self.buttonDatabaseRemove.set_sensitive(False)
self.buttonDatabaseRemove.connect('clicked', self.on_button_database_remove_clicked)
#TODO: i dont think we should do any real database management here. maybe drop it
#self.buttonDatabaseDelete = gtk.Button("Delete")
#self.buttonDatabaseDelete.set_tooltip_text('removes the database from the list and deletes it')
#self.buttonDatabaseDelete.set_sensitive(False)
# init database tree
# init database tree
self.treeDatabases = gtk.TreeView()
treeDatabaseColumns = ( # name, displayName, dataType
('name', 'Name', str),
@ -584,7 +584,7 @@ class WidgetDatabaseManager(gtk.VBox):
col.set_visible(False)
self.treeDatabaseColumns[name] = i
self.treeDatabases.get_selection().connect('changed', self.on_tree_databases_selection_changed)
# layout widgets
vbox = gtk.VBox(self)
vbox.pack_start(self.labelInfo, False, False, 2)
@ -602,12 +602,12 @@ class WidgetDatabaseManager(gtk.VBox):
#vbox.pack_start(self.buttonDatabaseDelete, False, False, 2)
box = gtk.VBox()
vbox.pack_start(box, True, True, 0)
hbox.pack_start(gtk.VSeparator(), False, False, 2)
hbox.pack_end(self.treeDatabases, True, True, 2)
self.show_all()
# init widget
model = self.treeDatabases.get_model()
for database in self.databaseManager:
@ -616,8 +616,8 @@ class WidgetDatabaseManager(gtk.VBox):
model.set_value(it, self.treeDatabaseColumns['status'], self.databaseStatusNames[database.status] )
model.set_value(it, self.treeDatabaseColumns['type'], database.display_name() )
model.set_value(it, self.treeDatabaseColumns['_id'], self.databaseManager.database_id(database))
def on_database_manager_database_activated(self, databaseManager, idDatabase):
database = self.databaseManager.database_from_id(idDatabase)
model = self.treeDatabases.get_model()
@ -627,8 +627,8 @@ class WidgetDatabaseManager(gtk.VBox):
break
else:
raise ValueError('database not found')
def on_database_manager_database_deactivated(self, databaseManager, idDatabase):
database = self.databaseManager.database_from_id(idDatabase)
model = self.treeDatabases.get_model()
@ -638,31 +638,31 @@ class WidgetDatabaseManager(gtk.VBox):
break
else:
raise ValueError('database not found')
def on_button_database_activate_clicked(self, button):
selection = self.treeDatabases.get_selection()
if selection is None:
return
model, it = selection.get_selected()
idDatabase = model.get_value(it, self.treeDatabaseColumns['_id'])
database = self.databaseManager.database_from_id(idDatabase)
self.databaseManager.activate_database(database)
#TODO: for some reason i have to click OK/Cancel twice to close the dialog
#TODO: for some reason i have to click OK/Cancel twice to close the dialog
def on_button_database_new_clicked(self, button):
databaseKlass = self.databaseManager.get_default_database_type()
if databaseKlass is None:
raise ValueError('no default database type set')
database = databaseKlass()
while True:
dlg = DialogDatabaseProperties(
self.databaseManager,
database,
parent=self.parentWidget,
self.databaseManager,
database,
parent=self.parentWidget,
mode=WidgetDatabaseProperties.ModeNew,
title='New database'
)
@ -679,11 +679,11 @@ class WidgetDatabaseManager(gtk.VBox):
database = None
dlg.destroy()
break
if database is None:
return
self.databaseManager.add_database(database)
model = self.treeDatabases.get_model()
it = model.append()
@ -691,19 +691,19 @@ class WidgetDatabaseManager(gtk.VBox):
model.set_value(it, self.treeDatabaseColumns['status'], self.databaseStatusNames[database.status] )
model.set_value(it, self.treeDatabaseColumns['type'], database.display_name() )
model.set_value(it, self.treeDatabaseColumns['_id'], self.databaseManager.database_id(database))
def on_button_database_add_clicked(self, button):
databaseKlass = self.databaseManager.get_default_database_type()
if databaseKlass is None:
raise ValueError('no defult database type set')
database = databaseKlass()
while True:
dlg = DialogDatabaseProperties(
self.databaseManager,
database,
parent=self.parentWidget,
self.databaseManager,
database,
parent=self.parentWidget,
mode=WidgetDatabaseProperties.ModeAdd,
title='Add database'
)
@ -719,11 +719,11 @@ class WidgetDatabaseManager(gtk.VBox):
else:
database = None
dlg.destroy()
break
break
if database is None:
return
self.databaseManager.add_database(database)
model = self.treeDatabases.get_model()
it = model.append()
@ -732,20 +732,20 @@ class WidgetDatabaseManager(gtk.VBox):
model.set_value(it, self.treeDatabaseColumns['type'], database.display_name() )
model.set_value(it, self.treeDatabaseColumns['_id'], self.databaseManager.database_id(database))
dlg.destroy()
def on_button_database_edit_clicked(self, button):
selection = self.treeDatabases.get_selection()
if selection is None:
return
model, it = selection.get_selected()
idDatabase = model.get_value(it, self.treeDatabaseColumns['_id'])
database = self.databaseManager.database_from_id(idDatabase)
dlg = DialogDatabaseProperties(
self.databaseManager,
database,
parent=self.parentWidget,
mode=WidgetDatabaseProperties.ModeEdit,
self.databaseManager,
database,
parent=self.parentWidget,
mode=WidgetDatabaseProperties.ModeEdit,
title='Edit database'
)
response = dlg.run()
@ -759,31 +759,31 @@ class WidgetDatabaseManager(gtk.VBox):
model.set_value(it, self.treeDatabaseColumns['name'], database.name)
dlg.destroy()
def on_button_database_remove_clicked(self, button):
selection = self.treeDatabases.get_selection()
if selection is None:
return
model, it = selection.get_selected()
#TODO: finalize database
model.remove(it)
def on_tree_databases_selection_changed(self, treeSelection):
hasSelection = bool(treeSelection.count_selected_rows())
# enable/disable selection dependend widgets
self.buttonDatabaseActivate.set_sensitive(hasSelection)
self.buttonDatabaseEdit.set_sensitive(hasSelection)
self.buttonDatabaseRemove.set_sensitive(hasSelection)
#self.buttonDatabaseDelete.set_sensitive(hasSelection)
class DialogDatabaseManager(gtk.Dialog):
def __init__(self, databaseManager, parent=None):
gtk.Dialog.__init__(self,
title="Databases",
title="Databases",
parent=parent,
flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
buttons=(
@ -794,11 +794,11 @@ class DialogDatabaseManager(gtk.Dialog):
self.widgetDatabaseManager = WidgetDatabaseManager(databaseManager, parentWidget=self)
self.vbox.pack_start(self.widgetDatabaseManager, True, True)
self.show_all()
#**************************************************************************************************
if __name__ == '__main__':
databaseManager = DatabaseManager.from_fpdb('', defaultDatabaseType=DatabaseTypeSqLite)
#d = DialogDatabaseProperties(
# DatabaseManager(defaultDatabaseType=DatabaseTypeSqLite),
#database=DatabaseTypePostgres(),
@ -808,5 +808,3 @@ if __name__ == '__main__':
d.connect("destroy", gtk.main_quit)
d.run()
#gtk.main()

View File

@ -69,7 +69,7 @@ class Filters(threading.Thread):
self.sbGroups = {}
self.numHands = 0
# Outer Packing box
# Outer Packing box
self.mainVBox = gtk.VBox(False, 0)
playerFrame = gtk.Frame("Hero:")
@ -332,7 +332,7 @@ class Filters(threading.Thread):
elif limit == "fl":
if not self.limits[limit]:
# only toggle all fl limits off if they are all currently on
# this stops turning one off from cascading into 'fl' box off
# this stops turning one off from cascading into 'fl' box off
# and then all fl limits being turned off
all_fl_on = True
for cb in self.cbLimits.values():
@ -359,7 +359,7 @@ class Filters(threading.Thread):
elif limit == "nl":
if not self.limits[limit]:
# only toggle all nl limits off if they are all currently on
# this stops turning one off from cascading into 'nl' box off
# this stops turning one off from cascading into 'nl' box off
# and then all nl limits being turned off
all_nl_on = True
for cb in self.cbLimits.values():
@ -731,11 +731,11 @@ def main(argv=None):
gtk.main_quit()
parser = OptionParser()
(options, sys.argv) = parser.parse_args(args = argv)
(options, argv) = parser.parse_args(args = argv)
config = Configuration.Config()
db = None
db = fpdb_db.fpdb_db()
db.do_connect(config)
@ -750,5 +750,3 @@ def main(argv=None):
if __name__ == '__main__':
sys.exit(main())

View File

@ -53,7 +53,7 @@ class GuiAutoImport (threading.Thread):
self.importer.setFailOnError(False)
self.importer.setHandCount(0)
# self.importer.setWatchTime()
self.server = settings['db-host']
self.user = settings['db-user']
self.password = settings['db-password']
@ -63,7 +63,7 @@ class GuiAutoImport (threading.Thread):
hbox = gtk.HBox(True, 0) # contains 2 equal vboxes
self.mainVBox.pack_start(hbox, False, False, 0)
vbox1 = gtk.VBox(True, 0)
hbox.pack_start(vbox1, True, True, 0)
vbox2 = gtk.VBox(True, 0)
@ -144,13 +144,13 @@ class GuiAutoImport (threading.Thread):
gobject.timeout_add(1000, self.reset_startbutton)
return True
return False
def reset_startbutton(self):
if self.pipe_to_hud is not None:
self.startButton.set_label(u' _Stop Autoimport ')
else:
self.startButton.set_label(u' _Start Autoimport ')
return False
@ -169,7 +169,7 @@ class GuiAutoImport (threading.Thread):
if widget.get_active(): # toggled on
# - Does the lock acquisition need to be more sophisticated for multiple dirs?
# (see comment above about what to do if pipe already open)
# - Ideally we want to release the lock if the auto-import is killed by some
# - Ideally we want to release the lock if the auto-import is killed by some
# kind of exception - is this possible?
if self.settings['global_lock'].acquire(False): # returns false immediately if lock not acquired
print "\nGlobal lock taken ..."
@ -183,7 +183,7 @@ class GuiAutoImport (threading.Thread):
command = os.path.join(sys.path[0], 'HUD_main.py')
command = [command, ] + string.split(self.settings['cl_options'])
bs = 1
try:
self.pipe_to_hud = subprocess.Popen(command, bufsize=bs,
stdin=subprocess.PIPE,
@ -191,17 +191,17 @@ class GuiAutoImport (threading.Thread):
except:
err = traceback.extract_tb(sys.exc_info()[2])[-1]
print "*** GuiAutoImport Error opening pipe: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1])
else:
else:
for site in self.input_settings:
self.importer.addImportDirectory(self.input_settings[site][0], True, site, self.input_settings[site][1])
print " * Add", site, " import directory", str(self.input_settings[site][0])
print "+Import directory - Site: " + site + " dir: " + str(self.input_settings[site][0])
self.do_import()
self.do_import()
interval = int(self.intervalEntry.get_text())
if self.importtimer != 0:
gobject.source_remove(self.importtimer)
self.importtimer = gobject.timeout_add(interval * 1000, self.do_import)
else:
print "auto-import aborted - global lock not available"
else: # toggled off
@ -258,7 +258,7 @@ class GuiAutoImport (threading.Thread):
vbox1.pack_start(pathHBox1, False, True, 0)
pathHBox2 = gtk.HBox(False, 0)
vbox2.pack_start(pathHBox2, False, True, 0)
params = self.config.get_site_parameters(site)
paths = self.config.get_default_paths(site)
self.createSiteLine(pathHBox1, pathHBox2, site, False, paths['hud-defaultPath'], params['converter'], params['enabled'])
@ -281,7 +281,7 @@ if __name__== "__main__":
parser.add_option("-q", "--quiet", action="store_false", dest="gui", default=True, help="don't start gui")
parser.add_option("-m", "--minPrint", "--status", dest="minPrint", default="0", type="int",
help="How often to print a one-line status report (0 (default) means never)")
(options, sys.argv) = parser.parse_args()
(options, argv) = parser.parse_args()
config = Configuration.Config()
# db = fpdb_db.fpdb_db()
@ -305,4 +305,3 @@ if __name__== "__main__":
gtk.main()
else:
pass

View File

@ -43,7 +43,7 @@ class GuiBulkImport():
def dopulse(self):
self.progressbar.pulse()
return True
def load_clicked(self, widget, data=None):
stored = None
dups = None
@ -58,9 +58,9 @@ class GuiBulkImport():
self.progressbar.set_text("Importing...")
self.progressbar.pulse()
while gtk.events_pending(): # see http://faq.pygtk.org/index.py?req=index for more hints (3.7)
gtk.main_iteration(False)
gtk.main_iteration(False)
self.timer = gobject.timeout_add(100, self.dopulse)
# get the dir to import from the chooser
selected = self.chooser.get_filenames()
@ -87,7 +87,7 @@ class GuiBulkImport():
else:
self.importer.setDropHudCache("auto")
sitename = self.cbfilter.get_model()[self.cbfilter.get_active()][0]
for selection in selected:
self.importer.addBulkImportImportFileOrDir(selection, site = sitename)
self.importer.setCallHud(False)
@ -99,7 +99,7 @@ class GuiBulkImport():
# raise Exceptions.FpdbError
# finally:
gobject.source_remove(self.timer)
ttime = time() - starttime
if ttime == 0:
ttime = 1
@ -324,9 +324,9 @@ def main(argv=None):
help="If this option is passed it quits when it encounters any error")
parser.add_option("-m", "--minPrint", "--status", dest="minPrint", default="0", type="int",
help="How often to print a one-line status report (0 (default) means never)")
parser.add_option("-u", "--usage", action="store_true", dest="usage", default=False,
parser.add_option("-u", "--usage", action="store_true", dest="usage", default=False,
help="Print some useful one liners")
(options, sys.argv) = parser.parse_args(args = argv)
(options, argv) = parser.parse_args(args = argv)
if options.usage == True:
#Print usage examples and exit
@ -339,7 +339,7 @@ def main(argv=None):
sys.exit(0)
config = Configuration.Config()
settings = {}
settings['minPrint'] = options.minPrint
if os.name == 'nt': settings['os'] = 'windows'
@ -362,7 +362,7 @@ def main(argv=None):
gtk.main()
else:
#Do something useful
importer = fpdb_import.Importer(False,settings, config)
importer = fpdb_import.Importer(False,settings, config)
# importer.setDropIndexes("auto")
importer.setDropIndexes("don't drop")
importer.setFailOnError(options.failOnError)
@ -377,4 +377,3 @@ def main(argv=None):
if __name__ == '__main__':
sys.exit(main())

View File

@ -39,7 +39,7 @@ def fpdb_options():
return (options, argv)
if __name__== "__main__":
(options, sys.argv) = fpdb_options()
(options, argv) = fpdb_options()
print "errorsToConsole =", options.errorsToConsole
print "database name =", options.dbname
print "config file =", options.config

View File

@ -3,17 +3,17 @@
Based on HUD_main .. who knows if we want to actually use this or not
"""
# Copyright 2008, 2009, Eric Blade
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@ -31,7 +31,7 @@ import os
import Options
import traceback
(options, sys.argv) = Options.fpdb_options()
(options, argv) = Options.fpdb_options()
if not options.errorsToConsole:
print "Note: error output is being diverted to fpdb-error-log.txt and HUD-error.txt. Any major error will be reported there _only_."
@ -55,7 +55,7 @@ import SummaryEverleaf
class Tournament:
"""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"""
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 ..
print "Tournament init"
self.parent = parent
@ -74,7 +74,7 @@ class Tournament:
self.prizepool = 0
self.players = {} # eventually i'd guess we'd probably want to fill this with playername:playerid's
self.results = {} # i'd guess we'd want to load this up with playerid's instead of playernames, too, as well, also
# 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
summary = SummaryEverleaf.EverleafSummary()
self.site = summary.parser.SiteName
@ -87,9 +87,9 @@ class Tournament:
self.rebuys = (summary.parser.TourneyRebuys == "yes")
self.prizepool = summary.parser.TourneyPool
self.numplayers = summary.parser.TourneyPlayers
self.openwindow() # let's start by getting any info we need.. meh
def openwindow(self, widget=None):
if self.window is not None:
self.window.show() # isn't there a better way to bring something to the front? not that GTK focus works right anyway, ever
@ -102,24 +102,24 @@ class Tournament:
self.window.set_border_width(1)
self.window.set_default_size(480,640)
self.window.set_resizable(True)
self.main_vbox = gtk.VBox(False, 1)
self.main_vbox.set_border_width(1)
self.window.add(self.main_vbox)
self.window.show()
def addrebuy(self, widget=None):
t = self
t.numrebuys += 1
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))
def delete_event(self, widget, event, data=None):
return False
def destroy(self, widget, data=None):
return False
#end def destroy
#end def destroy
class ttracker_main(object):
"""A main() object to own both the read_stdin thread and the gui."""
@ -143,11 +143,11 @@ class ttracker_main(object):
self.addbutton = gtk.Button(label="Enter Tournament")
self.addbutton.connect("clicked", self.addClicked, "add tournament")
self.vb.add(self.addbutton)
self.main_window.add(self.vb)
self.main_window.set_title("FPDB Tournament Tracker")
self.main_window.show_all()
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
print "addClicked", widget, data
t = Tournament(self, None, None)
@ -162,7 +162,7 @@ class ttracker_main(object):
rebuybutton = gtk.Button(label="Rebuy")
rebuybutton.connect("clicked", t.addrebuy)
self.vb.add(rebuybutton)
self.vb.add(editbutton) # These should probably be put in.. a.. h-box? i don't know..
self.vb.add(editbutton) # These should probably be put in.. a.. h-box? i don't know..
self.vb.add(mylabel)
self.main_window.resize_children()
self.main_window.show()
@ -172,29 +172,29 @@ class ttracker_main(object):
t.mylabel = mylabel
t.editbutton = editbutton
t.rebuybutton = rebuybutton
self.vb.show()
self.vb.show()
print self.tourney_list
return True
else:
return False
# 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
# at least that was my initial thought on it
def destroy(*args): # call back for terminating the main eventloop
gtk.main_quit()
def create_HUD(self, new_hand_id, table, table_name, max, poker_game, stat_dict, cards):
def idle_func():
gtk.gdk.threads_enter()
try:
newlabel = gtk.Label("%s - %s" % (table.site, table_name))
self.vb.add(newlabel)
newlabel.show()
self.main_window.resize_children()
self.hud_dict[table_name].tablehudlabel = newlabel
self.hud_dict[table_name].create(new_hand_id, self.config, stat_dict, cards)
for m in self.hud_dict[table_name].aux_windows:
@ -212,11 +212,11 @@ class ttracker_main(object):
self.hud_dict[table_name].cards = cards
[aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[table_name].aux_windows]
gobject.idle_add(idle_func)
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
# 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()
@ -227,7 +227,7 @@ class ttracker_main(object):
finally:
gtk.gdk.threads_leave()
gobject.idle_add(idle_func)
def read_stdin(self): # This is the thread function
"""Do all the non-gui heavy lifting for the HUD program."""
@ -238,7 +238,7 @@ class ttracker_main(object):
self.db_connection = Database.Database(self.config, self.db_name, 'temp')
# self.db_connection.init_hud_stat_vars(hud_days)
tourny_finder = re.compile('(\d+) (\d+)')
while 1: # wait for a new hand number on stdin
new_hand_id = sys.stdin.readline()
new_hand_id = string.rstrip(new_hand_id)
@ -272,7 +272,7 @@ class ttracker_main(object):
print "could not find tournament: skipping "
sys.stderr.write("Could not find tournament %d in hand %d. Skipping.\n" % (int(tour_number), int(new_hand_id)))
continue
else:
temp_key = table_name
@ -282,7 +282,7 @@ class ttracker_main(object):
self.hud_dict[temp_key].cards = cards
[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)
# Or create a new HUD
else:
if type == "tour":