urlbar.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (c) 2009 by FlashCode <flashcode@flashtux.org>
  4. # Copyright (c) 2009 by xt <xt@bash.no>
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. #
  20. # Bar with URLs (easy click on long URLs)
  21. # (this script requires WeeChat 0.3.0 or newer)
  22. #
  23. # History:
  24. # 2010-12-20, xt <xt@bash.no>
  25. # version 10: use API for nick color, strip nick prefix
  26. # 2009-12-17, FlashCode <flashcode@flashtux.org>
  27. # version 0.9: fix option name "show_index" (spaces removed)
  28. # 2009-12-12, FlashCode <flashcode@flashtux.org>
  29. # version 0.8: update WeeChat site
  30. # 2009-11-05, xt <xt@bash.no>
  31. # version 0.7: config option to turn off index
  32. # 2009-10-20, xt <xt@bash.no>
  33. # version 0.6: removed priority on the bar
  34. # 2009-07-01, xt <xt@bash.no>
  35. # version 0.5: changed script command to /urlbar, comma separated ignore list
  36. # 2009-05-22, xt <xt@bash.no>
  37. # version 0.4: added configurable showing of buffer name, nick and time
  38. # 2009-05-21, xt <xt@bash.no>
  39. # version 0.3: bug fixes, add ignore feature from sleo
  40. # 2009-05-19, xt <xt@bash.no>
  41. # version 0.2-dev: fixes
  42. # 2009-05-04, FlashCode <flashcode@flashtux.org>
  43. # version 0.1-dev: dev snapshot
  44. #
  45. SCRIPT_NAME = "urlbar"
  46. SCRIPT_AUTHOR = "FlashCode <flashcode@flashtux.org>"
  47. SCRIPT_VERSION = "10"
  48. SCRIPT_LICENSE = "GPL3"
  49. SCRIPT_DESC = "Bar with URLs. For easy clicking or selecting."
  50. SCRIPT_COMMAND = "urlbar"
  51. settings = {
  52. "visible_amount" : '5', # Amount of URLS visible in urlbar at any given time
  53. "visible_seconds" : '5', # Amount of seconds URLbar is visible
  54. "use_popup" : 'on', # Pop up automatically
  55. "remember_amount" : '25', # Max amout of URLs to keep in RAM
  56. "ignore" : 'grep', # List of buffers to ignore. (comma separated)
  57. "show_timestamp" : 'off', # Show timestamp in list
  58. "show_nick" : 'off', # Show nick in list
  59. "show_buffername" : 'on', # Show buffer name in list
  60. "show_index" : 'on', # Show url index in list
  61. "time_format" : '%H:%M', # Time format
  62. }
  63. import_ok = True
  64. try:
  65. import weechat
  66. except ImportError:
  67. print "This script must be run under WeeChat."
  68. print "Get WeeChat now at: http://www.weechat.org/"
  69. import_ok = False
  70. import re
  71. from time import strftime, localtime
  72. octet = r'(?:2(?:[0-4]\d|5[0-5])|1\d\d|\d{1,2})'
  73. ipAddr = r'%s(?:\.%s){3}' % (octet, octet)
  74. # Base domain regex off RFC 1034 and 1738
  75. label = r'[0-9a-z][-0-9a-z]*[0-9a-z]?'
  76. domain = r'%s(?:\.%s)*\.[a-z][-0-9a-z]*[a-z]?' % (label, label)
  77. urlRe = re.compile(r'(\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?)' % (domain, ipAddr), re.I)
  78. # list of URL-objects
  79. urls = []
  80. # Display ALL, a toggle
  81. DISPLAY_ALL = False
  82. def urlbar_item_cb(data, item, window):
  83. ''' Callback that prints the lines in the urlbar '''
  84. global DISPLAY_ALL, urls
  85. try:
  86. visible_amount = int(weechat.config_get_plugin('visible_amount'))
  87. except ValueError:
  88. weechat.prnt('', 'Invalid value for visible_amount setting.')
  89. if not urls:
  90. return 'Empty URL list'
  91. if DISPLAY_ALL:
  92. DISPLAY_ALL = False
  93. printlist = urls
  94. else:
  95. printlist = urls[-visible_amount:]
  96. result = ''
  97. for index, url in enumerate(printlist):
  98. if weechat.config_get_plugin('show_index') == 'on':
  99. index = index+1
  100. result += '%s%2d%s %s \r' %\
  101. (weechat.color("yellow"), index, weechat.color("bar_fg"), url)
  102. else:
  103. result += '%s%s \r' %(weechat.color('bar_fg'), url)
  104. return result
  105. def get_buffer_name(bufferp, long=False):
  106. if not weechat.buffer_get_string(bufferp, "short_name") or long:
  107. bufferd = weechat.buffer_get_string(bufferp, "name")
  108. else:
  109. bufferd = weechat.buffer_get_string(bufferp, "short_name")
  110. return bufferd
  111. class URL(object):
  112. ''' URL class that holds the urls in the URL list '''
  113. def __init__(self, url, buffername, timestamp, nick):
  114. self.url = url
  115. self.buffername = buffername
  116. self.time = strftime(
  117. weechat.config_get_plugin('time_format'),
  118. localtime(int(timestamp)))
  119. self.time = self.time.replace(':', '%s:%s' %
  120. (weechat.color(weechat.config_string(
  121. weechat.config_get('weechat.color.chat_time_delimiters'))),
  122. weechat.color('reset')))
  123. self.nick = irc_nick_find_color(nick.strip('%&@+'))
  124. def __str__(self):
  125. # Format options
  126. time, buffername, nick = '', '', ''
  127. if weechat.config_get_plugin('show_timestamp') == 'on':
  128. time = self.time + ' '
  129. if weechat.config_get_plugin('show_buffername') == 'on':
  130. buffername = self.buffername + ' '
  131. if weechat.config_get_plugin('show_nick') == 'on':
  132. nick = self.nick + ' '
  133. return '%s%s%s%s' % (time, nick, buffername, self.url)
  134. def __cmp__(this, other):
  135. if this.url == other.url:
  136. return 0
  137. return 1
  138. def urlbar_print_cb(data, buffer, time, tags, displayed, highlight, prefix, message):
  139. buffer_name = get_buffer_name(buffer, long=True)
  140. # Skip ignored buffers
  141. for ignored_buffer in weechat.config_get_plugin('ignore').split(','):
  142. if ignored_buffer.lower() == buffer_name.lower():
  143. return weechat.WEECHAT_RC_OK
  144. # Clean list of URLs
  145. for i in range(len(urls) - int(weechat.config_get_plugin('remember_amount'))):
  146. # Delete the oldest
  147. urls.pop(0)
  148. for url in urlRe.findall(message):
  149. urlobject = URL(url, get_buffer_name(buffer), time, prefix)
  150. # Do not add duplicate URLs
  151. if urlobject in urls:
  152. continue
  153. urls.append(urlobject)
  154. if weechat.config_get_plugin('use_popup') == 'on':
  155. weechat.command("", "/bar show urlbar")
  156. # auto hide bar after delay
  157. try:
  158. weechat.command('', '/wait %s /bar hide urlbar' %
  159. int(weechat.config_get_plugin('visible_seconds')))
  160. except ValueError:
  161. weechat.prnt('', 'Invalid visible_seconds')
  162. weechat.bar_item_update("urlbar_urls")
  163. return weechat.WEECHAT_RC_OK
  164. def urlbar_cmd(data, buffer, args):
  165. """ Callback for /url command. """
  166. global urls, DISPLAY_ALL
  167. if args == "list":
  168. if urls:
  169. DISPLAY_ALL = True
  170. weechat.command("", '/bar show urlbar')
  171. weechat.bar_item_update("urlbar_urls")
  172. else:
  173. weechat.prnt('', 'URL list empty.')
  174. if args == "show":
  175. weechat.command('', '/bar show urlbar')
  176. elif args == 'hide':
  177. weechat.command("", "/bar hide urlbar")
  178. elif args == 'toggle':
  179. weechat.command("", "/bar toggle urlbar")
  180. elif args == 'clear':
  181. urls = []
  182. else:
  183. weechat.command("", "/help %s" % SCRIPT_COMMAND)
  184. return weechat.WEECHAT_RC_OK
  185. def urlbar_completion_urls_cb(data, completion_item, buffer, completion):
  186. """ Complete with URLS, for command '/url'. """
  187. for url in urls:
  188. weechat.hook_completion_list_add(completion, url.url,
  189. 0, weechat.WEECHAT_LIST_POS_SORT)
  190. return weechat.WEECHAT_RC_OK
  191. def irc_nick_find_color(nick):
  192. color = weechat.info_get('irc_nick_color', nick)
  193. if not color:
  194. # probably we're in WeeChat 0.3.0
  195. color %= weechat.config_integer(weechat.config_get("weechat.look.color_nicks_number"))
  196. color = weechat.config_get('weechat.color.chat_nick_color%02d' %(color+1))
  197. color = w.color(weechat.config_string(color))
  198. return '%s%s%s' %(color, nick, weechat.color('reset'))
  199. if __name__ == "__main__" and import_ok:
  200. if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
  201. SCRIPT_DESC, "", ""):
  202. # Set default settings
  203. for option, default_value in settings.iteritems():
  204. if not weechat.config_is_set_plugin(option):
  205. weechat.config_set_plugin(option, default_value)
  206. weechat.hook_command(SCRIPT_COMMAND,
  207. "URL bar control",
  208. "[list | hide | show | toggle | URL]",
  209. " list: list all URL and show URL bar\n"
  210. " hide: hide URL bar\n"
  211. " show: show URL bar\n"
  212. " toggle: toggle showing of URL bar\n",
  213. "list %(urlbar_urls)",
  214. "urlbar_cmd", "")
  215. weechat.hook_completion("urlbar_urls", "list of URLs",
  216. "urlbar_completion_urls_cb", "")
  217. weechat.bar_item_new("urlbar_urls", "urlbar_item_cb", "");
  218. weechat.bar_new("urlbar", "on", "0", "root", "", "top", "horizontal",
  219. "vertical", "0", "0", "default", "default", "default", "0",
  220. "urlbar_urls");
  221. weechat.hook_print("", "", "://", 1, "urlbar_print_cb", "")