"""
     python/ui/FontManager.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     Copyright (C) 2009-2010 University of York

     This library is free software: you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public License
     version 3, modified in accordance with the provisions of the 
     license to address the requirements of UK law.
 
     You should have received a copy of the modified GNU Lesser General 
     Public License along with this library.  If not, copies may be 
     downloaded from http://www.ccp4.ac.uk/ccp4license.php
 
     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 Lesser General Public License for more details.
"""
import sys
import dataobj
from global_definitions import *

CONTEXT_LIST = ['atom_label','annotation',
                'legend','pick_atom_label','applicationFont']

DEFAULT_SIZES = {'atom_label':13, 'pick_atom_label':13,'annotation':18,'legend':32}

FONT_LABELS = { 'atom_label' : "Atom labels",
                'pick_atom_label' : "Picked atoms",
                'annotation' : "Annotation",
                'legend' : 'Legend',
                'applicationFont' : 'Application font',
              }

class FontManager(dataobj.Dependency):

  insts = None

  def __init__(self,params={}):
    dataobj.Dependency.__init__(self)
    FontManager.insts = self
    for item in CONTEXT_LIST:
      if item == 'applicationFont':
        setattr(self,item,self.GetValidFont(useSize=False))
      else:
        if item in DEFAULT_SIZES:
          setattr(self,item,self.GetValidFont(size_in=DEFAULT_SIZES[item]))
        else:
          setattr(self,item,self.GetValidFont())
    self.setparams(params)

  def setparams(self,params):
    for item in CONTEXT_LIST:
      if params.has_key(item) or params.has_key(item+'_font'):
        tmp = getattr(self,item)
        if params.has_key(item):
          tmp.update(params[item])
        if params.has_key(item+'_font'):
          tmp.update(params[item+'_font'])
        #print "fontManager.setparams",item,tmp
        tmp['size'] = int(tmp['size'])
        setattr(self,item,tmp)
        self.update(item)

  def getparams(self):
    pars = {}
    for item in CONTEXT_LIST:
      pars[item] = {}
      tmp = getattr(self,item,{})
      pars[item].update(tmp)
    #print "fontManager.getparams",pars
    return pars

  def getFont(self,mode):
    if hasattr(self,mode):
      return getattr(self,mode)
    else:
      if mode == 'applicationFont':
        return self.GetValidFont(useSize=False)
      else:
        if mode in DEFAULT_SIZES:
          return self.GetValidFont(size_in=DEFAULT_SIZES[mode])
        else:
          return self.GetValidFont()

  def getHtmlFont(self,mode):
    font = self.getFont(mode)
    text =  'style=" font-family:\''+ font['family']+'\'; font-size:'+str(font['size'])+'pt;'
    if font.has_key('weight') and font['weight'] == 'bold':
      text += ' font-weight:600;'
    if font.has_key('slant') and font['slant'] == 'i':
      text += ' font-style:italic;'
    if font.has_key('underline') and font['underline'] >0:
      text += ' text-decoration: underline;'
    text += '"'
    #font-weight:600; font-style:italic; text-decoration: underline;
    return text
  
  def update_data_status(self,params):
    for item in CONTEXT_LIST:
      if params.has_key(item) and params[item] != getattr(self,item):
        tmp = getattr(self,item)
        tmp.update(params[item])
        setattr(self,item,tmp)
        self.update(item)

  def update(self,mode):
    if mode == 'atom_label':
      font = self.atom_label
      for obj in get_dispobj():
        if hasattr(obj,"graphmod") and hasattr(obj.graphmod,"obj") and ['MolDisp','HBonds','Contacts'].count(obj.object_type):
          obj.graphmod.obj.SetTextFont( str(font['family']), str(font['weight']), \
                                     str(font['slant']),font['size'],int(font['underline']))

      MAINWINDOW().updateGLWindows()

    if not sys.argv.count('-quit') and mode == 'applicationFont':
      from PyQt4 import QtGui
      app = QtGui.QApplication.instance()
      style = "QWidget { "
      if self.applicationFont.has_key('size'): style = style + "font-size : " + str(self.applicationFont['size']) + "pt; "
      if self.applicationFont.has_key('family'): style = style + "font-family : " + self.applicationFont['family'] + "; "
      if self.applicationFont.has_key('weight'): style = style + "font-weight : " + self.applicationFont['weight'] + "; "
      if self.applicationFont.has_key('slant') and self.applicationFont['slant'] == "o" or self.applicationFont['slant'] == "i":
        style = style + "font-style : " + 'italic' + "; "
      else:
        style = style + "font-style : " + 'normal' + "; "
      if self.applicationFont.has_key('underline') and self.applicationFont['underline'] != 0:
        style = style + "text-decoration: " + 'underline' + "; "
      else:
        style = style + "text-decoration: " + 'none' + "; "
      style = style + " }"
      app.setStyleSheet(style)

      
#----------------------------------------------------------------------    
  def isValidFont(self,font):
#----------------------------------------------------------------------    
    return 1
      
#----------------------------------------------------------------------    
  def GetValidFont(self,size_in=18,useSize=True):
#----------------------------------------------------------------------
    if not sys.argv.count('-quit'):
      from PyQt4 import QtGui
      app = QtGui.QApplication.instance()
      family = app.font().family()
      if app.font().weight() >50:
        weight = 'bold'
      else:
        weight = 'normal'
      if app.font().pixelSize()>-1:
        size = app.font().pixelSize()
        if size!=size_in and useSize:
          try:
            fn = QtGui.QFont(app.font())
            fn.setPixelSize(size_in)
            s2 = fn.pixelSize()
            if s2 == size_in:
              size = size_in
          except:
            size = app.font().pixelSize()
      elif app.font().pointSize() > -1:
        size = app.font().pointSize()
        if size!=size_in and useSize:
          try:
            fn = QtGui.QFont(app.font())
            fn.setPointSize(size_in)
            s2 = fn.pointSize()
            if s2 == size_in:
              size = size_in
          except:
            size = app.font().pointSize()
      else:
        size = size_in
      if app.font().italic():
        slant = 'i'
      else:
        slant = 'r'
  
      font = { 'family' : family,
             'weight' : weight,
             'slant' : slant,
             'underline' : 0,
             'size' : size
               }
    else:
      font = { 'family' : 'Sans Serif',
             'weight' : 'medium',
             'slant' : 'r',
             'underline' : 0,
             'size' : size_in
               }

    return font
