"""
Font browser
"""
"""
     qtgui/FontBrowser.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     Copyright (C) 2009-2011 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.
"""
from PyQt4 import QtCore, QtGui
import os,sys
from xml.dom import minidom
import FontManager
from global_definitions import FONTMANAGER, get_dispobj
import rebuild
from MGFontSelector import MGFontSelector

def initializePlugin():
  return
  MAINWINDOW().plugin_dialog = FontBrowser(mainwin)

class FontBrowser(QtGui.QWidget):
    _has_no_help_ = True
  
    def changeAllFonts(self,_text,font):
    
      text = str(_text)
      # Sanitize the potentially dodgy HTML generated by MG's Annotation class
      if text.find('<span')>-1 and text.find('<!DOCTYPE HTML PUBLIC') >-1 and (text.find('<span') <  text.find('<!DOCTYPE HTML PUBLIC')):
        text = text[text.find('<!DOCTYPE HTML PUBLIC'):]
      if text.rfind('</span>') > -1 and text.rfind('</html>') >-1 and text.rfind('</span>') > text.rfind('</html>'):
        text = text[:text.rfind('</html>')+len('</html>')]
      
      
      # Parse with minidom
      xmldoc = minidom.parseString(text)
    
      for hit in xmldoc.getElementsByTagName('body'):
        style = str(hit.getAttribute('style'))
        new_style = ''
        old_style = style.split(';')
        # Strip out the old font style
        for s in old_style:
          if s.strip().startswith('font-family:'):
            pass
          elif s.strip().startswith('font-size:'):
            pass
          elif s.strip().startswith('font-weight:'):
            pass
          elif s.strip().startswith('font-style:'):
            pass
          elif s.strip().startswith('text-decoration:'):
            pass
          elif len(s.strip())==0:
            pass
          else:
            new_style += s+';'
    
        # Put in the new font style
        if font.has_key('family') and font['family']:
          new_style += ' font-family:\''+font['family']+'\';'
        if font.has_key('size'):
          new_style += ' font-size:'+str(font['size'])+'pt;'
        if font.has_key('weight') and font['weight'] == 'bold':
          new_style += ' font-weight:600;'
        if font.has_key('slant') and font['slant'] == 'i' or font['slant'] == 'o':
          new_style += ' font-style:italic;'
        if font.has_key('underline') and font['underline'] >0:
          new_style += ' text-decoration: underline;'
        
        hit.setAttribute('style',new_style)

      for hit in xmldoc.getElementsByTagName('span'):
        style = str(hit.getAttribute('style'))
        new_style = ''
        old_style = style.split(';')
        # Strip out the old font style
        for s in old_style:
          if s.strip().startswith('font-family:'):
            pass
          elif s.strip().startswith('font-size:'):
            pass
          elif s.strip().startswith('font-weight:'):
            pass
          elif s.strip().startswith('font-style:'):
            pass
          elif s.strip().startswith('text-decoration:'):
            pass
          elif len(s.strip())==0:
            pass
          else:
            new_style += s+';'
    
        # Put in the new font style
        if font.has_key('family') and font['family']:
          new_style += ' font-family:\''+font['family']+'\';'
        if font.has_key('size'):
          new_style += ' font-size:'+str(font['size'])+'pt;'
        if font.has_key('weight') and font['weight'] == 'bold':
          new_style += ' font-weight:600;'
        if font.has_key('slant') and font['slant'] == 'i' or font['slant'] == 'o':
          new_style += ' font-style:italic;'
        if font.has_key('underline') and font['underline'] >0:
          new_style += ' text-decoration: underline;'
        
        hit.setAttribute('style',new_style)
    
    
      # Return with <xml> tag removed.
      return xmldoc.toxml()[len('<?xml version="1.0" ?>'):]

    def __init__(self,parent=None,params={},width=0):
        QtGui.QWidget.__init__(self,parent)
        self.draw(width=width)
        self.setParams(params)       

    def draw(self,width=0):
        layout = QtGui.QGridLayout(self)
        #layout.setSpacing(0)
        self.setContentsMargins(0,0,0,0)

        line = -1
        for name in FontManager.CONTEXT_LIST:
          label = FontManager.FONT_LABELS[name]
          widget = MGFontSelector(label)
          #widget.layout().deleteLater()
          line = line + 1
          layout.addWidget(widget.label,line,0,1,1)
          layout.addWidget(widget.size_spin,line,1,1,1)
          layout.addWidget(widget.family_combo,line,2,1,1)
          layout.addWidget(widget.bold_check,line,3,1,1)
          layout.addWidget(widget.italic_check,line,4,1,1)
          layout.addWidget(widget.underline_check,line,5,1,1)
          setattr(self,name,widget)

        self.setLayout(layout)

    def setParams(self,params):
      #print "FontBrowser.setParams",params
      for  name in FontManager.CONTEXT_LIST:
        widget = getattr(self,name,None)
        if widget and params.has_key(name):
          widget.setParams(params[name])

    def getParams(self):
      pars = {}
      for name in FontManager.CONTEXT_LIST:
        widget =  getattr(self,name,None)
        if widget:
          pars[name] = widget.getParams()
      #print "FontBrowser pars",pars
      return pars
        
    def help(self):
      return

    def applyAll(self):
      FONTMANAGER().setparams(self.getParams())
      objs = get_dispobj(object_type='Annotation')
      for o in objs:
        o.set_text(self.changeAllFonts(o.text,self.getParams()['annotation']))
      rebuild.UpdateDisplay()

    def apply(self):
      FONTMANAGER().setparams(self.getParams())

    def resetDefaults(self):
      return
    
