#!/usr/bin/perl -w
# (c) Copyright 2001-2003. CodeWeavers, Inc.
# ----------------------------------------------------------------------
# | Module:     cxassoc                                                |
# |                                                                    |
# | Purpose:    Query/Modify file associations                         |
# |                                                                    |
# | Functions:  main                                                   |
# |                                                                    |
# |             query_mailcap     set_mailcap     remove_mailcap       |
# |             query_kde         set_kde         remove_kde           |
# |             query_gnome       set_gnome       remove_gnome         |
# |                                                                    |
# |                                                                    |
# ----------------------------------------------------------------------
use strict;

use IO::File;

my $name0=$0;
$name0 =~ s+^.*/++;

$main::productid="cxoffice";
$main::productname="CrossOver Office";
$main::productpkg="local.CrossOver_Office";


# Portable which(1) implementation
use Cwd;
sub cxwhich($$)
{
    my $path=$_[0];
    my $app=$_[1];
    if ($app =~ /^\//)
    {
        return $app if (-x $app);
    }
    elsif ($app =~ /\//)
    {
        my $path=cwd . "/$app";
        return $path if (-x $path);
    }
    else
    {
        foreach my $dir (split /:/, $path)
        {
            return "$dir/$app" if ($dir ne "" and -x "$dir/$app");
        }
    }
    return undef;
}

# Locate where CrossOver is installed by looking for the directory
# where this this script is located, unwinding symlinks on the way
my $cx_root;
use File::Basename;
sub locate_cx_root()
{
    return $cx_root if (defined $cx_root);
    $cx_root=$ENV{"CX_ROOT"};
    if (!defined $cx_root)
    {
        my $argv0=cxwhich($ENV{"PATH"},$0);
        $argv0=$0 if (!defined $argv0);
        if ($argv0 =~ m+^[^/]+)
        {
            $argv0=cwd() . "/$argv0";
        }
        my $dir=dirname($argv0);
        while (!-x "$dir/cxtcl")
        {
            last if (!-l $argv0);
            $argv0=readlink($argv0);
            $argv0="$dir/$argv0" if ($argv0 =~ m+^[^/]+);
            $dir=dirname($argv0);
        }
        $dir =~ s%(/\.)*$%%;
        $dir =~ s%(/\./(\./)*)%/%;
        $cx_root=dirname($dir);
    }
    if (!-x "$cx_root/bin/cxtcl")
    {
        my $name0=$0;
        $name0 =~ s+^.*/++;
        print STDERR "$name0:error: could not find CrossOver in \"$cx_root\"\n";
        exit 1;
    }
    $ENV{"CX_ROOT"}=$cx_root;
    return $cx_root;
}

# Include our modules
BEGIN {
    push @INC, locate_cx_root() . "/lib/perl";
}
use CXLog;
use CXAssocNS;
use CXAssocGnome;
use CXAssocKDE;
use CXAssocCDE;


# --------------------------------------------------------------
# | Globals                                                    |
# --------------------------------------------------------------
%main::gui_info = ();


# ----------------------------------------------------------------------
# | main                                                               |
# |                                                                    |
# |                                                                    |
# |                                                                    |
# ----------------------------------------------------------------------
{
    # Locals
    my  ($input_file);
    my  $global = 0;
    my  $fh;
    my  ($cmd, @cmd_list);
    my  ($k, $v);
    my  $s;
    my  ($func, $func_tab);
    my  $locate_gui_script;
    my  $r;


    # --------------------------------------------------------------
    # | Parse args                                                 |
    # --------------------------------------------------------------
    my $usage;
    while (@ARGV > 0)
    {
        my $arg = shift @ARGV;
        if ($arg eq "--input-file" or $arg eq "--fn")
        {
            if (defined $input_file)
            {
                print STDERR "$name0:error: $arg can only be specified once\n";
                $usage = 1;
                last;
            }
            if (! @ARGV)
            {
                print STDERR "$name0:error: missing argument for $arg\n";
                $usage = 1;
                last;
            }
            $input_file = shift @ARGV;
        }
        elsif ($arg eq "--global")
        {
            $global = 1;
            shift @ARGV;
        }
        elsif ($arg eq "-?" or $arg eq "-h" or $arg eq "--help")
        {
            $usage = 2;
        }
        else
        {
            print STDERR "$name0:error: unknown option $arg\n";
            $usage = 1;
            last;
        }
    }
    if ($usage)
    {
        print STDERR "Usage: $name0 [--help] [--input-file filename] [--global]\n";
        exit $usage;
    }


    # --------------------------------------------------------------
    # | Get input source                                           |
    # --------------------------------------------------------------
    if (defined $input_file)
    {
        $fh = IO::File->new($input_file) or die "Can't open input [$input_file]";
    }
    else
    {
        $fh = IO::File->new;
        $fh->fdopen(fileno(STDIN), "r");
    }

    # --------------------------------------------------------------
    # | Run script that will tell us everything we want to know    |
    # | about where KDE/Gnome/Netscape stuff is located; get path  |
    # | to it from $0                                              |
    # --------------------------------------------------------------
    $locate_gui_script = "$cx_root/bin/locate_gui.sh";
    if (-f $locate_gui_script)
    {
        foreach (`"$locate_gui_script" --mime`)
        {
            chomp;
            ($k, $v) = split /\s*=\s*/;
            $main::gui_info{$k} = $v;
        }
    }
    else
    {
        die "Can't find [$locate_gui_script]";
    }

    # --------------------------------------------------------------
    # | Process input lines                                        |
    # --------------------------------------------------------------
    @cmd_list = ();
    $cmd = undef;
    while (<$fh>)
    {
        chomp;
        s/#.*$//;
        s/^\s*//;
        next if (/^\s*$/);

        # --------------------------------------------------------------
        # | Extract key and val                                        |
        # --------------------------------------------------------------
        ($k, $v) = split /\s*=\s*/;

        # --------------------------------------------------------------
        # | The split() above already will pull trailing spaces off $k |
        # | and leading spaces off $v.  Now pull leading spaces off $k |
        # | $k and trailing spaces off $v ...                          |
        # --------------------------------------------------------------
        $k =~ s/^\s*//;
        $v =~ s/\s*$//;

        # --------------------------------------------------------------
        # | New command                                                |
        # --------------------------------------------------------------
        if ($k =~ /^(query|set|remove|removeall)$/)
        {
            (defined $cmd) && push @cmd_list, $cmd;
            undef $cmd;
            $cmd->{cmd} = $k;
            $cmd->{a}   = [ split /\s*,\s*/, $v ];
        }

        # --------------------------------------------------------------
        # | Other keys                                                 |
        # --------------------------------------------------------------
        elsif ($k =~ /^(mime-type|extensions|document-type|app-name|command|icon)/)
        {
            $cmd->{$k} = $v;
        }
    }
    (defined $cmd) && push @cmd_list, $cmd;

    # --------------------------------------------------------------
    # | Set up table of function pointers                          |
    # --------------------------------------------------------------
    my  $fnc_tab =
    {
        query_mailcap      => \&query_mailcap,
        query_kde          => \&query_kde,
        query_gnome        => \&query_gnome,
        query_cde          => \&query_cde,

        set_mailcap        => \&set_mailcap,
        set_kde            => \&set_kde,
        set_gnome          => \&set_gnome,
        set_cde            => \&set_cde,

        remove_mailcap     => \&remove_mailcap,
        remove_kde         => \&remove_kde,
        remove_gnome       => \&remove_gnome,
        remove_cde         => \&remove_cde,

        removeall_mailcap  => \&removeall_mailcap,
        removeall_kde      => \&removeall_kde,
        removeall_gnome    => \&removeall_gnome,
        removeall_cde      => \&removeall_cde,
    };

    # --------------------------------------------------------------
    # | Run commands                                               |
    # --------------------------------------------------------------
    foreach (@cmd_list)
    {
        $cmd = $_;
        next
            unless (grep { $cmd->{cmd} eq $_ } qw(query set remove removeall));

        # --------------------------------------------------------------
        # | Need to print header for query command                     |
        # --------------------------------------------------------------
        if ($cmd->{cmd} eq 'query')
        {
            printf "mime-type=%s\n",     $cmd->{"mime-type"};
        }

        # --------------------------------------------------------------
        # | Run command for each system                                |
        # --------------------------------------------------------------
        foreach (@{$cmd->{a}})
        {
            $s = $_;
            if (grep { $s eq $_ } qw(mailcap kde gnome cde))
            {
                $r = &{$fnc_tab->{$cmd->{cmd} . "_" . $s}}
                (
                    $cmd->{"mime-type"},
                    $cmd->{"extensions"},
                    $cmd->{"document-type"},
                    $cmd->{"app-name"},
                    $cmd->{"command"},
                    $cmd->{"icon"},
                    $global
                );
                print "$s=$r\n"
                    if ($cmd->{cmd} eq "query");
            }
        }
        printf "==========\n"
            if ($cmd->{cmd} eq "query");

    }
}

sub n_command_match($$$)
{
    my $ref=$_[0];
    my $wrappers=$_[1];
    my $cmd=$_[2];

    $ref=~s%(~W[BS]~|:switch:|/|\\)%/%g;
    $cmd=~s%(~W[BS]~|:switch:|/|\\)%/%g;
    $cmd=~s%\"\%s\"$%\'\%s\'%g;
    return (defined $cmd and
            ($cmd =~ /^\Q$ref\E(\s+(\"?)%[0-9lL]\2)?(\s+\'\%s\')?$/ or
             $wrappers->{$cmd}));
}

sub kg_command_match($$)
{
    my $ref=$_[0];
    my $cmd=$_[1];

    $ref=~s%(~W[BS]~|:switch:|/|\\)%/%g;
    $cmd=~s%(~W[BS]~|:switch:|/|\\)%/%g;
    return (defined $cmd and $cmd =~ /^\Q$ref\E(\s+(\"?)%[0-9lL]\2)?$/);
}

sub qglob($$)
{
    my $dir=$_[0];
    my $filter=$_[1];
    my @r=();
    local *DIR;
    if (opendir(*DIR,$dir))
    {
        if ($filter)
        {
            @r=grep /$filter/, readdir(*DIR);
        }
        else
        {
            @r=readdir(*DIR);
        }
    }
    closedir(*DIR);
    return map { "$dir/$_" } @r;
}

exit 0;


# ----------------------------------------------------------------------
# | === Netscape functions ===                                         |
# |                                                                    |
# |                                                                    |
# ----------------------------------------------------------------------




# ----------------------------------------------------------------------
# | Sub:      query_mailcap                                            |
# |                                                                    |
# | Purpose:  Determine whether this association is set in the mailcap |
# |           file.                                                    |
# |                                                                    |
# | Usage:    query_mailcap                                            |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  1 if association exists, 0 if not                        |
# ----------------------------------------------------------------------
sub query_mailcap($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;
    my  $r=0;


    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return 0
        unless ($main::gui_info{mailcap_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[query_mailcap]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    global        [$global]\n");

    # Get a list of possible wrappers
    my $wrappers=n_get_wrappers($command,$global);

    # --------------------------------------------------------------
    # | Check whether an association between the given mime-type   |
    # | and command exists in the mailcap file                     |
    # --------------------------------------------------------------
    my $blobs = n_read_mailcap($global);
    foreach my $blob (@$blobs)
    {
        my $mime=n_mime_type($blob);
        my $cmd=n_command($blob);
        if (defined $mime and $mime eq $mime_type and
            n_command_match($command,$wrappers,$cmd))
        {
            $r=1;
            last;
        }
    }

    cxlog("[query_mailcap] -> [$r]\n");
    return $r;
}


# ----------------------------------------------------------------------
# | Sub:      set_mailcap                                              |
# |                                                                    |
# | Purpose:  Set association in the mailcap file.                     |
# |                                                                    |
# | Usage:    set_mailcap                                              |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub set_mailcap($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;
    my  ($blob);

    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return
        unless ($main::gui_info{mailcap_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[set_mailcap]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");


    # Get a list of possible wrappers
    my $wrappers=n_get_wrappers($command,$global);

    # --------------------------------------------------------------
    # | mailcap                                                    |
    # |                                                            |
    # |     1) read in file                                        |
    # |     2) add entry for mime-type at end                      |
    # |     3) write back out                                      |
    # --------------------------------------------------------------
    my $mcap = n_read_mailcap($global);
    undef $blob;
    foreach my $item (@$mcap)
    {
        my $mime=n_mime_type($item);
        if (defined $mime and $mime eq $mime_type)
        {
            $blob = $item;
            last;
        }
    }
    if (!defined $blob)
    {
        my $cmd=n_wrap_command($command,$global);
        push @$mcap, {
                      file => "mailcap",
                      type => "entry",
                      raw  => [
                               "$mime_type;$cmd; \\",
                               "    description=\"$app_name\"; \\",
                               "    x-$main::productid"
                              ]
                     };
        n_write_mailcap($mcap,1,$global);
    }
    else
    {
        my $cmd=n_command($blob);
        if (!n_command_match($command,$wrappers,$cmd))
        {
            $cmd=n_wrap_command($command,$global);
            $blob->{type}="entry";
            $blob->{raw}=[
                          "$mime_type;$cmd; \\",
                          "    description=\"$app_name\"; \\",
                          "    x-$main::productid"
                         ];
            n_write_mailcap($mcap,1,$global);
        }
    }

    # --------------------------------------------------------------
    # | mime.types                                                 |
    # |                                                            |
    # |     1) read in file                                        |
    # |     2) add entry for mime-type at end                      |
    # |     3) write back out                                      |
    # |                                                            |
    # | Netscape appears to only grok the exts= keyword if it's    |
    # | the last keyword in the blob.  I very much think that this |
    # | is not reasonable, possibly a bug in Netscape.  Anyway,    |
    # | it happens that when we read in blobs from the file, we    |
    # | preserve the order of the keywords.  So if a blob starts   |
    # | life out that way, it'll stay that way.  Here, we're       |
    # | creating a new blob.  So we need to make sure we write     |
    # | the exts= keyword out last ...                             |
    # --------------------------------------------------------------
    my $mtype = n_read_mime_types($global);
    undef $blob;
    foreach my $item (@$mtype)
    {
        my $mime=n_mime_type($item);
        if (defined $mime and $mime eq $mime_type)
        {
            $blob = $item;
            last;
        }
    }
    if (!defined $blob)
    {
        push @$mtype, {
                       file          => "mime_types",
                       type          => "simple",
                       mime_type     => "$mime_type",
                       document_type => "$document_type",
                       extensions    => [split /\s*,\s*/, $extensions]
                      };
        n_write_mime_types($mtype,1,$global);
    }

    return;
}


# ----------------------------------------------------------------------
# | Sub:      remove_mailcap                                           |
# |                                                                    |
# | Purpose:  Remove association from the mailcap file.                |
# |                                                                    |
# | Usage:    remove_mailcap                                           |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub remove_mailcap($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;
    my  ($mcap, $mtype);
    my  ($i, $mime_refs, $removed);
    my  $blob;


    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return
        unless ($main::gui_info{mailcap_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[remove_mailcap]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");


    # Get a list of possible wrappers
    my $wrappers=n_get_wrappers($command,$global);

    # --------------------------------------------------------------
    # | mailcap                                                    |
    # |                                                            |
    # |     1) read in file                                        |
    # |     2) remove our entry, if present                        |
    # |     3) write back out                                      |
    # --------------------------------------------------------------
    $mime_refs=0;
    $removed=0;
    $mcap = n_read_mailcap($global);
    if (defined $mcap)
    {
        $i=0;
        while ($i < @$mcap)
        {
            $blob = @$mcap[$i++];
            my $mime=n_mime_type($blob);
            if (defined $mime and $mime eq $mime_type)
            {
                $mime_refs++;
                my $cmd=n_command($blob);
                if (n_command_match($command,$wrappers,$cmd) and
                    n_is_crossover($blob))
                {
                    $i--;
                    splice @$mcap, $i, 1;
                    if ($wrappers->{$cmd})
                    {
                        $cmd =~ s/\s+"%s"$//;
                        unlink $cmd;
                    }
                    $removed++;
                }
            }
        }
        n_write_mailcap($mcap,1,$global) if ($removed>0);
    }

    # --------------------------------------------------------------
    # | mime.types                                                 |
    # |                                                            |
    # | This MIME type is no longer used, remove it                |
    # |     1) read in file                                        |
    # |     2) remove our entry(s), if present                     |
    # |     3) write back out                                      |
    # --------------------------------------------------------------
    if ($mime_refs<=$removed)
    {
        $mtype = n_read_mime_types($global);
        if (defined $mtype)
        {
            $removed=0;
            $i=0;
            while ($i < @$mtype)
            {
                $blob = @$mtype[$i++];
                if ((n_mime_type($blob) eq $mime_type) and
                    n_is_crossover($blob))
                {
                    $i--;
                    splice @$mtype, $i, 1;
                    $removed++;
                }
            }
            n_write_mime_types($mtype,1,$global) if ($removed>0);
        }
    }

    return;
}


# ----------------------------------------------------------------------
# | Sub:      removeall_mailcap                                        |
# |                                                                    |
# | Purpose:  Remove all Mailcap associations                          |
# |                                                                    |
# | Usage:    removeall_mailcap                                        |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub removeall_mailcap($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return
        unless ($main::gui_info{mailcap_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[removeall_mailcap]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");


    n_remove_all($global);
    return;
}




# ----------------------------------------------------------------------
# | === KDE functions ===                                              |
# |                                                                    |
# |                                                                    |
# ----------------------------------------------------------------------




# ----------------------------------------------------------------------
# | Sub:      query_kde                                                |
# |                                                                    |
# | Purpose:  Determine whether association is set up for kde          |
# |                                                                    |
# | Usage:    query_kde                                                |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  1 if association exists, 0 if not                        |
# ----------------------------------------------------------------------
sub query_kde($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;


    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return 0
        unless ($main::gui_info{kde_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[query_kde]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    global        [$global]\n");

    # --------------------------------------------------------------
    # | Determine locations                                        |
    # --------------------------------------------------------------
    my $menu_dir =
    (
        $global ?
        $main::gui_info{kde_global_menu} :
        $main::gui_info{kde_preferred_menu}
    );


    # --------------------------------------------------------------
    # | [applnk]                                                   |
    # --------------------------------------------------------------
    my $r = 0;
    my $filter = "^$main::productid-app-\\d{5}\\.desktop\$";
    foreach my $fn (qglob($menu_dir,$filter), qglob("$menu_dir/CrossOver",$filter))
    {
        my $blob = k_read_file($fn);
        if (kg_command_match($command,$blob->{Exec}) and
            defined $blob->{MimeType} and
            grep(/\Q$mime_type\E/, split(";", $blob->{MimeType}))
           )
        {
            $r = 1;
            last;
        }
    }

    cxlog("[query_kde] -> [$r]\n");
    return $r;
}


# ----------------------------------------------------------------------
# | Sub:      set_kde                                                  |
# |                                                                    |
# | Purpose:  Set association for kde                                  |
# |                                                                    |
# | Usage:    set_kde                                                  |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub set_kde($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    my  @args;
    my  (%ext_assoc, @ext_list);
    my  $blob;
    my  $app_dir;

    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return
        unless ($main::gui_info{kde_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[set_kde]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");

    # --------------------------------------------------------------
    # | Determine locations                                        |
    # --------------------------------------------------------------
    my $mime_dir = 
    (
        $global ?
        $main::gui_info{kde_global_mime} :
        $main::gui_info{kde_preferred_mime}
    );
    my $menu_dir =
    (
        $global ?
        $main::gui_info{kde_global_menu} :
        $main::gui_info{kde_preferred_menu}
    );
    my $debian_menu_dir =
    (
        $global ?
        $main::gui_info{debian_global_menu} :
        $main::gui_info{debian_preferred_menu}
    );

    # --------------------------------------------------------------
    # | We're given a list of extensions.  First, we need to find  |
    # | out what mime type (if any) each is associated with ...    |
    # --------------------------------------------------------------
    # KDE 3.1 treats extensions as case-sensitive so we double all of them
    @args = split ",", $extensions;
    $extensions=~ tr/a-z/A-Z/;
    push @args, split ",", $extensions;
    my $ext_to_mime=k_mime_from_ext(\@args);

    # Logging
    cxlog("Pre-existing extensions/MIME types:\n");
    map { cxlog("    $_ -> [", join(",",keys %{$ext_to_mime->{$_}}, "]\n")) } keys (%$ext_to_mime);


    # Build a list of the extensions that are not yet associated to a
    # MIME type
    # And a list of all the MIME types we found
    my %missing_exts;
    my %mime_list;
    $mime_list{$mime_type}=1;
    foreach my $ext (@args)
    {
        my $mimes=$ext_to_mime->{$ext};
        if (defined $mimes)
        {
            foreach my $mime (keys %$mimes)
            {
                $mime_list{$mime}=1;
            }
        }
        else
        {
            $missing_exts{$ext}=1;
        }
    }
    cxlog("Missing extensions: ",join(" ",keys %missing_exts),"\n");
    cxlog("Full MIME type list: ", join(" ",keys %mime_list),"\n");

    if (%missing_exts)
    {
        # Create a .desktop file with our MIME type and
        # the missing extensions.

        my $fn = "$mime_dir/$mime_type.desktop";
        my $blob = k_read_file($fn);

        if (!defined $blob->{MimeType})
        {
            # This is a new file, tag it.
            $blob->{MimeType}=$mime_type;
            $blob->{"X-Created-By"}=$main::productname;
        }
        else
        {
            # Make a backup of the original file
            system("cp",$fn,"$fn.bak") if (-f $fn && ! -f "$fn.bak");
        }
        if (defined $blob->{Patterns})
        {
            # Merge the existing extensions with ours
            foreach (split ";", $blob->{Patterns})
            {
                s/\*\.//;
                $missing_exts{$_}=1;
            }
        }
        $blob->{Patterns}=join(";",map { "*.$_"} sort keys %missing_exts);
        $blob->{Icon}=$icon if (defined $icon and $icon ne "");

        cxlog("Writing [$fn]\n");
        k_write_file($fn, $blob);
    }

    # --------------------------------------------------------------
    # | [applnk]                                                   |
    # --------------------------------------------------------------

    # --------------------------------------------------------------
    # | Create appropriate blob                                    |
    # --------------------------------------------------------------
    %{$blob} =
    (
        Comment           => "",
        Exec              => $command,
        Icon              => $icon,
        InitialPreference => "2",
        MimeType          => join(";", sort keys %mime_list),
        Name              => $app_name,
        ServiceTypes      => "",
        Terminal          => "false",
        Type              => "Application",
        NoDisplay         => "true"
    );

    # --------------------------------------------------------------
    # | Create dir, if it doesn't exist                            |
    # --------------------------------------------------------------
    $app_dir = "$menu_dir/CrossOver";
    mkdir ($app_dir,0755)
        unless (-d $app_dir);

    # --------------------------------------------------------------
    # | Create unique file name                                    |
    # --------------------------------------------------------------
    my @a = sort { $a cmp $b } qglob($app_dir,"^$main::productid-app-\\d{5}\\.desktop\$");
    my $n = ($global or $> == 0)?90000:0;
    if (@a > 0)
    {
        my $t = pop @a;
        $n=$1+1 if ($t =~ /$main::productid-app-(\d{5}).desktop/ and $1 >= $n);
    }
    my $fn = sprintf "$app_dir/$main::productid-app-%05d.desktop", $n;

    # --------------------------------------------------------------
    # | Write it out                                               |
    # --------------------------------------------------------------
    cxlog("Writing [$fn]\n");
    k_write_file($fn, $blob);


    # --------------------------------------------------------------
    # | And now once more for Mandrake                             |
    # --------------------------------------------------------------
    # We do not want to execute this code on Debian as it creates an
    # ugly '.hidden' menu entry for fvwm.
    if ($main::gui_info{debian_menu_on} && -d "/usr/share/applnk-mdk")
    {
        mkdir ($debian_menu_dir,0755) unless (-d $debian_menu_dir);

        my $menu_file="$debian_menu_dir/$main::productid";
        $command =~ s/\\/\\\\/g;
        $command =~ s/\"/\\\"/g;
        my $title=$app_name;
        $title =~ s/\\/\\\\/g;
        $title =~ s/\"/\\\"/;
        $mime_type=join(";", keys %mime_list);

        # Read the existing file
        my @lines=();
        if (open(FILEI,$menu_file))
        {
            @lines=<FILEI>;
            close FILEI;
        }

        # Check if we already have a matching line
        my $match;
        foreach (@lines)
        {
            next if (!/\ssection=\".hidden\"\s/);
            if (/\\\\nMimeType=$mime_type\\\\n/)
            {
                # Replace the existing line
                chomp;
                s/^.*\skde_filename=\"$main::productid-app-([^\"]*)\"\s.*$/$1/;
                $_="?package($main::productpkg): needs=\"x11\" kde_filename=\"$main::productid-app-$_\" section=\".hidden\" title=\"$title\" icon=\"$icon\" command=\"$command\" kde_opt=\"\\\\nTerminal=0\\\\nMimeType=$mime_type\\\\nInitialPreference=2\\\\nNoDisplay=true\"\n";
                $match=1;
                last;
            }
        }
        if (!defined $match)
        {
            # We have to add a new line
            # Find a suitable file number
            my @numbers=sort map { /\ssection=\".hidden\"\s/ && /^.*\skde_filename=\"$main::productid-app-([0-9]*)\"\s.*$/ ? $1 : () } @lines;
            $n = 0;
            if (@numbers)
            {
                while ($n < @numbers and $numbers[$n]==$n) { $n += 1; }
            }
            my $crossover_app=sprintf "$main::productid-app-%05d", $n;
            push @lines,"?package($main::productpkg): needs=\"x11\" kde_filename=\"$crossover_app\" section=\".hidden\" title=\"$title\" icon=\"$icon\" command=\"$command\" kde_opt=\"\\\\nTerminal=0\\\\nMimeType=$mime_type\\\\nInitialPreference=2\\\\nNoDisplay=true\"\n";
        }

        # Write the result
        if (open(FILEO,">$menu_file"))
        {
            foreach (@lines) { print FILEO; }
            close FILEO;
        }
	system("killall update-menus >/dev/null 2>&1");
        system("update-menus >/dev/null 2>&1");
    }

    return;
}


# ----------------------------------------------------------------------
# | Sub:      remove_kde                                               |
# |                                                                    |
# | Purpose:  Remove association for kde                               |
# |                                                                    |
# | Usage:    remove_kde                                               |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub remove_kde($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    my  $blob;

    return
        unless ($main::gui_info{kde_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[remove_kde]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");

    # --------------------------------------------------------------
    # | Determine locations                                        |
    # --------------------------------------------------------------
    my $mime_dir = 
    (
        $global ?
        $main::gui_info{kde_global_mime} :
        $main::gui_info{kde_preferred_mime}
    );
    my $menu_dir =
    (
        $global ?
        $main::gui_info{kde_global_menu} :
        $main::gui_info{kde_preferred_menu}
    );
    my $debian_menu_dir =
    (
        $global ?
        $main::gui_info{debian_global_menu} :
        $main::gui_info{debian_preferred_menu}
    );

    # --------------------------------------------------------------
    # | Remove mime file                                           |
    # --------------------------------------------------------------
    my $fn = "$mime_dir/$mime_type.desktop";
    if (-f $fn)
    {
        my $blob=k_read_file($fn);

        if ((defined $blob->{"X-Created-By"} and $blob->{"X-Created-By"} eq $main::productname) or -f "$fn.bak")
        {
            cxlog("Removing [$fn]\n");
            unlink $fn;
        }
        if (-f "$fn.bak")
        {
            # Restore the original file
            system("mv","$fn.bak",$fn);
        }
        else
        {
            # Or remove the directory if it is empty
            $fn =~ s+/[^/]*$++;
            rmdir $fn;
        }
    }

    # --------------------------------------------------------------
    # | Remove app file                                            |
    # --------------------------------------------------------------
    my $filter = "^$main::productid-app-\\d{5}\\.desktop\$";
    foreach (qglob($menu_dir,$filter), qglob("$menu_dir/CrossOver",$filter))
    {
        $fn = $_;
        $blob = k_read_file($fn);
        if (kg_command_match($command,$blob->{Exec}))
        {
            cxlog("Removing [$fn]\n");
            unlink $fn;
            last;
        }
    }

    # --------------------------------------------------------------
    # | And now once more for Mandrake                             |
    # --------------------------------------------------------------

    if ($main::gui_info{debian_menu_on} && -d $debian_menu_dir && -d "/usr/share/applnk-mdk")
    {
        my $menu_file="$debian_menu_dir/$main::productid";
        $command =~ s/\\/\\\\/g;
        $command =~ s/\"/\\\"/g;

        # Read the existing file
        my @lines=();
        if (open(FILEI,$menu_file))
        {
            @lines=<FILEI>;
            close FILEI;
        }

        # Rewrite the file omitting the entry we want to remove
        if (open(FILEO,">$menu_file"))
        {
            foreach (@lines)
            {
                next if (/\ssection=\".hidden\"\s/ && /\scommand=\"\Q$command\E(\s+(\\\"?)%[0-9lL]\2)?\"\s/);
                print FILEO;
            }
            close FILEO;
        }
        system("killall update-menus >/dev/null 2>&1");
        system("update-menus >/dev/null 2>&1");
    }

    return;
}


# ----------------------------------------------------------------------
# | Sub:      removeall_kde                                            |
# |                                                                    |
# | Purpose:  Remove all our KDE associations                          |
# |                                                                    |
# | Usage:    removeall_kde                                            |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub removeall_kde($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    my  $blob;

    return
        unless ($main::gui_info{kde_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[removeall_kde]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");


    # --------------------------------------------------------------
    # | Determine locations                                        |
    # --------------------------------------------------------------
    my $mime_dir =
    (
        $global ?
        $main::gui_info{kde_global_mime} :
        $main::gui_info{kde_preferred_mime}
    );
    my $menu_dir =
    (
        $global ?
        $main::gui_info{kde_global_menu} :
        $main::gui_info{kde_preferred_menu}
    );
    my $debian_menu_dir =
    (
        $global ?
        $main::gui_info{debian_global_menu} :
        $main::gui_info{debian_preferred_menu}
    );


    # --------------------------------------------------------------
    # | Remove mime files                                          |
    # --------------------------------------------------------------
    foreach my $dir (qglob($mime_dir,".*"))
    {
        next if ($dir =~ m+/\.\.?$+);
        foreach my $file (qglob($dir,"\\.desktop\$"))
        {
            my $blob=k_read_file($file);
            if (defined $blob->{"X-Created-By"} and $blob->{"X-Created-By"} eq $main::productname)
            {
                cxlog("Removing [$file]\n");
                unlink $file;
            }
            # Restore the original file
            system("mv","$file.bak",$file) if (-f "$file.bak");
        }
        # Try to remove the directory in case it is empty
        rmdir $dir;
    }

    # --------------------------------------------------------------
    # | Remove app file                                            |
    # --------------------------------------------------------------
    my $filter="^$main::productid-app-\\d+\\.desktop\$";
    foreach my $fn (qglob($menu_dir,$filter), qglob("$menu_dir/CrossOver",$filter))
    {
        cxlog("Removing [$fn]\n");
        unlink "$fn";
    }

    # --------------------------------------------------------------
    # | And now once more for Mandrake                             |
    # --------------------------------------------------------------
    if ($main::gui_info{debian_menu_on} && -d $debian_menu_dir && -d "/usr/share/applnk-mdk")
    {
        unlink("$debian_menu_dir/$main::productid");
        system("killall update-menus >/dev/null 2>&1");
        system("update-menus >/dev/null 2>&1");
    }

    return;
}




# ----------------------------------------------------------------------
# | === Gnome functions ===                                            |
# |                                                                    |
# |                                                                    |
# ----------------------------------------------------------------------

# In GNOME, associations between applications and MIME types are
# composed of three parts:
#
# * application-registry/*.applications
#   Each of these defines a list of applications, their requirements,
#   a description and what MIME types they can handle.
#   The latter lets the GNOME Control Center display a list of
#   'potential handlers' for each MIME type you click on.
#
# * mime-info/*.mime
#   Each of these defines a list of MIME types, i.e. their name and
#   which extensions (or file patterns) they correspond to. Note that
#   extensions and patterns can have priorities and that the fields
#   defining them can be duplicated.
#
# * mime-info/*.keys
#   Each of these defines the associations between a MIME type and an
#   ordered list of applications in decreasing priority order.
#   In addition to this it also provides descriptions for the MIME
#   types (what is this doing there?).

# ----------------------------------------------------------------------
# | Sub:      query_gnome                                              |
# |                                                                    |
# | Purpose:  Determine whether association is set up for gnome        |
# |                                                                    |
# | Usage:    query_gnome                                              |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  1 if association exists, 0 if not                        |
# ----------------------------------------------------------------------
sub query_gnome($$$$$$$)
{
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    # Sanity check
    return 0 unless ($main::gui_info{gnome_on});


    # Debug
    cxlog("\n[query_gnome]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    global        [$global]\n");

    # --------------------------------------------------------------
    # | Determine locations                                        |
    # --------------------------------------------------------------
    my $mime_dir = (
        $global ?
        $main::gui_info{gnome_global_mime} :
        $main::gui_info{gnome_preferred_mime}
    );
    my $application_dir = (
        $global ?
        $main::gui_info{gnome_global_application} :
        $main::gui_info{gnome_preferred_application}
    );

    # Read in *.applications files
    # In theory we should only have one app_id for our
    # application. However we are not quite sure where it will
    # be declared so we just read all files.
    my %app_ids;
    foreach my $apps_file (qglob($application_dir,"\\.applications\$"))
    {
        my $apps = g_read_file($apps_file);
        foreach my $blob (@$apps)
        {
            if (kg_command_match($command,g_get_key_val($blob, "command")))
            {
                cxlog("    application match: $blob->{label}\n");
                $app_ids{$blob->{label}}=1;
            }
        }
    }

    # If no application matches then we are done
    return 0 if (!%app_ids);

    # Otherwise we must check whether one of these is set as the
    # default application handler for the specified MIME type.
    # This will be in one of the *.keys files, usually either
    # user.keys or $productid.keys, but we are not really sure which
    # so we will just try them all.
    foreach my $keys_file (qglob($mime_dir,"\\.keys\$"))
    {
        my $keys = g_read_file($keys_file);
        foreach my $blob (@$keys)
        {
            my $app_id=g_get_key_val($blob, "default_application_id");
            if (!defined $app_id)
            {
                my $tmp=g_get_key_val($blob, "short_list_application_user_additions");
                if (defined $tmp)
                {
                    foreach (split /\s*,\s*/, $tmp)
                    {
                        if ($app_ids{$_})
                        {
                            $app_id=$_;
                            last;
                        }
                    }
                }
            }
            if (defined $app_id and $app_ids{$app_id} and
                g_contained_in_list($blob->{label},$mime_type))
            {
                cxlog("    found: handled by $app_id in $blob->{label}\n");
                return 1;
            }
        }
    }

    cxlog("    not found\n");
    return 0;
}


# ----------------------------------------------------------------------
# | Sub:      set_gnome                                                |
# |                                                                    |
# | Purpose:  Set association for gnome                                |
# |                                                                    |
# | Usage:    set_gnome                                                |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub set_gnome($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    my  $blob;
    my  $app_id;


    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return
        unless ($main::gui_info{gnome_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[set_gnome]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");

    # --------------------------------------------------------------
    # | Determine locations                                        |
    # --------------------------------------------------------------
    my $mime_dir = (
        $global ?
        $main::gui_info{gnome_global_mime} :
        $main::gui_info{gnome_preferred_mime}
    );
    my $application_dir = (
        $global ?
        $main::gui_info{gnome_global_application} :
        $main::gui_info{gnome_preferred_application}
    );


    # --------------------------------------------------------------
    # | *.mime file                                                |
    # |                                                            |
    # |                                                            |
    # | Here, associations are set up between mime type and        |
    # | extensions. We want to find out which of the extensions    |
    # | in our list are already associated, and leave those alone. |
    # | But we want to associate our mime type with any that       |
    # | aren't already set up.                                     |
    # --------------------------------------------------------------

    # --------------------------------------------------------------
    # | First, get list of current mime-type<->extension assn's    |
    # --------------------------------------------------------------
    my @args = split ",", $extensions;
    my $ext_to_mime=g_mime_from_ext(\@args);

    # Logging
    cxlog("Pre-existing extensions/MIME types:\n");
    map { cxlog("    $_ -> [", join(",",keys %{$ext_to_mime->{$_}}), "]\n") } keys (%$ext_to_mime);


    # Build a list of the extensions that are not yet associated to a
    # MIME type
    # And a list of all the MIME types we found
    my %missing_exts;
    my %mime_list;
    $mime_list{$mime_type}=1;
    foreach my $ext (@args)
    {
        my $mimes=$ext_to_mime->{$ext};
        if (defined $mimes)
        {
            foreach my $mime (keys %$mimes)
            {
                $mime_list{$mime}=1;
            }
        }
        else
        {
            $missing_exts{$ext}=1;
        }
    }
    cxlog("Missing extensions: ",join(" ",keys %missing_exts),"\n");
    cxlog("Full MIME type list: ", join(" ",keys %mime_list),"\n");

    if (%missing_exts)
    {
        # Create a .mime file with our MIME type and
        # the missing extensions.
        my $fn = "$mime_dir/$main::productid.mime";

        # ----------------------------------------------------------
        # | Check for mime-type entry                              |
        # ----------------------------------------------------------
        my $mimes = g_read_file($fn);
        undef $blob;
        foreach (@$mimes)
        {
            if ($_->{label} eq $mime_type)
            {
                $blob = $_;
                last;
            }
        }

        # ----------------------------------------------------------
        # | If no entry previously existed, create a new one       |
        # ----------------------------------------------------------
        if (!defined $blob)
        {
            $blob = g_new_blob($mime_type, ":");
            push @$mimes, $blob;
        }

        # ----------------------------------------------------------
        # | Set appropriate values                                 |
        # ----------------------------------------------------------
        if (defined $blob->{fields} and
            @{$blob->{fields}} == 1 and
            @{@{$blob->{fields}}[0]}[0] eq "ext")
        {
            # Let's append to the ext field
            @{@{$blob->{fields}}[0]}[1] .= " " . join(" ", keys %missing_exts);
        }
        else
        {
            # Create our own ext field
            push @{$blob->{fields}}, ["ext", join(" ", keys %missing_exts)];
        }

        # ----------------------------------------------------------
        # | Write 'em out                                          |
        # ----------------------------------------------------------
        g_write_file($fn, $mimes);
    }


    # --------------------------------------------------------------
    # | *.applications file                                        |
    # |                                                            |
    # |                                                            |
    # | This is where we 'declare' our application. We must        |
    # | specify the full list of MIME types that it is capable     |
    # | of handling.                                               |
    # --------------------------------------------------------------
    mkdir ($application_dir, 0755)
        unless (-d $application_dir);
    my $fn = "$application_dir/$main::productid.applications";

    # --------------------------------------------------------------
    # | Check for application entry                                |
    # --------------------------------------------------------------
    my $apps = g_read_file($fn);
    undef $blob;
    foreach (@$apps)
    {
        if (kg_command_match($command,g_get_key_val($_,"command")))
        {
            $blob = $_;
            last;
        }
    }

    # --------------------------------------------------------------
    # | If no entry previously existed, create a new one           |
    # --------------------------------------------------------------
    if (!defined $blob)
    {
        $blob = g_new_blob(g_first_unused_crossover_id($apps), "=");
        push @$apps, $blob;
    }

    # --------------------------------------------------------------
    # | Set appropriate values                                     |
    # --------------------------------------------------------------
    g_set_key_val($blob, "command", $command);
    g_set_key_val($blob, "name", $app_name);
    foreach my $mime (keys %mime_list)
    {
        g_append_to_key_list($blob, "mime_types", $mime);
    }
    $app_id = $blob->{label};

    # --------------------------------------------------------------
    # | Write 'em out                                              |
    # --------------------------------------------------------------
    g_write_file($fn, $apps);



    # --------------------------------------------------------------
    # | *.keys file                                                |
    # |                                                            |
    # |                                                            |
    # | Here is where we define which application is used for      |
    # | which MIME type. We should first check the user.keys file  |
    # | in case the user use the Gnome Control Center to make or   |
    # | delete associations 'behind our back'. But otherwise we    |
    # | keep to our own .keys file.                                |
    # --------------------------------------------------------------
    if ($> != 0)
    {
        $fn = "$mime_dir/user.keys";
        my $keys = g_read_file($fn);

        my $keys_modified;
        foreach my $blob (@$keys)
        {
            # See if this blob is about one of our MIME types
            my $found;
            foreach my $mime (split /\s*,\s*/, $blob->{label})
            {
                if ($mime_list{$mime})
                {
                    delete $mime_list{$mime};
                    $found=1;
                }
            }
            next if (!$found);

            # Make sure it references our application
            g_set_key_val($blob, "default_application_id", $app_id);
            g_prepend_to_key_list($blob, "short_list_application_user_additions", $app_id);
            g_remove_from_key_list($blob,"short_list_application_user_removals",$app_id);
            if (defined $icon and $icon ne "")
            {
                g_set_key_val($blob, "icon_filename", $icon);
            }
            $keys_modified=1;
        }
        g_write_file($fn, $keys) if ($keys_modified);
    }

    # --------------------------------------------------------------
    # | Now, $productid.keys                                       |
    # --------------------------------------------------------------
    $fn = "$mime_dir/$main::productid.keys";
    my $keys = g_read_file($fn);

    # --------------------------------------------------------------
    # | Now, try to add our app to each mime type's short list     |
    # --------------------------------------------------------------
    foreach my $mime (keys %mime_list)
    {
        my $blob;
        foreach my $entry (@$keys)
        {
            # This is our *.keys file and we will only have one
            # MIME type per blob.
            if ($entry->{label} eq $mime)
            {
                $blob=$entry;
                last;
            }
        }
        if (!defined $blob) {
            $blob=g_new_blob($mime, "=");
            push @$keys, $blob;
        }
        g_set_key_val($blob, "description", $document_type);
        g_set_key_val($blob, "default_action_type", "application");
        g_set_key_val($blob, "default_application_id", $app_id);
        if (defined $icon and $icon ne "")
        {
            g_set_key_val($blob, "icon_filename", $icon);
        }
        g_prepend_to_key_list($blob, "short_list_application_user_additions", $app_id);
        # FIXME: What about
        #        short_list_application_ids_for_novice_user_level
        #        short_list_application_ids_for_intermediate_user_level
        #        short_list_application_ids_for_advanced_user_level?
    }

    # --------------------------------------------------------------
    # | Ok, write 'em out                                          |
    # --------------------------------------------------------------
    g_write_file($fn, $keys);

    return;
}


# ----------------------------------------------------------------------
# | Sub:      remove_gnome                                             |
# |                                                                    |
# | Purpose:  Remove association for gnome                             |
# |                                                                    |
# | Usage:    remove_gnome                                             |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub remove_gnome($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;


    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return
        unless ($main::gui_info{gnome_on});

    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[removeall_gnome]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");

    # --------------------------------------------------------------
    # | Determine locations                                        |
    # --------------------------------------------------------------
    my $mime_dir = (
        $global ?
        $main::gui_info{gnome_global_mime} :
        $main::gui_info{gnome_preferred_mime}
    );
    my $application_dir = (
        $global ?
        $main::gui_info{gnome_global_application} :
        $main::gui_info{gnome_preferred_application}
    );

    # --------------------------------------------------------------
    # | First, get list of current mime-type<->extension assn's    |
    # --------------------------------------------------------------
    my @args = split ",", $extensions;
    my $ext_to_mime=g_mime_from_ext(\@args);

    # Logging
    cxlog("Pre-existing extensions/MIME types:\n");
    map { cxlog("    $_ -> [", join(",",keys %{$ext_to_mime->{$_}}), "]\n") } keys (%$ext_to_mime);


    # Build a list of all the MIME types corresponding to the specified
    # extensions
    my %mime_list;
    $mime_list{$mime_type}=1;
    foreach my $ext (@args)
    {
        my $mimes=$ext_to_mime->{$ext};
        if (defined $mimes)
        {
            foreach my $mime (keys %$mimes)
            {
                $mime_list{$mime}=1;
            }
        }
    }
    cxlog("Full MIME type list: ", join(" ",keys %mime_list),"\n");

    # --------------------------------------------------------------
    # | *.applications file                                        |
    # | Leave the entries in the *.applications file               |
    # | This makes it easy to re-activate associations from the    |
    # | GNOME Control Center at a later time                       |
    # --------------------------------------------------------------

    # Find the application id so that we can remove the right
    # entries from the .keys files
    # We are not quite sure where this entry is. It could be in
    # user.applications (old CrossOver) or in $productid.applications.
    # Just check out all files.
    my %app_ids;
    foreach my $apps_file (qglob($application_dir,"\\.applications\$"))
    {
        my $apps = g_read_file($apps_file);
        foreach my $blob (@$apps)
        {
            if (kg_command_match($command,g_get_key_val($blob,"command")))
            {
                $app_ids{$blob->{label}}=1;
            }
        }
    }

    # --------------------------------------------------------------
    # | *.keys file                                                |
    # |                                                            |
    # | We are not sure in which file the association is going to  |
    # | be. It could be in user.keys if created via the Gnome      |
    # | Control Center, or in $productid.keys if done via cxassoc  |
    # | So we just scan all *.keys files                           |
    # --------------------------------------------------------------
    foreach my $keys_file (qglob($mime_dir,"\\.keys\$"))
    {
        my $keys = g_read_file($keys_file);
        next if (!defined $keys);
        my $keys_modified;

        my $i=0;
        while ($i < @$keys)
        {
            my $blob=@$keys[$i++];

            # See if this blob is about one of our MIME types
            my $found;
            foreach my $mime (split /\s*,\s*/, $blob->{label})
            {
                if ($mime_list{$mime})
                {
                    $found=1;
                    last;
                }
            }
            next if (!$found);

            # Now, check if it concerns our application
            my $blob_modified;
            my $app_id=g_get_key_val($blob, "default_application_id");
            if (defined $app_id and $app_ids{$app_id})
            {
                delete $blob->{keys}->{default_application_id};
                $blob_modified=1;
            }
            my $tmp=g_get_key_val($blob, "short_list_application_user_additions") || "";
            my @user_apps=split /\s*,\s*/, $tmp;
            if (@user_apps > 0)
            {
                my $j=0;
                while ($j < @user_apps)
                {
                    if ($app_ids{$user_apps[$j++]})
                    {
                        $j--;
                        splice @user_apps, $j, 1;
                        $blob_modified=1;
                    }
                }
            }

            # And now remove/update the blob
            # Note that for multi-mime multi-applications blobs the right
            # thing to do would be to split the blob in two. One where our
            # app handles the remaining MIME types (if any) together with
            # the others, and another where the other applications still
            # handle our MIME types.
            # Fortunately the Gnome Control Center does not create
            # multi-mime blobs.
            if ($blob_modified)
            {
                $keys_modified=1;
                if (@user_apps == 0)
                {
                    # This blob is empty. Remove it.
                    $i--;
                    splice @$keys, $i, 1;
                }
                else
                {
                    # This blob still associates this MIME type(s) to a few 
                    # other applications.
                    # Update it  and continue
                    g_set_key_val($blob,"short_list_application_user_additions",join(",",@user_apps));
                }
            }
        }
        g_write_file($keys_file, $keys) if ($keys_modified);
    }

    # --------------------------------------------------------------
    # | *.mime file                                                |
    # |                                                            |
    # |                                                            |
    # --------------------------------------------------------------

    # It's best to leave them
    # - they may still be in use (we did not check)
    # - they may still be handy to the user

    return;
}


# ----------------------------------------------------------------------
# | Sub:      removeall_gnome                                          |
# |                                                                    |
# | Purpose:  Remove all CrossOver information from Gnome              |
# |                                                                    |
# | Usage:    removeall_gnome                                          |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub removeall_gnome($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;


    # --------------------------------------------------------------
    # | Sanity checks                                              |
    # --------------------------------------------------------------
    return
        unless ($main::gui_info{gnome_on});

    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[remove_gnome]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");


    # --------------------------------------------------------------
    # | Determine locations                                        |
    # --------------------------------------------------------------
    my $mime_dir = (
        $global ?
        $main::gui_info{gnome_global_mime} :
        $main::gui_info{gnome_preferred_mime}
    );
    my $application_dir = (
        $global ?
        $main::gui_info{gnome_global_application} :
        $main::gui_info{gnome_preferred_application}
    );


    # --------------------------------------------------------------
    # | Cleanup the *.applications files                           |
    # --------------------------------------------------------------

    # Read the user.applications file and remove the entries we have
    # there if any. This should only happen if they were created by
    # an old version of CrossOver
    my $file="$application_dir/user.applications";
    my $apps = g_read_file($file);
    if (defined $apps)
    {
        my $apps_modified;
        my $i=0;
        while ($i < @$apps)
        {
            my $blob=@$apps[$i++];
            if ($blob->{label} =~ /^$main::productid-app-\d+$/)
            {
                # Remove our entry
                $i--;
                splice @$apps, $i, 1;
                $apps_modified=1;
            }
        }
        g_write_file($file, $apps) if ($apps_modified);
    }
    # And summarily remove our file
    cxlog("Deleting $application_dir/$main::productid.applications\n");
    unlink "$application_dir/$main::productid.applications";

    # --------------------------------------------------------------
    # | *.keys file                                                |
    # --------------------------------------------------------------

    # First cleanup the user.keys file
    $file="$mime_dir/user.keys";
    my $keys = g_read_file($file);
    if (defined $keys)
    {
        my $keys_modified;

        my $i=0;
        while ($i < @$keys)
        {
            my $blob=@$keys[$i++];

            # Now, check if it concerns our application
            my $blob_modified;
            my $app_id=g_get_key_val($blob, "default_application_id");
            if (defined $app_id and $app_id =~ /^$main::productid-app-\d+$/)
            {
                delete $blob->{keys}->{default_application_id};
                $blob_modified=1;
            }
            my $tmp=g_get_key_val($blob, "short_list_application_user_additions") || "";
            my @user_apps=split /\s*,\s*/, $tmp;
            if (@user_apps > 0)
            {
                my $j=0;
                while ($j < @user_apps)
                {
                    if ($user_apps[$j++] =~ /^$main::productid-app-\d+$/)
                    {
                        $j--;
                        splice @user_apps, $j, 1;
                        $blob_modified=1;
                    }
                }
            }

            # And now remove/update the blob
            # Note that for multi-mime multi-applications blobs the right
            # thing to do would be to split the blob in two. One where our
            # app handles the remaining MIME types (if any) together with
            # the others, and another where the other applications still
            # handle our MIME types.
            # Fortunately the Gnome Control Center does not create
            # multi-mime blobs.
            if ($blob_modified)
            {
                $keys_modified=1;
                if (@user_apps == 0)
                {
                    # This blob is empty. Remove it.
                    $i--;
                    splice @$keys, $i, 1;
                }
                else
                {
                    # This blob still associates this MIME type(s) to a few 
                    # other applications.
                    # Update it  and continue
                    g_set_key_val($blob,"short_list_application_user_additions",join(",",@user_apps));
                }
            }
        }
        g_write_file($file, $keys) if ($keys_modified);
    }

    # And summarily remove our file
    unlink "$mime_dir/$main::productid.keys";

    # --------------------------------------------------------------
    # | *.mime file                                                |
    # --------------------------------------------------------------

    # We cannot cleanup user.mime because nothing distinguishes
    # our MIME types from regular MIME types. Newer CrossOver
    # versions don't modify this file anyway.

    # And summarily remove our file
    unlink "$mime_dir/$main::productid.mime";

    return;
}



# ----------------------------------------------------------------------
# | === CDE functions ===                                              |
# |                                                                    |
# |                                                                    |
# ----------------------------------------------------------------------



# ----------------------------------------------------------------------
# | Sub:      query_cde                                                |
# |                                                                    |
# | Purpose:  Determine whether association is set up for CDE          |
# |                                                                    |
# | Usage:    query_cde                                                |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  1 if association exists, 0 if not                        |
# ----------------------------------------------------------------------
sub query_cde ($$$$$$$)
{
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    # Debug
    cxlog("\n[query_cde]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    global        [$global]\n");

    # Locals
    my  @cde = read_cde_file ($global);

    my  $data_ref;
    my  ($actions_key, $action);
    my  $map_ref;
    my  $map_action_key;
    my  $exec_ref;
    my  $data_record_name;

    my  $r = 0;

# Begin query_cde

    # --------------------------------------------------------------
    # | (1) Find DATA_ATTRIBUTES object with given MIME_TYPE       |
    # | (2) Fetch ACTIONS                                          |
    # | (3) For each item in ACTIONS:                              |
    # |                                                            |
    # |     (a) Look for ACTION object with matching name          |
    # |     (b) Look for TYPE=MAP and MAP_ACTION keyword           |
    # |     (c) Find ACTION object with name matching value for    |
    # |         MAP_ACTION                                         |
    # |     (d) If EXEC_STRING value matches command, Bingo!       |
    # --------------------------------------------------------------
    $data_ref = find_cde_object 
    (
        \@cde,
        type => "DATA_ATTRIBUTES",
        MIME_TYPE => $mime_type
    );


    if ($data_ref && ($actions_key = cde_key ($data_ref, "ACTIONS")))
    {
        $data_record_name = $data_ref->{name};

        for $action (split (/\s+/, $actions_key))
        {

            $map_ref = find_cde_object 
            (
                \@cde,
                type => "ACTION",
                name => $action,
                TYPE => "MAP",
                ARG_TYPE => $data_record_name
            );
            if ($map_ref && ($map_action_key = cde_key ($map_ref, "MAP_ACTION")))
            {
                $exec_ref = find_cde_object 
                (
                    \@cde,
                    type        => "ACTION",
                    name        => $map_action_key,
                    EXEC_STRING => "$command %Arg_1%"
                );
                $r = 1
                    if ($exec_ref);
            }
        }
    }


    # --------------------------------------------------------------
    # | Return what we got                                         |
    # --------------------------------------------------------------
    return ($r);

} # end query_cde



# ----------------------------------------------------------------------
# | Sub:      set_cde                                                  |
# |                                                                    |
# | Purpose:  Set up CDE association                                   |
# |                                                                    |
# | Usage:    query_cde                                                |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# |                                                                    |
# | [todo]  Be concerned about unique names for created objects        |
# | [todo]  Handle multiple extensions in one call                     |
# ----------------------------------------------------------------------
sub set_cde ($$$$$$$)
{
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    # Debug
    cxlog("\n[set_cde]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");

    # Locals
    my  @cde = read_cde_file ($global);
    my  ($exec_ref, $exec_name);
    my  ($data_ref, $data_name);
    my  ($crit_ref, $crit_name);
    my  ($map_ref,  $map_name);
    my  $template;
    my  $extension;

# Begin set_cde

    # --------------------------------------------------------------
    # | Create ACTION object with appropriate EXEC_STRING value,   |
    # | unless one exists already                                  |
    # --------------------------------------------------------------
    unless 
    (
        $exec_ref = find_cde_object 
        (
            \@cde,
            type        => "ACTION",
            EXEC_STRING => "$command %Arg_1%"
        )
    )
    {
        ($exec_name = ("Open_" . $command)) =~ s/\W/_/g;
        $exec_ref =
        {
            type => "ACTION",
            name => $exec_name,
            keys =>
            {
                EXEC_STRING => "$command %Arg_1%",
                WINDOW_TYPE => "NO_STDIO"
            }
        };
        push @cde, $exec_ref;
    }

    # --------------------------------------------------------------
    # | Handle all extensions                                      |
    # --------------------------------------------------------------
    for $extension (split(",", $extensions))
    {
        $template = "%s." . $extension;
        ($data_name = ("Data_" . $mime_type)) =~ s/\W/_/g;
        $data_name = $data_name . "_" . $extension;
        # --------------------------------------------------------------
        # | Create DATA_ATTRIBUTES object for mime type                |
        # --------------------------------------------------------------
        unless 
        (
            $data_ref = find_cde_object 
            (
                \@cde,
                type        => "DATA_ATTRIBUTES",
                MIME_TYPE   => $mime_type,
                NAME_TEMPLATE => $template
            )
        )
        {
            $data_ref =
            {
                type => "DATA_ATTRIBUTES",
                name => $data_name,
                keys =>
                {
                    ACTIONS       => "Open",
                    ICON          => $icon,
                    NAME_TEMPLATE => $template,
                    MIME_TYPE     => $mime_type,
                    DESCRIPTION   => $document_type,
                }
            };
            push @cde, $data_ref;
        }
  
        # --------------------------------------------------------------
        # | Create DATA_CRITERIA object                                |
        # --------------------------------------------------------------
        unless 
        (
            $crit_ref = find_cde_object 
            (
                \@cde,
                type         => "DATA_CRITERIA",
                NAME_PATTERN => $extension,
            )
        )
        {
            $crit_name = $data_ref->{name} . "_Criteria";
            $crit_ref =
            {
                type => "DATA_CRITERIA",
                name => $crit_name,
                keys =>
                {
                    DATA_ATTRIBUTES_NAME => $data_ref->{name},
                    NAME_PATTERN         => "*." . $extension,
                }
            };
            push @cde, $crit_ref;
        }

        # --------------------------------------------------------------
        # | Create ACTION object to map DATA_ATTRIBUTES object to      |
        # | ACTION object                                              |
        # --------------------------------------------------------------
        unless 
        (
            $map_ref = find_cde_object 
            (
                \@cde,
                type       => "ACTION",
                ARG_TYPE   => $data_ref->{name},
                TYPE       => "MAP",
                MAP_ACTION => $exec_ref->{name}
            )
        )
        {
            $map_name = "Open";  # [todo] Does this name need to be unique?
            $map_ref =
            {
                type => "ACTION",
                name => $map_name,
                keys =>
                {
                    ARG_TYPE   => $data_ref->{name},
                    TYPE       => "MAP",
                    MAP_ACTION => $exec_ref->{name},
                }
            };
            push @cde, $map_ref;
        }
    }

    # --------------------------------------------------------------
    # | Righty then; write it back out                             |
    # --------------------------------------------------------------
    write_cde_file ($global,@cde);

    system("PATH=\$PATH:/usr/dt/bin ; dtaction ReloadActions");

    # --------------------------------------------------------------
    # | Later, dude                                                |
    # --------------------------------------------------------------
    return;

} # end set_cde



# ----------------------------------------------------------------------
# | Sub:      remove_cde                                               |
# |                                                                    |
# | Purpose:  Set up CDE association                                   |
# |                                                                    |
# | Usage:    query_cde                                                |
# |           (                                                        |
# |               mime_type,                                           |
# |               extensions,                                          |
# |               document_type,                                       |
# |               command,                                             |
# |               icon,                                                |
# |               global                                               |
# |           )                                                        |
# |                                                                    |
# |                                                                    |
# | Returns:  (none)                                                   |
# ----------------------------------------------------------------------
sub remove_cde ($$$$$$$)
{
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    # Debug
    cxlog("\n[remove_cde]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");

    # Locals
    my  @cde = read_cde_file ($global);
    my  ($exec_ref, $attr_ref);
    my  ($map_ref, $crit_ref);
    my  (@save_cde, $i);

# Begin remove_cde

    # --------------------------------------------------------------
    # | Find ACTION object with given EXEC_STRING value and        |
    # | DATA_ATTRIBUTES object with given MIME_TYPE value          |
    # --------------------------------------------------------------
    if
    (
        (
            $exec_ref = find_cde_object 
            (
                \@cde,
                type        => "ACTION",
                EXEC_STRING => "$command %Arg_1%",
            )
        )
        &&
        (
            $attr_ref = find_cde_object 
            (
                \@cde,
                type      => "DATA_ATTRIBUTES",
                MIME_TYPE => $mime_type,
            )
        )
    )
    {

        # --------------------------------------------------------------
        # | Find ACTION object with type MAP which links the two, and  |
        # | DATA_CRITERIA object that goes with DATA_ATTRIBUTES object |
        # --------------------------------------------------------------
        if
        (
            (
                $map_ref = find_cde_object 
                (
                    \@cde,
                    type       => "ACTION",
                    TYPE       => "MAP",
                    ARG_TYPE   => $attr_ref->{name},
                    MAP_ACTION => $exec_ref->{name}
                )
            )
            &&
            (
                $crit_ref = find_cde_object 
                (
                    \@cde,
                    type                 => "DATA_CRITERIA",
                    DATA_ATTRIBUTES_NAME => $attr_ref->{name}
                )
            )
        )
        {

            # --------------------------------------------------------------
            # | Copy array, leaving out objects found                      |
            # --------------------------------------------------------------
            @save_cde = @cde;
            @cde = ();
            for $i (@save_cde)
            {
                push @cde, $i
                    unless (grep { $i eq $_ } ($exec_ref, $attr_ref, $map_ref, $crit_ref));
            }

        }  # end if
    }  # end if


    # --------------------------------------------------------------
    # | Righty then; write modified array back out                 |
    # --------------------------------------------------------------
    write_cde_file ($global,@cde);

    system("PATH=\$PATH:/usr/dt/bin dtaction ReloadActions");

    # --------------------------------------------------------------
    # | Later, dude                                                |
    # --------------------------------------------------------------
    return;

} # end remove_cde


sub removeall_cde($$$$$$$)
{
    # Locals
    my  ($mime_type, $extensions, $document_type, $app_name, $command, $icon, $global) = @_;

    my  $blob;

    return
        unless ($main::gui_info{kde_on});


    # --------------------------------------------------------------
    # | Debug                                                      |
    # --------------------------------------------------------------
    cxlog("\n[removeall_kde]\n");
    cxlog("    mime-type     [$mime_type]\n");
    cxlog("    extensions    [$extensions]\n");
    cxlog("    document-type [$document_type]\n");
    cxlog("    command       [$command]\n");
    cxlog("    icon          [$icon]\n");
    cxlog("    global        [$global]\n");

    delete_cde_file ($global);

    system("PATH=\$PATH:/usr/dt/bin dtaction ReloadActions");

    return;
}
