Ejemplo n.º 1
0
  def read_plugin_file( self, dir, name):
    doc = dom.parse( os.path.join( dir, name))
    root = doc.childNodes[0]
    plugin_type = root.getAttribute( 'type') or 'script'
    sources = dom_ext.simpleXPathSearch( doc, "/plugin/source")
    if sources:
      source = sources[0]
      files = dom_ext.simpleXPathSearch( source, "file")
      names = dom_ext.simpleXPathSearch( source, "menu-text")
      descs = dom_ext.simpleXPathSearch( source, "/plugin/meta/description")
      menus = dom_ext.simpleXPathSearch( source, "menu")
      if files and names:
        file = dom_ext.getAllTextFromElement( files[0])
        if not os.path.isabs( file):
          file = os.path.normpath( os.path.join( dir, file))
        name = self._select_correct_text( names)
        if menus:
          menu = dom_ext.getAllTextFromElement( menus[0])
        else:
          menu = ""

        plugin = plugin_handler( name, file, type=plugin_type,
                                 desc=self._select_correct_text( descs),
                                 menu=menu)
        self.plugins[ name] = plugin
Ejemplo n.º 2
0
 def _select_correct_text( self, texts):
   """returns the right text according to the lang attribute"""
   if not texts:
     return ''
   for text in texts:
     lang = text.getAttribute( "lang") or "en"
     if lang == Store.lang:
       return dom_ext.getAllTextFromElement( text)
   # if nothing found, return the first one
   return dom_ext.getAllTextFromElement( texts[0])
Ejemplo n.º 3
0
 def read_from_dom( self, doc):
   top = doc.getElementsByTagName( "bkchem-prefs")[0]
   for child in dom_extensions.childNodesWithoutEmptySpaces( top):
     name = child.nodeName
     itype = child.getAttribute( 'type') or unicode
     if itype in ("ListType", "TupleType", "DictType"):
       value = eval( dom_extensions.getAllTextFromElement( child))
     else:
       itype = types.__dict__[ itype]
       try:
         value = itype( dom_extensions.getAllTextFromElement( child))
       except:
         print >> sys.stderr, "Preference manager: ignoring value %s of type %s" % (dom_extensions.getAllTextFromElement( child), itype)
         break
     self.add_preference( name, value)
Ejemplo n.º 4
0
    def read_package(self, doc):
        self.id = doc.getAttribute("id")
        self.type = doc.getAttribute("type") or "explicit"
        name = dom_ext.getFirstChildNamed(doc, "name")
        if name:
            self.name = dom_ext.getAllTextFromElement(name)
        for b in dom_ext.simpleXPathSearch(doc, "bond"):
            try:
                self.edges.add(
                    Store.id_manager.get_object_with_id(b.getAttribute("id")))
            except KeyError:
                raise bkchem_fragment_error("inconsistent", "")

        for v in dom_ext.simpleXPathSearch(doc, "vertex"):
            try:
                self.vertices.add(
                    Store.id_manager.get_object_with_id(v.getAttribute("id")))
            except KeyError:
                raise bkchem_fragment_error("inconsistent", "")

        for p in dom_ext.simpleXPathSearch(doc, "property"):
            k = p.getAttribute("name")
            v = p.getAttribute("value")
            t = p.getAttribute("type")
            typ = types.__dict__[t]
            self.properties[k] = typ(v)
Ejemplo n.º 5
0
    def text(self):
        """Unmarked plain-text representing the object.

    Taken from xml_ftext and the markup is stripped.
    """
        doc = dom.parseString(ftext.ftext.sanitize_text(self.xml_ftext))
        return dom_extensions.getAllTextFromElement(doc)
Ejemplo n.º 6
0
    def read_data_definition(self, filename):
        doc = dom.parse(filename)
        root = doc.childNodes[0]
        for ecls in dom_ext.simpleXPathSearch(root, "class"):
            cls = ecls.getAttribute('name')
            self.definitions[cls] = {}
            for eobj in dom_ext.simpleXPathSearch(ecls, "object"):
                obj = eobj.getAttribute('type')
                self.definitions[cls][obj] = {}
                for evalue in dom_ext.simpleXPathSearch(eobj, "value"):
                    vname = evalue.getAttribute('name')
                    vtype = evalue.getAttribute('type')
                    # try to decode list style types
                    if vtype.startswith("[") and vtype.endswith("]"):
                        try:
                            vtype = eval(vtype)
                        except ValueError:
                            pass
                    text = dom_ext.getAllTextFromElement(
                        dom_ext.getFirstChildNamed(evalue, "text"))
                    self.definitions[cls][obj][vname] = {
                        'type': vtype,
                        'text': text
                    }

        self.records[cls] = {}
Ejemplo n.º 7
0
  def text(self):
    """Unmarked plain-text representing the object.

    Taken from xml_ftext and the markup is stripped.
    """
    doc = dom.parseString( ftext.ftext.sanitize_text(self.xml_ftext))
    return dom_extensions.getAllTextFromElement(doc)
Ejemplo n.º 8
0
 def _read_bond(self, bo):
     b = bond(self.paper)
     b.order = gtml_to_bkchem_bond_order_remap.index(
         dom_ext.getAllTextFromElement(xpath.Evaluate("bond", bo)[0]))
     ids = [i.nodeValue for i in xpath.Evaluate("end/@idref", bo)]
     b.atoms = [self._atom_id_remap[i] for i in ids]
     return b
Ejemplo n.º 9
0
 def _read_atom(self, at, mol):
     a = atom(self.paper, molecule=mol)
     a.set_name(
         dom_ext.getAllTextFromElement(
             dom_ext.getFirstChildNamed(at, "symbol")))
     coords = dom_ext.getFirstChildNamed(at, "coordinates")
     a.x = float(
         dom_ext.getAllTextFromElement(
             dom_ext.getFirstChildNamed(coords, "x")))
     a.y = float(
         dom_ext.getAllTextFromElement(
             dom_ext.getFirstChildNamed(coords, "y")))
     a.z = float(
         dom_ext.getAllTextFromElement(
             dom_ext.getFirstChildNamed(coords, "z")))
     a.show_hydrogens = int(a.name != 'C')
     # charge
     chel = dom_ext.getFirstChildNamed(at, "charge")
     if chel:
         a.charge = int(dom_ext.getAllTextFromElement(chel))
     # multiplicity
     radical = dom_ext.getFirstChildNamed(at, "radical")
     if radical:
         a.multiplicity = 1 + int(dom_ext.getAllTextFromElement(radical))
     # remap of ids
     self._atom_id_remap[at.getAttribute('id')] = a
     return a
Ejemplo n.º 10
0
  def read_data_definition( self, filename):
    doc = dom.parse( filename)
    root = doc.childNodes[0]
    for ecls in dom_ext.simpleXPathSearch( root, "class"):
      cls = ecls.getAttribute( 'name')
      self.definitions[ cls] = {}
      for eobj in dom_ext.simpleXPathSearch( ecls, "object"):
        obj = eobj.getAttribute( 'type')
        self.definitions[ cls][ obj] = {}
        for evalue in dom_ext.simpleXPathSearch( eobj, "value"):
          vname = evalue.getAttribute( 'name')
          vtype = evalue.getAttribute( 'type')
          # try to decode list style types
          if vtype.startswith( "[") and vtype.endswith( "]"):
            try:
              vtype = eval( vtype)
            except ValueError:
              pass
          text = dom_ext.getAllTextFromElement( dom_ext.getFirstChildNamed( evalue, "text"))
          self.definitions[ cls][ obj][ vname] = {'type': vtype,
                                                  'text': text }

    self.records[ cls] = {}
Ejemplo n.º 11
0
  def read_package( self, doc):
    self.id = doc.getAttribute( "id")
    self.type = doc.getAttribute( "type") or "explicit"
    name = dom_ext.getFirstChildNamed( doc, "name")
    if name:
      self.name = dom_ext.getAllTextFromElement( name)
    for b in dom_ext.simpleXPathSearch( doc, "bond"):
      try:
        self.edges.add( Store.id_manager.get_object_with_id( b.getAttribute( "id")))
      except KeyError:
        raise bkchem_fragment_error( "inconsistent", "")

    for v in dom_ext.simpleXPathSearch( doc, "vertex"):
      try:
        self.vertices.add( Store.id_manager.get_object_with_id( v.getAttribute( "id")))
      except KeyError:
        raise bkchem_fragment_error( "inconsistent", "")

    for p in dom_ext.simpleXPathSearch( doc, "property"):
      k = p.getAttribute( "name")
      v = p.getAttribute( "value")
      t = p.getAttribute( "type")
      typ = types.__dict__[ t]
      self.properties[k] = typ( v)
Ejemplo n.º 12
0
 def _read_atom(self, at, mol):
     a = atom(self.paper, molecule=mol)
     a.set_name(dom_ext.getAllTextFromElement(dom_ext.getFirstChildNamed(at, "symbol")))
     coords = dom_ext.getFirstChildNamed(at, "coordinates")
     a.x = float(dom_ext.getAllTextFromElement(dom_ext.getFirstChildNamed(coords, "x")))
     a.y = float(dom_ext.getAllTextFromElement(dom_ext.getFirstChildNamed(coords, "y")))
     a.z = float(dom_ext.getAllTextFromElement(dom_ext.getFirstChildNamed(coords, "z")))
     a.show_hydrogens = int(a.name != "C")
     # charge
     chel = dom_ext.getFirstChildNamed(at, "charge")
     if chel:
         a.charge = int(dom_ext.getAllTextFromElement(chel))
     # multiplicity
     radical = dom_ext.getFirstChildNamed(at, "radical")
     if radical:
         a.multiplicity = 1 + int(dom_ext.getAllTextFromElement(radical))
     # remap of ids
     self._atom_id_remap[at.getAttribute("id")] = a
     return a
Ejemplo n.º 13
0
 def _read_bond(self, bo):
     b = bond(self.paper)
     b.order = gtml_to_bkchem_bond_order_remap.index(dom_ext.getAllTextFromElement(xpath.Evaluate("bond", bo)[0]))
     ids = [i.nodeValue for i in xpath.Evaluate("end/@idref", bo)]
     b.atoms = [self._atom_id_remap[i] for i in ids]
     return b
Ejemplo n.º 14
0
 def _get_text(self):
     doc = dom.parseString(ftext.ftext.sanitize_text(self.xml_ftext))
     return dom_extensions.getAllTextFromElement(doc)
Ejemplo n.º 15
0
  def get_molecules( self, file_name):
    doc = dom.parse( file_name)
    molecules = []
    # read colors
    colors=[]
    for elem7 in doc.getElementsByTagName("color"):
      red=(float(elem7.getAttribute("r"))*255)
      green=(float(elem7.getAttribute("g"))*255)
      blue=(float(elem7.getAttribute("b"))*255)
      colors.append("#%02x%02x%02x" % (red,green,blue))

    # read fonts
    fonts={}
    for elem8 in doc.getElementsByTagName("font"):
      family=str(elem8.getAttribute("name"))
      fonts[int(elem8.getAttribute("id"))]=family

    # read molecules
    for elem1 in doc.getElementsByTagName("fragment"):
      if elem1.parentNode.nodeName=="page":
        mol = molecule( paper=self.paper)
        atom_id_to_atom = {}
        atom_id_to_text = {}
        for elem2 in elem1.childNodes:

          # atom
          if elem2.nodeName=="n":
            font = ""
            Size = 12
            text = "C"
            color1="#000000"
            for elem3 in elem2.childNodes:
              if elem3.nodeName=="t":
                if elem3.hasAttribute("color"):
                  color1=colors[int(elem3.getAttribute("color"))-2]
                text = ""
                for elem4 in elem3.childNodes:
                  if elem4.nodeName=="s":
                    if elem3.hasAttribute("color"):
                      color1=colors[int(elem3.getAttribute("color"))-2]
                    for Id, Font in fonts.items():
                      if Id==int(elem4.getAttribute("font")):
                        font=Font
                    Size= int(elem4.getAttribute("size"))
                    text += dom_ext.getAllTextFromElement( elem4).strip()

            position = elem2.getAttribute("p").split()
            assert len( position) == 2


            # we must postpone symbol assignment until we know the valency of the atoms
            atom_id_to_text[ elem2.getAttribute('id')] = text
            atom = mol.create_vertex()
            atom.line_color = color1
            atom.font_family = font
            atom.font_size = Size
            atom.x = float( position[0])
            atom.y = float( position[1])
            mol.add_vertex( atom)
            atom_id_to_atom[ elem2.getAttribute('id')] = atom

          # bond
          #{"v BKChemu bond.type":"v ChemDraw hodnota atributu Display elementu b"}
          bondType2={"WedgeBegin":"w",
          "WedgedHashBegin":"h",
          "Wavy":"a",
          "Bold":"b",
          "Dash":"d"
          }

          if elem2.nodeName=="b":
            if elem2.hasAttribute("color"):
              color2 = colors[(int(elem2.getAttribute("color"))-2)]
            else:
              color2="#000000"
            order = 1
            if elem2.hasAttribute("Order"):
              order = int( elem2.getAttribute("Order"))
            bond = mol.create_edge()
            if elem2.hasAttribute("Display"):
              display = elem2.getAttribute("Display").strip()
              for bondC, bondB in bondType2.items():
                if bondC ==display:
                  bond.type = bondB
            bond.line_color = color2
            bond.order = order
            atom1 = atom_id_to_atom[ elem2.getAttribute("B")]
            atom2 = atom_id_to_atom[ elem2.getAttribute("E")]
            mol.add_edge( atom1, atom2, bond)

        # here we reassign the symbols
        for id, atom in atom_id_to_atom.items():
          text = atom_id_to_text[ id]
          v = mol.create_vertex_according_to_text( atom, text)
          atom.copy_settings( v)
          mol.replace_vertices( atom, v)
          atom.delete()
        # finally we add the molecule to the list of molecules for output
        molecules.append( mol)

    # read texts
    textik={2:"i",
            1:"b",
            32:"sub",
            64:"sup"}

    for elem5 in doc.getElementsByTagName("t"):
      if elem5.parentNode.nodeName=="page":
        position = map( float, elem5.getAttribute("p").split())
        assert len( position) == 2
        celyText=""
        for elem51 in elem5.childNodes:
          if elem51.nodeName=="s":
            for elem52 in elem51.childNodes:
              if isinstance( elem52, dom.Text):
                rodice=[]
                text100=elem52.data
                if elem51.hasAttribute("face"):
                  Face01=int(elem51.getAttribute("face"))
                  for face, parent in textik.items():
                    for i in range(9):
                      if not Face01&2**i==0:
                        if face==Face01&2**i:
                          rodice.append(parent)
                for rodic in rodice:
                  text100 = "<%s>%s</%s>" % (rodic,text100,rodic)
            celyText += text100

            if elem5.hasAttribute("color"):
              color3=colors[(int(elem5.getAttribute("color"))-2)]
            else:
              color3="#000000"

            font_id = elem51.getAttribute("font")
            if font_id != "":
              font=fonts[int(font_id)]
            #text = dom_ext.getAllTextFromElement(elem51)
        #print celyText
        text = celyText
        t = text_class( self.paper, position, text=text)
        t.line_color = color3
        #print elem51
        if elem51.hasAttribute("size"):
          t.font_size = int( elem51.getAttribute("size"))
        if font:
          t.font_family = font
        molecules.append(t)

    # read graphics - plus
    for elem6 in doc.getElementsByTagName("graphic"):
      if elem6.getAttribute("GraphicType")=="Symbol" and elem6.getAttribute("SymbolType")=="Plus":
        position = map( float, elem6.getAttribute("BoundingBox").split())
        position2=[position[0],position[1]]
        assert len(position2) == 2
        if elem6.hasAttribute("color"):
          color4=colors[(int(elem6.getAttribute("color"))-2)]
        else:
          color4="#000000"
        pl = plus(self.paper, position2)
        pl.line_color = color4
        molecules.append(pl)

    sipka=[]
    #for elem71 in doc.getElementsByTagName("graphic"):
      #if elem71.getAttribute("GraphicType")=="Line":

    for elem7 in doc.getElementsByTagName("arrow"):
      sipka.insert(0,elem7.getAttribute('Head3D') )
      sipka.insert(1,elem7.getAttribute('Tail3D') )
      if elem7.hasAttribute("color"):
        sipka.insert(0,colors[(int(elem7.getAttribute("color"))-2)])
      point1 = map( float, sipka[1].split())
      point2 = map( float, sipka[2].split())
      arr = arrow( self.paper, points=[point2[0:2],point1[0:2]], fill=sipka[0])
      arr.line_color=sipka[0]
      molecules.append( arr)

    sipka=[]
    return molecules
Ejemplo n.º 16
0
    def get_molecules(self, file_name):
        doc = dom.parse(file_name)
        molecules = []
        # read colors
        colors = []
        for elem7 in doc.getElementsByTagName("color"):
            red = (float(elem7.getAttribute("r")) * 255)
            green = (float(elem7.getAttribute("g")) * 255)
            blue = (float(elem7.getAttribute("b")) * 255)
            colors.append("#%02x%02x%02x" % (red, green, blue))

        # read fonts
        fonts = {}
        for elem8 in doc.getElementsByTagName("font"):
            family = str(elem8.getAttribute("name"))
            fonts[int(elem8.getAttribute("id"))] = family

        # read molecules
        for elem1 in doc.getElementsByTagName("fragment"):
            if elem1.parentNode.nodeName == "page":
                mol = molecule(paper=self.paper)
                atom_id_to_atom = {}
                atom_id_to_text = {}
                for elem2 in elem1.childNodes:

                    # atom
                    if elem2.nodeName == "n":
                        font = ""
                        Size = 12
                        text = "C"
                        color1 = "#000000"
                        for elem3 in elem2.childNodes:
                            if elem3.nodeName == "t":
                                if elem3.hasAttribute("color"):
                                    color1 = colors[
                                        int(elem3.getAttribute("color")) - 2]
                                text = ""
                                for elem4 in elem3.childNodes:
                                    if elem4.nodeName == "s":
                                        if elem3.hasAttribute("color"):
                                            color1 = colors[int(
                                                elem3.getAttribute("color")) -
                                                            2]
                                        for Id, Font in fonts.items():
                                            if Id == int(
                                                    elem4.getAttribute(
                                                        "font")):
                                                font = Font
                                        Size = int(elem4.getAttribute("size"))
                                        text += dom_ext.getAllTextFromElement(
                                            elem4).strip()

                        position = elem2.getAttribute("p").split()
                        assert len(position) == 2

                        # we must postpone symbol assignment until we know the valency of the atoms
                        atom_id_to_text[elem2.getAttribute('id')] = text
                        atom = mol.create_vertex()
                        atom.line_color = color1
                        atom.font_family = font
                        atom.font_size = Size
                        atom.x = float(position[0])
                        atom.y = float(position[1])
                        mol.add_vertex(atom)
                        atom_id_to_atom[elem2.getAttribute('id')] = atom

                    # bond
                    #{"v BKChemu bond.type":"v ChemDraw hodnota atributu Display elementu b"}
                    bondType2 = {
                        "WedgeBegin": "w",
                        "WedgedHashBegin": "h",
                        "Wavy": "a",
                        "Bold": "b",
                        "Dash": "d"
                    }

                    if elem2.nodeName == "b":
                        if elem2.hasAttribute("color"):
                            color2 = colors[(int(elem2.getAttribute("color")) -
                                             2)]
                        else:
                            color2 = "#000000"
                        order = 1
                        if elem2.hasAttribute("Order"):
                            order = int(elem2.getAttribute("Order"))
                        bond = mol.create_edge()
                        if elem2.hasAttribute("Display"):
                            display = elem2.getAttribute("Display").strip()
                            for bondC, bondB in bondType2.items():
                                if bondC == display:
                                    bond.type = bondB
                        bond.line_color = color2
                        bond.order = order
                        atom1 = atom_id_to_atom[elem2.getAttribute("B")]
                        atom2 = atom_id_to_atom[elem2.getAttribute("E")]
                        mol.add_edge(atom1, atom2, bond)

                # here we reassign the symbols
                for id, atom in atom_id_to_atom.items():
                    text = atom_id_to_text[id]
                    v = mol.create_vertex_according_to_text(atom, text)
                    atom.copy_settings(v)
                    mol.replace_vertices(atom, v)
                    atom.delete()
                # finally we add the molecule to the list of molecules for output
                molecules.append(mol)

        # read texts
        textik = {2: "i", 1: "b", 32: "sub", 64: "sup"}

        for elem5 in doc.getElementsByTagName("t"):
            if elem5.parentNode.nodeName == "page":
                position = map(float, elem5.getAttribute("p").split())
                assert len(position) == 2
                celyText = ""
                for elem51 in elem5.childNodes:
                    if elem51.nodeName == "s":
                        for elem52 in elem51.childNodes:
                            if isinstance(elem52, dom.Text):
                                rodice = []
                                text100 = elem52.data
                                if elem51.hasAttribute("face"):
                                    Face01 = int(elem51.getAttribute("face"))
                                    for face, parent in textik.items():
                                        for i in range(9):
                                            if not Face01 & 2**i == 0:
                                                if face == Face01 & 2**i:
                                                    rodice.append(parent)
                                for rodic in rodice:
                                    text100 = "<%s>%s</%s>" % (rodic, text100,
                                                               rodic)
                        celyText += text100

                        if elem5.hasAttribute("color"):
                            color3 = colors[(int(elem5.getAttribute("color")) -
                                             2)]
                        else:
                            color3 = "#000000"

                        font_id = elem51.getAttribute("font")
                        if font_id != "":
                            font = fonts[int(font_id)]
                        #text = dom_ext.getAllTextFromElement(elem51)
                #print celyText
                text = celyText
                t = text_class(self.paper, position, text=text)
                t.line_color = color3
                #print elem51
                if elem51.hasAttribute("size"):
                    t.font_size = int(elem51.getAttribute("size"))
                if font:
                    t.font_family = font
                molecules.append(t)

        # read graphics - plus
        for elem6 in doc.getElementsByTagName("graphic"):
            if elem6.getAttribute(
                    "GraphicType") == "Symbol" and elem6.getAttribute(
                        "SymbolType") == "Plus":
                position = map(float,
                               elem6.getAttribute("BoundingBox").split())
                position2 = [position[0], position[1]]
                assert len(position2) == 2
                if elem6.hasAttribute("color"):
                    color4 = colors[(int(elem6.getAttribute("color")) - 2)]
                else:
                    color4 = "#000000"
                pl = plus(self.paper, position2)
                pl.line_color = color4
                molecules.append(pl)

        sipka = []
        #for elem71 in doc.getElementsByTagName("graphic"):
        #if elem71.getAttribute("GraphicType")=="Line":

        for elem7 in doc.getElementsByTagName("arrow"):
            sipka.insert(0, elem7.getAttribute('Head3D'))
            sipka.insert(1, elem7.getAttribute('Tail3D'))
            if elem7.hasAttribute("color"):
                sipka.insert(0, colors[(int(elem7.getAttribute("color")) - 2)])
            point1 = map(float, sipka[1].split())
            point2 = map(float, sipka[2].split())
            arr = arrow(self.paper,
                        points=[point2[0:2], point1[0:2]],
                        fill=sipka[0])
            arr.line_color = sipka[0]
            molecules.append(arr)

        sipka = []
        return molecules
Ejemplo n.º 17
0
 def _get_text( self):
   doc = dom.parseString( ftext.ftext.sanitize_text( self.xml_ftext))
   return dom_extensions.getAllTextFromElement( doc)