# -*- coding: latin-1; -*-
#
# PgWorksheet - PostgreSQL Front End
# http://pgworksheet.projects.postgresql.org/
#
# Copyright © 2004-2008 Henri Michelon & CML http://www.e-cml.org/
#
# 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 (read LICENSE.txt).
#
# 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.
#
# $Id: __init__.py,v 1.10 2008/03/12 20:26:23 hmichelon Exp $
#
import sys
import os
import string


def mswindows():
    """Return TRUE is we run under Microsoft Windows"""
    return sys.platform == "win32"


def get_user_encoding():
    if (mswindows()):
      return "ISO-8859-1" #"UTF-8"
    try:
      enc = os.environ['MM_CHARSET']
      return enc
    except KeyError:
      try:
        enc = os.environ['LANG']
      except KeyError:
        try:
          enc = os.environ['LC_LANG']
        except KeyError:
          try:
            enc = os.environ['LC_ALL']
          except KeyError:
            return "ISO8859-1"
    parts = string.split(enc, '.')
    if (len(parts) > 1) :
      return parts[1]
    return "ISO8859-1"


def set_proportional(buffer):
    """Change the font of a widget to proportional"""
    tagname = 'font-' + str(buffer)
    try:
      font = buffer.create_tag(tagname)
      if (mswindows()):
        font.set_property('font', 'Courier New 10')
      else:
        font.set_property('family', 'monospace')
      buffer.apply_tag(font, buffer.get_start_iter(), buffer.get_end_iter())
    except TypeError: # tag already exists
      buffer.apply_tag_by_name(tagname, buffer.get_start_iter(), buffer.get_end_iter())


def get_user_configdir():
    """Return the directory where the configuration file is stored"""
    if (mswindows()):
      try:
        return os.environ['USERPROFILE']
      except KeyError:
        try:
          return os.environ['ALLUSERSPROFILE']
        except KeyError:
          return os.environ['SYSTEMROOT']
    else:
      return os.environ['HOME']


def get_config_path():
    return os.path.join(get_user_configdir(), '.pgworksheet')
