]> git.cworth.org Git - sup/blob - lib/sup.rb
Merge branch 'zsh-completion'
[sup] / lib / sup.rb
1 require 'rubygems'
2 require 'yaml'
3 require 'zlib'
4 require 'thread'
5 require 'fileutils'
6 require 'gettext'
7 require 'curses'
8
9 class Object
10   ## this is for debugging purposes because i keep calling #id on the
11   ## wrong object and i want it to throw an exception
12   def id
13     raise "wrong id called on #{self.inspect}"
14   end
15 end
16
17 class Module
18   def yaml_properties *props
19     props = props.map { |p| p.to_s }
20     vars = props.map { |p| "@#{p}" }
21     klass = self
22     path = klass.name.gsub(/::/, "/")
23     
24     klass.instance_eval do
25       define_method(:to_yaml_properties) { vars }
26       define_method(:to_yaml_type) { "!#{Redwood::YAML_DOMAIN},#{Redwood::YAML_DATE}/#{path}" }
27     end
28
29     YAML.add_domain_type("#{Redwood::YAML_DOMAIN},#{Redwood::YAML_DATE}", path) do |type, val|
30       klass.new(*props.map { |p| val[p] })
31     end
32   end
33 end
34
35 module Redwood
36   VERSION = "git"
37
38   BASE_DIR   = ENV["SUP_BASE"] || File.join(ENV["HOME"], ".sup")
39   CONFIG_FN  = File.join(BASE_DIR, "config.yaml")
40   COLOR_FN   = File.join(BASE_DIR, "colors.yaml")
41   SOURCE_FN  = File.join(BASE_DIR, "sources.yaml")
42   LABEL_FN   = File.join(BASE_DIR, "labels.txt")
43   CONTACT_FN = File.join(BASE_DIR, "contacts.txt")
44   DRAFT_DIR  = File.join(BASE_DIR, "drafts")
45   SENT_FN    = File.join(BASE_DIR, "sent.mbox")
46   LOCK_FN    = File.join(BASE_DIR, "lock")
47   SUICIDE_FN = File.join(BASE_DIR, "please-kill-yourself")
48   HOOK_DIR   = File.join(BASE_DIR, "hooks")
49
50   YAML_DOMAIN = "masanjin.net"
51   YAML_DATE = "2006-10-01"
52
53   ## record exceptions thrown in threads nicely
54   @exceptions = []
55   @exception_mutex = Mutex.new
56
57   attr_reader :exceptions
58   def record_exception e, name
59     @exception_mutex.synchronize do
60       @exceptions ||= []
61       @exceptions << [e, name]
62     end
63   end
64
65   def reporting_thread name
66     if $opts[:no_threads]
67       yield
68     else
69       ::Thread.new do
70         begin
71           yield
72         rescue Exception => e
73           record_exception e, name
74         end
75       end
76     end
77   end
78
79   module_function :reporting_thread, :record_exception, :exceptions
80
81 ## one-stop shop for yamliciousness
82   def save_yaml_obj object, fn, safe=false
83     if safe
84       safe_fn = "#{File.dirname fn}/safe_#{File.basename fn}"
85       mode = File.stat(fn).mode if File.exists? fn
86       File.open(safe_fn, "w", mode) { |f| f.puts object.to_yaml }
87       FileUtils.mv safe_fn, fn
88     else
89       File.open(fn, "w") { |f| f.puts object.to_yaml }
90     end
91   end
92
93   def load_yaml_obj fn, compress=false
94     if File.exists? fn
95       if compress
96         Zlib::GzipReader.open(fn) { |f| YAML::load f }
97       else
98         YAML::load_file fn
99       end
100     end
101   end
102
103   def start
104     Redwood::SentManager.new Redwood::SENT_FN
105     Redwood::ContactManager.new Redwood::CONTACT_FN
106     Redwood::LabelManager.new Redwood::LABEL_FN
107     Redwood::AccountManager.new $config[:accounts]
108     Redwood::DraftManager.new Redwood::DRAFT_DIR
109     Redwood::UpdateManager.new
110     Redwood::PollManager.new
111     Redwood::SuicideManager.new Redwood::SUICIDE_FN
112     Redwood::CryptoManager.new
113   end
114
115   def finish
116     Redwood::LabelManager.save if Redwood::LabelManager.instantiated?
117     Redwood::ContactManager.save if Redwood::ContactManager.instantiated?
118     Redwood::BufferManager.deinstantiate! if Redwood::BufferManager.instantiated?
119   end
120
121   ## not really a good place for this, so I'll just dump it here.
122   ##
123   ## a source error is either a FatalSourceError or an OutOfSyncSourceError.
124   ## the superclass SourceError is just a generic.
125   def report_broken_sources opts={}
126     return unless BufferManager.instantiated?
127
128     broken_sources = Index.sources.select { |s| s.error.is_a? FatalSourceError }
129     unless broken_sources.empty?
130       BufferManager.spawn_unless_exists("Broken source notification for #{broken_sources.join(',')}", opts) do
131         TextMode.new(<<EOM)
132 Source error notification
133 -------------------------
134
135 Hi there. It looks like one or more message sources is reporting
136 errors. Until this is corrected, messages from these sources cannot
137 be viewed, and new messages will not be detected.
138
139 #{broken_sources.map { |s| "Source: " + s.to_s + "\n Error: " + s.error.message.wrap(70).join("\n        ")}.join("\n\n")}
140 EOM
141 #' stupid ruby-mode
142       end
143     end
144
145     desynced_sources = Index.sources.select { |s| s.error.is_a? OutOfSyncSourceError }
146     unless desynced_sources.empty?
147       BufferManager.spawn_unless_exists("Out-of-sync source notification for #{broken_sources.join(',')}", opts) do
148         TextMode.new(<<EOM)
149 Out-of-sync source notification
150 -------------------------------
151
152 Hi there. It looks like one or more sources has fallen out of sync
153 with my index. This can happen when you modify these sources with
154 other email clients. (Sorry, I don't play well with others.)
155
156 Until this is corrected, messages from these sources cannot be viewed,
157 and new messages will not be detected. Luckily, this is easy to correct!
158
159 #{desynced_sources.map do |s|
160   "Source: " + s.to_s + 
161    "\n Error: " + s.error.message.wrap(70).join("\n        ") + 
162    "\n   Fix: sup-sync --changed #{s.to_s}"
163   end}
164 EOM
165 #' stupid ruby-mode
166       end
167     end
168   end
169
170   module_function :save_yaml_obj, :load_yaml_obj, :start, :finish,
171                   :report_broken_sources
172 end
173
174 ## set up default configuration file
175 if File.exists? Redwood::CONFIG_FN
176   $config = Redwood::load_yaml_obj Redwood::CONFIG_FN
177 else
178   require 'etc'
179   require 'socket'
180   name = Etc.getpwnam(ENV["USER"]).gecos.split(/,/).first rescue nil
181   name ||= ENV["USER"]
182   email = ENV["USER"] + "@" + 
183     begin
184       Socket.gethostbyname(Socket.gethostname).first
185     rescue SocketError
186       Socket.gethostname
187     end
188
189   $config = {
190     :accounts => {
191       :default => {
192         :name => name,
193         :email => email,
194         :alternates => [],
195         :sendmail => "/usr/sbin/sendmail -oem -ti",
196         :signature => File.join(ENV["HOME"], ".signature")
197       }
198     },
199     :editor => ENV["EDITOR"] || "/usr/bin/vim -f -c 'setlocal spell spelllang=en_us' -c 'set filetype=mail'",
200     :thread_by_subject => false,
201     :edit_signature => false,
202     :ask_for_cc => true,
203     :ask_for_bcc => false,
204     :ask_for_subject => true,
205     :confirm_no_attachments => true,
206     :confirm_top_posting => true,
207     :discard_snippets_from_encrypted_messages => false,
208     :default_attachment_save_dir => "",
209   }
210   begin
211     FileUtils.mkdir_p Redwood::BASE_DIR
212     Redwood::save_yaml_obj $config, Redwood::CONFIG_FN
213   rescue StandardError => e
214     $stderr.puts "warning: #{e.message}"
215   end
216 end
217
218 require "sup/util"
219 require "sup/hook"
220
221 ## we have to initialize this guy first, because other classes must
222 ## reference it in order to register hooks, and they do that at parse
223 ## time.
224 Redwood::HookManager.new Redwood::HOOK_DIR
225
226 ## everything we need to get logging working
227 require "sup/buffer"
228 require "sup/keymap"
229 require "sup/mode"
230 require "sup/modes/scroll-mode"
231 require "sup/modes/text-mode"
232 require "sup/modes/log-mode"
233 require "sup/logger"
234 module Redwood
235   def log s; Logger.log s; end
236   module_function :log
237 end
238
239 ## determine encoding and character set
240   $encoding = Locale.current.charset
241   if $encoding
242     Redwood::log "using character set encoding #{$encoding.inspect}"
243   else
244     Redwood::log "warning: can't find character set by using locale, defaulting to utf-8"
245     $encoding = "utf-8"
246   end
247
248 ## now everything else (which can feel free to call Redwood::log at load time)
249 require "sup/update"
250 require "sup/suicide"
251 require "sup/message-chunks"
252 require "sup/message"
253 require "sup/source"
254 require "sup/mbox"
255 require "sup/maildir"
256 require "sup/imap"
257 require "sup/person"
258 require "sup/account"
259 require "sup/thread"
260 require "sup/index"
261 require "sup/textfield"
262 require "sup/colormap"
263 require "sup/label"
264 require "sup/contact"
265 require "sup/tagger"
266 require "sup/draft"
267 require "sup/poll"
268 require "sup/crypto"
269 require "sup/horizontal-selector"
270 require "sup/modes/line-cursor-mode"
271 require "sup/modes/help-mode"
272 require "sup/modes/edit-message-mode"
273 require "sup/modes/compose-mode"
274 require "sup/modes/resume-mode"
275 require "sup/modes/forward-mode"
276 require "sup/modes/reply-mode"
277 require "sup/modes/label-list-mode"
278 require "sup/modes/contact-list-mode"
279 require "sup/modes/thread-view-mode"
280 require "sup/modes/thread-index-mode"
281 require "sup/modes/label-search-results-mode"
282 require "sup/modes/search-results-mode"
283 require "sup/modes/person-search-results-mode"
284 require "sup/modes/inbox-mode"
285 require "sup/modes/buffer-list-mode"
286 require "sup/modes/poll-mode"
287 require "sup/modes/file-browser-mode"
288 require "sup/modes/completion-mode"
289 require "sup/sent"
290
291 $:.each do |base|
292   d = File.join base, "sup/share/modes/"
293   Redwood::Mode.load_all_modes d if File.directory? d
294 end