Logo Search packages:      
Sourcecode: edubuntu-menueditor version File versions  Download package

FileWriter.py

# -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 <Marc Gariépy> <mgariepy@revolutionlinux.com> Révolution Linux
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3  or (at your option)
#any later version, as published by the Free Software Foundation.
#
#This program is distributed in the hope that it will be useful, but
#WITHOUT ANY WARRANTY; without even the implied warranties of
#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
#PURPOSE.  See the GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License along
#with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE

import os
import tempfile
from menueditor import MenuTreeModel

class FileWriter():
    def __init__(self, menu_tree_model, filename):
        self.model = menu_tree_model
        self.tmp_dir = tempfile.mkdtemp()
        self.create_tree()
        self.sync()
        self.create_tar_gz(self.tmp_dir,filename)
        self.cleanup_tmp_dir()

    def append_menu (self, contents, indent, iter, system_menu_file = None):
        has_changes = False
        orig_contents = contents

        contents += indent + "<Menu>\n"
        contents += indent + "  <Name>%s</Name>\n" % self.model[iter][self.model.COLUMN_NAME]

        #only if we are managing a directory. For the moment we do not manage new application
        user_added = self.model[iter][self.model.COLUMN_USER_ADDED]
        if user_added:
            contents += indent + "  <Directory>%s</Directory>\n" %  self.create_directory(self.model,iter)

        if system_menu_file:
            contents += indent + '  <MergeFile type="parent">%s</MergeFile>\n' % system_menu_file

        includes = []
        excludes = []

        child_iter = self.model.iter_children (iter)
        while child_iter:
            if self.model[child_iter][self.model.COLUMN_IS_ENTRY]:
                desktop_file_id = self.model[child_iter][self.model.COLUMN_ID]
                system_visible  = self.model[child_iter][self.model.COLUMN_SYSTEM_VISIBLE]
                user_visible    = self.model[child_iter][self.model.COLUMN_USER_VISIBLE]


                if not system_visible and user_visible:
                    includes.append (desktop_file_id)
                elif system_visible and not user_visible:
                    excludes.append (desktop_file_id)

            child_iter = self.model.iter_next (child_iter)

        if len (includes) > 0:
            contents += indent + "  <Include>\n"
            for desktop_file_id in includes:
                contents += indent + "    <Filename>%s</Filename>\n" % desktop_file_id
            contents += indent + "  </Include>\n"
            has_changes = True

        if len (excludes) > 0:
            contents += indent + "  <Exclude>\n"
            for desktop_file_id in excludes:
                contents += indent + "    <Filename>%s</Filename>\n" % desktop_file_id
            contents += indent + "  </Exclude>\n"
            has_changes = True

        child_iter = self.model.iter_children (iter)
        while child_iter:
            if not self.model[child_iter][self.model.COLUMN_IS_ENTRY]:
                (contents, subdir_has_changes) = self.append_menu (contents,
                                                                     indent + "  ",
                                                                     child_iter)
                if not has_changes:
                    has_changes = subdir_has_changes

            child_iter = self.model.iter_next (child_iter)

        if has_changes:
            return (contents + indent + "</Menu>\n", True)
        else:
            return (orig_contents, False)

    def cleanup_tmp_dir(self):
        """Cleanup a directory tree"""
        import shutil
        shutil.rmtree(self.tmp_dir)

    def create_tar_gz(self,directory,destination):
        """This function create a tar.gz file of the directory"""
        import tarfile
        if os.path.exists(destination):
            # We have user confirmation to overwrite.
            os.remove(destination)
        target = tarfile.TarFile.open(destination, "w:gz")
        target.add(directory,arcname=os.path.basename("."))
        target.close()
        return True

    def create_tree(self):
        """ create the tree containing the files.
        """
        dirs = ['xdg/menus/applications-merged','share/desktop-directories']
        for dir in dirs:
            try:
                os.makedirs(os.path.join(self.tmp_dir,dir))
            except OSError:
                pass

    def create_directory(self,model,iter):
        """This function create the .directory file for submenu."""
        # Create the string
        text = "[Desktop Entry]\n"
        text += "Name=" + model[iter][self.model.COLUMN_NAME] + "\n"
        text += "Comment=" + model[iter][self.model.COLUMN_COMMENT] + "\n"
        text += "Icon=" + model[iter][self.model.COLUMN_ICON_NAME] + "\n"
        text += "Type=Directory\n"

        file_dir = os.path.join(self.tmp_dir,"share/desktop-directories")
        file_name = model[iter][self.model.COLUMN_ID]

        if not os.path.exists(os.path.join(file_dir,file_name+".directory")):
            name = os.path.join(file_dir,file_name+".directory")
        else:
            old_file = open(os.path.join(file_dir,file_name+".directory"))
            old_text = old_file.read()
            old_file.close()
            if old_text == text:
                return os.path.basename(os.path.join(file_dir,file_name+".directory"))
            else:
                i = 1
                while os.path.exists(os.path.join(file_dir,file_name+"_"+str(i)+".directory")):
                    i += 1
                name = os.path.join(file_dir,file_name+"_"+str(i)+".directory")

        file = open(name,'w')
        file.write(text)
        file.close()
        return os.path.basename(name)

    def sync (self):
        DTD_DECLARATION = '<!DOCTYPE Menu PUBLIC "-//freedesktop//DTD Menu 1.0//EN"\n' \
                          ' "http://www.freedesktop.org/standards/menu-spec/menu-1.0.dtd">\n'
        # get the first element
        iter = self.model.get_iter_first()
        while iter:
            menu_file = None
            menu_file = self.model.get_value(iter, self.model.COLUMN_MENU_FILE)
            system_file = None
            system_file = MenuTreeModel.lookup_system_menu_file(menu_file)

            if system_file:
                (contents, has_changes) = self.append_menu (DTD_DECLARATION, \
                                          "", iter, system_file)
                # if there are changes, write the file else, do nothing
                if has_changes:
                    file  = open(os.path.join(self.tmp_dir, "xdg/menus", menu_file), 'w')
                    file.write(contents)
                    file.close()
            iter = self.model.iter_next(iter)


Generated by  Doxygen 1.6.0   Back to index