"""utils.py, part of GvR http://gvr.sourceforge.net
This module provides functions and classes to be used in GvR

copyright 2004 stasz@linux.isbeter.nl

/*
 *  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 Library 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.
 */

"""
import os,sys,traceback,gettext,locale,__builtin__,shutil
# Basic world description used as a fallback in case of an exception when loading
# a world file from the editor window.
NULL_WORLD = 'Robot 1 1 N 0'
# will hold the locale set by set_locale()

LANG_TRANS = ''
def get_rootdir():
    """Returns the CWD of GvR, on Linux this will be the same as os.getcwd().
     But on win32, it can be anything when run from a standalone exe, crapware!"""
    return os.path.abspath(sys.path[0])

# Base path for the gettext mo files
if os.name == 'nt':
    LOCALEDIR = os.path.join(get_rootdir(),'locale')
else:
    LOCALEDIR = os.path.join('/','usr','local','share','locale')# Base path for the gettext mo files, change this for all the modules
# path for the rc file
if os.name == 'posix':
    RCFILE = os.path.expanduser('~/.gvrrc')
else:
    RCFILE = os.path.join(get_rootdir(),'gvrrc')

def get_locale():
    """Get the systems locale.
    This can be different from the locale used by gvr.(see set_locale())"""
    try:
        lang = locale.getdefaultlocale()[0].split("_")[0]
    except Exception,info:
        print >> sys.stderr,info
        print "Switching to English"
        lang = 'en'
    return lang
    
def set_locale(lang=None):
    """Set the locale to be used by gvr.
    It will first check th rc file and then the systems locale.
    It uses English (en) as the fallback locale.
    It will also set a global constant holding the locale used called LANG_TRANS."""
    global LANG_TRANS
    lang_trans = 'en'
    txt = ""
    try:
        # "system" is/can be used to signal that the sysytem locale should be used
        # from a config file, see also gvrrc 
        if not lang or lang == 'system':
            lang = get_locale()
        if lang == 'en': 
            __builtin__.__dict__['_'] = lambda x:x
            return ("","en")
        lang_trans = gettext.translation('gvr',\
                                     localedir=LOCALEDIR,\
                                     languages=[lang])
        __builtin__.__dict__['_'] = lang_trans.gettext
    except Exception,info:
        txt = "Cannot set language to %s \n switching to English" % lang
        print >> sys.stderr,info,txt
        __builtin__.__dict__['_'] = lambda x:x
        return (txt,"en")
    LANG_TRANS = lang_trans
    return ("",lang)

def trace_error(file=sys.stderr):
    """  Print a stack trace usefull for debugging"""
    print >> file, '*'*60
    info = sys.exc_info()
    traceback.print_exception(info[0],info[1],info[2],file)
    print >> file,' Please send a bug report with this stuff to,\n gvr@linux.isbeter.nl'
    print >> file,'*'*60

def isOsX():
    if os.name == 'posix' and os.uname()[0] == 'Darwin':
        return 1
    return 0

def setUpUnixRC():
    if not os.path.exists(os.path.expanduser('~/.gvrrc')):
        src = os.path.join(get_rootdir(),'gvrrc')
        dest = os.path.join(os.path.expanduser('~/.gvrrc'))
        try:
            shutil.copy(src,dest)
        except Exception,info:
            print >> sys.stderr, info

class Latin2Uni:
    def __init__(self):
        pass
    def latin2unicode(self,string):
        return string.decode("latin1") 

# Start the latin2unicode converter so that modules can do: from utils import L2U
L = Latin2Uni()
L2U =  L.latin2unicode # for usage see gvr.py Application.__init__()
