# sensible_copy.tcl --
#
#       "Sensible Copy" chat plugin for Tkabber.
#       Copies selected text from the chat window (containing the
#       log of the conversation) or the input windows -- depending
#       on which one contains the selection.
#
# Author: Konstantin Khomoutov <flatworm@users.sourceforge.net>
#
# See license.terms for the terms of distribution.
# See README for usage details.

package require msgcat

namespace eval sensible_copy {
    variable options

    ::msgcat::mcload [file join [file dirname [info script]] msgs]

    variable desc [::msgcat::mc \
            "This plugin copies the selected text from the chat log\
            window or the chat input window - depending on which one\
            contains the selection."]

    if {![::plugins::is_registered sensible_copy]} {
        ::plugins::register sensible_copy \
            -namespace [namespace current] \
            -source [info script] \
            -description [::msgcat::mc \
                "Whether the sensible text copying plugin is loaded."]\n$desc \
            -loadcommand [namespace code load] \
            -unloadcommand [namespace code unload]
        return
    }
}

proc sensible_copy::load {} {
    hook::add open_chat_post_hook [namespace current]::prepare_chat_window

    foreach chatid [chat::opened] {
        prepare_chat_window $chatid ?
    }
}

proc sensible_copy::unload {} {
    foreach chatid [chat::opened] {
        unprepare_chat_window $chatid
    }

    hook::remove open_chat_post_hook [namespace current]::prepare_chat_window
}

proc sensible_copy::prepare_chat_window {chatid type} {
    set iw [::chat::input_win $chatid]
    bind $iw <<_DefaultCopy>> [bind [winfo class $iw] <<Copy>>]
    bind $iw <<Copy>> \
         [list [namespace current]::copy [double% $chatid]]
}

proc sensible_copy::unprepare_chat_window {chatid} {
    set iw [::chat::input_win $chatid]
    bind $iw <<Copy>> {}
    bind $iw <<_DefaultCopy>> {}
}

proc sensible_copy::copy {chatid} {
    set cw [::chat::chat_win $chatid]
    set iw [::chat::input_win $chatid]

    set range [$cw tag ranges sel]
    if {$range == ""} {
        event generate $iw <<_DefaultCopy>>
        return
    }

    event generate $cw <<Copy>>
}

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