#!/usr/bin/python3
# Author: Dimitrios Glentadakis <dglent@free.fr>, 2014
# Purpose: Configure manualy the autohint value for the fonts
# License: GPLv3

import sys
from lxml import etree
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *


class Autohint(QDialog):

    def __init__(self, parent=None):
        super(Autohint, self).__init__(parent)
        home = os.getenv('HOME')
        self.path = home+'/.config/fontconfig/fonts.conf'
        if os.path.exists(home+'/.fonts.conf'):
            notice = QMessageBox.information(self, self.trUtf8("'~/.fonts.conf' file found"),
            self.trUtf8('<a>$XDG_CONFIG_HOME/fontconfig/fonts.conf and ~/.fonts.conf</a><br/>') +
            self.trUtf8('is the conventional location for per-user font configuration,<br/>') +
            self.trUtf8('although the actual location is specified in the global fonts.conf file.<br/>') +
            self.trUtf8('<b>please note that ~/.fonts.conf is deprecated now.</b><br/>') +
            self.trUtf8('it will not be read by default in the future version.<br/>') +
            self.trUtf8('See: <a href="http://freedesktop.org/software/fontconfig/fontconfig-user.html">') +
            'http://freedesktop.org/software/fontconfig/fontconfig-user.html</a>')
        self.data = []
        self.fontsconfPresent = False
        if os.path.exists(self.path):
            readFile = open(self.path, 'r')
            self.data = readFile.readlines()
            readFile.close()
            self.fontsconfPresent = True
        self.memory = set(self.data[:])
        fontsLista=[]
        self.fontDico = self.fonts()
        if len(self.fontDico) >= 1:
            for i in self.fontDico:
                fontsLista.append(i)
        if 'autohint' not in self.fontDico:
            self.autohintPresent = False
        self.listWidget = QListWidget()
        self.listWidget.addItems(fontsLista)
        buttonLayout = QVBoxLayout()
        self.buttonAdd = QPushButton(self.trUtf8('&Add...'))
        self.buttonEdit = QPushButton(self.trUtf8('&Edit...'))
        buttonLayout.addWidget(self.buttonAdd)
        buttonLayout.addWidget(self.buttonEdit)
        buttonLayout.addStretch()
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                     QDialogButtonBox.Cancel)
        buttonLayout.addWidget(buttonBox)
        self.connect(self.buttonAdd, SIGNAL("clicked()"), self.add)
        self.connect(self.buttonEdit, SIGNAL("clicked()"), self.edit)
        self.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(buttonBox, SIGNAL("rejected()"), self.reject)
        self.labelPx = QLabel()
        self.connect(self.listWidget, SIGNAL("itemSelectionChanged()"), self.output)
        self.connect(self.listWidget, SIGNAL("itemDoubleClicked(QListWidgetItem *)"), self.edit)
        self.listWidget.setCurrentRow(0)
        layout = QHBoxLayout()
        vlayout = QVBoxLayout()
        vlayout.addWidget(self.listWidget)
        vlayout.addWidget(self.labelPx)
        self.output()
        layout.addLayout(vlayout)
        layout.addLayout(buttonLayout)
        self.checkAutohint()
        self.setLayout(layout)
        self.setWindowTitle(self.trUtf8("Autohint OnOff"))
        self.setWindowIcon(QIcon("/usr/share/icons/oxygen/22x22/apps/preferences-desktop-font.png"))

    def checkAutohint(self):
        if 'autohint' in self.fontDico:
            self.buttonAdd.setEnabled(False)
            self.buttonEdit.setEnabled(True)
        else:
            self.buttonEdit.setEnabled(False)

    def output(self):
        dico = self.fontDico
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if self.fontsconfPresent:
            fontConf = item.text()
            if fontConf == 'autohint':
                self.buttonEdit.setEnabled(True)
            else:
                self.buttonEdit.setEnabled(False)
            currentSet = dico[fontConf]
            self.labelPx.setText(self.trUtf8('<b>Value:</b> ')+currentSet)

    def add(self):
        if self.fontsconfPresent and not self.autohintPresent:
            reply = QMessageBox.question(self, self.trUtf8("Add autohint fonts setting"),
                    self.trUtf8("Do you want to add Autohint setting in the {} ?").format(self.path),
                                         QMessageBox.Yes|QMessageBox.No)
            if reply == QMessageBox.Yes:
                count = 0
                for i in self.data:
                    if i.count('match') >= 1:
                        break
                    count += 1
                self.data.insert(count, '<match target="font">\n'+
                                 ' <edit mode="assign" name="autohint">\n'+
                                 '  <bool>true</bool>\n'+
                                 ' </edit>\n'+
                                 '</match>\n')
                self.fontDico['autohint'] = 'true'
                self.listWidget.addItem('autohint')
                self.checkAutohint()
                self.labelPx.setText(self.trUtf8('<b>Value:</b> ') + self.fontDico['autohint'])
                self.output()
            else:
                return
        elif not self.fontsconfPresent:
            reply = QMessageBox.question(self, self.trUtf8("Add autohint fonts setting"),
                    self.trUtf8("Do you want to create file and add Autohint setting in the {} ?")
                    .format(self.path), QMessageBox.Yes|QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.data.append(
                    '<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd">\n'+
                    '<fontconfig>\n'+
                    '<match target="font">\n'
                    ' <edit mode="assign" name="autohint">\n'
                    '  <bool>true</bool>\n'+
                    ' </edit>\n'
                    '</match>\n'+
                    '</fontconfig>\n')
                self.fontDico['autohint'] = 'true'
                self.listWidget.addItem('autohint')
                self.checkAutohint()
                self.labelPx.setText(self.trUtf8('<b>Value:</b> ') + self.fontDico['autohint'])
                self.output()
        else:
            return

    def edit(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item.text() != 'autohint':
            self.labelPx.setText(self.trUtf8('Only "autohint" can be modified'))
            return
        value = self.fontDico[item.text()]
        valueBool = (value.capitalize())
        if valueBool == 'True':
            valueBool = True
        elif valueBool == 'False':
            valueBool = False
        autohintCheckBox = QCheckBox(self.trUtf8('&Autohint'))
        autohintCheckBox.setChecked(valueBool)
        okButton = QPushButton(self.trUtf8("&OK"))
        cancelButton = QPushButton(self.trUtf8("&Cancel"))
        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch()
        buttonLayout.addWidget(okButton)
        buttonLayout.addWidget(cancelButton)
        layout = QGridLayout()
        layout.addWidget(autohintCheckBox, 0, 0)
        layout.addLayout(buttonLayout, 3, 3, 1, 3)
        form = QDialog()
        form.setLayout(layout)
        form.setMinimumSize(250,100)
        self.connect(okButton, SIGNAL("clicked()"),
                     form, SLOT("accept()"))
        self.connect(cancelButton, SIGNAL("clicked()"),
                     form, SLOT("reject()"))
        form.setWindowTitle(self.trUtf8("Autohint Property"))
        if form.exec_():
            checked = autohintCheckBox.isChecked()
            tag='true'
            if checked:
                self.fontDico['autohint'] = 'true'
            if not checked:
                self.fontDico['autohint'] = 'false'
                tag = 'false'
            self.labelPx.setText(self.trUtf8('<b>Value:</b> ') + self.fontDico['autohint'])
            flagAutohint = False
            count = 0
            for xmltag in self.data:
                if flagAutohint:
                    if xmltag.count('true') >= 1:
                        self.data[count] = xmltag.replace('true', tag)
                    elif xmltag.count('false') >= 1:
                        self.data[count] = xmltag.replace('false', tag)
                    break
                if xmltag.count('autohint'):
                    flagAutohint = True
                count += 1

    def accept(self):
        if len(self.data) >= 1:
            try:
                outFile = open(self.path, 'w')
            except FileNotFoundError:
                os.system('mkdir -p {}'.format(os.path.dirname(self.path)))
                outFile = open(self.path, 'w')
            finally:
                outFile.writelines(self.data)
                outFile.close()
        QDialog.accept(self)

    def reject(self):
        if self.memory != set(self.data):
            reply = QMessageBox.question(self, self.trUtf8("Confirmation"),
                self.trUtf8("Close the dialogue and discard modifications?"),
                QMessageBox.Yes|QMessageBox.No)
            if reply == QMessageBox.No:
                return
        QDialog.reject(self)

    def fonts(self):
        home = os.getenv('HOME')
        fontsdico = {}
        if self.fontsconfPresent:
            tree = etree.parse(home + '/.config/fontconfig/fonts.conf')
            fontslist = tree.findall('.//edit')
            fontsdico = {}
            for i in fontslist:
                name = i.get('name')
                try:
                    value = i[0].text
                except IndexError:
                    value = self.trUtf8('None')
                fontsdico[name] = value
        return fontsdico

if __name__ == "__main__":
    app = QApplication(sys.argv)
    filePath = os.path.dirname(os.path.realpath(__file__))
    locale = QLocale.system().name()
    appTranslator = QTranslator()
    if appTranslator.load(filePath +
       "/translations/autohint-onoff_" + locale):
        app.installTranslator(appTranslator)
    if appTranslator.load(
       "/../../usr/share/autohint-onoff/translations/autohint-onoff_" + locale):
        app.installTranslator(appTranslator)
    qtTranslator = QTranslator()
    if qtTranslator.load(filePath + "/translations/qt_" + locale):
        app.installTranslator(qtTranslator)
    if qtTranslator.load(
        "/../../usr/share/autohint-onoff/translations/qt_" + locale):
        app.installTranslator(qtTranslator)


    ui = Autohint()
    ui.show()
    sys.exit(app.exec_())
