# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Thu May 28 10:18:45 2009

import wx
import intl, __builtin__, os, sys, traceback, codecs
from ConfigParser import ConfigParser

# begin wxGlade: dependencies
# end wxGlade

# begin wxGlade: extracode

# end wxGlade

class PreferencesDialog(wx.Dialog):
    def __init__(self, *args, **kwds):
        # Set app language
        intl.setLanguage()

        # begin wxGlade: PreferencesDialog.__init__
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
        wx.Dialog.__init__(self, *args, **kwds)
        self.notebook_2 = wx.Notebook(self, -1, style=0)
        self.notebook_2_pane_6 = wx.Panel(self.notebook_2, -1)
        self.notebook_2_pane_5 = wx.Panel(self.notebook_2, -1)
        self.notebook_2_pane_4 = wx.Panel(self.notebook_2, -1)
        self.notebook_2_pane_3 = wx.Panel(self.notebook_2, -1)
        self.notebook_2_pane_2 = wx.Panel(self.notebook_2, -1)
        self.notebook_2_pane_1 = wx.Panel(self.notebook_2, -1)
        self.sizer_63_staticbox = wx.StaticBox(self.notebook_2_pane_1, -1, _(u"Segurança"))
        self.sizer_64_staticbox = wx.StaticBox(self.notebook_2_pane_1, -1, _(u"Aparência"))
        self.label_27 = wx.StaticText(self.notebook_2_pane_1, -1, _("Linguagem:"))
        self.cbo_app_language = wx.ComboBox(self.notebook_2_pane_1, -1, choices=[_(u"Português (brasileiro)"), _("English")], style=wx.CB_DROPDOWN|wx.CB_READONLY)
        self.label_lang = wx.StaticText(self.notebook_2_pane_1, -1, "")
        self.static_line_1 = wx.StaticLine(self.notebook_2_pane_1, -1)
        self.chk_linebk = wx.CheckBox(self.notebook_2_pane_1, -1, _(u"Realizar quebra de linha na edição"))
        self.chk_bkp_save = wx.CheckBox(self.notebook_2_pane_1, -1, _(u"Salvar cópia anterior (com extensão \"~\")"))
        self.chk_auto_save = wx.CheckBox(self.notebook_2_pane_1, -1, _(u"Gravações automáticas em cópia temporária oculta"))
        self.label_24 = wx.StaticText(self.notebook_2_pane_2, -1, _("Sigla:"))
        self.text_edtype_acr = wx.TextCtrl(self.notebook_2_pane_2, -1, "")
        self.label_25 = wx.StaticText(self.notebook_2_pane_2, -1, _(u"Descrição:"))
        self.text_edtype_name = wx.TextCtrl(self.notebook_2_pane_2, -1, "")
        self.btn_edtype_add = wx.Button(self.notebook_2_pane_2, -1, _("Adicionar >>"))
        self.btn_up = wx.BitmapButton(self.notebook_2_pane_2, -1, wx.Bitmap(__builtin__.application_path + "/res/up.png",wx.BITMAP_TYPE_ANY))
        self.btn_down = wx.BitmapButton(self.notebook_2_pane_2, -1, wx.Bitmap(__builtin__.application_path + "/res/down.png",wx.BITMAP_TYPE_ANY))
        self.btn_remove = wx.BitmapButton(self.notebook_2_pane_2, -1, wx.Bitmap(__builtin__.application_path + "/res/exclude.png",wx.BITMAP_TYPE_ANY))
        self.list_edtype = wx.ListBox(self.notebook_2_pane_2, -1, choices=[_(u"jun|Junção"), _(u"seg|Ressegmentação")])
        self.label_26 = wx.StaticText(self.notebook_2_pane_2, -1, _(u"ATENÇÃO: ordene os elementos da lista por ordem de aplicação"), style=wx.ALIGN_CENTRE)
        self.label_26_copy = wx.StaticText(self.notebook_2_pane_2, -1, _(u"(do primeiro para o último)."))
        self.label_29 = wx.StaticText(self.notebook_2_pane_3, -1, _("Elemento:"))
        self.cbo_element = wx.ComboBox(self.notebook_2_pane_3, -1, choices=["", _(u"Seção"), _(u"Parágrafo"), _(u"Sentença"), _("Palavra")], style=wx.CB_DROPDOWN|wx.CB_READONLY)
        self.label_28 = wx.StaticText(self.notebook_2_pane_3, -1, _("Tipo:"))
        self.text_el_type = wx.TextCtrl(self.notebook_2_pane_3, -1, "")
        self.chk_ignore_to_pos = wx.CheckBox(self.notebook_2_pane_3, -1, _(u"Ignorar para análise morfológica"))
        self.label_35 = wx.StaticText(self.notebook_2_pane_3, -1, _("Estilo CSS (opcional):"))
        self.text_css = wx.TextCtrl(self.notebook_2_pane_3, -1, "")
        self.btn_edtype_add_copy = wx.Button(self.notebook_2_pane_3, -1, _("Adicionar >>"))
        self.btn_el_type_remove = wx.BitmapButton(self.notebook_2_pane_3, -1, wx.Bitmap(__builtin__.application_path + "/res/exclude.png",wx.BITMAP_TYPE_ANY))
        self.list_el_type = wx.ListBox(self.notebook_2_pane_3, -1, choices=[], style=wx.LB_MULTIPLE|wx.LB_SORT)
        self.label_37 = wx.StaticText(self.notebook_2_pane_4, -1, _(u"Nível de edição para o etiquetador:"))
        self.cbo_nivel_ed_tagger = wx.ComboBox(self.notebook_2_pane_4, -1, choices=[], style=wx.CB_DROPDOWN)
        self.label_6 = wx.StaticText(self.notebook_2_pane_4, -1, _(u"Etiquetas válidas (uma por linha):"))
        self.text_tag_list = wx.TextCtrl(self.notebook_2_pane_4, -1, "", style=wx.TE_MULTILINE)
        self.chk_allow_new_tag = wx.CheckBox(self.notebook_2_pane_4, -1, _(u"Permitir a criação de novas etiquetas durante a edição"))
        self.label_mtype = wx.StaticText(self.notebook_2_pane_5, -1, _("Tipo:"))
        self.cbo_mtype = wx.ComboBox(self.notebook_2_pane_5, -1, choices=[], style=wx.CB_DROPDOWN|wx.CB_SORT)
        self.label_mname = wx.StaticText(self.notebook_2_pane_5, -1, _("Nome:"))
        self.text_mname = wx.TextCtrl(self.notebook_2_pane_5, -1, "")
        self.btn_add_meta = wx.Button(self.notebook_2_pane_5, -1, _("Adicionar >>"))
        self.btn_rm_meta = wx.BitmapButton(self.notebook_2_pane_5, -1, wx.Bitmap(__builtin__.application_path + "/res/exclude.png",wx.BITMAP_TYPE_ANY))
        self.list_metadata = wx.ListBox(self.notebook_2_pane_5, -1, choices=[], style=wx.LB_MULTIPLE|wx.LB_SORT)
        self.label_xml = wx.StaticText(self.notebook_2_pane_6, -1, _(u"Lista de contrações, siglas, etc. (expressões regulares):"))
        self.text_xml_list = wx.TextCtrl(self.notebook_2_pane_6, -1, "", style=wx.TE_MULTILINE)
        self.btn_save_pref = wx.Button(self, -1, _("Salvar..."))
        self.btn_load_pref = wx.Button(self, -1, _("Carregar..."))
        self.btn_ok = wx.Button(self, wx.ID_OK, "")
        self.btn_apply = wx.Button(self, wx.ID_APPLY, "")
        self.btn_cancel_copy = wx.Button(self, wx.ID_CANCEL, "")

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_COMBOBOX, self.OnComboLanguageClick, self.cbo_app_language)
        self.Bind(wx.EVT_CHECKBOX, self.OnChkLinebkClick, self.chk_linebk)
        self.Bind(wx.EVT_BUTTON, self.OnEdTypeAddClick, self.btn_edtype_add)
        self.Bind(wx.EVT_BUTTON, self.OnEdTypeUpClick, self.btn_up)
        self.Bind(wx.EVT_BUTTON, self.OnEdTypeDownClick, self.btn_down)
        self.Bind(wx.EVT_BUTTON, self.OnEdTypeRemoveClick, self.btn_remove)
        self.Bind(wx.EVT_LISTBOX, self.OnListEdTypeClick, self.list_edtype)
        self.Bind(wx.EVT_COMBOBOX, self.OnCboElTypeClick, self.cbo_element)
        self.Bind(wx.EVT_BUTTON, self.OnElTypeAddClick, self.btn_edtype_add_copy)
        self.Bind(wx.EVT_BUTTON, self.OnElTypeRemoveClick, self.btn_el_type_remove)
        self.Bind(wx.EVT_LISTBOX, self.OnListElTypeClick, self.list_el_type)
        self.Bind(wx.EVT_COMBOBOX, self.OnCboNivelEdClick, self.cbo_nivel_ed_tagger)
        self.Bind(wx.EVT_TEXT, self.OnMorphoTagText, self.text_tag_list)
        self.Bind(wx.EVT_CHECKBOX, self.OnChkAllowTagClick, self.chk_allow_new_tag)
        self.Bind(wx.EVT_BUTTON, self.OnMetaAddClick, self.btn_add_meta)
        self.Bind(wx.EVT_BUTTON, self.OnMetaRemoveClick, self.btn_rm_meta)
        self.Bind(wx.EVT_LISTBOX, self.OnListMetaClick, self.list_metadata)
        self.Bind(wx.EVT_TEXT, self.OnXMLListText, self.text_xml_list)
        self.Bind(wx.EVT_BUTTON, self.OnOkButtonClick, self.btn_ok)
        self.Bind(wx.EVT_BUTTON, self.OnApplyButtonClick, self.btn_apply)
        self.Bind(wx.EVT_BUTTON, self.OnCancelButtonClick, self.btn_cancel_copy)
        # end wxGlade

        self.Bind(wx.EVT_BUTTON, self.OnLoadButtonClick, self.btn_load_pref)
        self.Bind(wx.EVT_BUTTON, self.OnSaveButtonClick, self.btn_save_pref)
        self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyDown)
        self.chk_allow_new_tag.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxClick)
        self.chk_auto_save.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxClick)
        self.chk_bkp_save.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxClick)
        self.notebook_2.ChangeSelection(0)
        self.cbo_app_language.SetFocus()
        
        self.main_frame = None
        
    def OnKeyDown(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_ESCAPE:
            self.Close(True)
        event.Skip()

    def OnCheckBoxClick(self, event):
        self.btn_apply.Enable(True)

    def __set_properties(self):
        # begin wxGlade: PreferencesDialog.__set_properties
        self.SetTitle(_(u"Preferências"))
        self.SetSize((524, 465))
        self.label_27.SetMinSize((80, 14))
        self.cbo_app_language.SetSelection(0)
        self.chk_bkp_save.SetValue(1)
        self.chk_auto_save.SetValue(1)
        self.text_edtype_acr.SetMinSize((70, 24))
        self.text_edtype_name.SetMinSize((138, 24))
        self.btn_up.Enable(False)
        self.btn_up.SetSize(self.btn_up.GetBestSize())
        self.btn_down.Enable(False)
        self.btn_down.SetSize(self.btn_down.GetBestSize())
        self.btn_remove.Enable(False)
        self.btn_remove.SetSize(self.btn_remove.GetBestSize())
        self.list_edtype.SetMinSize((460, 281))
        self.list_edtype.SetSelection(0)
        self.label_26.SetForegroundColour(wx.Colour(204, 50, 50))
        self.label_26.SetFont(wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, ""))
        self.label_26_copy.SetForegroundColour(wx.Colour(204, 50, 50))
        self.label_26_copy.SetFont(wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, ""))
        self.cbo_element.SetSelection(-1)
        self.label_28.SetMinSize((58, 14))
        self.text_el_type.SetMinSize((120, 24))
        self.text_css.SetMinSize((260, 24))
        self.btn_el_type_remove.Enable(False)
        self.btn_el_type_remove.SetSize(self.btn_el_type_remove.GetBestSize())
        self.list_el_type.SetMinSize((460, 240))
        self.cbo_mtype.SetMinSize((165, 27))
        self.text_mname.SetMinSize((138, 24))
        self.btn_rm_meta.Enable(False)
        self.btn_rm_meta.SetSize(self.btn_rm_meta.GetBestSize())
        self.list_metadata.SetMinSize((460, 310))
        self.notebook_2.SetMinSize((515, 397))
        self.btn_save_pref.SetMinSize((70, 30))
        self.btn_load_pref.SetMinSize((75, 30))
        self.btn_apply.Enable(False)
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: PreferencesDialog.__do_layout
        sizer_21 = wx.BoxSizer(wx.VERTICAL)
        sizer_2_copy_copy_copy_copy = wx.BoxSizer(wx.HORIZONTAL)
        sizer_22_copy = wx.BoxSizer(wx.VERTICAL)
        sizer_23_copy = wx.BoxSizer(wx.VERTICAL)
        sizer_25_copy_1 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_btns_meta = wx.BoxSizer(wx.VERTICAL)
        sizer_24_copy = wx.BoxSizer(wx.HORIZONTAL)
        sizer_22 = wx.BoxSizer(wx.VERTICAL)
        sizer_85 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_66 = wx.BoxSizer(wx.VERTICAL)
        sizer_25_copy = wx.BoxSizer(wx.HORIZONTAL)
        sizer_61_copy = wx.BoxSizer(wx.VERTICAL)
        sizer_79 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_67 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_68 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_23 = wx.BoxSizer(wx.VERTICAL)
        sizer_25 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_61 = wx.BoxSizer(wx.VERTICAL)
        sizer_24 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_62 = wx.BoxSizer(wx.VERTICAL)
        sizer_63 = wx.StaticBoxSizer(self.sizer_63_staticbox, wx.VERTICAL)
        sizer_64 = wx.StaticBoxSizer(self.sizer_64_staticbox, wx.VERTICAL)
        sizer_65 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_65.Add(self.label_27, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_65.Add(self.cbo_app_language, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_65.Add(self.label_lang, 1, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_64.Add(sizer_65, 0, wx.EXPAND, 0)
        sizer_64.Add(self.static_line_1, 0, wx.TOP|wx.BOTTOM|wx.EXPAND, 5)
        sizer_64.Add(self.chk_linebk, 0, 0, 0)
        sizer_62.Add(sizer_64, 1, wx.EXPAND, 0)
        sizer_63.Add(self.chk_bkp_save, 0, 0, 0)
        sizer_63.Add(self.chk_auto_save, 0, 0, 0)
        sizer_62.Add(sizer_63, 1, wx.EXPAND, 0)
        self.notebook_2_pane_1.SetSizer(sizer_62)
        sizer_24.Add(self.label_24, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_24.Add(self.text_edtype_acr, 0, wx.ALIGN_CENTER_VERTICAL, 2)
        sizer_24.Add(self.label_25, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 20)
        sizer_24.Add(self.text_edtype_name, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_24.Add(self.btn_edtype_add, 0, wx.LEFT, 15)
        sizer_23.Add(sizer_24, 0, wx.TOP|wx.BOTTOM|wx.EXPAND, 5)
        sizer_61.Add(self.btn_up, 0, wx.BOTTOM, 10)
        sizer_61.Add(self.btn_down, 0, wx.BOTTOM, 10)
        sizer_61.Add(self.btn_remove, 0, 0, 0)
        sizer_25.Add(sizer_61, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL, 5)
        sizer_25.Add(self.list_edtype, 0, 0, 0)
        sizer_23.Add(sizer_25, 1, wx.EXPAND, 0)
        sizer_23.Add(self.label_26, 0, wx.LEFT|wx.RIGHT|wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 5)
        sizer_23.Add(self.label_26_copy, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL, 5)
        self.notebook_2_pane_2.SetSizer(sizer_23)
        sizer_68.Add(self.label_29, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_68.Add(self.cbo_element, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_66.Add(sizer_68, 0, wx.ALL, 5)
        sizer_67.Add(self.label_28, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_67.Add(self.text_el_type, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_67.Add(self.chk_ignore_to_pos, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 10)
        sizer_66.Add(sizer_67, 0, wx.ALL|wx.EXPAND, 5)
        sizer_79.Add(self.label_35, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_79.Add(self.text_css, 0, 0, 0)
        sizer_79.Add(self.btn_edtype_add_copy, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 15)
        sizer_66.Add(sizer_79, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_61_copy.Add(self.btn_el_type_remove, 0, 0, 0)
        sizer_25_copy.Add(sizer_61_copy, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL, 5)
        sizer_25_copy.Add(self.list_el_type, 0, 0, 0)
        sizer_66.Add(sizer_25_copy, 1, wx.EXPAND, 0)
        self.notebook_2_pane_3.SetSizer(sizer_66)
        sizer_85.Add(self.label_37, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 10)
        sizer_85.Add(self.cbo_nivel_ed_tagger, 0, 0, 0)
        sizer_22.Add(sizer_85, 0, wx.EXPAND, 0)
        sizer_22.Add(self.label_6, 0, wx.ALL, 5)
        sizer_22.Add(self.text_tag_list, 1, wx.ALL|wx.EXPAND, 3)
        sizer_22.Add(self.chk_allow_new_tag, 0, 0, 0)
        self.notebook_2_pane_4.SetSizer(sizer_22)
        sizer_24_copy.Add(self.label_mtype, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_24_copy.Add(self.cbo_mtype, 0, 0, 0)
        sizer_24_copy.Add(self.label_mname, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 10)
        sizer_24_copy.Add(self.text_mname, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_24_copy.Add(self.btn_add_meta, 0, wx.LEFT, 15)
        sizer_23_copy.Add(sizer_24_copy, 0, wx.TOP|wx.BOTTOM|wx.EXPAND, 5)
        sizer_btns_meta.Add(self.btn_rm_meta, 0, 0, 0)
        sizer_25_copy_1.Add(sizer_btns_meta, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL, 5)
        sizer_25_copy_1.Add(self.list_metadata, 0, 0, 0)
        sizer_23_copy.Add(sizer_25_copy_1, 1, wx.EXPAND, 0)
        self.notebook_2_pane_5.SetSizer(sizer_23_copy)
        sizer_22_copy.Add(self.label_xml, 0, wx.ALL, 5)
        sizer_22_copy.Add(self.text_xml_list, 1, wx.ALL|wx.EXPAND, 3)
        self.notebook_2_pane_6.SetSizer(sizer_22_copy)
        self.notebook_2.AddPage(self.notebook_2_pane_1, _("Geral"))
        self.notebook_2.AddPage(self.notebook_2_pane_2, _(u"Edição de Palavras"))
        self.notebook_2.AddPage(self.notebook_2_pane_3, _("Elementos do Texto"))
        self.notebook_2.AddPage(self.notebook_2_pane_4, _("Morfologia"))
        self.notebook_2.AddPage(self.notebook_2_pane_5, _("Metadados"))
        self.notebook_2.AddPage(self.notebook_2_pane_6, _("XML"))
        sizer_21.Add(self.notebook_2, 1, wx.ALL|wx.EXPAND, 5)
        sizer_2_copy_copy_copy_copy.Add(self.btn_save_pref, 0, wx.RIGHT, 5)
        sizer_2_copy_copy_copy_copy.Add(self.btn_load_pref, 0, wx.RIGHT, 10)
        sizer_2_copy_copy_copy_copy.Add(self.btn_ok, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 10)
        sizer_2_copy_copy_copy_copy.Add(self.btn_apply, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 10)
        sizer_2_copy_copy_copy_copy.Add(self.btn_cancel_copy, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 10)
        sizer_21.Add(sizer_2_copy_copy_copy_copy, 0, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_CENTER_HORIZONTAL, 10)
        self.SetSizer(sizer_21)
        self.Layout()
        self.Centre()
        # end wxGlade

    def OnComboLanguageClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        self.label_lang.SetLabel(_(u'Será preciso reiniciar a aplicação.'))

    def OnEdTypeAddClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        ed_acr = self.text_edtype_acr.GetValue().strip().lower()
        ed_name = self.text_edtype_name.GetValue().strip()
        if ed_acr.find(' ') >= 0:
            wx.MessageBox(_(u'A sigla não pode conter espaço em branco.'), 'E-Dictor')
            self.text_edtype_acr.SetFocus()
            return
        if len(ed_acr) > 0 and len(ed_name) > 0:
            ii = -1
            for it in self.list_edtype.GetStrings():
                if it.find(ed_acr+'|') >= 0: 
                    ii = self.list_edtype.GetStrings().index(it)
                    self.list_edtype.Delete(ii)
                    break
            if ii == -1:
                self.list_edtype.Append(ed_acr+'|'+ed_name)
            else:
                self.list_edtype.Insert(ed_acr+'|'+ed_name, ii)
            self.text_edtype_acr.ChangeValue('')
            self.text_edtype_name.ChangeValue('')
            self.btn_apply.Enable(True)
        self.text_edtype_acr.SetFocus()
        # Atualiza combobox do nível de edição para o tagger
        self.refreshCboNivelEdTagger()

    def OnEdTypeUpClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        ii = self.list_edtype.GetStrings().index(self.list_edtype.GetStringSelection())
        if ii > 2:
            it = self.list_edtype.GetStringSelection()
            self.list_edtype.Delete(ii)
            self.list_edtype.Insert(it, ii - 1)
            self.list_edtype.SetStringSelection(it)
            self.list_edtype.Select(ii - 1)
            self.OnListEdTypeClick(None)
            self.btn_apply.Enable(True)
        # Atualiza combobox do nível de edição para o tagger
        self.refreshCboNivelEdTagger()

    def OnEdTypeDownClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        ii = self.list_edtype.GetStrings().index(self.list_edtype.GetStringSelection())
        if ii > 1 and ii < (len(self.list_edtype.GetStrings()) - 1):
            it = self.list_edtype.GetStringSelection()
            self.list_edtype.Delete(ii)
            self.list_edtype.Insert(it, ii + 1)
            self.list_edtype.SetStringSelection(it)
            self.list_edtype.Select(ii + 1)
            self.OnListEdTypeClick(None)
            self.btn_apply.Enable(True)
        # Atualiza combobox do nível de edição para o tagger
        self.refreshCboNivelEdTagger()
    
    def OnEdTypeRemoveClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        ii = self.list_edtype.GetStrings().index(self.list_edtype.GetStringSelection())
        if ii > 1:
            # Checa se está removendo o nível de edição marcado para o tagger
            if self.list_edtype.GetStringSelection().split('|')[1] == self.cbo_nivel_ed_tagger.GetStringSelection():             
                # 'segmentação' é o nível padrão (mínimo)
                self.cbo_nivel_ed_tagger.Delete(self.cbo_nivel_ed_tagger.GetSelection())
                self.cbo_nivel_ed_tagger.Select(0)
            self.list_edtype.Delete(ii)
            self.list_edtype.DeselectAll()
            self.btn_up.Enable(False)
            self.btn_down.Enable(False)
            self.btn_remove.Enable(False)
            self.text_edtype_acr.ChangeValue('')
            self.text_edtype_name.ChangeValue('')
            self.text_edtype_acr.SetFocus()
            self.btn_apply.Enable(True)
        # Atualiza combobox do nível de edição para o tagger
        self.refreshCboNivelEdTagger()

    def refreshCboNivelEdTagger(self):
        # Atualiza combobox do nível de edição para o tagger
        nivel_ed = self.cbo_nivel_ed_tagger.GetStringSelection()
        self.cbo_nivel_ed_tagger.Clear()
        for eds in self.list_edtype.GetItems()[1:]:
            type, desc = eds.split('|')
            self.cbo_nivel_ed_tagger.Append(desc)
        self.cbo_nivel_ed_tagger.SetStringSelection(nivel_ed)
        
    def OnListEdTypeClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        try:
            ii = self.list_edtype.GetStrings().index(self.list_edtype.GetStringSelection())
        except:
            return
        tmp = ii > 1
        if not tmp:
            self.list_edtype.SetSelection(ii, False)
            self.btn_up.Enable(ii > 2)
            self.btn_down.Enable(tmp and ii < (len(self.list_edtype.GetStrings()) - 1))
            self.btn_remove.Enable(tmp)
            self.text_edtype_acr.ChangeValue('')
            self.text_edtype_name.ChangeValue('')
            return
            
#        if tmp:
        (acr, name) = self.list_edtype.GetStringSelection().split('|')
        self.text_edtype_acr.ChangeValue(acr)
        self.text_edtype_name.ChangeValue(name)
        self.text_edtype_acr.SetFocus()
        
        self.btn_up.Enable(ii > 2)
        self.btn_down.Enable(tmp and ii < (len(self.list_edtype.GetStrings()) - 1))
        self.btn_remove.Enable(tmp)
        self.text_edtype_acr.Enable(tmp)
        self.text_edtype_name.Enable(tmp)

    def OnElTypeAddClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        ed_name = self.cbo_element.GetStringSelection()
        ed_type = self.text_el_type.GetValue().strip().lower()
        ed_css  = self.text_css.GetValue().strip()
        if ed_type.find(' ') >= 0:
            wx.MessageBox(_(u'O tipo não pode conter espaço em branco.'), 'E-Dictor')
            self.text_el_type.SetFocus()
            return
        ed_pos = _(u'ignorar')
        if not self.chk_ignore_to_pos.GetValue():
            ed_pos = u' '
        if len(ed_name) > 0 and len(ed_type) > 0:
            ii = -1
            for it in self.list_el_type.GetStrings():
                if it.find(ed_name+'|'+ed_type) >= 0: 
                    ii = self.list_el_type.GetStrings().index(it)
                    self.list_el_type.Delete(ii)
                    break
            if ii == -1:
                self.list_el_type.Append(ed_name+'|'+ed_type+'|'+ed_pos+'|'+ed_css)
            else:
                self.list_el_type.Insert(ed_name+'|'+ed_type+'|'+ed_pos+'|'+ed_css, ii)
            self.text_el_type.Clear()
            self.text_css.Clear()
            self.chk_ignore_to_pos.SetValue(False)
            self.btn_apply.Enable(True)
            self.text_el_type.SetFocus()

    def OnListElTypeClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        tmp = (len(self.list_el_type.GetSelections()) > 0)
        if len(self.list_el_type.GetSelections()) == 1:
            sel = self.list_el_type.GetString(self.list_el_type.GetSelections()[0])
            while sel.count('|') <= 2:
                sel += '|'
            (el, type, pos, css) = sel.split('|')
            self.cbo_element.SetStringSelection(el)
            self.text_el_type.ChangeValue(type)
            self.text_css.ChangeValue(css)
            self.chk_ignore_to_pos.SetValue(not (pos == ' '))
            self.text_el_type.SetFocus()
        self.btn_el_type_remove.Enable(tmp)

    def OnOkButtonClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        self.OnApplyButtonClick(event)
        # Close window
        self.EndModal(wx.ID_OK)

    def OnApplyButtonClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        # Save in configuration file
        self.prefsToConfigFile()
        self.main_frame.SavePreferences()
        
        # Update application UI
        intl.setLanguage()
        self.main_frame.LoadPreferences()
        
        # Disable Apply button        
        self.btn_apply.Enable(False)

    def OnCancelButtonClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        self.EndModal(wx.ID_CANCEL)
        
    def prefsToConfigFile(self):
        __builtin__.cfg.set(u'Preferences', u'Language', self.cbo_app_language.GetValue())
        __builtin__.cfg.set(u'Preferences', u'Line_break', str(self.chk_linebk.GetValue()))
        __builtin__.cfg.set(u'Preferences', u'Backup_copy', str(self.chk_bkp_save.GetValue()))
        __builtin__.cfg.set(u'Preferences', u'Auto_save', str(self.chk_auto_save.GetValue()))
        __builtin__.cfg.set(u'Preferences', u'EditionTypes', ','.join(self.list_edtype.GetItems()))
        __builtin__.cfg.set(u'Preferences', u'ElementTypes', ','.join(self.list_el_type.GetItems()))
        if self.text_tag_list.GetValue().strip() != '':
            tag_list = self.text_tag_list.GetValue().strip().replace(' ','\n').replace('\n','|')
            if tag_list[-1] == '\n': tag_list[-1] = ''
            __builtin__.cfg.set(u'Preferences', u'POS_tag_list', tag_list)
        __builtin__.cfg.set(u'Preferences', u'New_POS_tag_on_demand', str(self.chk_allow_new_tag.GetValue()))
        for eds in self.list_edtype.GetItems():
            type, desc = eds.split('|')
            if desc == self.cbo_nivel_ed_tagger.GetValue():
                __builtin__.cfg.set(u'Preferences', u'POS_ed_level', type)
                break
        __builtin__.cfg.set(u'Preferences', u'Metadata', ','.join(self.list_metadata.GetItems()))
        if self.text_xml_list.GetValue().strip() != '':
            xml_list = self.text_xml_list.GetValue().strip().replace(' ','\n').replace('\n','|')
            if xml_list[-1] == '\n': xml_list[-1] = ''
            __builtin__.cfg.set(u'Preferences', u'XML_list', xml_list)


    def configDialog(self, main_frame, cfg=None):
        '''
        Configure dialog sections based on configuration object passed.
        '''
        self.main_frame = main_frame
        
        if cfg is None:
            cfg = __builtin__.cfg
        
        if not cfg.has_section(u'Preferences'):
            cfg.add_section(u'Preferences')
        
        if not cfg.has_option(u'Preferences', u'Language'):
            cfg.set(u'Preferences', u'Language', u'')

        if not cfg.has_option(u'Preferences', u'Line_break'):
            cfg.set(u'Preferences', u'Line_break', u'False')

        if not cfg.has_option(u'Preferences', u'Backup_copy'):
            cfg.set(u'Preferences', u'Backup_copy', u'True')
            
        if not cfg.has_option(u'Preferences', u'Auto_save'):
            cfg.set(u'Preferences', u'Auto_save', u'True')

        if not cfg.has_option(u'Preferences', u'EditionTypes'):
            cfg.set(u'Preferences', u'EditionTypes', u'')

        if not cfg.has_option(u'Preferences', u'ElementTypes'):
            cfg.set(u'Preferences', u'ElementTypes', u'')

        if not cfg.has_option(u'Preferences', u'POS_tag_list'):
            cfg.set(u'Preferences', u'POS_tag_list', u'')

        if not cfg.has_option(u'Preferences', u'New_POS_tag_on_demand'):
            cfg.set(u'Preferences', u'New_POS_tag_on_demand', u'True')

        if not cfg.has_option(u'Preferences', u'POS_ed_level'):
            cfg.set(u'Preferences', u'POS_ed_level', 'seg')

        if not cfg.has_option(u'Preferences', u'Metadata'):
            cfg.set(u'Preferences', u'Metadata', u'')

        if not cfg.has_option(u'Preferences', u'XML_list'):
            cfg.set(u'Preferences', u'XML_list', u'')

        if cfg.get(u'Preferences', u'Language') != '':
            self.cbo_app_language.SetStringSelection(cfg.get(u'Preferences', u'Language').decode('utf-8'))
        if cfg.get(u'Preferences', u'Line_break') != '':
            self.chk_linebk.SetValue(eval(cfg.get(u'Preferences', u'Line_break').decode('utf-8')))
        if cfg.get(u'Preferences', u'Backup_copy') != '':
            self.chk_bkp_save.SetValue(eval(cfg.get(u'Preferences', u'Backup_copy').decode('utf-8')))
        if cfg.get(u'Preferences', u'Auto_save') != '':
            self.chk_auto_save.SetValue(eval(cfg.get(u'Preferences', u'Auto_save').decode('utf-8')))
        if cfg.get(u'Preferences', u'EditionTypes') != '':
            self.list_edtype.Clear()
            for it in cfg.get(u'Preferences', u'EditionTypes').decode('utf-8').split(','):
                self.list_edtype.Append(_(it))
            # Atualiza combobox do nível de edição para o tagger
            self.refreshCboNivelEdTagger()
                        
        if cfg.get(u'Preferences', u'ElementTypes') != '':
            el_type = cfg.get(u'Preferences', u'ElementTypes').decode('utf-8').split(',')
            for ii in range(len(el_type)):
                while el_type[ii].count('|') <= 2:
                    el_type[ii] += '|'
            self.list_el_type.SetItems(el_type)
            
        if cfg.get(u'Preferences', u'POS_tag_list') != '':
            self.text_tag_list.ChangeValue(cfg.get(u'Preferences', u'POS_tag_list').decode('utf-8').replace('|','\n').upper())
        if cfg.get(u'Preferences', u'New_POS_tag_on_demand') != '':
            self.chk_allow_new_tag.SetValue(eval(cfg.get(u'Preferences', u'New_POS_tag_on_demand').decode('utf-8')))
        if cfg.get(u'Preferences', u'POS_ed_level') != '':
            for eds in self.list_edtype.GetItems():
                type, desc = eds.split('|')
                if type == cfg.get(u'Preferences', u'POS_ed_level').decode('utf-8'):
                    self.cbo_nivel_ed_tagger.SetStringSelection(desc)
        else:
            # 'segmentação' é o nível padrão (mínimo)
            self.cbo_nivel_ed_tagger.Select(0)
                        
        if cfg.get(u'Preferences', u'Metadata') != '':
            self.list_metadata.SetItems(cfg.get(u'Preferences', u'Metadata').decode('utf-8').split(','))
            self.comboMetaTypeUpdate()

        if cfg.get(u'Preferences', u'XML_list') != '':
            self.text_xml_list.ChangeValue(cfg.get(u'Preferences', u'XML_list').decode('utf-8').replace('|','\n'))

        self.prefsToConfigFile()

    def OnMorphoTagText(self, event): # wxGlade: PreferencesDialog.<event_handler>
        '''
        Change text to uppercase and do not permit blank spaces.
        '''
        ii = self.text_tag_list.GetInsertionPoint()
        vl = self.text_tag_list.GetValue()
        if len(self.text_tag_list.GetValue()) > 0:
            if vl[-1] == u' ': vl = self.text_tag_list.GetValue()[0:len(self.text_tag_list.GetValue())-1]
            self.text_tag_list.ChangeValue(vl.upper())
            self.text_tag_list.SetInsertionPoint(ii)
            self.btn_apply.Enable(True)
    
    def OnElTypeRemoveClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        tmp = (len(self.list_el_type.GetSelections()) > 0)
        if tmp:
            while len(self.list_el_type.GetSelections()) > 0:
                self.list_el_type.Delete(self.list_el_type.GetSelections()[0])
            self.list_el_type.DeselectAll()
            self.btn_el_type_remove.Enable(False)
            self.cbo_element.SetStringSelection('')
            self.text_el_type.ChangeValue('')
            self.text_css.ChangeValue('')
            self.chk_ignore_to_pos.SetValue(False)
            self.cbo_element.SetFocus()
            self.btn_apply.Enable(True)
            
    def OnCboElTypeClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        self.text_el_type.Clear()
        self.text_css.Clear()
        self.text_el_type.SetFocus()

    def OnLoadButtonClick(self, event):
        wildcard = _(u"Todos arquivos (*.*)|*.*")
        wildcard = _(u"Arquivos de preferências (*.cfg)|*.cfg;*.CFG") + "|" + wildcard
        dlg = wx.FileDialog(
            self, message=_(u"Abrir arquivo"), defaultDir=os.getcwd(),
            defaultFile="", wildcard=wildcard, style=wx.OPEN | wx.CHANGE_DIR
            )
        if dlg.ShowModal() == wx.ID_OK:
            __builtin__.log(u'Log: [op:LoadPref] [params:CFG, ' + dlg.GetPath() + ']\n')
            # Creates a backup copy of the actual preferences
            cfg_file = codecs.open(self.main_frame.properties_file+'.old','w','utf-8')
            __builtin__.cfg.write(cfg_file)
            # Apply the new one
            cfg_file = dlg.GetPath()
            cfg = ConfigParser()
            cfg.read(cfg_file)
            self.configDialog(self.main_frame, cfg)
            self.btn_apply.Enable(True)
        dlg.Destroy()

    def OnSaveButtonClick(self, event):
        if self.btn_apply.Enabled:
            if not self.main_frame.YesNoMessageDialog(_(u'Para que as modificações sejam salvas é preciso aplicá-las. Continua?'), 'E-Dictor'):
                return
            else:
                self.OnApplyButtonClick(None)
            
        wildcard = _(u"Todos arquivos (*.*)|*.*")
        wildcard = _(u"Arquivos de preferências (*.cfg)|*.cfg;*.CFG|") + wildcard
        ext = '.cfg'
        dir = os.getcwd()
        file_name = '*' + ext
        dlg = wx.FileDialog(
            self, message=_(u"Salvar preferências em arquivo"), defaultDir=dir,
            defaultFile=file_name, wildcard=wildcard, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
            )
        ret = False
        if dlg.ShowModal() == wx.ID_OK:
            try:
                path = dlg.GetPath()
                if not path.lower().endswith(ext):
                    path += ext
                __builtin__.log(u'Log: [op:SavePref] [params:CFG, ' + path + ']\n')
                cfg_file = codecs.open(path.encode('utf-8'),'w','utf-8')
                __builtin__.cfg.set(u'File Settings',u'Recent files', "")
                __builtin__.cfg.write(cfg_file)
                ret = True
            except:
                msg = str(sys.exc_info()[0]) + ':' + str(sys.exc_info()[1]) + '\n' + str(sys.exc_info()[2])
                __builtin__.log(str(sys.exc_info()[0]) + ':' + str(sys.exc_info()[1]) + '\n')
                traceback.print_tb(sys.exc_info()[2], None, open(__builtin__.log_file.name, "a"))
                wx.MessageBox(_(u"Não foi possível salvar o arquivo."),"E-Dictor")
        dlg.Destroy()
        return ret

    def OnMetaAddClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        if self.cbo_mtype.GetSelection() == wx.NOT_FOUND:
            m_type = self.cbo_mtype.GetValue().strip()
            if m_type == "": 
                wx.MessageBox(_(u"É preciso informar o tipo de metadado!"), "E-Dictor")
                self.cbo_mtype.SetFocus()
                return
        else:
            m_type = self.cbo_mtype.GetStringSelection().strip()
        m_name = self.text_mname.GetValue().strip()
        if m_name == "": 
            wx.MessageBox(_(u"É preciso informar o nome do metadado!"), "E-Dictor")
            self.cbo_mtype.SetFocus()
            return

        self.cbo_mtype.SetFocus()
        self.text_mname.Clear()
        self.btn_apply.Enable(True)

        for it in self.list_metadata.GetStrings():
            if it.find(m_type+' | '+m_name) >= 0: 
                return

        self.list_metadata.Append(m_type+" | "+m_name)
        self.comboMetaTypeUpdate()
    
    def comboMetaTypeUpdate(self):
        types = []
        for it in self.list_metadata.GetItems():
            if it[:it.find(' | ')] not in types: types.append(it[:it.find(' | ')])
        self.cbo_mtype.SetItems(types)

    def OnMetaRemoveClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        tmp = (len(self.list_metadata.GetSelections()) > 0)
        if tmp:
            while len(self.list_metadata.GetSelections()) > 0:
                self.list_metadata.Delete(self.list_metadata.GetSelections()[0])
            self.list_metadata.DeselectAll()
            self.btn_rm_meta.Enable(False)
            self.cbo_mtype.SetStringSelection('')
            self.text_mname.ChangeValue('')
            self.cbo_mtype.SetFocus()
            self.btn_apply.Enable(True)
            self.comboMetaTypeUpdate()

    def OnListMetaClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        tmp = (len(self.list_metadata.GetSelections()) > 0)
        if len(self.list_metadata.GetSelections()) == 1:
            (type, name) = self.list_metadata.GetString(self.list_metadata.GetSelections()[0]).split(' | ')
            self.cbo_mtype.SetStringSelection(type)
            self.text_mname.ChangeValue(name)
            self.text_mname.SetFocus()
        self.btn_rm_meta.Enable(tmp)

    def OnChkLinebkClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        self.btn_apply.Enable(True)

    def OnCboNivelEdClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        self.btn_apply.Enable(True)

    def OnChkAllowTagClick(self, event): # wxGlade: PreferencesDialog.<event_handler>
        self.btn_apply.Enable(True)

    def OnXMLListText(self, event): # wxGlade: PreferencesDialog.<event_handler>
        self.btn_apply.Enable(True)

# end of class PreferencesDialog


