lib/sup/buffer.rb (22415B) - raw
1 # encoding: utf-8
2
3 require 'etc'
4 require 'thread'
5 require 'ncursesw'
6
7 require 'sup/util/ncurses'
8
9 module Redwood
10
11 class InputSequenceAborted < StandardError; end
12
13 class Buffer
14 attr_reader :mode, :x, :y, :width, :height, :title, :atime
15 bool_reader :dirty, :system
16 bool_accessor :force_to_top, :hidden
17
18 def initialize window, mode, width, height, opts={}
19 @w = window
20 @mode = mode
21 @dirty = true
22 @focus = false
23 @title = opts[:title] || ""
24 @force_to_top = opts[:force_to_top] || false
25 @hidden = opts[:hidden] || false
26 @x, @y, @width, @height = 0, 0, width, height
27 @atime = Time.at 0
28 @system = opts[:system] || false
29 end
30
31 def content_height; @height - 1; end
32 def content_width; @width; end
33
34 def resize rows, cols
35 return if cols == @width && rows == @height
36 @width = cols
37 @height = rows
38 @dirty = true
39 mode.resize rows, cols
40 end
41
42 def redraw status
43 if @dirty
44 draw status
45 else
46 draw_status status
47 end
48
49 commit
50 end
51
52 def mark_dirty; @dirty = true; end
53
54 def commit
55 @dirty = false
56 @w.noutrefresh
57 end
58
59 def draw status
60 @mode.draw
61 draw_status status
62 commit
63 @atime = Time.now
64 end
65
66 ## s nil means a blank line!
67 def write y, x, s, opts={}
68 return if x >= @width || y >= @height
69
70 @w.attrset Colormap.color_for(opts[:color] || :none, opts[:highlight])
71 s ||= ""
72 maxl = @width - x # maximum display width width
73
74 # fill up the line with blanks to overwrite old screen contents
75 @w.mvaddstr y, x, " " * maxl unless opts[:no_fill]
76
77 @w.mvaddstr y, x, s.slice_by_display_length(maxl)
78 end
79
80 def clear
81 @w.clear
82 end
83
84 def draw_status status
85 write @height - 1, 0, status, :color => :status_color
86 end
87
88 def focus
89 @focus = true
90 @dirty = true
91 @mode.focus
92 end
93
94 def blur
95 @focus = false
96 @dirty = true
97 @mode.blur
98 end
99 end
100
101 class BufferManager
102 include Redwood::Singleton
103
104 attr_reader :focus_buf
105
106 ## we have to define the key used to continue in-buffer search here, because
107 ## it has special semantics that BufferManager deals with---current searches
108 ## are canceled by any keypress except this one.
109 CONTINUE_IN_BUFFER_SEARCH_KEY = "n"
110
111 HookManager.register "status-bar-text", <<EOS
112 Sets the status bar. The default status bar contains the mode name, the buffer
113 title, and the mode status. Note that this will be called at least once per
114 keystroke, so excessive computation is discouraged.
115
116 Variables:
117 num_inbox: number of messages in inbox
118 num_inbox_unread: total number of messages marked as unread
119 num_total: total number of messages in the index
120 num_spam: total number of messages marked as spam
121 title: title of the current buffer
122 mode: current mode name (string)
123 status: current mode status (string)
124 Return value: a string to be used as the status bar.
125 EOS
126
127 HookManager.register "terminal-title-text", <<EOS
128 Sets the title of the current terminal, if applicable. Note that this will be
129 called at least once per keystroke, so excessive computation is discouraged.
130
131 Variables: the same as status-bar-text hook.
132 Return value: a string to be used as the terminal title.
133 EOS
134
135 HookManager.register "extra-contact-addresses", <<EOS
136 A list of extra addresses to propose for tab completion, etc. when the
137 user is entering an email address. Can be plain email addresses or can
138 be full "User Name <email@domain.tld>" entries.
139
140 Variables: none
141 Return value: an array of email address strings.
142 EOS
143
144 def initialize
145 @name_map = {}
146 @buffers = []
147 @focus_buf = nil
148 @dirty = true
149 @minibuf_stack = []
150 @minibuf_mutex = Mutex.new
151 @textfields = {}
152 @flash = nil
153 @shelled = @asking = false
154 @have_xterm_title = Ncurses.tigetflag("XT") > 0 || ENV["TERM"] =~ /(screen|tmux)/
155 @sigwinch_happened = false
156 @sigwinch_mutex = Mutex.new
157 end
158
159 def sigwinch_happened!
160 @sigwinch_mutex.synchronize do
161 return if @sigwinch_happened
162 @sigwinch_happened = true
163 Ncurses.ungetch ?\C-l.ord
164 end
165 end
166
167 def sigwinch_happened?; @sigwinch_mutex.synchronize { @sigwinch_happened } end
168
169 def buffers; @name_map.to_a; end
170 def shelled?; @shelled; end
171
172 def focus_on buf
173 return unless @buffers.member? buf
174 return if buf == @focus_buf
175 @focus_buf.blur if @focus_buf
176 @focus_buf = buf
177 @focus_buf.focus
178 end
179
180 def raise_to_front buf
181 @buffers.delete(buf) or return
182 if @buffers.length > 0 && @buffers.last.force_to_top?
183 @buffers.insert(-2, buf)
184 else
185 @buffers.push buf
186 end
187 focus_on @buffers.last
188 @dirty = true
189 end
190
191 ## we reset force_to_top when rolling buffers. this is so that the
192 ## human can actually still move buffers around, while still
193 ## programmatically being able to pop stuff up in the middle of
194 ## drawing a window without worrying about covering it up.
195 ##
196 ## if we ever start calling roll_buffers programmatically, we will
197 ## have to change this. but it's not clear that we will ever actually
198 ## do that.
199 def roll_buffers
200 bufs = rollable_buffers
201 bufs.last.force_to_top = false
202 raise_to_front bufs.first
203 end
204
205 def roll_buffers_backwards
206 bufs = rollable_buffers
207 return unless bufs.length > 1
208 bufs.last.force_to_top = false
209 raise_to_front bufs[bufs.length - 2]
210 end
211
212 def rollable_buffers
213 @buffers.select { |b| !(b.system? || b.hidden?) || @buffers.last == b }
214 end
215
216 def handle_input c
217 if @focus_buf
218 if @focus_buf.mode.in_search? && c != CONTINUE_IN_BUFFER_SEARCH_KEY
219 @focus_buf.mode.cancel_search!
220 @focus_buf.mark_dirty
221 end
222 @focus_buf.mode.handle_input c
223 end
224 end
225
226 def exists? n; @name_map.member? n; end
227 def [] n; @name_map[n]; end
228 def []= n, b
229 raise ArgumentError, "duplicate buffer name" if b && @name_map.member?(n)
230 raise ArgumentError, "title must be a string" unless n.is_a? String
231 @name_map[n] = b
232 end
233
234 def completely_redraw_screen
235 return if @shelled
236
237 ## this magic makes Ncurses get the new size of the screen
238 Ncurses.endwin
239 Ncurses.stdscr.keypad 1
240 Ncurses.curs_set 0
241 Ncurses.refresh
242 @sigwinch_mutex.synchronize { @sigwinch_happened = false }
243 debug "new screen size is #{Ncurses.rows} x #{Ncurses.cols}"
244
245 status, title = get_status_and_title(@focus_buf) # must be called outside of the ncurses lock
246
247 Ncurses.sync do
248 @dirty = true
249 Ncurses.clear
250 draw_screen :sync => false, :status => status, :title => title
251 end
252 end
253
254 def draw_screen opts={}
255 return if @shelled
256
257 status, title =
258 if opts.member? :status
259 [opts[:status], opts[:title]]
260 else
261 raise "status must be supplied if draw_screen is called within a sync" if opts[:sync] == false
262 get_status_and_title @focus_buf # must be called outside of the ncurses lock
263 end
264
265 emit_xterm_title title if title
266
267 Ncurses.mutex.lock unless opts[:sync] == false
268
269 ## disabling this for the time being, to help with debugging
270 ## (currently we only have one buffer visible at a time).
271 ## TODO: reenable this if we allow multiple buffers
272 false && @buffers.inject(@dirty) do |dirty, buf|
273 buf.resize Ncurses.rows - minibuf_lines, Ncurses.cols
274 #dirty ? buf.draw : buf.redraw
275 buf.draw status
276 dirty
277 end
278
279 ## quick hack
280 if true
281 buf = @buffers.last
282 buf.resize Ncurses.rows - minibuf_lines, Ncurses.cols
283 @dirty ? buf.draw(status) : buf.redraw(status)
284 end
285
286 draw_minibuf :sync => false unless opts[:skip_minibuf]
287
288 @dirty = false
289 Ncurses.doupdate
290 Ncurses.refresh if opts[:refresh]
291 Ncurses.mutex.unlock unless opts[:sync] == false
292 end
293
294 def emit_xterm_title title
295 return unless @have_xterm_title
296 ## Escape terminal control characters.
297 title = title.gsub(/[[:cntrl:]]/) { |c| Ncurses.unctrl c.ord }
298 ## Screen does not properly handle characters above U+FF in the title.
299 ## It truncates them to 8 bits which may cause it to emit control
300 ## characters into the terminal title.
301 title = title.gsub(/[^\u0000-\u00ff]/, "?") if ENV["TERM"] =~ /screen/
302 print "\033]0;#{title}\07"
303 end
304
305 ## if the named buffer already exists, pops it to the front without
306 ## calling the block. otherwise, gets the mode from the block and
307 ## creates a new buffer. returns two things: the buffer, and a boolean
308 ## indicating whether it's a new buffer or not.
309 def spawn_unless_exists title, opts={}
310 new =
311 if @name_map.member? title
312 raise_to_front @name_map[title] unless opts[:hidden]
313 false
314 else
315 mode = yield
316 spawn title, mode, opts
317 true
318 end
319 [@name_map[title], new]
320 end
321
322 def spawn title, mode, opts={}
323 raise ArgumentError, "title must be a string" unless title.is_a? String
324 realtitle = title
325 num = 2
326 while @name_map.member? realtitle
327 realtitle = "#{title} <#{num}>"
328 num += 1
329 end
330
331 width = opts[:width] || Ncurses.cols
332 height = opts[:height] || Ncurses.rows - 1
333
334 ## since we are currently only doing multiple full-screen modes,
335 ## use stdscr for each window. once we become more sophisticated,
336 ## we may need to use a new Ncurses::WINDOW
337 ##
338 ## w = Ncurses::WINDOW.new(height, width, (opts[:top] || 0),
339 ## (opts[:left] || 0))
340 w = Ncurses.stdscr
341 b = Buffer.new w, mode, width, height, :title => realtitle, :force_to_top => opts[:force_to_top], :system => opts[:system]
342 mode.buffer = b
343 mode.spawned
344 @name_map[realtitle] = b
345
346 @buffers.unshift b
347 if opts[:hidden]
348 focus_on b unless @focus_buf
349 else
350 raise_to_front b
351 end
352 b
353 end
354
355 ## requires the mode to have #done? and #value methods
356 def spawn_modal title, mode, opts={}
357 b = spawn title, mode, opts
358 draw_screen
359
360 until mode.done?
361 c = Ncurses::CharCode.get
362 next unless c.present? # getch timeout
363 break if c.is_keycode? Ncurses::KEY_CANCEL
364 begin
365 mode.handle_input c
366 rescue InputSequenceAborted # do nothing
367 end
368 draw_screen
369 erase_flash
370 end
371
372 kill_buffer b
373 mode.value
374 end
375
376 def kill_all_buffers_safely
377 until @buffers.empty?
378 ## inbox mode always claims it's unkillable. we'll ignore it.
379 return false unless @buffers.last.mode.is_a?(InboxMode) || @buffers.last.mode.killable?
380 kill_buffer @buffers.last
381 end
382 true
383 end
384
385 def kill_buffer_safely buf
386 return false unless buf.mode.killable?
387 kill_buffer buf
388 true
389 end
390
391 def kill_all_buffers
392 kill_buffer @buffers.first until @buffers.empty?
393 end
394
395 def kill_buffer buf
396 raise ArgumentError, "buffer not on stack: #{buf}: #{buf.title.inspect}" unless @buffers.member? buf
397
398 buf.mode.cleanup
399 @buffers.delete buf
400 @name_map.delete buf.title
401 @focus_buf = nil if @focus_buf == buf
402 if @buffers.empty?
403 ## TODO: something intelligent here
404 ## for now I will simply prohibit killing the inbox buffer.
405 else
406 raise_to_front @buffers.last
407 end
408 end
409
410 ## ask* functions. these functions display a one-line text field with
411 ## a prompt at the bottom of the screen. answers typed or choosen by
412 ## tab-completion
413 ##
414 ## common arguments are:
415 ##
416 ## domain: token used as key for @textfields, which seems to be a
417 ## dictionary of input field objects
418 ## question: string used as prompt
419 ## completions: array of possible answers, that can be completed by using
420 ## the tab key
421 ## default: default value to return
422 def ask_with_completions domain, question, completions, default=nil
423 ask domain, question, default do |s|
424 s.fix_encoding!
425 completions.select { |x| x =~ /^#{Regexp::escape s}/iu }.map { |x| [x, x] }
426 end
427 end
428
429 def ask_many_with_completions domain, question, completions, default=nil
430 ask domain, question, default do |partial|
431 prefix, target =
432 case partial
433 when /^\s*$/
434 ["", ""]
435 when /^(.*\s+)?(.*?)$/
436 [$1 || "", $2]
437 else
438 raise "william screwed up completion: #{partial.inspect}"
439 end
440
441 prefix.fix_encoding!
442 target.fix_encoding!
443 completions.select { |x| x =~ /^#{Regexp::escape target}/iu }.map { |x| [prefix + x, x] }
444 end
445 end
446
447 def ask_many_emails_with_completions domain, question, completions, default=nil
448 ask domain, question, default do |partial|
449 prefix, target = partial.split_on_commas_with_remainder
450 target ||= prefix.pop || ""
451 target.fix_encoding!
452
453 prefix = prefix.join(", ") + (prefix.empty? ? "" : ", ")
454 prefix.fix_encoding!
455
456 completions.select { |x| x =~ /^#{Regexp::escape target}/iu }.sort_by { |c| [ContactManager.contact_for(c) ? 0 : 1, c] }.map { |x| [prefix + x, x] }
457 end
458 end
459
460 def ask_for_filename domain, question, default=nil, allow_directory=false
461 answer = ask domain, question, default do |s|
462 if s =~ /(~([^\s\/]*))/ # twiddle directory expansion
463 full = $1
464 name = $2.empty? ? Etc.getlogin : $2
465 dir = Etc.getpwnam(name).dir rescue nil
466 if dir
467 [[s.sub(full, dir), "~#{name}"]]
468 else
469 users.select { |u| u =~ /^#{Regexp::escape name}/u }.map do |u|
470 [s.sub("~#{name}", "~#{u}"), "~#{u}"]
471 end
472 end
473 else # regular filename completion
474 Dir["#{s}*"].sort.map do |fn|
475 suffix = File.directory?(fn) ? "/" : ""
476 [fn + suffix, File.basename(fn) + suffix]
477 end
478 end
479 end
480
481 if answer
482 answer =
483 if answer.empty?
484 spawn_modal "file browser", FileBrowserMode.new
485 elsif File.directory?(answer) && !allow_directory
486 spawn_modal "file browser", FileBrowserMode.new(answer)
487 else
488 File.expand_path answer
489 end
490 end
491
492 answer
493 end
494
495 ## returns an array of labels
496 def ask_for_labels domain, question, default_labels, forbidden_labels=[]
497 default_labels = default_labels - forbidden_labels - LabelManager::RESERVED_LABELS
498 default = default_labels.to_a.join(" ")
499 default += " " unless default.empty?
500
501 # here I would prefer to give more control and allow all_labels instead of
502 # user_defined_labels only
503 applyable_labels = (LabelManager.user_defined_labels - forbidden_labels).map { |l| LabelManager.string_for l }.sort_by { |s| s.downcase }
504
505 answer = ask_many_with_completions domain, question, applyable_labels, default
506
507 return unless answer
508
509 user_labels = answer.to_set_of_symbols
510 user_labels.each do |l|
511 if forbidden_labels.include?(l) || LabelManager::RESERVED_LABELS.include?(l)
512 BufferManager.flash "'#{l}' is a reserved label!"
513 return
514 end
515 end
516 user_labels
517 end
518
519 def ask_for_contacts domain, question, default_contacts=[]
520 default = default_contacts.is_a?(String) ? default_contacts : default_contacts.map { |s| s.to_s }.join(", ")
521 default += " " unless default.empty?
522
523 recent = Index.load_contacts(AccountManager.user_emails, :num => 10).map { |c| [c.full_address, c.email] }
524 contacts = ContactManager.contacts.map { |c| [ContactManager.alias_for(c), c.full_address, c.email] }
525
526 completions = (recent + contacts).flatten.uniq
527 completions += HookManager.run("extra-contact-addresses") || []
528
529 answer = BufferManager.ask_many_emails_with_completions domain, question, completions, default
530
531 if answer
532 answer.split_on_commas.map { |x| ContactManager.contact_for(x) || Person.from_address(x) }
533 end
534 end
535
536 def ask_for_account domain, question
537 completions = AccountManager.user_emails
538 answer = BufferManager.ask_many_emails_with_completions domain, question, completions, ""
539 answer = AccountManager.default_account.email if answer == ""
540 AccountManager.account_for Person.from_address(answer).email if answer
541 end
542
543 ## for simplicitly, we always place the question at the very bottom of the
544 ## screen
545 def ask domain, question, default=nil, &block
546 raise "impossible!" if @asking
547 raise "Question too long" if Ncurses.cols <= question.length
548 @asking = true
549
550 @textfields[domain] ||= TextField.new
551 tf = @textfields[domain]
552 completion_buf = nil
553
554 status, title = get_status_and_title @focus_buf
555
556 Ncurses.sync do
557 tf.activate Ncurses.stdscr, Ncurses.rows - 1, 0, Ncurses.cols, question, default, &block
558 @dirty = true # for some reason that blanks the whole fucking screen
559 draw_screen :sync => false, :status => status, :title => title
560 tf.position_cursor
561 Ncurses.refresh
562 end
563
564 while true
565 c = Ncurses::CharCode.get
566 next unless c.present? # getch timeout
567 break unless tf.handle_input c # process keystroke
568
569 if tf.new_completions?
570 kill_buffer completion_buf if completion_buf
571
572 shorts = tf.completions.map { |full, short| short }
573 prefix_len = shorts.shared_prefix(caseless=true).length
574
575 mode = CompletionMode.new shorts, :header => "Possible completions for \"#{tf.value}\": ", :prefix_len => prefix_len
576 completion_buf = spawn "<completions>", mode, :height => 10
577
578 draw_screen :skip_minibuf => true
579 tf.position_cursor
580 elsif tf.roll_completions?
581 completion_buf.mode.roll
582 draw_screen :skip_minibuf => true
583 tf.position_cursor
584 end
585
586 Ncurses.sync { Ncurses.refresh }
587 end
588
589 kill_buffer completion_buf if completion_buf
590
591 @dirty = true
592 @asking = false
593 Ncurses.sync do
594 tf.deactivate
595 draw_screen :sync => false, :status => status, :title => title
596 end
597 tf.value.tap { |x| x }
598 end
599
600 def ask_getch question, accept=nil
601 raise "impossible!" if @asking
602
603 accept = accept.split(//).map { |x| x.ord } if accept
604
605 status, title = get_status_and_title @focus_buf
606 Ncurses.sync do
607 draw_screen :sync => false, :status => status, :title => title
608 Ncurses.mvaddstr Ncurses.rows - 1, 0, question
609 Ncurses.move Ncurses.rows - 1, question.length + 1
610 Ncurses.curs_set 1
611 Ncurses.refresh
612 end
613
614 @asking = true
615 ret = nil
616 done = false
617 until done
618 key = Ncurses::CharCode.get
619 next if key.empty?
620 if key.is_keycode? Ncurses::KEY_CANCEL
621 done = true
622 elsif accept.nil? || accept.empty? || accept.member?(key.code)
623 ret = key
624 done = true
625 end
626 end
627
628 @asking = false
629 Ncurses.sync do
630 Ncurses.curs_set 0
631 draw_screen :sync => false, :status => status, :title => title
632 end
633
634 ret
635 end
636
637 ## returns true (y), false (n), or nil (ctrl-g / cancel)
638 def ask_yes_or_no question
639 case(r = ask_getch question, "ynYN")
640 when ?y, ?Y
641 true
642 when nil
643 nil
644 else
645 false
646 end
647 end
648
649 ## turns an input keystroke into an action symbol. returns the action
650 ## if found, nil if not found, and throws InputSequenceAborted if
651 ## the user aborted a multi-key sequence. (Because each of those cases
652 ## should be handled differently.)
653 ##
654 ## this is in BufferManager because multi-key sequences require prompting.
655 def resolve_input_with_keymap c, keymap
656 action, text = keymap.action_for c
657 while action.is_a? Keymap # multi-key commands, prompt
658 key = BufferManager.ask_getch text
659 unless key # user canceled, abort
660 erase_flash
661 raise InputSequenceAborted
662 end
663 action, text = action.action_for(key) if action.has_key?(key)
664 end
665 action
666 end
667
668 def minibuf_lines
669 @minibuf_mutex.synchronize do
670 [(@flash ? 1 : 0) +
671 (@asking ? 1 : 0) +
672 @minibuf_stack.compact.size, 1].max
673 end
674 end
675
676 def draw_minibuf opts={}
677 m = nil
678 @minibuf_mutex.synchronize do
679 m = @minibuf_stack.compact
680 m << @flash if @flash
681 m << "" if m.empty? unless @asking # to clear it
682 end
683
684 Ncurses.mutex.lock unless opts[:sync] == false
685 Ncurses.attrset Colormap.color_for(:text_color)
686 adj = @asking ? 2 : 1
687 m.each_with_index do |s, i|
688 Ncurses.mvaddstr Ncurses.rows - i - adj, 0, s + (" " * [Ncurses.cols - s.length, 0].max)
689 end
690 Ncurses.refresh if opts[:refresh]
691 Ncurses.mutex.unlock unless opts[:sync] == false
692 end
693
694 def say s, id=nil
695 new_id = nil
696
697 @minibuf_mutex.synchronize do
698 new_id = id.nil?
699 id ||= @minibuf_stack.length
700 @minibuf_stack[id] = s
701 end
702
703 if new_id
704 draw_screen :refresh => true
705 else
706 draw_minibuf :refresh => true
707 end
708
709 if block_given?
710 begin
711 yield id
712 ensure
713 clear id
714 end
715 end
716 id
717 end
718
719 def erase_flash; @flash = nil; end
720
721 def flash s
722 @flash = s
723 draw_screen :refresh => true
724 end
725
726 ## a little tricky because we can't just delete_at id because ids
727 ## are relative (they're positions into the array).
728 def clear id
729 @minibuf_mutex.synchronize do
730 @minibuf_stack[id] = nil
731 if id == @minibuf_stack.length - 1
732 id.downto(0) do |i|
733 break if @minibuf_stack[i]
734 @minibuf_stack.delete_at i
735 end
736 end
737 end
738
739 draw_screen :refresh => true
740 end
741
742 def shell_out command
743 @shelled = true
744 Ncurses.sync do
745 Ncurses.endwin
746 system command
747 Ncurses.stdscr.keypad 1
748 Ncurses.refresh
749 Ncurses.curs_set 0
750 end
751 @shelled = false
752 end
753
754 private
755
756 def default_status_bar buf
757 " [#{buf.mode.name}] #{buf.title} #{buf.mode.status}"
758 end
759
760 def default_terminal_title buf
761 "Sup #{Redwood::VERSION} :: #{buf.title}"
762 end
763
764 def get_status_and_title buf
765 opts = {
766 :num_inbox => lambda { Index.num_results_for :label => :inbox },
767 :num_inbox_unread => lambda { Index.num_results_for :labels => [:inbox, :unread] },
768 :num_total => lambda { Index.size },
769 :num_spam => lambda { Index.num_results_for :label => :spam },
770 :title => buf.title,
771 :mode => buf.mode.name,
772 :status => buf.mode.status
773 }
774
775 statusbar_text = HookManager.run("status-bar-text", opts) || default_status_bar(buf)
776 term_title_text = HookManager.run("terminal-title-text", opts) || default_terminal_title(buf)
777
778 [statusbar_text, term_title_text]
779 end
780
781 def users
782 unless @users
783 @users = []
784 while(u = Etc.getpwent)
785 @users << u.name
786 end
787 end
788 @users
789 end
790 end
791 end