#!/usr/bin/env python3

"""
Janela principal do o-VPN.
"""

#sudo cp resources/br.gov.serpro.ovpn.gschema.xml /usr/share/glib-2.0/schemas/
#sudo glib-compile-schemas /usr/share/glib-2.0/schemas/

import sys
import os
import re
import subprocess
import fnmatch

from datetime import datetime
from dateutil import relativedelta

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, Gio, Gtk, Gdk, GdkPixbuf, GObject

_icon_size_dialog = 5

gnmkeyring="""
# The file is installed/loaded from the default module p11-kit directory
module: gnome-keyring-pkcs11.so

# And where to store and lookup trust objects
x-trust-store: pkcs11:library-manufacturer=GNOME%20Keyring;serial=1:XDG:DEFAULT
x-trust-lookup: pkcs11:library-manufacturer=GNOME%20Keyring
"""

safenet="""
module: /usr/lib/libeTPkcs11.so
"""

wdata="""
module: /usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so
"""

# Classe principal da aplicacao
class Application(Gtk.Application):

        class Cert(object):
            """ Classe para armazenar os certificados"""
            def __init__(self, requerente=None, emissor=None, notBefore=None, expires=None, thumbPrint=None):
                self.requerente = requerente
                self.emissor = emissor
                self.notBefore = notBefore
                self.expires = expires
                self.thumbPrint = thumbPrint

        class Profile(object):
            #""" Classe para armazenar os perfis"""    
            def __init__(self, nome=None, desc=None, server=None, data=None, caminho=None):
                self.nome = nome
                self.desc = desc
                self.server = server
                self.data = data
                self.caminho = caminho

        def __init__(self, *args, **kwargs):
                super().__init__(*args, application_id="br.gov.serpro.ovpn",
                                                 flags=Gio.ApplicationFlags.FLAGS_NONE,
                                                 **kwargs)

                self.handlers = {
                        "on_ApplicationWindow_delete_event": self._quit,
                        #"on_profiles_listbox_row_activated": self._show_tab_conn,
                        "on_ApplicationWindow_key_press_event": self._check_escape,
                        "on_conn_textbox_size_allocate": self._autoscroll,
                }

                self.handlers_md = {
                    "on_ModulosWindow_delete_event": self._close_modulos,
                    "on_add_mod_clicked": self._add_modulos,
                    "on_del_mod_clicked": self._del_modulos,
                }

                self.handlers_importar = {
                    "on_ImportarWindow_delete_event": self._close_importar,
                    "on_add_pkcs12_clicked": self._add_pkcs12,
                }

                self.appwin = None
                self.modwin = None
                self.importarwin = None
                self.sup = None
                self.sobre = None
                self.pindialog = None
                self.dialogo = None
                self.perf_list = None
                #self.pkcs_text = None

                self.process = None
                self.SCROLLBACK_SIZE = 500
                self._buffer_cert = ""
                self._buffer_prof = ""
                self._buffer_conn = ""
                self._buffer_upd = ""
                self._buffer_mod = ""
                self._buffer_importar = ""

                self.certObj = None
                self.profObj = None
                
                self.listProfObj = []
                self.settings = None
                self.listCertObj = []
                self.listModulos = []
                self.stdin = None
                self.menu_model = None
                
                self.perfil = ""
                self.cert = ""
                self.pin = ""
                self.appcicon = ""
                self.homedir = ""
                self.nome_mod = ""
                self.pkcs_file = ""
                self.version = "2.1.210218"
                
        def do_startup(self):
                Gtk.Application.do_startup(self)

                #Ações do menu da aplicação
                action = Gio.SimpleAction.new("modulos", None)
                action.connect("activate", self.on_modulos)
                self.add_action(action)

                action = Gio.SimpleAction.new("importar", None)
                action.connect("activate", self.on_importar)
                self.add_action(action)

                action = Gio.SimpleAction.new("sobre", None)
                action.connect("activate", self.on_sobre)
                self.add_action(action)

                action = Gio.SimpleAction.new("sair", None)
                action.connect("activate", self._quit)
                self.add_action(action)

                #Carrega definição do Menu
                builder_mn = Gtk.Builder()
                builder_mn.add_from_file("/opt/ovpnserpro/ovpn_menu.ui")
                self.menu_model = builder_mn.get_object("appmenu1")
                
        def do_activate(self):
                global _icon_size_dialog
                
                # Apenas uma instancia da janela sera permitida
                if not self.appwin:
                        
                        self.homedir = os.environ['HOME']
                        _file_path = self.homedir + "/.ovpnserpro"
                        
                        if not os.path.exists(_file_path):
                            os.makedirs(_file_path)

                        self._log_file = open(_file_path + "/o-vpn.log","a")

                        self.appicon = GdkPixbuf.Pixbuf.new_from_file("/usr/share/pixmaps/o-VPN.png")
                        
                        #Carrega definição da janela principal
                        builder = Gtk.Builder()                    
                        builder.add_from_file("/opt/ovpnserpro/ovpn_main.ui")
                        builder.connect_signals(self.handlers)
                       
                        #self.settings = Gio.Settings.new('br.gov.serpro.ovpn')
                        self.appwin = builder.get_object("ApplicationWindow")

                        hamburger_menu = builder.get_object("gear_button")
                        hamburger_menu.set_menu_model(self.menu_model)
                                                
                        self.views_stack = builder.get_object("views_stack")
                        
                        self.certs_frame = builder.get_object("certs_frame")
                        #self.perf_list = builder.get_object("profiles_listbox")
                        self.perfs_frame = builder.get_object("perfs_frame")
                        
                        self.txt_conn = builder.get_object("conn_textbox")
                        self.conn_label = builder.get_object("conn_label")
                        self.button_box = builder.get_object("button_box")
                        self.scroll_textbox = builder.get_object("scroll_textbox")
                        self.icon_cert = Gio.ThemedIcon.new_with_default_fallbacks ("application-certificate")
                        self.icon_perf = Gio.ThemedIcon.new_with_default_fallbacks ("emblem-system")
                        
                
                        # Criação do botão para a HeaderBar 
                        # Fazendo no xml (ovpn_main.ui) não tinha como deixar escondido na tela de certificados
                        self.back_button = Gtk.Button.new()
                        self.back_button.connect_after("clicked", self._show_previous_stack)
                        self.back_button.set_can_focus(False)
                        self.go_back_icon = Gio.ThemedIcon.new_with_default_fallbacks ("go-previous-symbolic")
                        self.go_back_image = Gtk.Image.new_from_gicon (self.go_back_icon, 4)
                        self.back_button.set_image (self.go_back_image)

                        self.cancelCert = Gio.Cancellable()
                        self.cancelUpdate = Gio.Cancellable()
                        self.cancelProfile = Gio.Cancellable()
                                          
                        # Criação dos listbox dinamicamente por causa 
                        # da inclusão do spinner no frame central
                        self.certs_list = Gtk.ListBox.new()
                        self.certs_list.set_selection_mode(1)
                        self.certs_list.connect('row-activated', self._show_tab_profiles, self.certs_list.get_selected_row())
                        self.certs_list.set_activate_on_single_click(True)

                        style_provider = Gtk.CssProvider()
                        style_provider.load_from_file(Gio.File.new_for_path("/opt/ovpnserpro/resources/ovpn.css"))

                        Gtk.StyleContext.add_provider_for_screen(
                            Gdk.Screen.get_default(), 
                            style_provider,     
                            Gtk.STYLE_PROVIDER_PRIORITY_USER
                        )

                        # Habilitar animação para o spinner funcionar - Ubuntu 18-04
                        GObject.GObject.set_property(Gtk.Settings.get_default(), "gtk-enable-animations", True )

                        self.spinner = Gtk.Spinner.new()
                        self.certs_frame.add(self.spinner)
                        self.spinner.start()

                        #Buscar módulos instalados no sistema
                        self.run_cmd_list_sync(["/usr/bin/p11-kit", "list-modules"])

                        #Carregar lista de certificados
                        self.run_cmd_async(["/opt/ovpnserpro/ovpnctl", "certificates"], self.cancelCert, self._certs_read, self._certs_finished)

                        #Update profiles
                        self.run_cmd_async(["/opt/ovpnserpro/ovpnctl", "update"], self.cancelUpdate, self._update_read, self._update_finished)
                            
                        self.add_window(self.appwin)
                        self.appwin.show_all()
                        #self.appwin.set_focus(self.certs_frame)
                        Gtk.main()

        def on_modulos(self, *args):

            self.run_cmd_list_sync(["/usr/bin/p11-kit", "list-modules"])

            if not self.modwin:
                
                self.builder_md = Gtk.Builder()                    
                self.builder_md.add_from_file("/opt/ovpnserpro/ovpn_modulos.ui")
                self.modwin = self.builder_md.get_object("ModulosWindow")
                self.mod_list = self.builder_md.get_object("modules_listbox")
                self.builder_md.connect_signals(self.handlers_md)

                self.modwin.set_modal(True)
                self.modwin.set_transient_for(self.appwin)
                
                for _modulo in self.listModulos:

                    self.list_row_mod = Gtk.ListBoxRow.new ()
                    self.row_grid_mod = Gtk.Grid.new ()
                    self.row_grid_mod.set_margin_bottom (10)
                    self.row_grid_mod.set_orientation (Gtk.Orientation.HORIZONTAL)
                    self.row_grid_mod.set_column_spacing (6)
                    self.row_grid_mod.set_hexpand (1)
                    self.list_row_mod.add (self.row_grid_mod)

                    # self.listModulos
                    _info_mod = "<span size='medium'>" + _modulo[1] + "</span>\n<span size='small'>" + _modulo[0] + "</span>"
                    
                    self.label_info_mod = Gtk.Label.new ()
                    self.label_info_mod.set_markup(_info_mod)
                    self.row_grid_mod.add (self.label_info_mod)

                    self.mod_list.add (self.list_row_mod)

                self.modwin.show_all()
                
        def on_importar(self, *args):
                
            chooser = Gtk.FileChooserDialog(title="Importa chave privada e certificado X.509 de arquivo PKCS#12", action=Gtk.FileChooserAction.OPEN)
            chooser.add_buttons(Gtk.STOCK_OPEN, Gtk.ResponseType.OK,  Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)                                                        
            chooser.set_default_response(Gtk.ResponseType.OK)
            filter = Gtk.FileFilter()
            filter.set_name("Arquivos p12/pfx")
            filter.add_pattern("*.p12")
            filter.add_pattern("*.pfx")
            chooser.add_filter(filter)
            filter = Gtk.FileFilter()
            filter.set_name("Todos os arquivos")
            filter.add_pattern("*")
            chooser.add_filter(filter)
            self.pkcs_file = ""
            
            if chooser.run() == Gtk.ResponseType.OK:
                self.pkcs_file = chooser.get_filename()
                _nome_arq = chooser.get_file().get_basename()
                chooser.destroy()
                
                if self.pkcs_file != None:
                    if os.path.exists(self.pkcs_file):
                        self._add_pkcs12(_nome_arq)
            else:
                chooser.destroy()             
            
            
             	    
        def on_sobre(self, *args):
            if not self.sobre:
                self.sobre = Gtk.AboutDialog.new()
                self.sobre.set_program_name("OVPN Serpro")
                self.sobre.set_version(self.version)
                self.sobre.set_logo(self.appicon)
                self.sobre.set_comments("Acesse a rede Serpro e de clientes.")
                self.sobre.set_website("http://ovpnus.serpro.gov.br/redirect/acesso_remoto.html")
                self.sobre.set_website_label("Página Web")

                self.sobre.set_authors(["Serviço Federal de Processamento de Dados (SERPRO)","\nDiretor-Presidente:","Gileno Gurjao Barreto\n","Diretor de Operações:","Antonino dos Santos Guerra Neto\n","Superintendente de Segurança da Informação:","João Vieira de Almeida Júnior\n","Gerente de Departamento:","Tiago Sell Iahn\n","Chefe de Divisão:","Carlos Eduardo Rodrigues de Alencar\n","Desenvolvedores:","Gerson Sampaio Martins","Jorge Luiz Silva Peixoto"])

                self.sobre.set_transient_for(self.appwin)
                self.sobre.set_modal(True)
                res = self.sobre.run()
                if res == Gtk.ResponseType.DELETE_EVENT:
                    self.sobre.destroy()
                    self.sobre = None

        def _close_modulos(self, *args):
            self.modwin.hide()
            self.listModulos = []
            self.modwin = None
            
            return False

        def _close_importar(self, *args):
            self.importarwin.hide()
            self.importarwin = None
            
            return False

        def modulos_dialog(self):
            dialog = Gtk.Dialog(title='Adicionar Módulo',
                                transient_for=self.modwin,
                                modal=True, use_header_bar=1,
                                destroy_with_parent=True,resizable=False)
    
            dialog.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK,  Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
            content_area = dialog.get_content_area()
            hbox = Gtk.HBox(orientation=0,spacing=8)
            hbox.set_border_width(8)

            content_area.pack_start(hbox, False, False, 0)

            table = Gtk.Grid.new()
            table.set_size_request(content_area.get_parent().get_preferred_width()[0], -1)
            table.set_column_homogeneous(False)
            table.set_column_spacing(6)


            hbox.pack_start(table, False, False, 0)
            
            label = Gtk.Label.new_with_mnemonic("Caminho")
            label.set_justify(Gtk.Justification.RIGHT)
            label.set_margin_start(4)
            
            table.attach(label, 0, 0, 1, 1)
            
            name_mod = Gtk.Entry()
            name_mod.set_hexpand(True)
            
            # Ativar o botão OK ao editar
            btOk = dialog.get_widget_for_response(Gtk.ResponseType.OK)
            context = btOk.get_style_context()
            btOk.set_sensitive(False)

            name_mod.connect("changed", self.ativa_button_dialog, dialog, context, btOk)
            name_mod.set_activates_default(True)
            
            table.attach(name_mod, 1, 0, 2, 1)

            hbox.show_all()

            response = dialog.run()
    
            if response == Gtk.ResponseType.OK:
                self.nome_mod = name_mod.get_text()
            else:
                self.nome_mod = ""
    
            dialog.destroy()



        def _add_modulos(self, *args):
             
            dialogmod = self.modulos_dialog()
            
            if self.nome_mod != "":
                if os.path.exists(self.nome_mod):                
                    _directory = self.homedir + "/.config/pkcs11/modules"
                    if not os.path.exists(_directory):
                        os.makedirs(_directory)
                                    
                    _nr_arq = str(len(os.listdir(_directory)) + 1)
                    _nm_arq = _directory + "/mod_" + _nr_arq + ".module"
                    _mod_file = open(_nm_arq, "w")
                    _mod_texto = "module: " + self.nome_mod + "\n"
                    _mod_file.write(_mod_texto)
                    _mod_file.close()
        

        
        def _add_pkcs12(self, arq):

               #Solicita a Senha do pkcs12
               ret = self.password_dialog("importar", arq)

               if (ret == Gtk.ResponseType.OK):

                    # Passa a senha do arquivo via pipe para o script de importação

                    echo = subprocess.Popen(
                        ['/bin/echo', self.pin],
                        stdout=subprocess.PIPE,
                    )

                    importar = subprocess.Popen(
                        ['/opt/ovpnserpro/ovpn-import-p12', self.pkcs_file],
                        stdin=echo.stdout,
                        stdout=subprocess.PIPE,
                    )                

                    importar.wait()
                    buffer = importar.stdout.read()
                    
                    if importar.returncode == 0:
                        ret = self.message_dialog("Sucesso", "Reinicie o programa OVPN Serpro." , "info", 0)
                    else:
                        ret = self.message_dialog("Erro", buffer.decode('utf-8',errors="ignore"), "info", 0)
                    
		
               self.pkcs_file = ""
               self.pin = ""

                
        def _del_modulos(self, *args):
            
            directory = self.homedir + "/.config/pkcs11/modules/"
            _mod_row = self.mod_list.get_selected_row()
            
            for file in os.listdir(directory):
                if fnmatch.fnmatch(file, '*.module'):
                    modfile = open(directory + file, 'r')
                    texto = modfile.read()
                    modfile.close()
                    matches = re.search(self.listModulos[_mod_row.get_index()][0], texto)
                    if matches:
                        os.remove(directory + file)

            self.mod_list.remove(self.mod_list.get_selected_row())


        def _show_tab_profiles(self, *args):
                self.views_stack.set_visible_child_name ("perfil")
                self.back_button.set_visible (True)
                self.button_box.add (self.back_button)

                if self.perf_list == None:
                   #Spinner para perfil
                   self.spinner_perf = Gtk.Spinner.new()
                   self.perfs_frame.add(self.spinner_perf)
                   self.spinner_perf.start()
                   self.perfs_frame.show_all()


                   # Criação dos listbox perfil dinamicamente por causa 
                   # da inclusão do spinner no frame central
                   self.perf_list = Gtk.ListBox.new()
                   self.perf_list.set_can_focus(True)
                   self.perf_list.set_selection_mode(1)
                   self.perf_list.connect('row-activated', self._show_tab_conn, self.perf_list.get_selected_row())
                   self.perf_list.set_activate_on_single_click(True)
                   self.perf_list.grab_focus()


                   #Carregar lista de perfis
                   self.run_cmd_async(["/opt/ovpnserpro/ovpnctl", "profiles"], self.cancelProfile, self._profiles_read, self._profiles_finished)


        def _show_tab_conn(self, *args):

                self.views_stack.set_visible_child_name ("conexao")
                self.back_button.set_visible (True)
                
                # Recupera certificado selecionado
                certRow = self.certs_list.get_selected_row()
                                
                #buffer.insert(end, self.listCertObj[certRow.get_index()][1] + '\n' + self.listCertObj[certRow.get_index()][4] + '\n')

                # Recupera perfil selecionado
                perfilRow = self.perf_list.get_selected_row()
                
                buffer = self.txt_conn.get_buffer()
                (start, end) = buffer.get_bounds()
                buffer.delete(start, end)

                #self.perfil = self.listProfObj[perfilRow.get_index()][0]
                #self.cert = self.listCertObj[certRow.get_index()][4]
                
                self.cancelConnect = Gio.Cancellable()                    
                self.run_cmd_async(["/opt/ovpnserpro/ovpnctl", "connect", self.listCertObj[certRow.get_index()][4], self.listProfObj[perfilRow.get_index()][4]], self.cancelConnect, self._connect_read, self._connect_finished)
                

        def password_dialog(self, acao, tit):
                dialog = Gtk.Dialog(title='Insira a senha',
                                    transient_for=self.appwin,
                                    use_header_bar=1,
                                    modal=True,
                                    destroy_with_parent=True,resizable=False)
                dialog.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK,
                                   Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)

                hb = dialog.get_header_bar()
                if tit != "":
                    hb.set_subtitle(tit)

                content_area = dialog.get_content_area()
                hbox = Gtk.HBox(orientation=0,spacing=0)
                
                hbox.set_border_width(0)
                content_area.pack_start(hbox, True, True, 8)
        
                icon = Gio.ThemedIcon.new_with_default_fallbacks ("gcr-smart-card")
                stock = Gtk.Image.new_from_gicon (icon, Gtk.IconSize.DIALOG)                
                hbox.pack_start(stock, True, True, 1)

                hbox2 = Gtk.HBox(orientation=1,spacing=0)
                
                hbox2.set_border_width(0)
                hbox.pack_end(hbox2, True, True, 8)

                table = Gtk.Grid.new()
                
                table.set_column_homogeneous(False)
                table.set_column_spacing(8)
                hbox2.pack_start(table, True, True, 8)

                label = Gtk.Label.new_with_mnemonic("_Senha:")
                table.attach(label, 1, 1, 1, 1)
 
                btOk = dialog.get_widget_for_response(Gtk.ResponseType.OK)
                context = btOk.get_style_context()
                btOk.set_sensitive(False)
 
                local_entry1 = Gtk.Entry()
                local_entry1.set_size_request(200, -1)
                if (acao == "conectar"):
                    local_entry1.connect("changed", self.ativa_button_dialog, dialog, context, btOk)
                    local_entry1.set_visibility(False)
                    ch = "\u25CF"
                    local_entry1.set_invisible_char(ch)
                    local_entry1.set_activates_default(True)
                else:
                    local_entry1.set_visibility(False)
                    ch = "\u25CF"
                    local_entry1.set_invisible_char(ch)
                    local_entry1.set_activates_default(True)
                    
    
                    if not btOk.has_default():
                        btOk.set_sensitive(True)
                        btOk.grab_default()
                        if context.has_class(Gtk.STYLE_CLASS_DEFAULT):
                           context.add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)
                        dialog.set_default(btOk)
                                       
                
                    
                table.attach(local_entry1, 2, 1, 1, 1)
                label.set_mnemonic_widget(local_entry1)

                hbox.show_all()
        
                response = dialog.run()

                if response == Gtk.ResponseType.OK:
                    self.pin = local_entry1.get_text()

                dialog.destroy()
                return response

        def ativa_button_dialog(self, entry, dialogo, context, bt):
            if (entry.get_text() == ""):
                if context.has_class(Gtk.STYLE_CLASS_DEFAULT):
                   context.remove_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)

                dialogo.set_default(None)
                bt.set_sensitive(False)
            
            elif len(entry.get_text()) >= 1 and not bt.has_default():
                bt.set_sensitive(True)
                bt.grab_default()
                if context.has_class(Gtk.STYLE_CLASS_DEFAULT):
                   context.add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)
        
        def message_dialog(self, tit, msglabel, icn, usehb):
        
                dialog = Gtk.Dialog(tit,
                                    transient_for=self.appwin,
                                    use_header_bar=usehb,
                                    width_request=450,
                                    modal=True,
                                    destroy_with_parent=True,resizable=False)

                dialog.set_default_response(Gtk.ResponseType.OK)
                                   
                if (icn == "card"):
                    #Destruir o dialogo de desconexão se a dialogo de inserção de token aparecer
                    if self.dialogo != None:
                        self.dialogo.hide()
                        self.dialogo.destroy()
                        self.dialogo = None

                    dialog.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK,
                    Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
                elif (icn == "aviso"):
                    self.dialogo = dialog
                    dialog.add_buttons("Encerrar", Gtk.ResponseType.OK,
                    Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
                    btOk = dialog.get_widget_for_response(Gtk.ResponseType.OK)
                    context = btOk.get_style_context()
                    if not btOk.has_default():
                        btOk.grab_default()
                        if context.has_class(Gtk.STYLE_CLASS_DEFAULT):
                           context.add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)                    
                elif (icn == "info"):
                    self.dialogo = dialog
                    dialog.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK)
                    btOk = dialog.get_widget_for_response(Gtk.ResponseType.OK)
                    context = btOk.get_style_context()
                    if not btOk.has_default():
                        btOk.set_sensitive(True)
                        btOk.grab_default()
                        if context.has_class(Gtk.STYLE_CLASS_DEFAULT):
                           context.add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)                    
                    
                            
                
                content_area = dialog.get_content_area()
                hbox = Gtk.HBox(orientation=0,spacing=0)
                hbox.set_border_width(0)
                #content_area.pack_start(hbox, False, False, 12)
                content_area.pack_start(hbox, True, True, 8)

                if (icn == "card"):        
                   icon = Gio.ThemedIcon.new_with_default_fallbacks ("gcr-smart-card")
                   stock = Gtk.Image.new_from_gicon (icon, Gtk.IconSize.DIALOG)
                elif (icn == "aviso"):
                   icon = Gio.ThemedIcon.new_with_default_fallbacks ("dialog-warning-symbolic")
                   stock = Gtk.Image.new_from_gicon (icon, Gtk.IconSize.DIALOG)
                elif (icn == "info"):
                   icon = Gio.ThemedIcon.new_with_default_fallbacks ("dialog-information-symbolic")
                   stock = Gtk.Image.new_from_gicon (icon, Gtk.IconSize.DIALOG)
                           
                hbox.pack_start(stock, True, True, 1)                
        
                hbox2 = Gtk.HBox(orientation=1,spacing=0)
                hbox2.set_border_width(0)
                hbox.pack_end(hbox2, True, True, 8)

                table = Gtk.Grid.new()
                table.set_column_homogeneous(False)
                table.set_column_spacing(8)
                hbox2.pack_start(table, True, True, 8)
                               
                
                label = Gtk.Label.new_with_mnemonic(msglabel)
                table.attach(label, 1, 1, 1, 1)
        
                hbox.show_all()
        
                response = dialog.run()

                dialog.destroy()
                return response


        def _show_previous_stack(self, *args):
                if (self.views_stack.get_visible_child_name() == "perfil"):
                    self.views_stack.set_visible_child_name ("certs")
                    self.button_box.remove (self.back_button)
                elif (self.views_stack.get_visible_child_name() == "conexao"):
                    if (self.conn_label.get_text() == "Conectado"):
                        

                        ret = self.message_dialog("Encerrar conexão", "Há uma conexão ativa. Deseja encerrá-la?", "aviso", 1)
                        if (ret == Gtk.ResponseType.OK):
                            self.views_stack.set_visible_child_name ("perfil")
                            self.conn_label.set_text("Desconectado")
                            self._send_signal(self.process, 15)
                    elif (self.conn_label.get_text() == "Conectando"):
                        ret = self.message_dialog("Encerrar conexão", "Há uma conexão em andamento. Deseja encerrá-la?", "aviso", 1)
                        if (ret == Gtk.ResponseType.OK):
                            self.views_stack.set_visible_child_name ("perfil")
                            self.conn_label.set_text("Desconectado")
                            self._send_signal(self.process, 15)                            
                    else:
                        self.views_stack.set_visible_child_name ("perfil")
                        self.conn_label.set_text("Desconectado")
                        self._send_signal(self.process, 15)

        def _quit(self, *args):
            if (self.conn_label.get_text() == "Conectado"):
                ret = self.message_dialog("Encerrar conexão", "Há uma conexão ativa. Deseja encerrá-la?", "aviso", 1)

                if (ret == Gtk.ResponseType.OK):
                    self._send_signal(self.process, 15)
                    #Salva arquivo de log
                    self._log_file.close()

                    if self.appwin:
                       self.appwin.destroy()

                    Gtk.main_quit()
                else:
                    #Se cancelar no dialogo , sair da função quit sem destruir a janela da aplicação
                    return True;
            elif (self.conn_label.get_text() == "Conectando"):
                ret = self.message_dialog("Encerrar conexão", "Há uma conexão em andamento. Deseja encerrá-la?", "aviso", 1)

                if (ret == Gtk.ResponseType.OK):
                    self._send_signal(self.process, 15)
                    #Salva arquivo de log
                    self._log_file.close()

                    if self.appwin:
                       self.appwin.destroy()

                    Gtk.main_quit()
                else:
                    #Se cancelar no dialogo , sair da função quit sem destruir a janela da aplicação
                    return True;                    
            else:
                self._send_signal(self.process, 15)
                #Salva arquivo de log
                self._log_file.close()

                if self.appwin:
                   self.appwin.destroy()

                Gtk.main_quit()


        def _check_escape(self, widget, event):
            if event.keyval == Gdk.KEY_Escape:
                self._show_previous_stack()

        def _autoscroll(self, *args):
            adj = self.scroll_textbox.get_vadjustment()
            adj.set_value(adj.get_upper() - adj.get_page_size())

        def _send_signal(self, proc, sgnl):
            proc.send_signal(sgnl)
            
            
        #Funcao de execucao do ovpnctl, as funcoes de callback sao usadas 
        #porque será preciso alimentar controles em diferentes telas
        def run_cmd_async(self, cmdline, Cancel, callbackRead, callbackFinish):
                _flags = Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_MERGE

                self.process = Gio.Subprocess.new(cmdline, _flags)
                self.process.wait_check_async(None, callbackFinish)
                stdout = self.process.get_stdout_pipe()
                stdout.read_bytes_async(2048, 0, Cancel, callbackRead, ())
                self.stdin = self.process.get_stdin_pipe()                

        #TODO- Desmembrar esta função para somente executar o processo
        #o tratamento do retorno ficaria na função que a chamou - menu modulos !
        def run_cmd_list_sync(self, cmdline):
                _flags2 = Gio.SubprocessFlags.STDOUT_PIPE

                self.process2 = Gio.Subprocess.new(cmdline, _flags2)
                ret = self.process2.wait_check(None)
                if ret == True:
                    lines = ""
                    stdout2 = self.process2.get_stdout_pipe()
                    
                    #Ler a saida do processo 
                    bufread = stdout2.read_bytes(200000, None)
                    _buffer = bufread.get_data().decode('utf-8',errors="ignore")

                    _nome_lib = ""
                    _nome_manuf = ""
                    self.listModulos = []
                    while "\n" in _buffer:
                        _m_lib = None
                        _m_manuf = None
                        line, _buffer =_buffer.split("\n", 1)
                        #Ver se linha começa com qq caracter sem ser espaço e seguido de :
                        #Os nomes dos modulos na listagem do p11-kit list-modules seguem este padrão              
                        _m_lib = re.match('\S*: ', line)
                        if _m_lib:
                            _nome_lib = line[_m_lib.end():]
                        else:
                            _m_manuf = re.match('^    library-manufacturer: ', line)
                            if _m_manuf:
                                _nome_manuf = line[_m_manuf.end():]
                                if _nome_lib != "p11-kit-trust.so":
                                    self.listModulos.append([_nome_lib, _nome_manuf])
                    
                    directory = self.homedir + "/.config/pkcs11/modules"
                    if len(self.listModulos) == 0:
                        if not os.path.exists(directory):
                            os.makedirs(directory)
                        
                        self._mod_file = open(directory + "/gnome-keyring.module","w")
                        self._mod_file.write(gnmkeyring)
                        self._mod_file.close()

                        if os.path.exists("/usr/lib/libeTPkcs11.so"):
                            self._mod_file = open(directory + "/safenet.module","w")
                            self._mod_file.write(safenet)
                            self._mod_file.close()

                        if os.path.exists("/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so"):
                            self._mod_file = open(directory + "/wdata.module","w")
                            self._mod_file.write(wdata)
                            self._mod_file.close()

                    #Verificar se falta algum dos módulos básicos e inserir no p11-kit
                    else:
                        if not os.path.exists(directory):
                            os.makedirs(directory)

                        _modulos = [['gnome-keyring-pkcs11.so', 'GNOME Keyring'], ['/usr/lib/libeTPkcs11.so', 'SafeNet, Inc.'], ['/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so', 'WatchData ']]
                        for _modulo in _modulos:
                            try:
                                _i_mod = self.listModulos.index(_modulo)                                
                            except ValueError:
                                if _modulo[0] == 'gnome-keyring-pkcs11.so':
                                    self._mod_file = open(directory + "/gnome-keyring.module","w")
                                    self._mod_file.write(gnmkeyring)
                                    self._mod_file.close()
                                elif _modulo[0] == '/usr/lib/libeTPkcs11.so':
                                    if os.path.exists("/usr/lib/libeTPkcs11.so"):
                                        self._mod_file = open(directory + "/safenet.module","w")
                                        self._mod_file.write(safenet)
                                        self._mod_file.close()
                                elif _modulo[0] == '/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so':
                                    if os.path.exists("/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so"):
                                        self._mod_file = open(directory + "/wdata.module","w")
                                        self._mod_file.write(wdata)
                                        self._mod_file.close()

        def _certs_read(self, pipe, results, *a):
                try:
                    response = pipe.read_bytes_finish(results)
                except GLib.GError:
                        if not self.cancelCert.is_cancelled():
                                #Nao imprimir e colocar arq de log
                                self._log_file.write(str(datetime.now()) +  ": Erro certs_read" + "\n")
                                GLib.idle_add(pipe.read_bytes_async, 2048, 1, None, self._certs_read)
                        return
                

                response = response.get_data().decode('utf-8',errors="ignore")
                                
                self._buffer_cert = "%s%s" % (self._buffer_cert, response)

                line = ""
                reqaux = ""
                dateaux = ""
                expira = ""
                #inclusao dos certificados no dict                
                while "\n" in self._buffer_cert:
                        line, self._buffer_cert = self._buffer_cert.split("\n", 1)
                        if line.startswith("== Certificado"):
                                self.certObj = self.Cert()                                
                        elif not (self.certObj == None):
                                if line.startswith("Requerente:"):
                                        reqaux = line.lstrip('Requerente: ')
                                        reqaux = reqaux.upper()
                                        self.certObj.requerente = reqaux[reqaux.find('CN=') + 3:]
                                elif line.startswith("Emissor:"):
                                        self.certObj.emissor = line.lstrip('Emissor: ')
                                elif line.startswith("Válido  de: "):
                                        self.certObj.notBefore = line.lstrip('Válido  de: ')
                                elif line.startswith("Válido até: "):
                                        dateaux = line.lstrip('Válido até: ')
                                        dateaux = datetime.strptime(dateaux, '%d/%m/%Y %H:%M')
                                        dateaux = relativedelta.relativedelta(dateaux, datetime.now())
                                        
                                        if dateaux.years > 0 :
                                            if dateaux.years == 1 :
                                                expira = str(dateaux.years) + " ano"
                                                if dateaux.months > 1 :
                                                    if dateaux.days > 1 :
                                                        expira += ", " + str(dateaux.months) + " meses"
                                                        expira += " e " + str(dateaux.days) + " dias"
                                                    elif dateaux.days == 1 :
                                                        expira += ", " + str(dateaux.months) + " meses"
                                                        expira += " e " + str(dateaux.days) + " dia"
                                                    elif dateaux.days == 0 :
                                                        expira += " e " + str(dateaux.months) + " meses"
                                                elif dateaux.months == 1 :
                                                    if dateaux.days > 1 :
                                                        expira += ", " + str(dateaux.months) + " mês"
                                                        expira += " e " + str(dateaux.days) + " dias"
                                                    elif dateaux.days == 1 :
                                                        expira += ", " + str(dateaux.months) + " mês"
                                                        expira += " e " + str(dateaux.days) + " dia"
                                                    elif dateaux.days == 0 :
                                                        expira += " e " + str(dateaux.months) + " mês"
                                                else :
                                                    if dateaux.days > 1 :
                                                        expira += " e " + str(dateaux.days) + " dias"
                                                    elif dateaux.days == 1 :
                                                        expira += " e " + str(dateaux.days) + " dia"
                                            else:
                                                expira = str(dateaux.years) + " anos"
                                                if dateaux.months > 1 :
                                                    if dateaux.days > 1 :
                                                        expira += ", " + str(dateaux.months) + " meses"
                                                        expira += " e " + str(dateaux.days) + " dias"
                                                    elif dateaux.days == 1 :
                                                        expira += ", " + str(dateaux.months) + " meses"
                                                        expira += " e " + str(dateaux.days) + " dia"
                                                    elif dateaux.days == 0 :
                                                        expira += " e " + str(dateaux.months) + " meses"
                                                elif dateaux.months == 1 :
                                                    if dateaux.days > 1 :
                                                        expira += ", " + str(dateaux.months) + " mês"
                                                        expira += " e " + str(dateaux.days) + " dias"
                                                    elif dateaux.days == 1 :
                                                        expira += ", " + str(dateaux.months) + " mês"
                                                        expira += " e " + str(dateaux.days) + " dia"
                                                    elif dateaux.days == 0 :
                                                        expira += " e " + str(dateaux.months) + " meses"
                                                else :
                                                    if dateaux.days > 1 :
                                                        expira += " e " + str(dateaux.days) + " dias"
                                                    elif dateaux.days == 1 :
                                                        expira += " e " + str(dateaux.days) + " dia"

                                        elif dateaux.months > 0:
                                            if dateaux.months > 1:
                                                expira = str(dateaux.months) + " meses"
                                                if dateaux.days > 1 :
                                                    expira += " e " + str(dateaux.days) + " dias"
                                                elif dateaux.days == 1 :
                                                    expira += " e " + str(dateaux.days) + " dia"
                                            else:
                                                expira = str(dateaux.months) + " mês"
                                                if dateaux.days > 1:
                                                    expira += " e " + str(dateaux.days) + " dias"
                                                elif dateaux.days == 1 :
                                                    expira += " e " + str(dateaux.days) + " dia"

                                        elif dateaux.days > 1:
                                            expira = str(dateaux.days) + " dias"
                                        elif dateaux.days == 1:
                                            expira = str(dateaux.days) + " dia"
                                        elif dateaux.hours > 1:
                                            expira = str(dateaux.hours) + " horas"
                                        elif dateaux.hours == 1:
                                            expira = str(dateaux.hours) + " hora"
                                        elif dateaux.minutes > 1:
                                            expira = str(dateaux.minutes) + " minutos"
                                        elif dateaux.minutes == 1:
                                            expira = str(dateaux.minutes) + " minuto"
                                        else:
                                            expira = "Certificado expirado"
                                        
                                        self.certObj.expires = expira
                                elif line.startswith("Impressão digital:"):
                                        self.certObj.thumbPrint = line.lstrip('Impressão digital: ')
                                        #Emissor, Requerente, notAfter, notBefore, thumbPrint
                                        self.listCertObj.append([self.certObj.emissor, self.certObj.requerente, self.certObj.expires, self.certObj.notBefore, self.certObj.thumbPrint])
        
                                        self.list_row = Gtk.ListBoxRow.new ()
                                        self.row_grid = Gtk.Grid.new ()
                                        self.row_grid.set_margin_bottom (10)
                                        self.row_grid.set_orientation (Gtk.Orientation.HORIZONTAL)
                                        self.row_grid.set_column_spacing (6)
                                        self.row_grid.set_hexpand (1)
                                        self.list_row.add (self.row_grid)
                    
                                        self.image = Gtk.Image.new_from_gicon (self.icon_cert, _icon_size_dialog)
                                        self.image.margin = 6
                                        self.row_grid.add (self.image)
                                        
                                        if self.certObj.expires == "Certificado expirado":
                                            _info_cert = "<span size='medium'>" + self.certObj.requerente + "</span>\n<span size='small'>" + self.certObj.expires + "</span>"
                                        else:
                                            _info_cert = "<span size='medium'>" + self.certObj.requerente + "</span>\n<span size='small'>Expira em " + self.certObj.expires + "</span>"

                                        self.label_info = Gtk.Label.new ()
                                        self.label_info.set_markup(_info_cert)
                                        self.row_grid.add (self.label_info)
                                        
                                        self.certs_list.add (self.list_row)

                if not self.cancelCert.is_cancelled():
                        GLib.idle_add(pipe.read_bytes_async, 2048, 1, None, self._certs_read, ())

        def _certs_finished(self, proc, results):
                try:
                    r = proc.wait_check_finish(results)
                except GLib.GError:
                    if proc.get_if_exited():
                        error = "_certs_finished: Processo saiu com o código " + str(proc.get_exit_status())
                        self._log_file.write(str(datetime.now()) + ": " + error + "\n")
                
                        if proc.get_exit_status() == 127:
                            self._log_file.write(str(datetime.now()) +  ": _certs_finished: Comando não encontrado" + "\n")

                
                self.cancelCert.cancel()
                
                self.spinner.stop()
                self.certs_frame.remove(self.spinner)
                self.certs_frame.add(self.certs_list)

                self.appwin.show_all()

                #Recupera e seleciona último certificado usado
                #self.cert = self.settings.get_string ("certificate");

                #Seleciona o primeiro certificado caso nunca tenha conectado
                #if self.cert == "":
                #    self.certs_list.select_row(self.certs_list.get_row_at_index(0))
                #else:
                #    #Selecionar o último usado
                #    #for row in self.instGuiCerts.model:
                #    #    if row[4] == self.cert:
                #    #        #print("Thumb :" + row[4])
                #    #        self.instGuiCerts.tselect.select_iter(row.iter)
                #    #        break

                
                #self.instGuiCerts.btVoltar.set_sensitive(True)
                #self.instGuiCerts.btConect.set_sensitive(True)

        def _profiles_read(self, pipe, results, *a):
                try:
                        response = pipe.read_bytes_finish(results)
                except GLib.GError:
                        if not self.cancelProfile.is_cancelled():
                                self._log_file.write(str(datetime.now()) + ": " + "Erro profiles_read" + "\n")
                                GLib.idle_add(pipe.read_bytes_async, 2048, 1, None, self._profiles_read)
                        return
                
                response = response.get_data().decode('utf-8',errors="ignore")
                                
                self._buffer_prof = "%s%s" % (self._buffer_prof, response)

                line = ""
                #inclusao dos perfis na liststore
                while "\n" in self._buffer_prof:
                        line, self._buffer_prof = self._buffer_prof.split("\n", 1)
                        if line.startswith("== Perfil"):
                                self.profObj = self.Profile()                                
                        elif not (self.profObj == None):
                                if line.startswith("Nome: "):
                                        self.profObj.nome = line.lstrip('Nome: ')
                                elif line.startswith("Descrição: "):
                                        self.profObj.desc = line.lstrip('Descrição: ')
                                elif line.startswith("Servidor: "):
                                        self.profObj.server = line.lstrip('Servidor: ')
                                elif line.startswith("Data: "):
                                        self.profObj.data = line.lstrip('Data: ')
                                elif line.startswith("Caminho: "):
                                        self.profObj.caminho = line.lstrip('Caminho: ')
                                        self.listProfObj.append([self.profObj.nome, self.profObj.desc, self.profObj.server, self.profObj.data, self.profObj.caminho])

                                        self.list_row_perf = Gtk.ListBoxRow.new ()
                                        self.row_grid_perf = Gtk.Grid.new ()
                                        self.row_grid_perf.set_margin_bottom (10)
                                        self.row_grid_perf.set_orientation (Gtk.Orientation.HORIZONTAL)
                                        self.row_grid_perf.set_column_spacing (6)
                                        self.row_grid_perf.set_hexpand (1)
                                        self.list_row_perf.add (self.row_grid_perf)
            
                                        self.image_perf = Gtk.Image.new_from_gicon (self.icon_perf, _icon_size_dialog)
                                        self.image_perf.margin = 6
                                        self.row_grid_perf.add (self.image_perf)
            
                                        _info_perf = "<span size='medium'>" + self.profObj.nome + "</span>\n<span size='small'>" + self.profObj.desc + "</span>"
                                        
                                        self.label_info_perf = Gtk.Label.new ()
                                        self.label_info_perf.set_markup(_info_perf)
                                        self.row_grid_perf.add (self.label_info_perf)
            
                                        self.perf_list.add (self.list_row_perf)

                                    
                if not self.cancelProfile.is_cancelled():                    
                        GLib.idle_add(pipe.read_bytes_async, 2048, 1, None, self._profiles_read, ())


        def _profiles_finished(self, proc, results):
                try:
                        r = proc.wait_check_finish(results)
                except GLib.GError:
                    if proc.get_if_exited():
                        error = "_profiles_finished: Subprocess exited with code " + str(proc.get_exit_status())
                        self._log_file.write(str(datetime.now()) + ": " + error + "\n")
                
                        if proc.get_exit_status() == 127:
                            self._log_file.write(str(datetime.now()) + ": " + "_profiles_finished: Command not found" + "\n")
                
                self.cancelProfile.cancel()

                #Parar o spinner da tela de perfil
                self.spinner_perf.stop()
                self.perfs_frame.remove(self.spinner_perf)
                self.perfs_frame.add(self.perf_list)

                self.perf_list.show_all()

        def _connect_read(self, pipe, results, *a):
            try:
                response = pipe.read_bytes_finish(results)
            except GLib.GError:
                if not self.cancelConnect.is_cancelled():
                    self._log_file.write(str(datetime.now()) + ": " + "Erro connect_read" + "\n")
                    GLib.idle_add(pipe.read_bytes_async, 2048, 1, None, self._connect_read)
                return
            response = response.get_data().decode('utf-8', errors="ignore")
            self._buffer_conn = "%s%s" % (self._buffer_conn, response)

            line = ""
            #mostrar resultado da conexão
            if self._buffer_conn.find("\n") != -1:
               #Algumas respostas do ovpnctl chegam em blocos com algumas linhas
               while "\n" in self._buffer_conn:
                  line, self._buffer_conn = self._buffer_conn.split("\n", 1)
                  if not self.cancelConnect.is_cancelled():
                        # Alimenta com a saida do ovpnctl
                        buffer = self.txt_conn.get_buffer()
                        (start, end) = buffer.get_bounds()
                        buffer.insert(end, line + '\n')

                        #Gtk.ScrolledWindow.do_scroll_child(self.scroll_textbox, 15, False)

                        if line.find("Conectado") != -1:
                            self.conn_label.set_text("Conectado")
                            self.pin = ""
                            #Gtk.ScrolledWindow.do_scroll_child(self.scroll_textbox, 15, False)
                        elif line.find("Esqueceste o PIN?") != -1:
                            self.conn_label.set_text("Desconectado")
                        elif line.find("Outra instância está em execução.") != -1:
                            self.conn_label.set_text("Desconectado")
                        else:
                            self.conn_label.set_text("Conectando")

            #Chegou dados sem EOL
            else:
               line = self._buffer_conn
               self._buffer_conn = ""
               if line.find("Senha (") != -1:
                   nometoken=""                          
                   ret = re.search(r'Senha (.*): ', line)
                   if ret:
                       nometoken = ret.group(1)

                   #Solicita o PIN - removendo os parentesis
                   nometoken = nometoken[1:len(nometoken)-1]
                   ret = self.password_dialog("conectar", nometoken)

                   if (ret == Gtk.ResponseType.OK):
                        (y, x) = self.stdin.write_all(str.encode(self.pin + "\n"), None)
                        self.stdin.flush(None)

                        buffer = self.txt_conn.get_buffer()
                        (start, end) = buffer.get_bounds()
                        buffer.insert(end, line + '\n')

                   else:
                       self._send_signal(self.process, 15)
                       
                       buffer = self.txt_conn.get_buffer()
                       (start, end) = buffer.get_bounds()
                       buffer.insert(end, "Cancelado")
                       self.conn_label.set_text("Desconectado")

               elif line.find("Insira o dispositivo") != -1:
                          nometoken=""                          
                          ret = re.search(r'Insira o dispositivo criptográfico (.*) e pressione ENTER', line)
                          if ret:
                              nometoken = ret.group(1)

                          ret = self.message_dialog("Insira o dispositivo", "Por favor, insira o dispositivo criptográfico: \n" + nometoken, "card", 1)
                          if (ret == Gtk.ResponseType.OK):
                             (y, x) = self.stdin.write_all(str.encode("\n"), None)
                             self.stdin.flush(None)
                          else:
                             self._send_signal(self.process, 15)

                             buffer = self.txt_conn.get_buffer()
                             (start, end) = buffer.get_bounds()
                             buffer.insert(end, "Cancelado")
                             self.conn_label.set_text("Desconectado")
                             #Gtk.ScrolledWindow.do_scroll_child(self.scroll_textbox, 15, False)

               else:
                   buffer = self.txt_conn.get_buffer()
                   (start, end) = buffer.get_bounds()
                   buffer.insert(end, line + '\n')
  
            if not self.cancelConnect.is_cancelled():
                GLib.idle_add(pipe.read_bytes_async, 2048, 1, None, self._connect_read, ())


        def _connect_finished(self, proc, results):
            
            try:
                r = proc.wait_check_finish(results)
            except GLib.GError:
                if proc.get_if_exited():
                    error = "_connect_finished: Processo saiu com código " +  str(proc.get_exit_status())
                    self._log_file.write(str(datetime.now()) + ": " + error + "\n")
            
            #Salva no Gsettings os dados usados na conexão
            #self.call.settings.set_string ("perfil", self.perfil);
            #self.call.settings.set_string ("certificate", self.cert);
            self.cancelConnect.cancel()



        def _update_read(self, pipe, results, *a):
            try:
                response = pipe.read_bytes_finish(results)
            except GLib.GError:
                if not self.cancelUpdate.is_cancelled():
                    self._log_file.write(str(datetime.now()) + ": " + "Erro update_read" + "\n")
                    GLib.idle_add(pipe.read_bytes_async, 2048, 1, None, self._update_read)
                return
            response = response.get_data().decode('utf-8', errors="ignore")
            self._buffer_upd = "%s%s" % (self._buffer_upd, response)
            
            line = ""
            #mostrar resultado do update - arquivo de log
            while "\n" in self._buffer_upd:
                line, self._buffer_upd = self._buffer_upd.split("\n", 1)
                if not self.cancelUpdate.is_cancelled():
                    self._log_file.write(str(datetime.now()) + ": " + line + "\n")
            
            if not self.cancelUpdate.is_cancelled():
                GLib.idle_add(pipe.read_bytes_async, 2048, 1, None, self._update_read, ())


        def _update_finished(self, proc, results):
            
            try:
                r = proc.wait_check_finish(results)
            except GLib.GError:
                if proc.get_if_exited():
                    error = "_modules_finished: Processo saiu com o código " + str(proc.get_exit_status())
                    self._log_file.write(str(datetime.now()) + ": " + error + "\n")
            self.cancelUpdate.cancel()


if __name__ == "__main__":
        app = Application()
        app.run(sys.argv)
