[Tkabber-dev] r409 - in trunk/plugins/tastebin: . msgs

tkabber-svn at jabber.ru tkabber-svn at jabber.ru
Wed Sep 29 16:30:43 MSD 2010


Author: Rejjin
Date: 2010-09-29 16:30:43 +0400 (Wed, 29 Sep 2010)
New Revision: 409

Added:
   trunk/plugins/tastebin/README-ru
Removed:
   trunk/plugins/tastebin/image/
Modified:
   trunk/plugins/tastebin/msgs/ru.msg
   trunk/plugins/tastebin/tastebin.tcl
Log:
New version of Tastebin - Tkabber plugin.
Please, see README-ru.

Added: trunk/plugins/tastebin/README-ru
===================================================================
--- trunk/plugins/tastebin/README-ru	                        (rev 0)
+++ trunk/plugins/tastebin/README-ru	2010-09-29 12:30:43 UTC (rev 409)
@@ -0,0 +1,61 @@
+Tastebin - Tkabber плагин.
+
+Использование.
+		После нажатия на кнопку tastebin (расположена на Toolbar)
+		открывается новая вкладка. Фокус автоматически 
+		перемещается на неё. Во вкладке есть отключенное поле
+		для ввода языка. Это индикатор текущей подсветки
+		синтаксиса. Чуть ниже расположено поле ввода вашего
+		имени. Если его оставить пустым, то при отправке
+		сообщения на сервер вам автоматически присвоится
+		имя "Tastebin - Tkabber plugin". Третье, большое поле -
+		поле ввода содержимого поста. Это основное поле.
+		Нажав на нём правую кнопку мыши вы увидите меню,
+		в котором следующие кнопки:
+		1) Вырезать 2) Скопировать
+		3) Вставить 4) Отмена
+		5) Повтор 6) Выделить всё
+		Правее основного поля находится пара окон списков.
+		Верхний - список избранных подсветок.
+		Нижний - список всех подсветок.
+		Выделите любую подсветку синтаксиса из списка
+		всех подсветок, нажмите правую кнопку мыши -
+		появится меню, в котором вы можете добавить
+		выбранный язык в список избранных подсветок.
+		Удаление из списка избранных подсветок происходит 
+		по-аналогии.
+		Плагин автоматически сохраняет последнюю выбранную
+		подсветку синтаксиса, и при следующем открытии
+		окна эта подсветка синтаксиса будет активной.
+		В самом низу окна расположены 4 кнопки.
+		Отправить - отправляет ваш пост.
+		Очистить - очищает содержимое основного поля поста.
+		История - показывает лог предыдущих постов.
+		(в истории сохраняется некоторое количество 
+		строк поста, время и выбранная подсветка синтаксиса)
+		Отмена - закрыть окно Tastebin.
+		
+		
+		Если вы отправляете сообщение, которое превысило 
+		ограничение по максимальному количеству символов -
+		то сообщение может автоматически отправиться
+		на сервер, либо откроется окно Tastebin, в котором
+		будет введено содержимое поста.
+		При посте через поле воода сообщения для чата
+		нельзя выбрать подсветку синтаксиса 
+		(TODO: исправить).
+		Команды для сообщений:
+		/post <текст> 
+			Отправляет ваше сообщение на сервер
+		/-post <текст>
+			Игнорирует все ограничения по максимальному
+			количеству символов. Происходит нормальная
+			отправка сообщения.
+			
+			
+		Если вы увидели ссылку на http://pastebin.com,
+		то можете нажать на ней правую кнопку мыши
+		выбрать "Показать содержимое pastebin" -
+		будет открыто новое окно tastebin, в котором 
+		вы сможете увидеть содержимое той ссылки
+		на pastebin.
\ No newline at end of file

Modified: trunk/plugins/tastebin/msgs/ru.msg
===================================================================
--- trunk/plugins/tastebin/msgs/ru.msg	2010-09-28 04:02:01 UTC (rev 408)
+++ trunk/plugins/tastebin/msgs/ru.msg	2010-09-29 12:30:43 UTC (rev 409)
@@ -1,26 +1,33 @@
+::msgcat::mcset ru "Tastebin options" "Настройка Tastebin"
+::msgcat::mcset ru "Automatically save all posted highlights to favorites list" "Автоматически сохранять новые подсветки синтаксиса после удачного поста"
+::msgcat::mcset ru "Save history to file" "Сохранять историю в файл"
+::msgcat::mcset ru "Automatically insert your nickname in every post" "Автоматически вставлять ваше имя перед каждым постом"
+::msgcat::mcset ru "Maximum lines of post for saving to history" "Максимальное количество строк для записи в историю"
+::msgcat::mcset ru "Automatically send a message to the server, if it are exceeding limit" "Автоматически отправлять сообщение на сервер pastebin, если превышено максимальное количество символов"
+::msgcat::mcset ru "Limit the number of characters, after which will automatically send to the server" "Максимальное количество символов, после которй произойдёт автоматическая отправка на сервер pastebin"
+::msgcat::mcset ru "Open a window tastebin if exceeded the size of messages" "Открывать окно Tastebin перед автоматической отправкой сообщения на сервер pastebin"
+::msgcat::mcset ru "Tastebin" "Tastebin плагин"
+::msgcat::mcset ru "Tastebin - pastebin uploader" "Tastebin - загрузчик pastebin"
 ::msgcat::mcset ru "Syntax Highlighting" "Подсветка синтаксиса"
-::msgcat::mcset ru  "Your name or nick" "Ваше имя или ник"
-::msgcat::mcset ru "Empty string." "Пустая строка."
-::msgcat::mcset ru "Error" "Ошибка"
+::msgcat::mcset ru "Your name or nick" "Ваше имя или ник"
 ::msgcat::mcset ru "Send" "Отправить"
 ::msgcat::mcset ru "Clean" "Очистить"
+::msgcat::mcset ru "History" "История"
 ::msgcat::mcset ru "Close" "Закрыть"
-::msgcat::mcset ru "History" "История"
-::msgcat::mcset ru "Tastebin options" "Tastebin-настройки"
-::msgcat::mcset ru "Show on top of all windows" "Отображать поверх всех окон"
-::msgcat::mcset ru "Your name or nick" "Ваше имя или ник"
-::msgcat::mcset ru "Use a special display window" "Использовать специальное отображение окна"
-::msgcat::mcset ru "Save state" "Сохранять состояние"
+::msgcat::mcset ru "Favorite highlights" "Избранные"
+::msgcat::mcset ru "All highlights" "Все"
+::msgcat::mcset ru "Add to favorite list" "Добавить в избранное"
+::msgcat::mcset ru "Remove from favorite list" "Удалить из избранного"
 ::msgcat::mcset ru "Cut" "Вырезать"
 ::msgcat::mcset ru "Copy" "Копировать"
 ::msgcat::mcset ru "Paste" "Вставить"
 ::msgcat::mcset ru "Undo" "Отмена"
 ::msgcat::mcset ru "Redo" "Повтор"
 ::msgcat::mcset ru "Select all" "Выделить всё"
-::msgcat::mcset ru "Please wait ..." "Пожалуйста, подождите ..."
-::msgcat::mcset ru "Your message are exceeding limit" "Ваше сообщение привысило ограничение"
-::msgcat::mcset ru "Tastebin autopost" "Автоотправка сообщений Tastebin"
-::msgcat::mcset ru "Tastebin autopost options" "Автоотправка сообщений Tastebin - настройки"
-::msgcat::mcset ru "Enable autopost for your messages" "Включить автоматическую отпраку сообщения"
-::msgcat::mcset ru "Max symbols in your message for normal sending, else - autopost to pastebin" "Максимальное количество символов для нормальной отправки сообщения. Если превышен - сообщение автоматически отсылается на pastebin"
-::msgcat::mcset ru "The number of characters can not be less than 10" "Количество символов не может быть меньше 10-и"
+::msgcat::mcset ru "Empty string." "Пустая строка."
+::msgcat::mcset ru "Please wait ..." "Пожалуйста подождите"
+::msgcat::mcset ru "Too many chars" "Слишком мало символов"
+::msgcat::mcset ru "Your message are exceeding limit" "Ваше сообщение превысило ограничение"
+::msgcat::mcset ru "Show pastebin content" "Показать содержимое pastebin"
+::msgcat::mcset ru "Error" "Ошибка"
+::msgcat::mcset ru "Cant parse content" "Не удалось обработать контент"

Modified: trunk/plugins/tastebin/tastebin.tcl
===================================================================
--- trunk/plugins/tastebin/tastebin.tcl	2010-09-28 04:02:01 UTC (rev 408)
+++ trunk/plugins/tastebin/tastebin.tcl	2010-09-29 12:30:43 UTC (rev 409)
@@ -1,570 +1,677 @@
-#	Tastebin - pastebin.com uploader plugin
-#	Written by Renji
-#	xmpp: rejjin at jabber.dk
-#	e-mail: webrenji at gmail.com
-
-package require http
-package require msgcat
-
 namespace eval tastebin {
-	variable options
+	package require http
+	package require msgcat
 	
-	set options(path) [file dirname [info script]]
+	variable script_dir [file dirname [info script]]
+	::msgcat::mcload [file join $script_dir msgs]
 	
-	set options(topmost_exist) 0
-	set options(toolwindow_exist) 0
-	
-	::msgcat::mcload [file join $options(path) msgs]
-}
-
-proc tastebin::initCustomOptions { } {
 	variable options
-	
 	custom::defgroup Plugins \
-		[::msgcat::mc "Plugins options."] \
-			-group Tkabber	
-	
+	[::msgcat::mc "Plugins options."] \
+	-group Tkabber	
     custom::defgroup Tastebin \
-		[::msgcat::mc "Tastebin options"] \
-			-group Plugins	
-		
-	custom::defvar options(save_state) 0 \
-		[::msgcat::mc "Save state"] \
-		-group Tastebin -type boolean
-		
+	[::msgcat::mc "Tastebin options"] \
+	-group Plugins	
 	custom::defvar options(save_history_to_file) 1 \
-		[::msgcat::mc "Save history to file"] \
-		-group Tastebin -type boolean
-		
-	custom::defgroup [::msgcat::mc "Tastebin autopost"] \
-		[::msgcat::mc "Tastebin autopost options"] \
-			-group Tastebin	
-		
-	custom::defvar options(autopost_enable) 1 \
-		[::msgcat::mc "Enable autopost for your messages"] \
-		-group [::msgcat::mc "Tastebin autopost"] -type boolean
-		
-	custom::defvar options(max_symbol_numbers) 500 \
-			[::msgcat::mc "Max symbols in your message for normal \
-			sending, else - autopost to pastebin"] \
-			-type string -group [::msgcat::mc "Tastebin autopost"]
-			
-	hook::add chat_send_message_hook \
-		[namespace current]::handle_command
-			
-	hook::add generate_completions_hook \
-		[namespace current]::command_comps	
-		
-		
-	if { [optionExist topmost] } {
-		custom::defvar options(topmost) 1 \
-			[::msgcat::mc "Show on top of all windows"] \
-			-group Tastebin -type boolean
-	}
+	[::msgcat::mc "Save history to file"] \
+	-group Tastebin -type boolean
+	custom::defvar options(nick) {} \
+	[::msgcat::mc "Automatically insert your nickname in every post"] \
+	-group Tastebin -type string
+	custom::defvar options(auto_save_to_favotites) 0 \
+	[::msgcat::mc "Automatically save all posted highlights to favorites list"] \
+	-group Tastebin -type boolean
+	custom::defvar options(history_maximum_lines) 15 \
+	[::msgcat::mc "Maximum lines of post for saving to history"] \
+	-group Tastebin -type integer
 	
-	if { [optionExist toolwindow] } {
-	custom::defvar options(toolwindow) 1 \
-		[::msgcat::mc "Use a special display window"] \
-		-group Tastebin -type boolean
-	}
+	custom::defvar options(autopost,enabled) 1 \
+	[::msgcat::mc "Automatically send a message to the server, if it are exceeding limit"] \
+	-group Tastebin -type boolean
+	custom::defvar options(autopost,maximum_chars) 800 \
+	[::msgcat::mc "Limit the number of characters, after which will automatically send to the server"] \
+	-group Tastebin -type integer	
+	custom::defvar options(autopost,open_window) 1 \
+	[::msgcat::mc "Open a window tastebin if exceeded the size of messages"] \
+	-group Tastebin -type boolean	
+	
+	variable last_lang
+	custom::defvar last_lang {} {} \
+	-group Hidden -type boolean	
+	
+	variable highlights
+	custom::defvar highlights(fav_names) {} {} \
+	-group Hidden -type boolean	
+	
+	variable NS [namespace current]
+	hook::add finload_hook ${NS}::handle
+	hook::add chat_send_message_hook ${NS}::handle_command	
+	hook::add generate_completions_hook ${NS}::command_comps
+	hook::add chat_win_popup_menu_hook ${NS}::popup_menu
 }
 
-proc tastebin::optionExist option {
-	return [expr {[lsearch -exact [wm attributes .] -$option] >= 0}]
+
+proc tastebin::handle { } {
+	variable highlights
+	
+	lassign [get_highlights] highlights(names) highlights(codes)
+	create_buttons
 }
 
 
-proc tastebin::GetHighlights { } {
-	variable options
+# Варианты открытия диалога tastebin
+# Toolbar-button
+# Menu Services / Plugins / command
+# + {} - {}
+
+proc tastebin::create_buttons { } {
+	variable script_dir
+	variable NS
 	
-	set chan [open [file join $options(path) highlights] RDONLY]
+	image create photo \
+		plugins/tastebin-button -file \
+		[file join $script_dir pixmaps toolbar.gif]
 	
-	set options(highlightsNames) {}
-	set options(highlights) {}
+	ifacetk::add_toolbar_button \
+		plugins/tastebin-button \
+		${NS}::open_dialog \
+		[::msgcat::mc "Tastebin"] 
 	
-	while { [eof $chan] == 0 } {
-		gets $chan line
-		lappend options(highlightsNames) [lindex $line 0]
-		lappend options(highlights) [lindex $line 1]
-	}
-	
-	close $chan
+	[.mainframe getmenu services] insert \
+		[::msgcat::mc "Plugins"] \
+		separator
+		
+	[.mainframe getmenu services] insert \
+		[::msgcat::mc "Plugins"] command \
+		-label [::msgcat::mc "Tastebin"] \
+		-command ${NS}::open_dialog
 }
 
 
-proc tastebin::SwitchState { } {
+# Чтение содержимого файла "highlights"
+# и инициализация кодов и названий
+# поддерживаемых подсветок синтаксиса.
+# + {} - {{названия подсветок} {коды подсветок}}
 
-	if { [winfo exist .tastebin] == 0 } {
-		return [CreateWindow]
-	}
+proc tastebin::get_highlights { } {
+	variable script_dir
 	
-	if { [wm state .tastebin] eq "normal" } {
-		return [wm state .tastebin withdraw]
+	set chan [open [file join $script_dir highlights] RDONLY]
+	while {![eof $chan]} {
+		lassign [gets $chan] name code
+		lappend hlnames $name
+		lappend hlcodes $code
 	}
+	close $chan
+	return [list $hlnames $hlcodes]
+}
 	
-	wm state .tastebin normal
-}
+#################################################
+# Диалог tastebin.
 
-proc tastebin::CreateWindow { } {
+proc tastebin::open_dialog { {start_str {}} {start_lang {}} } {
+	variable NS
 	variable options
+	variable highlights
+	variable last_lang
+	variable save_fav
 	
-	if { [winfo exist .tastebin] } { 
-		destroy .tastebin 
-	}
-
-	toplevel .tastebin
+	set w [unicue_win_path]
+	set save_fav 0
 	
-	if { [optionExist topmost] } {
-		wm attributes .tastebin -topmost $options(topmost) 
-	}
+	add_win $w -title [::msgcat::mc "Tastebin - pastebin uploader"] \
+		-tabtitle [::msgcat::mc "Tastebin"] \
+	    -raisecmd [list focus $w]
+		
+	frame $w.main -relief ridge -pady 3
 	
-	if { [optionExist toolwindow] } {
-		wm attributes .tastebin -toolwindow $options(toolwindow) 
-	}
-
-	wm title .tastebin "Tastebin"
-	wm resizable .tastebin 0 0
-	
-	frame .tastebin.main_bar \
-		-relief ridge -pady 3 -width 500
+	label $w.main.help_lang -text [::msgcat::mc "Syntax Highlighting"]
+	set L [entry $w.main.lang -state disabled]
+	pack $w.main.help_lang -anchor w 
+	pack $w.main.lang -fill x -pady 2
 		
-	label .tastebin.main_bar.help_lang \
-		-text [::msgcat::mc "Syntax Highlighting"]
+	label $w.main.help_nick -text [::msgcat::mc "Your name or nick"]
+	set H [entry $w.main.header]
+	pack $w.main.help_nick -anchor w 
+	pack $w.main.header -fill x -pady 2	
 		
-	entry .tastebin.main_bar.lang -state disabled
+	set T [text $w.main.txt -yscrollcommand [list $w.main.ys set] \
+		-maxundo 0 -undo true -wrap word]
+	scrollbar $w.main.ys -command [list $w.main.txt yview]
+	pack $w.main.txt $w.main.ys -pady 4 -side left -fill both -expand 1
 	
-	pack .tastebin.main_bar.help_lang \
-		-anchor w 
+	frame $w.options_bar -bd 2 -pady 3
 		
-	pack .tastebin.main_bar.lang \
-		-fill x -pady 2
+	button $w.options_bar.send \
+		-text [msgcat::mc "Send"] \
+		-command [list ${NS}::send $L $H $T]
 		
-	bind .tastebin.main_bar.lang <1> [list [namespace current]::initMenu %X %Y]
+	button $w.options_bar.clean \
+		-text [msgcat::mc "Clean"] \
+		-command [list ${NS}::del_content $T]
 		
-	label .tastebin.main_bar.help_nick \
-		-text [::msgcat::mc "Your name or nick"]
+	button $w.options_bar.history \
+		-text [msgcat::mc "History"] \
+		-command [list ${NS}::history $T]
+	
+	button $w.options_bar.close \
+		-text [msgcat::mc "Close"] \
+		-command [list ${NS}::close $w]
+	
+	pack $w.options_bar.send $w.options_bar.clean \
+	$w.options_bar.history $w.options_bar.close -side left -fill x -padx 4 -expand 1
+	
+	frame $w.fav_lang -bd 2 -pady 3
+	label $w.fav_lang.lab -text [msgcat::mc "Favorite highlights"]
+	listbox $w.fav_lang.list -listvariable ${NS}::highlights(fav_names) \
+	-yscrollcommand [list $w.fav_lang.ys set] -height 5
+	scrollbar $w.fav_lang.ys -command [list $w.fav_lang.list yview]	
+	pack $w.fav_lang.lab -anchor w
 		
-	entry .tastebin.main_bar.header \
-		-state disabled
-		
-	text .tastebin.main_bar.txt \
-		-yscrollcommand [list .tastebin.main_bar.ys set] \
-		-maxundo 0 -undo true -wrap word
-		
-	scrollbar .tastebin.main_bar.ys \
-		-command [list .tastebin.main_bar.txt yview]
+	frame $w.lang -bd 2 -pady 3
+	label $w.lang.lab -text [msgcat::mc "All highlights"]
+	listbox $w.lang.list -listvariable ${NS}::highlights(names) \
+	-yscrollcommand [list $w.lang.ys set]
+	scrollbar $w.lang.ys -command [list $w.lang.list yview]	
+	pack $w.lang.lab -anchor w
 	
-	pack .tastebin.main_bar \
-		-padx 3  -pady 2
+	pack $w.fav_lang.list $w.fav_lang.ys -fill both -pady 2 -expand 1 -side left
+	pack $w.lang.list $w.lang.ys -fill both -pady 2 -expand 1 -side left 
 	
-	pack .tastebin.main_bar.help_nick -anchor w 
+	grid $w.main -row 0 -column 0 -rowspan 4 -columnspan 2 -padx 5 -pady 4 -sticky news
+	grid $w.fav_lang -row 0 -column 2 -sticky n -rowspan 2 -padx 5 
+	grid $w.lang -row 1 -column 2 -sticky ns -padx 5 -rowspan 3
+	grid $w.options_bar -row 4 -column 0 -columnspan 2 -sticky sew -pady 4
 	
-	pack .tastebin.main_bar.header \
-		-fill x -pady 2
+	$L configure -state normal
+	$L insert 0 $start_lang
 	
-	pack .tastebin.main_bar.txt .tastebin.main_bar.ys \
-	-pady 4 -side left -fill y
+	if {[string equal $start_lang {}]} {
+	$L insert 0 $last_lang
+	}
 	
-	bind .tastebin.main_bar.header <1> {
-		.tastebin.main_bar.header configure -state normal
-		.tastebin.main_bar.header delete 0 end
-		set [namespace current]::options(choised,name) 1
+	$L configure -state disabled
+	
+	$T insert 0.0 $start_str
+	$H insert 0 $options(nick)
+	
+	bind  $w.lang.list <<ListboxSelect>> [list ${NS}::lang_selected %W $L]
+	bind  $w.fav_lang.list <<ListboxSelect>> [list ${NS}::lang_selected %W $L]
+	bind $w.main.txt <3> [list ${NS}::create_menu %W %X %Y]
+	bind $w.lang.list <3> [list ${NS}::update_favorite_list add %W %X %Y]
+	bind $w.fav_lang.list <3> [list ${NS}::update_favorite_list del %W %X %Y]
+	
+	puts $w
+	
+	eval [ format { proc $w { who {text {}} } {
+			set T %s
+			switch -- $who {
+				put {
+					$T insert end $text
+				}
+				clean {
+					del_content $T
+				}
+			}
+		}
+	 } $T ]
+	
+	return $w
+}
+
+proc tastebin::update_favorite_list { type w x y } {
+
+	set idx [$w curselection]
+	
+	if {[string length $idx] < 1} {
+		return
 	}
 	
-	frame .tastebin.options_bar \
-		-relief ridge -bd 2 -pady 3
-		
-	button .tastebin.options_bar.send \
-		-text [msgcat::mc Send] -command [namespace current]::Send
-		
-	button .tastebin.options_bar.clean \
-		-text [msgcat::mc Clean] -command [namespace current]::delContent
-		
-	button .tastebin.options_bar.history \
-		-text [msgcat::mc History] \
-		-command [list [namespace current]::history .tastebin.main_bar.txt]
+	set lang_name [$w get $idx]
 	
-	button .tastebin.options_bar.close \
-		-text [msgcat::mc Close] -command [list [namespace current]::Close]
+	if [winfo exist $w.choise_menu] {
+		destroy $w.choise_menu
+	}
 	
-	pack .tastebin.options_bar \
-		-padx 3 -pady 2 -expand 1 -fill x
+	menu $w.choise_menu -tearoff 0
+
+	switch -- $type {
+		add {
+			$w.choise_menu add command -label [::msgcat::mc "Add to favorite list"] \
+				-command  [list [namespace current]::fav_lang_add $lang_name]
+		}
+		del {
+			$w.choise_menu add command -label [::msgcat::mc "Remove from favorite list"] \
+				-command  [list [namespace current]::fav_lang_del $lang_name]
+		}
+	}
 		
-	pack .tastebin.options_bar.send \
-		.tastebin.options_bar.clean \
-		.tastebin.options_bar.history \
-		.tastebin.options_bar.close \
-			-padx 4 -side left -fill x -expand 1
-			
-	bind .tastebin.main_bar.txt <3> [list [namespace current]::create_menu %W %X %Y]
+	tk_popup $w.choise_menu $x $y
 }
 
-proc tastebin::create_menu { W X Y } {
-	set m $W.menu
+# Инициирующая команда для клика
+# по элементу Listbox.
+# + {путь_к_listbox путь_окна_индикации} - {}
+
+proc tastebin::lang_selected { w L } {
+	set idx [$w curselection]
+	if {[string length $idx] < 1} return
+	set lang_name [$w get $idx]
+	insert_lang $L $lang_name
+	variable last_lang $lang_name
+}
+
+# Вставляет указанный язык в окно
+# индикации выбранного языка.
+# + {путь_окна_индикации имя_языка} - {}
+
+proc tastebin::insert_lang { L lang_name } {
+	$L configure -state normal
+	$L delete 0 end
+	$L insert 0 $lang_name
+	$L configure -state readonly
+}
+
+# Инициализирует всплывающее меню 
+# для правой кнопки мыши
+# + {путь_содержимого_поста X Y} - {}
+
+proc tastebin::create_menu { T x y } {
+	variable NS
 	
-	 if {[winfo exists $m]} {
-	destroy $m
+	set m $T.popup
+	
+	if {[winfo exists $m]} {
+		destroy $m
     }
-
-    menu $m -tearoff 0
 	
-	$m add command -label [::msgcat::mc "Cut"] \
-		-command  [list [namespace current]::cut $W]
-	$m add command -label [::msgcat::mc "Copy"] \
-		-command  [list [namespace current]::copy $W]
-	$m add command -label [::msgcat::mc "Paste"] \
-		-command  [list [namespace current]::paste $W]
-	$m add command -label [::msgcat::mc "Undo"] \
-		-command  [list [namespace current]::undo $W]
-	$m add command -label [::msgcat::mc "Redo"] \
-		-command  [list [namespace current]::redo $W]
-	$m add command -label [::msgcat::mc "Select all"] \
-		-command  [list [namespace current]::select_all $W]
+	menu $m -tearoff 0
 	
-	tk_popup $m $X $Y
+	$m add command -label [::msgcat::mc "Cut"] -command  [list ${NS}::cut $T]
+	$m add command -label [::msgcat::mc "Copy"] -command  [list ${NS}::copy $T]
+	$m add command -label [::msgcat::mc "Paste"] -command  [list ${NS}::paste $T]
+	$m add command -label [::msgcat::mc "Undo"] -command  [list ${NS}::undo $T]
+	$m add command -label [::msgcat::mc "Redo"] -command  [list ${NS}::redo $T]
+	$m add command -label [::msgcat::mc "Select all"] -command  [list ${NS}::select_all $T]
+	
+	tk_popup $m $x $y
 }
+#################################################
+# Добавить / удалить избранные языки
 
-proc tastebin::cut text {
-	if {![catch {set data [$text get sel.first sel.last]}]} {
-		clipboard clear -displayof $text
-		clipboard append -displayof $text $data
-		$text delete sel.first sel.last
+proc tastebin::fav_lang_add { lang } {
+	variable highlights
+	if ![fav_lang_exist $lang] {
+		lappend highlights(fav_names) $lang
 	}
 }
 
-proc tastebin::copy text {
-	if {![catch {set data [$text get sel.first sel.last]}]} {
-		clipboard clear -displayof $text
-		clipboard append -displayof $text $data
+proc tastebin::fav_lang_exist { lang } {
+	variable highlights
+	if {[lsearch -exact highlights(fav_names) $lang] >= 0} {
+		return 1
 	}
+	return 0
 }
 
-proc tastebin::undo text {
-	catch {$text edit undo}
+proc tastebin::fav_lang_del { lang } {
+	variable highlights
+	if {[set ix [lsearch -exact $highlights(fav_names) $lang]] >= 0} {
+		set highlights(fav_names) [lreplace $highlights(fav_names) $ix $ix]
+	}
 }
 
-proc tastebin::redo text {
-	catch {$text edit redo}
+#################################################
+# Команды для всплывающего меню
+# cut, copy, paste, undo, redo, select_all
+# + {путь_содержимого_поста} - {}
+
+proc tastebin::cut { T } {
+	if {![catch {set data [$T get sel.first sel.last]}]} {
+		clipboard clear -displayof $T
+		clipboard append -displayof $T $data
+		$T delete sel.first sel.last
+	}
 }
 
-proc tastebin::select_all text {
-	$text tag add sel 1.0 end
+proc tastebin::copy { T } {
+	if {![catch {set data [$T get sel.first sel.last]}]} {
+		clipboard clear -displayof $T
+		clipboard append -displayof $T $data
+	}
 }
 
-proc tastebin::paste text {
+proc tastebin::undo { T } {
+	catch {$T edit undo}
+}
+
+proc tastebin::redo { T } {
+	catch {$T edit redo}
+}
+
+proc tastebin::select_all { T } {
+	$T tag add sel 1.0 end
+}
+
+proc tastebin::paste { T } {
 	global tcl_platform
-	if {![catch {::tk::GetSelection $text CLIPBOARD} sel]} {
-		set oldSeparator [$text cget -autoseparators]
+	if {![catch {::tk::GetSelection $T CLIPBOARD} sel]} {
+		set oldSeparator [$T cget -autoseparators]
 		if {$oldSeparator} {
-			$text configure -autoseparators 0
-			$text edit separator
+			$T configure -autoseparators 0
+			$T edit separator
 		}
 		if {[tk windowingsystem] ne "x11"} {
-			catch { $text delete sel.first sel.last }
+			catch { $T delete sel.first sel.last }
 		}
-		$text insert insert $sel
+		$T insert insert $sel
 		if {$oldSeparator} {
-			$text edit separator
-			$text configure -autoseparators 1
+			$T edit separator
+			$T configure -autoseparators 1
 		}
 	}
 }
 
-proc tastebin::initMenu { X Y } {
-	variable options
-	
-	set m .tastebin_popup_input
-	
-	if { [winfo exists $m] == 0 } {
-	
-		menu $m -tearoff 0
-						
-		set map_small [set map_big {}]
-		set nomap {}
+#################################################
+# Команды для send, del_content, history и close.
 
-		foreach name $options(highlightsNames) {
-			if { [set ix [lsearch -index 0 $map_small [string index $name 0]]] >= 0 } {
-				set lng [lindex $map_small $ix]
-				set map_small [lreplace $map_small $ix $ix]
-				lappend map_big $lng
-				lappend map_big [list [string index $name 0] $name]
-				lappend nomap [string index $name 0]
-			} else {
-				if { [lsearch -exact $nomap [string index $name 0]] < 0 } {
-					lappend map_small [list [string index $name 0] $name]
-				} else {
-					lappend map_big [list [string index $name 0] $name]
-				}
-			}
-		}
-		
-		set map_all [concat $map_small $map_big]
+# Отправка поста на сервер pastebin.com
+# + {
+# путь_индикатора_подсветки(entry)
+# путь_имени_пользователя(entry)
+# путь_содержимого поста(text)
+# } - {}
 
-		foreach name [lsort -ascii -nocase $map_all] {
-			if {[lsearch -exact $map_small $name] >= 0} {
-				$m add command -label [string totitle [lindex $name 1]] \
-					-command [list [namespace current]::ChoiseLangCallback [lindex $name 1]]
-			} else {
-				set children $m.[string tolower [lindex $name 0]]
-				if { [winfo exist $children] == 0 } {
-					$m add cascade -menu $children \
-						-label "[string totitle [lindex $name 0]]  ..."
-					menu $children -tearoff 0
-				}
-				$children add command -label [lindex $name 1] \
-					-command [list [namespace current]::ChoiseLangCallback [lindex $name 1]]
-			}
-		}
-	}
-	
-	tk_popup $m $X $Y
-}
-
-
-proc tastebin::Close { } {
+proc tastebin::send { L H T } {
+	variable NS
 	variable options
 	
-	if { $options(save_state) == 1 } {
-		return [SwitchState]
+	set URL "http://pastebin.com/api_public.php"
+	set HISTORY [$T get 0.0 $options(history_maximum_lines).0]
+	set CODE [$T get 0.0 end]
+	set NAME [$H get]
+	set LANG_NAME [$L get]
+	
+	if {[string length $CODE] <= 1} {
+		return [info_message [::msgcat::mc "Empty string."] \
+		[::msgcat::mc "Error!"] warning]
 	}
 	
-	destroy .tastebin
-}
-
-proc tastebin::ChoiseLangCallback value {
-	variable options
-	
-	.tastebin.main_bar.lang configure -state normal
-	.tastebin.main_bar.lang delete 0 end
-	.tastebin.main_bar.lang insert 0 $value
-	.tastebin.main_bar.lang configure -state readonly
-	
-	set options(choised,lang) 1
-}
-	
-	
-proc tastebin::GetTrueLang old_lang {
-	variable options
-	if { [set ix [lsearch -exact $options(highlightsNames) $old_lang]] >= 0 } {
-		return [lindex  $options(highlights) $ix]
-	} 
-	return text
-}
-
-
-proc tastebin::Send { } {
-	variable options 
-	
-	set url "http://pastebin.com/api_public.php"
-	set w ".tastebin.main_bar.txt"
-	
-	set code [$w get 0.0 end]
-	
-	if { [string length $code] < 5 } {
-		return [infoMessage \
-			[::msgcat::mc "Empty string."] \
-				[::msgcat::mc "Error"] warning]
-	}	
-	
-	if { ( [info exist options(choised,name)] && $options(choised,name) == 0 ) || \
-		( [.tastebin.main_bar.header get] eq {} ) } {
-			set name "Tastebin - Tkabber Plugin"
-	} else {
-		set name [.tastebin.main_bar.header get]
+	if {[string length $NAME] == 0} {
+	set NAME "Tastebin - Tkabber Plugin"
 	}
 	
-	if { [info exist options(choised,lang)] && $options(choised,lang) == 0 } {
-		set lang text
+	if {[string length $LANG_NAME] == 0} {
+	set LANG "text"
 	} else {
-		set lang [GetTrueLang [.tastebin.main_bar.lang get]]
+	set LANG [get_lang_code $LANG_NAME]
 	}
 	
-	set log [$w get 0.0 10.0]
+	$T delete 0.0 end
+	$T insert 0.0 [::msgcat::mc "Please wait ..."]
+	$T configure -state disabled
 	
-	$w delete 0.0 end
-	$w insert 0.0 [::msgcat::mc "Please wait ..."]
-	$w configure -state disabled
+	set post [http::formatQuery paste_code $CODE \
+	paste_format $LANG paste_name $NAME]
 	
-	set post [http::formatQuery paste_code $code \
-		paste_format $lang paste_name $name]
+	set token [http::geturl $URL -query $post]
+	http::wait $token
 	
-		set token [http::geturl $url -query $post \
-			-command [list [namespace current]::TransComplite $w $log]]
-		http::wait $token
-}
-			
-proc tastebin::TransComplite { w log token } {
-	variable options 
+	set status [http::status $token]
+	set data [http::data $token]
+	http::cleanup $token
 	
-	if { [http::status $token] ne "ok" } {
-		$w configure -state normal
-		$w delete 0.0 end
-		$w insert 0.0 "Error"
-		return [http::cleanup $token]
+	if ![string equal $status ok] {
+		$T configure -state normal
+		$T delete 0.0 end
+		$T insert 0.0 "Error"
+		return
 	}
 	
-	set data [http::data $token]
+	add_history "[get_time]\t$LANG - \
+	${data}:\n\n$HISTORY\
+	\n...\n[string repeat _ 20]\n\n"
+		
+	if $options(auto_save_to_favotites) {
+		fav_lang_add $LANG_NAME
+	}
 	
-	$w configure -state normal
-	$w delete 0.0 end
-	$w insert 0.0 $data
-	http::cleanup $token
-	
-	set date [clock format [clock seconds] -format \
-	$::plugins::options(delayed_timestamp_format)]
-	putHistory "$date\t[.tastebin.main_bar.lang get] - ${data}:\
-	 \n\n$log\n...\n[string repeat _ 20]\n\n"
+	$T configure -state normal
+	$T delete 0.0 end
+	$T insert 0.0 $data
 }
 
+# Всплывающее окно нотификации
+# + {сообщение ?заголовок? ?тип?} - {}
 
-proc tastebin::infoMessage { msg {title Info} {type info} } {
+proc tastebin::info_message { msg {title Info} {type info} } {
 	tk_messageBox -default ok \
 		-message $msg -title $title \
 		-icon $type -type ok
 }
 
+# Вернуть код подсветки по названию
+# + {имя_подсветки} - {код_подсветки}
 
-proc tastebin::delContent { {w .tastebin.main_bar.txt} } {
-	$w delete 0.0 end
+proc tastebin::get_lang_code { LANG } {
+	variable highlights
+	if {[set ix [lsearch -exact $highlights(names) $LANG]] >= 0} {
+		return [lindex  $highlights(codes) $ix]
+	} 
+	return text
 }
 
+# Возвращает время в принятом в Tkabber 
+# формате.
+# + {} - time
 
-proc tastebin::putHistory msg {
+proc tastebin::get_time { } {
+	return [clock format [clock seconds] \
+	-format $::plugins::options(delayed_timestamp_format)]
+}
+
+# Удаляет содержимое поста
+# + {путь_содержимого_поста} - {}
+proc tastebin::del_content { T } {
+	$T configure -state normal
+	$T delete 0.0 end
+}
+
+# Закрывает окно поста
+# + {путь_окна_поста} - {} 
+proc tastebin::close { w } {
+	destroy_win $w
+}
+
+# Показывает историю постов 
+# в поле редактирования поста.
+# + {путь_окна_поста} - {}
+proc tastebin::history { T } {
+	$T configure -state normal
+	$T delete 0.0 end
+	$T insert 0.0 [get_history]
+}
+
+#################################################
+# History команды
+
+proc tastebin::add_history { msg } {
 	variable options
 	
-	if { $options(save_history_to_file) == 0 } {
-		return [lappend options(history) $msg]
+	lappend options(history) $msg
+	
+	if {!$options(save_history_to_file)} {
+	return
 	}
 	
-	set per a 	
+	puts $msg
 	
-	if { [file exist [file join $options(path) history]] == 0 } {
-		set per w
-	}
+	catch { file mkdir [file join $::configdir tastebin_history]}
+	set file [open [file join $::configdir tastebin_history history] a]
 	
-	set file [open [file join $options(path) history] $per]
 	puts $file $msg
+	flush $file
 	close $file
 }
 
-
-proc tastebin::getHistory { } {
+proc tastebin::get_history { } {
 	variable options
+	variable script_dir
 	
-	if { $options(save_history_to_file) == 0 } {
-		if { [info exist options(history)] } {
+	if !$options(save_history_to_file) {
+		if [info exist options(history)] {
 			return $options(history)
 		}
 		return 
 	}
 	
-	if { [file exist [file join $options(path) history]] == 0 } {
+	if {![file exist [file join $::configdir tastebin_history history]]} {
 		return
 	}
 
-	set file [open [file join $options(path) history] r]
+	set file [open [file join $::configdir tastebin_history history] r]
+	
 	set data [read $file]
 	close $file
 	return $data
 }
 
-proc tastebin::history w {
-	variable options
-	
-	delContent
-	
-	$w insert 0.0 [getHistory]
-}
+#################################################
 
-proc tastebin::create_buttons { } {
-	set com [subst [namespace current]::SwitchState]
-	
-	ifacetk::add_toolbar_button \
-		TastebinButton $com \
-		[::msgcat::mc "Tastebin"] 
-		
-	[.mainframe getmenu services] insert \
-		[::msgcat::mc "Plugins"] separator
-		
-	[.mainframe getmenu services] insert \
-		[::msgcat::mc "Plugins"] command \
-		-label [::msgcat::mc "Tastebin"] -command $com
+# Создаёт уникальный путь размещения
+# виджета toplevel.
+# Создана для поддержки открытия нескольких диалогов
+# + {} - {path}
+
+proc tastebin::unicue_win_path { } {
+	variable unique_id
+	return .tastebin_[incr unique_id]
 }
 
+#################################################
+# Автоматический пост сообщений 
+# при превышении ограничения
+
 proc tastebin::command_comps {chatid compsvar wordstart line} {
     upvar 0 $compsvar comps
-
-    if { $wordstart == 0 } {
-		lappend comps {/+p } {/-p }
-    }
+    if {!$wordstart} { lappend comps {/post } {/-post} }
 }
 
 proc tastebin::handle_command {chatid user body type} {
 	variable options
 	
-	if { [string match {/+p*} $body] } {
-		set com post
-	} elseif { [string match {/-p*} $body] } {
-		return stop
-	} elseif { $options(autopost_enable) && \
-		[string length $body] >= \
-			$options(max_symbol_numbers) } {
-				set com big
-	} else {
-		return
+	if {[string match {/post*} $body]} {
+		if {[string length $body] < 10} {
+			show error $chatid [::msgcat::mc "Too many chars"]
+			return -code break
+		} else {
+			set out [post_message [string range $body 7 end]]
+			show info $chatid " >>> $out"
+			add_history "[get_time]\t${out}[string repeat _ 20]\n\n"
+			return -code break
+		}
 	}
 	
-	set tab \n[string repeat _ 40]\n
-	
-	if { $com eq "post" } {
-		set body [string range $body 4 end]
+	if {[string match {/-post*} $body]} {
+		return 
 	}
 	
-	if { [string length $body] < 10 } {
-		show info $chatid $tab[::msgcat::mc "The number of characters can not be less than 10"]$tab
-		return stop
+	if {$options(autopost,enabled)} {
+		if {[string length $body] >= $options(autopost,maximum_chars)} {
+			if {$options(autopost,open_window)} {
+				open_dialog $body
+				return -code break
+			}
+			set link [post_message $body]
+			show info $chatid [::msgcat::mc "Your message are exceeding limit"]
+			show info $chatid " >>> $link"
+			### WARNING ZONE!!!!! ###
+			after 50 [list [chat::input_win $chatid] insert end $link]
+			return -code break
+		}
 	}
+}
 	
-	if { $com eq "big" } {
-		show error $chatid $tab[::msgcat::mc "Your message are exceeding limit"]$tab
-	}
-		
-	show info $chatid $tab[::msgcat::mc "Please wait ..."]$tab
-	
-	set url [sendFromLimit $body]
-	
-	show error $chatid $tab$url$tab
-	return stop
-}
-
-proc tastebin::sendFromLimit code {
+proc tastebin::post_message { body } {
 	set url "http://pastebin.com/api_public.php"
 	set name "Tastebin - Tkabber Plugin"
-	set lang text
-	set post [http::formatQuery paste_code $code \
-		paste_format $lang paste_name $name]
+	set post [http::formatQuery paste_code $body \
+		paste_format text paste_name $name]
 	set token [http::geturl $url -query $post]
 	set data [http::data $token]
 	http::cleanup $token
 	return $data
 }
 
-proc tastebin::show { type chatid msg } {
-    set jid [chat::get_jid $chatid]
-    set cw [chat::chat_win $chatid]
+proc tastebin::show {type chatid msg} {
+	set jid [chat::get_jid $chatid]
+	set cw [chat::chat_win $chatid]
+	chat::add_message $chatid $jid $type $msg {}
+}
 
-    chat::add_message $chatid $jid $type $msg {}
+proc tastebin::popup_menu { m chatwin X Y x y } {
+	variable options
+	variable NS
+	
+	set tags [$chatwin tag names "@$x,$y"]	
+    set idx [lsearch $tags href_*]
+	set idx1 [lsearch $tags uri*]
+	
+	 if { $idx < 0 } {
+		return
+	}
+	
+    if { $idx1 >= 0 } {
+		set url [lindex [lindex $tags $idx1] 1]
+    } else {
+		lassign [$w tag prevrange url "@$x,$y"] a b
+		set url [$w get $a $b]
+    }
+	
+	if {[regexp -- {http://pastebin.com/(.*)} $url => part]} {
+		set url "http://pastebin.com/raw.php?i=$part"
+
+		$m add command \
+			-label [::msgcat::mc "Show pastebin content"] \
+			-command [list ${NS}::get_pastebin_url $url]
+	}
 }
 
-namespace eval tastebin {
-	initCustomOptions
-	GetHighlights
-		
-	image create photo TastebinButton -file \
-		[file join $options(path) image toolbar_icon.gif]
-		
-	hook::add finload_hook \
-		[namespace current]::create_buttons
+proc tastebin::get_pastebin_url { url } {
+	variable NS
 	
+	set w [open_dialog [::msgcat::mc "Please wait ..."]]
+
+	if {[catch {set token [http::geturl $url]}]} {
+		$w clean
+		$w put [::msgcat::mc "Error"]
+		return
+	}
+	
+	http::wait $token
+	
+	set status [http::status $token]
+	
+	if {![string equal $status ok]} {
+		$w clean
+		$w put [::msgcat::mc "Error"]
+		return
+	}
+	
+	set data [http::data $token]
+	http::cleanup $token
+	
+	puts $data 
+	
+	$w clean
+	set data [parse $data]
+	$w put $data
 }
-	
\ No newline at end of file
+
+proc tastebin::parse { data } {
+	if {[regexp -- {<pre>(.*)</pre>} $data => result]} {
+		return [encoding convertfrom utf-8 $result]
+	} else {
+		return  [::msgcat::mc "Cant parse content"]
+	}
+}



More information about the Tkabber-dev mailing list