Пример #1
0
    def export_kv(self, PATH=None):
        if PATH is None:
            from conf import gamepath
            PATH = gamepath
        from kivy.logger import Logger
        #print " -- EXPORT KV  -- "*10
        from conf import CP
        relativ = CP.getboolean('Designer', 'TMPL_RELATIVE_SIZE_POS')
        save_cm = CP.getboolean('Designer', 'SAVE_IN_CM')
        save_relpath = CP.getboolean('Designer', 'TMPL_RELATIVE_GAMEPATH')
        imports = list()
        directives = self.current_template.directives[:]
        #Will be used to find a interresting base for relpath
        print 'at this stage, i should insert a check for name vs libraty & templates'
        if not self.current_template.template_name:
            print 'Current template as no name: reverting to default'
            self.current_template.template_name = "TMPL"
        KV = list()
        for template in self.templates:
            tmpls, imports, directives = template.export_to_kv(
                level=1,
                save_cm=save_cm,
                relativ=relativ,
                save_relpath=save_relpath,
                RELPATH=PATH)
            Logger.debug('export these imports to kv: ' + str(imports))
            print self.nodes, template
            for node in self.nodes[template].nodes:
                if not hasattr(node, 'target'):
                    continue
                field = node.target
                if field == template:  #skip export of the root template: done above
                    continue
                t, i, d = field.export_field(level=2,
                                             save_cm=save_cm,
                                             relativ=relativ,
                                             save_relpath=save_relpath,
                                             RELPATH=PATH)
                tmpls.extend(t)
                imports.extend(i)
                directives.extend(d)
            #Prepend include
            if imports:
                tmpls.insert(0, "")
                for imp in imports:
                    if imp:
                        tmpls.insert(0, "#:include %s" % imp)
            Logger.debug("directives at the end" + str(directives))
            if directives:
                tmpls.insert(0, "")
                for directive in directives:
                    tmpls.insert(0, "#:%s" % directive)

            from os import linesep
            KV.append(linesep.join(tmpls))
            KV.extend('  ')
        return linesep.join(KV)
Пример #2
0
    def export_kv(self, PATH=None):
        if PATH is None:
            from conf import gamepath
            PATH = gamepath
        from kivy.logger import Logger
        #print " -- EXPORT KV  -- "*10
        from conf import CP
        relativ = CP.getboolean('Designer', 'TMPL_RELATIVE_SIZE_POS')
        save_cm = CP.getboolean('Designer', 'SAVE_IN_CM')
        save_relpath = CP.getboolean('Designer', 'TMPL_RELATIVE_GAMEPATH')
        imports = list()
        directives = self.current_template.directives[:]
        #Will be used to find a interresting base for relpath
        print 'at this stage, i should insert a check for name vs libraty & templates'
        if not self.current_template.template_name:
            print 'Current template as no name: reverting to default'
            self.current_template.template_name = "TMPL"
        KV = list()
        for template in self.templates:
            tmpls, imports, directives = template.export_to_kv(level=1, save_cm=save_cm, relativ=relativ, save_relpath=save_relpath, RELPATH=PATH)
            Logger.debug('export these imports to kv: ' + str(imports))
            print self.nodes, template
            for node in self.nodes[template].nodes:
                if not hasattr(node, 'target'):
                    continue
                field = node.target
                if field == template: #skip export of the root template: done above
                    continue
                t, i, d = field.export_field(level=2, save_cm=save_cm, relativ=relativ, save_relpath=save_relpath, RELPATH=PATH)
                tmpls.extend(t)
                imports.extend(i)
                directives.extend(d)
            #Prepend include
            if imports:
                tmpls.insert(0, "")
                for imp in imports:
                    if imp:
                        tmpls.insert(0,"#:include %s"%imp)
            Logger.debug("directives at the end" + str(directives))
            if directives:
                tmpls.insert(0,"")
                for directive in directives:
                    tmpls.insert(0, "#:%s"%directive)

            from os import linesep
            KV.append(linesep.join(tmpls))
            KV.extend('  ')
        return linesep.join(KV)
Пример #3
0
 def write_file_popup(self, title, cb, default='export.pdf'):
     from conf import CP
     if default.endswith('.pdf'):
         lf = CP.get('Path', 'last_pdf')
     else:
         lf = CP.get('Path', 'last_file')
     if default.endswith(('.csv', '.xlsx')): #try to use last file if exsits
         default = lf or default
     elif default.endswith('.pdf'):
         if lf:
             default = lf.replace('.xlsx', '.pdf').replace('.csv', '.pdf')
     p = Factory.get('WriteFilePopup')()
     p.title = title
     p.cb = cb
     p.default_name = default
     p.open()
Пример #4
0
    def build(self):
        from conf import CP, gamepath
        from utils import path_reader
        root = RootWidget()
        if CP.getboolean('Startup', 'load_tmpl_lib'):
            root.ids.deck.load_template_lib(force_reload=True,
                                            background_mode=True)
        if CP.getboolean('Startup', 'startup_tips'):
            from kivy.factory import Factory
            p = Factory.StartupPopup()
            from kivy.clock import Clock

            def _inner(*args):
                p.open()

            Clock.schedule_once(_inner)
        if gamepath:
            from kivy.clock import Clock
            from time import clock
            #Startup file csv
            fpath = CP.get('Path', 'last_file')
            from os.path import join, isfile, split
            j = join(gamepath, fpath)
            TARGET = None
            if isfile(j):
                TARGET = join(gamepath, fpath)
            elif isfile(path_reader(fpath)):
                TARGET = path_reader(fpath)

            def launcher(*args):
                if TARGET:
                    root.ids.deck.load_folder(split(TARGET)[0])
                    if TARGET.endswith('.xlsx'):
                        root.ids.deck.load_file(TARGET)
                    elif TARGET.endswith('.csv'):
                        root.ids.deck.load_file_csv(TARGET)

            Clock.schedule_once(launcher, .2)
            #Filling ENV Global Variable
            from conf import fill_env
            Clock.schedule_once(fill_env, 1)

        #Dropfile Mngt
        from kivy.core.window import Window
        Window.bind(on_dropfile=self.load_file)

        return root
Пример #5
0
 def write_file_popup(self, title, cb, default='export.pdf'):
     from conf import CP
     if default.endswith('.pdf'):
         lf = CP.get('Path', 'last_pdf')
     else:
         lf = CP.get('Path', 'last_file')
     if default.endswith(
         ('.csv', '.xlsx')):  #try to use last file if exsits
         default = lf or default
     elif default.endswith('.pdf'):
         if lf:
             default = lf.replace('.xlsx', '.pdf').replace('.csv', '.pdf')
     p = Factory.get('WriteFilePopup')()
     p.title = title
     p.cb = cb
     p.default_name = default
     p.open()
Пример #6
0
 def save(self, PATH=None, *args):
     from conf import CP
     from os.path import isfile, split, splitext
     if PATH is not None:
         self.current_template.template_name = splitext(
             split(PATH)[-1])[0].capitalize()
         self.tmplPath = PATH
     else:
         self.current_template.template_name = self.current_template.template_name.capitalize(
         )
     if PATH is None:
         if self.tmplPath:
             PATH = self.tmplPath
             if "@" in PATH:
                 PATH = PATH.split('@')[-1]
             overwrite = True
         else:
             PATH = 'templates/%s.kv' % self.current_template.template_name
             overwrite = CP.getboolean('Designer', 'OVERWRITE_SAVED_TMPL')
             alert('Template Saved in Library as %s.kv' %
                   self.current_template.template_name)
     else:
         overwrite = CP.getboolean('Designer', 'OVERWRITE_SAVED_TMPL')
     exists = isfile(PATH)
     kv = self.export_kv(split(PATH)[0])
     if overwrite or not exists:
         file(PATH, 'wb').write(kv)
     else:
         from utils import alert
         alert('Template %s already exists !' % PATH)
         return
     from utils import alert
     alert('Template %s saved' % self.current_template.template_name)
     #Force update on deck widget
     from kivy.app import App
     deck = App.get_running_app().root.ids.deck
     stack = deck.ids['stack']
     from template import find_template_path, templateList
     templateList.register_file(PATH)
     for child in stack.children:
         if not hasattr(child, 'template'): continue
         _, tpath = find_template_path(getattr(child, 'template'))
         if tpath.endswith(PATH):
             child.realise(use_cache=True)
     print 'todo: how do I save pultiple template on a single KV file ? '
Пример #7
0
    def build(self):
        from conf import CP, gamepath
        from utils import path_reader
        root = RootWidget()
        if CP.getboolean('Startup', 'load_tmpl_lib'):
            root.ids.deck.load_template_lib(force_reload=True, background_mode=True)
        if CP.getboolean('Startup', 'startup_tips'):
            from kivy.factory import Factory
            p = Factory.StartupPopup()
            from kivy.clock import Clock
            def _inner(*args):
                p.open()
            Clock.schedule_once(_inner)
        if gamepath:
            from kivy.clock import Clock
            from time import clock
            #Startup file csv
            fpath = CP.get('Path','last_file')
            from os.path import join, isfile, split
            j = join(gamepath,fpath)
            TARGET= None
            if isfile(j):
                TARGET = join(gamepath,fpath)
            elif isfile(path_reader(fpath)):
                TARGET = path_reader(fpath)
            def launcher(*args):
                if TARGET:
                    root.ids.deck.load_folder(split(TARGET)[0])
                    if TARGET.endswith('.xlsx'):
                        root.ids.deck.load_file(TARGET)
                    elif TARGET.endswith('.csv'):
                        root.ids.deck.load_file_csv(TARGET)
            Clock.schedule_once(launcher,.2)
            #Filling ENV Global Variable
            from conf import fill_env
            Clock.schedule_once(fill_env, 1)

        #Dropfile Mngt
        from kivy.core.window import Window
        Window.bind(on_dropfile=self.load_file)


        return root
Пример #8
0
 def save(self,PATH=None, *args):
     from conf import CP
     from os.path import isfile, split, splitext
     if PATH is not None:
         self.current_template.template_name = splitext(split(PATH)[-1])[0].capitalize()
         self.tmplPath = PATH
     else:
         self.current_template.template_name = self.current_template.template_name.capitalize()
     if PATH is None:
         if self.tmplPath:
             PATH = self.tmplPath
             if "@" in PATH:
                 PATH = PATH.split('@')[-1]
             overwrite = True
         else:
             PATH = 'templates/%s.kv'%self.current_template.template_name
             overwrite = CP.getboolean('Designer','OVERWRITE_SAVED_TMPL')
             alert('Template Saved in Library as %s.kv'%self.current_template.template_name)
     else:
         overwrite = CP.getboolean('Designer', 'OVERWRITE_SAVED_TMPL')
     exists = isfile(PATH)
     kv = self.export_kv(split(PATH)[0])
     if overwrite or not exists:
         file(PATH,'wb').write(kv)
     else:
         from utils import alert
         alert('Template %s already exists !'%PATH)
         return
     from utils import alert
     alert('Template %s saved'%self.current_template.template_name)
     #Force update on deck widget
     from kivy.app import App
     deck = App.get_running_app().root.ids.deck
     stack = deck.ids['stack']
     from template import find_template_path, templateList
     templateList.register_file(PATH)
     for child in stack.children:
         if not hasattr(child, 'template'): continue
         _, tpath = find_template_path(getattr(child, 'template'))
         if tpath.endswith(PATH):
             child.realise(use_cache=True)
     print 'todo: how do I save pultiple template on a single KV file ? '
Пример #9
0
        from kivy.metrics import cm
        self.size = color.size = (cm(6.5),cm(8.8))
        from kivy.clock import Clock

#templateList.register(RedSkin())


#Now load all files from the templates dir to templatelist
def LoadTemplateFolder(folder="templates"):
    from glob import glob
    from os.path import join
    for kv in glob(join(folder, '*.kv')):
        templateList.register_file(kv)

from conf import CP
if CP.getboolean('Startup', 'LOAD_TMPL_LIB'):
    LoadTemplateFolder()


def find_template_path(filename):
    from os.path import abspath, isfile, join
    from conf import gamepath
    from utils import find_path
    if "@" in filename: #Only using subone
        name, filename = filename.split('@')
    else:
        name = ""
    r = find_path(filename)
    from kivy.resources import resource_paths, resource_find
    #for p in resource_paths: print p, isfile(join(p,filename))
    if not r or not isfile(r):
Пример #10
0
    def generation_step(self, with_realize=False):
        "Will be called in order to show some advancement"
        i, row, col, face, item = self.index.pop()

        #Determine wheter a new page should be appended

        face_index = 0 if self.current_face == 'F' else 1
        if self.current_face != face:
            self.current_face = face
            self.current_page_num[1 - face_index] = i
            self.AddPage()
        elif self.current_page_num[face_index] != i:
            self.current_page_num[face_index] = i
            self.AddPage()

        #Determine Image X/Y/W/H depending on print mode
        if self.mode == 'LAYOUT':
            x, y, self.x, self.y, angle, pageindex = item.layout
            x /= cm(1)
            y /= cm(1)
            self.x /= cm(1)
            self.y /= cm(1)
        elif self.mode == 'BINCAN':
            x, y, self.x, self.y, angle, item = item  #hackick: replace item in place !
            x /= cm(1)
            y /= cm(1)
            self.x /= cm(1)
            self.y /= cm(1)
        else:
            if face == 'F':
                x, y = col * self.x + left, height - (1 + row) * self.y - top
            else:
                x, y = width - (1 + col) * self.x - left - right, height - (
                    1 + row) * self.y - top
                #x, y = width - (1+col)*self.x - right, height-(1+row)*self.y - top
            #self.x & slef.y has already been setp by calculate_size
            #Check is there is a layout that could be used, just for the angle
            if getattr(item, 'layout', 0):
                angle = item.layout[4]
            else:
                angle = 0

        #Now that in item lies the Stack Item, before rendering it, inject special print vairables
        item.print_index = {
            'pagenum': i,
            'stackrow': row,
            'stackcol': col,
            'pageface': face
        }

        # Now, define source for image: we either get the source or convert to image
        if item.image:  #speicla case for complex image manip

            src = ImageReader(item.image.rotate(angle))
        elif item.template:
            if with_realize:
                item.realise(True, True)
                tmplWidget = item.tmplWidget
            elif item.tmplWidget:  #it has been modified
                tmplWidget = item.tmplWidget
            else:
                from template import BGTemplate
                Logger.info('[Printer] Generation Step without tmplWidget')
                tmplWidget = BGTemplate.FromFile(item.template)
                if tmplWidget:
                    #only taking the last one
                    tmplWidget = tmplWidget[-1]
                else:
                    raise NameError('No such template: ' + item.template)
                if item.values:
                    tmplWidget.apply_values(item.values)
                from kivy.base import EventLoop
                EventLoop.idle()
            cim = tmplWidget.toImage(for_print=True)
            pim = frombuffer('RGBA', cim.size, cim._texture.pixels, 'raw',
                             'RGBA', 0, 1)
            src = ImageReader(pim.rotate(angle))
        else:
            src = item.source
            from utils import find_path
            src = find_path(src)
            if angle:
                src = ImageReader(PILOpen(src).rotate(angle))

        #print "Adding Image to pdf", i, row, col, face, item, src, x, y, self.x, self.y, angle
        self.pdf.drawImage(src,
                           x * r_cm,
                           y * r_cm,
                           self.x * r_cm,
                           self.y * r_cm,
                           mask='auto')
        from conf import CP
        if CP.getboolean('Print', 'draw_cut_rect'):
            #add line after image: they ll be above
            self.AddLines(x, y, self.x, self.y)
Пример #11
0
 def record_last_file(self,filepath):
     #set path as last_opoend_file
     from conf import CP, gamepath
     from os.path import relpath
     if filepath.startswith(gamepath):
         fpath = relpath(filepath,gamepath)
     else:
         fpath = filepath
     if not(fpath):
         CP.set('Path','last_pdf',fpath)
         CP.set('Path', 'last_file', fpath)
         CP.write()
     elif fpath.endswith('.pdf'):
         CP.set('Path','last_pdf',fpath)
         CP.write()
     else:
         CP.set('Path', 'last_file', fpath)
         CP.write()
Пример #12
0
    def prepare_print(self, dst):
        """Launch PDF preparation. First determine the best method for placing images"""
        from conf import CP
        from utils import alert
        if CP.getboolean('Print', 'AUTOCSV'):
            alert('Auto saving XLS deck')
            self.export_file(dst.replace('.pdf', '.xlsx'))
        #Save last pdf file name & path
        self.record_last_file(dst)
        from printer import prepare_pdf
        from conf import card_format
        FFORMAT = (card_format.width, card_format.height)
        #3 possibilites
        # If FORCE_FOMART, just use it with auto layout placement
        if self.ids['force_format'].active:
            mode = 'FORCED'
        else:
            #Loop on all stack & check their size.
            #IF ALL have layout, launch print with layout
            #ELSE
            USE_LAYOUT = True
            sizes = set()
            WARNING = False
            for cs in self.ids.stack.children:
                if cs.layout:
                    WARNING = True
                else:
                    USE_LAYOUT = False
                    if WARNING:
                        from utils import alert
                        alert(
                            'Can not have both with and without layout (%s was without)!'
                            % cs)
                        return
                if cs.template:
                    if cs.tmplWidget:
                        sizes.add(tuple(cs.tmplWidget.size))
                    else:
                        from template import BGTemplate
                        sizes.add(
                            tuple(
                                BGTemplate.FromFile(cs.template,
                                                    use_cache=True)[-1].size))
                elif cs.image:
                    sizes.add(cs.image.size)
                else:
                    sizes.add(FFORMAT)
            if USE_LAYOUT:
                mode = 'LAYOUT'
            else:
                if len(sizes) == 1:
                    mode = sizes.pop()
                else:
                    mode = 'BINCAN'
        #Now add the advancement gauge
        progress = self.ids['load_progress']
        progress.value = 0
        #ensure the stop button is reachable
        self.ids['stop_action'].width = 80
        self.ids['stop_action'].text = 'Stop'
        self.cancel_action = False
        size, book = prepare_pdf(stack=self.ids['stack'],
                                 dst=dst,
                                 console_mode=False,
                                 mode=mode)
        progress.max = size
        from kivy.clock import Clock
        step_counter = range(size)

        #Now ensure that ALL stackpart from front & back are realized, while re-creating cache
        from template import templateList
        templateList.templates = dict()
        SS = book.stack[0] + book.stack[1]

        def inner(*args):
            step_counter.pop()
            progress.value += 1
            #print 'remaninig index', len(book.index)
            book.generation_step()
            if (not step_counter) or self.cancel_action:
                self.cancel_action = False
                Clock.unschedule(inner)
                self.ids['stop_action'].width = 0
                self.ids['stop_action'].text = ''
                progress.value = 0
                book.save()
                book.show()
                from utils import alert
                alert('PDF Export completed')
                return False
            else:
                Clock.schedule_once(inner, 0.01)

        def realize_inner(*args):
            s = SS.pop()
            s.realise(withValue=True, use_cache=True)
            if SS:
                Clock.schedule_once(realize_inner, 0.01)
            else:
                Clock.schedule_once(inner, .1)

        if step_counter:
            Clock.schedule_once(inner, .1)
        return True
Пример #13
0
    def prepare_print(self, dst):
        """Launch PDF preparation. First determine the best method for placing images"""
        from conf import CP
        from utils import alert
        if CP.getboolean('Print', 'AUTOCSV'):
            alert('Auto saving XLS deck')
            self.export_file(dst.replace('.pdf','.xlsx'))
        #Save last pdf file name & path
        self.record_last_file(dst)
        from printer import prepare_pdf
        from conf import card_format
        FFORMAT = (card_format.width, card_format.height)
        #3 possibilites
        # If FORCE_FOMART, just use it with auto layout placement
        if self.ids['force_format'].active:
            mode = 'FORCED'
        else:
            #Loop on all stack & check their size.
            #IF ALL have layout, launch print with layout
            #ELSE
            USE_LAYOUT = True
            sizes = set()
            WARNING = False
            for cs in self.ids.stack.children:
                if cs.layout:
                    WARNING = True
                else:
                    USE_LAYOUT = False
                    if WARNING:
                        from utils import alert
                        alert('Can not have both with and without layout (%s was without)!'%cs)
                        return
                if cs.template:
                    if cs.tmplWidget:
                        sizes.add(tuple(cs.tmplWidget.size))
                    else:
                        from template import BGTemplate
                        sizes.add(tuple(BGTemplate.FromFile(cs.template, use_cache=True)[-1].size))
                elif cs.image:
                    sizes.add(cs.image.size)
                else:
                    sizes.add(FFORMAT)
            if USE_LAYOUT:
                mode = 'LAYOUT'
            else:
                if len(sizes) == 1:
                    mode = sizes.pop()
                else:
                    mode = 'BINCAN'
        #Now add the advancement gauge
        progress = self.ids['load_progress']
        progress.value = 0
        #ensure the stop button is reachable
        self.ids['stop_action'].width = 80
        self.ids['stop_action'].text = 'Stop'
        self.cancel_action = False
        size, book = prepare_pdf(stack=self.ids['stack'], dst=dst, console_mode= False, mode = mode)
        progress.max = size
        from kivy.clock import Clock
        step_counter = range(size)

        #Now ensure that ALL stackpart from front & back are realized, while re-creating cache
        from template import templateList
        templateList.templates = dict()
        SS = book.stack[0] + book.stack[1]

        def inner(*args):
            step_counter.pop()
            progress.value += 1
            #print 'remaninig index', len(book.index)
            book.generation_step()
            if (not step_counter) or self.cancel_action:
                self.cancel_action = False
                Clock.unschedule(inner)
                self.ids['stop_action'].width = 0
                self.ids['stop_action'].text = ''
                progress.value = 0
                book.save()
                book.show()
                from utils import alert
                alert('PDF Export completed')
                return False
            else:
                Clock.schedule_once(inner, 0.01)

        def realize_inner(*args):
            s = SS.pop()
            s.realise(withValue=True, use_cache=True)
            if SS:
                Clock.schedule_once(realize_inner, 0.01)
            else:
                Clock.schedule_once(inner,.1)

        if step_counter:
            Clock.schedule_once(inner, .1)
        return True
Пример #14
0
    def export_file(self, filepath='myxlfile.xlsx'):
        from collections import OrderedDict
        from conf import gamepath
        from os.path import relpath, isfile, splitext, split
        self.record_last_file(filepath)
        FOLDER, FNAME = split(filepath)
        FNAME = splitext(FNAME)[0]
        od = OrderedDict()
        cards = list()
        HAS_LAYOUT = False
        HAS_TEMPLATE = False
        HAS_SOURCE = False
        for item in reversed(self.ids['stack'].children):
            if not isinstance(item, Factory.get('StackPart')): continue
            d = dict()
            d['qt'] = item.qt
            if item.source:
                HAS_SOURCE = True
                if isfile(item.source): #it is a full path. convert it
                    _s = relpath(item.source, gamepath)
                    if item.source.startswith(FOLDER):
                        _s = relpath(item.source, FOLDER)
                else:
                    _s = item.source
                if item.template and item.source == 'img/card_template.png':
                    _s = ""
                d['source'] = _s
            else:
                d['source'] = ""
            if item.template:
                HAS_TEMPLATE = True
                d['template'] = item.template
            d['dual'] = not(item.verso == 'normal')
            d['values'] = item.values
            if item.layout:
                HAS_LAYOUT = True
                #d['layout'] = item.layout
                _x,_y,_w,_h,_a, _p = item.layout
                d['layout_w'] = _w
                d['layout_h'] = _h
                d['layout_y'] = _y
                d['layout_x'] = _x
                d['layout_page'] = _p
                d['layout_angle'] = _a

            cards.append(d)
        od['cards'] = cards
        from conf import CP
        mode = CP.get('Export','format')
        if mode =='csv':
            self.export_file_CSV(cards, filepath, HAS_LAYOUT)
            return
        elif mode == 'xlsx':
            #Now also XL export
            import openpyxl
            from openpyxl.utils import get_column_letter
            if cards:
                my_dict = {}
                #update the dict with all possible 'values' keys
                for c in cards:
                    if c['values']:
                        my_dict.update(**c['values'])
                wb= openpyxl.Workbook()
                ws = wb.active
                ws.title = FNAME
                fields_order = ['qt','dual']
                if HAS_TEMPLATE:
                    fields_order.append('template')
                if HAS_SOURCE:
                    fields_order.append('source')
                if HAS_LAYOUT:
                    fields_order.extend([ 'layout_x','layout_y','layout_w','layout_h', 'layout_angle','layout_page'])
                fields_order.extend(sorted(my_dict.keys()))
                for colindex, h in enumerate(fields_order):
                    ws['%s%s'%(get_column_letter(colindex+1),1)] = h
                for rowindex,c in enumerate(cards):
                    for k in my_dict:
                        my_dict[k]=None
                    my_dict.update(c)
                    del my_dict['values']
                    my_dict.update(**c['values'])
                    for colindex,h in enumerate(fields_order):
                        _v = my_dict[h]
                        ws['%s%s' % (get_column_letter(colindex+1),rowindex+2)] = _v
            wb.save(filepath)
        from utils import alert
        from os.path import split
        alert('Exporting %s over'%split(filepath)[-1])
Пример #15
0
 def record_last_file(self, filepath):
     #set path as last_opoend_file
     from conf import CP, gamepath
     from os.path import relpath
     if filepath.startswith(gamepath):
         fpath = relpath(filepath, gamepath)
     else:
         fpath = filepath
     if not (fpath):
         CP.set('Path', 'last_pdf', fpath)
         CP.set('Path', 'last_file', fpath)
         CP.write()
     elif fpath.endswith('.pdf'):
         CP.set('Path', 'last_pdf', fpath)
         CP.write()
     else:
         CP.set('Path', 'last_file', fpath)
         CP.write()
Пример #16
0
    def export_file(self, filepath='myxlfile.xlsx'):
        from collections import OrderedDict
        from conf import gamepath
        from os.path import relpath, isfile, splitext, split
        self.record_last_file(filepath)
        FOLDER, FNAME = split(filepath)
        FNAME = splitext(FNAME)[0]
        od = OrderedDict()
        cards = list()
        HAS_LAYOUT = False
        HAS_TEMPLATE = False
        HAS_SOURCE = False
        for item in reversed(self.ids['stack'].children):
            if not isinstance(item, Factory.get('StackPart')): continue
            d = dict()
            d['qt'] = item.qt
            if item.source:
                HAS_SOURCE = True
                if isfile(item.source):  #it is a full path. convert it
                    _s = relpath(item.source, gamepath)
                    if item.source.startswith(FOLDER):
                        _s = relpath(item.source, FOLDER)
                else:
                    _s = item.source
                if item.template and item.source == 'img/card_template.png':
                    _s = ""
                d['source'] = _s
            else:
                d['source'] = ""
            if item.template:
                HAS_TEMPLATE = True
                d['template'] = item.template
            d['dual'] = not (item.verso == 'normal')
            d['values'] = item.values
            if item.layout:
                HAS_LAYOUT = True
                #d['layout'] = item.layout
                _x, _y, _w, _h, _a, _p = item.layout
                d['layout_w'] = _w
                d['layout_h'] = _h
                d['layout_y'] = _y
                d['layout_x'] = _x
                d['layout_page'] = _p
                d['layout_angle'] = _a

            cards.append(d)
        od['cards'] = cards
        from conf import CP
        mode = CP.get('Export', 'format')
        if mode == 'csv':
            self.export_file_CSV(cards, filepath, HAS_LAYOUT)
            return
        elif mode == 'xlsx':
            #Now also XL export
            import openpyxl
            from openpyxl.utils import get_column_letter
            if cards:
                my_dict = {}
                #update the dict with all possible 'values' keys
                for c in cards:
                    if c['values']:
                        my_dict.update(**c['values'])
                wb = openpyxl.Workbook()
                ws = wb.active
                ws.title = FNAME
                fields_order = ['qt', 'dual']
                if HAS_TEMPLATE:
                    fields_order.append('template')
                if HAS_SOURCE:
                    fields_order.append('source')
                if HAS_LAYOUT:
                    fields_order.extend([
                        'layout_x', 'layout_y', 'layout_w', 'layout_h',
                        'layout_angle', 'layout_page'
                    ])
                fields_order.extend(sorted(my_dict.keys()))
                for colindex, h in enumerate(fields_order):
                    ws['%s%s' % (get_column_letter(colindex + 1), 1)] = h
                for rowindex, c in enumerate(cards):
                    for k in my_dict:
                        my_dict[k] = None
                    my_dict.update(c)
                    del my_dict['values']
                    my_dict.update(**c['values'])
                    for colindex, h in enumerate(fields_order):
                        _v = my_dict[h]
                        ws['%s%s' % (get_column_letter(colindex + 1),
                                     rowindex + 2)] = _v
            wb.save(filepath)
        from utils import alert
        from os.path import split
        alert('Exporting %s over' % split(filepath)[-1])
Пример #17
0
    def generation_step(self, with_realize = False):
        "Will be called in order to show some advancement"
        i, row, col, face, item = self.index.pop()

        #Determine wheter a new page should be appended

        face_index = 0 if self.current_face == 'F' else 1
        if self.current_face != face:
            self.current_face = face
            self.current_page_num[1-face_index] = i
            self.AddPage()
        elif self.current_page_num[face_index] != i:
            self.current_page_num[face_index] = i
            self.AddPage()


        #Determine Image X/Y/W/H depending on print mode
        if self.mode == 'LAYOUT':
            x, y, self.x, self.y, angle, pageindex = item.layout
            x /= cm(1)
            y /= cm(1)
            self.x /= cm(1)
            self.y /= cm(1)
        elif self.mode == 'BINCAN':
            x, y, self.x, self.y, angle, item = item #hackick: replace item in place !
            x /= cm(1)
            y /= cm(1)
            self.x /= cm(1)
            self.y /= cm(1)
        else:
            if face == 'F':
                x, y = col * self.x + left, height-(1+row)*self.y - top
            else:
                x, y = width - (1+col)*self.x - left - right, height-(1+row)*self.y - top
                #x, y = width - (1+col)*self.x - right, height-(1+row)*self.y - top
            #self.x & slef.y has already been setp by calculate_size
            #Check is there is a layout that could be used, just for the angle
            if getattr(item, 'layout',0):
                angle = item.layout[4]
            else:
                angle = 0

        #Now that in item lies the Stack Item, before rendering it, inject special print vairables
        item.print_index = {
            'pagenum' : i,
            'stackrow': row,
            'stackcol': col,
            'pageface': face
        }

        # Now, define source for image: we either get the source or convert to image
        if item.image:#speicla case for complex image manip

            src = ImageReader(item.image.rotate(angle))
        elif item.template:
            if with_realize:
                item.realise(True,True)
                tmplWidget = item.tmplWidget
            elif item.tmplWidget:#it has been modified
                tmplWidget = item.tmplWidget
            else:
                from template import BGTemplate
                Logger.info( '[Printer] Generation Step without tmplWidget')
                tmplWidget = BGTemplate.FromFile(item.template)
                if tmplWidget:
                    #only taking the last one
                    tmplWidget = tmplWidget[-1]
                else:
                    raise NameError('No such template: '+ item.template)
                if item.values:
                    tmplWidget.apply_values(item.values)
                from kivy.base import EventLoop
                EventLoop.idle()
            cim = tmplWidget.toImage(for_print=True)
            pim = frombuffer('RGBA', cim.size, cim._texture.pixels, 'raw', 'RGBA',0,1)
            src = ImageReader(pim.rotate(angle))
        else:
            src = item.source
            from utils import find_path
            src = find_path(src)
            if angle:
                src = ImageReader(PILOpen(src).rotate(angle))

        #print "Adding Image to pdf", i, row, col, face, item, src, x, y, self.x, self.y, angle
        self.pdf.drawImage(src, x*r_cm, y*r_cm, self.x*r_cm, self.y*r_cm, mask='auto')
        from conf import CP
        if CP.getboolean('Print','draw_cut_rect'):
            #add line after image: they ll be above
            self.AddLines(x,y,self.x,self.y)