"""
FtpCube
Copyright (C) Michael Gilfix
This file is part of FtpCube.
You should have received a file COPYING containing license terms
along with this program; if not, write to Michael Gilfix
(mgilfix@eecs.tufts.edu) for a copy.
This version of FtpCube is open source; you can redistribute it and/or
modify it under the terms listed in the file COPYING.
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.
"""
import config
import messages
import mainwin
import threads
import logger
import wx
import sys
import getopt
import os
# The main application instance
app = None
class App(wx.App):
"""Main application instance.
This class initializes the application, loads the application configuration, and display
the main window. The main window acts as the parent window for all sub-windows. The
application instance also holds the thread manager for creating new connection threads.
"""
def OnInit(self):
"""Called by the wx runtime to initialize the application instance."""
self.setDefaultConfigDirectory()
config_file = os.path.join(self.getConfigDirectory(), "config")
try:
configuration = config.Configuration(config_file)
self.setConfiguration(configuration)
except config.ParserError, strerror:
messages.displayErrorDialog(None,
_("Error opening configuration at %(path)s: %(err)s")
%{ 'path' : config_file, 'err' : strerror })
return False
# Create the application thread manager
self.thread_mgr = threads.ThreadManager()
wx.InitAllImageHandlers()
self.SetAppName(_("Ftpcube"))
return True
def createMainWindow(self):
"""Creates and displays the main window."""
self.main_window = mainwin.MainWindow(None, _("Ftpcube"))
self.main_window.Show(True)
self.SetTopWindow(self.main_window)
def getMainWindow(self):
"""Returns the main window object."""
return self.main_window
def getLocalWindow(self):
"""Returns the local window object."""
return self.main_window.getLocalWindow()
def getRemoteWindow(self):
"""Returns the remote window object."""
return self.main_window.getRemoteWindow()
def getControlWindow(self):
"""Returns the control window object."""
return self.main_window.getControlWindow()
def getConsoleWindow(self):
"""Returns the console window object."""
return self.main_window.getConsoleWindow()
def getTransferMethod(self):
"""Returns the transfer method."""
return self.config['transfer_type']
def setConfiguration(self, config):
"""Sets the application configuration object."""
self.config = config
def getConfiguration(self):
"""Returns the application configuration object."""
return self.config
def getThreadManager(self):
"""Returns the application thread manager."""
return self.thread_mgr
def setConfigDirectory(self, dir):
"""Sets the configuration directory."""
self.config_dir = dir
def getConfigDirectory(self):
"""Returns the configuration directory."""
return self.config_dir
def setDefaultConfigDirectory(self):
"""Sets the default configuration directory."""
if os.environ.has_key('HOME'):
self.setConfigDirectory(os.path.join(os.environ['HOME'], ".ftpcube"))
elif os.environ.has_key('HOMEPATH'):
self.setConfigDirectory(os.path.join(os.environ['USERPROFILE'], "Ftpcube Config"))
else:
if sys.platform == 'win32':
self.setConfigDirectory('.')
elif os.name == 'posix':
if os.path.exists('/usr/local/share/ftpcube'):
self.setConfigDirectory('/usr/local/share/ftpcube')
elif os.path.exists('/usr/share/ftpcube'):
self.setConfigDirectory('/usr/share/ftpcube')
else:
self.setConfigDirectory('.')
def initiateConnection(self, opts):
"""Initiates a connection through the main browser thread."""
if opts is None:
return
clogger, dlogger, ulogger = self.getLoggers()
self.thread_mgr.newMainThread(
name=_("MainThread"),
opts=opts,
logger=clogger,
download_logger=dlogger,
upload_logger=ulogger,
)
thread = self.thread_mgr.getMainThread()
try:
thread.initiateConnect()
except threads.ThreadException, strerror:
messages.displayErrorDialog(self, _("Error initiating connection: %(err)s")
%{ 'err' : strerror })
def getLoggers(self):
"""Returns a tuple of loggers: (console logger, download logger, upload logger)."""
clogger, dlogger, ulogger = None, None, None
config = self.getConfiguration()
if config['logging']:
conf_dir = self.getConfigDirectory()
path = os.path.join(conf_dir, config['cmd_log'])
clogger = logger.FileAndConsoleLogger(path)
path = os.path.join(conf_dir, config['download_log'])
dlogger = logger.FileLogger(path)
path = os.path.join(conf_dir, config['upload_log'])
ulogger = logger.FileLogger(path)
else:
clogger = logger.ConsoleLogger()
return (clogger, dlogger, ulogger)
def parseCmdLineOpts():
"""Parses command line options.
Returns a dictionary populated with command-line arguments. If an error occurs
parsing command-line options, then either None will be returned or optionally
an exceptional will be thrown with a reason that should be displayed to the
user."""
opts = { }
try:
opts, args = getopt.getopt(sys.argv[1:], 'hd', [
'help', # print out usage info
'debug', # enables debugging output
])
except getopt.GetOptError:
raise
for o, a in opts:
if o in ('-d', '--debug'):
import __builtin__
__builtin__.__dict__['__debug__'] = True
if o in ('-h', '--help'):
usage()
return None
return opts
def usage():
"""Prints application usage."""
sys.stdout.write(_("""Ftpcube usage:
\t-h, --help Prints this usage help message.
\t-d, --debug Enables debugging output."""))
def main(args):
"""Main program routine.
Creates a global instance of the application and sets it in the main module namespace."""
opts = None
try:
opts = parseCmdLineOpts()
except Exception, strerror:
print _("Error parsing options: %(str)s") %{ 'str' : strerror }
usage()
if opts is None:
sys.exit(4)
global app
try:
app = App()
app.createMainWindow()
app.MainLoop()
except SystemError, strerror:
print _("Fatal error initializing Ftpcube: \n\t%(str)s") %{ 'str' : strerror }
sys.exit(5)
|