view_fax.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 » view_fax.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys, time, tempfile, shutil, subprocess
from twisted.internet import defer

import wx_util, FreeImagePy, img_view

def new_view_fax(inst, opt_cls, paths, attrName = 'view_fax', set = 1):
    """ Control if I have to reinit the view_fax class
        Use me if you want to call view_fax
    """
    #No class presents, go with it
    if not hasattr(inst, attrName) or not getattr(inst, 'view_fax'):
        print 'FreeImage init'
        view = view_fax(opt_cls, paths)
        return view.initLib()
    # I found an already instanced class, so return ok
    else:
        print 'FreeImage already done'
        return (0, 'ok_yet', getattr(inst, 'view_fax') )

class view_fax:
    def __init__(self, opt_cls, paths):
        self.paths = paths
        self.opt_cls = opt_cls
        self.offline = 0
        self.use_FreeImage = 0

    def initLib(self):
        """ Return the status of library initialization
        """
        lib_path = self.opt_cls.get('txt_freeimage_path')
        use_freeimage = self.opt_cls.getint('chk_use_freeimage')

        #Send error
        if use_freeimage and lib_path == '':
            self.offline = 1
            return (2, 'error', self)
        elif use_freeimage:
            self.freeImage = FreeImagePy.Image(libraryName=lib_path)
            ret, status = self.freeImage.getStatus()
            #All ok
            if ret == 0:
                self.use_FreeImage = 1
                self.paths.log4write.write("Init library: %s, Version: %s" % 
                            (status, self.freeImage.GetVersion()) )
            #Some errors, exit
            else:
                self.offline = 1
                return (3, status, self)
        return 0, 'ok_new', self

    def loadAndSave(self, *args):
        return self.freeImage.loadAndSave(*args)

    def concatenate(self, file_lst):
        if self.offline: return 'error'
        #Concatenate (and convert) more than one fax
        lst2convert = []
        self._lbox_attachList = []
        file_lst = [ str(x) for x in file_lst ]
        for file in file_lst:
            ext = os.path.splitext(file)[1].lower()
            if ext == '.ps' or ext == '.pdf':
                d = defer.Deferred()
                d.addCallback(self._convert_files_ps, tofo = 'tiffg3', ext = 'tif')
                d.addCallback(self._convert_end)
                d.addCallback(self.__get_args)
                d.callback(file)
            else:
                self._lbox_attachList.append(file)
            self.paths.log4write.write('concatenate, add %s'  % (file))
        fo = tempfile.mkstemp(dir=self.paths.tmp_dir)[1]  + '.tif'

        self.paths.log4write.write('concatenate, convertToMultiPage: from %s to %s'
                % (self._lbox_attachList, fo))
        if self.use_FreeImage:
            ret = self.freeImage.convertToMultiPage(self._lbox_attachList, fo,
                flags=FreeImagePy.TIFF_CCITTFAX3, convertToFax=1, deleteOld=1)
        else:
            return self._lbox_attachList

        if ret[0] == 0:
            return fo
        else:
            return 'Error: %s' % str(ret[1])

    def __get_args(self, ret):
        if not ret:
            return
        for val in ret:
            self._lbox_attachList.append(val)

    def view_file(self, tof, file = '', text4print = '', modify=0):
        if self.offline: return 'error'
        if not file:
            if tof == 4 or tof == 9:
                file = self.paths.temp_file_tiff
            else:
                file = self.paths.temp_file_ps
        msg = "I'll open the file: %s, type: %s" % (file, tof)
        self.paths.log4write.write(msg)
        
        #Call convert
        if self.opt_cls.getint('chk_int_view'):
            
            if tof == 4 or tof == 9:
                fileList = self._convert_file_tif(file, type="png")
            else:
                ret = self._convert_files_ps(file, tofo='pngmono', ext='png')
                fileList = self._convert_end(ret)
            
            self._view_file_prog(fileList, tof, text4print, modify)

        else:
            self._view_file_prog('', tof)

    def _convert_file_tif(self, fi, fo = '', type='tif'):
        if self.offline: return 'error'

        #Convert file and return files names
        if not fi:
            print 'no fi in _convert_file_tif'
            return
        if not fo:
            fo = tempfile.mkstemp(dir=self.paths.tmp_dir)[1]
        self.paths.log4write.write('tiff conversion: %s -> %s, type: %s'
            % (fi, fo, type))

        if self.use_FreeImage:
            if type == 'tif':
                return self.freeImage.convertToSinglePages(fi, FreeImagePy.FIF_TIFF,
                        '.tiff', outputName=fo, flags=FreeImagePy.TIFF_DEFAULT,
                        bitmapType=FreeImagePy.FIF_TIFF)
            else:
                try:
                    return self.freeImage.convertToSinglePages(fi, FreeImagePy.FIF_PNG,
                        '.png', outputName=fo)
                except:
                    #There are errors on conversion
                    return ["ERROR on convert file... Why?"]
        else:
            if os.path.splitext(fi)[1] == '.png': return (fi,)
            lstReturn = list()
            for num in range(wx.Image_GetImageCount(fi, wx.BITMAP_TYPE_ANY)):
                file_out = '%s%s.png' % (fo, num)
                image = wx.Image(fi, index=num)
                type = wx.BITMAP_TYPE_PNG
                image.SaveFile(file_out, type)
                lstReturn.append(file_out)
            return lstReturn


    def _convert_files_ps(self, fi, fo = None, tofo = 'tiffg3', ext = 'tif'):
        #tofo = Type Of File Out, fo = File Name Out
        #fi = File Name In
        tofo = "pnggray"
        ext = "png"
        if self.offline: return ('error', 'error')

        if not fo: fo = tempfile.mkstemp(dir=self.paths.tmp_dir)[1]
        if sys.platform == 'win32':
            #If my s.o. win9x

            #Control the right of the out folder
            self.paths.log4write.write(fo)

            try:
                f = file(fo, 'w')
                f.write('test to write')
                f.close()
            except Exception, ex:
                self.paths.log4write.write('I cannot open the file: %s, Error: %s' % (fo, ex) )
                fo = tempfile.mkstemp()[1]
                self.paths.log4write.write('I create a new one: %s ' % fo)

                fi_n = tempfile.mkstemp()[1]
                shutil.copyfile(fi, fi_n)
                time.sleep(0.3)
                fi = fi_n

            #Create the out filename
            if sys.getwindowsversion()[3] == 1:
                fo += ('%%d.' + ext)
            else:
                fo += ('%d.' + ext)

            gs_home = self.opt_cls.get('txt_gs_home')
            lib_path = os.path.join(gs_home, 'lib')
            if not ( os.path.exists(gs_home) and os.path.exists(lib_path) ):
                wx.MessageBox("Ghostscript not exists!\n%s\nChange it on Configure" % (gs_home + "\n" + lib_path),
                    "Error", wx.ICON_ERROR)


            #Create font path
            fonts_path = os.path.join(
                    os.path.normpath(os.path.join(gs_home, '..\\')),
                    'fonts')
            args = ['-I"%s;%s"' % (lib_path , fonts_path)]
        else:
            fo += ('%d.' + ext)
            args = []

        args += [' -sDEVICE=%s ' % tofo, '-q -dBATCH -dNOPAUSE -r204x196 -sPAPERSIZE=a4 ',
                '-sOutputFile="%s" ' % fo,' "%s" ' % fi]

        #Create argoments
        reg = self.__prep_args(args)
        cmd_exe = '"%s" %s' % (self.opt_cls.get('txt_gs'), reg)
        if sys.platform.startswith("win"):
           cmd_exe = '"%s"' % cmd_exe
        self.paths.log4write.write(cmd_exe)
        
        inp,out,err = os.popen3(cmd_exe)
        
        #Only need for slow HD or LAN work
        time.sleep(0.3)
        self.paths.log4write.write(err)
        self.paths.log4write.write(out)

        f_name = fo[:fo.find('%')]

        return f_name, ext

    def _convert_end(self, ret):
        """ The conversion with gs is ended, so now go to find how many pages
            it has create
        """
        if self.offline: return 'error'
        f_name, ext = ret
        dir_work = os.path.dirname(f_name)
        f_name = os.path.split(f_name)[1]
        f_name_len = len(f_name)

        #Number of page
        NP = 1
        f_name_list = []
        time.sleep(0.2)
        for i in os.listdir(dir_work):
            if i[:f_name_len] == f_name and len(i) != f_name_len:
                f_name_list.append(os.path.join(dir_work, f_name + str(NP) + '.' + ext))
                NP += 1
        return f_name_list

    def __prep_args(self, args, space = 0):
        arg = ''
        for i in args:
            if space:
                arg = arg + ' ' + i
            else:
                arg += i
        return arg

    def _view_file_prog(self, ret, tof, text4print = '', modify=0, funct4save=''):
        print '_view_file_prog'
        if self.offline: return 1
        if self.opt_cls.getint('chk_int_view'):
            if not ret:
                self.paths.log4write.write('No open file in _view_file_prog, exit')
                print 'No open file in _view_file_prog, exit'
                return 1

            my_view = img_view.Img_view(None, ret, close = 0, text4print = text4print,
                paths = self.paths, opt_cls = self.opt_cls, modify = modify,
                funct4save=funct4save)
            my_view.Show()
            return 0
        else:
            if tof == 4 or tof == 9: #tiff
                if ret:
                    new_file_name = os.path.join(self.paths.tmp_dir, 'file_temp_tiff.tif')
                    shutil.copy(ret, new_file_name)
                    file = new_file_name
                else: file = self.paths.temp_file_tiff
                prog_path = self.opt_cls.get('txt_tiff_view')
            else:
                if ret: file = ret
                else: file = self.paths.temp_file_ps
                prog_path = self.opt_cls.get('txt_ps_view')
            
            #
            # Wait some time before open the file, so the os can flush to the fs the data
            #
            
            time.sleep(0.5)
            
            if prog_path:
                args = [prog_path, file]
                subprocess.Popen(args)
                self.paths.log4write.write(
                    "Open external image view: %s, args: %s" % (prog_path, args))
            else:
                os.system(file)
                self.paths.log4write.write(
                    "No external image view. Open system default: %s" % file)
            return 0

    def closeLib(self):
        """ Call me before exit!!!
        """
        if self.use_FreeImage:
            self.freeImage.DeInitialise()
    
    def getNumPages(self, file_):
        """ Return the numberof pages
        """
        self.freeImage.load(file_)
        return self.freeImage.getNumPages()
    
    def getTiffInfo(self, file):
        """ Return tiff informations
        """
    def getTiffInfo(self, file_):
        """ Return tiff informations
        """
        args = [self.paths.tiffinfo, file_]
        self.paths.log4write.write("I execute (at getTiffInfo): %s" % str(args))
        out, err = subprocess.Popen(args, stdin=subprocess.PIPE,
                 stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
        dictVal = dict()
        for line in out:
            values = line.split(":", 1)
            if len(values) == 1: continue
            key, val = values
            dictVal[key.strip()] = val.replace('"', '').strip()
        return dictVal
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.