Пример #1
0
 def __init__(self,lh,name,dv,**kw):
     #~ self.dv = dv
     kw.update(store=js_code('this.store'))
     kw.update(tpl=js_code('new Ext.XTemplate(%s)' % py2js(dv.xtemplate)))
     kw.update(emptyText='No images to display')
     kw.update(itemSelector='div.thumb-wrap')
     kw.update(loadingText='Loading...')
     LayoutElement.__init__(self,lh,name,**kw)
Пример #2
0
 def __init__(self,rh,action,main,**kw):
     self.rh = rh
     self.value_template = "new Lino.%s.FormPanel(ww,%%s)" % self.rh.report
     self.main = main
     kw.update(
       #~ items=main,
       #~ autoScroll=True,
       #~ autoHeight=True,
       layout='fit',
     )
     if not isinstance(action,reports.InsertRow):
         kw.update(has_navigator=rh.report.has_navigator)
         
     on_render = []
     elems_by_field = {}
     field_elems = []
     for e in main.active_children:
         if isinstance(e,FieldElement):
             field_elems.append(e)
             l = elems_by_field.get(e.field.name,None)
             if l is None:
                 l = []
                 elems_by_field[e.field.name] = l
             l.append(e)
         
     for e in field_elems:
         #~ if isinstance(e,FileFieldElement):
             #~ kw.update(fileUpload=True)
         chooser = choosers.get_for_field(e.field)
         if chooser:
             #~ logger.debug("20100615 %s.%s has chooser", self.lh.layout, e.field.name)
             for f in chooser.context_fields:
                 for el in elems_by_field.get(f.name,[]):
                     #~ if main.has_field(f):
                     #~ varname = varname_field(f)
                     #~ on_render.append("%s.on('change',Lino.chooser_handler(%s,%r));" % (varname,e.ext_name,f.name))
                     on_render.append(
                         "%s.on('change',Lino.chooser_handler(%s,%r));" % (
                         el.ext_name,e.ext_name,f.name))
     
     if on_render:
         assert not kw.has_key('listeners')
         #~ kw.update(listeners=dict(render=js_code('function(){%s}' % '\n'.join(on_render))))
         self.listeners=dict(render=js_code('function(){%s}' % '\n'.join(on_render)))
     #~ kw.update(before_row_edit=before_row_edit(main))
     self.before_row_edit=before_row_edit(main)
     
     rpt = rh.report
     a = rpt.get_action('detail')
     if a:
         kw.update(ls_detail_handler=js_code("Lino.%s" % a))
     a = rpt.get_action('insert')
     if a:
         kw.update(ls_insert_handler=js_code("Lino.%s" % a))
     
     kw.update(ls_bbar_actions=[rh.ui.a2btn(a) for a in rpt.get_actions(action)])
     kw.update(ls_url=rh.ui.build_url(rpt.app_label,rpt._actor_name))
     jsgen.Component.__init__(self,'form_panel',**kw)
Пример #3
0
 def get_field_options(self,**kw):
     kw.update(name=self.field.name)
     kw.update(layout='fit')
     if self.field.drop_zone: # testing with drop_zone 'FooBar'
         kw.update(listeners=dict(render=js_code('initialize%sDropZone' % self.field.drop_zone)))
     kw.update(items=js_code("new Ext.BoxComponent()"))
     if self.label:
         kw.update(title=unicode(self.label))
     #~ if self.field.bbar is not None:
         #~ kw.update(ls_bbar_actions=self.field.bbar)
     return kw
Пример #4
0
def a2btn(a):
    return dict(
      opens_a_slave=a.opens_a_slave,
      handler=js_code("Lino.%s" % a),
      name=a.name,
      label=unicode(a.label),
      #~ url="/".join(("/ui",a.actor.app_label,a.actor._actor_name,a.name))
    )
Пример #5
0
    def get_column_options(self, **kw):
        """Return a string to be used as `Ext.grid.Column.renderer
        <http://docs.sencha.com/extjs/3.4.0/#!/api/Ext.grid.Column-cfg-renderer>`.

        """
        kw = super(UppercaseTextFieldElement, self).get_column_options(**kw)
        kw.update(renderer=js_code("Lino.iban_renderer"))
        return kw
Пример #6
0
 def get_column_options(self, **kw):
     """
     Return a string to be used as `Ext.grid.Column.renderer
     <http://docs.sencha.com/extjs/3.4.0/#!/api/Ext.grid.Column-cfg-renderer>`.
     """
     kw = super(UppercaseTextFieldElement, self).get_column_options(**kw)
     kw.update(renderer=js_code('Lino.iban_renderer'))
     return kw
Пример #7
0
 def get_column_options(self,**kw):
     #~ kw.update(dataIndex=self.field.name)
     #~ if self.label is None:
         #~ kw.update(header=self.field.name)
     #~ else:
     kw.update(header=unicode(self.label))
     kw.update(editable=False)
     kw.update(sortable=False)
     rend = 'Lino.cell_button_renderer'
     kw.update(renderer=js_code(rend))
     return kw    
Пример #8
0
 def __init__(self,lh,field,**kw):
 #~ def __init__(self,*args,**kw):
     #~ print 20100903,repr(self.field.rel.to)
     #~ assert issubclass(self.field.rel.to,models.Model), "%r is not a model" % self.field.rel.to
     self.report = reports.get_model_report(field.rel.to)
     a = self.report.detail_action
     if a is not None:
         #~ self.value_template = "new Lino.TwinCombo(%s)"
         self.value_template = "new qx.ui.basic.Atom().set(%s)"
         kw.update(onTrigger2Click=js_code(
           "function(e){ Lino.show_fk_detail(this,e,Lino.%s)}" % a))
     FieldElement.__init__(self,lh,field,**kw)
Пример #9
0
    def __init__(self,lh,name,rpt,*elements,**kw):
        """
        :param lh: the handle of the DetailLayout owning this grid
        :param rpt: the report being displayed
        """
        assert isinstance(rpt,reports.Report), "%r is not a Report!" % rpt
        self.report = rpt
        if len(elements) == 0:
            self.rh = rpt.get_handle(lh.rh.ui)
            elements = self.rh.list_layout._main.elements
            #~ columns = self.rh.list_layout._main.elements
        w = 0
        for e in elements:
            w += (e.width or e.preferred_width)
        self.preferred_width = constrain(w,10,120)
        #~ kw.update(boxMinWidth=500)
        #~ self.columns = elements
        #~ self.store = qx_store.Store(lh)
        self.columns = [GridColumn(i,e) for i,e in enumerate(elements)]
        
        kw.update(page_length=self.report.page_length)

        a = rpt.get_action('detail')
        if a:
            kw.update(ls_detail_handler=js_code("Lino.%s" % a))
        a = rpt.get_action('insert')
        if a:
            kw.update(ls_insert_handler=js_code("Lino.%s" % a))
        
        Container.__init__(self,lh,name,*elements,**kw)
        #~ self.active_children = columns
        assert not kw.has_key('before_row_edit')
        self.update(before_row_edit=before_row_edit(self))
        
        self.preferred_height = rpt.page_length 
        if self.report.master is not None:
            self.mt = ContentType.objects.get_for_model(self.report.master).pk
        else:
            self.mt = 'undefined'
Пример #10
0
 def add_help_text(self, kw, help_text, title, datasource, fieldname):
     if settings.SITE.use_quicktips:
         if settings.SITE.show_internal_field_names:
             ttt = "(%s.%s) " % (datasource, fieldname)
         else:
             ttt = ''
         if help_text:
             ttt = format_lazy(u"{}{}", ttt, help_text)
         if ttt:
             # kw.update(qtip=self.field.help_text)
             # kw.update(toolTipText=self.field.help_text)
             # kw.update(tooltip=self.field.help_text)
             kw.update(listeners=dict(
                 render=js_code("Lino.quicktip_renderer(%s,%s)" %
                                (py2js(title), py2js(ttt)))))
Пример #11
0
 def add_help_text(self, kw, help_text, title, datasource, fieldname):
     if settings.SITE.use_quicktips:
         if settings.SITE.show_internal_field_names:
             ttt = "(%s.%s) " % (datasource, fieldname)
         else:
             ttt = ''
         if help_text:
             ttt = format_lazy(u"{}{}", ttt, help_text)
         if ttt:
             # kw.update(qtip=self.field.help_text)
             # kw.update(toolTipText=self.field.help_text)
             # kw.update(tooltip=self.field.help_text)
             kw.update(listeners=dict(render=js_code(
                 "Lino.quicktip_renderer(%s,%s)" % (
                     py2js(title),
                     py2js(ttt)))
             ))
Пример #12
0
 def ext_options(self,**kw):
     rh = self.report.get_handle(self.lh.rh.ui)
     kw = LayoutElement.ext_options(self,**kw)
     #~ d.update(ls_data_url=rh.ui.get_actor_url(self.report))
     kw.update(ls_url=rh.ui.build_url(self.report.app_label,self.report._actor_name))
     kw.update(ls_store_fields=[js_code(f.as_js()) for f in rh.store.list_fields])
     #~ kw.update(ls_columns=[GridColumn(i,e) for i,e in enumerate(self.columns)])
     #~ kw.update(ls_filters=[e.get_filter_options() for e in self.elements if e.filter_type])
     kw.update(ls_id_property=rh.store.pk.name)
     kw.update(pk_index=rh.store.pk_index)
     kw.update(ls_quick_edit=rh.report.cell_edit)
     kw.update(ls_bbar_actions=[rh.ui.a2btn(a) for a in rh.get_actions(rh.report.default_action)])
     kw.update(ls_grid_configs=[gc.data for gc in self.report.grid_configs])
     kw.update(gc_name=DEFAULT_GC_NAME)
     #~ gc = self.report.grid_configs.get('',None)
     #~ if gc is not None:
         #~ kw.update(ls_grid_config=gc)
     return kw
Пример #13
0
 def __init__(self,index,editor,**kw):
     """editor may be a Panel for columns on a GenericForeignKey
     """
     #~ print 20100515, editor.name, editor.__class__
     #~ assert isinstance(editor,FieldElement), \
         #~ "%s.%s is a %r (expected FieldElement instance)" % (cm.grid.report,editor.name,editor)
     self.editor = editor
     #~ self.value_template = editor.grid_column_template
     kw.update(sortable=True)
     self.index = index
     self.label = editor.label
     kw.update(self.editor.get_column_options())
     kw.update(hidden=editor.hidden)
     if settings.USE_GRIDFILTERS and editor.filter_type:
         kw.update(filter=dict(type=editor.filter_type))
     #~ if isinstance(editor,FieldElement) and editor.field.primary_key:
     if isinstance(editor,FieldElement):
         self.field = editor.field
         rend = None
         if isinstance(editor.field,models.AutoField):
             rend = 'Lino.id_renderer'
             #~ kw.update(renderer=js_code('Lino.id_renderer'))
         elif isinstance(editor.field,models.ForeignKey):
             # FK fields are clickable if their target has a detail view
             rpt = editor.field.rel.to._lino_model_report
             if rpt.detail_action is not None:
             #~ a = rpt.get_action('detail')
             #~ if a is not None:
                 rend = "Lino.fk_renderer('%s','Lino.%s')" % (
                   editor.field.name + 'Hidden',
                   rpt.detail_action)
                 #~ rend = "Lino.fk_renderer('%s','%s')" % (
                   #~ editor.field.name + 'Hidden',
                   #~ editor.lh.rh.ui.get_actor_url(rpt))
         #~ if not rend:
             #~ rend = 'Lino.default_renderer'
         if rend:
             kw.update(renderer=js_code(rend))
         kw.update(editable=editor.editable)
         if editor.editable:
             kw.update(editor=editor)
     else:
         kw.update(editable=False)
     Component.__init__(self,editor.name,**kw)
Пример #14
0
def before_row_edit(panel):
    l = []
    #~ l.append("console.log('before_row_edit',record);")
    for e in panel.active_children:
        if isinstance(e,GridElement):
            l.append("%s.on_master_changed();" % e.as_ext())
        elif isinstance(e,PictureElement):
            l.append("this.load_picture_to(%s,record);" % e.as_ext())
        elif isinstance(e,HtmlBoxElement):
            l.append("%s.refresh();" % e.as_ext())
        elif isinstance(e,FieldElement):
            chooser = choosers.get_for_field(e.field)
            if chooser:
                #~ logger.debug("20100615 %s.%s has chooser", self.lh.layout, e.field.name)
                for f in chooser.context_fields:
                    #~ l.append("console.log('20110128 before_row_edit',record.data);")
                    l.append("%s.setContextValue(%r,record ? record.data[%r] : undefined);" % (
                        e.ext_name,f.name,ext_requests.form_field_name(f)))
    #~ return js_code('function(record){\n  %s\n}' % ('\n  '.join(l)))
    return js_code('function(record){ %s }' % (' '.join(l)))
Пример #15
0
 def __init__(self,lh,name,action,**kw):
     #~ print 20100730, name
     #~ kw.update(html='<img height="100%"/>')
     #~ kw.update(html='<img height="100%" onclick="Lino.img_onclick()"/>')
     #~ kw.update(autoHeight=True)
     #~ kw.update(anchor="100% 100%")
     kw.update(autoEl=dict(tag='img'))
     #~ kw.update(autoEl=dict(tag='img',onclick="Lino.img_onclick(%s)" % name))
     #~ kw.update(autoEl=dict(tag='img',onclick="Lino.img_onclick(this)" ))
     #~ kw.update(onclick=js_code('"Lino.img_onclick()"'))
     #~ kw.update(cls='ext-el-mask')
     #~ kw.update(style=dict(width='100px',cursor='pointer'))
     #~ kw.update(style=dict(width='100px',height='150px',cursor='pointer'))
     kw.update(plugins=js_code('Lino.PictureBoxPlugin'))
     #~ kw.update(plugins=js_code('new Lino.PictureBoxPlugin(caller)'))
     #~ kw.update(listeners=dict(click=js_code('Lino.img_onclick')))
     LayoutElement.__init__(self,lh,name,**kw)
     #~ print "PictureElement", self.width, self.preferred_width
     self.update(style=dict(
       width='%dpx' % ((self.width or self.preferred_width)*10), # assume 1 char ~ 10px
       cursor='pointer'))
Пример #16
0
 def __init__(self,tabs,**kw):
     self.active_children = []
     for t in tabs:
         self.active_children += t.active_children
         t.update(listeners=dict(activate=js_code("Lino.on_tab_activate")))
         #~ if t.has_upload:
             #~ self.has_upload = True
   
     self.tabs = tabs
     kw.update(
       split=True,
       activeTab=0,
       #~ layoutOnTabChange=True, # 20101028
       #~ forceLayout=True, # 20101028
       #~ deferredRender=False, # 20101028
       #~ autoScroll=True, 
       #~ width=300, # ! http://code.google.com/p/lino/wiki/20100513
       items=tabs,
       # http://www.extjs.com/forum/showthread.php?26564-Solved-FormPanel-in-a-TabPanel
       #~ listeners=dict(activate=js_code("function(p) {p.doLayout();}"),single=True),
     )
     jsgen.Value.__init__(self,kw)
Пример #17
0
def grid_model_lines(rh):
    #~ yield "Ext.define('Lino.%s.GridModel',{" % rh.report
    #~ yield "extend: 'Ext.data.Model',"
    #~ yield "fields: %s," % py2js([js_code(f.as_js()) for f in rh.store.list_fields])
    #~ yield "proxy: {"
    #~ yield "    type: 'rest',"
    #~ yield "    url : '%s'," % rh.ui.build_url(rh.report.app_label,rh.report._actor_name)
    #~ yield "    format: 'json'"
    #~ yield "    root: 'rows', "
    #~ yield "}"
    #~ yield "});"
    kw = dict()
    kw.update(extend='Ext.data.Model')
    kw.update(fields=[js_code(f.as_js()) for f in rh.store.list_fields])
    kw.update(idProperty=rh.store.pk.name)
    kw.update(proxy=dict(
      type='rest',
      url = '/api' + rh.ui.build_url(rh.report.app_label,rh.report._actor_name),
      totalProperty="count",
      format='json',
      root='rows',
      reader='array',
    ))
    yield "Ext.define('Lino.%s.GridModel',%s);" % (rh.report,py2js(kw))
Пример #18
0
 def ext_options(self,**kw):
     self.setup()
     kw = Panel.ext_options(self,**kw)
     if self.lh.layout.label:
         #~ kw.update(title=unicode(self.lh.layout.label))
         kw.update(title=_(self.lh.layout.label))
     #d.update(region='east',split=True) #,width=300)
     #~ kw.update(width=800)
     #~ kw.update(autoScroll=True)
     if False:
         kw.update(tbar=js_code("""new Ext.PagingToolbar({
           store: %s,
           displayInfo: true,
           pageSize: 1,
           prependButtons: true,
         }) """ % self.rh.store.ext_name))
     #d.update(items=js_code(self._main.as_ext(request)))
     #d.update(items=js_code("[%s]" % ",".join([e.as_ext() for e in self.elements])))
     #~ kw.update(items=self.elements)
     #d.update(autoHeight=False)
     #~ kw.update(bbar=self.bbar_buttons)
     #~ kw.update(bbar=self.buttons)
     #d.update(standardSubmit=True)
     return kw
Пример #19
0
    def py2js_converter(self, v):
        """
        Additional converting logic for serializing Python values to json.
        """
        if v is settings.SITE.LANGUAGE_CHOICES:
            return js_code('LANGUAGE_CHOICES')
        if isinstance(v, choicelists.Choice):
            """
            This is special. We don't render the text but the value.
            """
            return v.value
        if isinstance(v, models.Model):
            return v.pk
        if isinstance(v, Exception):
            return str(v)
        if isinstance(v, Menu):
            if v.parent is None:
                return v.items
                # kw.update(region='north',height=27,items=v.items)
                # return py2js(kw)
            return dict(text=v.label, menu=dict(items=v.items))

        if isinstance(v, MenuItem):
            if v.instance is not None:
                h = self.instance_handler(None, v.instance, None)
                assert h is not None
                js = "%s" % h
                return self.handler_item(v, h, None)
            elif v.bound_action is not None:
                if v.params:
                    ar = v.bound_action.request(**v.params)
                    js = self.request_handler(ar)
                else:
                    js = self.action_call(None, v.bound_action, {})
                return self.handler_item(v, js, v.help_text)

            elif v.javascript is not None:
                js = "%s" % v.javascript
                return self.handler_item(v, js, v.help_text)
            elif v.href is not None:
                url = v.href
            # ~ elif v.request is not None:
            # ~ raise Exception("20120918 request %r still used?" % v.request)
            # ~ url = self.get_request_url(v.request)
            else:
                # a separator
                # ~ return dict(text=v.label)
                return v.label
                # ~ url = self.build_url('api',v.action.actor.app_label,v.action.actor.__name__,fmt=v.action.name)
            if v.parent.parent is None:
                # special case for href items in main menubar
                return dict(
                    xtype='button',
                    text=v.label,
                    # ~ handler=js_code("function() { window.location='%s'; }" % url))
                    handler=js_code("function() { Lino.load_url('%s'); }" %
                                    url))
            return dict(text=v.label, href=url)
        if issubclass(v.__class__, LayoutElement):
            # Layout elems
            result = dict(label=v.get_label(),
                          repr=repr(v),
                          react_name=v.__class__.__name__
                          )  # Used for choosing correct react component
            if hasattr(v, "elements"):  # dd
                result['items'] = [
                    e for e in v.elements
                    if e.get_view_permission(get_user_profile())
                ]
            result.update(
                obj2dict(
                    v,
                    "fields_index fields_index_hidden editable vertical hpad is_fieldset name width preferred_width\
                                      hidden value hflex vflex"))
            # result["width"] = v.width or v.preferred_width
            # Slave tables
            if hasattr(v, "actor"):
                # reference to actor data for slave-grids
                result.update(obj2dict(
                    v.actor, "actor_id"))  # to get siteDate layout index

            # if hasattr(v, "get_field_options"):
            if issubclass(v.__class__, FieldElement):
                result.update(field_options=v.get_field_options())
                result.update(help_text=v.field.help_text)

            return result
        if isinstance(v, LayoutHandle):
            # Layout entry-point
            return dict(main=v.main, window_size=v.layout.window_size)

        if isinstance(v, Action):
            # todo include all aux info
            # todo include grid info
            # todo refactor this into a all_actions object and have the bound actions ref it to reduse json size
            result = dict(
                an=v.action_name,
                label=v.get_label(
                ),  # todo fix this, this is a readable action, not ID for the action
                window_action=v.is_window_action(),
                http_method=v.http_method,
            )

            # if v.show_in_bbar: result["bbar"] = True # not needed
            if v.preprocessor: result["preprocessor"] = v.preprocessor
            if v.combo_group: result["combo_group"] = v.combo_group
            if v.select_rows: result['select_rows'] = v.select_rows
            if v.submit_form_data: result['submit_form_data'] = True
            if v.button_text: result['button_text'] = v.button_text

            icon = self.get_action_icon(v)
            if icon: result['icon'] = icon

            return result

        if isinstance(v, BoundAction):

            # todo include all aux info
            # todo include grid info
            # todo refactor this into a all_actions object and have the bound actions ref it to reduse json size
            result = dict(
                an=v.action.action_name,
                window_layout=v.get_layout_handel(),
            )

            # if v.action.show_in_bbar: result["bbar"] = True # not needed
            if v.action.window_type:
                tba = []
                combo_group = None
                for ba in v.actor.get_toolbar_actions(v.action):
                    if ba.action.combo_group == combo_group and combo_group is not None:
                        previous = tba.pop()
                        if not isinstance(previous, list):
                            previous = [previous]
                        previous.append(ba.action.action_name)
                        tba.append(previous)
                    else:  # is normal
                        tba.append(ba.action.action_name)
                        combo_group = ba.action.combo_group
                result["toolbarActions"] = tba

            return result
        if isclass(v) and issubclass(v, Actor):
            result = dict(
                id=v.actor_id,
                ba=v._actions_dict,
                label=v.get_actor_label(),
                slave=bool(v.master),
                editable=v.editable,
                # [py2js(b) for b in v.actions.items()]
            )
            # grids
            if hasattr(v.get_handle(), "get_columns"):
                result['col'] = v.get_handle().get_columns()
                index_mod = 0
                for c in result['col']:
                    c.fields_index = find(v.get_handle().store.list_fields,
                                          c.field.name,
                                          key=lambda f: f.name) + index_mod
                    if isinstance(c, ComboFieldElement) and not isinstance(
                            c, SimpleRemoteComboFieldElement):
                        # Skip the data value for multi value columns, such as choices and FK fields.
                        # use c.fields_index -1 for data value
                        c.fields_index_hidden = c.fields_index + 1
                        index_mod += 1

            result.update(obj2dict(v.get_handle().store,
                                   "pk_index"))  # Data index which is the PK
            result.update(
                obj2dict(
                    v,
                    "preview_limit "  # number of rows to render # if 0 no paginator.
                    "use_detail_param_panel "  # show PV panel in detail
                    "use_detail_params_value "  # in grid, use parrent PV values
                    "hide_top_toolbar "  # No selection and toolbar
                    "use_detail_params_value "
                    "react_responsive "
                    "react_big_search "
                    "display_mode "
                    "max_render_depth "
                    "simple_slavegrid_header "
                    "paginator_template "
                    "hide_if_empty "
                    "borderless_list_mode "))

            card_layout = getattr(v, "card_layout", None)
            if card_layout is not None:
                result.update(card_layout=card_layout.get_layout_handle())
            # mt + slave-tables

            chooser_dict = getattr(v.model, "_choosers_dict", {})
            if chooser_dict:
                result.update(
                    chooser_dict={
                        fn: [cf.name for cf in c.context_fields]
                        for fn, c in chooser_dict.items()
                    })

            if settings.SITE.is_installed('contenttypes') and getattr(
                    v, 'model', None) is not None and hasattr(
                        v.model, "_meta"):
                # Perhaps I should have the model also be py2js'd?
                result.update(
                    content_type=ContentType.objects.get_for_model(v.model).pk)
            for a in "detail_action insert_action default_action".split(" "):
                if hasattr(v, a) and getattr(v, a) is not None:
                    result.update({a: getattr(v, a).action.action_name})

            if v.params_layout is not None:
                # Param field array and layout struct
                result.update(
                    pv_layout=v.params_layout.get_layout_handle(),
                    pv_fields=[
                        f.name
                        for f in v.params_layout.params_store.param_fields
                    ],
                )
            return result

        if isinstance(v, js_code) and getattr(self, "serialise_js_code",
                                              False):
            # Convert js_code into strings so they are serialised. rather than displayed w/o quotes
            return str(v.s)

        return v
Пример #20
0
        # ~ de.primary_key = False # for ext_store.Store()
        #~ lh.add_store_field(de)
        #~ return ext_elems.LinkedForeignKeyElement(lh,de,**kw)

    if isinstance(de, generic.GenericForeignKey):
        # create a horizontal panel with 2 comboboxes
        #~ print 20111123, name,de.ct_field + ' ' + de.fk_field
        #~ return lh.desc2elem(panelclass,name,de.ct_field + ' ' + de.fk_field,**kw)
        #~ return ext_elems.GenericForeignKeyField(lh,name,de,**kw)
        de.primary_key = False  # for ext_store.Store()
        lh.add_store_field(de)
        return ext_elems.GenericForeignKeyElement(lh, de, **kw)

    if isinstance(de, type) and issubclass(de, tables.AbstractTable):
        # The data element refers to a table.
        kw.update(master_panel=js_code("this"))
        if isinstance(lh.layout, FormLayout):
            # When a table is specified in the layout a DetailWindow,
            # then it will be rendered as a panel that displays a
            # "summary" of that table. The panel will have a tool
            # button to "open that table in its own window". The
            # format of that summary is defined by the
            # `slave_grid_format` of the table. `slave_grid_format` is
            # a string with one of the following values:

            kw.update(tools=[
                js_code("Lino.show_in_own_window_button(Lino.%s)" %
                      de.default_action.full_name())])
            if de.slave_grid_format == 'grid':
                kw.update(hide_top_toolbar=True)
                if de.preview_limit is not None:
Пример #21
0
    def js_render_window_action(self, rh, ba):
        # x = str(rh)
        # if x.startswith('working'):
        #     print "20150421 {0}".format(x)
        # profile = get_user_profile()
        rpt = rh.actor

        if rpt.parameters and ba.action.use_param_panel:
            params_panel = rh.params_layout_handle
        else:
            params_panel = None

        if isinstance(ba.action, ShowDetail):
            mainPanelClass = "Lino.%sPanel" % ba.full_name()
        elif isinstance(ba.action, ShowInsert):
            mainPanelClass = "Lino.%sPanel" % ba.full_name()
        elif isinstance(ba.action, ShowTable):
            mainPanelClass = "Lino.%s.GridPanel" % rpt
        elif ba.action.parameters and not ba.action.no_params_window:
            params_panel = ba.action.make_params_layout_handle()
        elif ba.action.extjs_main_panel:
            pass
        else:
            # print "20150421 {0}".format(rh)
            return

        windowConfig = dict()
        wl = ba.get_window_layout()
        ws = ba.get_window_size()
        # ~ if wl is not None:
        # ~ ws = wl.window_size
        if True:
            if ws:
                windowConfig.update(
                    # ~ width=ws[0],
                    # width=js_code('Lino.chars2width(%d)' % ws[0]),
                    maximized=False,
                    draggable=True,
                    maximizable=True,
                    modal=True)
                # if isinstance(ws[0], basestring) and ws[0].endswith("%"):
                #     windowConfig.update(
                #         width=js_code('Lino.perc2width(%s)' % ws[0][:-1]))
                if isinstance(ws[0], str):
                    windowConfig.update(width=ws[0])
                else:
                    windowConfig.update(width=js_code('Lino.chars2width(%d)' %
                                                      ws[0]))
                if ws[1] == 'auto':
                    # windowConfig.update(autoHeight=True)
                    windowConfig.update(height=True)
                elif isinstance(ws[1], int):
                    # ~ windowConfig.update(height=ws[1])
                    windowConfig.update(height=js_code('Lino.rows2height(%d)' %
                                                       ws[1]))
                else:
                    raise ValueError("height")
                    # ~ print 20120629, action, windowConfig

        yield "Lino.%s = Ext.create('Lino.WindowAction',%s, function(){" % (
            ba.full_name(), py2js(windowConfig))
        # ~ yield "  console.log('20120625 fn');"
        if ba.action.extjs_main_panel:
            yield "  return %s;" % ba.action.extjs_main_panel
        else:
            p = dict()
            # if ba.action is settings.SITE.get_main_action(profile):
            #     p.update(is_home_page=True)
            if ba.action.hide_top_toolbar or ba.actor.hide_top_toolbar or ba.action.parameters:
                p.update(hide_top_toolbar=True)
            if rpt.hide_window_title:
                p.update(hide_window_title=True)

            p.update(is_main_window=True)  # workaround for problem 20111206
            yield "  var p = %s;" % py2js(p)
            if params_panel:
                if ba.action.parameters:
                    yield "  return Ext.create('Lino.%s',{});" % wl._formpanel_name
                else:
                    yield "  p.params_panel = Ext.create('Lino.%s',{});" % params_panel.layout._formpanel_name
                    yield "  return Ext.create('%s',{p});" % mainPanelClass
            else:
                yield "  return Ext.create('%s',{p});" % mainPanelClass
        yield "});"
Пример #22
0
    def js_render_GridPanel_class(self, rh):

        yield ""
        yield "// js_render_GridPanel_class %s" % rh.actor
        # yield "Lino.%s.GridPanel = Ext.extend(Lino.GridPanel,{" % rh.actor
        yield "Ext.define('Lino.%s.GridPanel', { extend : 'Lino.GridPanel'," % rh.actor

        kw = dict()
        # ~ kw.update(empty_title=%s,rh.actor.get_button_label()
        if getattr(rh.actor, 'use_detail_params_value', None):
            kw.update(use_detail_params_value=True)
        kw.update(ls_url=rh.actor.actor_url())
        kw.update(ls_store_fields=[
            js_code(f.as_js(f.name)) for f in rh.store.list_fields
        ])
        if rh.store.pk is not None:
            kw.update(ls_id_property=rh.store.pk.name)
            kw.update(pk_index=rh.store.pk_index)
            if settings.SITE.is_installed('contenttypes'):
                m = getattr(rh.store.pk, 'model', None)
                # e.g. pk may be the VALUE_FIELD of a choicelist which
                # has no model
                if m is not None:
                    ct = ContentType.objects.get_for_model(m).pk
                    kw.update(content_type=ct)

        kw.update(cell_edit=rh.actor.cell_edit)
        kw.update(ls_bbar_actions=self.toolbar(
            rh.actor.get_toolbar_actions(rh.actor.default_action.action)))
        kw.update(ls_grid_configs=[gc.data for gc in rh.actor.grid_configs])
        kw.update(gc_name=constants.DEFAULT_GC_NAME)
        # ~ if action != rh.actor.default_action:
        # ~ kw.update(action_name=action.name)
        # ~ kw.update(content_type=rh.report.content_type)

        vc = dict(emptyText=_("No data to display."))
        if rh.actor.editable:
            vc.update(getRowClass=js_code('Lino.getRowClass'))
        if rh.actor.auto_fit_column_widths:
            kw.update(forceFit=True)
        if rh.actor.variable_row_height:
            vc.update(cellTpl=js_code("Lino.auto_height_cell_template"))
        if rh.actor.row_height != 1:
            kw.update(row_height=rh.actor.row_height)
            tpl = """new Ext.Template(
        '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>',
        '<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" style="height:%dpx" {attr}>{value}</div>',
        '</td>')""" % (rh.actor.row_height * 11)
            vc.update(cellTpl=js_code(tpl))

        if rh.actor.drag_drop_sequenced_field is not None:
            vc.update(
                plugins={
                    'ptype': 'gridviewdragdrop',
                    'dragText': 'Drag and drop to reorganize',
                    'sequenced_field': rh.actor.drag_drop_sequenced_field
                })
        #todo get a field atrib also into the config somehow.
        kw.update(viewConfig=vc)

        if not rh.actor.editable:
            kw.update(disable_editing=True)

        if rh.actor.use_paging:
            kw.update(use_paging=True)

        if rh.actor.params_panel_hidden:
            kw.update(params_panel_hidden=True)

        if rh.actor.start_at_bottom:
            kw.update(start_at_bottom=True)
        kw.update(page_length=rh.actor.page_length)
        kw.update(stripeRows=True)

        # if rh.actor.label is not None:
        kw.update(title=rh.actor.label)
        if rh.actor.editable:
            kw.update(
                disabled_fields_index=rh.store.column_index('disabled_fields'))

        for k, v in kw.items():
            yield "  %s : %s," % (k, py2js(v))

        yield "  initComponent : function() {"

        a = rh.actor.detail_action
        if a:
            yield "    this.ls_detail_handler = Lino.%s;" % a.full_name()
        a = rh.actor.insert_action
        if a:
            yield "    this.ls_insert_handler = Lino.%s;" % a.full_name()

        yield "    var ww = this.containing_window;"
        for ln in jsgen.declare_vars(rh.list_layout.main.columns):
            yield "    " + ln

        yield "    this.before_row_edit = function(record) {"
        for ln in self.before_row_edit(rh.list_layout.main):
            yield "      " + ln
        yield "    };"

        on_render = self.build_on_render(rh.list_layout.main)
        if on_render:
            yield "    this.onRender = function(ct, position) {"
            for ln in on_render:
                yield "      " + ln
            yield "      Lino.%s.GridPanel.superclass.onRender.call(this, ct, position);" % rh.actor
            # yield "this.callSuper(ct, position);"
            yield "    }"

        yield "    this.ls_columns = %s;" % py2js([
            ext_elems.GridColumn(rh.list_layout, i, e)
            for i, e in enumerate(rh.list_layout.main.columns)
        ])

        # yield "    Lino.%s.GridPanel.superclass.initComponent.call(this);" \
        #     % rh.actor
        yield "this.callSuper();"
        yield "  }"
        yield "});"
        yield ""
Пример #23
0
 def __init__(self,lh,name,dv,**kw):
     #~ self.dv = dv
     #~ kw.update(tpl=js_code('new Ext.XTemplate(%s)' % py2js(dv.xtemplate)))
     kw.update(plugins=js_code('new Lino.TemplateBoxPlugin(caller,%s)' % py2js(dv.xtemplate)))
     LayoutElement.__init__(self,lh,name,**kw)
Пример #24
0
 def store_options(self,**kw):
     proxy = dict(url=self.lh.rh.ui.get_choices_url(self),method='GET')
     kw.update(proxy=js_code("new Ext.data.HttpProxy(%s)" % py2js(proxy)))
     # a JsonStore without explicit proxy sometimes used method POST
     return kw
Пример #25
0
 def get_field_options(self,**kw):
     kw = FieldElement.get_field_options(self,**kw)
     sto = self.store_options()
     #print repr(sto)
     kw.update(store=js_code("new Lino.ComplexRemoteComboStore(%s)" % py2js(sto)))
     return kw