## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 Red Hat, Inc.
## Authors:
##  Tim Waugh <twaugh@redhat.com>
##  Jiri Popelka <jpopelka@redhat.com>

## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import asyncconn
import authconn
import cups
import dbus
import dbus.glib
import dbus.service
from gi.repository import Notify
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import Gtk
from gui import GtkGUI
import monitor
import os, shutil
from gi.repository import Pango
import pwd
import smburi
import subprocess
import sys
import time
import urllib
from xml.sax import saxutils

from debug import *
import config
import statereason
import errordialogs

cups.require("1.9.47")

try:
    from gi.repository import GnomeKeyring
    USE_KEYRING=True
except ImportError:
    USE_KEYRING=False

import gettext
gettext.install(domain=config.PACKAGE, localedir=config.localedir, unicode=True)

from statereason import StateReason

pkgdata = config.pkgdatadir
ICON="printer"
ICON_SIZE=22
SEARCHING_ICON="document-print-preview"

# We need to call Notify.init before we can check the server for caps
Notify.init('System Config Printer Notification')

class PrinterURIIndex:
    def __init__ (self, names=[]):
        self.printer = {}
        self.names = names
        self._collect_names ()

    def _collect_names (self, connection=None):
        if not self.names:
            return

        if not connection:
            try:
                c = cups.Connection ()
            except RuntimeError:
                return

        for name in self.names:
            self.add_printer (name, connection=c)

        self.names = []

    def add_printer (self, printer, connection=None):
        try:
            self._map_printer (name=printer, connection=connection)
        except KeyError:
            return

    def update_from_attrs (self, printer, attrs):
        uris = []
        if attrs.has_key ('printer-uri-supported'):
            uri_supported = attrs['printer-uri-supported']
            if type (uri_supported) != list:
                uri_supported = [uri_supported]
            uris.extend (uri_supported)
        if attrs.has_key ('notify-printer-uri'):
            uris.append (attrs['notify-printer-uri'])
        if attrs.has_key ('printer-more-info'):
            uris.append (attrs['printer-more-info'])

        for uri in uris:
            self.printer[uri] = printer

    def remove_printer (self, printer):
        # Remove references to this printer in the URI map.
        self._collect_names ()
        uris = self.printer.keys ()
        for uri in uris:
            if self.printer[uri] == printer:
                del self.printer[uri]

    def lookup (self, uri, connection=None):
        self._collect_names ()
        try:
            return self.printer[uri]
        except KeyError:
            return self._map_printer (uri=uri, connection=connection)

    def all_printer_names (self):
        self._collect_names ()
        return set (self.printer.values ())

    def lookup_cached_by_name (self, name):
        self._collect_names ()
        for uri, printer in self.printer.iteritems ():
            if printer == name:
                return uri

        raise KeyError

    def _map_printer (self, uri=None, name=None, connection=None):
        try:
            if connection == None:
                connection = cups.Connection ()
            if isinstance(name, bytes):
                name = name.decode ('utf-8')

            r = ['printer-name', 'printer-uri-supported', 'printer-more-info']
            if uri != None:
                attrs = connection.getPrinterAttributes (uri=uri,
                                                         requested_attributes=r)
            else:
                attrs = connection.getPrinterAttributes (name,
                                                         requested_attributes=r)
        except RuntimeError:
            # cups.Connection() failed
            raise KeyError
        except cups.IPPError:
            # URI not known.
            raise KeyError

        name = attrs['printer-name']
        self.update_from_attrs (name, attrs)
        if uri != None:
            self.printer[uri] = name
        return name

class CancelJobsOperation(GObject.GObject):
    __gsignals__ = {
        'destroy':     (GObject.SIGNAL_RUN_LAST, None, ()),
        'job-deleted': (GObject.SIGNAL_RUN_LAST, None, (int,)),
        'ipp-error':   (GObject.SIGNAL_RUN_LAST, None,
                        (int, GObject.TYPE_PYOBJECT)),
        'finished':    (GObject.SIGNAL_RUN_LAST, None, ())
        }

    def __init__ (self, parent, host, port, encryption, jobids, purge_job):
        GObject.GObject.__init__ (self)
        self.jobids = list (jobids)
        self.purge_job = purge_job
        self.host = host
        self.port = port
        self.encryption = encryption
        if purge_job:
            if len(self.jobids) > 1:
                dialog_title = _("Delete Jobs")
                dialog_label = _("Do you really want to delete these jobs?")
            else:
                dialog_title = _("Delete Job")
                dialog_label = _("Do you really want to delete this job?")
        else:
            if len(self.jobids) > 1:
                dialog_title = _("Cancel Jobs")
                dialog_label = _("Do you really want to cancel these jobs?")
            else:
                dialog_title = _("Cancel Job")
                dialog_label = _("Do you really want to cancel this job?")

        dialog = Gtk.Dialog (dialog_title, parent,
                             Gtk.DialogFlags.MODAL |
                             Gtk.DialogFlags.DESTROY_WITH_PARENT,
                             (_("Keep Printing"), Gtk.ResponseType.NO,
                              dialog_title, Gtk.ResponseType.YES))
        dialog.set_default_response (Gtk.ResponseType.NO)
        dialog.set_border_width (6)
        dialog.set_resizable (False)
        hbox = Gtk.HBox.new (False, 12)
        image = Gtk.Image ()
        image.set_from_stock (Gtk.STOCK_DIALOG_QUESTION, Gtk.IconSize.DIALOG)
        image.set_alignment (0.0, 0.0)
        hbox.pack_start (image, False, False, 0)
        label = Gtk.Label(label=dialog_label)
        label.set_line_wrap (True)
        label.set_alignment (0.0, 0.0)
        hbox.pack_start (label, False, False, 0)
        dialog.vbox.pack_start (hbox, False, False, 0)
        dialog.connect ("response", self.on_job_cancel_prompt_response)
        dialog.connect ("delete-event", self.on_job_cancel_prompt_delete)
        dialog.show_all ()
        self.dialog = dialog
        self.connection = None
        debugprint ("+%s" % self)

    def __del__ (self):
        debugprint ("-%s" % self)

    def do_destroy (self):
        if self.connection:
            self.connection.destroy ()
            self.connection = None

        if self.dialog:
            self.dialog.destroy ()
            self.dialog = None

        debugprint ("DESTROY: %s" % self)

    def destroy (self):
        self.emit ('destroy')

    def on_job_cancel_prompt_delete (self, dialog, event):
        self.on_job_cancel_prompt_response (dialog, Gtk.ResponseType.NO)

    def on_job_cancel_prompt_response (self, dialog, response):
        dialog.destroy ()
        self.dialog = None

        if response != Gtk.ResponseType.YES:
            self.emit ('finished')
            return

        if len(self.jobids) == 0:
            self.emit ('finished')
            return

        asyncconn.Connection (host=self.host,
                              port=self.port,
                              encryption=self.encryption,
                              reply_handler=self._connected,
                              error_handler=self._connect_failed)

    def _connect_failed (self, connection, exc):
        debugprint ("CancelJobsOperation._connect_failed %s:%s" % (connection, repr (exc)))

    def _connected (self, connection, result):
        self.connection = connection

        if self.purge_job:
            operation = _("deleting job")
        else:
            operation = _("canceling job")

        self.connection._begin_operation (operation)
        self.connection.cancelJob (self.jobids[0], self.purge_job,
                                   reply_handler=self.cancelJob_finish,
                                   error_handler=self.cancelJob_error)

    def cancelJob_error (self, connection, exc):
        debugprint ("cancelJob_error %s:%s" % (connection, repr (exc)))
        if type (exc) == cups.IPPError:
            (e, m) = exc.args
            if (e != cups.IPP_NOT_POSSIBLE and
                e != cups.IPP_NOT_FOUND):
                self.emit ('ipp-error', self.jobids[0], exc)
            self.cancelJob_finish(connection, None)
        else:
            self.connection._end_operation ()
            self.connection.destroy ()
            self.connection = None
            self.emit ('ipp-error', self.jobids[0], exc)
            # Give up.
            self.emit ('finished')
            return

    def cancelJob_finish (self, connection, result):
        debugprint ("cancelJob_finish %s:%s" % (connection, repr (result)))
        self.emit ('job-deleted', self.jobids[0])
        del self.jobids[0]
        if not self.jobids:
            # Last job canceled.
            self.connection._end_operation ()
            self.connection.destroy ()
            self.connection = None
            self.emit ('finished')
            return
        else:
            # there are other jobs to cancel/delete
            connection.cancelJob (self.jobids[0], self.purge_job,
                                  reply_handler=self.cancelJob_finish,
                                  error_handler=self.cancelJob_error)

class JobViewer (GtkGUI):
    required_job_attributes = set(['job-k-octets',
                                   'job-name',
                                   'job-originating-user-name',
                                   'job-printer-uri',
                                   'job-state',
                                   'time-at-creation',
                                   'job-preserved'])

    __gsignals__ = {
        'finished':    (GObject.SIGNAL_RUN_LAST, None, ())
        }

    def __init__(self, bus=None, loop=None,
                 applet=False, suppress_icon_hide=False,
                 my_jobs=True, specific_dests=None,
                 parent=None):
        GObject.GObject.__init__ (self)
        self.loop = loop
        self.applet = applet
        self.suppress_icon_hide = suppress_icon_hide
        self.my_jobs = my_jobs
        self.specific_dests = specific_dests
        notify_caps = Notify.get_server_caps ()
        self.notify_has_actions = "actions" in notify_caps
        self.notify_has_persistence = "persistence" in notify_caps

        self.jobs = {}
        self.jobiters = {}
        self.jobids = []
        self.jobs_attrs = {} # dict of jobid->(GtkListStore, page_index)
        self.active_jobs = set() # of job IDs
        self.stopped_job_prompts = set() # of job IDs
        self.printer_state_reasons = {}
        self.num_jobs_when_hidden = 0
        self.connecting_to_device = {} # dict of printer->time first seen
        self.state_reason_notifications = {}
        self.auth_info_dialogs = {} # by job ID
        self.job_creation_times_timer = None
        self.new_printer_notifications = {}
        self.completed_job_notifications = {}
        self.authenticated_jobs = set() # of job IDs
        self.ops = []

        self.getWidgets ({"JobsWindow":
                              ["JobsWindow",
                               "treeview",
                               "statusbar",
                               "toolbar"],
                          "statusicon_popupmenu":
                              ["statusicon_popupmenu"]},

                         domain=config.PACKAGE)

        job_action_group = Gtk.ActionGroup ("JobActionGroup")
        job_action_group.add_actions ([
                ("cancel-job", Gtk.STOCK_CANCEL, _("_Cancel"), None,
                 _("Cancel selected jobs"), self.on_job_cancel_activate),
                ("delete-job", Gtk.STOCK_DELETE, _("_Delete"), None,
                 _("Delete selected jobs"), self.on_job_delete_activate),
                ("hold-job", Gtk.STOCK_MEDIA_PAUSE, _("_Hold"), None,
                 _("Hold selected jobs"), self.on_job_hold_activate),
                ("release-job", Gtk.STOCK_MEDIA_PLAY, _("_Release"), None,
                 _("Release selected jobs"), self.on_job_release_activate),
                ("reprint-job", Gtk.STOCK_REDO, _("Re_print"), None,
                 _("Reprint selected jobs"), self.on_job_reprint_activate),
                ("retrieve-job", Gtk.STOCK_SAVE_AS, _("Re_trieve"), None,
                 _("Retrieve selected jobs"), self.on_job_retrieve_activate),
                ("move-job", None, _("_Move To"), None, None, None),
                ("authenticate-job", None, _("_Authenticate"), None, None,
                 self.on_job_authenticate_activate),
                ("job-attributes", None, _("_View Attributes"), None, None,
                 self.on_job_attributes_activate),
                ("close", Gtk.STOCK_CLOSE, None, "<ctrl>w",
                 _("Close this window"), self.on_delete_event)
                ])
        self.job_ui_manager = Gtk.UIManager ()
        self.job_ui_manager.insert_action_group (job_action_group, -1)
        self.job_ui_manager.add_ui_from_string (
"""
<ui>
 <accelerator action="cancel-job"/>
 <accelerator action="delete-job"/>
 <accelerator action="hold-job"/>
 <accelerator action="release-job"/>
 <accelerator action="reprint-job"/>
 <accelerator action="retrieve-job"/>
 <accelerator action="move-job"/>
 <accelerator action="authenticate-job"/>
 <accelerator action="job-attributes"/>
 <accelerator action="close"/>
</ui>
"""
)
        self.job_ui_manager.ensure_update ()
        self.JobsWindow.add_accel_group (self.job_ui_manager.get_accel_group ())
        self.job_context_menu = Gtk.Menu ()
        for action_name in ["cancel-job",
                            "delete-job",
                            "hold-job",
                            "release-job",
                            "reprint-job",
                            "retrieve-job",
                            "move-job",
                            None,
                            "authenticate-job",
                            "job-attributes"]:
            if not action_name:
                item = Gtk.SeparatorMenuItem ()
            else:
                action = job_action_group.get_action (action_name)
                action.set_sensitive (False)
                item = action.create_menu_item ()

                if action_name == 'move-job':
                    self.move_job_menuitem = item
                    printers = Gtk.Menu ()
                    item.set_submenu (printers)

            item.show ()
            self.job_context_menu.append (item)

        for action_name in ["cancel-job",
                            "delete-job",
                            "hold-job",
                            "release-job",
                            "reprint-job",
                            "retrieve-job",
                            "close"]:
            action = job_action_group.get_action (action_name)
            action.set_sensitive (action_name == "close")
            action.set_is_important (action_name == "close")
            item = action.create_tool_item ()
            item.show ()
            self.toolbar.insert (item, -1)

        for skip, ellipsize, name, setter in \
                [(False, False, _("Job"), self._set_job_job_number_text),
                 (True, False, _("User"), self._set_job_user_text),
                 (False, True, _("Document"), self._set_job_document_text),
                 (False, True, _("Printer"), self._set_job_printer_text),
                 (False, False, _("Size"), self._set_job_size_text)]:
            if applet and skip:
                # Skip the user column when running as applet.
                continue

            cell = Gtk.CellRendererText()
            if ellipsize:
                # Ellipsize the 'Document' and 'Printer' columns.
                cell.set_property ("ellipsize", Pango.EllipsizeMode.END)
                cell.set_property ("width-chars", 20)
            column = Gtk.TreeViewColumn(name, cell)
            column.set_cell_data_func (cell, setter, None)
            column.set_resizable(True)
            self.treeview.append_column(column)

        cell = Gtk.CellRendererText ()
        column = Gtk.TreeViewColumn (_("Time submitted"), cell, text=1)
        column.set_resizable (True)
        self.treeview.append_column (column)

        column = Gtk.TreeViewColumn (_("Status"))
        icon = Gtk.CellRendererPixbuf ()
        column.pack_start (icon, False)
        text = Gtk.CellRendererText ()
        text.set_property ("ellipsize", Pango.EllipsizeMode.END)
        text.set_property ("width-chars", 20)
        column.pack_start (text, True)
        column.set_cell_data_func (icon, self._set_job_status_icon, None)
        column.set_cell_data_func (text, self._set_job_status_text, None)
        self.treeview.append_column (column)

        self.store = Gtk.TreeStore(int, str)
        self.store.set_sort_column_id (0, Gtk.SortType.DESCENDING)
        self.treeview.set_model(self.store)
        self.treeview.set_rules_hint (True)
        self.selection = self.treeview.get_selection()
        self.selection.set_mode(Gtk.SelectionMode.MULTIPLE)
        self.selection.connect('changed', self.on_selection_changed)
        self.treeview.connect ('button_release_event',
                               self.on_treeview_button_release_event)
        self.treeview.connect ('popup-menu', self.on_treeview_popup_menu)

        self.JobsWindow.set_icon_name (ICON)
        self.JobsWindow.hide ()

        if specific_dests:
            the_dests = reduce (lambda x, y: x + ", " + y, specific_dests)

        if my_jobs:
            if specific_dests:
                title = _("my jobs on %s") % the_dests
            else:
                title = _("my jobs")
        else:
            if specific_dests:
                title = "%s" % the_dests
            else:
                title = _("all jobs")
        self.JobsWindow.set_title (_("Document Print Status (%s)") % title)

        if parent:
            self.JobsWindow.set_transient_for (parent)

        def load_icon(theme, icon):
            try:
                pixbuf = theme.load_icon (icon, ICON_SIZE, 0)
            except GObject.GError:
                debugprint ("No %s icon available" % icon)
                # Just create an empty pixbuf.
                pixbuf = GdkPixbuf.Pixbuf.new (GdkPixbuf.Colorspace.RGB,
                                         True, 8, ICON_SIZE, ICON_SIZE)
                pixbuf.fill (0)
            return pixbuf

        theme = Gtk.IconTheme.get_default ()
        self.icon_jobs = load_icon (theme, ICON)
        self.icon_jobs_processing = load_icon (theme, "printer-printing")
        self.icon_no_jobs = self.icon_jobs.copy ()
        self.icon_no_jobs.fill (0)
        self.icon_jobs.composite (self.icon_no_jobs,
                                  0, 0,
                                  self.icon_no_jobs.get_width(),
                                  self.icon_no_jobs.get_height(),
                                  0, 0,
                                  1.0, 1.0,
                                  GdkPixbuf.InterpType.BILINEAR,
                                  127)
        if self.applet and not self.notify_has_persistence:
            self.statusicon = Gtk.StatusIcon ()
            self.statusicon.set_from_pixbuf (self.icon_no_jobs)
            self.statusicon.connect ('activate', self.toggle_window_display)
            self.statusicon.connect ('popup-menu', self.on_icon_popupmenu)
            self.statusicon.set_visible (False)

        # D-Bus
        if bus == None:
            bus = dbus.SystemBus ()

        self.connect_signals ()
        self.set_process_pending (True)


import sys
import os
import numpy as np
import array

class ploadparticles(object):
    def __init__(self, ns, wdir=None, datatype=None):
        self.ns = ns
        if wdir == None:
            self.wdir = os.getcwd()+'/'
        else:
            self.wdir = wdir

        if datatype == None:
            datatype = 'dbl'
            self.extsize = 8

        self.ext = datatype
        if self.ext == 'flt': self.extsize = 4
        if self.ext == 'vtk': self.extsize = 4

        self.Header = {}
        try:
            self.GetParticleDataFileName()
        except (IOError):
            print "!ERROR! - Particle Data file not found : %s"%self.fname
        else:
            if self.ext == 'vtk':
                Part_Data_dict = self.GetParticleDataVTK()
            else:
                self.ReadParticleFile()
                Part_Data_dict = self.GetParticleData()

            self.partdata_keys = []
            for keys in Part_Data_dict:
                self.partdata_keys.append(keys)
                object.__setattr__(self, keys, Part_Data_dict.get(keys))

    def GetParticleDataFileName(self):
        nsstr_ = str(self.ns)
        while len(nsstr_) < 4:
            nsstr_ = '0'+ nsstr_
        self.fname = self.wdir+"particles."+nsstr_+"."+self.ext

    def GetParticleFileHeader(self, line_):
        if line_.split()[1] != 'PLUTO':
            hlist = line_.split()[1:]
            if hlist[0] == 'field_names':
                vars_ = hlist[1:]#[v.strip(' ') for v in hlist[1:]]
                t = tuple([hlist[0], vars_])
                self.Header.update(dict([t]))
            elif hlist[0] == 'field_dim':
                varsdim_ =hlist[1:]
                t = tuple([hlist[0], varsdim_])
                self.Header.update(dict([t]))
                self.Header['nflux'] = int(varsdim_[-3])
                self.Header['ebins'] = int(varsdim_[-1])
            else:
                t = tuple([''.join(hlist[:-1]), hlist[-1]])
                self.Header.update(dict([t]))

    def ReadParticleFile(self):
        print "Reading Particle Data file : %s"%self.fname
        fp_ = open(self.fname,'rb')
        for l in fp_.readlines():
            if l.split()[0] == '#':
            	self.GetParticleFileHeader(l)
            else:
            	break
        fp_.close()

        cnt_ = 9
        HeadBytes_ = int(self.Header['nparticles'])*cnt_*self.extsize
        if int(self.Header['spectrum']):
            cnt_ += 6+2*int(self.Header['nflux'])+ 2*int(self.Header['ebins'])
            HeadBytes_ = int(self.Header['nparticles'])*cnt_*self.extsize

        fp_ = open(self.fname,'rb')
        scrh_ = fp_.read()
        self.datastr = scrh_[len(scrh_)-HeadBytes_:]
        fp_.close()

    def GetParticleDataVTK(self):
        print "Reading Particle Data file : %s"%self.fname
        fp_ = open(self.fname,'rb')
        ks_ = []
        vtk_scalars_ = []
        while True:
            l = fp_.readline()
            try:
                l.split()[0]
            except IndexError:
                pass
            else:
                if l.split()[0] == "POINTS":
                    np_ = int(l.split()[1])
                    endianess = '>'
                    dtyp_ = np.dtype(endianess+'%df'%(3*np_))
                    nb_ = np.dtype(dtyp_).itemsize
                    posbuf_ = array.array('f')
                    posbuf_.fromstring(fp_.read(nb_))
                    pos_ = np.frombuffer(posbuf_, dtype=np.dtype(dtyp_))

                    pos1_ = np.zeros(np_)
                    pos2_ = np.zeros(np_)
                    pos3_ = np.zeros(np_)
                    for i in range(np_):
                        pos1_[i] = pos_[0][3*i]
                        pos2_[i] = pos_[0][3*i+1]
                        pos3_[i] = pos_[0][3*i+2]

                elif l.split()[0] == "VECTORS":
                    endianess = '>'
                    dtyp_ = np.dtype(endianess+'%df'%(3*np_))
                    nb_ = np.dtype(dtyp_).itemsize
                    velbuf_ = array.array('f')
                    velbuf_.fromstring(fp_.read(nb_))
                    vel_ = np.frombuffer(velbuf_, dtype=np.dtype(dtyp_))

                    vel1_ = np.zeros(np_)
                    vel2_ = np.zeros(np_)
                    vel3_ = np.zeros(np_)
                    for i in range(np_):
                        vel1_[i] = vel_[0][3*i]
                        vel2_[i] = vel_[0][3*i+1]
                        vel3_[i] = vel_[0][3*i+2]

                elif l.split()[0] == "SCALARS":
                    ks_.append(l.split()[1])
                elif l.split()[0] == "LOOKUP_TABLE":
                    endianess = '>'
                    if ks_[-1] == "Identity":
                        dtyp_ = np.dtype(endianess+'%di'%np_)
                    else:
                        dtyp_ = np.dtype(endianess+'%df'%np_)

                    nb_ = np.dtype(dtyp_).itemsize
                    scalbuf_ = array.array('f')
                    scalbuf_.fromstring(fp_.read(nb_))
                    scal_ = np.frombuffer(scalbuf_, dtype=np.dtype(dtyp_))

                    vtk_scalars_.append(scal_[0])
                else:
                    pass

            if l == '':
                break
        ks_ = ['id', 'color', 'tinj']
        vtkvardict = dict(zip(ks_,vtk_scalars_))
        tup_ = [('x1', pos1_),('x2', pos2_),('x3', pos3_),\
                ('vx1', vel1_),('vx2', vel2_),('vx3', vel3_)]
        vtkvardict.update(dict(tup_))
        return vtkvardict

    def GetParticleData(self):
        vars_ = self.Header['field_names']
        endianess = '<'
        if self.Header['endianity'] == 'big':endianess = '>'
        dtyp_ = np.dtype(endianess+self.ext[0])
        DataDict_ = self.Header
        np_ = int(DataDict_['nparticles'])
        data_ = np.fromstring(self.datastr,dtype=dtyp_)

        spectrum_ = int(DataDict_['spectrum'])
        ids_   = np.zeros(np_)
        pos1_  = np.zeros(np_)
        pos2_  = np.zeros(np_)
        pos3_  = np.zeros(np_)
        vel1_  = np.zeros(np_)
        vel2_  = np.zeros(np_)
        vel3_  = np.zeros(np_)
        tinj_  = np.zeros(np_)
        col_   = np.zeros(np_)

        A = np.array_split(data_, [9*i for i in range(1,np_)])

        if spectrum_:
            nmic_      = np.zeros(np_)
            cmpratio_  = np.zeros(np_)
            shkflg_    = np.zeros(np_)
            shkgradp_  = np.zeros(np_)
            a_         = np.zeros(np_)
            c_         = np.zeros(np_)
            A = np.array_split(data_, [10*i for i in range(1,np_)])
            A = np.array_split(data_, [11*i for i in range(1,np_)])
            A = np.array_split(data_, [12*i for i in range(1,np_)])
            A = np.array_split(data_, [13*i for i in range(1,np_)])
            A = np.array_split(data_, [14*i for i in range(1,np_)])

            ebins_ = int(DataDict_['ebins'])
            nflx_  = int(DataDict_['nflux'])

            shkvL_ = np.zeros((np_, nflx_))
            shkvR_ = np.zeros((np_, nflx_))

            specE_ = np.zeros((np_,ebins_))
            specN_ = np.zeros((np_,ebins_))
            A = np.array_split(data_, [(15+2*nflx_)*i for i in range(1,np_)])
            A = np.array_split(data_, [(15+2*nflx_+2*ebins_)*i for i in range(1,np_)])

        for n in range(np_):
            ids_[n]   = A[n][0]
            pos1_[n] = A[n][1]
            pos2_[n] = A[n][2]
            pos3_[n] = A[n][3]


"""Commonly used dialogs"""
# pylint: disable=no-member
import os

from lutris import api, pga, runtime, settings
from lutris.gui.widgets.utils import open_uri
from lutris.gui.widgets.log_text_view import LogTextView
from lutris.util import datapath
from lutris.util.log import logger

import gi
gi.require_version("WebKit2", "4.0")

from gi.repository import GLib, GObject, Gtk, WebKit2

class Dialog(Gtk.Dialog):
    def __init__(self, title=None, parent=None, flags=0, buttons=None):
        super().__init__(title, parent, flags, buttons)
        self.set_border_width(10)
        self.set_destroy_with_parent(True)

class GtkBuilderDialog(GObject.Object):
    def __init__(self, parent=None, **kwargs):
        super().__init__()
        ui_filename = os.path.join(datapath.get(), "ui", self.glade_file)
        if not os.path.exists(ui_filename):
            raise ValueError("ui file does not exists: %s" % ui_filename)

        self.builder = Gtk.Builder()
        self.builder.add_from_file(ui_filename)
        self.dialog = self.builder.get_object(self.dialog_object)

        self.builder.connect_signals(self)
        if parent:
            self.dialog.set_transient_for(parent)
        self.dialog.show_all()
        self.dialog.connect("delete-event", lambda *x: x[0].destroy())
        self.initialize(**kwargs)

    def initialize(self, **kwargs):
        pass

    def on_close(self, *args):
        self.dialog.destroy()

    def on_response(self, widget, response):
        if response == Gtk.ResponseType.DELETE_EVENT:
            try:
                self.dialog.hide()
            except AttributeError:
                pass

class AboutDialog(GtkBuilderDialog):
    glade_file = "about-dialog.ui"
    dialog_object = "about_dialog"

    def initialize(self):
        self.dialog.set_version(settings.VERSION)

class NoticeDialog(Gtk.MessageDialog):
    """Display a message to the user."""

    def __init__(self, message, parent=None):
        super().__init__(buttons=Gtk.ButtonsType.OK, parent=parent)
        self.set_markup(message)
        self.run()
        self.destroy()

class ErrorDialog(Gtk.MessageDialog):
    """Display an error message."""

    def __init__(self, message, secondary=None, parent=None):
        super().__init__(buttons=Gtk.ButtonsType.OK, parent=parent)
        self.set_markup(message)
        if secondary:
            self.format_secondary_text(secondary)
        self.run()
        self.destroy()

class QuestionDialog(Gtk.MessageDialog):
    """Ask the user a question."""

    YES = Gtk.ResponseType.YES
    NO = Gtk.ResponseType.NO

    def __init__(self, dialog_settings):
        super().__init__(
            message_type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO
        )
        self.set_markup(dialog_settings["question"])
        self.set_title(dialog_settings["title"])
        self.result = self.run()
        self.destroy()

class DirectoryDialog(Gtk.FileChooserDialog):
    """Ask the user to select a directory."""

    def __init__(self, message, parent=None):
        super().__init__(
            title=message,
            action=Gtk.FileChooserAction.SELECT_FOLDER,
            buttons=("_Cancel", Gtk.ResponseType.CLOSE, "_OK", Gtk.ResponseType.OK),
            parent=parent,
        )
        self.result = self.run()
        self.folder = self.get_current_folder()
        self.destroy()

class FileDialog(Gtk.FileChooserDialog):
    """Ask the user to select a file."""

    def __init__(self, message=None, default_path=None):
        self.filename = None
        if not message:
            message = "Please choose a file"
        super().__init__(
            message,
            None,
            Gtk.FileChooserAction.OPEN,
            ("_Cancel", Gtk.ResponseType.CANCEL, "_OK", Gtk.ResponseType.OK),
        )
        if default_path and os.path.exists(default_path):
            self.set_current_folder(default_path)
        self.set_local_only(False)
        response = self.run()
        if response == Gtk.ResponseType.OK:
            self.filename = self.get_filename()

        self.destroy()

class InstallOrPlayDialog(Gtk.Dialog):
    def __init__(self, game_name):
        Gtk.Dialog.__init__(self, "%s is already installed" % game_name)
        self.connect("delete-event", lambda *x: self.destroy())

        self.action = "play"
        self.action_confirmed = False

        self.set_size_request(320, 120)
        self.set_border_width(12)
        vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 6)
        self.get_content_area().add(vbox)

        play_button = Gtk.RadioButton.new_with_label_from_widget(None, "Launch game")
        play_button.connect("toggled", self.on_button_toggled, "play")
        vbox.pack_start(play_button, False, False, 0)
        install_button = Gtk.RadioButton.new_from_widget(play_button)
        install_button.set_label("Install the game again")
        install_button.connect("toggled", self.on_button_toggled, "install")
        vbox.pack_start(install_button, False, False, 0)

        confirm_button = Gtk.Button("OK")
        confirm_button.connect("clicked", self.on_confirm)
        vbox.pack_start(confirm_button, False, False, 0)

        self.show_all()
        self.run()

    def on_button_toggled(self, button, action):
        logger.debug("Action set to %s", action)
        self.action = action

    def on_confirm(self, button):
        logger.debug("Action %s confirmed", self.action)
        self.action_confirmed = True
        self.destroy()

class RuntimeUpdateDialog(Gtk.Dialog):
    """Dialog showing the progress of ongoing runtime update."""

    def __init__(self, parent=None):
        Gtk.Dialog.__init__(self, "Runtime updating", parent=parent)
        self.set_size_request(360, 104)
        self.set_border_width(12)
        progress_box = Gtk.Box()
        self.progressbar = Gtk.ProgressBar()
        self.progressbar.set_margin_top(40)
        self.progressbar.set_margin_bottom(40)
        self.progressbar.set_margin_right(20)
        self.progressbar.set_margin_left(20)
        progress_box.pack_start(self.progressbar, True, True, 0)
        self.get_content_area().add(progress_box)
        GLib.timeout_add(200, self.on_runtime_check)
        self.show_all()

    def on_runtime_check(self, *args, **kwargs):
        self.progressbar.pulse()
        if not runtime.is_updating():
            self.response(Gtk.ResponseType.OK)
            self.destroy()
            return False
        return True

class PgaSourceDialog(GtkBuilderDialog):
    glade_file = "dialog-pga-sources.ui"
    dialog_object = "pga_dialog"

    def __init__(self, parent=None):
        super(PgaSourceDialog, self).__init__(parent=parent)

        # GtkBuilder Objects
        self.sources_selection = self.builder.get_object("sources_selection")
        self.sources_treeview = self.builder.get_object("sources_treeview")
        self.remove_source_button = self.builder.get_object("remove_source_button")

        # Treeview setup
        self.sources_liststore = Gtk.ListStore(str)
        renderer = Gtk.CellRendererText()
        renderer.set_padding(4, 10)
        uri_column = Gtk.TreeViewColumn("URI", renderer, text=0)
        self.sources_treeview.append_column(uri_column)
        self.sources_treeview.set_model(self.sources_liststore)
        sources = pga.read_sources()
        for index, source in enumerate(sources):
            self.sources_liststore.append((source,))

        self.remove_source_button.set_sensitive(False)
        self.dialog.show_all()

    @property
    def sources_list(self):
        return [source[0] for source in self.sources_liststore]

    def on_apply(self, widget, data=None):
        pga.write_sources(self.sources_list)
        self.on_close(widget, data)

    def on_add_source_button_clicked(self, widget, data=None):
        chooser = Gtk.FileChooserDialog(
            "Select directory",
            self.dialog,
            Gtk.FileChooserAction.SELECT_FOLDER,
            ("_Cancel", Gtk.ResponseType.CANCEL, "_OK", Gtk.ResponseType.OK),
        )
        chooser.set_local_only(False)
        response = chooser.run()
        if response == Gtk.ResponseType.OK:
            uri = chooser.get_uri()
            if uri not in self.sources_list:
                self.sources_liststore.append((uri,))
        chooser.destroy()

    def on_remove_source_button_clicked(self, widget, data=None):
        """Remove a source."""
        (model, treeiter) = self.sources_selection.get_selected()
        if treeiter:
            # TODO : Add confirmation
            model.remove(treeiter)

    def on_sources_selection_changed(self, widget, data=None):
        """Set sentivity of remove source button."""
        (model, treeiter) = self.sources_selection.get_selected()
        self.remove_source_button.set_sensitive(treeiter is not None)

class ClientLoginDialog(GtkBuilderDialog):
    glade_file = "dialog-lutris-login.ui"
    dialog_object = "lutris-login"
    __gsignals__ = {
        "connected": (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT,)),
        "cancel": (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT,)),
    }

    def __init__(self, parent):
        super().__init__(parent=parent)

        self.parent = parent
        self.username_entry = self.builder.get_object("username_entry")
        self.password_entry = self.builder.get_object("password_entry")

        cancel_button = self.builder.get_object("cancel_button")
        cancel_button.connect("clicked", self.on_close)


#
# Copyright (C) 2018  Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.  You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Vendula Poncova <vponcova@redhat.com>
#
import os
import tempfile
import unittest
import pytest

from textwrap import dedent
from unittest.mock import patch
from blivet.size import Size
from pykickstart.constants import AUTOPART_TYPE_BTRFS

from pyanaconda.modules.storage.partitioning.automatic.utils import get_default_partitioning
from pyanaconda.modules.storage.partitioning.specification import PartSpec
from pyanaconda.core.configuration.anaconda import AnacondaConfiguration
from pyanaconda.core.configuration.base import ConfigurationError, create_parser, read_config
from pyanaconda.core.configuration.profile import ProfileLoader

PROFILE_DIR = os.path.join(os.environ.get("ANACONDA_DATA"), "profile.d")

SERVER_PARTITIONING = [
    PartSpec(
        mountpoint="/",
        size=Size("2GiB"),
        max_size=Size("15GiB"),
        grow=True,
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    )
]

WORKSTATION_PARTITIONING = [
    PartSpec(
        mountpoint="/",
        size=Size("1GiB"),
        max_size=Size("70GiB"),
        grow=True,
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/home",
        size=Size("500MiB"), grow=True,
        required_space=Size("50GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True
    ),
]

WORKSTATIONPLUS_PARTITIONING = WORKSTATION_PARTITIONING + [
    PartSpec(
        mountpoint="/var",
        # size=Size("15GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
        schemes={AUTOPART_TYPE_BTRFS}
    ),
]

ENTERPRISE_PARTITIONING = [
    PartSpec(
        mountpoint="/",
        size=Size("1GiB"),
        max_size=Size("70GiB"),
        grow=True,
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/home",
        size=Size("500MiB"), grow=True,
        required_space=Size("50GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True
    ),
    PartSpec(
        fstype="swap",
        lv=True,
        encrypted=True
    ),
]

VIRTUALIZATION_PARTITIONING = [
    PartSpec(
        mountpoint="/",
        size=Size("6GiB"),
        grow=True,
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/home",
        size=Size("1GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/tmp",
        size=Size("1GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/var",
        size=Size("5GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/var/crash",
        size=Size("10GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/var/log",
        size=Size("8GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/var/log/audit",
        size=Size("2GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        mountpoint="/var/tmp",
        size=Size("10GiB"),
        btr=True,
        lv=True,
        thin=True,
        encrypted=True,
    ),
    PartSpec(
        fstype="swap",
        lv=True,
        encrypted=True,
    )
]

class ProfileConfigurationTestCase(unittest.TestCase):
    """Test the default profile configurations."""

    def setUp(self):
        """Set up the default loader."""
        self.maxDiff = None
        self._loader = ProfileLoader()
        self._loader.load_profiles(PROFILE_DIR)

    def _load_profile(self, content):
        """Load a profile configuration with the given content."""
        with tempfile.NamedTemporaryFile("w") as f:
            f.write(content)
            f.flush()

            self._loader.load_profile(f.name)
            return f.name

    def _check_profile(self, profile_id, file_paths):
        """Check a profile."""
        assert self._loader.check_profile(profile_id)
        assert self._loader.collect_configurations(profile_id) == file_paths

    def _check_detection(self, profile_id, os_id, variant_id):
        """Check the profile detection."""
        assert self._loader.detect_profile(os_id, variant_id) == profile_id

    def _check_partitioning(self, config, partitioning):
        with patch("pyanaconda.modules.storage.partitioning.automatic.utils.platform") as platform:
            platform.partitions = []

            with patch("pyanaconda.modules.storage.partitioning.automatic.utils.conf", new=config):
                default = get_default_partitioning()
                print("Default: " + repr(default))
                print("Supplied: " + repr(partitioning))
                assert default == partitioning

    def _check_default_profile(self, profile_id, os_release_values, file_names, partitioning):
        """Check a default profile."""
        paths = [os.path.join(PROFILE_DIR, path) for path in file_names]
        self._check_profile(profile_id, paths)

        config = AnacondaConfiguration.from_defaults()
        paths = self._loader.collect_configurations(profile_id)

        for path in paths:
            config.read(path)

        config.validate()

        self._check_detection(profile_id, *os_release_values)
        self._check_partitioning(config, partitioning)
        assert "{}.conf".format(profile_id) == file_names[-1]

    def _get_config(self, profile_id):
        """Get parsed config file."""
        config = AnacondaConfiguration.from_defaults()
        paths = self._loader.collect_configurations(profile_id)

        for path in paths:
            config.read(path)

        config.validate()

        return config

    def test_fedora_profiles(self):
        self._check_default_profile(
            "fedora",
            ("fedora", ""),
            ["fedora.conf"],
            WORKSTATION_PARTITIONING
        )
        self._check_default_profile(
            "fedora-server",
            ("fedora", "server"),
            ["fedora.conf", "fedora-server.conf"],
            SERVER_PARTITIONING
        )
        self._check_default_profile(
            "fedora-workstation",
            ("fedora", "workstation"),
            ["fedora.conf", "fedora-workstation.conf"],
            WORKSTATION_PARTITIONING
        )
        self._check_default_profile(
            "fedora-silverblue",
            ("fedora", "silverblue"),
            ["fedora.conf", "fedora-workstation.conf", "fedora-silverblue.conf"],
            WORKSTATIONPLUS_PARTITIONING
        )
        self._check_default_profile(
            "fedora-kde",
            ("fedora", "kde"),
            ["fedora.conf", "fedora-kde.conf"],
            WORKSTATION_PARTITIONING
        )
        self._check_default_profile(
            "fedora-kinoite",
            ("fedora", "kinoite"),
            ["fedora.conf", "fedora-kde.conf", "fedora-kinoite.conf"],
            WORKSTATIONPLUS_PARTITIONING
        )
        self._check_default_profile(
            "fedora-iot",
            ("fedora", "iot"),
            ["fedora.conf", "fedora-iot.conf"],
            WORKSTATION_PARTITIONING
        )
        self._check_default_profile(
            "fedora-eln",
            ("fedora", "eln"),
            ["rhel.conf", "fedora-eln.conf"],
            ENTERPRISE_PARTITIONING
        )

    def test_rhel_profiles(self):
        self._check_default_profile(
            "rhel",
            ("rhel", ""),
            ["rhel.conf"],
            ENTERPRISE_PARTITIONING
        )
        self._check_default_profile(
            "centos",
            ("centos", ""),
            ["rhel.conf", "centos.conf"],
            ENTERPRISE_PARTITIONING
        )
        self._check_default_profile(
            "rhvh",
            ("rhel", "ovirt-node"),
            ["rhel.conf", "rhvh.conf"],
            VIRTUALIZATION_PARTITIONING
        )
        self._check_default_profile(
            "ovirt",
            ("centos", "ovirt-node"),
            ["rhel.conf", "centos.conf", "ovirt.conf"],
            VIRTUALIZATION_PARTITIONING
        )
        self._check_default_profile(
            "scientific-linux",
            ("scientific", ""),
            ["rhel.conf", "scientific-linux.conf"],
            ENTERPRISE_PARTITIONING
        )
        self._check_default_profile(
            "almalinux",
            ("almalinux", ""),
            ["rhel.conf", "almalinux.conf"],
            ENTERPRISE_PARTITIONING
        )
        self._check_default_profile(
            "rocky",
            ("rocky", ""),
            ["rhel.conf", "rocky.conf"],
            ENTERPRISE_PARTITIONING
        )

    def _compare_profile_files(self, file_name, other_file_name, ignored_sections=()):
        parser = create_parser()
        read_config(parser, os.path.join(PROFILE_DIR, file_name))

        other_parser = create_parser()
        read_config(other_parser, os.path.join(PROFILE_DIR, other_file_name))

        # Ignore the specified and profile-related sections.
        ignored_sections += ("Profile", "Profile Detection")

        sections = set(parser.sections()).difference(ignored_sections)
        other_sections = set(other_parser.sections()).difference(ignored_sections)

        # Otherwise, the defined sections should be the same.
        assert sections == other_sections

        for section in sections:
            # The defined options should be the same.
            assert parser.options(section) == other_parser.options(section)

            for key in parser.options(section):
                # The values of the options should be the same.
                assert parser.get(section, key) == other_parser.get(section, key)

    def test_ovirt_and_rhvh(self):
        """Test the similarity of oVirt Node Next with Red Hat Virtualization Host."""
        self._compare_profile_files("rhvh.conf", "ovirt.conf", ignored_sections=("License", ))

    def test_valid_profile(self):
        content = dedent("""
        [Profile]
        profile_id = custom-profile
        """)

        base_path = self._load_profile(content)
        self._check_profile("custom-profile", [base_path])

        content = dedent("""
        [Profile]
        profile_id = another-profile
        base_profile = custom-profile
        """)


#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2013-2015 - Juergen Riegel <FreeCAD@juergen-riegel.net> *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   This program is distributed in the hope that it will be useful,       *
#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
#*   GNU Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

__title__ = "Result Control Task Panel"
__author__ = "Juergen Riegel"
__url__ = "http://www.freecadweb.org"

import FreeCAD
from FemTools import FemTools

if FreeCAD.GuiUp:
    import FreeCADGui
    import FemGui
    from PySide import QtCore, QtGui
    from PySide.QtCore import Qt
    from PySide.QtGui import QApplication

class _ResultControlTaskPanel:
    '''The control for the displacement post-processing'''
    def __init__(self):
        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/ShowDisplacement.ui")

        #Connect Signals and Slots
        QtCore.QObject.connect(self.form.rb_none, QtCore.SIGNAL("toggled(bool)"), self.none_selected)
        QtCore.QObject.connect(self.form.rb_x_displacement, QtCore.SIGNAL("toggled(bool)"), self.x_displacement_selected)
        QtCore.QObject.connect(self.form.rb_y_displacement, QtCore.SIGNAL("toggled(bool)"), self.y_displacement_selected)
        QtCore.QObject.connect(self.form.rb_z_displacement, QtCore.SIGNAL("toggled(bool)"), self.z_displacement_selected)
        QtCore.QObject.connect(self.form.rb_abs_displacement, QtCore.SIGNAL("toggled(bool)"), self.abs_displacement_selected)
        QtCore.QObject.connect(self.form.rb_vm_stress, QtCore.SIGNAL("toggled(bool)"), self.vm_stress_selected)

        QtCore.QObject.connect(self.form.cb_show_displacement, QtCore.SIGNAL("clicked(bool)"), self.show_displacement)
        QtCore.QObject.connect(self.form.hsb_displacement_factor, QtCore.SIGNAL("valueChanged(int)"), self.hsb_disp_factor_changed)
        QtCore.QObject.connect(self.form.sb_displacement_factor, QtCore.SIGNAL("valueChanged(int)"), self.sb_disp_factor_changed)
        QtCore.QObject.connect(self.form.sb_displacement_factor_max, QtCore.SIGNAL("valueChanged(int)"), self.sb_disp_factor_max_changed)

        self.update()
        self.restore_result_dialog()

    def restore_result_dialog(self):
        try:
            rt = FreeCAD.FEM_dialog["results_type"]
            if rt == "None":
                self.form.rb_none.setChecked(True)
                self.none_selected(True)
            elif rt == "Uabs":
                self.form.rb_abs_displacement.setChecked(True)
                self.abs_displacement_selected(True)
            elif rt == "U1":
                self.form.rb_x_displacement.setChecked(True)
                self.x_displacement_selected(True)
            elif rt == "U2":
                self.form.rb_y_displacement.setChecked(True)
                self.y_displacement_selected(True)
            elif rt == "U3":
                self.form.rb_z_displacement.setChecked(True)
                self.z_displacement_selected(True)
            elif rt == "Sabs":
                self.form.rb_vm_stress.setChecked(True)
                self.vm_stress_selected(True)

            sd = FreeCAD.FEM_dialog["show_disp"]
            self.form.cb_show_displacement.setChecked(sd)
            self.show_displacement(sd)

            df = FreeCAD.FEM_dialog["disp_factor"]
            dfm = FreeCAD.FEM_dialog["disp_factor_max"]
            self.form.hsb_displacement_factor.setMaximum(dfm)
            self.form.hsb_displacement_factor.setValue(df)
            self.form.sb_displacement_factor_max.setValue(dfm)
            self.form.sb_displacement_factor.setValue(df)
        except:
            FreeCAD.FEM_dialog = {"results_type": "None", "show_disp": False,
                                  "disp_factor": 0, "disp_factor_max": 100}

    def getStandardButtons(self):
        return int(QtGui.QDialogButtonBox.Close)

    def get_result_stats(self, type_name, analysis=None):
        if analysis is None:
            analysis = FemGui.getActiveAnalysis()
        for i in analysis.Member:
            if (i.isDerivedFrom("Fem::FemResultObject")) and ("Stats" in i.PropertiesList):
                match_table = {"U1": (i.Stats[0], i.Stats[1], i.Stats[2]),
                               "U2": (i.Stats[3], i.Stats[4], i.Stats[5]),
                               "U3": (i.Stats[6], i.Stats[7], i.Stats[8]),
                               "Uabs": (i.Stats[9], i.Stats[10], i.Stats[11]),
                               "Sabs": (i.Stats[12], i.Stats[13], i.Stats[14]),
                               "None": (0.0, 0.0, 0.0)}
                return match_table[type_name]
        return (0.0, 0.0, 0.0)

    def none_selected(self, state):
        FreeCAD.FEM_dialog["results_type"] = "None"
        self.set_result_stats("mm", 0.0, 0.0, 0.0)
        fea = FemTools()
        fea.reset_mesh_color()

    def abs_displacement_selected(self, state):
        FreeCAD.FEM_dialog["results_type"] = "Uabs"
        self.select_displacement_type("Uabs")

    def x_displacement_selected(self, state):
        FreeCAD.FEM_dialog["results_type"] = "U1"
        self.select_displacement_type("U1")

    def y_displacement_selected(self, state):
        FreeCAD.FEM_dialog["results_type"] = "U2"
        self.select_displacement_type("U2")

    def z_displacement_selected(self, state):
        FreeCAD.FEM_dialog["results_type"] = "U3"
        self.select_displacement_type("U3")

    def vm_stress_selected(self, state):
        FreeCAD.FEM_dialog["results_type"] = "Sabs"
        QApplication.setOverrideCursor(Qt.WaitCursor)
        if self.suitable_results:
            self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.NodeNumbers, self.result_object.StressValues)
        (minm, avg, maxm) = self.get_result_stats("Sabs")
        self.set_result_stats("MPa", minm, avg, maxm)
        QtGui.qApp.restoreOverrideCursor()

    def select_displacement_type(self, disp_type):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        if disp_type == "Uabs":
            if self.suitable_results:
                self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.NodeNumbers, self.result_object.DisplacementLengths)
        else:
            match = {"U1": 0, "U2": 1, "U3": 2}
            d = zip(*self.result_object.DisplacementVectors)
            displacements = list(d[match[disp_type]])
            if self.suitable_results:
                self.MeshObject.ViewObject.setNodeColorByScalars(self.result_object.NodeNumbers, displacements)
        (minm, avg, maxm) = self.get_result_stats(disp_type)
        self.set_result_stats("mm", minm, avg, maxm)
        QtGui.qApp.restoreOverrideCursor()

    def set_result_stats(self, unit, minm, avg, maxm):
        self.form.le_min.setProperty("unit", unit)
        self.form.le_min.setText("{:.6} {}".format(minm, unit))
        self.form.le_avg.setProperty("unit", unit)
        self.form.le_avg.setText("{:.6} {}".format(avg, unit))
        self.form.le_max.setProperty("unit", unit)
        self.form.le_max.setText("{:.6} {}".format(maxm, unit))

    def update_displacement(self, factor=None):
        if factor is None:
            if FreeCAD.FEM_dialog["show_disp"]:
                factor = self.form.hsb_displacement_factor.value()
            else:
                factor = 0.0
        self.MeshObject.ViewObject.applyDisplacement(factor)

    def show_displacement(self, checked):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        FreeCAD.FEM_dialog["show_disp"] = checked
        if "result_object" in FreeCAD.FEM_dialog:
            if FreeCAD.FEM_dialog["result_object"] != self.result_object:
                self.update_displacement()
        FreeCAD.FEM_dialog["result_object"] = self.result_object
        if self.suitable_results:
            self.MeshObject.ViewObject.setNodeDisplacementByVectors(self.result_object.NodeNumbers, self.result_object.DisplacementVectors)
        self.update_displacement()
        QtGui.qApp.restoreOverrideCursor()

    def hsb_disp_factor_changed(self, value):
        self.form.sb_displacement_factor.setValue(value)
        self.update_displacement()

    def sb_disp_factor_max_changed(self, value):
        FreeCAD.FEM_dialog["disp_factor_max"] = value
        self.form.hsb_displacement_factor.setMaximum(value)

    def sb_disp_factor_changed(self, value):
        FreeCAD.FEM_dialog["disp_factor"] = value
        self.form.hsb_displacement_factor.setValue(value)

    def update(self):
        self.MeshObject = None
        self.result_object = get_results_object(FreeCADGui.Selection.getSelection())


# test_nsdfreader.py ---
#
# Filename: test_nsdfreader.py
# Description:
# Author: Subhasis Ray
# Maintainer:
# Created: Sat Aug  9 15:26:14 2014 (+0530)
# Version:
# Last-Updated:
#           By:
#     Update #: 0
# URL:
# Keywords:
# Compatibility:
#
#

# Commentary:
#
#
#
#

# Change log:
#
#
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth
# Floor, Boston, MA 02110-1301, USA.
#
#

# Code:
"""Test the reading of NSDF file in Python"""

import sys
from collections import defaultdict
import itertools as it
import numpy as np
from numpy import testing as nptest
import h5py as h5
from datetime import datetime
import unittest
import os

sys.path.append('..')

import nsdf

from util import *

def create_test_data_file(filename, dialect):
    """Create a datafile at path `filename` using dialect `dialect`.

    """
    tstart = datetime.now()
    mdict = create_ob_model_tree()
    uniform_data = nsdf.UniformData('Vm', unit='mV', field='Vm',
                                    dt=1e-2, tunit='ms')
    for cell in mdict['granule_cells']:
        uniform_data.put_data(cell.children['gc_0'].uid, np.random.uniform(-63, -57, 100))

    if dialect == nsdf.dialect.NUREGULAR:
        size = 150
        nonuniform_data = nsdf.NonuniformRegularData('Im', unit='pA', field='Im', tunit='ms')
        nonuniform_data.set_times(np.cumsum(np.random.rand(size)))
        for ii, cell in enumerate(mdict['mitral_cells']):
            nonuniform_data.put_data(cell.children['mc_0'].uid,
                                     np.random.rand(size))
    else:
        nonuniform_data = nsdf.NonuniformData('Im', unit='pA', field='Im', tunit='ms', dtype=np.float32)
        sizes = 150 + np.random.randint(-50, 50, len(mdict['mitral_cells']))
        for ii, cell in enumerate(mdict['mitral_cells']):
            data = np.random.rand(sizes[ii])
            times = np.cumsum(np.random.rand(sizes[ii]))
            assert len(data) == len(times)
            nonuniform_data.put_data(cell.children['mc_0'].uid,
                                     (data, times))
    sizes = 200 + np.random.randint(-50, 50, len(mdict['cells']))
    event_data = nsdf.EventData('spike', unit='ms', dtype=np.float32)
    for ii, cell in enumerate(mdict['cells']):
        times = np.cumsum(np.random.exponential(scale=0.01, size=sizes[ii]))
        event_data.put_data(cell.uid, times)
    writer = nsdf.NSDFWriter(filename, dialect=dialect, mode='w')
    writer.add_modeltree(mdict['model_tree'])
    uniform_ds = writer.add_uniform_ds('granule', uniform_data.get_sources())
    writer.add_uniform_data(uniform_ds, uniform_data)

    if dialect == nsdf.dialect.ONED:
        nonuniform_ds = writer.add_nonuniform_ds_1d(
            'mitral', 'Im',
            nonuniform_data.get_sources())
    else:
        nonuniform_ds = writer.add_nonuniform_ds('mitral',
                                                 nonuniform_data.get_sources())
    if (dialect == nsdf.dialect.ONED) or (dialect == nsdf.dialect.NUREGULAR):
        event_ds = writer.add_event_ds_1d('cells', 'spike',
                                          event_data.get_sources())
    else:
        event_ds = writer.add_event_ds('cells', event_data.get_sources())
    if dialect == nsdf.dialect.ONED:
        writer.add_nonuniform_1d(nonuniform_ds, nonuniform_data)
        writer.add_event_1d(event_ds, event_data)
    elif dialect == nsdf.dialect.NUREGULAR:
        writer.add_nonuniform_regular(nonuniform_ds, nonuniform_data)
        writer.add_event_1d(event_ds, event_data)
    elif dialect == nsdf.dialect.VLEN:
        writer.add_nonuniform_vlen(nonuniform_ds, nonuniform_data)
        writer.add_event_vlen(event_ds, event_data)
    elif dialect == nsdf.dialect.NANPADDED:
        writer.add_nonuniform_nan(nonuniform_ds, nonuniform_data)
        writer.add_event_nan(event_ds, event_data)
    else:
        raise Exception('unknown dialect: {}'.format(dialect))
    tend = datetime.now()
    description = 'Testing nsdf reader'
    title = 'NSDFReader.test'
    creator = ['Subhasis Ray']
    contributor = ['Chaitanya Chintaluri', 'Daniel Wojcik', 'Upinder Bhalla']
    software = ['Python']
    method = ['manual']
    license = 'CC-BY-SA'
    rights = 'Subhasis Ray, 2014'
    writer.tstart = tstart
    writer.tend = tend
    writer.title = title
    writer.creator = creator
    writer.description = description
    writer.contributor = contributor
    writer.software = software
    writer.method = method
    writer.rights = rights
    writer.license = license
    return {'uniform_data': uniform_data,
            'nonuniform_data': nonuniform_data,
            'event_data': event_data,
            'title': title,
            'creator': creator,
            'contributor': contributor,
            'software': software,
            'tstart': tstart,
            'tend': tend,
            'description': description,
            'method': method,
            'rights': rights,
            'license': license,
    }

class TestNSDFReaderOneD(unittest.TestCase):
    """Check that file written in ONED dialect is read correctly"""
    def setUp(self):
        self.filename = '{}.h5'.format(self.id())
        self.data_dict = create_test_data_file(self.filename,
                                               nsdf.dialect.ONED)

    def test_get_uniform_data(self):
        reader = nsdf.NSDFReader(self.filename)
        file_data = reader.get_uniform_data('granule', 'Vm')
        data = self.data_dict['uniform_data']
        self.assertEqual(set(file_data.get_sources()),
                         set(data.get_sources()))
        self.assertEqual(data.unit, file_data.unit)
        self.assertEqual(data.name, file_data.name)
        self.assertEqual(data.tunit, file_data.tunit)
        self.assertAlmostEqual(data.dt, file_data.dt)
        for src in data.get_sources():
            np.testing.assert_allclose(data.get_data(src),
                                       file_data.get_data(src))

    def test_get_uniform_ts(self):
        raise NotImplementedError('Fix me')

    def test_get_nonuniform_ts(self):
        raise NotImplementedError('Fix me')

    def test_get_nonuniform_data(self):
        data = self.data_dict['nonuniform_data']
        reader = nsdf.NSDFReader(self.filename)
        file_data = reader.get_nonuniform_data('mitral', 'Im')
        self.assertEqual(set(file_data.get_sources()),
                         set(data.get_sources()))
        self.assertEqual(data.unit, file_data.unit)
        self.assertEqual(data.name, file_data.name)
        self.assertEqual(data.tunit, file_data.tunit)
        for src in data.get_sources():
            var, times = data.get_data(src)
            fvar, ftimes = file_data.get_data(src)
            np.testing.assert_allclose(var, fvar)
            np.testing.assert_allclose(times, ftimes)

    def test_get_event_data(self):
        data = self.data_dict['event_data']
        reader = nsdf.NSDFReader(self.filename)
        file_data = reader.get_event_data('cells', 'spike')
        self.assertEqual(set(file_data.get_sources()),
                         set(data.get_sources()))
        self.assertEqual(data.unit, file_data.unit)
        self.assertEqual(data.name, file_data.name)
        for src in data.get_sources():
            var = data.get_data(src)
            fvar = file_data.get_data(src)
            np.testing.assert_allclose(var, fvar)

    def test_attributes(self):
        reader = nsdf.NSDFReader(self.filename)
        self.assertEqual(reader.title, self.data_dict['title'])
        self.assertEqual(reader.description, self.data_dict['description'])
        for left, right in it.izip_longest(reader.creator,
                                           self.data_dict['creator']):
            self.assertEqual(left, right)
        for left, right in it.izip_longest(reader.contributor,
                                           self.data_dict['contributor']):
            self.assertEqual(left, right)
        for left, right in it.izip_longest(reader.software,
                                           self.data_dict['software']):
            self.assertEqual(left, right)
        for left, right in it.izip_longest(reader.method,
                                           self.data_dict['method']):
            self.assertEqual(left, right)
        self.assertEqual(reader.tstart, self.data_dict['tstart'].isoformat())
        self.assertEqual(reader.tend, self.data_dict['tend'].isoformat())
        self.assertEqual(reader.license, self.data_dict['license'])
        self.assertEqual(reader.rights, self.data_dict['rights'])

class TestNSDFReaderNAN(unittest.TestCase):
    """Check that file written in ONED dialect is read correctly"""
    def setUp(self):
        self.filename = '{}.h5'.format(self.id())
        self.data_dict = create_test_data_file(self.filename,
                                               nsdf.dialect.NANPADDED)

    def test_get_uniform_data(self):
        reader = nsdf.NSDFReader(self.filename)
        file_data = reader.get_uniform_data('granule', 'Vm')
        data = self.data_dict['uniform_data']
        self.assertEqual(set(file_data.get_sources()),
                         set(data.get_sources()))
        self.assertEqual(data.unit, file_data.unit)
        self.assertEqual(data.name, file_data.name)
        self.assertEqual(data.tunit, file_data.tunit)
        self.assertAlmostEqual(data.dt, file_data.dt)
        for src in data.get_sources():
            np.testing.assert_allclose(data.get_data(src),
                                       file_data.get_data(src))

    def test_get_uniform_ts(self):
        raise NotImplementedError('Fix me')

    def test_get_nonuniform_ts(self):
        raise NotImplementedError('Fix me')

    def test_get_nonuniform_data(self):
        data = self.data_dict['nonuniform_data']
        reader = nsdf.NSDFReader(self.filename)
        file_data = reader.get_nonuniform_data('mitral', 'Im')
        self.assertEqual(set(file_data.get_sources()),
                         set(data.get_sources()))
        self.assertEqual(data.unit, file_data.unit)
        self.assertEqual(data.name, file_data.name)
        self.assertEqual(data.tunit, file_data.tunit)
        for src in data.get_sources():
            var, times = data.get_data(src)
            fvar, ftimes = file_data.get_data(src)
            np.testing.assert_allclose(var, fvar)
            np.testing.assert_allclose(times, ftimes)

    def test_get_event_data(self):
        data = self.data_dict['event_data']
        reader = nsdf.NSDFReader(self.filename)
        file_data = reader.get_event_data('cells', 'spike')
        self.assertEqual(set(file_data.get_sources()),
                         set(data.get_sources()))
        self.assertEqual(data.unit, file_data.unit)
        self.assertEqual(data.name, file_data.name)
        for src in data.get_sources():
            var = data.get_data(src)


# -*- coding: iso-8859-1 -*-
#
#  Copyright (C) 2001 - 2020 Massimo Gerardi all rights reserved.
#
#  Author: Massimo Gerardi massimo.gerardi@gmail.com
#
#  Copyright (c) 2020 Qsistemi.com.  All rights reserved.
#
#  Viale Giorgio Ribotta, 11 (Roma)
#  00144 Roma (RM) - Italy
#  Phone: (+39) 06.87.163
#
#
#  Si veda file COPYING per le condizioni di software.
#
#   www.qsistemi.com - italy@qsistemi.com

import wx
import string
from cfg import *
import cfg

def create(parent,cnt):
    return ConsolidaOrd(parent,cnt)

class ConsolidaOrd(wx.ScrolledWindow):
    def __init__(self, prnt, cnt):
        self.win=wx.ScrolledWindow.__init__(self, parent=prnt, id=-1,size = wx.DefaultSize)
        self.SetScrollbars(1,1,100,100) #####
        self.FitInside()  ######

        png = wx.Image((cfg.path_img + "cerca19x19.png"),
              wx.BITMAP_TYPE_PNG).ConvertToBitmap()

        #wx.Frame.__init__(self, id = wx.NewId(), name = '',
        #      parent = prnt, pos = wx.Point(0, 0),
        #      style = wx.DEFAULT_FRAME_STYLE  , title = cnt[0])
        #self.SetIcon(wx.Icon(cfg.path_img+"/null.ico", wx.BITMAP_TYPE_ICO))
        #self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False))
        #self.SetClientSize(wx.Size(600, 455))
        self.ttl = cnt[0]
        self.tcpart = "C"
        self.tblart = "articoli"
        self.AggMenu = cnt[3]
        self.IDMENU = cnt[4]
        #self.font = self.GetFont()
        self.color = self.GetBackgroundColour()
        Nid = wx.NewId()
        self.__MDI__ = wx.GetApp().GetPhasisMdi()

        self.font=self.__MDI__.font
        self.SetFont(self.font)

        self.CnAz = self.__MDI__.GetConnAZ()
        self.annoc = self.__MDI__.GetAnnoC()
        self.datacon = self.__MDI__.GetDataC()
        self.dzDatiAzienda = self.__MDI__.dzDatiAzienda

        self.pnl = wx.Panel(id = wx.NewId(), name = '',
              parent = self, pos = wx.Point(0, 0),
              style = wx.SIMPLE_BORDER | wx.TAB_TRAVERSAL)
        self.pnl.SetFont(self.font)

        self.lnum_ord = wx.StaticText(self.pnl, -1, _("Numero Ordine :"),
              wx.DLG_PNT(self.pnl, 7,12))
        self.num_ord = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 65,10),
              wx.DLG_SZE(self.pnl, 60,cfg.DIMFONTDEFAULT),wx.TE_PROCESS_ENTER)
        self.cnum_ord = wx.BitmapButton(self.pnl, -1, png,#wx.Button(self.pnl, Nid, "...",
              wx.DLG_PNT(self.pnl, 130,10),
              wx.DLG_SZE(self.pnl,cfg.btnSzeSH,cfg.btnSzeV))
        self.rbFATTF2 = wx.RadioButton(self.pnl, Nid, _("Fattura Immediata"),
              wx.DLG_PNT(self.pnl, 150,5),
              wx.DLG_SZE(self.pnl, 120,10))
        self.rbFATTI1 = wx.RadioButton(self.pnl, Nid, _("Fattura Accompagnatoria"),
              wx.DLG_PNT(self.pnl, 150,15),
              wx.DLG_SZE(self.pnl, 120,10) )
        self.rbBOLL = wx.RadioButton(self.pnl, Nid, cfg.vcBOLL,
              wx.DLG_PNT(self.pnl, 150,25),
              wx.DLG_SZE(self.pnl, 120,10))
        self.sbox_cf = wx.StaticBox(self.pnl, Nid, _(' Cliente '),
              wx.DLG_PNT(self.pnl, 5,35), wx.DLG_SZE(self.pnl, 265,65))
        self.lcodcf = wx.StaticText(self.pnl, -1, _("Codice"),
              wx.DLG_PNT(self.pnl, 10,45))
        self.codcf = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 10, 55),
              wx.DLG_SZE(self.pnl, 40,cfg.DIMFONTDEFAULT),wx.TE_PROCESS_ENTER)
        self.codcf1 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 10, 55),
              wx.DLG_SZE(self.pnl, 40,cfg.DIMFONTDEFAULT))
        self.ccodcf = wx.BitmapButton(self.pnl, -1, png,#wx.Button(self.pnl, Nid, "...",
              wx.DLG_PNT(self.pnl, 55,55),
              wx.DLG_SZE(self.pnl,cfg.btnSzeSH,cfg.btnSzeV))
        self.lragsoc = wx.StaticText(self.pnl, -1, _("Cessionario :"),
              wx.DLG_PNT(self.pnl, 75,45))
        self.ragsoc1 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 75,55),
              wx.DLG_SZE(self.pnl, 120,cfg.DIMFONTDEFAULT),wx.TE_PROCESS_ENTER)
        self.cragsoc1 = wx.BitmapButton(self.pnl, -1, png,#wx.Button(self.pnl, Nid, "...",
              wx.DLG_PNT(self.pnl, 200,55),
              wx.DLG_SZE(self.pnl,cfg.btnSzeSH,cfg.btnSzeV))
        self.ragsoc3 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 75,55),
              wx.DLG_SZE(self.pnl, 120,cfg.DIMFONTDEFAULT))
        self.cragsoc3 = wx.BitmapButton(self.pnl, -1, png,#wx.Button(self.pnl, Nid, "...",
              wx.DLG_PNT(self.pnl, 200,55),
              wx.DLG_SZE(self.pnl,cfg.btnSzeSH,cfg.btnSzeV))
        self.ragsoc2 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 148, 55),
              wx.DLG_SZE(self.pnl, 100,cfg.DIMFONTDEFAULT))
        self.ragsoc4 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 148, 55),
              wx.DLG_SZE(self.pnl, 100,cfg.DIMFONTDEFAULT))
        self.lindiriz = wx.StaticText(self.pnl, -1, _("Indirizzo :"),
              wx.DLG_PNT(self.pnl, 10,72))
        self.indiriz = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 45,70),
              wx.DLG_SZE(self.pnl, 170,cfg.DIMFONTDEFAULT))
        self.cdest = wx.Button(self.pnl, Nid,  _(' Cliente '),
              wx.DLG_PNT(self.pnl, 218,70),
              wx.DLG_SZE(self.pnl,cfg.btnSzeLH,cfg.btnSzeV))
        self.rdest1 = wx.Button(self.pnl, Nid, _("Annulla"),
              wx.DLG_PNT(self.pnl, 218,55),
              wx.DLG_SZE(self.pnl,cfg.btnSzeLH,cfg.btnSzeV))
        wx.StaticText(self.pnl, -1, _("Citta' :"),
              wx.DLG_PNT(self.pnl, 10,87))
        self.zona = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 45,85),
              wx.DLG_SZE(self.pnl, 100,cfg.DIMFONTDEFAULT))
        wx.StaticText(self.pnl, -1, _("CAP :"),
              wx.DLG_PNT(self.pnl, 150,87))
        self.cap = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 180, 85),
              wx.DLG_SZE(self.pnl, 35,cfg.DIMFONTDEFAULT))
        wx.StaticText(self.pnl, -1, _("PR :"),
              wx.DLG_PNT(self.pnl, 225,87))
        self.pr = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 243, 85),
              wx.DLG_SZE(self.pnl, 20,cfg.DIMFONTDEFAULT))
        self.indiriz1 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 45,70),
              wx.DLG_SZE(self.pnl, 170,cfg.DIMFONTDEFAULT))
        self.zona1 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 45,85),
              wx.DLG_SZE(self.pnl, 100,cfg.DIMFONTDEFAULT))
        self.cap1 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 180, 85),
              wx.DLG_SZE(self.pnl, 35,cfg.DIMFONTDEFAULT))
        self.pr1 = wx.TextCtrl(self.pnl, Nid, "",
              wx.DLG_PNT(self.pnl, 243, 85),
              wx.DLG_SZE(self.pnl, 20,cfg.DIMFONTDEFAULT))
        self.localit = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 280,37))
        self.stato = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 280,37))
        self.localit1 = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 280,37))
        self.stato1 = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 280,37))
        self.data_ord = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,162))
        self.codage = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,162))
        self.vPAGAM = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,162))
        self.data_tra = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,162))
        self.ora_tra = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,162))
        self.vTIPO_DOC = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,162))
        self.vTIPO_ORD = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,162))
        self.anno = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,162))
        self.fndvTIPO_ORD = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 285,117))
        self.vdata_ord = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 285,117))
        self.lgendoc = wx.StaticText(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 7,182))
        self.lc = wx.ListCtrl(self.pnl, Nid,
              wx.DLG_PNT(self.pnl, 5,105), wx.DLG_SZE(self.pnl, 323,70),
              wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
        self.ltotale = wx.StaticText(self.pnl, -1, _("Totale Documento:"),
              wx.DLG_PNT(self.pnl, 185,182))
        #self.ltotale.SetFont(self.font)
        self.totale = wx.TextCtrl(self.pnl, Nid, "0,00",
              wx.DLG_PNT(self.pnl, 262,180),
              wx.DLG_SZE(self.pnl, 65, cfg.DIMFONTDEFAULT), wx.ALIGN_RIGHT )
        #self.totale.SetFont(self.font)
        self.stt_doc1 = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 5,160))
        self.stt_doc2 = wx.TextCtrl(self.pnl, -1, "",
              wx.DLG_PNT(self.pnl, 5,170))
        self.inte = wx.Button(self.pnl, Nid, cfg.vcint,
              wx.DLG_PNT(self.pnl, 275,10),
              wx.DLG_SZE(self.pnl,cfg.btnSzeLH,cfg.btnSzeV))
        self.canc = wx.Button(self.pnl, Nid, cfg.vccanc,
              wx.DLG_PNT(self.pnl, 275,10),
              wx.DLG_SZE(self.pnl,cfg.btnSzeLH,cfg.btnSzeV))
        self.okconf = wx.Button(self.pnl, Nid, cfg.vcconf,
              wx.DLG_PNT(self.pnl, 275,25),
              wx.DLG_SZE(self.pnl,cfg.btnSzeLH,cfg.btnSzeV))
        self.join = wx.Button(self.pnl, Nid, cfg.vcjoin,
              wx.DLG_PNT(self.pnl, 275,40),
              wx.DLG_SZE(self.pnl,cfg.btnSzeLH,cfg.btnSzeV))
        #self.SetFont(self.font)

        for x in self.pnl.GetChildren(): x.SetFont(self.font)

        #box_sizer = wx.BoxSizer(wx.VERTICAL)
       	#box_sizer.Add(self.pnl, 0, wx.EXPAND|wx.ALL,0)
        #self.SetAutoLayout(1)
        #self.SetSizer(box_sizer)
        #box_sizer.Fit(self)

        box = wx.GridSizer(1, 1)
        box.Add(self.pnl, 0, wx.ALIGN_CENTER|wx.ALL,10)
        self.SetSizer(box)
        box.Fit(self)

        self.ragsoc1.Bind(wx.EVT_TEXT_ENTER, self.FndAnag)
        self.cragsoc1.Bind(wx.EVT_BUTTON, self.FndAnag)
        self.num_ord.Bind(wx.EVT_TEXT_ENTER, self.FndOrd)
        self.cnum_ord.Bind(wx.EVT_BUTTON, self.FndOrd)
        self.canc.Bind(wx.EVT_BUTTON, self.Close)
        self.inte.Bind(wx.EVT_BUTTON, self.Start)
        self.okconf.Bind(wx.EVT_BUTTON, self.OkGDoc)
        self.join.Bind(wx.EVT_BUTTON, self.OkUnisci)
        self.rbFATTF2.Bind(wx.EVT_RADIOBUTTON, self.RadioB)
        self.rbFATTI1.Bind(wx.EVT_RADIOBUTTON, self.RadioB)
        self.rbBOLL.Bind(wx.EVT_RADIOBUTTON, self.RadioB)
        self.cdest.Bind(wx.EVT_BUTTON, self.CDest)
        self.rdest1.Bind(wx.EVT_BUTTON, self.RDest)
        self.Bind(wx.EVT_CLOSE, self.Close)

        self.Start(self)

    def Start(self, evt):
        self.lc.Show(True)
        self.lc.Enable(False)
        self.cdest.SetLabel(_('Destinatario')) ####### mettere in cfg
        self.indiriz.SetValue('')
        self.zona.SetValue('')
        self.cap.SetValue('')
        self.localit.SetValue('')
        self.pr.SetValue('--')
        self.stato.SetValue('')
        self.indiriz1.SetValue('')
        self.zona1.SetValue('')
        self.cap1.SetValue('')
        self.localit1.SetValue('')
        self.pr1.SetValue('--')
        self.stato1.SetValue('')
        self.codage.SetValue('')
        self.vPAGAM.SetValue('')
        self.ragsoc2.SetValue('')
        self.totale.SetValue('0,00')
        self.vTIPO_DOC.SetValue('B1')#str(cfg.tipodocGDoc))
        self.vTIPO_ORD.SetValue('OC')
        self.rbFATTI1.SetValue(False)
	self.rbFATTF2.SetValue(False)
        self.rbBOLL.SetValue(True)
        self.stt_doc1.SetValue('')
        self.stt_doc2.SetValue('')
        self.lgendoc.SetLabel('')
        self.codcf.SetValue('')
        self.ragsoc1.SetValue('')
        self.num_ord.SetValue('')
        self.data_tra.SetValue('')
        self.ora_tra.SetValue('00:00:00')
        self.okconf.Show(True)
        self.ragsoc1.SetFocus()
        self.canc.Show(True)
        self.canc.Enable(True)
        self.LC_clear(self)
        self.lc.Enable(False)
        self.sbox_cf.SetLabel(_(' Cliente '))
        self.ShowFalse(self)
        self.EnableFalse(self)
	self.anno.SetValue(self.annoc)
	self.rbFATTI1.Enable(True)
	self.rbFATTF2.Enable(True)
        self.rbBOLL.Enable(True)
	self.codcf.Enable(True)
	self.ccodcf.Enable(True)
	self.cragsoc1.Enable(True)
	self.ragsoc1.Enable(True)
	self.cnum_ord.Enable(True)
	self.num_ord.Enable(True)
        self.ragsoc1.SetFocus()

    def LC_clear(self, evt):
        self.lc.ClearAll()
        self.lc.InsertColumn(0, _("Codice"))
        self.lc.InsertColumn(1, _("Descrizione"))
        self.lc.InsertColumn(2, _("Q.ta`"))
        self.lc.InsertColumn(3, _("Prezzo Un"))
        self.lc.InsertColumn(4, _("Importo"))
        self.lc.InsertColumn(5, _("Iva"))
        self.lc.InsertColumn(6, _("Sc%"))
        self.lc.InsertColumn(7, _("NRiga"))
        self.lc.InsertColumn(8, "")
        self.lc.InsertColumn(9, "")
        self.lc.InsertColumn(10, "")
        self.lc.InsertColumn(11, "")
        self.lc.InsertColumn(12, "")
        self.lc.InsertColumn(13, "")
        self.lc.InsertColumn(14, "")
        self.lc.InsertColumn(15, "")
        self.lc.InsertColumn(16, "")
        self.lc.InsertColumn(17, "")
        self.lc.InsertColumn(18, "")
        self.lc.InsertColumn(19, "")
        self.lc.InsertColumn(20, "")
        self.lc.InsertColumn(21, "")
        self.lc.InsertColumn(22, "")
        self.lc.InsertColumn(23, "")
        self.lc.InsertColumn(24, "")
        self.lc.InsertColumn(25, "")
        self.lc.InsertColumn(26, "")
        self.lc.InsertColumn(27, "")
        self.lc.InsertColumn(28, "")
        self.lc.InsertColumn(29, "")
        self.lc.InsertColumn(30, "")
        self.lc.InsertColumn(31, "")
        self.lc.InsertColumn(32, "")
        self.lc.InsertColumn(33, "")
        #self.lc.InsertColumn(34, "")
        self.lc.SetColumnWidth(0, wx.DLG_SZE(self.pnl, 60,-1).width)
        self.lc.SetColumnWidth(1, wx.DLG_SZE(self.pnl, 150,-1).width)
        self.lc.SetColumnWidth(2, wx.DLG_SZE(self.pnl, 40,-1).width)
        self.lc.SetColumnWidth(3, wx.DLG_SZE(self.pnl, 80,-1).width)
        self.lc.SetColumnWidth(4, wx.DLG_SZE(self.pnl, 80,-1).width)
        self.lc.SetColumnWidth(5, wx.DLG_SZE(self.pnl,  40,-1).width)
        self.lc.SetColumnWidth(6, wx.DLG_SZE(self.pnl, 40,-1).width)
        self.lc.SetColumnWidth(7, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(8, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(9, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(10, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(11, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(12, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(13, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(14, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(15, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(16, wx.DLG_SZE(self.pnl,  0,-1).width)
        self.lc.SetColumnWidth(17, wx.DLG_SZE(self.pnl,  0,-1).width)
        self.lc.SetColumnWidth(18, wx.DLG_SZE(self.pnl,  0,-1).width)
        self.lc.SetColumnWidth(19, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(20, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(21, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(22, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(23, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(24, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(25, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(26, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(27, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(28, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(29, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(30, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(31, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(32, wx.DLG_SZE(self.pnl, 0,-1).width)
        self.lc.SetColumnWidth(33, wx.DLG_SZE(self.pnl, 0,-1).width)
        #self.lc.SetColumnWidth(34, wx.DLG_SZE(self.pnl, 0,-1).width)
        #self.lc.SetFont(self.font)
        self.lc.SetBackgroundColour(self.color)

    def ShowFalse(self, evt):
        self.ragsoc3.Show(False)
        self.ragsoc4.Show(False)
        self.cragsoc3.Show(False)
        self.localit1.Show(False)
        self.stato1.Show(False)
        self.localit.Show(False)
        self.stato.Show(False)
        self.indiriz1.Show(False)
        self.cap1.Show(False)
        self.zona1.Show(False)
        self.pr1.Show(False)
        self.codcf1.Show(False)
        self.ragsoc2.Show(False)
        self.ragsoc4.Show(False)
        self.data_ord.Show(False)
        self.vTIPO_DOC.Show(False)
        self.vTIPO_ORD.Show(False)
        self.fndvTIPO_ORD.Show(False)
	self.vdata_ord.Show(False)
        self.anno.Show(False)
        self.codage.Show(False)
        self.vPAGAM.Show(False)
        self.inte.Show(False)
        self.data_tra.Show(False)
        self.ora_tra.Show(False)
        self.stt_doc2.Show(False)
        self.stt_doc1.Show(False)

    def EnableFalse(self, evt):
        self.cdest.Enable(False)
        self.rdest1.Enable(False)
        self.indiriz1.Enable(False)
        self.zona1.Enable(False)
        self.pr1.Enable(False)
        self.cap1.Enable(False)
        self.localit1.Enable(False)
        self.stato1.Enable(False)
        self.indiriz.Enable(False)
        self.zona.Enable(False)
        self.pr.Enable(False)
        self.cap.Enable(False)
        self.localit.Enable(False)
        self.stato.Enable(False)
        self.ragsoc3.Enable(False)
        self.ragsoc4.Enable(False)
        self.codcf1.Enable(False)
        self.codage.Enable(False)
        self.vPAGAM.Enable(False)
        self.totale.Enable(False)
        self.vTIPO_DOC.Enable(False)
        self.stt_doc1.Enable(False)
        self.stt_doc2.Enable(False)
        self.okconf.Enable(False)
        self.inte.Enable(False)
        self.join.Enable(False)

    def CDest(self, evt):
        if self.cdest.GetLabel()== _('Destinatario'):
            self.cdest.SetLabel(_(' Cliente '))
            self.sbox_cf.SetLabel(_(' Destinatario '))
            self.lragsoc.SetLabel(_("Destinazione merce :"))
            self.codcf.Show(False)
            self.codcf1.Show(True)
            self.ragsoc1.Show(False)
            self.cragsoc1.Show(False)
            self.indiriz1.Show(True)
            self.ragsoc3.Show(True)
            self.ragsoc3.Enable(True)
            self.cragsoc3.Show(True)
            self.cap1.Show(True)
            self.zona1.Show(True)
            self.pr1.Show(True)
            self.indiriz.Show(False)
            self.cap.Show(False)
            self.zona.Show(False)
            self.pr.Show(False)
            self.rdest1.Enable(True)
            self.ragsoc3.SetFocus()
        else:
            self.cdest.SetLabel(_('Destinatario'))
            self.sbox_cf.SetLabel(_(' Cliente '))
            self.lragsoc.SetLabel(_("Cessionario :"))
            self.codcf.Show(True)
            self.codcf1.Show(False)
            self.ragsoc1.Show(True)
            self.cragsoc1.Show(True)
            self.indiriz1.Show(True)
            self.ragsoc3.Show(False)
            self.ragsoc3.Enable(False)
            self.cragsoc3.Show(False)
            self.indiriz.Show(True)
            self.cap.Show(True)
            self.zona.Show(True)
            self.pr.Show(True)
            self.indiriz1.Show(False)
            self.cap1.Show(False)
            self.zona1.Show(False)
            self.pr1.Show(False)
            self.rdest1.Enable(False)
            self.ragsoc1.SetFocus()

    def RDest(self, evt):
        self.ragsoc3.SetValue('')
        self.ragsoc4.SetValue('')
        self.indiriz1.SetValue('')
        self.zona1.SetValue('')
        self.localit1.SetValue('')
        self.cap1.SetValue('')
        self.pr1.SetValue('')
        self.stato1.SetValue('')
        self.codcf1.SetValue('')
        self.ragsoc3.SetFocus()

    def RadioB(self, evt):
	if self.rbFATTF2.GetValue()==True:
            self.vTIPO_DOC.SetValue("F2")
            self.rbFATTI1.SetValue(False)
	    self.rbFATTF2.SetValue(True)
            self.rbBOLL.SetValue(False)
	    self.stt_doc1.SetValue('E')
            self.stt_doc2.SetValue('E')
        elif self.rbBOLL.GetValue()==True:
            self.vTIPO_DOC.SetValue("B1")
            self.rbFATTI1.SetValue(False)
	    self.rbFATTF2.SetValue(False)
            self.rbBOLL.SetValue(True)
            self.stt_doc1.SetValue('C')
            self.stt_doc2.SetValue('C')
        elif self.rbFATTI1.GetValue()==True:
            self.vTIPO_DOC.SetValue("I1")
            self.rbFATTI1.SetValue(True)
	    self.rbFATTF2.SetValue(False)
            self.rbBOLL.SetValue(False)
            self.stt_doc1.SetValue('E')
            self.stt_doc2.SetValue('E')
        self.ragsoc1.SetFocus()

    def CalcTotale(self,evt):
        importo = 0