send.py :  » Business-Application » hylaPEx » hylapex » library » gui » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Business Application » hylaPEx 
hylaPEx » hylapex » library » gui » send.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time, datetime, os, os.path, sys, shutil, subprocess, string

import wx, wx.grid as gridlib
from twisted.internet import protocol,defer,reactor

from library import i18n
from library.ftp import hylaproto,hylaproto_t,read_conf,cover
from library.observable import Observable
from library.constants import *
from library import log

from view_fax import new_view_fax

import p_fb

DEBUG = 0

class my_var:
    frm_ist = None
    pass

class CoverData(wx.Frame):
    def __init__(self, parent, observable, opt_cls):
        """ Class init
        """
        super(CoverData, self).__init__(parent, title=_("title_cover_data"),)
            #style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN)
        self.SetBackgroundColour(wx.Colour(235, 235, 235))
        
        self._p = wx.Panel(self)
        self._opt_cls = opt_cls
        
        f = self._p.GetFont()
        if f.GetPointSize() < 10:
            f.SetPointSize(10)
        self._p.SetFont(f)
        
        self.__doc = observable
        self.__doc.attach(self)

        self._gui_part(self._p)
        
        self.Bind(wx.EVT_CLOSE, self._onClose)
        
        #set the position, near the main frame
        cpk = "cover_position"
        csk = "cover_size"
        
        vpp = (opt_cls.has_option(cpk) and 
                "x" in opt_cls.get(cpk) and
                opt_cls.get(cpk).replace("x", "").isdigit() )
        vsp = (opt_cls.has_option(csk) and 
                "x" in opt_cls.get(csk) and
                opt_cls.get(csk).replace("x", "").isdigit() )

        if ( vpp and vsp ):
            cover_pos = map(int, opt_cls.get(cpk).split("x"))
            cover_size = map(int, opt_cls.get(csk).split("x"))
            self.SetSize(cover_size)
        else:
            p_size = parent.GetSize()
            p_pos = parent.GetPosition()
            cover_pos = (p_pos.x + p_size.width,
                           p_pos.y + ((p_size.height - self.GetSize().height) /2)
                           ) 
            
        self.SetPosition(cover_pos)
        
        self.Show()
        
    def update(self):
        pass
    
    def get_data(self):
        """ Return our data
        """
        lst = ("txt_receiver", "txt_company", "txt_location", "txt_voice", "txt_comment")
        d_data = {}
        
        for w_name in lst:
            w = getattr("_%s" % w_name)
            d_data[w_name] = w.GetValue()
        
        return d_data
    
    def set_data(self, data):
        """ Set the data
        """
        comp, fax_num, regard = data
        self._txt_company.SetValue(comp)
        self._txt_fax.SetValue(fax_num)
        self._txt_subject.SetValue(regard)
    
    def set_regarding(self, regard):
        self._txt_subject.SetValue(regard)
        
    def enable_multi_receivers(self):
        """ Enable or disable for multiple receivers
        """
        for i in ("_txt_receiver","_txt_location","_txt_voice","_txt_fax","_txt_company"):
            getattr(self, i).Disable()
        wx.CallAfter(self._txt_subject.SetFocus)
        
    def _gui_part(self, parent):
        """ Create gui and widgets"""
        self._txt_receiver = wx.TextCtrl(parent)
        self._txt_company = wx.TextCtrl(parent)
        self._txt_location = wx.TextCtrl(parent)
        self._txt_voice = wx.TextCtrl(parent)
        self._txt_fax = wx.TextCtrl(parent)
        self._txt_subject = wx.TextCtrl(parent)
        self._txt_comment = wx.TextCtrl(parent, size=(150, 150), style=wx.TE_MULTILINE)
        
        lbl_receiver = wx.StaticText(parent, -1, _("lbl_cover_receiver"))
        lbl_company = wx.StaticText(parent, -1, _("lbl_cover_company"))
        lbl_location = wx.StaticText(parent, -1, _("lbl_cover_location"))
        lbl_voice = wx.StaticText(parent, -1, _("lbl_cover_voice"))
        lbl_fax = wx.StaticText(parent, -1, _("lbl_cover_fax"))
        lbl_subject = wx.StaticText(parent, -1, _("lbl_cover_subject"))
        lbl_comment = wx.StaticText(parent, -1, _("lbl_cover_comment"))

        sizer = wx.GridBagSizer()
        sizer.AddGrowableCol(1)
        sizer.AddGrowableRow(6)
        sz_all = wx.BoxSizer()
        
        flag_lbl = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND
        flag_txt = flag_lbl
        
        sizer.Add(lbl_receiver, (0,0), flag=flag_lbl|wx.TOP, border=4)
        sizer.Add(self._txt_receiver, (0,1), flag=flag_txt, border=4)
        sizer.Add(lbl_company, (1,0), flag=flag_lbl, border=4)
        sizer.Add(self._txt_company, (1,1), flag=flag_txt, border=4)
        sizer.Add(lbl_location, (2,0), flag=flag_lbl, border=4)
        sizer.Add(self._txt_location, (2,1), flag=flag_txt, border=4)
        sizer.Add(lbl_voice, (3,0), flag=flag_lbl, border=4)
        sizer.Add(self._txt_voice, (3,1), flag=flag_txt, border=4)
        sizer.Add(lbl_fax, (4,0), flag=flag_lbl, border=4)
        sizer.Add(self._txt_fax, (4,1), flag=flag_txt, border=4)

        sizer.Add(lbl_subject, (5,0), flag=flag_lbl, border=4)
        sizer.Add(self._txt_subject, (5,1), flag=flag_txt, border=4)
        sizer.Add(lbl_comment, (6,0), flag=flag_lbl, border=4)
        sizer.Add(self._txt_comment, (6,1), (1,1), flag_lbl, border=4)
        
        sz_all.Add(sizer, 1, wx.EXPAND)
        
        parent.SetSizerAndFit(sz_all)
        self.SetClientSize( parent.GetSize() )
        
    def _onClose(self, evt):
        """
        """
        self.__doc.detach(self)
        self.__doc.set(OBS_FR_DATA_COVER_CLOSE)
        
        self._opt_cls.set("cover_position", "%sx%s" % self.GetPositionTuple())
        self._opt_cls.set("cover_size", "%sx%s" % self.GetSizeTuple())
        
        evt.Skip()
        
class SendGui(wx.Frame):
    def __init__(self, parent, paths, state=None, file2send=None, listen=1, 
                        observable=None):
        """ Class init
        """
        if state and not file2send:
            file2send=paths.temp_file_ps
        super(SendGui, self).__init__(parent)
        self.SetBackgroundColour(wx.Colour(235, 235, 235))
        
        global _
        _ = i18n.i18n(default=paths.language, dir_path=paths.my_path)
        
        self.SetTitle(_("title_send"))

        self._p = wx.Panel(self)
        
        if state is None: state = ""
        if file2send is None: file2send = ""
        
        #Doc/view
        if not observable:
            observable = Observable()
        self.__doc = observable
        self.__doc.attach(self)
        
        self._f_cover_data = None
        
        #Some attributes
        self.parent = parent
        self.paths = paths
        self.state = state
        self.file2send = file2send
        self.listen = listen
        
        #Option class
        self._parent_opt_cls = parent and hasattr(parent, "opt_cls")
        if self._parent_opt_cls:
            self.opt_cls = getattr(parent, "opt_cls")
        else:
            self.opt_cls = read_conf.conf_parser(self.paths.file_conf_gen, 'hylapex')
            self.opt_cls.exist()
        #wx.MessageBox(self.opt_cls.get("cover_position"))
        self._p.opt_cls = self.opt_cls
        
        #Go with the imsgs

        # path of the images
        self.imgsPath = self.paths.imgs_dir
        self.bigBtnSz = wx.Size(32,32)
        self.smallBtnSz = wx.Size(24,24)
        
        self.imgsDict = {"add":"add.png", "preview":"preview.png",
            "ok":"ok.png", "delete":"delete.png", "up":"up.png",
            "down":"down.png", "send":"send.png"}
        
        # main sizer components
        sz_dest = self._createDestSizer(self._p)
        sz_attach = self._createAttachSizer(self._p)
        #sep = wx.StaticLine(self, -1, size=wx.Size(200, 2))
        sz_contacts = self._createContactsSizer(self._p)
        
        # main sizer creation
        sz_main = wx.GridBagSizer(3, 2)
        sz_main.AddGrowableRow(0)
        sz_main.AddGrowableCol(1)
        
        # main sizer adding
        flag_main = wx.ALIGN_LEFT | wx.EXPAND | wx.ALL
        sz_main.Add(sz_dest, (0,0), (1,1), flag_main, 2)
        sz_main.Add(sz_attach, (0,1), (1,1), flag_main, 2)
        sz_main.Add(sz_contacts, (1,0), (1,2), flag_main, 2)

        self._p.SetSizerAndFit(sz_main)
        
        sz_ = wx.BoxSizer(wx.VERTICAL)
        sz_.Add(self._p, 1, wx.EXPAND)
        self.SetSizerAndFit(sz_)

        wx.CallAfter(self.my_init)

        self.CenterOnScreen()
        self.Show(True)
        self._fdebug = None
        self._OpenDebugFile()
        
        #event bind
        self.Bind(wx.EVT_CLOSE, self._onClose)
        

    def my_init(self):
        my_var.te = 0                   #For callater
        my_var.frm_ist = self           #For callater

        #Connect to server
        self.hy = hylaproto.Hylafax(self.opt_cls.get('txt_server'), 
                passive=self.opt_cls.getint('chk_passive'), debug_funct=self.paths.log4write.write)
        
        self.paths.log4write.write( "Ftp passive: %s" % self.hy.ftp.passiveserver )
        
        self.hy.username = self.opt_cls.get('txt_user')
        if not self.opt_cls.get('txt_pass') == '': self.hy.password = self.opt_cls.get('txt_pass')

        self.myl = log.log(self.paths.log_file, tmp_dir=self.paths.tmp_dir)

        if self.file2send:
            self._lbox_attachList.Append(self.file2send)
        """
        why this temporary file?? Toggled by Luca :)
        else:
            print "self.paths.temp_file_ps", self.paths.temp_file_ps
            self._lbox_attachList.Append(self.paths.temp_file_ps)
        """
        #For fax view/send
        self.view_fax = None
        if self.parent and hasattr(self.parent, 'view_fax'):
            self.view_fax = getattr(self.parent, 'view_fax')

        self.ctrl_ret_img_view(1)

        #Used for listen if there's another printer
        rcv_prt = protocol.ServerFactory()
        rcv_prt.protocol = Rcv_print
        
        #For hylaprint
        self._rcv_prt = None
        
        try:
            if self.listen:
                self._rcv_prt = reactor.listenTCP(8003, rcv_prt)
            
        except Exception, ex:
            print ex
            pass


        if self.opt_cls.has_option("txt_cover_path"):
            cover_path = self.opt_cls.get("txt_cover_path")
            self.tctrl_cover.SetValue(cover_path)

    #
    # Gui creation
    #
    def _createAttachSizer(self, parent):
        """ returns the sizer containing the attachment ctrls
        """
        # button for attach adding
        lbl_attachAdd = wx.StaticText(parent, -1, _("lbl_add"))
        bmpPath = os.path.join(self.imgsPath, self.imgsDict.get("add"))
        bmp_attachAdd = wx.Bitmap(bmpPath, wx.BITMAP_TYPE_PNG)
        bmpBtn_attachAdd = wx.BitmapButton(parent, -1, bmp_attachAdd, size=self.bigBtnSz)
        bmpBtn_attachAdd.Bind(wx.EVT_BUTTON, self._onAttachAddBmpBtn)
        
        # button for preview
        lbl_attachPreview = wx.StaticText(parent, -1, _("lbl_prev"))
        bmpPath = os.path.join(self.imgsPath, self.imgsDict.get("preview"))
        bmp_attachPreview = wx.Bitmap(bmpPath, wx.BITMAP_TYPE_PNG)
        bmpBtn_attachPreview = wx.BitmapButton(parent, -1, bmp_attachPreview,
            size=self.bigBtnSz)
        bmpBtn_attachPreview.Bind(wx.EVT_BUTTON, self._onAttachPreviewBmpBtn)

        # button send
        bmpPath = os.path.join(self.imgsPath, self.imgsDict.get("send"))
        bmp_attachSend = wx.Bitmap(bmpPath, wx.BITMAP_TYPE_PNG)
        bmpBtn_attachSend = wx.BitmapButton(parent, -1, bmp_attachSend,
            size=self.bigBtnSz)
        bmpBtn_attachSend.Bind(wx.EVT_BUTTON, self._onAttachSendBmpBtn)
        
        w,h = self.smallBtnSz
        w -= 5
        h -= 5
        
        # button up arrow
        bmpPath = os.path.join(self.imgsPath, self.imgsDict.get("up"))
        bmp_attachUp = wx.ImageFromBitmap( wx.Bitmap(bmpPath, wx.BITMAP_TYPE_PNG) )
        bmp_attachUp = wx.BitmapFromImage( bmp_attachUp.Scale(w,h, wx.IMAGE_QUALITY_HIGH) )
        bmpBtn_attachUp = wx.BitmapButton(parent, -1, bmp_attachUp,
            size=self.smallBtnSz)
        bmpBtn_attachUp.Bind(wx.EVT_BUTTON, self._onAttachUpBmpBtn)
        
        # button down arrow
        bmpPath = os.path.join(self.imgsPath, self.imgsDict.get("down"))
        bmp_attachDown = wx.ImageFromBitmap( wx.Bitmap(bmpPath, wx.BITMAP_TYPE_PNG) )
        bmp_attachDown = wx.BitmapFromImage( bmp_attachDown.Scale(w,h, wx.IMAGE_QUALITY_HIGH) )
        bmpBtn_attachDown = wx.BitmapButton(parent, -1, bmp_attachDown,
            size=self.smallBtnSz)
        bmpBtn_attachDown.Bind(wx.EVT_BUTTON, self._onAttachDownBmpBtn)
        
        # button del
        bmpPath = os.path.join(self.imgsPath, self.imgsDict.get("delete"))
        bmp_attachDel = wx.ImageFromBitmap( wx.Bitmap(bmpPath, wx.BITMAP_TYPE_PNG) )
        bmp_attachDel = wx.BitmapFromImage( bmp_attachDel.Scale(w,h, wx.IMAGE_QUALITY_HIGH) )
        bmpBtn_attachDel = wx.BitmapButton(parent, -1, bmp_attachDel,
            size=self.smallBtnSz)
        bmpBtn_attachDel.Bind(wx.EVT_BUTTON, self._onAttachDelBmpBtn)
        
        # attachments list box
        lbl_listToSend = wx.StaticText(parent, -1, _("lbl_list"))
        self._lbox_attachList = wx.ListBox(parent, -1, size=wx.Size(100, 100),
            style=wx.LB_HSCROLL)
        self._lbox_attachList.Bind(wx.EVT_LISTBOX_DCLICK,
              self._on_lbox_attachListDclick)

        # cover ctrls
        lbl_cover = wx.StaticText(parent, -1, _("lbl_cover"))
        self.tctrl_cover = wx.TextCtrl(parent, size=wx.Size(150, -1))
        btn_selectPath = wx.Button(parent, -1, _("lbl_btn_select_path"))
        self._chk_view_cover_data = wx.CheckBox(parent, -1, _("chk_view_cover_data"))

        btn_selectPath.Bind(wx.EVT_BUTTON, self._onAttachCoverBtn)
        self._chk_view_cover_data.Bind(wx.EVT_CHECKBOX, self._onCheckCoverData)

        if ( not self.opt_cls.has_option("chk_use_cover") or
           (self.opt_cls.has_option("chk_use_cover") and not self.opt_cls.getint("chk_use_cover"))):
            btn_selectPath.Enable(False)
            self.tctrl_cover.Enable(False)
            self._chk_view_cover_data.Enable(False)


        sz_cover = wx.GridBagSizer(2, 2)
        sz_cover.Add(lbl_cover, (0,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2)
        sz_cover.Add(self._chk_view_cover_data, (0,1), (1,1),
            wx.ALIGN_LEFT | wx.ALL, 2)
        sz_cover.Add(self.tctrl_cover, (1,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2)
        sz_cover.Add(btn_selectPath, (1,1), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2)
        
        lbl_attachSend = wx.StaticText(parent, -1, _("lbl_send"))
        
        # sizer for attach add button
        sz_addBtn = wx.BoxSizer(wx.VERTICAL)
        sz_addBtn.Add(lbl_attachAdd, 0, wx.CENTER | wx.ALL, 5)
        sz_addBtn.Add(bmpBtn_attachAdd, 0, wx.CENTER | wx.ALL, 5)

        # sizer for attach preview button
        sz_previewBtn = wx.BoxSizer(wx.VERTICAL)
        sz_previewBtn.Add(lbl_attachPreview, 0, wx.CENTER | wx.ALL, 5)
        sz_previewBtn.Add(bmpBtn_attachPreview, 0, wx.CENTER | wx.ALL, 5)
        
        # sizer for send bmp button
        sz_sendBtn = wx.BoxSizer(wx.VERTICAL)
        flag_bt = wx.CENTER | wx.LEFT | wx.TOP | wx.BOTTOM
        sz_sendBtn.Add(lbl_attachSend, 0, flag_bt, 5)
        sz_sendBtn.Add(bmpBtn_attachSend, 0, flag_bt, 5)


        # sizer for add and preview buttons
        sz_addPreviewBtn = wx.BoxSizer(wx.HORIZONTAL)
        sz_addPreviewBtn.Add(sz_addBtn, 0, wx.CENTER | wx.ALL, 5)
        sz_addPreviewBtn.Add(sz_previewBtn, 0, wx.CENTER | wx.ALL, 5)
        sz_addPreviewBtn.Add(sz_sendBtn, 0, wx.CENTER | wx.ALL, 5)

        # sizer for up, down and del buttons
        sz_upDownDelBtn = wx.BoxSizer(wx.VERTICAL)
        flag_bt = wx.CENTER | wx.TOP | wx.BOTTOM
        sz_upDownDelBtn.Add(bmpBtn_attachUp, 0, flag_bt, 5)
        sz_upDownDelBtn.Add(bmpBtn_attachDown, 0, flag_bt, 5)
        sz_upDownDelBtn.Add(bmpBtn_attachDel, 0, flag_bt, 5)

        # sizer for attach list
        sz_attachList = wx.GridBagSizer(2, 2)
        sz_attachList.AddGrowableRow(1)
        sz_attachList.AddGrowableCol(0)
        sz_attachList.Add(lbl_listToSend, (0,0), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)
        sz_attachList.Add(self._lbox_attachList, (1,0), (1,1),
            wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 2)
        sz_attachList.Add(sz_upDownDelBtn, (1,1), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)

        sz_attach = wx.BoxSizer(wx.VERTICAL)
        sz_attach.Add(sz_addPreviewBtn, 0, wx.ALIGN_CENTER | wx.ALL, 2)
        sz_attach.Add(sz_attachList, 1, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 2)
        sz_attach.Add(sz_cover, 0, wx.ALIGN_CENTER | wx.ALL, 2)

        sz_all_attach = wx.StaticBoxSizer(wx.StaticBox(parent, -1, _("sb_attach")), wx.VERTICAL)
        sz_all_attach.Add(sz_attach, 1, wx.EXPAND | wx.RIGHT, 5)
        return sz_all_attach

    def _createContactsSizer(self, parent):
        """ returns the sizer containing the ctrls for the contacts search
        """

        self.p_fb = p_fb.wxPanel1(parent, self.paths, observable=self.__doc)
        return self.p_fb
    
    def _createDestCenterSizer(self, parent):
        """ returns the sizer that contains the list (grid) of the dest companies
        """
        # grid creation and setting
        h, w = (wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X),
                wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y))

        if w > 1024:
           w_gr = 230
           h_gr = 150
        else:
           w_gr = 200
           h_gr = 120

        self.gr_dest = gridlib.Grid(parent, size=(w_gr, h_gr))
        self.gr_dest.CreateGrid(0, 2)
        self.gr_dest.SetColLabelValue(0, _("grid_col_company"))
        self.gr_dest.SetColLabelValue(1, _("grid_col_fax"))
        colLblExtentH = self.gr_dest.GetTextExtent(_("grid_col_company"))[1]
        rowLblExtentH = self.gr_dest.GetTextExtent("00")[0]
        self.gr_dest.SetColLabelSize(colLblExtentH + 10)
        self.gr_dest.SetRowLabelSize(rowLblExtentH + 10)
        self.gr_dest.SetColSize(0, 120)
        self.gr_dest.SetColSize(1, 90)
        
        # button for row(dest) deleting
        lbl_destList = wx.StaticText(parent, -1, _("lbl_list"))
        bmpPath = os.path.join(self.imgsPath, self.imgsDict.get("delete"))
        bmp_delDest = wx.Bitmap(bmpPath, wx.BITMAP_TYPE_PNG)
        bmpBtn_delDest = wx.BitmapButton(parent, -1, bmp_delDest,
            size=self.smallBtnSz)
        bmpBtn_delDest.Bind(wx.EVT_BUTTON, self._onDestDelBmpBtn)
        sz_delDest = wx.BoxSizer(wx.VERTICAL)
        sz_delDest.Add(lbl_destList, -1, wx.ALIGN_LEFT | wx.ALL, 0)
        sz_delDest.Add(bmpBtn_delDest, -1, wx.ALIGN_CENTER | wx.ALL, 0)
        
        # center sizer
        sz_center = wx.GridBagSizer(1, 2)
        sz_center.AddGrowableCol(1)
        sz_center.AddGrowableRow(0)
        sz_center.Add(sz_delDest, (0,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_LEFT | wx.ALL, 2)
        sz_center.Add(self.gr_dest, (0,1), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.ALL, 10)

        return sz_center
        
    def _createDestNorthSizer(self, parent):
        """ returns the sizer that contains fax number, company, 
            subject and ok button
        """
        # components creation
        lbl_number = wx.StaticText(parent, -1, _("lbl_num"))
        lbl_company = wx.StaticText(parent, -1, _("lbl_company"))
        lbl_subject = wx.StaticText(parent, -1, _("lbl_obj"))
        self.tctrl_number = wx.TextCtrl(parent, -1, size=wx.Size(150, -1))
        self.tctrl_company = wx.TextCtrl(parent, -1, size=wx.Size(150, -1))
        self.tctrl_subject = wx.TextCtrl(parent, -1, size=wx.Size(150, -1))
        
        # bmpButton sizer
        bmpPath = os.path.join(self.imgsPath, self.imgsDict.get("ok"))
        bmp_ok = wx.Bitmap(bmpPath, wx.BITMAP_TYPE_PNG)
        bmpBtn_ok = wx.BitmapButton(parent, -1, bmp_ok, size=self.bigBtnSz)
        bmpBtn_ok.Bind(wx.EVT_BUTTON, self._onDestOkBmpBtn)
        lbl_ok = wx.StaticText(parent, -1, _("btn_dest_ok"))
        sz_btnOk = wx.BoxSizer(wx.VERTICAL)
        sz_btnOk.Add(lbl_ok, -1, wx.ALIGN_CENTER, 0)
        sz_btnOk.Add(bmpBtn_ok, -1, wx.ALIGN_CENTER, 0)
        
        # laying out components
        sz_north = wx.GridBagSizer(3, 3)
        sz_north.Add(lbl_number, (0,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2)
        sz_north.Add(self.tctrl_number, (0,1), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)
        sz_north.Add(lbl_company, (1,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2)
        sz_north.Add(self.tctrl_company, (1,1), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)
        sz_north.Add(lbl_subject, (2,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2)
        sz_north.Add(self.tctrl_subject, (2,1), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)
        sz_north.Add(sz_btnOk, (0,2), (3,1),
            wx.ALIGN_CENTER | wx.ALL, 0)
        
        
        return sz_north
        
    def _createDestSizer(self, parent):
        """ returns the sizer that contains information on fax destination
        """
        sz_north = self._createDestNorthSizer(parent)
        sz_center = self._createDestCenterSizer(parent)
        sz_south = self._createDestSouthSizer(parent)
        
        sz_dest = wx.GridBagSizer(3, 1)
        sz_dest.AddGrowableCol(0)
        sz_dest.AddGrowableRow(1)
        sz_dest.Add(sz_north, (0,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_LEFT | wx.ALL, 2)
        sz_dest.Add(sz_center, (1,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)
        sz_dest.Add(sz_south, (2,0), (1,1),
            wx.ALIGN_LEFT | wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)

        # static box  for search
        sbx_dest = wx.StaticBox(parent, -1, " "+_("sb_destination")+" ")
        sz_dest_all = wx.StaticBoxSizer(sbx_dest, wx.VERTICAL)
        sz_dest_all.Add(sz_dest, 1, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5)

        return sz_dest_all

    def _createDestSouthSizer(self, parent):
        """ returns the sizer containing the priority and datetime ctrls
        """
        lbl_prioriy = wx.StaticText(parent, -1, _("lbl_priority"))
        lbl_dateTime = wx.StaticText(parent, -1, _("lbl_when"))
        lbl_lastTime = wx.StaticText(parent, -1, _("lbl_last_time"))
        lbl_resolution = wx.StaticText(parent, -1, _("lbl_resolution"))
        
        self.sld_priority = wx.Slider(parent, -1, 3, 0, 6,
            size=wx.Size(150, -1), style=wx.SL_HORIZONTAL)
        self.sld_dateTime = wx.Slider(parent, -1, 0, 0, 100,
            size=wx.Size(150, -1), style=wx.SL_HORIZONTAL)

        self.lbl_priorityVal = wx.StaticText(parent, -1,
            str(self.sld_priority.GetValue()), style=wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE)
        self.lbl_dateTimeVal = wx.StaticText(parent, -1, label=_('now'),
                               size=(self.lbl_priorityVal.GetTextExtent("00:00 39/12")[0], -1),
                               style=wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE)
        
        self.sld_priority.Bind(wx.EVT_SCROLL, self._onDestSldPriorityScroll)
        self.sld_dateTime.Bind(wx.EVT_SCROLL, self._onDestSldDateTimeScroll)
        
        # getting the slider value from config file
        if self.opt_cls.has_option("sld_last_time"):
            last_time = self.opt_cls.get("sld_last_time")
        else:
            last_time = "1"
        if self.opt_cls.has_option("txt_last_time_manual"):
            last_time_manual = self.opt_cls.get("txt_last_time_manual")
        else:
            last_time_manual = "0100"

        if not self.opt_cls.has_option("max_days_last_time"):
            self.opt_cls.set("max_days_last_time", 15)
        
        max_days_LT = self.opt_cls.getint("max_days_last_time")

        # creating and setting ctrls
        self.sld_lastTime = wx.Slider(parent, -1, int(last_time), 1, max_days_LT,
            size=wx.Size(150, -1), style=wx.SL_HORIZONTAL)
        self.lbl_lastTimeVal = wx.StaticText(parent, -1, label=last_time_manual,
                               size=(self.lbl_priorityVal.GetTextExtent("00:00 39/12")[0], -1),
                               style=wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE)
       
        self.sld_lastTime.Bind(wx.EVT_SCROLL, self._onDestSldLastTimeScroll)
        
        self.cb_resolution = wx.Choice(parent, choices=_.getList("_lst_resolutions"))
                
        sz_priority = wx.GridBagSizer()
        sz_priority.Add(lbl_prioriy, (0,0), (1,1),
            wx.ALIGN_LEFT | wx.ALL, 2)
        sz_priority.Add(self.sld_priority, (0,1), (1,1),
            wx.ALIGN_LEFT | wx.ALL, 2)
        sz_priority.Add(self.lbl_priorityVal, (0,2), (1,1),
            wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)
        sz_priority.Add(lbl_dateTime, (1,0), (1,1),
            wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)
        sz_priority.Add(self.sld_dateTime, (1,1), (1,1),
            wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)
        sz_priority.Add(self.lbl_dateTimeVal, (1,2), (1,1),
            wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)
        
        sz_priority.Add(lbl_lastTime, (2,0), (1,1),
            wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)
        sz_priority.Add(self.sld_lastTime, (2,1), (1,1),
            wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)
        
        sz_priority.Add(self.lbl_lastTimeVal, (2,2), (1,1),
            wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 2)
        
        sz_priority.Add(lbl_resolution, (3,0), (1,1),
            wx.ALIGN_CENTER | wx.EXPAND | wx.ALL, 2)
        sz_priority.Add(self.cb_resolution, (3,1), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)
        
        return sz_priority    
    
    #
    # EVENTS MANAGEMENT
    #
    
    def _onClose(self, event=None):
        #Update the comunication var
        
        self._Debug("Start to close")
        
        self.__doc.detach(self)
        
        #Say that we are closing
        self.__doc.set(OBS_FR_SEND_CLOSE)
        
        if self._rcv_prt:
            self._rcv_prt.stopListening()
        
        my_var.frm_ist = None
        if self.view_fax:
            self.view_fax.closeLib()

        self._Debug("Close log")
        self.myl.close()
        self._Debug("Close panel phone book")
        self.p_fb.close()
        
        if self._f_cover_data:
            self.opt_cls.set("cover_position", "%sx%s" % self._f_cover_data.GetPositionTuple())
            self.opt_cls.set("cover_size", "%sx%s" % self._f_cover_data.GetSizeTuple())
        
        #if not self._parent_opt_cls:
            #we opened the file alone, so close
        self.opt_cls.exit()
        
        #For test...
        #self.state = 'r'
        if self.state == 'r':
            self._Debug("Destroy and exit")
            reactor.addSystemEventTrigger('after', 'shutdown', self.internalClose, True)
            try:
                reactor.stop()
                self._Debug("Reactor stopped")
            except:
                self._Debug("Reactor NOT stopped")
            
            if DEBUG: self._fdebug.close()
        else:
            self._Debug("Event skip")
            if DEBUG: self._fdebug.close()
            if event:
                event.Skip()
            self.Destroy()

        #Never go here
        if DEBUG: self._fdebug.close()

    def internalClose(self, *args, **kargs):
        self.Destroy()

    def _onAttachAddBmpBtn(self, evt):
        """ button "Add attachment in list" event management
        """
        if self.opt_cls.has_option("path_new_file"):
            path_file = self.opt_cls.get("path_new_file")
        else:
            path_file = "."
        
        path_file = os.path.abspath(os.path.dirname(path_file))

        dlg = wx.FileDialog(self, _('choose_file'), path_file, "",
            "Acrobat and Postscript (*.ps;*.pdf)|*.ps;*.pdf|Tiff(*.tiff;*.tif)|*.tiff;*.tif", 
            wx.OPEN)
        filename = ''
        try:
            if dlg.ShowModal() == wx.ID_OK:
                filename = dlg.GetPath()
        finally:
            dlg.Destroy()
        if not filename: return
        
        self.opt_cls.set("path_new_file", filename)
        
        self._lbox_attachList.Append(filename)
    
    def _onAttachCoverBtn(self, evt):
        """ button "Select path" event management
        """
        dlg = wx.FileDialog(self, _('choose_file'), os.path.abspath("."), "",
            "|*.*|*.*", wx.OPEN)
        filename = ''
        try:
            if dlg.ShowModal() == wx.ID_OK:
                filename = dlg.GetPath()
        finally:
            dlg.Destroy()
        if not filename: return
        
        self.tctrl_cover.SetValue(filename)

    def _onCheckCoverData(self, evt):
        """
        """
        if self._f_cover_data:
            self.__doc.detach(self._f_cover_data)
            self._f_cover_data.Destroy()
            self._f_cover_data = None
            return
            
        self._f_cover_data = CoverData(self, self.__doc, self.opt_cls)
        num_row = self.gr_dest.GetNumberRows()
        regarding = self.tctrl_subject.GetValue()
        
        if num_row == 1:
            self._f_cover_data.set_data( 
                    [ self.gr_dest.GetCellValue(0, x) for x in xrange(2) ] +
                    [ regarding ] )
        
        elif num_row > 1:
            self._f_cover_data.enable_multi_receivers()
            self._f_cover_data.set_regarding(regarding)
            
    def _onAttachDelBmpBtn(self, evt):
        """ button "del attachment" event management. 
            Deletes the selected row
        """
        sel = self._lbox_attachList.GetSelection()
        if sel == -1: 
            return
        self._lbox_attachList.Delete(sel)
        
    def _onAttachDownBmpBtn(self, evt):
        """ button "down arrow" event management. 
            Moves the selected row down
        """
        sel = self._lbox_attachList.GetSelection()
        if sel == -1: return
        string = self._lbox_attachList.GetString(sel)
        atc_count = self._lbox_attachList.GetCount()
        if atc_count < 2 or sel == atc_count -1:
            return
        self._lbox_attachList.InsertItems([string],sel +2)
        self._lbox_attachList.Delete(sel)
        self._lbox_attachList.SetSelection(sel+1)
    
    def _onAttachPreviewBmpBtn(self, evt=None):
        """ button "attachment preview" event management
        """
        if not self._lbox_attachList.GetCount(): return
        sel = self._lbox_attachList.GetSelection()
        if sel == -1:
            self._lbox_attachList.SetSelection(0)
            sel = 0
        if self.opt_cls.getint('chk_int_view'):
            lst_file_in = [ self._lbox_attachList.GetString(x)
                            for x in range(self._lbox_attachList.GetCount()) ]

            lst_files_out = list()
            for file in lst_file_in:
                f = open(file, 'rb')
                header = f.read(4)
                f.close()

                ext = os.path.splitext(file)[1]
                if header in (r'%PDF', r'%!PS') or ext.lower() in (".pdf", ".ps"):
                    if self.opt_cls.getint('chk_use_freeimage'):
                        tofo='tiffg3'
                        ext='tif'
                    else:
                        tofo='pngmono'
                        ext='png'
                    ret = self.view_fax._convert_end(
                        self.view_fax._convert_files_ps(file, tofo=tofo, ext=ext) )
                    if not ret: continue
                    self.paths.log4write.write(ret)
                else:
                    ret = self.view_fax._convert_file_tif(file, type="png")
                    #ret = [file]

                for x in ret:
                    lst_files_out.append( x )
            if self.__ctrlErrorFreeImage(lst_files_out): return

            if self.opt_cls.getint('chk_use_freeimage'):
                self._lbox_attachList.Clear()
                self._lbox_attachList.AppendItems(lst_files_out)

            self.paths.log4write.write(lst_files_out)
            ret = self.view_fax._view_file_prog(lst_files_out, 4,
                funct4save=self.SaveFilesFromModify,
                modify=self.opt_cls.getint('chk_modify_preview') and
                       self.opt_cls.getint('chk_use_freeimage'))
            if ret:
                dlg = wx.MessageDialog(None,
                    '%s\n%s' % (_('_error_no_img_open'),
                        self.paths.log_file ) ,
                    _('error', 1), wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
        else:
            f_name = self._lbox_attachList.GetStringSelection()
            f = open(f_name, 'rb')
            header = f.read(4)
            f.close()
            if header in (r'%PDF', r'%!PS'):
                self.view_fax._view_file_prog(f_name, 1)
            else:
                self.view_fax._view_file_prog(f_name, 4)
    
    def _onAttachSendBmpBtn(self, evt):
        """ button "Send" event management
        """
        errDlg = None
        if self.gr_dest.GetNumberRows() == 0:
            errDlg = 1
            label, caption = _('_insert_one_fax_number'), \
                _('_no_fax_number')

        fileList = self._lbox_attachList.GetStrings()

        if errDlg:
            dlg = wx.MessageDialog(self, label, caption, wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
            self.tctrl_number.SetFocus()
            return
        
        num_pages = ""
        
        if (fileList and self.opt_cls.getint('chk_use_freeimage') and
                self.opt_cls.getint('chk_concatenate')):

            file_name = self.view_fax.concatenate(fileList)

            self._lbox_attachList.Clear()
            self._lbox_attachList.Append(file_name)

            if self.__ctrlErrorFreeImage(file_name): return

            num_pages = str(self.view_fax.getNumPages(file_name))

        self._sendFax_old(num_pages)
        
        """
        lst_file = list()
        for lst in range(self._lbox_attachList.GetCount()):
            lst_file.append(self._lbox_attachList.GetString(lst))

        self._sendFax_new(lst_file)
        """
        
        #Update because we send the fax
        self.__doc.set(OBS_FR_HY_UPDATE)
        
        wx.CallAfter(self._onClose)
    
    def _onAttachUpBmpBtn(self, evt):
        """ button "up arrow" event management. Moves the selected row up
        """
        sel = self._lbox_attachList.GetSelection()
        if sel == -1: return
        string = self._lbox_attachList.GetString(sel)
        if self._lbox_attachList.GetCount() < 2 or sel == 0:
            return
        self._lbox_attachList.InsertItems([string],sel -1)
        self._lbox_attachList.Delete(sel+1)
        if not sel == 0:
            self._lbox_attachList.SetSelection(sel-1)

    def _onDestDelBmpBtn(self, evt):
        """ button "Cancel destination from grid" event management
        """
        rows = self.gr_dest.GetSelectedRows()
        for row in sorted(rows, reverse=True):
            self.gr_dest.DeleteRows(row)
        
    def _onDestOkBmpBtn(self, evt):
        """ button "Insert destination in dest grid" event management
        """
        if self._ctrl_num_fax(self.tctrl_number.GetValue(), self.tctrl_company.GetValue()):
            return
        self.tctrl_number.SetValue('')
        self.tctrl_company.SetValue('')
    
    def _onDestSldDateTimeScroll(self, evt):
        """ scroll on priority slider
        """
        now = time.time()
        time_sld = self.sld_dateTime.GetValue()
        if time_sld == 0:
            self.lbl_dateTimeVal.SetLabel(_("now"))
            return
        val = time_sld * 15 * 60  # Every 15 minutes
        
        when = datetime.datetime.fromtimestamp(val + now)
        self.lbl_dateTimeVal.SetLabel("%s:%s %s/%s" % (when.hour, when.minute,
            when.day, when.month))
    
    def _onDestSldLastTimeScroll(self, evt):
        """ scroll on last time slider
        """
        v = str(self.sld_lastTime.GetValue())
        if len(v) == 1: v = "0" + v
        self.lbl_lastTimeVal.SetLabel(v + "00")
        
    def _onDestSldPriorityScroll(self, evt):
        """ scroll on priority slider
        """
        self.lbl_priorityVal.SetLabel(str(self.sld_priority.GetValue()))
    
    def _on_lbox_attachListDclick(self, evt):
        """ Show preview
        """
        self._onAttachPreviewBmpBtn('')
        
    #
    # Internal methods
    #
    def _OpenDebugFile(self):
        """
        """

        if DEBUG:
            if self._fdebug:
                #Try to flush data
                try: self._fdebug.close()
                except: pass

            if sys.platform == "win32":
                self._fdebug = open("C:\\hylapex_send.log", "a")
            else:
                self._fdebug = open("/tmp/hylapex_send.log", "a")

    def _Debug(self, *args, **kw):
        """
        """
        if DEBUG:
            self._fdebug.write("%s\n" % str(args) + str(kw))

    def update(self):
        """
        """
        type_, val = self.__doc.get()
        if type_ == OBS_ADD_ALL_FILES:
            self._ctrl_num_fax(*val)
        elif type_ == OBS_FR_DATA_COVER_CLOSE:
            self._chk_view_cover_data.SetValue(False)
            self._f_cover_data = None
    #
    # Called from outside
    #

    def SaveFilesFromModify(self, files):
        """ Called from other frames
        """
        self.Raise()
        if not files: return
        self._lbox_attachList.Clear()
        for f in files:
            if os.path.splitext(f)[1] == '.tif':
                new_file = f
            else:
                new_file = self.view_fax.loadAndSave(f, self.paths.tmp_dir, 'tiffg3')
            if self.__ctrlErrorFreeImage(new_file): return
            self._lbox_attachList.Append(new_file)


    #
    # Old methods that make the send work
    #

    def ctrl_ret_img_view(self, setParent=0):
        """ Control the imageview return value
        """
        ret, msg, inst = new_view_fax(self._p, self.opt_cls, self.paths)
        if ret:
            dlg = wx.MessageDialog(None, "Error:%s" % msg +"\nTip: You have select to use freeimage, but\n" +
                    "you haven't set the freeimage path. Go to configure", 'Error',
                    wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
        #If I have already my class, don't re-set
        if not msg == 'ok_yet':
            setattr(self, 'view_fax', inst)
            if setParent and self.parent:
                setattr(self.parent, 'view_fax', inst)


    def _sendFax_new(self, lstFiles):
        newfax = hylaproto_t.SendFax()
        newfax.fromuser = self.opt_cls.get('txt_user')
        newfax.notifyaddr = self.opt_cls.get('txt_email')
        newfax.lasttime = '010000'
        newfax.maxdials = self.opt_cls.get('sld_tel')
        newfax.SCHEDPRI = self.sld_priority.GetLabel()
        newfax.TOLOCATION = self.tctrl_subject.GetValue()

        if self.opt_cls.get('notify') == 'always':
            newfax.NOTIFY = '"done+requeue"'
        elif self.opt_cls.get('notify') == 'done':
            newfax.NOTIFY = 'done'

        if self.lbl_date_num.GetLabel() == _('now', 1):
            newfax.SENDTIME = 'Now'
        else:
            when = self.sendtime
            sendTime =  "%d%02d%02d%02d%02d" % (when.year, when.month, when.day, when.hour, when.minute)
            newfax.SENDTIME = sendTime

    def _sendFax_old(self, num_pages):
        """ Send the fax
        """
        
        #cover page handling
        """ to, to_company, to_location, to_voice_number, to_fax_number, 
        from, from_fax_number, from_voice_number, from_company, from_location, 
        todays_days, regarding, comments,
        
        page_count
        """
        
        cover_not_use = (self.opt_cls.has_option("chk_use_cover") and self.opt_cls.getint("chk_use_cover") == 0)
        d_cover = {"page_count": num_pages}
        
        #our parameters
        send_parameters = {}
        
        send_parameters['FROMUSER'] = self.opt_cls.get('txt_user')
        d_cover["from"] = self.opt_cls.get('txt_user')
        
        if not self.opt_cls.get('txt_email') == '':
            send_parameters['NOTIFYADDR'] = self.opt_cls.get('txt_email')
        last_time = self.lbl_lastTimeVal.GetLabel() + "00"
        send_parameters['LASTTIME'] = last_time
        send_parameters['MAXDIALS'] = self.opt_cls.get('sld_tel')
        send_parameters['SCHEDPRI'] = self._get_priority_hy()

        subj = self.tctrl_subject.GetValue().strip()
        
        if self._f_cover_data:
            #the cover data subject overwrite the main one
            subj = self._f_cover_data._txt_subject.GetValue().strip() or subj
            subj = self._ctrl_chars_no_ascii(subj)
            
        if subj:
            send_parameters['REGARDING'] = subj
            d_cover["regarding"] = subj

        if self.opt_cls.get('notify') == 'always':
            send_parameters['NOTIFY'] = '"done+requeue"'
        elif self.opt_cls.get('notify') == 'done':
            send_parameters['NOTIFY'] = 'done'

        time_sld = self.sld_dateTime.GetValue()
        now = time.time()
        val = time_sld * 15 * 60  # Every 15 minutes
        when = datetime.datetime.fromtimestamp(val + now)
        #print when, (when.year, when.month, when.day, 
        #                            when.hour, when.minute)
        sendTime =  "%d%02d%02d%02d%02d" % (when.year, when.month, when.day, 
                                    when.hour, when.minute)
        if time_sld == 0:
            #whant to send now
            send_parameters['SENDTIME'] = 'Now'
        else:
            send_parameters['SENDTIME'] = sendTime

        d_cover["todays_date"] = "%02d:%02d %02d-%02d-%d" % (when.hour, when.minute,
                            when.day, when.month, when.year)
        
        #resolution
        if self.cb_resolution.GetSelection() == 0:
            resolution = "196"
        else:
            resolution = "98"
        
        send_parameters["VRES"] = resolution
        
        #Add to the dict the "TO" and COMMENTS that become from the cover data 
        #frame, if any. Will be overwrote from the cell values
        CMD_SKIP = ("TOFAX","FROMFAX")
        
        if self._f_cover_data:
            l_k = (("TOCOMPANY", "to_company"), ("TOLOCATION", "to_location"),
                    ("TOUSER", "to"), ("TOVOICE", "to_voice_number"),  
                    ("TOFAX", "to_fax_number"), 
                    ("COMMENTS", "comments"))
                    
            l_f = ("_txt_company", "_txt_location", 
                   "_txt_receiver","_txt_voice",
                "_txt_fax",
                "_txt_comment",)

            for (k, cover_k), f in zip(l_k, l_f):
                f_isnt = getattr(self._f_cover_data, f)
                val = f_isnt.GetValue().strip()
                if val:
                    #if comments, set the right, acceptable, next line command
                    if k == "COMMENTS":
                        val = val.replace("\n", "\\n")
                    
                    val = self._ctrl_chars_no_ascii(val)
                    
                    if not k in CMD_SKIP:
                        send_parameters[k] = val
                    self.paths.log4write.write((k, cover_k, val))
                    d_cover[cover_k] = val
                    
        #add the sender data
        l_k = (("FROMCOMPANY", "from_company"), ("FROMLOCATION", "from_location"),
                ("FROMUSER", "from"), ("FROMVOICE", "from_voice_number"),
                ("FROMFAX", "from_fax_number"),  )
                
        l_co = ("txt_cover_comp_name", "txt_cover_town", "txt_cover_sender_name", 
                "txt_cover_number", "txt_cover_fax",)
        
        for (k, cover_k), co in zip(l_k, l_co):
            if self.opt_cls.has_option(co) and self.opt_cls.get(co).strip():
                val = self.opt_cls.get(co)
                
                val = self._ctrl_chars_no_ascii(val)
                
                if not k in CMD_SKIP:
                    send_parameters[k] = val
                self.paths.log4write.write((k, cover_k, val))
                d_cover[cover_k] = val
        
        cover_path = self.tctrl_cover.GetValue() 

        if cover_path:
            cover_page = cover.CoverData(cover_path, **d_cover)
        else:
            cover_page = None

        for row in range(self.gr_dest.GetNumberRows()):

            num = self.opt_cls.get('txt_prefix') + self.gr_dest.GetCellValue(row,1)
            send_parameters['DIALSTRING'] = num
            send_parameters['EXTERNAL'] = num
            
            if self._f_cover_data:
                comp_name = self._ctrl_chars_no_ascii(
                        self._f_cover_data._txt_company.GetValue().strip() )
            else:
                comp_name = ""
                
            comp_val = self.gr_dest.GetCellValue(row, 0).strip() or comp_name
            
            if cover_page:
               cover_page.to_company = comp_val

            if comp_val:
                send_parameters['TOCOMPANY'] = comp_val

            if cover_not_use and self.tctrl_subject.GetValue().strip():
                send_parameters['TOLOCATION'] = self.tctrl_subject.GetValue()

            #have us to set the tofax value for the cover?
            to_fax_val = self.gr_dest.GetCellValue(row,1)
            if cover_page:
                cover_page.to_fax_number = d_cover.get("TOFAX", "") or to_fax_val

            #parameters list
            lst_pars = [ [str(x) for x in self._lbox_attachList.GetStrings()],
                        send_parameters]

            #need a cover? Add it
            if cover_page:
                lst_pars.append(cover_page)
                
            status, msg = self.hy.sndfax(*lst_pars)
            
            if status:
                self.ctrl_ret_hy(status, msg)
    
    def _ctrl_chars_no_ascii(self, value):
        """ Control for the not-ascii chars and replace them with a "X"
        """
        #print value, repr(value),

        """for c_from, c_to in CHAR_TRANSLATE_TABLE:
            value = value.replace(c_from, c_to)
        
        print value, repr(value)
        """
        
        new_value = ""
        for c in value:
            try:
                new_value += str(c)
            except UnicodeEncodeError:
                if c in CHAR_TRANSLATE_TABLE[0]:
                    new_value += CHAR_TRANSLATE_TABLE[1][ CHAR_TRANSLATE_TABLE[0].index(c) ]
                else:
                    new_value += "X"
        
        return new_value
    
    def _ctrl_num_fax(self, fax_num, company):
        """ Control if the fax number are correct
        """
        fax_num = fax_num.strip()
        if not fax_num: return 1
        for i in ("\\", "/", " ", ".", ",", ";", ":", "_", "-"):
            fax_num = fax_num.replace(i, "")

        try: int(fax_num)
        except ValueError:
            dlg = wx.MessageDialog(self, _('_insert_valid_fax_num') +":\n"+ \
                'Company: %s\nFax - %s' % (company, fax_num), _('attention'),
                wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
            return 1

        self.gr_dest.InsertRows()
        self.gr_dest.SetCellValue(0, 0, company)
        self.gr_dest.SetCellValue(0, 1, fax_num)

        return 0
    
    def __ctrlErrorFreeImage(self, strToCtrl):
        """ Control the FreeImage operation's return message
            and return True if there is an error
        """
        if not strToCtrl: return True
        elif type(strToCtrl) == type( list() ) and len( strToCtrl ) > 0:
            strToCtrl = strToCtrl[0]
        if strToCtrl.find('Error:') != -1:
            self.paths.log4write.write('Error on hylapex_send -> freeimage: %s'
                % strToCtrl)
            dlg = wx.MessageDialog(self, '%s' % strToCtrl ,
                _('error', 1), wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
            return True
        else:
            return False

    def _get_priority_hy(self):
        """ Return the right value for hylafax from our slider
        """
        lst = [0, 42, 85, 127, 170, 212, 255]
        return lst[self.sld_priority.GetValue()]

    def ctrl_ret_hy(self, status, msg):
        """ Control the hylafax return value
        """

        wx.MessageBox("%s :%s" % (_('error'), msg), _('error'),
                wx.ICON_ERROR)
        
        self.paths.log4write.write(str(msg))


    def add_new_fax(self, file_path):
        """ Interface method for add new file to the current gui
        """
        if not os.path.exists(file_path):
            return
        
        self._lbox_attachList.Append(file_path)
        
class Rcv_print(protocol.Protocol):
    #If receive data from another session of printer, call update
    def dataReceived(self, data):
        my_var.frm_ist._lbox_attachList.Append(data)
        my_var.frm_ist.Raise()
    
    def close_protocol(self):
        self.transport.loseConnection()
        print self.transport, dir(self.transport)
    
if __name__ == "__main__":
    app = wx.PySimpleApp()
    f = wx.Frame(None, -1, _("frame_title"))
    sg = SendGui(f)
    f.SetClientSize(sg.GetSize())
    f.CenterOnParent()
    f.SetMinSize(f.GetSize())
    wx.FutureCall(120, f.Show)
    app.MainLoop()
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.