# aniemoticons.tcl --
#
#       This file is a part of Aniemoticons plugin for the Tkabber XMPP
#       client. This plugin replaces the ::plugins::emoticons::create_image
#       and ::plugins::emoticons::delete_image by the animated GIFs aware
#       procedures. The plugin can be loaded and unloaded dynamically.

package require msgcat

namespace eval aniemoticons {
    ::msgcat::mcload [file join [file dirname [info script]] msgs]

    if {![::plugins::is_registered aniemoticons]} {
        ::plugins::register aniemoticons \
                            -namespace [namespace current] \
                            -source [info script] \
                            -description [::msgcat::mc "Whether the animated\
                                                        GIFs support plugin\
                                                        is loaded."] \
                            -loadcommand [namespace code load] \
                            -unloadcommand [namespace code unload]
        return
    }
}

namespace eval :: {
    source [file join [file dirname [info script]] anigif.tcl]
}

proc aniemoticons::load {} {
    rename ::plugins::emoticons::create_image \
           ::plugins::emoticons::create_image:anigif
    rename ::plugins::emoticons::delete_image \
           ::plugins::emoticons::delete_image:anigif

    proc ::plugins::emoticons::create_image {name args} {
        if {[dict exists $args -file]} {
            set file [dict get $args -file]
            if {[catch {::anigif::anigif $name $file} res]} {
                ::create_image $name {*}$args
                return $name
            } else {
                return $res
            }
        } else {
            ::create_image $name {*}$args
            return $name
        }
    }

    proc ::plugins::emoticons::delete_image {name} {
        ::anigif::destroy $name
    }

    ::plugins::emoticons::on_theme_changed
    return
}

proc aniemoticons::unload {} {
    if {[llength [info procs \
                       ::plugins::emoticons::create_image:anigif]] == 0 || \
        [llength [info procs \
                       ::plugins::emoticons::delete_image:anigif]] == 0} {
        return
    }

    rename ::plugins::emoticons::create_image ""
    rename ::plugins::emoticons::delete_image ""
    rename ::plugins::emoticons::create_image:anigif \
           ::plugins::emoticons::create_image
    rename ::plugins::emoticons::delete_image:anigif \
           ::plugins::emoticons::delete_image

    foreach name [image names] {
        ::anigif::stop $name
    }

    namespace delete ::anigif
}

# vim:ts=8:sw=4:sts=4:et
