Beispiel #1
0
    def parse(self, model, root_node, fields, container):
        attrs = Common.nodeAttributes(root_node)
        self.title = attrs.get('string', 'Unknown')

        onWriteFunction = ''

        axis = []
        groups = []
        axis_data = {}
        for node in root_node.childNodes:
            if node.localName == 'field':
                node_attrs = Common.nodeAttributes(node)
                if node_attrs.get('group', False):
                    groups.append(str(node_attrs['name']))
                else:
                    axis.append(str(node_attrs['name']))
                axis_data[str(node_attrs['name'])] = node_attrs

        #
        # TODO: parse root_node to fill in axis
        #

        chart = ChartGraphicsView(container)
        chart.setModel(self.parent.currentRecord())
        chart.setType(attrs.get('type', 'pie'))
        chart.setAxis(axis)
        chart.setGroups(groups)
        chart.setFields(fields)
        chart.setAxisData(axis_data)
        if attrs.get('orientation', 'vertical') == 'vertical':
            chart.setOrientation(Qt.Vertical)
        else:
            chart.setOrientation(Qt.Horizontal)

        return chart, onWriteFunction
Beispiel #2
0
    def create(self, viewId, parent, viewModel, rootNode, fields, filter=None):
        self.viewModel = viewModel
        self.filter = filter
        self.widgetList = []
        # Create the view
        self.view = SvgView(parent)
        self.view.id = viewId
        self.view
        directory = os.path.abspath(os.path.dirname(__file__))

        for node in rootNode.childNodes:
            if node.localName == 'field':
                attributes = Common.nodeAttributes(node)
                name = attributes['name']
                type = attributes.get('widget', fields[name]['type'])
                fields[name].update(attributes)
                fields[name]['model'] = viewModel

                # Create the appropiate widget for the given field type
                widget = FieldWidgetFactory.create(type, None, self.view,
                                                   fields[name])
                if not widget:
                    continue
                self.view.widgets[name] = widget

        self.view.fields = fields

        self.view.setSvg(os.path.join(directory, 'restaurant.svg'))
        return self.view
Beispiel #3
0
    def _parseDiagram(self, model, view, rootNode):
        # The parsing part:
        mainNod = None
        for node in rootNode.childNodes:
            if node.nodeType != xml.dom.Node.ELEMENT_NODE:
                continue
            natrs = Common.nodeAttributes(node)
            itno = None
            if node.localName == 'linear':
                itno = KsmLinear(view.scene)
                try:
                    dx, dy = _dxy2deltas(natrs.get('dxy', 'right'))
                    itno.setSpacing(dx, dy)
                except:
                    pass

                itno.setFreeMove(True)

                chnod = self._parseDiaNode(model, view, node)
                itno.setChildProj(chnod)

            #elif node.localName == 'main':

            else:
                print "Unknown node in diagram:", node.localName

            if itno:
                view.projections.append(itno)

            if itno and not natrs.get('name', False):
                if mainNod:
                    raise Exception("Two unnamed nodes found in diagram")
                mainNod = itno

        return mainNod
Beispiel #4
0
    def _parseDiaNode(self, model, view, dNode):
        # The parsing part:
        for node in dNode.childNodes:
            itno = None
            if node.nodeType != ELEMENT_NODE:
                continue

            natrs = Common.nodeAttributes(node)
            if node.localName == 'lincols':
                itno = KsmColumns(view.scene)  # FIXME
                try:
                    dx, dy = _dxy2deltas(natrs.get('dxy', 'right'))
                    itno.setSpacing(dx, dy)
                except:
                    pass
                #itno.setDrawBox(True)
                pbox = KsmBox(view.scene)
                pbox.setDrawBox(False)
                view.projections.append(pbox)
                itno.setChildProj(pbox)
                for chn in node.childNodes:
                    if chn.nodeType != ELEMENT_NODE:
                        continue
                    if chn.localName == 'field':
                        chnat = Common.nodeAttributes(chn)
                        self.header.append({'name': chnat['name']})

            elif node.localName == 'box':
                itno = KsmBox(view.scene)
            else:
                print "Unknown node in projection:", node.localName

            if itno:  # TODO
                view.projections.append(itno)
                return itno
        return None
Beispiel #5
0
 def _parse_fields(self, node, fields):
     if node.nodeType == node.ELEMENT_NODE:
         if node.localName == 'field':
             attrs = Common.nodeAttributes(node)
             if attrs.get('widget', False):
                 if attrs['widget'] == 'one2many_list':
                     attrs['widget'] = 'one2many'
                 attrs['type'] = attrs['widget']
             try:
                 fields[attrs['name']].update(attrs)
             except:
                 print("-" * 30, "\n malformed tag for :", attrs)
                 print("-" * 30)
                 raise
     for node2 in node.childNodes:
         self._parse_fields(node2, fields)
Beispiel #6
0
    def create(self, viewId, parent, viewModel, node, fields):
        self.viewModel = viewModel
        self.parent = parent

        attrs = Common.nodeAttributes(node)

        # Create the view
        self.view = ChartView(parent)
        self.view.id = viewId
        self.view.title = attrs.get('string', _('Unknown'))
        self.view.model = self.parent.currentRecord()

        widget, onWriteFunction = self.parse(self.parent.currentRecord(), node,
                                             fields, self.view)
        self.view.setWidget(widget)
        self.view.setOnWriteFunction(onWriteFunction)

        return self.view
Beispiel #7
0
    def parse(self, root_node, fields, notebook=None, container=None):
        attrs = Common.nodeAttributes(root_node)
        onWriteFunction = attrs.get('on_write', '')

        if container == None:
            parent = self.view
            if notebook:
                parent = notebook
            # We want FormContainer parent to be the notebook for the case
            # when it's a QTabWidget. This way FormContainer can enable/disable
            # the tab when necessary.
            container = FormContainer(parent, int(attrs.get('col', 4)), fields)

        if not self.view.title:
            self.view.title = attrs.get('string', 'Unknown')

        for node in root_node.childNodes:
            if not node.nodeType == node.ELEMENT_NODE:
                continue
            attrs = Common.nodeAttributes(node)
            if node.localName == 'image':
                icon = QLabel(container)
                icon.setPixmap(Icons.kdePixmap(attrs['name']))
                container.addWidget(icon, attrs)

            elif node.localName == 'separator':
                caption = attrs.get('string', '')

                separator = QWidget(container)
                label = QLabel(separator)
                label.setText(caption)
                font = label.font()
                font.setBold(True)
                label.setFont(font)
                line = QFrame(separator)
                line.setFrameShadow(QFrame.Plain)
                if attrs.get('orientation') == 'vertical':
                    line.setFrameShape(QFrame.VLine)
                    separator.setSizePolicy(
                        QSizePolicy.Fixed, QSizePolicy.Expanding)
                    layout = QHBoxLayout(separator)
                else:
                    line.setFrameShape(QFrame.HLine)
                    separator.setSizePolicy(
                        QSizePolicy.Expanding, QSizePolicy.Fixed)
                    layout = QVBoxLayout(separator)
                layout.setAlignment(Qt.AlignTop)
                layout.setContentsMargins(0, 0, 0, 0)
                layout.setSpacing(0)
                layout.addWidget(label)
                layout.addWidget(line)

                self.view.addStateWidget(
                    separator, attrs.get('attrs'), attrs.get('states'))
                container.addWidget(separator, attrs)

            elif node.localName == 'label':
                text = attrs.get('string', '')
                if not text:
                    for node in node.childNodes:
                        if node.nodeType == node.TEXT_NODE:
                            text += node.data
                        else:
                            text += node.toxml()
                label = QLabel(text, container)
                label.setWordWrap(True)
                if 'width' in attrs:
                    label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                    label.setMinimumWidth(int(attrs['width']))
                    label.setMaximumWidth(int(attrs['width']))
                else:
                    label.setSizePolicy(
                        QSizePolicy.Preferred, QSizePolicy.Fixed)
                container.addWidget(label, attrs)

            elif node.localName == 'newline':
                container.newRow()

            elif node.localName == 'button':
                if not self.isWidgetVisible(attrs):
                    continue
                button = FieldWidgetFactory.create(
                    'button', container, self.view, attrs)
                name = attrs.get('name')
                if not name:
                    name = 'unnamed_%d' % self.unnamed
                    self.unnamed += 1
                self.view.widgets[name] = button
                self.view.addStateWidget(
                    button, attrs.get('attrs'), attrs.get('states'))
                container.addWidget(button, attrs)

            elif node.localName == 'notebook':
                if not self.isWidgetVisible(attrs):
                    continue
                tab = FormTabWidget(container)
                if attrs and 'tabpos' in attrs:
                    pos = {
                        'up': QTabWidget.North,
                        'down': QTabWidget.South,
                        'left': QTabWidget.West,
                        'right': QTabWidget.East
                    }[attrs['tabpos']]
                else:
                    pos = {
                        'left': QTabWidget.West,
                        'top': QTabWidget.North,
                        'right': QTabWidget.East,
                        'bottom': QTabWidget.South
                    }[Settings.value('koo.tabs_position')]

                tab.setTabPosition(pos)

                attrs['colspan'] = attrs.get('colspan', 3)

                container.addWidget(tab, attrs)

                # We pass a container because othewise a new container would
                # be created by parse() and we don't want that because the tab
                # itself doesn't have a container: it's each of it's pages
                # that will have a container.
                _, onWriteFunction = self.parse(node, fields, tab, container)

            elif node.localName == 'page':
                if not self.isWidgetVisible(attrs):
                    continue
                widget, onWriteFunction = self.parse(node, fields, notebook)
                # Mark the container as the main widget in a Tab. This way
                # we can enable/disable the whole tab easily.
                widget.isTab = True
                self.view.addStateWidget(
                    widget, attrs.get('attrs'), attrs.get('states'))

                notebook.addTab(widget, Common.normalizeLabel(
                    attrs.get('string', '')))

            elif node.localName == 'hpaned':
                widget = QSplitter(Qt.Horizontal, container)

                container.addWidget(widget, attrs)
                self.parse(node, fields, widget, container)

            elif node.localName == 'vpaned':
                widget = QSplitter(Qt.Vertical, container)

                container.addWidget(widget, attrs)
                self.parse(node, fields, widget, container)

            elif node.localName == 'child1':
                widget, onWriteFunction = self.parse(node, fields)
                notebook.addWidget(widget)

            elif node.localName == 'child2':
                widget, onWriteFunction = self.parse(node, fields)
                notebook.addWidget(widget)

            elif node.localName == 'action':
                name = str(attrs['name'])
                widget = FieldWidgetFactory.create(
                    'action', container, self.view, attrs)
                attrs['colspan'] = attrs.get('colspan', 3)
                self.view.widgets[name] = widget
                container.addWidget(widget, attrs)

            elif node.localName == 'field':
                if not self.isWidgetVisible(attrs):
                    continue
                name = attrs['name']
                del attrs['name']
                type = attrs.get('widget', fields[name]['type'])
                fields[name].update(attrs)
                fields[name]['model'] = self.viewModel

                # Create the appropiate widget for the given field type
                widget = FieldWidgetFactory.create(
                    type, container, self.view, fields[name])
                if not widget:
                    continue

                fields[name]['name'] = name
                if self.filter:
                    widget.node = node
                    self.widgetList.append(widget)

                label = None
                if not int(attrs.get('nolabel', 0)):
                    label = fields[name]['string'] + ' :'

                self.view.widgets[name] = widget
                #attrs['colspan'] = int(attrs.get('colspan', widgets_type[ type ][1]))

                if not 'help' in attrs:
                    attrs['help'] = fields[name].get('help', False)

                container.addWidget(widget, attrs, label)

            elif node.localName == 'group':
                if not self.isWidgetVisible(attrs):
                    continue
                widget, onWriteFunction = self.parse(node, fields, notebook)
                if 'string' in attrs:
                    group = QGroupBox(notebook)
                    group.setTitle(attrs['string'])
                    layout = QHBoxLayout(group)
                    layout.setAlignment(Qt.AlignTop)
                    layout.setContentsMargins(0, 0, 0, 0)
                    layout.setSpacing(0)
                    layout.addWidget(widget)
                    widget = group

                self.view.addStateWidget(
                    widget, attrs.get('attrs'), attrs.get('states'))
                container.addWidget(widget, attrs)

        return container, onWriteFunction
Beispiel #8
0
    def create(self, viewId, parent, model, rootNode, fields):
        # It's expected that parent will be a Screen
        screen = parent

        attrs = Common.nodeAttributes(rootNode)

        view = TreeView(parent, attrs.get('type', 'tree'))
        view.id = viewId
        if 'gridwidth' in attrs:
            view.setGridWidth(int(attrs['gridwidth']))
        if 'gridheight' in attrs:
            view.setGridWidth(int(attrs['gridheight']))

        view.setOnWriteFunction(attrs.get('on_write', ''))

        if not view.title:
            view.title = attrs.get('string', 'Unknown')

        colors = []
        for color_spec in attrs.get('colors', '').split(';'):
            if color_spec:
                colour, test = color_spec.split(':')
                colors.append((colour, str(test)))

        columns = []
        buttons = {}
        for node in rootNode.childNodes:
            node_attrs = Common.nodeAttributes(node)
            if node.localName == 'button':
                fname = node_attrs['name']
                columns.append({
                    'name': fname,
                    'width': 20,
                    'type': 'button',
                    'attributes': node_attrs,
                    'visible': True,
                })
                buttons[fname] = node_attrs
            if node.localName == 'field':
                fname = node_attrs['name']
                twidth = {
                    'integer': 60,
                    'float': 80,
                    'date': 70,
                    'datetime': 130,
                    'selection': 130,
                    'char': 140,
                    'one2many': 50,
                }

                if 'readonly' in node_attrs:
                    fields[fname]['readonly'] = Common.stringToBool(
                        node_attrs['readonly'])
                if 'required' in node_attrs:
                    fields[fname]['required'] = Common.stringToBool(
                        node_attrs['required'])

                if 'sum' in node_attrs and fields[fname]['type'] in ('integer', 'float', 'float_time'):
                    bold = bool(int(node_attrs.get('sum_bold', 0)))
                    label = node_attrs['sum']
                    digits = fields.get('digits', (16, 2))
                    view.addAggregate(fname, label, bold, digits)

                node_attrs.update(fields[fname])

                visible = not eval(fields[fname].get('invisible', 'False'), {
                                   'context': screen.context})

                if 'width' in fields[fname]:
                    width = int(fields[fname]['width'])
                else:
                    width = twidth.get(fields[fname]['type'], 200)
                columns.append({
                    'name': fname,
                    'width': width,
                    'type': fields[fname]['type'],
                    'attributes': node_attrs,
                    'visible': visible,
                })

        view.finishAggregates()

        model = KooModel.KooModel(view)
        model.setMode(KooModel.KooModel.ListMode)
        model.setRecordGroup(screen.group)
        model.setFields(fields)
        model.setButtons(buttons)
        model.setFieldsOrder([x['name'] for x in columns])
        model.setColors(colors)
        model.setReadOnly(not attrs.get('editable', False))
        view.setReadOnly(not attrs.get('editable', False))

        if attrs.get('editable', False) == 'top':
            view.setAddOnTop(True)

        if view.isReadOnly():
            model.setShowBackgroundColor(False)
        else:
            model.setShowBackgroundColor(True)

        # Here we use a trick to avoid double data loading.
        # If we don't disallow record loading, records would be loaded twice
        # once, in "view.setModel( model )" and another one when Screen loads
        # view.setViewSettings(). What we do here is disallow record loading,
        # run setModel(), load settings and finally allow record loading again.
        # This optimizes Tree View loading times.
        domain = screen.group.domain()
        screen.group.setDomainForEmptyGroup()

        view.setModel(model)

        for column in range(len(columns)):
            current = columns[column]
            if view._widgetType in ('tree', 'table'):
                view.widget.setColumnWidth(column, current['width'])
            if not current['visible']:
                view.widget.hideColumn(column)

            delegate = FieldDelegateFactory.create(
                current['type'], view.widget, current['attributes'])
            view.widget.setItemDelegateForColumn(column, delegate)

        view.setViewSettings(ViewSettings.load(view.id))

        screen.group.setDomain(domain)

        return view
Beispiel #9
0
    def create(self, viewId, parent, viewModel, rootNode, fields, filter=None):
        self.viewModel = viewModel
        self.filter = filter

        self.header = [{'name': 'name'}]
        # It's expected that parent will be a Screen
        screen = parent
        attrs = Common.nodeAttributes(rootNode)
        colors = []
        print "Model, Filter:", viewModel, ',', filter

        for color_spec in attrs.get('colors', '').split(';'):
            if color_spec:
                colour, test = color_spec.split(':')
                colors.append((colour, str(test)))

        if attrs.get('debug', True):
            model = KooModelDbg.KooModelDbg(parent)
        else:
            model = KooModel.KooModel(parent)

        model.setMode(KooModel.KooModel.ListMode)
        #model.setMode( KooModel.KooModel.TreeMode )
        model.setReadOnly(not attrs.get('editable', False))
        screen.group.setAllowRecordLoading(False)
        model.setRecordGroup(screen.group)

        view = ShowerView(model, parent)
        #if not view.title:
        #	view.title = attrs.get('string', 'Unknown' )
        # view.setReadOnly( not attrs.get('editable', False) )

        #if attrs.get('editable', False) == 'top':
        #	view.setAddOnTop( True )

        rootProj = self._parseDiagram(model, view, rootNode)
        assert rootProj, "No main projection found in <diagram>"

        print "Diagram fields:", fields.keys()
        print "Diagram header:", self.header
        model.setFields(fields)
        try:
            pfields = []
            for n in self.header:
                if not fields.has_key(n['name']):
                    pfields.append(n['name'])

            afields = {}
            if len(pfields):
                afields.update(
                    Rpc.session.execute('/object', 'execute', self.viewModel,
                                        'fields_get', pfields,
                                        screen.group.context))
                # print "Brought extra fields:", afields

            for h in self.header:
                for k in h.keys():
                    if k in ('type', 'string', 'width'):
                        afields[h['name']][k] = h[k]

            print "Fields to add:", afields
            screen.group.addFields(afields)
            del afields
        except Exception, e:
            print "Sth went wrong", e
            pass