Beispiel #1
0
 def __init__(self,
              site=None,
              page_id=None,
              request_kwargs=None,
              request_args=None,
              filepath=None,
              packageId=None,
              pluginId=None,
              basename=None,
              page_info=None):
     self._inited = False
     self._start_time = time()
     self.workspace = dict()
     self.sql_count = 0
     self.sql_time = 0
     self.site = site
     if page_info:
         for k, v in page_info.items():
             setattr(self, k, v)
         self.connection = GnrWebConnection(
             self, connection_id=self.connection_id, user=self.user)
     self.page_item = self._check_page_id(page_id, kwargs=request_kwargs)
     #dbstore = request_kwargs.pop('temp_dbstore',None) or None
     #self.dbstore = dbstore if dbstore != self.application.db.rootstore else None
     self.dbstore = None  # find a way to handle it based on call/thread
     self._locale = 'en'  # find a way to handle it based on call/thread
     self._event_subscribers = {}
     self.filepath = filepath
     self.packageId = packageId
     self.pluginId = pluginId
     self.basename = basename
     self.siteFolder = self.site.site_path
     self.folders = self._get_folders()
     self.pagepath = self.filepath.replace(self.folders['pages'], '')
     self._dbconnection = None
     self.application.db.clearCurrentEnv()  # ?? dump and restore?
     self.debug_sql = boolean(request_kwargs.pop('debug_sql', None))
     debug_py = request_kwargs.pop('debug_py', None)
     self.debug_py = False if boolean(debug_py) is not True else debug_py
     self.callcounter = request_kwargs.pop('callcounter', None) or 'begin'
     self.root_page_id = None
     self.parent_page_id = None
     self.sourcepage_id = request_kwargs.pop('sourcepage_id', None)
     self.instantiateProxies()
     self.onPreIniting(request_args, request_kwargs)
     self.onIniting(request_args, request_kwargs)
     self._call_args = request_args or tuple()
     self._call_kwargs = dict(request_kwargs)
     self._workdate = self.page_item['data'][
         'rootenv.workdate']  #or datetime.date.today()
     self._language = self.page_item['data']['rootenv.language']
     self._inited = True
     self._shareds = dict()
     self._privates = defaultdict(dict)
     self.freezedSelections = dict()
     self.envelope_js_requires = {}
     self.envelope_css_requires = {}
Beispiel #2
0
 def _th_prepareForm(self,
                     root,
                     pkey=None,
                     th_kwargs=None,
                     store_kwargs=None,
                     formCb=None,
                     **kwargs):
     pkey = pkey or th_kwargs.pop('pkey', None)
     formResource = th_kwargs.pop('formResource', None)
     root.attributes.update(overflow='hidden')
     public = boolean(th_kwargs.pop('public', False))
     formId = th_kwargs.pop('formId', self.maintable.replace('.', '_'))
     if public:
         root.attributes.update(_class='pbl_root')
         root = root.rootContentPane(title=self.tblobj.name_long)
     else:
         root.attributes.update(tag='ContentPane', _class=None)
     root.attributes.update(datapath=self.maintable.replace('.', '_'))
     formkw = kwargs
     formkw.update(th_kwargs)
     form = root.thFormHandler(table=self.maintable,
                               formId=formId,
                               startKey=pkey,
                               formResource=formResource,
                               formCb=formCb,
                               form_isRootForm=True,
                               **formkw)
     if public:
         form.dataController("""
                         SET gnr.publicTitle = title;
                         """,
                             title='^#FORM.controller.title',
                             _if='title')
     self._th_parentFrameMessageSubscription(form)
     return form
Beispiel #3
0
 def init_options(self):
     self.siteconfig = self.get_config()
     options = self.options.__dict__
     vassals_dir = self.gnr_config['gnr.environment_xml.vassals?path'] or os.path.join(gnrConfigPath(),'uwsgi','vassals')
     vassal_path = os.path.join(vassals_dir,'%s.ini'%self.site_name)
     vassal_params = None
     if os.path.exists(vassal_path):
         
         with open(vassal_path) as vassal_file:
             config_parser = ConfigParser()
             config_parser.readfp(vassal_file)
         try:
             vassal_params = dict(config_parser.items('genropy'))
         except NoSectionError:
             pass
     for option in wsgi_options.keys():
         if options.get(option, None) is None: # not specified on the command-line
             site_option = self.siteconfig['wsgi?%s' % option]
             self.options[option] = site_option or wsgi_options.get(option)
     for (key, dtype) in (('debug','B'),('restore','T'),('profile','B'),('remote_edit','B'),('gzip','B')):
         env_key = 'GNR_%s_%s'%(self.site_name.upper(), key.upper())
         env_value = os.getenv(env_key)
         if env_value:
             if dtype=='B':
                 env_value = boolean(env_value)
             self.options.__dict__[key] = env_value
     if vassal_params:
         for key,value in vassal_params.items():
             self.options[key]=value   
Beispiel #4
0
    def init_options(self):
        self.siteconfig = self.get_config()
        options = self.options.__dict__
        vassals_dir = self.gnr_config[
            'gnr.environment_xml.vassals?path'] or os.path.join(
                gnrConfigPath(), 'uwsgi', 'vassals')
        vassal_path = os.path.join(vassals_dir, '%s.ini' % self.site_name)
        vassal_params = None
        if os.path.exists(vassal_path):

            with open(vassal_path) as vassal_file:
                config_parser = ConfigParser()
                config_parser.readfp(vassal_file)
            try:
                vassal_params = dict(config_parser.items('genropy'))
            except NoSectionError:
                pass
        for option in wsgi_options.keys():
            if options.get(option,
                           None) is None:  # not specified on the command-line
                site_option = self.siteconfig['wsgi?%s' % option]
                self.options[option] = site_option or wsgi_options.get(option)
        for (key, dtype) in (('debug', 'B'), ('restore', 'T'),
                             ('profile', 'B'), ('remote_edit', 'B'), ('gzip',
                                                                      'B')):
            env_key = 'GNR_%s_%s' % (self.site_name.upper(), key.upper())
            env_value = os.getenv(env_key)
            if env_value:
                if dtype == 'B':
                    env_value = boolean(env_value)
                self.options.__dict__[key] = env_value
        if vassal_params:
            for key, value in vassal_params.items():
                self.options[key] = value
Beispiel #5
0
    def main(self,root,th_public=None,**kwargs):
        callArgs = self.getCallArgs('th_pkg','th_table')
        public = boolean(th_public) if th_public else True
        root.attributes['datapath'] = 'main'
        pkg = callArgs.get('th_pkg')
        tbl = callArgs.get('th_table')
        fixed_table =False
        title = '!!Lookup Tables' 
        if pkg:
            title = '%s' %self.db.model.package(pkg).attributes.get('name_long')
            if tbl:
                tblobj = self.db.table('%(th_pkg)s.%(th_table)s' %callArgs)
                title = tblobj.name_plural or tblobj.name_long
        if public:
            root = root.rootContentPane(title=title,**kwargs)
        frame = root.framePane(nodeId='lookup_root')

        if not tbl:
            bar = frame.top.slotToolbar('10,tblfb,*')
            fb = bar.tblfb.formbuilder(cols=2,border_spacing='3px')
            fb.data('.package',pkg)
            fb.dataRemote('.packages',self.packageMenu)
            fb.dataRemote('.tables',self.tableMenu,currPkg='^.package')
            width='30em'
            if not pkg:
                fb.filteringSelect(value='^.package',lbl='!!Package',storepath='.packages',storeid='.code', width=width,
                                storecaption='.description',validate_onAccept='SET .table=null;')
            fb.filteringSelect(value='^.table',lbl='!!Tables',storepath='.tables',storeid='.code', width=width,
                                storecaption='.description',disabled='^.package?=!#v')
        else:
            root.dataFormula('.table','tbl',tbl='%(th_pkg)s.%(th_table)s' %callArgs,_onStart=1)
            fixed_table = True
        root.dataController("""
                SET main.current_table=table;""",table='^main.table',status='=main.mainth.view.grid.status')
        frame.center.contentPane(overflow='hidden').remote(self.remoteTh,table='^main.current_table',fixed_table=fixed_table,_onRemote='FIRE main.load_data;')
Beispiel #6
0
 def __init__(self, site=None, page_id=None, request_kwargs=None, request_args=None,
              filepath=None, packageId=None, pluginId=None, basename=None,page_info=None):
     self._inited = False
     self._start_time = time()
     self.workspace = dict()
     self.sql_count = 0
     self.sql_time = 0
     self.site = site
     if page_info:
         for k,v in page_info.items():
             setattr(self,k,v)
         self.connection =  GnrWebConnection(self,connection_id=self.connection_id,user=self.user)
     self.page_item = self._check_page_id(page_id, kwargs=request_kwargs)
     #dbstore = request_kwargs.pop('temp_dbstore',None) or None
     #self.dbstore = dbstore if dbstore != self.application.db.rootstore else None
     self.dbstore=None  # find a way to handle it based on call/thread
     self._locale='en'  # find a way to handle it based on call/thread
     self._event_subscribers = {}
     self.filepath = filepath
     self.packageId = packageId
     self.pluginId = pluginId
     self.basename = basename
     self.siteFolder = self.site.site_path
     self.folders = self._get_folders()
     self.pagepath = self.filepath.replace(self.folders['pages'], '')
     self._dbconnection = None
     self.application.db.clearCurrentEnv() # ?? dump and restore?
     self.debug_sql = boolean(request_kwargs.pop('debug_sql', None))
     debug_py = request_kwargs.pop('debug_py', None)
     self.debug_py = False if boolean(debug_py) is not True else debug_py
     self.callcounter = request_kwargs.pop('callcounter', None) or 'begin'
     self.root_page_id = None
     self.parent_page_id = None
     self.sourcepage_id = request_kwargs.pop('sourcepage_id', None)
     self.instantiateProxies()
     self.onPreIniting(request_args, request_kwargs)
     self.onIniting(request_args, request_kwargs)
     self._call_args = request_args or tuple()
     self._call_kwargs = dict(request_kwargs)
     self._workdate = self.page_item['data']['rootenv.workdate'] #or datetime.date.today()
     self._language = self.page_item['data']['rootenv.language']
     self._inited = True
     self._shareds = dict()
     self._privates = defaultdict(dict)
     self.freezedSelections = dict()
     self.envelope_js_requires= {}
     self.envelope_css_requires= {}
Beispiel #7
0
    def main(self, root, th_public=None, **kwargs):
        callArgs = self.getCallArgs('th_pkg', 'th_table')
        public = boolean(th_public) if th_public else True
        root.attributes['datapath'] = 'main'
        pkg = callArgs.get('th_pkg')
        tbl = callArgs.get('th_table')
        fixed_table = False
        title = '!!Lookup Tables'
        if pkg:
            title = '%s' % self.db.model.package(pkg).attributes.get(
                'name_long')
            if tbl:
                tblobj = self.db.table('%(th_pkg)s.%(th_table)s' % callArgs)
                title = tblobj.name_plural or tblobj.name_long
        if public:
            root = root.rootContentPane(title=title, **kwargs)
        frame = root.framePane(nodeId='lookup_root')

        if not tbl:
            bar = frame.top.slotToolbar('10,tblfb,*')
            fb = bar.tblfb.formbuilder(cols=2, border_spacing='3px')
            fb.data('.package', pkg)
            fb.dataRemote('.packages', self.packageMenu)
            fb.dataRemote('.tables', self.tableMenu, currPkg='^.package')
            width = '30em'
            if not pkg:
                fb.filteringSelect(value='^.package',
                                   lbl='!!Package',
                                   storepath='.packages',
                                   storeid='.code',
                                   width=width,
                                   storecaption='.description',
                                   validate_onAccept='SET .table=null;')
            fb.filteringSelect(value='^.table',
                               lbl='!!Tables',
                               storepath='.tables',
                               storeid='.code',
                               width=width,
                               storecaption='.description',
                               disabled='^.package?=!#v')
        else:
            root.dataFormula('.table',
                             'tbl',
                             tbl='%(th_pkg)s.%(th_table)s' % callArgs,
                             _onStart=1)
            fixed_table = True
        root.dataController("""
                SET main.current_table=table;""",
                            table='^main.table',
                            status='=main.mainth.view.grid.status')
        frame.center.contentPane(overflow='hidden').remote(
            self.remoteTh,
            table='^main.current_table',
            fixed_table=fixed_table,
            _onRemote='FIRE main.load_data;')
Beispiel #8
0
 def parsBaronNodeCall(self,node):
     args = []
     kwargs = OrderedDict()
     for argNode in node.find_all('call_argument'):
         key = argNode.target.value if argNode.target else None
         value = argNode.value.value
         argtype = argNode.value.type
         if argtype=='string':
             value = value.strip("'") if "'" in value else value.strip('"')
         elif value in ('True','False'):
             value = boolean(value)
         elif hasattr(value,'value'):
             value = Bag(self.parsBaronNodeCall(value)[1])
         if not key:
             args.append(value)
         else:
             kwargs[key] = value
     return args,kwargs
Beispiel #9
0
 def parsBaronNodeCall(self, node):
     args = []
     kwargs = OrderedDict()
     for argNode in node.find_all('call_argument'):
         key = argNode.target.value if argNode.target else None
         value = argNode.value.value
         argtype = argNode.value.type
         if argtype == 'string':
             value = value.strip("'") if "'" in value else value.strip('"')
         elif value in ('True', 'False'):
             value = boolean(value)
         elif hasattr(value, 'value'):
             value = Bag(self.parsBaronNodeCall(value)[1])
         if not key:
             args.append(value)
         else:
             kwargs[key] = value
     return args, kwargs
Beispiel #10
0
 def extdb_getDbStructure(self,connection_params=None,project=None,package=None):
     externaldb = self.extdb_getSourceDb(connection_params)
     existing_tables = []
     if project and package:
         p = PathResolver()
         project_path = p.project_name_to_path(project)
         modelpath = os.path.join(project_path,'packages',package,'model')
         if os.path.isdir(modelpath):
             existing_tables = map(lambda r: os.path.splitext(r)[0], filter(lambda r: r.endswith('.py'), os.listdir(modelpath)))
     src = externaldb.model.src
     result = Bag()
     for pkg in src['packages'].keys():
         pkgval = Bag()
         result.setItem(pkg, pkgval,name=pkg,checked=False)
         tables = src['packages'][pkg]['tables']
         if not tables:
             continue
         tables.sort('#k')
         for table,tblattr,tblval in tables.digest('#k,#a,#v'):
             tblattr = dict(tblattr)
             tblattr['checked'] = 'disabled:on' if table.lower() in existing_tables else False
             tblattr['name'] = table
             tableval = Bag()
             pkgval.setItem(table,tableval,**tblattr)
             for column,colattr,colval in tblval['columns'].digest('#k,#a,#v'):
                 cv = dict(colattr)
                 for t,v in tblattr.items():
                     cv['table_%s' %t] = v
                 #cv['checked'] = False
                 cv['name'] = column
                 if colval:
                     relnode = colval.getNode('relation')
                     cv['relate_to'] = relnode.attr['related_column']
                 tableval.setItem(column,None,**cv)
             if tblval['indexes']:
                 for column,unique in tblval['indexes'].digest('#a.columns,#a.unique'):
                     n = tableval.getNode(column)
                     if n:
                         n.attr['is_pkey'] = column == tblattr.get('pkey')
                         n.attr['indexed'] = True
                         n.attr['unique'] = boolean(unique)
     return result
Beispiel #11
0
 def _th_prepareForm(self,root,pkey=None,th_kwargs=None,store_kwargs=None,formCb=None,**kwargs):
     pkey = pkey or th_kwargs.pop('pkey',None)
     formResource = th_kwargs.pop('formResource',None)
     root.attributes.update(overflow='hidden')
     public = boolean(th_kwargs.pop('public',False))
     formId = th_kwargs.pop('formId',self.maintable.replace('.','_'))
     if  public:
         root.attributes.update(_class='pbl_root')
         root = root.rootContentPane(title=self.tblobj.name_long)
     else:
         root.attributes.update(tag='ContentPane',_class=None)
     root.attributes.update(datapath=self.maintable.replace('.','_'))
     formkw = kwargs
     formkw.update(th_kwargs)
     form = root.thFormHandler(table=self.maintable,formId=formId,startKey=pkey,
                               formResource=formResource,
                               formCb=formCb,form_isRootForm=True,**formkw)
     if public:
         form.dataController("""
                         SET gnr.publicTitle = title;
                         """,title='^#FORM.controller.title',_if='title') 
     self._th_parentFrameMessageSubscription(form) 
     return form
Beispiel #12
0
    def _th_main(self,root,th_options=None,**kwargs): 
        self._th_setDocumentation(key='thmain',table=self.maintable,doc=True)
        th_public = th_options.get('public',True)
        publicCollapse = th_public=='collapse'
        insidePublic = False
        if not publicCollapse:
            insidePublic = boolean(th_public) is True
        tablecode = self.maintable.replace('.','_')
        kwargs.update(th_options)
        if kwargs['virtualStore'] is False:
            kwargs['extendedQuery'] = False
            kwargs['view_root_tablehandler'] = True
        extendedQuery = kwargs.pop('extendedQuery','*') 
        lockable = kwargs.pop('lockable',True)
        if th_options['partitioned']:
            self.public_partitioned = th_options['partitioned']
            if self.public_partitioned is True:
                self.public_partitioned = self.tblobj.partitionParameters
        if insidePublic:
            pbl_root = root = root.rootContentPane(datapath=tablecode)
        else:
            root.attributes.update(_class=None,datapath=tablecode)
        extras = []
        if hasattr(self,'stats_main') or hasattr(self,'hv_main'):
            tc = root.stackContainer(selectedPage='^.view.selectedPage')
            root = tc.contentPane(title='!!Main View',pageName='th_main')
            if hasattr(self,'stats_main'):
                extras.append('statisticalHandler')
                self.stats_main(tc,title='!!Statistical View')
            if hasattr(self,'hv_main'):
                extras.append('hierarchicalHandler')
                self.hv_main(tc)
        self.th_mainUserSettings(kwargs=kwargs)
        thwidget = kwargs.pop('widget','stack')
        if thwidget=='inline':
            kwargs['saveButton'] = True
            kwargs['autoSave'] = False
            kwargs['semaphore'] = True
            lockable = False
        kwargs.setdefault('preview_tpl',True)
        kwargs.setdefault('form_form_isRootForm',True)
        th = getattr(root,'%sTableHandler' %thwidget)(table=self.maintable,datapath=tablecode,lockable=lockable,
                                                      extendedQuery=extendedQuery,**kwargs)
        root.dataController("""
            if(_subscription_kwargs.start_pkey){
                formNode.form.load({destPkey:start_pkey});
                return
            }
            var sections = objectExtract(_subscription_kwargs,'start_section_*',true);
            for (var k in sections){
                viewNode.setRelativeData('.sections.'+k+'.current',sections[k]);
            }
            if(_subscription_kwargs.start_query){
                if(_subscription_kwargs.start_query!='*'){
                    viewNode.setRelativeData('.query.currentQuery',start_query);
                }
                viewNode.fireEvent('.runQuery',true);
            }
            """,subscribe_frameindex_external=True,
                            formNode=getattr(th,'form',False),viewNode=th.view)
        if getattr(self,'public_partitioned',None):
            th.view.dataController("""FIRE .runQueryDo;""",subscribe_public_changed_partition=True,
                    storeServerTime='=.store?servertime',_if='storeServerTime')
            #partition_kwargs = dictExtract(self.tblobj.attributes,'partition_')
            if th['view.top.bar.addrow']:
                th.view.top.bar.addrow.getNode('#0').attr.update(hidden='^current.%s?=!#v' %self.public_partitioned['field'])
            if th['form.top.bar.form_add']:
                th.form.top.bar.form_add.getNode('#0').attr.update(hidden='^current.%s?=!#v' %self.public_partitioned['field'])
            if th['form']: #and partition_kwargs:
                th.form.dataController("SET gnr.partition_selector.disabled = pkey?true:false;",pkey='^#FORM.pkey')
        self.root_tablehandler = th
        vstore = th.view.store
        viewbar = th.view.top.bar

        if insidePublic:
            pbl_root.top.bar.captionslot.captionbox.attributes.update(connect_onclick="""if(genro.dom.getEventModifiers($1)=="Shift"){
                    th_usersettings(this.getAttributeFromDatasource("_mainth"));
                }
                """,_mainth=th.js_sourceNode())

        if publicCollapse:
            th.view.attributes.update(_class='pbl_root')
            viewbar.attributes.update(toolbar=False,_class='slotbar_toolbar pbl_root_top',height='22px')
            viewbar.replaceSlots('#','#,avatarslot,10')
            viewbar.replaceSlots('5,searchOn','10,captionslot,searchOn')
            viewbar.avatarslot.publicRoot_avatar(margin_top='-2px')
            viewbar.captionslot.publicRoot_captionslot()

        storeupd = dict(startLocked=lockable)
        if not extendedQuery:
            storeupd['_onStart'] = True
        vstore.attributes.update(storeupd)
        if len(extras)>0:
            viewbar.replaceSlots('resourceMails','resourceMails,5,%s' %','.join(extras))  
        if insidePublic and hasattr(self,'customizePublicFrame'):
            self.customizePublicFrame(root)
        th.view.attributes.update(dict(border='0',margin='0', rounded=0))
        self.__th_title(th,thwidget,insidePublic or publicCollapse,extendedQuery=extendedQuery)
        self.__th_moverdrop(th)
        if th_options.get('filterSlot'):
            th.view.top.bar.replaceSlots('menuUserSets','menuUserSets,5,mainFilter')

        gridattr = th.view.grid.attributes
        selfDragRowsOpt = self._th_hook('selfDragRows',mangler=th.view,defaultCb=False) or {}

        unifyTag = self.tblobj.attributes.get('unifyRecordsTag')
        allowUnify = self.application.checkResourcePermission(unifyTag,self.userTags) if unifyTag else False
        if selfDragRowsOpt or allowUnify:
            selfDragRowsOpt['allowUnifyCb']=allowUnify and selfDragRowsOpt.get('allowUnifyCb',allowUnify)
            if selfDragRowsOpt['allowUnifyCb'] in (True,False):
                selfDragRowsOpt['allowUnifyCb'] = 'return true;' if selfDragRowsOpt['allowUnifyCb'] is True else 'return false'
            selfDragRowsOpt.setdefault('onSelfDragRows','return false;')
            gridattr['selfDragRows'] = True 
            selfDragRowsOpt.setdefault('canBeDropped','return true;')
            gridattr['dropTargetCb_selfdragrows'] = """function(dropInfo){
                var modifiers = genro.dom.getEventModifiers(dropInfo.event);
                var dragInfo = genro.dom.getFromDataTransfer(dropInfo.event.dataTransfer,'gridrow');
                if(!dragInfo){
                    return true;
                }
                var targetRowData = dropInfo.targetRowData;
                var dragRowData = dragInfo.rowdata;
                if(!targetRowData){
                    return true
                }
                if(targetRowData['_pkey']==dragRowData['_pkey']){
                    return false;
                }
                if(modifiers=='Shift,Meta'||modifiers=='Shift,Alt'){ 
                    return funcApply("%(allowUnifyCb)s",{targetRowData:targetRowData,dragRowData:dragRowData});
                }else{
                    return funcApply("%(onSelfDragRows)s",{targetRowData:targetRowData,dragRowData:dragRowData});
                }
            }
            """%selfDragRowsOpt
            gridattr['onSelfDropRows'] = """function(rows,dropInfo){
                var kw = {sourcePkey:this.widget.rowIdByIndex(rows[0]),destPkey:this.widget.rowIdByIndex(dropInfo.row)};
                kw['table'] = this.attr.table;
                th_unifyrecord(kw);
            }
            """
        if hasattr(th,'form'):
            self._th_parentFrameMessageSubscription(th.form)
        return th
Beispiel #13
0
    def _th_applyOnForm(self,form,options=None,mangler=None):
        if not self.th_checkPermission(form):
            form.attributes['_notallowed'] = True
            parent = form.parent
            if hasattr(parent,'view'):
                th_attributes =  parent.attributes
                th_class = th_attributes.get('_class') or ''
                th_attributes['_class'] = '%s th_form_not_allowed' %th_class
        table = form.getInheritedAttributes()['table']
        form.dataController("""var title = newrecord?( newTitleTemplate? dataTemplate(newTitleTemplate,record): caption ): (titleTemplate? dataTemplate(titleTemplate,record) : tablename+': '+caption);
                            
                            SET #FORM.controller.title = title;
                            this.form.publish('onChangedTitle',{title:title});
                            """,
                            tablename=self.db.table(table).name_long,
                            caption='=#FORM.record?caption',
                            newrecord='=#FORM.record?_newrecord',
                            record='=#FORM.record',titleTemplate=options.pop('titleTemplate',False),
                            newTitleTemplate=options.pop('newTitleTemplate',False),
                            _fired='^#FORM.controller.loaded')
        if form.attributes.get('form_isRootForm'):
            form.data('gnr.rootform.size',Bag(height=options.pop('dialog_height','500px'),width=options.pop('dialog_width','600px')))
        if 'lazyBuild' in options:
            form.attributes['_lazyBuild'] = options.pop('lazyBuild')
        showtoolbar = boolean(options.pop('showtoolbar',True))
        navigation = options.pop('navigation',None)
        hierarchical = options.pop('hierarchical',None)   
        tree_kwargs = dictExtract(options,'tree_',pop=True)     
        readOnly = options.pop('readOnly',False)
        modal = options.pop('modal',False)
        autoSave = options.pop('autoSave',False)
        draftIfInvalid= options.pop('draftIfInvalid',False)
        allowSaveInvalid= options.pop('allowSaveInvalid',draftIfInvalid)
        form_add = options.pop('form_add',True)
        form_delete = options.pop('form_delete',True)

        form.attributes.update(form_draftIfInvalid=draftIfInvalid,form_allowSaveInvalid=allowSaveInvalid)
        if autoSave:
            form.store.attributes.update(autoSave=autoSave)

        form.dataController(""" if(reason=='nochange' && modal){return;}
                                genro.dlg.alert(msg+' '+this.form.getRecordCaption()+': '+(reason=='invalid'?invalid:nochange),titledialog);""",
                            reason="^.controller.save_failed",_if='reason',
                            titledialog='!!Save failed',
                            msg='!!You cannot save',
                            invalid='!!Invalid record',
                            nochange='!!No change to save',modal=modal)
        box_kwargs = dictExtract(options,'box_',pop=True)
        extra_slots = []
        if hierarchical:
            box_kwargs['sidebar'] = True
            box_kwargs['persist'] = True
        if box_kwargs:
            sidebar = box_kwargs.pop('sidebar')
            if sidebar:
                box_kwargs['design'] = 'sidebar'
            form.attributes.update(**box_kwargs)
        
        if form.store.attributes.get('storeType') == 'Collection':
            if navigation is not False:
                navigation = True
        if readOnly:
            form.attributes.update(form_readOnly=True)
        if options.get('saveOnChange'):
            form.attributes.update(form_saveOnChange=options.pop('saveOnChange'))
            showtoolbar = False
        if 'parentLock' in options:
            form.attributes.update(form_parentLock=options.pop('parentLock'))
        if modal:
            slots='revertbtn,*,cancel,savebtn'
            form.attributes['hasBottomMessage'] = False
            bar = form.bottom.slotBar(slots,margin_bottom='2px',_class='slotbar_dialog_footer')
            bar.revertbtn.button('!!Revert',action='this.form.publish("reload")',disabled='^.controller.changed?=!#v',hidden=readOnly)
            bar.cancel.button('!!Cancel',action='this.form.abort();')
            bar.savebtn.button('!!Save',iconClass='fh_semaphore',action='this.form.publish("save",{destPkey:"*dismiss*"})',hidden=readOnly)
        elif showtoolbar:
            default_slots = '*,semaphore,5' if readOnly else '*,form_delete,form_add,form_revert,form_save,semaphore,locker'
            if form_add is False:
                default_slots.replace('form_add','')
            if form_delete is False:
                default_slots.replace('form_delete','')

            if options.pop('duplicate',False):
                default_slots= default_slots.replace('form_add','form_add,form_duplicate')
            if hierarchical:
                default_slots = 'dismiss,hbreadcrumb,%s' %default_slots
            elif navigation:
                default_slots = 'navigation,%s' %default_slots
            elif options.pop('selector',False):
                default_slots = default_slots.replace('*','5,form_selectrecord,*')
            if options.pop('printMenu',False):
                #default_slots = default_slots.replace('form_delete','form_print,100,form_delete')
                extra_slots.append('form_print')
            if options.pop('copypaste',False):
                extra_slots.append('form_copypaste')
            if options.pop('linker',False):
                default_slots = default_slots.replace('form_delete',','.join(extra_slots) if extra_slots else '')
                default_slots = default_slots.replace('form_add','')
                #default_slots = default_slots.replace('locker','') 
            table = form.getInheritedAttributes()['table']  
            if extra_slots:
                default_slots = default_slots.replace('form_delete','%s,10,form_delete' %(','.join(extra_slots)))
            slots = options.pop('slots',default_slots)
            if table == self.maintable:
                slots = 'logicalDeleter,%s' %slots 
            form.top.slotToolbar(slots,form_add_defaults=form_add if form_add and form_add is not True else None,**options)
        if not options.pop('showfooter',True):
            form.attributes['hasBottomMessage'] = False
        if hierarchical:
            form.left.attributes.update(splitter=True)
            leftkw = dict()
            if hierarchical is True or hierarchical=='open':
                form.store.attributes.setdefault('startKey','*norecord*')
                form.attributes.update(form_deleted_destPkey='*norecord*')
                if hierarchical=='open':
                    leftkw['closable'] = 'open'      
            elif hierarchical=='closed':
                leftkw['closable'] = 'close'
            bar = form.left.slotBar('0,htreeSlot,0',width=tree_kwargs.pop('width','200px'),border_right='1px solid silver',**leftkw)
            bar.htreeSlot.treeViewer(**tree_kwargs)

        for side in ('top','bottom','left','right'):
            hooks = self._th_hook(side,mangler=mangler,asDict=True)
            for hook in hooks.values():
                hook(getattr(form,side))    
        form.store.handler('load',onLoadingHandler=self._th_hook('onLoading',mangler=mangler))
        form.store.handler('save',onSavingHandler=self._th_hook('onSaving',mangler=mangler),
                                 onSavedHandler=self._th_hook('onSaved',mangler=mangler))
Beispiel #14
0
    def _th_main(self, root, th_options=None, **kwargs):
        self._th_setDocumentation(key='thmain', table=self.maintable, doc=True)
        th_public = th_options.get('public', True)
        publicCollapse = th_public == 'collapse'
        insidePublic = False
        if not publicCollapse:
            insidePublic = boolean(th_public) is True
        tablecode = self.maintable.replace('.', '_')
        kwargs.update(th_options)
        if kwargs['virtualStore'] is False:
            kwargs['extendedQuery'] = False
            kwargs['view_root_tablehandler'] = True
        extendedQuery = kwargs.pop('extendedQuery', '*')
        lockable = kwargs.pop('lockable', True)
        if th_options['partitioned']:
            self.public_partitioned = th_options['partitioned']
            if self.public_partitioned is True:
                self.public_partitioned = self.tblobj.partitionParameters
        if insidePublic:
            pbl_root = root = root.rootContentPane(datapath=tablecode)
        else:
            root.attributes.update(_class=None, datapath=tablecode)
        extras = []
        if hasattr(self, 'stats_main') or hasattr(self, 'hv_main'):
            tc = root.stackContainer(selectedPage='^.view.selectedPage')
            root = tc.contentPane(title='!!Main View', pageName='th_main')
            if hasattr(self, 'stats_main'):
                extras.append('statisticalHandler')
                self.stats_main(tc, title='!!Statistical View')
            if hasattr(self, 'hv_main'):
                extras.append('hierarchicalHandler')
                self.hv_main(tc)
        self.th_mainUserSettings(kwargs=kwargs)
        thwidget = kwargs.pop('widget', 'stack')
        if thwidget == 'inline':
            kwargs['saveButton'] = True
            kwargs['autoSave'] = False
            kwargs['semaphore'] = True
            lockable = False
        kwargs.setdefault('preview_tpl', True)
        kwargs.setdefault('form_form_isRootForm', True)
        th = getattr(root,
                     '%sTableHandler' % thwidget)(table=self.maintable,
                                                  datapath=tablecode,
                                                  lockable=lockable,
                                                  extendedQuery=extendedQuery,
                                                  **kwargs)
        if getattr(self, 'public_partitioned', None):
            th.view.dataController("""FIRE .runQueryDo;""",
                                   subscribe_public_changed_partition=True,
                                   storeServerTime='=.store?servertime',
                                   _if='storeServerTime')
            #partition_kwargs = dictExtract(self.tblobj.attributes,'partition_')
            if th['view.top.bar.addrow']:
                th.view.top.bar.addrow.getNode('#0').attr.update(
                    hidden='^current.%s?=!#v' %
                    self.public_partitioned['field'])
            if th['form.top.bar.form_add']:
                th.form.top.bar.form_add.getNode('#0').attr.update(
                    hidden='^current.%s?=!#v' %
                    self.public_partitioned['field'])
            if th['form']:  #and partition_kwargs:
                th.form.dataController(
                    "SET gnr.partition_selector.disabled = pkey?true:false;",
                    pkey='^#FORM.pkey')
        self.root_tablehandler = th
        vstore = th.view.store
        viewbar = th.view.top.bar

        if insidePublic:
            pbl_root.top.bar.captionslot.captionbox.attributes.update(
                connect_onclick="""if(genro.dom.getEventModifiers($1)=="Shift"){
                    th_usersettings(this.getAttributeFromDatasource("_mainth"));
                }
                """,
                _mainth=th.js_sourceNode())

        if publicCollapse:
            th.view.attributes.update(_class='pbl_root')
            viewbar.attributes.update(toolbar=False,
                                      _class='slotbar_toolbar pbl_root_top',
                                      height='22px')
            if not hasattr(th.view.bottom, 'bar'):
                self.public_frameBottomBar(th.view.bottom,
                                           slots='*,messageBox,*')
            else:
                th.view.bottom.bar.attributes.update(
                    _class='slotbar_toolbar pbl_root_bottom')
            viewbar.replaceSlots('#', '#,avatarslot,10')
            viewbar.replaceSlots('5,searchOn', '10,captionslot,searchOn')
            viewbar.avatarslot.publicRoot_avatar(margin_top='-2px')
            viewbar.captionslot.publicRoot_captionslot()

        storeupd = dict(startLocked=lockable)
        if not extendedQuery:
            storeupd['_onStart'] = True
        vstore.attributes.update(storeupd)
        if len(extras) > 0:
            viewbar.replaceSlots('resourceMails',
                                 'resourceMails,5,%s' % ','.join(extras))
        if insidePublic and hasattr(self, 'customizePublicFrame'):
            self.customizePublicFrame(root)
        th.view.attributes.update(dict(border='0', margin='0', rounded=0))
        self.__th_title(th,
                        thwidget,
                        insidePublic or publicCollapse,
                        extendedQuery=extendedQuery)
        self.__th_moverdrop(th)
        if th_options.get('filterSlot'):
            th.view.top.bar.replaceSlots('menuUserSets',
                                         'menuUserSets,5,mainFilter')

        gridattr = th.view.grid.attributes
        selfDragRowsOpt = self._th_hook(
            'selfDragRows', mangler=th.view, defaultCb=False) or {}

        unifyTag = self.tblobj.attributes.get('unifyRecordsTag')
        allowUnify = self.application.checkResourcePermission(
            unifyTag, self.userTags) if unifyTag else False
        if selfDragRowsOpt or allowUnify:
            selfDragRowsOpt[
                'allowUnifyCb'] = allowUnify and selfDragRowsOpt.get(
                    'allowUnifyCb', allowUnify)
            if selfDragRowsOpt['allowUnifyCb'] in (True, False):
                selfDragRowsOpt[
                    'allowUnifyCb'] = 'return true;' if selfDragRowsOpt[
                        'allowUnifyCb'] is True else 'return false'
            selfDragRowsOpt.setdefault('onSelfDragRows', 'return false;')
            gridattr['selfDragRows'] = True
            selfDragRowsOpt.setdefault('canBeDropped', 'return true;')
            gridattr['dropTargetCb_selfdragrows'] = """function(dropInfo){
                var modifiers = genro.dom.getEventModifiers(dropInfo.event);
                var dragInfo = genro.dom.getFromDataTransfer(dropInfo.event.dataTransfer,'gridrow');
                if(!dragInfo){
                    return true;
                }
                var targetRowData = dropInfo.targetRowData;
                var dragRowData = dragInfo.rowdata;
                if(!targetRowData){
                    console.log('no targetRowData')
                    return true
                }
                if(targetRowData['_pkey']==dragRowData['_pkey']){
                    return false;
                }
                if(modifiers=='Shift,Meta'){
                    return funcApply("%(allowUnifyCb)s",{targetRowData:targetRowData,dragRowData:dragRowData});
                }else{
                    return funcApply("%(onSelfDragRows)s",{targetRowData:targetRowData,dragRowData:dragRowData});
                }
            }
            """ % selfDragRowsOpt
            gridattr['onSelfDropRows'] = """function(rows,dropInfo){
                var kw = {sourcePkey:this.widget.rowIdByIndex(rows[0]),destPkey:this.widget.rowIdByIndex(dropInfo.row)};
                kw['table'] = this.attr.table;
                th_unifyrecord(kw);
            }
            """
        if hasattr(th, 'form'):
            self._th_parentFrameMessageSubscription(th.form)
        return th
Beispiel #15
0
def convert_boolean(val):
    return boolean(val)
Beispiel #16
0
    def _th_applyOnForm(self,form,options=None,mangler=None):
        if not self.th_checkPermission(form):
            form.attributes['_notallowed'] = True
            parent = form.parent
            if hasattr(parent,'view'):
                th_attributes =  parent.attributes
                th_class = th_attributes.get('_class') or ''
                th_attributes['_class'] = '%s th_form_not_allowed' %th_class
        table = form.getInheritedAttributes()['table']
        form.dataController("""var title = newrecord?( newTitleTemplate? dataTemplate(newTitleTemplate,record): caption ): (titleTemplate? dataTemplate(titleTemplate,record) : tablename+': '+caption);
                            
                            SET #FORM.controller.title = title;
                            this.form.publish('onChangedTitle',{title:title});
                            """,
                            tablename=self.db.table(table).name_long,
                            caption='=#FORM.record?caption',
                            newrecord='=#FORM.record?_newrecord',
                            record='=#FORM.record',titleTemplate=options.pop('titleTemplate',False),
                            newTitleTemplate=options.pop('newTitleTemplate',False),
                            _fired='^#FORM.controller.loaded')
        if form.attributes.get('form_isRootForm'):
            form.data('gnr.rootform.size',Bag(height=options.pop('dialog_height','500px'),width=options.pop('dialog_width','600px')))
        if 'lazyBuild' in options:
            form.attributes['_lazyBuild'] = options.pop('lazyBuild')
        showtoolbar = boolean(options.pop('showtoolbar',True))
        navigation = options.pop('navigation',None)
        hierarchical = options.pop('hierarchical',None)   
        tree_kwargs = dictExtract(options,'tree_',pop=True)     
        readOnly = options.pop('readOnly',False)
        modal = options.pop('modal',False)
        autoSave = options.pop('autoSave',False)
        draftIfInvalid= options.pop('draftIfInvalid',False)
        allowSaveInvalid= options.pop('allowSaveInvalid',draftIfInvalid)
        form_add = options.pop('form_add',True)
        form_delete = options.pop('form_delete',True)
        selector = options.pop('selector',False)
        form.attributes.update(form_draftIfInvalid=draftIfInvalid,form_allowSaveInvalid=allowSaveInvalid)
        if autoSave:
            form.store.attributes.update(autoSave=autoSave)

        form.dataController(""" if(reason=='nochange' && modal){return;}
                                genro.dlg.alert(msg+' '+this.form.getRecordCaption()+': '+(reason=='invalid'?invalid:nochange),titledialog);""",
                            reason="^.controller.save_failed",_if='reason',
                            titledialog='!!Save failed',
                            msg='!!You cannot save',
                            invalid='!!Invalid record',
                            nochange='!!No change to save',modal=modal)
        box_kwargs = dictExtract(options,'box_',pop=True)
        extra_slots = []
        if hierarchical:
            box_kwargs['sidebar'] = True
            box_kwargs['persist'] = True
        if box_kwargs:
            sidebar = box_kwargs.pop('sidebar')
            if sidebar:
                box_kwargs['design'] = 'sidebar'
            form.attributes.update(**box_kwargs)
        
        if form.store.attributes.get('storeType') == 'Collection':
            if navigation is not False:
                navigation = True
        if readOnly:
            form.attributes.update(form_readOnly=True)
        if options.get('saveOnChange'):
            form.attributes.update(form_saveOnChange=options.pop('saveOnChange'))
            showtoolbar = False
        if 'parentLock' in options:
            form.attributes.update(form_parentLock=options.pop('parentLock'))
        if modal:
            slots='revertbtn,*,cancel,savebtn'
            bar = form.bottom.slotBar(slots,margin_bottom='2px',_class='slotbar_dialog_footer')
            bar.revertbtn.button('!!Revert',action='this.form.publish("reload")',disabled='^.controller.changed?=!#v',hidden=readOnly)
            bar.cancel.button('!!Cancel',action='this.form.abort();')
            bar.savebtn.button('!!Save',iconClass='fh_semaphore',action='this.form.publish("save",{destPkey:"*dismiss*"})',hidden=readOnly)
        elif showtoolbar:
            default_slots = '*,semaphore,5' if readOnly else '*,form_delete,form_add,form_revert,form_save,semaphore,locker'
            if form_add is False:
                default_slots.replace('form_add','')
            if form_delete is False:
                default_slots.replace('form_delete','')
            if options.pop('duplicate',False):
                default_slots= default_slots.replace('form_add','form_add,form_duplicate')
            if hierarchical:
                default_slots = 'dismiss,hbreadcrumb,%s' %default_slots
            elif navigation:
                default_slots = 'navigation,%s' %default_slots
            if selector:
                default_slots = default_slots.replace('*','5,form_selectrecord,*')
                if isinstance(selector,dict):
                    options['form_selectrecord_pars'] = selector
            if options.pop('printMenu',False):
                #default_slots = default_slots.replace('form_delete','form_print,100,form_delete')
                extra_slots.append('form_print')
            if options.pop('copypaste',False):
                extra_slots.append('form_copypaste')
            if options.pop('linker',False):
                default_slots = default_slots.replace('form_delete',','.join(extra_slots) if extra_slots else '')
                default_slots = default_slots.replace('form_add','')
                #default_slots = default_slots.replace('locker','') 
            table = form.getInheritedAttributes()['table']  
            if extra_slots:
                default_slots = default_slots.replace('form_delete','%s,10,form_delete' %(','.join(extra_slots)))
            slots = options.pop('slots',default_slots)
            if table == self.maintable:
                slots = 'logicalDeleter,%s' %slots 
            form.top.slotToolbar(slots,form_add_defaults=form_add if form_add and form_add is not True else None,**options)
        if hierarchical:
            form.left.attributes.update(splitter=True)
            leftkw = dict()
            if hierarchical is True or hierarchical=='open':
                form.store.attributes.setdefault('startKey','*norecord*')
                form.attributes.update(form_deleted_destPkey='*norecord*')
                if hierarchical=='open':
                    leftkw['closable'] = 'open'      
            elif hierarchical=='closed':
                leftkw['closable'] = 'close'
            bar = form.left.slotBar('0,htreeSlot,0',width=tree_kwargs.pop('width','200px'),border_right='1px solid silver',**leftkw)
            bar.htreeSlot.treeViewer(**tree_kwargs)

        for side in ('top','bottom','left','right'):
            hooks = self._th_hook(side,mangler=mangler,asDict=True)
            for hook in hooks.values():
                hook(getattr(form,side))    
        form.store.handler('load',onLoadingHandler=self._th_hook('onLoading',mangler=mangler))
        form.store.handler('save',onSavingHandler=self._th_hook('onSaving',mangler=mangler),
                                 onSavedHandler=self._th_hook('onSaved',mangler=mangler))
Beispiel #17
0
 def reuse_relation_tree(self):
     if self.application:
         return boolean(self.application.config['db?reuse_relation_tree']) is not False
     return
Beispiel #18
0
def convert_boolean(val):
    return boolean(val)